OXYGENHUB

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

287 of 340 lines run, 56 of 113 functions · run #385 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.
93148×
    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`]).
101148×
    fn adjust_refs(
102148×
        &self,
103148×
        _name: &str,
104148×
        repo: &Repo,
105148×
        refs: &mut oxy_core::protocol::RefsResponse,
106148×
        headers: &HeaderMap,
107148×
    ) {
108148×
        tailor_refs(repo, refs, headers);
109148×
    }
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 {
170454×
    pub fn parse(name: &str) -> Option<Endpoint> {
171454×
        Some(match name {
172454×
            "capabilities" => Endpoint::Capabilities,
173304×
            "refs" => Endpoint::Refs,
174156×
            "negotiate" => Endpoint::Negotiate,
17599×
            "fetch" => Endpoint::Fetch,
17642×
            "objects" => Endpoint::Objects,
17741×
            "checkpoint" => Endpoint::Checkpoint,
17841×
            "shallow" => Endpoint::Shallow,
17941×
            "push" => Endpoint::Push,
1800×
            _ => return None,
181
        })
182454×
    }
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.
198454×
    pub fn method(self) -> Method {
199454×
        match self {
200298×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
201156×
            _ => Method::POST,
202
        }
203454×
    }
204
205454×
    fn access(self) -> Access {
206454×
        match self {
20741×
            Endpoint::Push => Access::Push,
208413×
            _ => Access::Read,
209
        }
210454×
    }
211
}
212
213445×
fn ok(body: Vec<u8>) -> Response {
214445×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
215445×
}
216
217546×
pub fn valid_repo_name(name: &str) -> bool {
218546×
    !name.is_empty()
219546×
        && !name.starts_with('.')
220545×
        && name
221545×
            .chars()
2223009×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
223546×
}
224
225
impl Server {
22616×
    pub fn new(backend: impl Backend) -> Arc<Server> {
22716×
        Arc::new(Server {
22816×
            backend: Box::new(backend),
22916×
            locks: Mutex::new(HashMap::new()),
23016×
        })
23116×
    }
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.
248454×
    pub async fn handle(
249454×
        self: &Arc<Self>,
250454×
        name: String,
251454×
        endpoint: Endpoint,
252454×
        method: &Method,
253454×
        headers: &HeaderMap,
254454×
        body: Bytes,
255454×
    ) -> Response {
256454×
        if *method != endpoint.method() {
2570×
            return Failure(
2580×
                StatusCode::METHOD_NOT_ALLOWED,
2590×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2600×
            )
2610×
            .into_response();
262454×
        }
263454×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2646×
            return f.into_response();
265448×
        }
266448×
        let claimed = headers
267448×
            .get(oxy_core::protocol::REPO_ID_HEADER)
268448×
            .and_then(|v| v.to_str().ok())
269448×
            .and_then(hex_id);
270448×
        let server = Arc::clone(self);
271448×
        let request_headers = headers.clone();
272448×
        let repo = name.clone();
273448×
        let result = tokio::task::spawn_blocking(move || {
274448×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
275448×
        })
276448×
        .await;
277448×
        let failure = match result {
278445×
            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()
289454×
    }
290
291448×
    fn respond(
292448×
        &self,
293448×
        name: &str,
294448×
        endpoint: Endpoint,
295448×
        body: Bytes,
296448×
        claimed: Option<[u8; 16]>,
297448×
        headers: &HeaderMap,
298448×
    ) -> Result<Response, Failure> {
299448×
        let r = self.backend.open(name)?;
300446×
        Ok(match endpoint {
301147×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
302
            Endpoint::Refs => {
303148×
                let mut refs = r.remote_refs()?;
304148×
                if let Some(d) = self.backend.default_bookmark(name) {
305126×
                    refs.default_bookmark = Some(d);
306126×
                }
307148×
                self.backend.add_log(name, &mut refs);
308148×
                self.backend.adjust_refs(name, &r, &mut refs, headers);
309148×
                ok(wire::encode_refs(r.id()?, &refs))
310
            }
311
            Endpoint::Negotiate => {
31257×
                let (have, want) = wire::decode_negotiate(&body)?;
31357×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
314
            }
315
            Endpoint::Fetch => {
31657×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
31757×
                ok(wire::encode_bundle(
31857×
                    &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) {
4059×
                    eprintln!(
4069×
                        "oxy-server: push to {name}: {} refused: {}",
4079×
                        r.name, r.reason
4089×
                    );
4099×
                }
41035×
                self.backend.after_push(name, &report, headers);
41135×
                ok(wire::encode_push_response(&report.results))
412
            }
413
        })
414448×
    }
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 {
425546×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
426546×
        if !valid_repo_name(name) {
4271×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
428545×
        }
429545×
        let dir = self.root.join(name);
430545×
        if !dir.join(".oxy").is_dir() {
4311×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
432544×
        }
433544×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
434546×
    }
435
436155×
    fn default_bookmark(&self, name: &str) -> Option<String> {
437155×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
438155×
    }
439
440395×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
441395×
        if access == Access::Read || self.tokens.is_empty() {
442389×
            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
        }
451395×
    }
452
}
453
454415×
fn hex_id(h: &str) -> Option<[u8; 16]> {
455415×
    let h = h.trim();
456415×
    if h.len() != 32 {
4570×
        return None;
458415×
    }
459415×
    let mut out = [0u8; 16];
4606640×
    for (i, byte) in out.iter_mut().enumerate() {
4616640×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
462
    }
463415×
    Some(out)
464415×
}
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).
468148×
pub fn client_features(headers: &HeaderMap) -> Option<&str> {
469148×
    headers
470148×
        .get(oxy_core::protocol::FEATURES_HEADER)
471148×
        .and_then(|v| v.to_str().ok())
472148×
}
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.
476148×
pub fn tailor_refs(repo: &Repo, refs: &mut oxy_core::protocol::RefsResponse, headers: &HeaderMap) {
477148×
    repo.refs_for_client(refs, client_features(headers));
478148×
}
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
489389×
async fn dispatch(
490389×
    State(server): State<Arc<Server>>,
491389×
    Path((repo, endpoint)): Path<(String, String)>,
492389×
    method: Method,
493389×
    headers: HeaderMap,
494389×
    body: Bytes,
495389×
) -> Response {
496389×
    match Endpoint::parse(&endpoint) {
497389×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
4980×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
499
    }
500389×
}
501
502
/// The largest request `oxy serve` takes: a push part is about
503
/// `push.batch-bytes` (64 MiB), but one change can weigh more; OxygenHub's
504
/// default `push_body_limit` is the same.
505
pub const BODY_LIMIT: usize = if usize::BITS > 32 {
506
    4 << 30
507
} else {
508
    usize::MAX
509
};
510
511
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
51213×
pub fn router(cfg: ServerConfig) -> Router {
51313×
    let server = Server::new(DirBackend {
51413×
        root: cfg.root,
51513×
        tokens: cfg.tokens,
51613×
    });
517
    // Without a limit of its own a request takes axum's 2 MB, and a larger
518
    // push was cut off with no word in the log ("Broken pipe" at the client).
51913×
    Router::new()
52013×
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
52113×
        .layer(axum::extract::DefaultBodyLimit::max(BODY_LIMIT))
52213×
        .with_state(server)
52313×
}
524
525
/// Serve on an already-bound listener until the process ends; HTTPS when
526
/// `cfg.tls` is set.
52713×
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
52813×
    listener.set_nonblocking(true)?;
52913×
    match cfg.tls.clone() {
5301×
        Some(tls) => {
5311×
            let _ = rustls::crypto::ring::default_provider().install_default();
5321×
            let rustls_cfg =
5331×
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
5341×
                    .await
5351×
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
5361×
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
5371×
                .serve(router(cfg).into_make_service())
5381×
                .await
539
        }
540
        None => {
54112×
            let listener = tokio::net::TcpListener::from_std(listener)?;
54212×
            axum::serve(listener, router(cfg)).await
543
        }
544
    }
5450×
}
546
547
/// Build a runtime and serve; for the CLI and for tests on a background thread.
54813×
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
54913×
    let rt = tokio::runtime::Builder::new_multi_thread()
55013×
        .enable_all()
55113×
        .build()?;
55213×
    rt.block_on(serve(listener, cfg))
55313×
}