OXYGENHUB

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

244 of 285 lines run, 36 of 80 functions · run #275 on carry-identical · 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.
6530×
    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 {
866×
    fn into_response(self) -> Response {
876×
        (self.0, self.1).into_response()
886×
    }
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 {
117345×
    pub fn parse(name: &str) -> Option<Endpoint> {
118345×
        Some(match name {
119345×
            "capabilities" => Endpoint::Capabilities,
120230×
            "refs" => Endpoint::Refs,
121121×
            "negotiate" => Endpoint::Negotiate,
12278×
            "fetch" => Endpoint::Fetch,
12335×
            "objects" => Endpoint::Objects,
12434×
            "checkpoint" => Endpoint::Checkpoint,
12534×
            "shallow" => Endpoint::Shallow,
12634×
            "push" => Endpoint::Push,
1270×
            _ => return None,
128
        })
129345×
    }
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.
145345×
    pub fn method(self) -> Method {
146345×
        match self {
147224×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
148121×
            _ => Method::POST,
149
        }
150345×
    }
151
152345×
    fn access(self) -> Access {
153345×
        match self {
15434×
            Endpoint::Push => Access::Push,
155311×
            _ => Access::Read,
156
        }
157345×
    }
158
}
159
160339×
fn ok(body: Vec<u8>) -> Response {
161339×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
162339×
}
163
164465×
pub fn valid_repo_name(name: &str) -> bool {
165465×
    !name.is_empty()
166465×
        && !name.starts_with('.')
167464×
        && name
168464×
            .chars()
1692557×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
170465×
}
171
172
impl Server {
17311×
    pub fn new(backend: impl Backend) -> Arc<Server> {
17411×
        Arc::new(Server {
17511×
            backend: Box::new(backend),
17611×
            locks: Mutex::new(HashMap::new()),
17711×
        })
17811×
    }
179
1800×
    pub fn backend(&self) -> &dyn Backend {
1810×
        self.backend.as_ref()
1820×
    }
183
18431×
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
18531×
        self.locks
18631×
            .lock()
18731×
            .unwrap()
18831×
            .entry(name.to_string())
18931×
            .or_default()
19031×
            .clone()
19131×
    }
192
193
    /// Answer one protocol request for repository `name`. `method` is
194
    /// checked against the endpoint; the body is the raw CBOR request.
195345×
    pub async fn handle(
196345×
        self: &Arc<Self>,
197345×
        name: String,
198345×
        endpoint: Endpoint,
199345×
        method: &Method,
200345×
        headers: &HeaderMap,
201345×
        body: Bytes,
202345×
    ) -> Response {
203345×
        if *method != endpoint.method() {
2040×
            return Failure(
2050×
                StatusCode::METHOD_NOT_ALLOWED,
2060×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2070×
            )
2080×
            .into_response();
209345×
        }
210345×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2114×
            return f.into_response();
212341×
        }
213341×
        let claimed = headers
214341×
            .get(oxy_core::protocol::REPO_ID_HEADER)
215341×
            .and_then(|v| v.to_str().ok())
216341×
            .and_then(hex_id);
217341×
        let server = Arc::clone(self);
218341×
        let request_headers = headers.clone();
219341×
        let repo = name.clone();
220341×
        let result = tokio::task::spawn_blocking(move || {
221341×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
222341×
        })
223341×
        .await;
224341×
        let failure = match result {
225339×
            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()
236345×
    }
237
238341×
    fn respond(
239341×
        &self,
240341×
        name: &str,
241341×
        endpoint: Endpoint,
242341×
        body: Bytes,
243341×
        claimed: Option<[u8; 16]>,
244341×
        headers: &HeaderMap,
245341×
    ) -> Result<Response, Failure> {
246341×
        let r = self.backend.open(name)?;
247339×
        Ok(match endpoint {
248112×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
249
            Endpoint::Refs => {
250109×
                let mut refs = r.remote_refs()?;
251109×
                if let Some(d) = self.backend.default_bookmark(name) {
252105×
                    refs.default_bookmark = Some(d);
253105×
                }
254109×
                ok(wire::encode_refs(r.id()?, &refs))
255
            }
256
            Endpoint::Negotiate => {
25743×
                let (have, want) = wire::decode_negotiate(&body)?;
25843×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
259
            }
260
            Endpoint::Fetch => {
26143×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
26243×
                ok(wire::encode_bundle(
26343×
                    &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 => {
28531×
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
28631×
                let lock = self.lock_for(name);
28731×
                let _guard = lock.lock().unwrap();
28831×
                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
                    }
30229×
                }
30331×
                let protected = self.backend.default_bookmark(name);
30431×
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
30531×
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
30631×
                });
30731×
                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.
31031×
                if !refused.is_empty() {
3111×
                    report
3121×
                        .results
3131×
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
31430×
                }
31531×
                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×
                }
32532×
                for r in report.results.iter().filter(|r| !r.ok) {
32612×
                    eprintln!(
32712×
                        "oxy-server: push to {name}: {} refused: {}",
32812×
                        r.name, r.reason
32912×
                    );
33012×
                }
33131×
                self.backend.after_push(name, &report, headers);
33231×
                ok(wire::encode_push_response(&report.results))
333
            }
334
        })
335341×
    }
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 {
346465×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
347465×
        if !valid_repo_name(name) {
3481×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
349464×
        }
350464×
        let dir = self.root.join(name);
351464×
        if !dir.join(".oxy").is_dir() {
3521×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
353463×
        }
354463×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
355465×
    }
356
357135×
    fn default_bookmark(&self, name: &str) -> Option<String> {
358135×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
359135×
    }
360
361332×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
362332×
        if access == Access::Read || self.tokens.is_empty() {
363329×
            return Ok(());
3643×
        }
3653×
        match bearer_token(headers) {
3662×
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
3672×
            _ => Err(Failure(
3682×
                StatusCode::UNAUTHORIZED,
3692×
                "a valid bearer token is required to push".into(),
3702×
            )),
371
        }
372332×
    }
373
}
374
375320×
fn hex_id(h: &str) -> Option<[u8; 16]> {
376320×
    let h = h.trim();
377320×
    if h.len() != 32 {
3780×
        return None;
379320×
    }
380320×
    let mut out = [0u8; 16];
3815120×
    for (i, byte) in out.iter_mut().enumerate() {
3825120×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
383
    }
384320×
    Some(out)
385320×
}
386
387
/// The token of an `Authorization: Bearer` header, if any.
38816×
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
38916×
    headers
39016×
        .get(header::AUTHORIZATION)
39116×
        .and_then(|v| v.to_str().ok())
39216×
        .and_then(|v| v.strip_prefix("Bearer "))
39316×
        .map(str::trim)
39416×
}
395
396332×
async fn dispatch(
397332×
    State(server): State<Arc<Server>>,
398332×
    Path((repo, endpoint)): Path<(String, String)>,
399332×
    method: Method,
400332×
    headers: HeaderMap,
401332×
    body: Bytes,
402332×
) -> Response {
403332×
    match Endpoint::parse(&endpoint) {
404332×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
4050×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
406
    }
407332×
}
408
409
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
41010×
pub fn router(cfg: ServerConfig) -> Router {
41110×
    let server = Server::new(DirBackend {
41210×
        root: cfg.root,
41310×
        tokens: cfg.tokens,
41410×
    });
41510×
    Router::new()
41610×
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
41710×
        .with_state(server)
41810×
}
419
420
/// Serve on an already-bound listener until the process ends; HTTPS when
421
/// `cfg.tls` is set.
42210×
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
42310×
    listener.set_nonblocking(true)?;
42410×
    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 => {
4369×
            let listener = tokio::net::TcpListener::from_std(listener)?;
4379×
            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.
44310×
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
44410×
    let rt = tokio::runtime::Builder::new_multi_thread()
44510×
        .enable_all()
44610×
        .build()?;
44710×
    rt.block_on(serve(listener, cfg))
44810×
}