OXYGENHUB

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

286 of 339 lines run, 56 of 113 functions · run #373 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.
6734×
    fn after_push(&self, _name: &str, _report: &oxy_core::repo::PushReport, _headers: &HeaderMap) {}
68
69
    /// Vet a push by what it adds before anything of it is stored or any
70
    /// reference moves (spec §16.1): `bundle` is the push as decoded, its
71
    /// changes with their lines, `updates` the references it would move.
72
    /// A host refuses the whole push by returning a [`Failure`], whose
73
    /// text reaches the client as the push's error, as it is, several
74
    /// lines included; it should answer neither 401, 403 nor 404, which a
75
    /// client takes for a credential it should change. Called for every
76
    /// part of a push sent in parts (each part's changes are its own),
77
    /// outside the repository's push lock, so a slow vet holds up no
78
    /// other push. The default accepts everything at no cost.
7934×
    fn vet_push(
8034×
        &self,
8134×
        _name: &str,
8234×
        _repo: &Repo,
8334×
        _bundle: &oxy_core::protocol::Bundle,
8434×
        _updates: &[oxy_core::protocol::RefUpdate],
8534×
        _headers: &HeaderMap,
8634×
    ) -> Result<(), Failure> {
8734×
        Ok(())
8834×
    }
89
90
    /// Add the host's transparency log to a refs answer (spec §14.8): its
91
    /// checkpoint, and each attestation's entry and inclusion proof. A host
92
    /// without a log leaves it as it is.
93139×
    fn add_log(&self, _name: &str, _refs: &mut oxy_core::protocol::RefsResponse) {}
94
95
    /// Tailor a refs answer to the client asking, by its request headers
96
    /// (its `User-Agent` and the features it declares in `Oxy-Features`),
97
    /// after [`Backend::add_log`]. The default leaves out the tags a client
98
    /// that does not declare `certified-tags` would refuse
99
    /// ([`Repo::refs_for_client`], oxygen#131); a host that overrides it
100
    /// should apply that too ([`tailor_refs`]).
101139×
    fn adjust_refs(
102139×
        &self,
103139×
        _name: &str,
104139×
        repo: &Repo,
105139×
        refs: &mut oxy_core::protocol::RefsResponse,
106139×
        headers: &HeaderMap,
107139×
    ) {
108139×
        tailor_refs(repo, refs, headers);
109139×
    }
110
111
    /// Whether tag `tag` of `name` may be withdrawn (oxygenhub#301): called
112
    /// for each withdrawal a push carries, before the repository sees it.
113
    /// A host refuses one it depends on (a forge's release names the tag)
114
    /// with the reason, which is that withdrawal's result. The default
115
    /// allows every one; the policy is checked after, as for any push.
1160×
    fn vet_tag_withdrawal(&self, _name: &str, _tag: &str) -> Result<(), String> {
1170×
        Ok(())
1180×
    }
119
120
    /// The bookmark of `name` that pushes may never delete (its default),
121
    /// when the host keeps one apart from the repository's own config.
12228×
    fn default_bookmark(&self, _name: &str) -> Option<String> {
12328×
        None
12428×
    }
125
}
126
127
/// A protocol server over any [`Backend`], serialising the pushes to each
128
/// repository. Hosts route requests to [`Server::handle`].
129
pub struct Server {
130
    backend: Box<dyn Backend>,
131
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
132
}
133
134
/// An error response: a status and a plain-text body.
135
#[derive(Debug)]
136
pub struct Failure(pub StatusCode, pub String);
137
138
impl IntoResponse for Failure {
1399×
    fn into_response(self) -> Response {
1409×
        (self.0, self.1).into_response()
1419×
    }
142
}
143
144
impl From<oxy_core::repo::RepoError> for Failure {
1450×
    fn from(e: oxy_core::repo::RepoError) -> Failure {
146
        use oxy_core::repo::RepoError;
147
        // The server's own storage failing is not the client's fault.
1480×
        let status = match &e {
1490×
            RepoError::Io(_) | RepoError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
1500×
            _ => StatusCode::BAD_REQUEST,
151
        };
1520×
        Failure(status, e.to_string())
1530×
    }
154
}
155
156
/// The wire protocol's endpoints (spec §16.1), named as in the URL.
157
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158
pub enum Endpoint {
159
    Capabilities,
160
    Refs,
161
    Negotiate,
162
    Fetch,
163
    Objects,
164
    Checkpoint,
165
    Shallow,
166
    Push,
167
}
168
169
impl Endpoint {
170428×
    pub fn parse(name: &str) -> Option<Endpoint> {
171428×
        Some(match name {
172428×
            "capabilities" => Endpoint::Capabilities,
173287×
            "refs" => Endpoint::Refs,
174148×
            "negotiate" => Endpoint::Negotiate,
17595×
            "fetch" => Endpoint::Fetch,
17642×
            "objects" => Endpoint::Objects,
17741×
            "checkpoint" => Endpoint::Checkpoint,
17841×
            "shallow" => Endpoint::Shallow,
17941×
            "push" => Endpoint::Push,
1800×
            _ => return None,
181
        })
182428×
    }
183
1843×
    pub fn name(self) -> &'static str {
1853×
        match self {
1862×
            Endpoint::Capabilities => "capabilities",
1870×
            Endpoint::Refs => "refs",
1880×
            Endpoint::Negotiate => "negotiate",
1890×
            Endpoint::Fetch => "fetch",
1900×
            Endpoint::Objects => "objects",
1910×
            Endpoint::Checkpoint => "checkpoint",
1920×
            Endpoint::Shallow => "shallow",
1931×
            Endpoint::Push => "push",
194
        }
1953×
    }
196
197
    /// The HTTP method the endpoint answers to.
198428×
    pub fn method(self) -> Method {
199428×
        match self {
200280×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
201148×
            _ => Method::POST,
202
        }
203428×
    }
204
205428×
    fn access(self) -> Access {
206428×
        match self {
20741×
            Endpoint::Push => Access::Push,
208387×
            _ => Access::Read,
209
        }
210428×
    }
211
}
212
213419×
fn ok(body: Vec<u8>) -> Response {
214419×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
215419×
}
216
217511×
pub fn valid_repo_name(name: &str) -> bool {
218511×
    !name.is_empty()
219511×
        && !name.starts_with('.')
220510×
        && name
221510×
            .chars()
2222799×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
223511×
}
224
225
impl Server {
22615×
    pub fn new(backend: impl Backend) -> Arc<Server> {
22715×
        Arc::new(Server {
22815×
            backend: Box::new(backend),
22915×
            locks: Mutex::new(HashMap::new()),
23015×
        })
23115×
    }
232
2330×
    pub fn backend(&self) -> &dyn Backend {
2340×
        self.backend.as_ref()
2350×
    }
236
23735×
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
23835×
        self.locks
23935×
            .lock()
24035×
            .unwrap()
24135×
            .entry(name.to_string())
24235×
            .or_default()
24335×
            .clone()
24435×
    }
245
246
    /// Answer one protocol request for repository `name`. `method` is
247
    /// checked against the endpoint; the body is the raw CBOR request.
248428×
    pub async fn handle(
249428×
        self: &Arc<Self>,
250428×
        name: String,
251428×
        endpoint: Endpoint,
252428×
        method: &Method,
253428×
        headers: &HeaderMap,
254428×
        body: Bytes,
255428×
    ) -> Response {
256428×
        if *method != endpoint.method() {
2570×
            return Failure(
2580×
                StatusCode::METHOD_NOT_ALLOWED,
2590×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2600×
            )
2610×
            .into_response();
262428×
        }
263428×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2646×
            return f.into_response();
265422×
        }
266422×
        let claimed = headers
267422×
            .get(oxy_core::protocol::REPO_ID_HEADER)
268422×
            .and_then(|v| v.to_str().ok())
269422×
            .and_then(hex_id);
270422×
        let server = Arc::clone(self);
271422×
        let request_headers = headers.clone();
272422×
        let repo = name.clone();
273422×
        let result = tokio::task::spawn_blocking(move || {
274422×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
275422×
        })
276422×
        .await;
277422×
        let failure = match result {
278419×
            Ok(Ok(r)) => return r,
2793×
            Ok(Err(f)) => f,
2800×
            Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
281
        };
282
        // Name the operation and repository, in the log and for the client.
2833×
        let f = Failure(
2843×
            failure.0,
2853×
            format!("{} of {name}: {}", endpoint.name(), failure.1),
2863×
        );
2873×
        eprintln!("oxy-server: {}: {}", f.0.as_u16(), f.1);
2883×
        f.into_response()
289428×
    }
290
291422×
    fn respond(
292422×
        &self,
293422×
        name: &str,
294422×
        endpoint: Endpoint,
295422×
        body: Bytes,
296422×
        claimed: Option<[u8; 16]>,
297422×
        headers: &HeaderMap,
298422×
    ) -> Result<Response, Failure> {
299422×
        let r = self.backend.open(name)?;
300420×
        Ok(match endpoint {
301138×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
302
            Endpoint::Refs => {
303139×
                let mut refs = r.remote_refs()?;
304139×
                if let Some(d) = self.backend.default_bookmark(name) {
305117×
                    refs.default_bookmark = Some(d);
306117×
                }
307139×
                self.backend.add_log(name, &mut refs);
308139×
                self.backend.adjust_refs(name, &r, &mut refs, headers);
309139×
                ok(wire::encode_refs(r.id()?, &refs))
310
            }
311
            Endpoint::Negotiate => {
31253×
                let (have, want) = wire::decode_negotiate(&body)?;
31353×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
314
            }
315
            Endpoint::Fetch => {
31653×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
31753×
                ok(wire::encode_bundle(
31853×
                    &r.bundle_for_filtered(&changes, max_blob)?,
319
                ))
320
            }
321
            Endpoint::Objects => {
3221×
                let refs = wire::decode_hashes(&body)?;
3231×
                let bundle = oxy_core::protocol::Bundle {
3241×
                    objects: r.objects_for(&refs)?,
3251×
                    ..Default::default()
326
                };
3271×
                ok(wire::encode_bundle(&bundle))
328
            }
329
            Endpoint::Checkpoint => {
3300×
                let heads = wire::decode_hashes(&body)?;
3310×
                let lock = self.lock_for(name);
3320×
                let _guard = lock.lock().unwrap();
3330×
                let bundle = r.checkpoint_bundle_for(&heads)?;
3340×
                let _t = oxy_core::timing::phase("serve: encode the checkpoint");
3350×
                ok(wire::encode_bundle(&bundle))
336
            }
337
            Endpoint::Shallow => {
3380×
                let (heads, depth) = wire::decode_shallow(&body)?;
3390×
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
340
            }
341
            Endpoint::Push => {
34236×
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
343
                // The host vets what the push adds before anything is stored
344
                // or bound: a refused push leaves the repository as it was.
34536×
                self.backend
34636×
                    .vet_push(name, &r, &bundle, &updates, headers)?;
34735×
                let lock = self.lock_for(name);
34835×
                let _guard = lock.lock().unwrap();
34935×
                if r.is_unbound() {
350
                    // The first push binds the repository to the pusher's id (spec §16.1).
3513×
                    match claimed {
3523×
                        Some(id) => r.bind_id(id)?,
353
                        None => {
3540×
                            return Err(Failure(
3550×
                                StatusCode::BAD_REQUEST,
3560×
                                format!(
3570×
                                    "this repository is unbound; push with a client that sends {}",
3580×
                                    oxy_core::protocol::REPO_ID_HEADER
3590×
                                ),
3600×
                            ))
361
                        }
362
                    }
36332×
                }
36435×
                let protected = self.backend.default_bookmark(name);
36535×
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
36635×
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
36735×
                });
36835×
                let mut kept_tags = Vec::new();
36935×
                let mut withdrawals_refused = Vec::new();
37035×
                for t in tags {
3713×
                    match t
3723×
                        .is_withdrawal()
3733×
                        .then(|| self.backend.vet_tag_withdrawal(name, &t.name))
374
                    {
3750×
                        Some(Err(reason)) => withdrawals_refused.push((t.name, reason)),
3763×
                        _ => kept_tags.push(t),
377
                    }
378
                }
37935×
                let mut report = r.receive_push_report(bundle, updates, policy, kept_tags)?;
380
                // The request named references, all refused here: it was no
381
                // push of objects alone, whatever the repository saw.
38235×
                if !refused.is_empty() || !withdrawals_refused.is_empty() {
3831×
                    report
3841×
                        .results
3851×
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
38634×
                }
38735×
                for u in refused {
3881×
                    report.results.push(oxy_core::protocol::RefResult {
3891×
                        name: u.name.clone(),
3901×
                        ok: false,
3911×
                        reason: format!(
3921×
                            "{:?} is this repository's default bookmark and cannot be deleted",
3931×
                            u.name
3941×
                        ),
3951×
                    });
3961×
                }
39735×
                for (tag, reason) in withdrawals_refused {
3980×
                    report.results.push(oxy_core::protocol::RefResult {
3990×
                        name: format!("tags/{tag}"),
4000×
                        ok: false,
4010×
                        reason,
4020×
                    });
4030×
                }
40441×
                for r in report.results.iter().filter(|r| !r.ok) {
40510×
                    eprintln!(
40610×
                        "oxy-server: push to {name}: {} refused: {}",
40710×
                        r.name, r.reason
40810×
                    );
40910×
                }
41035×
                self.backend.after_push(name, &report, headers);
41135×
                ok(wire::encode_push_response(&report.results))
412
            }
413
        })
414422×
    }
415
}
416
417
/// The backend of `oxy serve`: one repository per subdirectory of a root,
418
/// open reads, and pushes gated by a list of bearer tokens.
419
pub struct DirBackend {
420
    pub root: PathBuf,
421
    pub tokens: Vec<String>,
422
}
423
424
impl Backend for DirBackend {
425511×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
426511×
        if !valid_repo_name(name) {
4271×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
428510×
        }
429510×
        let dir = self.root.join(name);
430510×
        if !dir.join(".oxy").is_dir() {
4311×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
432509×
        }
433509×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
434511×
    }
435
436146×
    fn default_bookmark(&self, name: &str) -> Option<String> {
437146×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
438146×
    }
439
440369×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
441369×
        if access == Access::Read || self.tokens.is_empty() {
442363×
            return Ok(());
4436×
        }
4446×
        match bearer_token(headers) {
4455×
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
4464×
            _ => Err(Failure(
4474×
                StatusCode::UNAUTHORIZED,
4484×
                "a valid bearer token is required to push".into(),
4494×
            )),
450
        }
451369×
    }
452
}
453
454391×
fn hex_id(h: &str) -> Option<[u8; 16]> {
455391×
    let h = h.trim();
456391×
    if h.len() != 32 {
4570×
        return None;
458391×
    }
459391×
    let mut out = [0u8; 16];
4606256×
    for (i, byte) in out.iter_mut().enumerate() {
4616256×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
462
    }
463391×
    Some(out)
464391×
}
465
466
/// The features a request declares in its `Oxy-Features` header, as the
467
/// header's text; `None` when it sent none (a client of the 0.5.0 era).
468139×
pub fn client_features(headers: &HeaderMap) -> Option<&str> {
469139×
    headers
470139×
        .get(oxy_core::protocol::FEATURES_HEADER)
471139×
        .and_then(|v| v.to_str().ok())
472139×
}
473
474
/// Tailor `refs` of `repo` to the client whose request carried `headers`:
475
/// the shared rule of [`Repo::refs_for_client`], which every host applies.
476139×
pub fn tailor_refs(repo: &Repo, refs: &mut oxy_core::protocol::RefsResponse, headers: &HeaderMap) {
477139×
    repo.refs_for_client(refs, client_features(headers));
478139×
}
479
480
/// The token of an `Authorization: Bearer` header, if any.
48119×
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
48219×
    headers
48319×
        .get(header::AUTHORIZATION)
48419×
        .and_then(|v| v.to_str().ok())
48519×
        .and_then(|v| v.strip_prefix("Bearer "))
48619×
        .map(str::trim)
48719×
}
488
489363×
async fn dispatch(
490363×
    State(server): State<Arc<Server>>,
491363×
    Path((repo, endpoint)): Path<(String, String)>,
492363×
    method: Method,
493363×
    headers: HeaderMap,
494363×
    body: Bytes,
495363×
) -> Response {
496363×
    match Endpoint::parse(&endpoint) {
497363×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
4980×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
499
    }
500363×
}
501
502
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
50312×
pub fn router(cfg: ServerConfig) -> Router {
50412×
    let server = Server::new(DirBackend {
50512×
        root: cfg.root,
50612×
        tokens: cfg.tokens,
50712×
    });
50812×
    Router::new()
50912×
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
51012×
        .with_state(server)
51112×
}
512
513
/// Serve on an already-bound listener until the process ends; HTTPS when
514
/// `cfg.tls` is set.
51512×
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
51612×
    listener.set_nonblocking(true)?;
51712×
    match cfg.tls.clone() {
5181×
        Some(tls) => {
5191×
            let _ = rustls::crypto::ring::default_provider().install_default();
5201×
            let rustls_cfg =
5211×
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
5221×
                    .await
5231×
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
5241×
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
5251×
                .serve(router(cfg).into_make_service())
5261×
                .await
527
        }
528
        None => {
52911×
            let listener = tokio::net::TcpListener::from_std(listener)?;
53011×
            axum::serve(listener, router(cfg)).await
531
        }
532
    }
5330×
}
534
535
/// Build a runtime and serve; for the CLI and for tests on a background thread.
53612×
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
53712×
    let rt = tokio::runtime::Builder::new_multi_thread()
53812×
        .enable_all()
53912×
        .build()?;
54012×
    rt.block_on(serve(listener, cfg))
54112×
}