OXYGENHUB

Coverage / crates/oxy-server/src/lib.rs 85.7%

246 of 287 lines run, 38 of 83 functions · run #335 on proposal/123 · run missed

1
//! Reference HTTP server for the Oxygen wire protocol (spec §15.1, §16).
2
//!
3
//! Serves every repository directory under a root at `/{repo}/oxy/v1/...`,
4
//! over TLS when a certificate and key are given, else plain HTTP for use
5
//! behind a TLS-terminating proxy or on a loopback interface (spec §15.1).
6
//!
7
//! Authentication: when bearer tokens are configured, `push` requires one;
8
//! reads are open. With no tokens configured everything is open (development).
9
//!
10
//! Hosts embed the protocol by implementing [`Backend`] (name resolution
11
//! and authorization) and routing to [`Server::handle`]; `router` is the
12
//! standalone server built on [`DirBackend`].
13
14
pub mod witness;
15
16
use axum::body::Bytes;
17
use axum::extract::{Path, State};
18
use axum::http::{header, HeaderMap, Method, StatusCode};
19
use axum::response::{IntoResponse, Response};
20
use axum::routing::any;
21
use axum::Router;
22
use oxy_core::protocol::{wire, CONTENT_TYPE};
23
use oxy_core::repo::Repo;
24
use std::collections::HashMap;
25
use std::path::PathBuf;
26
use std::sync::{Arc, Mutex};
27
28
#[derive(Clone, Debug)]
29
pub struct ServerConfig {
30
    /// Directory containing one repository per subdirectory.
31
    pub root: PathBuf,
32
    /// Bearer tokens allowed to push; empty means no authentication.
33
    pub tokens: Vec<String>,
34
    /// Serve HTTPS with this certificate chain and private key (PEM files).
35
    pub tls: Option<TlsFiles>,
36
}
37
38
#[derive(Clone, Debug)]
39
pub struct TlsFiles {
40
    pub cert: PathBuf,
41
    pub key: PathBuf,
42
}
43
44
/// Which kind of access a request needs (spec §15.1: reads may be open;
45
/// a push must be authenticated when any credential is configured).
46
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47
pub enum Access {
48
    Read,
49
    Push,
50
}
51
52
/// What a host provides to the protocol server: how a repository name maps
53
/// to a repository on disk and who may do what. `oxy serve` uses
54
/// [`DirBackend`]; a hub supplies its own with accounts and roles.
55
pub trait Backend: Send + Sync + 'static {
56
    /// Open the repository called `name`, or fail with the status to
57
    /// answer. An unknown name is `404`; a name the caller may not see
58
    /// SHOULD also be `404`, so private repositories are not enumerable.
59
    fn open(&self, name: &str) -> Result<Repo, Failure>;
60
61
    /// Decide whether this request may perform `access` on `name`.
62
    fn authorize(&self, name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure>;
63
64
    /// Called after a push was processed, with its per-reference results
65
    /// (accepted or refused), the states each accepted reference moved
66
    /// between, and the changes stored, for logs and cache invalidation.
6734×
    fn after_push(&self, _name: &str, _report: &oxy_core::repo::PushReport, _headers: &HeaderMap) {}
68
69
    /// Add the host's transparency log to a refs answer (spec §14.8): its
70
    /// checkpoint, and each attestation's entry and inclusion proof. A host
71
    /// without a log leaves it as it is.
72121×
    fn add_log(&self, _name: &str, _refs: &mut oxy_core::protocol::RefsResponse) {}
73
74
    /// The bookmark of `name` that pushes may never delete (its default),
75
    /// when the host keeps one apart from the repository's own config.
765×
    fn default_bookmark(&self, _name: &str) -> Option<String> {
775×
        None
785×
    }
79
}
80
81
/// A protocol server over any [`Backend`], serialising the pushes to each
82
/// repository. Hosts route requests to [`Server::handle`].
83
pub struct Server {
84
    backend: Box<dyn Backend>,
85
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
86
}
87
88
/// An error response: a status and a plain-text body.
89
#[derive(Debug)]
90
pub struct Failure(pub StatusCode, pub String);
91
92
impl IntoResponse for Failure {
938×
    fn into_response(self) -> Response {
948×
        (self.0, self.1).into_response()
958×
    }
96
}
97
98
impl From<oxy_core::repo::RepoError> for Failure {
990×
    fn from(e: oxy_core::repo::RepoError) -> Failure {
100
        use oxy_core::repo::RepoError;
101
        // The server's own storage failing is not the client's fault.
1020×
        let status = match &e {
1030×
            RepoError::Io(_) | RepoError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
1040×
            _ => StatusCode::BAD_REQUEST,
105
        };
1060×
        Failure(status, e.to_string())
1070×
    }
108
}
109
110
/// The wire protocol's endpoints (spec §16.1), named as in the URL.
111
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112
pub enum Endpoint {
113
    Capabilities,
114
    Refs,
115
    Negotiate,
116
    Fetch,
117
    Objects,
118
    Checkpoint,
119
    Shallow,
120
    Push,
121
}
122
123
impl Endpoint {
124385×
    pub fn parse(name: &str) -> Option<Endpoint> {
125385×
        Some(match name {
126385×
            "capabilities" => Endpoint::Capabilities,
127258×
            "refs" => Endpoint::Refs,
128137×
            "negotiate" => Endpoint::Negotiate,
12989×
            "fetch" => Endpoint::Fetch,
13041×
            "objects" => Endpoint::Objects,
13140×
            "checkpoint" => Endpoint::Checkpoint,
13240×
            "shallow" => Endpoint::Shallow,
13340×
            "push" => Endpoint::Push,
1340×
            _ => return None,
135
        })
136385×
    }
137
1382×
    pub fn name(self) -> &'static str {
1392×
        match self {
1402×
            Endpoint::Capabilities => "capabilities",
1410×
            Endpoint::Refs => "refs",
1420×
            Endpoint::Negotiate => "negotiate",
1430×
            Endpoint::Fetch => "fetch",
1440×
            Endpoint::Objects => "objects",
1450×
            Endpoint::Checkpoint => "checkpoint",
1460×
            Endpoint::Shallow => "shallow",
1470×
            Endpoint::Push => "push",
148
        }
1492×
    }
150
151
    /// The HTTP method the endpoint answers to.
152385×
    pub fn method(self) -> Method {
153385×
        match self {
154248×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
155137×
            _ => Method::POST,
156
        }
157385×
    }
158
159385×
    fn access(self) -> Access {
160385×
        match self {
16140×
            Endpoint::Push => Access::Push,
162345×
            _ => Access::Read,
163
        }
164385×
    }
165
}
166
167377×
fn ok(body: Vec<u8>) -> Response {
168377×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
169377×
}
170
171519×
pub fn valid_repo_name(name: &str) -> bool {
172519×
    !name.is_empty()
173519×
        && !name.starts_with('.')
174518×
        && name
175518×
            .chars()
1762865×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
177519×
}
178
179
impl Server {
18012×
    pub fn new(backend: impl Backend) -> Arc<Server> {
18112×
        Arc::new(Server {
18212×
            backend: Box::new(backend),
18312×
            locks: Mutex::new(HashMap::new()),
18412×
        })
18512×
    }
186
1870×
    pub fn backend(&self) -> &dyn Backend {
1880×
        self.backend.as_ref()
1890×
    }
190
19135×
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
19235×
        self.locks
19335×
            .lock()
19435×
            .unwrap()
19535×
            .entry(name.to_string())
19635×
            .or_default()
19735×
            .clone()
19835×
    }
199
200
    /// Answer one protocol request for repository `name`. `method` is
201
    /// checked against the endpoint; the body is the raw CBOR request.
202385×
    pub async fn handle(
203385×
        self: &Arc<Self>,
204385×
        name: String,
205385×
        endpoint: Endpoint,
206385×
        method: &Method,
207385×
        headers: &HeaderMap,
208385×
        body: Bytes,
209385×
    ) -> Response {
210385×
        if *method != endpoint.method() {
2110×
            return Failure(
2120×
                StatusCode::METHOD_NOT_ALLOWED,
2130×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2140×
            )
2150×
            .into_response();
216385×
        }
217385×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2186×
            return f.into_response();
219379×
        }
220379×
        let claimed = headers
221379×
            .get(oxy_core::protocol::REPO_ID_HEADER)
222379×
            .and_then(|v| v.to_str().ok())
223379×
            .and_then(hex_id);
224379×
        let server = Arc::clone(self);
225379×
        let request_headers = headers.clone();
226379×
        let repo = name.clone();
227379×
        let result = tokio::task::spawn_blocking(move || {
228379×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
229379×
        })
230379×
        .await;
231379×
        let failure = match result {
232377×
            Ok(Ok(r)) => return r,
2332×
            Ok(Err(f)) => f,
2340×
            Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
235
        };
236
        // Name the operation and repository, in the log and for the client.
2372×
        let f = Failure(
2382×
            failure.0,
2392×
            format!("{} of {name}: {}", endpoint.name(), failure.1),
2402×
        );
2412×
        eprintln!("oxy-server: {}: {}", f.0.as_u16(), f.1);
2422×
        f.into_response()
243385×
    }
244
245379×
    fn respond(
246379×
        &self,
247379×
        name: &str,
248379×
        endpoint: Endpoint,
249379×
        body: Bytes,
250379×
        claimed: Option<[u8; 16]>,
251379×
        headers: &HeaderMap,
252379×
    ) -> Result<Response, Failure> {
253379×
        let r = self.backend.open(name)?;
254377×
        Ok(match endpoint {
255124×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
256
            Endpoint::Refs => {
257121×
                let mut refs = r.remote_refs()?;
258121×
                if let Some(d) = self.backend.default_bookmark(name) {
259117×
                    refs.default_bookmark = Some(d);
260117×
                }
261121×
                self.backend.add_log(name, &mut refs);
262121×
                ok(wire::encode_refs(r.id()?, &refs))
263
            }
264
            Endpoint::Negotiate => {
26548×
                let (have, want) = wire::decode_negotiate(&body)?;
26648×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
267
            }
268
            Endpoint::Fetch => {
26948×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
27048×
                ok(wire::encode_bundle(
27148×
                    &r.bundle_for_filtered(&changes, max_blob)?,
272
                ))
273
            }
274
            Endpoint::Objects => {
2751×
                let refs = wire::decode_hashes(&body)?;
2761×
                let bundle = oxy_core::protocol::Bundle {
2771×
                    objects: r.objects_for(&refs)?,
2781×
                    ..Default::default()
279
                };
2801×
                ok(wire::encode_bundle(&bundle))
281
            }
282
            Endpoint::Checkpoint => {
2830×
                let heads = wire::decode_hashes(&body)?;
2840×
                let lock = self.lock_for(name);
2850×
                let _guard = lock.lock().unwrap();
2860×
                ok(wire::encode_bundle(&r.checkpoint_bundle_for(&heads)?))
287
            }
288
            Endpoint::Shallow => {
2890×
                let (heads, depth) = wire::decode_shallow(&body)?;
2900×
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
291
            }
292
            Endpoint::Push => {
29335×
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
29435×
                let lock = self.lock_for(name);
29535×
                let _guard = lock.lock().unwrap();
29635×
                if r.is_unbound() {
297
                    // The first push binds the repository to the pusher's id (spec §16.1).
2982×
                    match claimed {
2992×
                        Some(id) => r.bind_id(id)?,
300
                        None => {
3010×
                            return Err(Failure(
3020×
                                StatusCode::BAD_REQUEST,
3030×
                                format!(
3040×
                                    "this repository is unbound; push with a client that sends {}",
3050×
                                    oxy_core::protocol::REPO_ID_HEADER
3060×
                                ),
3070×
                            ))
308
                        }
309
                    }
31033×
                }
31135×
                let protected = self.backend.default_bookmark(name);
31235×
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
31335×
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
31435×
                });
31535×
                let mut report = r.receive_push_report(bundle, updates, policy, tags)?;
316
                // The request named references, all refused here: it was no
317
                // push of objects alone, whatever the repository saw.
31835×
                if !refused.is_empty() {
3191×
                    report
3201×
                        .results
3211×
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
32234×
                }
32335×
                for u in refused {
3241×
                    report.results.push(oxy_core::protocol::RefResult {
3251×
                        name: u.name.clone(),
3261×
                        ok: false,
3271×
                        reason: format!(
3281×
                            "{:?} is this repository's default bookmark and cannot be deleted",
3291×
                            u.name
3301×
                        ),
3311×
                    });
3321×
                }
33336×
                for r in report.results.iter().filter(|r| !r.ok) {
33415×
                    eprintln!(
33515×
                        "oxy-server: push to {name}: {} refused: {}",
33615×
                        r.name, r.reason
33715×
                    );
33815×
                }
33935×
                self.backend.after_push(name, &report, headers);
34035×
                ok(wire::encode_push_response(&report.results))
341
            }
342
        })
343379×
    }
344
}
345
346
/// The backend of `oxy serve`: one repository per subdirectory of a root,
347
/// open reads, and pushes gated by a list of bearer tokens.
348
pub struct DirBackend {
349
    pub root: PathBuf,
350
    pub tokens: Vec<String>,
351
}
352
353
impl Backend for DirBackend {
354519×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
355519×
        if !valid_repo_name(name) {
3561×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
357518×
        }
358518×
        let dir = self.root.join(name);
359518×
        if !dir.join(".oxy").is_dir() {
3601×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
361517×
        }
362517×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
363519×
    }
364
365151×
    fn default_bookmark(&self, name: &str) -> Option<String> {
366151×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
367151×
    }
368
369372×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
370372×
        if access == Access::Read || self.tokens.is_empty() {
371366×
            return Ok(());
3726×
        }
3736×
        match bearer_token(headers) {
3745×
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
3754×
            _ => Err(Failure(
3764×
                StatusCode::UNAUTHORIZED,
3774×
                "a valid bearer token is required to push".into(),
3784×
            )),
379
        }
380372×
    }
381
}
382
383356×
fn hex_id(h: &str) -> Option<[u8; 16]> {
384356×
    let h = h.trim();
385356×
    if h.len() != 32 {
3860×
        return None;
387356×
    }
388356×
    let mut out = [0u8; 16];
3895696×
    for (i, byte) in out.iter_mut().enumerate() {
3905696×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
391
    }
392356×
    Some(out)
393356×
}
394
395
/// The token of an `Authorization: Bearer` header, if any.
39619×
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
39719×
    headers
39819×
        .get(header::AUTHORIZATION)
39919×
        .and_then(|v| v.to_str().ok())
40019×
        .and_then(|v| v.strip_prefix("Bearer "))
40119×
        .map(str::trim)
40219×
}
403
404372×
async fn dispatch(
405372×
    State(server): State<Arc<Server>>,
406372×
    Path((repo, endpoint)): Path<(String, String)>,
407372×
    method: Method,
408372×
    headers: HeaderMap,
409372×
    body: Bytes,
410372×
) -> Response {
411372×
    match Endpoint::parse(&endpoint) {
412372×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
4130×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
414
    }
415372×
}
416
417
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
41811×
pub fn router(cfg: ServerConfig) -> Router {
41911×
    let server = Server::new(DirBackend {
42011×
        root: cfg.root,
42111×
        tokens: cfg.tokens,
42211×
    });
42311×
    Router::new()
42411×
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
42511×
        .with_state(server)
42611×
}
427
428
/// Serve on an already-bound listener until the process ends; HTTPS when
429
/// `cfg.tls` is set.
43011×
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
43111×
    listener.set_nonblocking(true)?;
43211×
    match cfg.tls.clone() {
4331×
        Some(tls) => {
4341×
            let _ = rustls::crypto::ring::default_provider().install_default();
4351×
            let rustls_cfg =
4361×
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
4371×
                    .await
4381×
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
4391×
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
4401×
                .serve(router(cfg).into_make_service())
4411×
                .await
442
        }
443
        None => {
44410×
            let listener = tokio::net::TcpListener::from_std(listener)?;
44510×
            axum::serve(listener, router(cfg)).await
446
        }
447
    }
4480×
}
449
450
/// Build a runtime and serve; for the CLI and for tests on a background thread.
45111×
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
45211×
    let rt = tokio::runtime::Builder::new_multi_thread()
45311×
        .enable_all()
45411×
        .build()?;
45511×
    rt.block_on(serve(listener, cfg))
45611×
}