OXYGENHUB

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

288 of 346 lines run, 56 of 113 functions · run #390 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.
6736×
    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.
7936×
    fn vet_push(
8036×
        &self,
8136×
        _name: &str,
8236×
        _repo: &Repo,
8336×
        _bundle: &oxy_core::protocol::Bundle,
8436×
        _updates: &[oxy_core::protocol::RefUpdate],
8536×
        _headers: &HeaderMap,
8636×
    ) -> Result<(), Failure> {
8736×
        Ok(())
8836×
    }
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.
93142×
    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`]).
101142×
    fn adjust_refs(
102142×
        &self,
103142×
        _name: &str,
104142×
        repo: &Repo,
105142×
        refs: &mut oxy_core::protocol::RefsResponse,
106142×
        headers: &HeaderMap,
107142×
    ) {
108142×
        tailor_refs(repo, refs, headers);
109142×
    }
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
    CheckpointIndex,
166
    Shallow,
167
    Push,
168
}
169
170
impl Endpoint {
171438×
    pub fn parse(name: &str) -> Option<Endpoint> {
172438×
        Some(match name {
173438×
            "capabilities" => Endpoint::Capabilities,
174294×
            "refs" => Endpoint::Refs,
175152×
            "negotiate" => Endpoint::Negotiate,
17698×
            "fetch" => Endpoint::Fetch,
17744×
            "objects" => Endpoint::Objects,
17843×
            "checkpoint" => Endpoint::Checkpoint,
17943×
            "checkpoint-index" => Endpoint::CheckpointIndex,
18043×
            "shallow" => Endpoint::Shallow,
18143×
            "push" => Endpoint::Push,
1820×
            _ => return None,
183
        })
184438×
    }
185
1863×
    pub fn name(self) -> &'static str {
1873×
        match self {
1882×
            Endpoint::Capabilities => "capabilities",
1890×
            Endpoint::Refs => "refs",
1900×
            Endpoint::Negotiate => "negotiate",
1910×
            Endpoint::Fetch => "fetch",
1920×
            Endpoint::Objects => "objects",
1930×
            Endpoint::Checkpoint => "checkpoint",
1940×
            Endpoint::CheckpointIndex => "checkpoint-index",
1950×
            Endpoint::Shallow => "shallow",
1961×
            Endpoint::Push => "push",
197
        }
1983×
    }
199
200
    /// The HTTP method the endpoint answers to.
201438×
    pub fn method(self) -> Method {
202438×
        match self {
203286×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
204152×
            _ => Method::POST,
205
        }
206438×
    }
207
208438×
    fn access(self) -> Access {
209438×
        match self {
21043×
            Endpoint::Push => Access::Push,
211395×
            _ => Access::Read,
212
        }
213438×
    }
214
}
215
216429×
fn ok(body: Vec<u8>) -> Response {
217429×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
218429×
}
219
220526×
pub fn valid_repo_name(name: &str) -> bool {
221526×
    !name.is_empty()
222526×
        && !name.starts_with('.')
223525×
        && name
224525×
            .chars()
2252889×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
226526×
}
227
228
impl Server {
22916×
    pub fn new(backend: impl Backend) -> Arc<Server> {
23016×
        Arc::new(Server {
23116×
            backend: Box::new(backend),
23216×
            locks: Mutex::new(HashMap::new()),
23316×
        })
23416×
    }
235
2360×
    pub fn backend(&self) -> &dyn Backend {
2370×
        self.backend.as_ref()
2380×
    }
239
24037×
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
24137×
        self.locks
24237×
            .lock()
24337×
            .unwrap()
24437×
            .entry(name.to_string())
24537×
            .or_default()
24637×
            .clone()
24737×
    }
248
249
    /// Answer one protocol request for repository `name`. `method` is
250
    /// checked against the endpoint; the body is the raw CBOR request.
251438×
    pub async fn handle(
252438×
        self: &Arc<Self>,
253438×
        name: String,
254438×
        endpoint: Endpoint,
255438×
        method: &Method,
256438×
        headers: &HeaderMap,
257438×
        body: Bytes,
258438×
    ) -> Response {
259438×
        if *method != endpoint.method() {
2600×
            return Failure(
2610×
                StatusCode::METHOD_NOT_ALLOWED,
2620×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2630×
            )
2640×
            .into_response();
265438×
        }
266438×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2676×
            return f.into_response();
268432×
        }
269432×
        let claimed = headers
270432×
            .get(oxy_core::protocol::REPO_ID_HEADER)
271432×
            .and_then(|v| v.to_str().ok())
272432×
            .and_then(hex_id);
273432×
        let server = Arc::clone(self);
274432×
        let request_headers = headers.clone();
275432×
        let repo = name.clone();
276432×
        let result = tokio::task::spawn_blocking(move || {
277432×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
278432×
        })
279432×
        .await;
280432×
        let failure = match result {
281429×
            Ok(Ok(r)) => return r,
2823×
            Ok(Err(f)) => f,
2830×
            Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
284
        };
285
        // Name the operation and repository, in the log and for the client.
2863×
        let f = Failure(
2873×
            failure.0,
2883×
            format!("{} of {name}: {}", endpoint.name(), failure.1),
2893×
        );
2903×
        eprintln!("oxy-server: {}: {}", f.0.as_u16(), f.1);
2913×
        f.into_response()
292438×
    }
293
294432×
    fn respond(
295432×
        &self,
296432×
        name: &str,
297432×
        endpoint: Endpoint,
298432×
        body: Bytes,
299432×
        claimed: Option<[u8; 16]>,
300432×
        headers: &HeaderMap,
301432×
    ) -> Result<Response, Failure> {
302432×
        let r = self.backend.open(name)?;
303430×
        Ok(match endpoint {
304141×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
305
            Endpoint::Refs => {
306142×
                let mut refs = r.remote_refs()?;
307142×
                if let Some(d) = self.backend.default_bookmark(name) {
308120×
                    refs.default_bookmark = Some(d);
309120×
                }
310142×
                self.backend.add_log(name, &mut refs);
311142×
                self.backend.adjust_refs(name, &r, &mut refs, headers);
312142×
                ok(wire::encode_refs(r.id()?, &refs))
313
            }
314
            Endpoint::Negotiate => {
31554×
                let (have, want) = wire::decode_negotiate(&body)?;
31654×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
317
            }
318
            Endpoint::Fetch => {
31954×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
32054×
                ok(wire::encode_bundle(
32154×
                    &r.bundle_for_filtered(&changes, max_blob)?,
322
                ))
323
            }
324
            Endpoint::Objects => {
3251×
                let refs = wire::decode_hashes(&body)?;
3261×
                let bundle = oxy_core::protocol::Bundle {
3271×
                    objects: r.objects_for(&refs)?,
3281×
                    ..Default::default()
329
                };
3301×
                ok(wire::encode_bundle(&bundle))
331
            }
332
            Endpoint::Checkpoint => {
3330×
                let heads = wire::decode_hashes(&body)?;
3340×
                let lock = self.lock_for(name);
3350×
                let _guard = lock.lock().unwrap();
3360×
                let bundle = r.checkpoint_bundle_for(&heads)?;
3370×
                let _t = oxy_core::timing::phase("serve: encode the checkpoint");
3380×
                ok(wire::encode_bundle(&bundle))
339
            }
340
            Endpoint::CheckpointIndex => {
3410×
                let heads = wire::decode_hashes(&body)?;
3420×
                let lock = self.lock_for(name);
3430×
                let _guard = lock.lock().unwrap();
3440×
                ok(wire::encode_bundle(&r.checkpoint_index_for(&heads)?))
345
            }
346
            Endpoint::Shallow => {
3470×
                let (heads, depth) = wire::decode_shallow(&body)?;
3480×
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
349
            }
350
            Endpoint::Push => {
35138×
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
352
                // The host vets what the push adds before anything is stored
353
                // or bound: a refused push leaves the repository as it was.
35438×
                self.backend
35538×
                    .vet_push(name, &r, &bundle, &updates, headers)?;
35637×
                let lock = self.lock_for(name);
35737×
                let _guard = lock.lock().unwrap();
35837×
                if r.is_unbound() {
359
                    // The first push binds the repository to the pusher's id (spec §16.1).
3603×
                    match claimed {
3613×
                        Some(id) => r.bind_id(id)?,
362
                        None => {
3630×
                            return Err(Failure(
3640×
                                StatusCode::BAD_REQUEST,
3650×
                                format!(
3660×
                                    "this repository is unbound; push with a client that sends {}",
3670×
                                    oxy_core::protocol::REPO_ID_HEADER
3680×
                                ),
3690×
                            ))
370
                        }
371
                    }
37234×
                }
37337×
                let protected = self.backend.default_bookmark(name);
37437×
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
37537×
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
37637×
                });
37737×
                let mut kept_tags = Vec::new();
37837×
                let mut withdrawals_refused = Vec::new();
37937×
                for t in tags {
3803×
                    match t
3813×
                        .is_withdrawal()
3823×
                        .then(|| self.backend.vet_tag_withdrawal(name, &t.name))
383
                    {
3840×
                        Some(Err(reason)) => withdrawals_refused.push((t.name, reason)),
3853×
                        _ => kept_tags.push(t),
386
                    }
387
                }
38837×
                let mut report = r.receive_push_report(bundle, updates, policy, kept_tags)?;
389
                // The request named references, all refused here: it was no
390
                // push of objects alone, whatever the repository saw.
39137×
                if !refused.is_empty() || !withdrawals_refused.is_empty() {
3921×
                    report
3931×
                        .results
3941×
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
39536×
                }
39637×
                for u in refused {
3971×
                    report.results.push(oxy_core::protocol::RefResult {
3981×
                        name: u.name.clone(),
3991×
                        ok: false,
4001×
                        reason: format!(
4011×
                            "{:?} is this repository's default bookmark and cannot be deleted",
4021×
                            u.name
4031×
                        ),
4041×
                    });
4051×
                }
40637×
                for (tag, reason) in withdrawals_refused {
4070×
                    report.results.push(oxy_core::protocol::RefResult {
4080×
                        name: format!("tags/{tag}"),
4090×
                        ok: false,
4100×
                        reason,
4110×
                    });
4120×
                }
41343×
                for r in report.results.iter().filter(|r| !r.ok) {
41411×
                    eprintln!(
41511×
                        "oxy-server: push to {name}: {} refused: {}",
41611×
                        r.name, r.reason
41711×
                    );
41811×
                }
41937×
                self.backend.after_push(name, &report, headers);
42037×
                ok(wire::encode_push_response(&report.results))
421
            }
422
        })
423432×
    }
424
}
425
426
/// The backend of `oxy serve`: one repository per subdirectory of a root,
427
/// open reads, and pushes gated by a list of bearer tokens.
428
pub struct DirBackend {
429
    pub root: PathBuf,
430
    pub tokens: Vec<String>,
431
}
432
433
impl Backend for DirBackend {
434526×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
435526×
        if !valid_repo_name(name) {
4361×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
437525×
        }
438525×
        let dir = self.root.join(name);
439525×
        if !dir.join(".oxy").is_dir() {
4401×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
441524×
        }
442524×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
443526×
    }
444
445151×
    fn default_bookmark(&self, name: &str) -> Option<String> {
446151×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
447151×
    }
448
449379×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
450379×
        if access == Access::Read || self.tokens.is_empty() {
451373×
            return Ok(());
4526×
        }
4536×
        match bearer_token(headers) {
4545×
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
4554×
            _ => Err(Failure(
4564×
                StatusCode::UNAUTHORIZED,
4574×
                "a valid bearer token is required to push".into(),
4584×
            )),
459
        }
460379×
    }
461
}
462
463399×
fn hex_id(h: &str) -> Option<[u8; 16]> {
464399×
    let h = h.trim();
465399×
    if h.len() != 32 {
4660×
        return None;
467399×
    }
468399×
    let mut out = [0u8; 16];
4696384×
    for (i, byte) in out.iter_mut().enumerate() {
4706384×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
471
    }
472399×
    Some(out)
473399×
}
474
475
/// The features a request declares in its `Oxy-Features` header, as the
476
/// header's text; `None` when it sent none (a client of the 0.5.0 era).
477142×
pub fn client_features(headers: &HeaderMap) -> Option<&str> {
478142×
    headers
479142×
        .get(oxy_core::protocol::FEATURES_HEADER)
480142×
        .and_then(|v| v.to_str().ok())
481142×
}
482
483
/// Tailor `refs` of `repo` to the client whose request carried `headers`:
484
/// the shared rule of [`Repo::refs_for_client`], which every host applies.
485142×
pub fn tailor_refs(repo: &Repo, refs: &mut oxy_core::protocol::RefsResponse, headers: &HeaderMap) {
486142×
    repo.refs_for_client(refs, client_features(headers));
487142×
}
488
489
/// The token of an `Authorization: Bearer` header, if any.
49019×
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
49119×
    headers
49219×
        .get(header::AUTHORIZATION)
49319×
        .and_then(|v| v.to_str().ok())
49419×
        .and_then(|v| v.strip_prefix("Bearer "))
49519×
        .map(str::trim)
49619×
}
497
498373×
async fn dispatch(
499373×
    State(server): State<Arc<Server>>,
500373×
    Path((repo, endpoint)): Path<(String, String)>,
501373×
    method: Method,
502373×
    headers: HeaderMap,
503373×
    body: Bytes,
504373×
) -> Response {
505373×
    match Endpoint::parse(&endpoint) {
506373×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
5070×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
508
    }
509373×
}
510
511
/// The largest request `oxy serve` takes: a push part is about
512
/// `push.batch-bytes` (64 MiB), but one change can weigh more; OxygenHub's
513
/// default `push_body_limit` is the same.
514
pub const BODY_LIMIT: usize = if usize::BITS > 32 {
515
    4 << 30
516
} else {
517
    usize::MAX
518
};
519
520
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
52113×
pub fn router(cfg: ServerConfig) -> Router {
52213×
    let server = Server::new(DirBackend {
52313×
        root: cfg.root,
52413×
        tokens: cfg.tokens,
52513×
    });
526
    // Without a limit of its own a request takes axum's 2 MB, and a larger
527
    // push was cut off with no word in the log ("Broken pipe" at the client).
52813×
    Router::new()
52913×
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
53013×
        .layer(axum::extract::DefaultBodyLimit::max(BODY_LIMIT))
53113×
        .with_state(server)
53213×
}
533
534
/// Serve on an already-bound listener until the process ends; HTTPS when
535
/// `cfg.tls` is set.
53613×
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
53713×
    listener.set_nonblocking(true)?;
53813×
    match cfg.tls.clone() {
5391×
        Some(tls) => {
5401×
            let _ = rustls::crypto::ring::default_provider().install_default();
5411×
            let rustls_cfg =
5421×
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
5431×
                    .await
5441×
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
5451×
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
5461×
                .serve(router(cfg).into_make_service())
5471×
                .await
548
        }
549
        None => {
55012×
            let listener = tokio::net::TcpListener::from_std(listener)?;
55112×
            axum::serve(listener, router(cfg)).await
552
        }
553
    }
5540×
}
555
556
/// Build a runtime and serve; for the CLI and for tests on a background thread.
55713×
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
55813×
    let rt = tokio::runtime::Builder::new_multi_thread()
55913×
        .enable_all()
56013×
        .build()?;
56113×
    rt.block_on(serve(listener, cfg))
56213×
}