OXYGENHUB
# b5e98094eb8f oxygen / crates / oxy-server / src / lib.rs
19.0 KiB · Rust · last changed A shallow clone fetches its checkpoint in parts (refs #137) 9 days ago source blame history raw
1
//! Reference HTTP server for the Oxygen wire protocol (spec §15.1, §16).
2
//!
3
//! Serves every repository directory under a root at `/{repo}/oxy/v1/...`,
4
//! over TLS when a certificate and key are given, else plain HTTP for use
5
//! behind a TLS-terminating proxy or on a loopback interface (spec §15.1).
6
//!
7
//! Authentication: when bearer tokens are configured, `push` requires one;
8
//! reads are open. With no tokens configured everything is open (development).
9
//!
10
//! Hosts embed the protocol by implementing [`Backend`] (name resolution
11
//! and authorization) and routing to [`Server::handle`]; `router` is the
12
//! standalone server built on [`DirBackend`].
13
14
use axum::body::Bytes;
15
use axum::extract::{Path, State};
16
use axum::http::{header, HeaderMap, Method, StatusCode};
17
use axum::response::{IntoResponse, Response};
18
use axum::routing::any;
19
use axum::Router;
20
use oxy_core::protocol::{wire, CONTENT_TYPE};
21
use oxy_core::repo::Repo;
22
use std::collections::HashMap;
23
use std::path::PathBuf;
24
use std::sync::{Arc, Mutex};
25
26
#[derive(Clone, Debug)]
27
pub struct ServerConfig {
28
    /// Directory containing one repository per subdirectory.
29
    pub root: PathBuf,
30
    /// Bearer tokens allowed to push; empty means no authentication.
31
    pub tokens: Vec<String>,
32
    /// Serve HTTPS with this certificate chain and private key (PEM files).
33
    pub tls: Option<TlsFiles>,
34
}
35
36
#[derive(Clone, Debug)]
37
pub struct TlsFiles {
38
    pub cert: PathBuf,
39
    pub key: PathBuf,
40
}
41
42
/// Which kind of access a request needs (spec §15.1: reads may be open;
43
/// a push must be authenticated when any credential is configured).
44
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45
pub enum Access {
46
    Read,
47
    Push,
48
}
49
50
/// What a host provides to the protocol server: how a repository name maps
51
/// to a repository on disk and who may do what. `oxy serve` uses
52
/// [`DirBackend`]; a hub supplies its own with accounts and roles.
53
pub trait Backend: Send + Sync + 'static {
54
    /// Open the repository called `name`, or fail with the status to
55
    /// answer. An unknown name is `404`; a name the caller may not see
56
    /// SHOULD also be `404`, so private repositories are not enumerable.
57
    fn open(&self, name: &str) -> Result<Repo, Failure>;
58
59
    /// Decide whether this request may perform `access` on `name`.
60
    fn authorize(&self, name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure>;
61
62
    /// Called after a push was processed, with its per-reference results
63
    /// (accepted or refused), the states each accepted reference moved
64
    /// between, and the changes stored, for logs and cache invalidation.
65
    fn after_push(&self, _name: &str, _report: &oxy_core::repo::PushReport, _headers: &HeaderMap) {}
66
67
    /// Vet a push by what it adds before anything of it is stored or any
68
    /// reference moves (spec §16.1): `bundle` is the push as decoded, its
69
    /// changes with their lines, `updates` the references it would move.
70
    /// A host refuses the whole push by returning a [`Failure`], whose
71
    /// text reaches the client as the push's error, as it is, several
72
    /// lines included; it should answer neither 401, 403 nor 404, which a
73
    /// client takes for a credential it should change. Called for every
74
    /// part of a push sent in parts (each part's changes are its own),
75
    /// outside the repository's push lock, so a slow vet holds up no
76
    /// other push. The default accepts everything at no cost.
77
    fn vet_push(
78
        &self,
79
        _name: &str,
80
        _repo: &Repo,
81
        _bundle: &oxy_core::protocol::Bundle,
82
        _updates: &[oxy_core::protocol::RefUpdate],
83
        _headers: &HeaderMap,
84
    ) -> Result<(), Failure> {
85
        Ok(())
86
    }
87
88
    /// Add the host's transparency log to a refs answer (spec §14.8): its
89
    /// checkpoint, and each attestation's entry and inclusion proof. A host
90
    /// without a log leaves it as it is.
91
    fn add_log(&self, _name: &str, _refs: &mut oxy_core::protocol::RefsResponse) {}
92
93
    /// Tailor a refs answer to the client asking, by its request headers
94
    /// (its `User-Agent` and the features it declares in `Oxy-Features`),
95
    /// after [`Backend::add_log`]. The default leaves out the tags a client
96
    /// that does not declare `certified-tags` would refuse
97
    /// ([`Repo::refs_for_client`], oxygen#131); a host that overrides it
98
    /// should apply that too ([`tailor_refs`]).
99
    fn adjust_refs(
100
        &self,
101
        _name: &str,
102
        repo: &Repo,
103
        refs: &mut oxy_core::protocol::RefsResponse,
104
        headers: &HeaderMap,
105
    ) {
106
        tailor_refs(repo, refs, headers);
107
    }
108
109
    /// The bookmark of `name` that pushes may never delete (its default),
110
    /// when the host keeps one apart from the repository's own config.
111
    fn default_bookmark(&self, _name: &str) -> Option<String> {
112
        None
113
    }
114
}
115
116
/// A protocol server over any [`Backend`], serialising the pushes to each
117
/// repository. Hosts route requests to [`Server::handle`].
118
pub struct Server {
119
    backend: Box<dyn Backend>,
120
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
121
}
122
123
/// An error response: a status and a plain-text body.
124
#[derive(Debug)]
125
pub struct Failure(pub StatusCode, pub String);
126
127
impl IntoResponse for Failure {
128
    fn into_response(self) -> Response {
129
        (self.0, self.1).into_response()
130
    }
131
}
132
133
impl From<oxy_core::repo::RepoError> for Failure {
134
    fn from(e: oxy_core::repo::RepoError) -> Failure {
135
        use oxy_core::repo::RepoError;
136
        // The server's own storage failing is not the client's fault.
137
        let status = match &e {
138
            RepoError::Io(_) | RepoError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
139
            _ => StatusCode::BAD_REQUEST,
140
        };
141
        Failure(status, e.to_string())
142
    }
143
}
144
145
/// The wire protocol's endpoints (spec §16.1), named as in the URL.
146
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147
pub enum Endpoint {
148
    Capabilities,
149
    Refs,
150
    Negotiate,
151
    Fetch,
152
    Objects,
153
    Checkpoint,
154
    CheckpointIndex,
155
    Shallow,
156
    Push,
157
}
158
159
impl Endpoint {
160
    pub fn parse(name: &str) -> Option<Endpoint> {
161
        Some(match name {
162
            "capabilities" => Endpoint::Capabilities,
163
            "refs" => Endpoint::Refs,
164
            "negotiate" => Endpoint::Negotiate,
165
            "fetch" => Endpoint::Fetch,
166
            "objects" => Endpoint::Objects,
167
            "checkpoint" => Endpoint::Checkpoint,
168
            "checkpoint-index" => Endpoint::CheckpointIndex,
169
            "shallow" => Endpoint::Shallow,
170
            "push" => Endpoint::Push,
171
            _ => return None,
172
        })
173
    }
174
175
    pub fn name(self) -> &'static str {
176
        match self {
177
            Endpoint::Capabilities => "capabilities",
178
            Endpoint::Refs => "refs",
179
            Endpoint::Negotiate => "negotiate",
180
            Endpoint::Fetch => "fetch",
181
            Endpoint::Objects => "objects",
182
            Endpoint::Checkpoint => "checkpoint",
183
            Endpoint::CheckpointIndex => "checkpoint-index",
184
            Endpoint::Shallow => "shallow",
185
            Endpoint::Push => "push",
186
        }
187
    }
188
189
    /// The HTTP method the endpoint answers to.
190
    pub fn method(self) -> Method {
191
        match self {
192
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
193
            _ => Method::POST,
194
        }
195
    }
196
197
    fn access(self) -> Access {
198
        match self {
199
            Endpoint::Push => Access::Push,
200
            _ => Access::Read,
201
        }
202
    }
203
}
204
205
fn ok(body: Vec<u8>) -> Response {
206
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
207
}
208
209
pub fn valid_repo_name(name: &str) -> bool {
210
    !name.is_empty()
211
        && !name.starts_with('.')
212
        && name
213
            .chars()
214
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
215
}
216
217
impl Server {
218
    pub fn new(backend: impl Backend) -> Arc<Server> {
219
        Arc::new(Server {
220
            backend: Box::new(backend),
221
            locks: Mutex::new(HashMap::new()),
222
        })
223
    }
224
225
    pub fn backend(&self) -> &dyn Backend {
226
        self.backend.as_ref()
227
    }
228
229
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
230
        self.locks
231
            .lock()
232
            .unwrap()
233
            .entry(name.to_string())
234
            .or_default()
235
            .clone()
236
    }
237
238
    /// Answer one protocol request for repository `name`. `method` is
239
    /// checked against the endpoint; the body is the raw CBOR request.
240
    pub async fn handle(
241
        self: &Arc<Self>,
242
        name: String,
243
        endpoint: Endpoint,
244
        method: &Method,
245
        headers: &HeaderMap,
246
        body: Bytes,
247
    ) -> Response {
248
        if *method != endpoint.method() {
249
            return Failure(
250
                StatusCode::METHOD_NOT_ALLOWED,
251
                format!("{} is {}", endpoint.name(), endpoint.method()),
252
            )
253
            .into_response();
254
        }
255
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
256
            return f.into_response();
257
        }
258
        let claimed = headers
259
            .get(oxy_core::protocol::REPO_ID_HEADER)
260
            .and_then(|v| v.to_str().ok())
261
            .and_then(hex_id);
262
        let server = Arc::clone(self);
263
        let request_headers = headers.clone();
264
        let repo = name.clone();
265
        let result = tokio::task::spawn_blocking(move || {
266
            server.respond(&repo, endpoint, body, claimed, &request_headers)
267
        })
268
        .await;
269
        let failure = match result {
270
            Ok(Ok(r)) => return r,
271
            Ok(Err(f)) => f,
272
            Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
273
        };
274
        // Name the operation and repository, in the log and for the client.
275
        let f = Failure(
276
            failure.0,
277
            format!("{} of {name}: {}", endpoint.name(), failure.1),
278
        );
279
        eprintln!("oxy-server: {}: {}", f.0.as_u16(), f.1);
280
        f.into_response()
281
    }
282
283
    fn respond(
284
        &self,
285
        name: &str,
286
        endpoint: Endpoint,
287
        body: Bytes,
288
        claimed: Option<[u8; 16]>,
289
        headers: &HeaderMap,
290
    ) -> Result<Response, Failure> {
291
        let r = self.backend.open(name)?;
292
        Ok(match endpoint {
293
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
294
            Endpoint::Refs => {
295
                let mut refs = r.remote_refs()?;
296
                if let Some(d) = self.backend.default_bookmark(name) {
297
                    refs.default_bookmark = Some(d);
298
                }
299
                self.backend.add_log(name, &mut refs);
300
                self.backend.adjust_refs(name, &r, &mut refs, headers);
301
                ok(wire::encode_refs(r.id()?, &refs))
302
            }
303
            Endpoint::Negotiate => {
304
                let (have, want) = wire::decode_negotiate(&body)?;
305
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
306
            }
307
            Endpoint::Fetch => {
308
                let (changes, max_blob) = wire::decode_fetch(&body)?;
309
                ok(wire::encode_bundle(
310
                    &r.bundle_for_filtered(&changes, max_blob)?,
311
                ))
312
            }
313
            Endpoint::Objects => {
314
                let refs = wire::decode_hashes(&body)?;
315
                let bundle = oxy_core::protocol::Bundle {
316
                    objects: r.objects_for(&refs)?,
317
                    ..Default::default()
318
                };
319
                ok(wire::encode_bundle(&bundle))
320
            }
321
            Endpoint::Checkpoint => {
322
                let heads = wire::decode_hashes(&body)?;
323
                let lock = self.lock_for(name);
324
                let _guard = lock.lock().unwrap();
325
                let bundle = r.checkpoint_bundle_for(&heads)?;
326
                let _t = oxy_core::timing::phase("serve: encode the checkpoint");
327
                ok(wire::encode_bundle(&bundle))
328
            }
329
            Endpoint::CheckpointIndex => {
330
                let heads = wire::decode_hashes(&body)?;
331
                let lock = self.lock_for(name);
332
                let _guard = lock.lock().unwrap();
333
                ok(wire::encode_bundle(&r.checkpoint_index_for(&heads)?))
334
            }
335
            Endpoint::Shallow => {
336
                let (heads, depth) = wire::decode_shallow(&body)?;
337
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
338
            }
339
            Endpoint::Push => {
340
                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.
343
                self.backend
344
                    .vet_push(name, &r, &bundle, &updates, headers)?;
345
                let lock = self.lock_for(name);
346
                let _guard = lock.lock().unwrap();
347
                if r.is_unbound() {
348
                    // The first push binds the repository to the pusher's id (spec §16.1).
349
                    match claimed {
350
                        Some(id) => r.bind_id(id)?,
351
                        None => {
352
                            return Err(Failure(
353
                                StatusCode::BAD_REQUEST,
354
                                format!(
355
                                    "this repository is unbound; push with a client that sends {}",
356
                                    oxy_core::protocol::REPO_ID_HEADER
357
                                ),
358
                            ))
359
                        }
360
                    }
361
                }
362
                let protected = self.backend.default_bookmark(name);
363
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
364
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
365
                });
366
                let mut report = r.receive_push_report(bundle, updates, policy, tags)?;
367
                // The request named references, all refused here: it was no
368
                // push of objects alone, whatever the repository saw.
369
                if !refused.is_empty() {
370
                    report
371
                        .results
372
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
373
                }
374
                for u in refused {
375
                    report.results.push(oxy_core::protocol::RefResult {
376
                        name: u.name.clone(),
377
                        ok: false,
378
                        reason: format!(
379
                            "{:?} is this repository's default bookmark and cannot be deleted",
380
                            u.name
381
                        ),
382
                    });
383
                }
384
                for r in report.results.iter().filter(|r| !r.ok) {
385
                    eprintln!(
386
                        "oxy-server: push to {name}: {} refused: {}",
387
                        r.name, r.reason
388
                    );
389
                }
390
                self.backend.after_push(name, &report, headers);
391
                ok(wire::encode_push_response(&report.results))
392
            }
393
        })
394
    }
395
}
396
397
/// The backend of `oxy serve`: one repository per subdirectory of a root,
398
/// open reads, and pushes gated by a list of bearer tokens.
399
pub struct DirBackend {
400
    pub root: PathBuf,
401
    pub tokens: Vec<String>,
402
}
403
404
impl Backend for DirBackend {
405
    fn open(&self, name: &str) -> Result<Repo, Failure> {
406
        if !valid_repo_name(name) {
407
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
408
        }
409
        let dir = self.root.join(name);
410
        if !dir.join(".oxy").is_dir() {
411
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
412
        }
413
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
414
    }
415
416
    fn default_bookmark(&self, name: &str) -> Option<String> {
417
        self.open(name).ok().map(|r| r.config.bookmark.clone())
418
    }
419
420
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
421
        if access == Access::Read || self.tokens.is_empty() {
422
            return Ok(());
423
        }
424
        match bearer_token(headers) {
425
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
426
            _ => Err(Failure(
427
                StatusCode::UNAUTHORIZED,
428
                "a valid bearer token is required to push".into(),
429
            )),
430
        }
431
    }
432
}
433
434
fn hex_id(h: &str) -> Option<[u8; 16]> {
435
    let h = h.trim();
436
    if h.len() != 32 {
437
        return None;
438
    }
439
    let mut out = [0u8; 16];
440
    for (i, byte) in out.iter_mut().enumerate() {
441
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
442
    }
443
    Some(out)
444
}
445
446
/// The features a request declares in its `Oxy-Features` header, as the
447
/// header's text; `None` when it sent none (a client of the 0.5.0 era).
448
pub fn client_features(headers: &HeaderMap) -> Option<&str> {
449
    headers
450
        .get(oxy_core::protocol::FEATURES_HEADER)
451
        .and_then(|v| v.to_str().ok())
452
}
453
454
/// Tailor `refs` of `repo` to the client whose request carried `headers`:
455
/// the shared rule of [`Repo::refs_for_client`], which every host applies.
456
pub fn tailor_refs(repo: &Repo, refs: &mut oxy_core::protocol::RefsResponse, headers: &HeaderMap) {
457
    repo.refs_for_client(refs, client_features(headers));
458
}
459
460
/// The token of an `Authorization: Bearer` header, if any.
461
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
462
    headers
463
        .get(header::AUTHORIZATION)
464
        .and_then(|v| v.to_str().ok())
465
        .and_then(|v| v.strip_prefix("Bearer "))
466
        .map(str::trim)
467
}
468
469
async fn dispatch(
470
    State(server): State<Arc<Server>>,
471
    Path((repo, endpoint)): Path<(String, String)>,
472
    method: Method,
473
    headers: HeaderMap,
474
    body: Bytes,
475
) -> Response {
476
    match Endpoint::parse(&endpoint) {
477
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
478
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
479
    }
480
}
481
482
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
483
pub fn router(cfg: ServerConfig) -> Router {
484
    let server = Server::new(DirBackend {
485
        root: cfg.root,
486
        tokens: cfg.tokens,
487
    });
488
    Router::new()
489
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
490
        .with_state(server)
491
}
492
493
/// Serve on an already-bound listener until the process ends; HTTPS when
494
/// `cfg.tls` is set.
495
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
496
    listener.set_nonblocking(true)?;
497
    match cfg.tls.clone() {
498
        Some(tls) => {
499
            let _ = rustls::crypto::ring::default_provider().install_default();
500
            let rustls_cfg =
501
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
502
                    .await
503
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
504
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
505
                .serve(router(cfg).into_make_service())
506
                .await
507
        }
508
        None => {
509
            let listener = tokio::net::TcpListener::from_std(listener)?;
510
            axum::serve(listener, router(cfg)).await
511
        }
512
    }
513
}
514
515
/// Build a runtime and serve; for the CLI and for tests on a background thread.
516
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
517
    let rt = tokio::runtime::Builder::new_multi_thread()
518
        .enable_all()
519
        .build()?;
520
    rt.block_on(serve(listener, cfg))
521
}