OXYGENHUB

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

244 of 285 lines run, 36 of 80 functions · run #307 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
use axum::body::Bytes;
15
use axum::extract::{Path, State};
16
use axum::http::{header, HeaderMap, Method, StatusCode};
17
use axum::response::{IntoResponse, Response};
18
use axum::routing::any;
19
use axum::Router;
20
use oxy_core::protocol::{wire, CONTENT_TYPE};
21
use oxy_core::repo::Repo;
22
use std::collections::HashMap;
23
use std::path::PathBuf;
24
use std::sync::{Arc, Mutex};
25
26
#[derive(Clone, Debug)]
27
pub struct ServerConfig {
28
    /// Directory containing one repository per subdirectory.
29
    pub root: PathBuf,
30
    /// Bearer tokens allowed to push; empty means no authentication.
31
    pub tokens: Vec<String>,
32
    /// Serve HTTPS with this certificate chain and private key (PEM files).
33
    pub tls: Option<TlsFiles>,
34
}
35
36
#[derive(Clone, Debug)]
37
pub struct TlsFiles {
38
    pub cert: PathBuf,
39
    pub key: PathBuf,
40
}
41
42
/// Which kind of access a request needs (spec §15.1: reads may be open;
43
/// a push must be authenticated when any credential is configured).
44
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45
pub enum Access {
46
    Read,
47
    Push,
48
}
49
50
/// What a host provides to the protocol server: how a repository name maps
51
/// to a repository on disk and who may do what. `oxy serve` uses
52
/// [`DirBackend`]; a hub supplies its own with accounts and roles.
53
pub trait Backend: Send + Sync + 'static {
54
    /// Open the repository called `name`, or fail with the status to
55
    /// answer. An unknown name is `404`; a name the caller may not see
56
    /// SHOULD also be `404`, so private repositories are not enumerable.
57
    fn open(&self, name: &str) -> Result<Repo, Failure>;
58
59
    /// Decide whether this request may perform `access` on `name`.
60
    fn authorize(&self, name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure>;
61
62
    /// Called after a push was processed, with its per-reference results
63
    /// (accepted or refused), the states each accepted reference moved
64
    /// between, and the changes stored, for logs and cache invalidation.
6528×
    fn after_push(&self, _name: &str, _report: &oxy_core::repo::PushReport, _headers: &HeaderMap) {}
66
67
    /// The bookmark of `name` that pushes may never delete (its default),
68
    /// when the host keeps one apart from the repository's own config.
695×
    fn default_bookmark(&self, _name: &str) -> Option<String> {
705×
        None
715×
    }
72
}
73
74
/// A protocol server over any [`Backend`], serialising the pushes to each
75
/// repository. Hosts route requests to [`Server::handle`].
76
pub struct Server {
77
    backend: Box<dyn Backend>,
78
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
79
}
80
81
/// An error response: a status and a plain-text body.
82
#[derive(Debug)]
83
pub struct Failure(pub StatusCode, pub String);
84
85
impl IntoResponse for Failure {
868×
    fn into_response(self) -> Response {
878×
        (self.0, self.1).into_response()
888×
    }
89
}
90
91
impl From<oxy_core::repo::RepoError> for Failure {
920×
    fn from(e: oxy_core::repo::RepoError) -> Failure {
93
        use oxy_core::repo::RepoError;
94
        // The server's own storage failing is not the client's fault.
950×
        let status = match &e {
960×
            RepoError::Io(_) | RepoError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
970×
            _ => StatusCode::BAD_REQUEST,
98
        };
990×
        Failure(status, e.to_string())
1000×
    }
101
}
102
103
/// The wire protocol's endpoints (spec §16.1), named as in the URL.
104
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105
pub enum Endpoint {
106
    Capabilities,
107
    Refs,
108
    Negotiate,
109
    Fetch,
110
    Objects,
111
    Checkpoint,
112
    Shallow,
113
    Push,
114
}
115
116
impl Endpoint {
117385×
    pub fn parse(name: &str) -> Option<Endpoint> {
118385×
        Some(match name {
119385×
            "capabilities" => Endpoint::Capabilities,
120256×
            "refs" => Endpoint::Refs,
121133×
            "negotiate" => Endpoint::Negotiate,
12284×
            "fetch" => Endpoint::Fetch,
12335×
            "objects" => Endpoint::Objects,
12434×
            "checkpoint" => Endpoint::Checkpoint,
12534×
            "shallow" => Endpoint::Shallow,
12634×
            "push" => Endpoint::Push,
1270×
            _ => return None,
128
        })
129385×
    }
130
1312×
    pub fn name(self) -> &'static str {
1322×
        match self {
1332×
            Endpoint::Capabilities => "capabilities",
1340×
            Endpoint::Refs => "refs",
1350×
            Endpoint::Negotiate => "negotiate",
1360×
            Endpoint::Fetch => "fetch",
1370×
            Endpoint::Objects => "objects",
1380×
            Endpoint::Checkpoint => "checkpoint",
1390×
            Endpoint::Shallow => "shallow",
1400×
            Endpoint::Push => "push",
141
        }
1422×
    }
143
144
    /// The HTTP method the endpoint answers to.
145385×
    pub fn method(self) -> Method {
146385×
        match self {
147252×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
148133×
            _ => Method::POST,
149
        }
150385×
    }
151
152385×
    fn access(self) -> Access {
153385×
        match self {
15434×
            Endpoint::Push => Access::Push,
155351×
            _ => Access::Read,
156
        }
157385×
    }
158
}
159
160377×
fn ok(body: Vec<u8>) -> Response {
161377×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
162377×
}
163
164515×
pub fn valid_repo_name(name: &str) -> bool {
165515×
    !name.is_empty()
166515×
        && !name.starts_with('.')
167514×
        && name
168514×
            .chars()
1692841×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
170515×
}
171
172
impl Server {
17312×
    pub fn new(backend: impl Backend) -> Arc<Server> {
17412×
        Arc::new(Server {
17512×
            backend: Box::new(backend),
17612×
            locks: Mutex::new(HashMap::new()),
17712×
        })
17812×
    }
179
1800×
    pub fn backend(&self) -> &dyn Backend {
1810×
        self.backend.as_ref()
1820×
    }
183
18429×
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
18529×
        self.locks
18629×
            .lock()
18729×
            .unwrap()
18829×
            .entry(name.to_string())
18929×
            .or_default()
19029×
            .clone()
19129×
    }
192
193
    /// Answer one protocol request for repository `name`. `method` is
194
    /// checked against the endpoint; the body is the raw CBOR request.
195385×
    pub async fn handle(
196385×
        self: &Arc<Self>,
197385×
        name: String,
198385×
        endpoint: Endpoint,
199385×
        method: &Method,
200385×
        headers: &HeaderMap,
201385×
        body: Bytes,
202385×
    ) -> Response {
203385×
        if *method != endpoint.method() {
2040×
            return Failure(
2050×
                StatusCode::METHOD_NOT_ALLOWED,
2060×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2070×
            )
2080×
            .into_response();
209385×
        }
210385×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2116×
            return f.into_response();
212379×
        }
213379×
        let claimed = headers
214379×
            .get(oxy_core::protocol::REPO_ID_HEADER)
215379×
            .and_then(|v| v.to_str().ok())
216379×
            .and_then(hex_id);
217379×
        let server = Arc::clone(self);
218379×
        let request_headers = headers.clone();
219379×
        let repo = name.clone();
220379×
        let result = tokio::task::spawn_blocking(move || {
221379×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
222379×
        })
223379×
        .await;
224379×
        let failure = match result {
225377×
            Ok(Ok(r)) => return r,
2262×
            Ok(Err(f)) => f,
2270×
            Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
228
        };
229
        // Name the operation and repository, in the log and for the client.
2302×
        let f = Failure(
2312×
            failure.0,
2322×
            format!("{} of {name}: {}", endpoint.name(), failure.1),
2332×
        );
2342×
        eprintln!("oxy-server: {}: {}", f.0.as_u16(), f.1);
2352×
        f.into_response()
236385×
    }
237
238379×
    fn respond(
239379×
        &self,
240379×
        name: &str,
241379×
        endpoint: Endpoint,
242379×
        body: Bytes,
243379×
        claimed: Option<[u8; 16]>,
244379×
        headers: &HeaderMap,
245379×
    ) -> Result<Response, Failure> {
246379×
        let r = self.backend.open(name)?;
247377×
        Ok(match endpoint {
248126×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
249
            Endpoint::Refs => {
250123×
                let mut refs = r.remote_refs()?;
251123×
                if let Some(d) = self.backend.default_bookmark(name) {
252119×
                    refs.default_bookmark = Some(d);
253119×
                }
254123×
                ok(wire::encode_refs(r.id()?, &refs))
255
            }
256
            Endpoint::Negotiate => {
25749×
                let (have, want) = wire::decode_negotiate(&body)?;
25849×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
259
            }
260
            Endpoint::Fetch => {
26149×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
26249×
                ok(wire::encode_bundle(
26349×
                    &r.bundle_for_filtered(&changes, max_blob)?,
264
                ))
265
            }
266
            Endpoint::Objects => {
2671×
                let refs = wire::decode_hashes(&body)?;
2681×
                let bundle = oxy_core::protocol::Bundle {
2691×
                    objects: r.objects_for(&refs)?,
2701×
                    ..Default::default()
271
                };
2721×
                ok(wire::encode_bundle(&bundle))
273
            }
274
            Endpoint::Checkpoint => {
2750×
                let heads = wire::decode_hashes(&body)?;
2760×
                let lock = self.lock_for(name);
2770×
                let _guard = lock.lock().unwrap();
2780×
                ok(wire::encode_bundle(&r.checkpoint_bundle_for(&heads)?))
279
            }
280
            Endpoint::Shallow => {
2810×
                let (heads, depth) = wire::decode_shallow(&body)?;
2820×
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
283
            }
284
            Endpoint::Push => {
28529×
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
28629×
                let lock = self.lock_for(name);
28729×
                let _guard = lock.lock().unwrap();
28829×
                if r.is_unbound() {
289
                    // The first push binds the repository to the pusher's id (spec §16.1).
2902×
                    match claimed {
2912×
                        Some(id) => r.bind_id(id)?,
292
                        None => {
2930×
                            return Err(Failure(
2940×
                                StatusCode::BAD_REQUEST,
2950×
                                format!(
2960×
                                    "this repository is unbound; push with a client that sends {}",
2970×
                                    oxy_core::protocol::REPO_ID_HEADER
2980×
                                ),
2990×
                            ))
300
                        }
301
                    }
30227×
                }
30329×
                let protected = self.backend.default_bookmark(name);
30429×
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
30529×
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
30629×
                });
30729×
                let mut report = r.receive_push_report(bundle, updates, policy, tags)?;
308
                // The request named references, all refused here: it was no
309
                // push of objects alone, whatever the repository saw.
31029×
                if !refused.is_empty() {
3111×
                    report
3121×
                        .results
3131×
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
31428×
                }
31529×
                for u in refused {
3161×
                    report.results.push(oxy_core::protocol::RefResult {
3171×
                        name: u.name.clone(),
3181×
                        ok: false,
3191×
                        reason: format!(
3201×
                            "{:?} is this repository's default bookmark and cannot be deleted",
3211×
                            u.name
3221×
                        ),
3231×
                    });
3241×
                }
32530×
                for r in report.results.iter().filter(|r| !r.ok) {
3269×
                    eprintln!(
3279×
                        "oxy-server: push to {name}: {} refused: {}",
3289×
                        r.name, r.reason
3299×
                    );
3309×
                }
33129×
                self.backend.after_push(name, &report, headers);
33229×
                ok(wire::encode_push_response(&report.results))
333
            }
334
        })
335379×
    }
336
}
337
338
/// The backend of `oxy serve`: one repository per subdirectory of a root,
339
/// open reads, and pushes gated by a list of bearer tokens.
340
pub struct DirBackend {
341
    pub root: PathBuf,
342
    pub tokens: Vec<String>,
343
}
344
345
impl Backend for DirBackend {
346515×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
347515×
        if !valid_repo_name(name) {
3481×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
349514×
        }
350514×
        let dir = self.root.join(name);
351514×
        if !dir.join(".oxy").is_dir() {
3521×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
353513×
        }
354513×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
355515×
    }
356
357147×
    fn default_bookmark(&self, name: &str) -> Option<String> {
358147×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
359147×
    }
360
361372×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
362372×
        if access == Access::Read || self.tokens.is_empty() {
363366×
            return Ok(());
3646×
        }
3656×
        match bearer_token(headers) {
3665×
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
3674×
            _ => Err(Failure(
3684×
                StatusCode::UNAUTHORIZED,
3694×
                "a valid bearer token is required to push".into(),
3704×
            )),
371
        }
372372×
    }
373
}
374
375356×
fn hex_id(h: &str) -> Option<[u8; 16]> {
376356×
    let h = h.trim();
377356×
    if h.len() != 32 {
3780×
        return None;
379356×
    }
380356×
    let mut out = [0u8; 16];
3815696×
    for (i, byte) in out.iter_mut().enumerate() {
3825696×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
383
    }
384356×
    Some(out)
385356×
}
386
387
/// The token of an `Authorization: Bearer` header, if any.
38819×
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
38919×
    headers
39019×
        .get(header::AUTHORIZATION)
39119×
        .and_then(|v| v.to_str().ok())
39219×
        .and_then(|v| v.strip_prefix("Bearer "))
39319×
        .map(str::trim)
39419×
}
395
396372×
async fn dispatch(
397372×
    State(server): State<Arc<Server>>,
398372×
    Path((repo, endpoint)): Path<(String, String)>,
399372×
    method: Method,
400372×
    headers: HeaderMap,
401372×
    body: Bytes,
402372×
) -> Response {
403372×
    match Endpoint::parse(&endpoint) {
404372×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
4050×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
406
    }
407372×
}
408
409
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
41011×
pub fn router(cfg: ServerConfig) -> Router {
41111×
    let server = Server::new(DirBackend {
41211×
        root: cfg.root,
41311×
        tokens: cfg.tokens,
41411×
    });
41511×
    Router::new()
41611×
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
41711×
        .with_state(server)
41811×
}
419
420
/// Serve on an already-bound listener until the process ends; HTTPS when
421
/// `cfg.tls` is set.
42211×
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
42311×
    listener.set_nonblocking(true)?;
42411×
    match cfg.tls.clone() {
4251×
        Some(tls) => {
4261×
            let _ = rustls::crypto::ring::default_provider().install_default();
4271×
            let rustls_cfg =
4281×
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
4291×
                    .await
4301×
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
4311×
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
4321×
                .serve(router(cfg).into_make_service())
4331×
                .await
434
        }
435
        None => {
43610×
            let listener = tokio::net::TcpListener::from_std(listener)?;
43710×
            axum::serve(listener, router(cfg)).await
438
        }
439
    }
4400×
}
441
442
/// Build a runtime and serve; for the CLI and for tests on a background thread.
44311×
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
44411×
    let rt = tokio::runtime::Builder::new_multi_thread()
44511×
        .enable_all()
44611×
        .build()?;
44711×
    rt.block_on(serve(listener, cfg))
44811×
}