OXYGENHUB

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

286 of 337 lines run, 56 of 113 functions · run #370 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.
6732×
    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.
7932×
    fn vet_push(
8032×
        &self,
8132×
        _name: &str,
8232×
        _repo: &Repo,
8332×
        _bundle: &oxy_core::protocol::Bundle,
8432×
        _updates: &[oxy_core::protocol::RefUpdate],
8532×
        _headers: &HeaderMap,
8632×
    ) -> Result<(), Failure> {
8732×
        Ok(())
8832×
    }
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.
93143×
    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`]).
101143×
    fn adjust_refs(
102143×
        &self,
103143×
        _name: &str,
104143×
        repo: &Repo,
105143×
        refs: &mut oxy_core::protocol::RefsResponse,
106143×
        headers: &HeaderMap,
107143×
    ) {
108143×
        tailor_refs(repo, refs, headers);
109143×
    }
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 {
170438×
    pub fn parse(name: &str) -> Option<Endpoint> {
171438×
        Some(match name {
172438×
            "capabilities" => Endpoint::Capabilities,
173293×
            "refs" => Endpoint::Refs,
174150×
            "negotiate" => Endpoint::Negotiate,
17595×
            "fetch" => Endpoint::Fetch,
17640×
            "objects" => Endpoint::Objects,
17739×
            "checkpoint" => Endpoint::Checkpoint,
17839×
            "shallow" => Endpoint::Shallow,
17939×
            "push" => Endpoint::Push,
1800×
            _ => return None,
181
        })
182438×
    }
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.
198438×
    pub fn method(self) -> Method {
199438×
        match self {
200288×
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
201150×
            _ => Method::POST,
202
        }
203438×
    }
204
205438×
    fn access(self) -> Access {
206438×
        match self {
20739×
            Endpoint::Push => Access::Push,
208399×
            _ => Access::Read,
209
        }
210438×
    }
211
}
212
213429×
fn ok(body: Vec<u8>) -> Response {
214429×
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
215429×
}
216
217523×
pub fn valid_repo_name(name: &str) -> bool {
218523×
    !name.is_empty()
219523×
        && !name.starts_with('.')
220522×
        && name
221522×
            .chars()
2222871×
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
223523×
}
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
23733×
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
23833×
        self.locks
23933×
            .lock()
24033×
            .unwrap()
24133×
            .entry(name.to_string())
24233×
            .or_default()
24333×
            .clone()
24433×
    }
245
246
    /// Answer one protocol request for repository `name`. `method` is
247
    /// checked against the endpoint; the body is the raw CBOR request.
248438×
    pub async fn handle(
249438×
        self: &Arc<Self>,
250438×
        name: String,
251438×
        endpoint: Endpoint,
252438×
        method: &Method,
253438×
        headers: &HeaderMap,
254438×
        body: Bytes,
255438×
    ) -> Response {
256438×
        if *method != endpoint.method() {
2570×
            return Failure(
2580×
                StatusCode::METHOD_NOT_ALLOWED,
2590×
                format!("{} is {}", endpoint.name(), endpoint.method()),
2600×
            )
2610×
            .into_response();
262438×
        }
263438×
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
2646×
            return f.into_response();
265432×
        }
266432×
        let claimed = headers
267432×
            .get(oxy_core::protocol::REPO_ID_HEADER)
268432×
            .and_then(|v| v.to_str().ok())
269432×
            .and_then(hex_id);
270432×
        let server = Arc::clone(self);
271432×
        let request_headers = headers.clone();
272432×
        let repo = name.clone();
273432×
        let result = tokio::task::spawn_blocking(move || {
274432×
            server.respond(&repo, endpoint, body, claimed, &request_headers)
275432×
        })
276432×
        .await;
277432×
        let failure = match result {
278429×
            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()
289438×
    }
290
291432×
    fn respond(
292432×
        &self,
293432×
        name: &str,
294432×
        endpoint: Endpoint,
295432×
        body: Bytes,
296432×
        claimed: Option<[u8; 16]>,
297432×
        headers: &HeaderMap,
298432×
    ) -> Result<Response, Failure> {
299432×
        let r = self.backend.open(name)?;
300430×
        Ok(match endpoint {
301142×
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
302
            Endpoint::Refs => {
303143×
                let mut refs = r.remote_refs()?;
304143×
                if let Some(d) = self.backend.default_bookmark(name) {
305121×
                    refs.default_bookmark = Some(d);
306121×
                }
307143×
                self.backend.add_log(name, &mut refs);
308143×
                self.backend.adjust_refs(name, &r, &mut refs, headers);
309143×
                ok(wire::encode_refs(r.id()?, &refs))
310
            }
311
            Endpoint::Negotiate => {
31255×
                let (have, want) = wire::decode_negotiate(&body)?;
31355×
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
314
            }
315
            Endpoint::Fetch => {
31655×
                let (changes, max_blob) = wire::decode_fetch(&body)?;
31755×
                ok(wire::encode_bundle(
31855×
                    &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×
                ok(wire::encode_bundle(&r.checkpoint_bundle_for(&heads)?))
334
            }
335
            Endpoint::Shallow => {
3360×
                let (heads, depth) = wire::decode_shallow(&body)?;
3370×
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
338
            }
339
            Endpoint::Push => {
34034×
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
341
                // The host vets what the push adds before anything is stored
342
                // or bound: a refused push leaves the repository as it was.
34334×
                self.backend
34434×
                    .vet_push(name, &r, &bundle, &updates, headers)?;
34533×
                let lock = self.lock_for(name);
34633×
                let _guard = lock.lock().unwrap();
34733×
                if r.is_unbound() {
348
                    // The first push binds the repository to the pusher's id (spec §16.1).
3493×
                    match claimed {
3503×
                        Some(id) => r.bind_id(id)?,
351
                        None => {
3520×
                            return Err(Failure(
3530×
                                StatusCode::BAD_REQUEST,
3540×
                                format!(
3550×
                                    "this repository is unbound; push with a client that sends {}",
3560×
                                    oxy_core::protocol::REPO_ID_HEADER
3570×
                                ),
3580×
                            ))
359
                        }
360
                    }
36130×
                }
36233×
                let protected = self.backend.default_bookmark(name);
36333×
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
36433×
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
36533×
                });
36633×
                let mut kept_tags = Vec::new();
36733×
                let mut withdrawals_refused = Vec::new();
36833×
                for t in tags {
3693×
                    match t
3703×
                        .is_withdrawal()
3713×
                        .then(|| self.backend.vet_tag_withdrawal(name, &t.name))
372
                    {
3730×
                        Some(Err(reason)) => withdrawals_refused.push((t.name, reason)),
3743×
                        _ => kept_tags.push(t),
375
                    }
376
                }
37733×
                let mut report = r.receive_push_report(bundle, updates, policy, kept_tags)?;
378
                // The request named references, all refused here: it was no
379
                // push of objects alone, whatever the repository saw.
38033×
                if !refused.is_empty() || !withdrawals_refused.is_empty() {
3811×
                    report
3821×
                        .results
3831×
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
38432×
                }
38533×
                for u in refused {
3861×
                    report.results.push(oxy_core::protocol::RefResult {
3871×
                        name: u.name.clone(),
3881×
                        ok: false,
3891×
                        reason: format!(
3901×
                            "{:?} is this repository's default bookmark and cannot be deleted",
3911×
                            u.name
3921×
                        ),
3931×
                    });
3941×
                }
39533×
                for (tag, reason) in withdrawals_refused {
3960×
                    report.results.push(oxy_core::protocol::RefResult {
3970×
                        name: format!("tags/{tag}"),
3980×
                        ok: false,
3990×
                        reason,
4000×
                    });
4010×
                }
40239×
                for r in report.results.iter().filter(|r| !r.ok) {
4038×
                    eprintln!(
4048×
                        "oxy-server: push to {name}: {} refused: {}",
4058×
                        r.name, r.reason
4068×
                    );
4078×
                }
40833×
                self.backend.after_push(name, &report, headers);
40933×
                ok(wire::encode_push_response(&report.results))
410
            }
411
        })
412432×
    }
413
}
414
415
/// The backend of `oxy serve`: one repository per subdirectory of a root,
416
/// open reads, and pushes gated by a list of bearer tokens.
417
pub struct DirBackend {
418
    pub root: PathBuf,
419
    pub tokens: Vec<String>,
420
}
421
422
impl Backend for DirBackend {
423523×
    fn open(&self, name: &str) -> Result<Repo, Failure> {
424523×
        if !valid_repo_name(name) {
4251×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
426522×
        }
427522×
        let dir = self.root.join(name);
428522×
        if !dir.join(".oxy").is_dir() {
4291×
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
430521×
        }
431521×
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
432523×
    }
433
434148×
    fn default_bookmark(&self, name: &str) -> Option<String> {
435148×
        self.open(name).ok().map(|r| r.config.bookmark.clone())
436148×
    }
437
438379×
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
439379×
        if access == Access::Read || self.tokens.is_empty() {
440373×
            return Ok(());
4416×
        }
4426×
        match bearer_token(headers) {
4435×
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
4444×
            _ => Err(Failure(
4454×
                StatusCode::UNAUTHORIZED,
4464×
                "a valid bearer token is required to push".into(),
4474×
            )),
448
        }
449379×
    }
450
}
451
452401×
fn hex_id(h: &str) -> Option<[u8; 16]> {
453401×
    let h = h.trim();
454401×
    if h.len() != 32 {
4550×
        return None;
456401×
    }
457401×
    let mut out = [0u8; 16];
4586416×
    for (i, byte) in out.iter_mut().enumerate() {
4596416×
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
460
    }
461401×
    Some(out)
462401×
}
463
464
/// The features a request declares in its `Oxy-Features` header, as the
465
/// header's text; `None` when it sent none (a client of the 0.5.0 era).
466143×
pub fn client_features(headers: &HeaderMap) -> Option<&str> {
467143×
    headers
468143×
        .get(oxy_core::protocol::FEATURES_HEADER)
469143×
        .and_then(|v| v.to_str().ok())
470143×
}
471
472
/// Tailor `refs` of `repo` to the client whose request carried `headers`:
473
/// the shared rule of [`Repo::refs_for_client`], which every host applies.
474143×
pub fn tailor_refs(repo: &Repo, refs: &mut oxy_core::protocol::RefsResponse, headers: &HeaderMap) {
475143×
    repo.refs_for_client(refs, client_features(headers));
476143×
}
477
478
/// The token of an `Authorization: Bearer` header, if any.
47919×
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
48019×
    headers
48119×
        .get(header::AUTHORIZATION)
48219×
        .and_then(|v| v.to_str().ok())
48319×
        .and_then(|v| v.strip_prefix("Bearer "))
48419×
        .map(str::trim)
48519×
}
486
487373×
async fn dispatch(
488373×
    State(server): State<Arc<Server>>,
489373×
    Path((repo, endpoint)): Path<(String, String)>,
490373×
    method: Method,
491373×
    headers: HeaderMap,
492373×
    body: Bytes,
493373×
) -> Response {
494373×
    match Endpoint::parse(&endpoint) {
495373×
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
4960×
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
497
    }
498373×
}
499
500
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
50112×
pub fn router(cfg: ServerConfig) -> Router {
50212×
    let server = Server::new(DirBackend {
50312×
        root: cfg.root,
50412×
        tokens: cfg.tokens,
50512×
    });
50612×
    Router::new()
50712×
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
50812×
        .with_state(server)
50912×
}
510
511
/// Serve on an already-bound listener until the process ends; HTTPS when
512
/// `cfg.tls` is set.
51312×
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
51412×
    listener.set_nonblocking(true)?;
51512×
    match cfg.tls.clone() {
5161×
        Some(tls) => {
5171×
            let _ = rustls::crypto::ring::default_provider().install_default();
5181×
            let rustls_cfg =
5191×
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
5201×
                    .await
5211×
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
5221×
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
5231×
                .serve(router(cfg).into_make_service())
5241×
                .await
525
        }
526
        None => {
52711×
            let listener = tokio::net::TcpListener::from_std(listener)?;
52811×
            axum::serve(listener, router(cfg)).await
529
        }
530
    }
5310×
}
532
533
/// Build a runtime and serve; for the CLI and for tests on a background thread.
53412×
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
53512×
    let rt = tokio::runtime::Builder::new_multi_thread()
53612×
        .enable_all()
53712×
        .build()?;
53812×
    rt.block_on(serve(listener, cfg))
53912×
}