OXYGENHUB

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

246 of 287 lines run, 38 of 83 functions · run #333 on main · 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.
6725×
    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.
72123×
    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 {
124382×
    pub fn parse(name: &str) -> Option<Endpoint> {
125382×
        Some(match name {
126382×
            "capabilities" => Endpoint::Capabilities,
127253×
            "refs" => Endpoint::Refs,
128130×
            "negotiate" => Endpoint::Negotiate,
12981×
            "fetch" => Endpoint::Fetch,
13032×
            "objects" => Endpoint::Objects,
13131×
            "checkpoint" => Endpoint::Checkpoint,
13231×
            "shallow" => Endpoint::Shallow,
13331×
            "push" => Endpoint::Push,
1340×
            _ => return None,
135
        })
136382×
    }
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.
152382×
    pub fn method(self) -> Method {
153382×
        match self {
154252×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
155130×
            _ => Method::POST,
156
        }
157382×
    }
158
159382×
    fn access(self) -> Access {
160382×
        match self {
16131×
            Endpoint::Push => Access::Push,
162351×
            _ => Access::Read,
163
        }
164382×
    }
165
}
166
167374×
fn ok(body: Vec<u8>) -> Response {
168374×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
169374×
}
170
171509×
pub fn valid_repo_name(name: &str) -> bool {
172509×
    !name.is_empty()
173509×
        && !name.starts_with('.')
174508×
        && name
175508×
            .chars()
1762805×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
177509×
}
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
19126×
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
19226×
        self.locks
19326×
            .lock()
19426×
            .unwrap()
19526×
            .entry(name.to_string())
19626×
            .or_default()
19726×
            .clone()
19826×
    }
199
200
    /// Answer one protocol request for repository `name`. `method` is
201
    /// checked against the endpoint; the body is the raw CBOR request.
202382×
    pub async fn handle(
203382×
        self: &Arc<Self>,
204382×
        name: String,
205382×
        endpoint: Endpoint,
206382×
        method: &Method,
207382×
        headers: &HeaderMap,
208382×
        body: Bytes,
209382×
    ) -> Response {
210382×
        if *method != endpoint.method() {
2110×
            return Failure(
2120×
                StatusCode::METHOD_NOT_ALLOWED,
2130×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2140×
            )
2150×
            .into_response();
216382×
        }
217382×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2186×
            return f.into_response();
219376×
        }
220376×
        let claimed = headers
221376×
            .get(oxy_core::protocol::REPO_ID_HEADER)
222376×
            .and_then(|v| v.to_str().ok())
223376×
            .and_then(hex_id);
224376×
        let server = Arc::clone(self);
225376×
        let request_headers = headers.clone();
226376×
        let repo = name.clone();
227376×
        let result = tokio::task::spawn_blocking(move || {
228376×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
229376×
        })
230376×
        .await;
231376×
        let failure = match result {
232374×
            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()
243382×
    }
244
245376×
    fn respond(
246376×
        &self,
247376×
        name: &str,
248376×
        endpoint: Endpoint,
249376×
        body: Bytes,
250376×
        claimed: Option<[u8; 16]>,
251376×
        headers: &HeaderMap,
252376×
    ) -> Result<Response, Failure> {
253376×
        let r = self.backend.open(name)?;
254374×
        Ok(match endpoint {
255126×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
256
            Endpoint::Refs => {
257123×
                let mut refs = r.remote_refs()?;
258123×
                if let Some(d) = self.backend.default_bookmark(name) {
259119×
                    refs.default_bookmark = Some(d);
260119×
                }
261123×
                self.backend.add_log(name, &mut refs);
262123×
                ok(wire::encode_refs(r.id()?, &refs))
263
            }
264
            Endpoint::Negotiate => {
26549×
                let (have, want) = wire::decode_negotiate(&body)?;
26649×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
267
            }
268
            Endpoint::Fetch => {
26949×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
27049×
                ok(wire::encode_bundle(
27149×
                    &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 => {
29326×
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
29426×
                let lock = self.lock_for(name);
29526×
                let _guard = lock.lock().unwrap();
29626×
                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
                    }
31024×
                }
31126×
                let protected = self.backend.default_bookmark(name);
31226×
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
31326×
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
31426×
                });
31526×
                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.
31826×
                if !refused.is_empty() {
3191×
                    report
3201×
                        .results
3211×
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
32225×
                }
32326×
                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×
                }
33327×
                for r in report.results.iter().filter(|r| !r.ok) {
3346×
                    eprintln!(
3356×
                        "oxy-server: push to {name}: {} refused: {}",
3366×
                        r.name, r.reason
3376×
                    );
3386×
                }
33926×
                self.backend.after_push(name, &report, headers);
34026×
                ok(wire::encode_push_response(&report.results))
341
            }
342
        })
343376×
    }
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 {
354509×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
355509×
        if !valid_repo_name(name) {
3561×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
357508×
        }
358508×
        let dir = self.root.join(name);
359508×
        if !dir.join(".oxy").is_dir() {
3601×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
361507×
        }
362507×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
363509×
    }
364
365144×
    fn default_bookmark(&self, name: &str) -> Option<String> {
366144×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
367144×
    }
368
369369×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
370369×
        if access == Access::Read || self.tokens.is_empty() {
371363×
            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
        }
380369×
    }
381
}
382
383353×
fn hex_id(h: &str) -> Option<[u8; 16]> {
384353×
    let h = h.trim();
385353×
    if h.len() != 32 {
3860×
        return None;
387353×
    }
388353×
    let mut out = [0u8; 16];
3895648×
    for (i, byte) in out.iter_mut().enumerate() {
3905648×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
391
    }
392353×
    Some(out)
393353×
}
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
404369×
async fn dispatch(
405369×
    State(server): State<Arc<Server>>,
406369×
    Path((repo, endpoint)): Path<(String, String)>,
407369×
    method: Method,
408369×
    headers: HeaderMap,
409369×
    body: Bytes,
410369×
) -> Response {
411369×
    match Endpoint::parse(&endpoint) {
412369×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
4130×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
414
    }
415369×
}
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×
}