OXYGENHUB
# 2f0b4b0651ea oxygen / crates / oxy-server / src / lib.rs
21.4 KiB · Rust · last changed oxy-server: a host can add a note to a reference a push moved (closes #148) 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
    /// Notes for the pusher on references this push moved: each
68
    /// `(reference, note)` is added to that accepted reference's result,
69
    /// which a client shows beside it (`Pushed origin/x - note`). For a
70
    /// push that did what the pusher may not expect, say moving the
71
    /// bookmark of a proposal that has landed (oxygenhub#329, #148). Called
72
    /// before [`Backend::after_push`], which sees the notes.
73
    fn push_notes(
74
        &self,
75
        _name: &str,
76
        _report: &oxy_core::repo::PushReport,
77
        _headers: &HeaderMap,
78
    ) -> Vec<(String, String)> {
79
        Vec::new()
80
    }
81
82
    /// Vet a push by what it adds before anything of it is stored or any
83
    /// reference moves (spec §16.1): `bundle` is the push as decoded, its
84
    /// changes with their lines, `updates` the references it would move.
85
    /// A host refuses the whole push by returning a [`Failure`], whose
86
    /// text reaches the client as the push's error, as it is, several
87
    /// lines included; it should answer neither 401, 403 nor 404, which a
88
    /// client takes for a credential it should change. Called for every
89
    /// part of a push sent in parts (each part's changes are its own),
90
    /// outside the repository's push lock, so a slow vet holds up no
91
    /// other push. The default accepts everything at no cost.
92
    fn vet_push(
93
        &self,
94
        _name: &str,
95
        _repo: &Repo,
96
        _bundle: &oxy_core::protocol::Bundle,
97
        _updates: &[oxy_core::protocol::RefUpdate],
98
        _headers: &HeaderMap,
99
    ) -> Result<(), Failure> {
100
        Ok(())
101
    }
102
103
    /// Add the host's transparency log to a refs answer (spec §14.8): its
104
    /// checkpoint, and each attestation's entry and inclusion proof. A host
105
    /// without a log leaves it as it is.
106
    fn add_log(&self, _name: &str, _refs: &mut oxy_core::protocol::RefsResponse) {}
107
108
    /// Tailor a refs answer to the client asking, by its request headers
109
    /// (its `User-Agent` and the features it declares in `Oxy-Features`),
110
    /// after [`Backend::add_log`]. The default leaves out the tags a client
111
    /// that does not declare `certified-tags` would refuse
112
    /// ([`Repo::refs_for_client`], oxygen#131); a host that overrides it
113
    /// should apply that too ([`tailor_refs`]).
114
    fn adjust_refs(
115
        &self,
116
        _name: &str,
117
        repo: &Repo,
118
        refs: &mut oxy_core::protocol::RefsResponse,
119
        headers: &HeaderMap,
120
    ) {
121
        tailor_refs(repo, refs, headers);
122
    }
123
124
    /// Whether tag `tag` of `name` may be withdrawn (oxygenhub#301): called
125
    /// for each withdrawal a push carries, before the repository sees it.
126
    /// A host refuses one it depends on (a forge's release names the tag)
127
    /// with the reason, which is that withdrawal's result. The default
128
    /// allows every one; the policy is checked after, as for any push.
129
    fn vet_tag_withdrawal(&self, _name: &str, _tag: &str) -> Result<(), String> {
130
        Ok(())
131
    }
132
133
    /// The bookmark of `name` that pushes may never delete (its default),
134
    /// when the host keeps one apart from the repository's own config.
135
    fn default_bookmark(&self, _name: &str) -> Option<String> {
136
        None
137
    }
138
}
139
140
/// A protocol server over any [`Backend`], serialising the pushes to each
141
/// repository. Hosts route requests to [`Server::handle`].
142
pub struct Server {
143
    backend: Box<dyn Backend>,
144
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
145
}
146
147
/// An error response: a status and a plain-text body.
148
#[derive(Debug)]
149
pub struct Failure(pub StatusCode, pub String);
150
151
impl IntoResponse for Failure {
152
    fn into_response(self) -> Response {
153
        (self.0, self.1).into_response()
154
    }
155
}
156
157
impl From<oxy_core::repo::RepoError> for Failure {
158
    fn from(e: oxy_core::repo::RepoError) -> Failure {
159
        use oxy_core::repo::RepoError;
160
        // The server's own storage failing is not the client's fault.
161
        let status = match &e {
162
            RepoError::Io(_) | RepoError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
163
            _ => StatusCode::BAD_REQUEST,
164
        };
165
        Failure(status, e.to_string())
166
    }
167
}
168
169
/// The wire protocol's endpoints (spec §16.1), named as in the URL.
170
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171
pub enum Endpoint {
172
    Capabilities,
173
    Refs,
174
    Negotiate,
175
    Fetch,
176
    Objects,
177
    Checkpoint,
178
    CheckpointIndex,
179
    Shallow,
180
    Push,
181
}
182
183
impl Endpoint {
184
    pub fn parse(name: &str) -> Option<Endpoint> {
185
        Some(match name {
186
            "capabilities" => Endpoint::Capabilities,
187
            "refs" => Endpoint::Refs,
188
            "negotiate" => Endpoint::Negotiate,
189
            "fetch" => Endpoint::Fetch,
190
            "objects" => Endpoint::Objects,
191
            "checkpoint" => Endpoint::Checkpoint,
192
            "checkpoint-index" => Endpoint::CheckpointIndex,
193
            "shallow" => Endpoint::Shallow,
194
            "push" => Endpoint::Push,
195
            _ => return None,
196
        })
197
    }
198
199
    pub fn name(self) -> &'static str {
200
        match self {
201
            Endpoint::Capabilities => "capabilities",
202
            Endpoint::Refs => "refs",
203
            Endpoint::Negotiate => "negotiate",
204
            Endpoint::Fetch => "fetch",
205
            Endpoint::Objects => "objects",
206
            Endpoint::Checkpoint => "checkpoint",
207
            Endpoint::CheckpointIndex => "checkpoint-index",
208
            Endpoint::Shallow => "shallow",
209
            Endpoint::Push => "push",
210
        }
211
    }
212
213
    /// The HTTP method the endpoint answers to.
214
    pub fn method(self) -> Method {
215
        match self {
216
            Endpoint::Capabilities | Endpoint::Refs => Method::GET,
217
            _ => Method::POST,
218
        }
219
    }
220
221
    fn access(self) -> Access {
222
        match self {
223
            Endpoint::Push => Access::Push,
224
            _ => Access::Read,
225
        }
226
    }
227
}
228
229
fn ok(body: Vec<u8>) -> Response {
230
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
231
}
232
233
pub fn valid_repo_name(name: &str) -> bool {
234
    !name.is_empty()
235
        && !name.starts_with('.')
236
        && name
237
            .chars()
238
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
239
}
240
241
impl Server {
242
    pub fn new(backend: impl Backend) -> Arc<Server> {
243
        Arc::new(Server {
244
            backend: Box::new(backend),
245
            locks: Mutex::new(HashMap::new()),
246
        })
247
    }
248
249
    pub fn backend(&self) -> &dyn Backend {
250
        self.backend.as_ref()
251
    }
252
253
    fn lock_for(&self, name: &str) -> Arc<Mutex<()>> {
254
        self.locks
255
            .lock()
256
            .unwrap()
257
            .entry(name.to_string())
258
            .or_default()
259
            .clone()
260
    }
261
262
    /// Answer one protocol request for repository `name`. `method` is
263
    /// checked against the endpoint; the body is the raw CBOR request.
264
    pub async fn handle(
265
        self: &Arc<Self>,
266
        name: String,
267
        endpoint: Endpoint,
268
        method: &Method,
269
        headers: &HeaderMap,
270
        body: Bytes,
271
    ) -> Response {
272
        if *method != endpoint.method() {
273
            return Failure(
274
                StatusCode::METHOD_NOT_ALLOWED,
275
                format!("{} is {}", endpoint.name(), endpoint.method()),
276
            )
277
            .into_response();
278
        }
279
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
280
            return f.into_response();
281
        }
282
        let claimed = headers
283
            .get(oxy_core::protocol::REPO_ID_HEADER)
284
            .and_then(|v| v.to_str().ok())
285
            .and_then(hex_id);
286
        let server = Arc::clone(self);
287
        let request_headers = headers.clone();
288
        let repo = name.clone();
289
        let result = tokio::task::spawn_blocking(move || {
290
            server.respond(&repo, endpoint, body, claimed, &request_headers)
291
        })
292
        .await;
293
        let failure = match result {
294
            Ok(Ok(r)) => return r,
295
            Ok(Err(f)) => f,
296
            Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
297
        };
298
        // Name the operation and repository, in the log and for the client.
299
        let f = Failure(
300
            failure.0,
301
            format!("{} of {name}: {}", endpoint.name(), failure.1),
302
        );
303
        eprintln!("oxy-server: {}: {}", f.0.as_u16(), f.1);
304
        f.into_response()
305
    }
306
307
    fn respond(
308
        &self,
309
        name: &str,
310
        endpoint: Endpoint,
311
        body: Bytes,
312
        claimed: Option<[u8; 16]>,
313
        headers: &HeaderMap,
314
    ) -> Result<Response, Failure> {
315
        let r = self.backend.open(name)?;
316
        Ok(match endpoint {
317
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
318
            Endpoint::Refs => {
319
                let mut refs = r.remote_refs()?;
320
                if let Some(d) = self.backend.default_bookmark(name) {
321
                    refs.default_bookmark = Some(d);
322
                }
323
                self.backend.add_log(name, &mut refs);
324
                self.backend.adjust_refs(name, &r, &mut refs, headers);
325
                ok(wire::encode_refs(r.id()?, &refs))
326
            }
327
            Endpoint::Negotiate => {
328
                let (have, want) = wire::decode_negotiate(&body)?;
329
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
330
            }
331
            Endpoint::Fetch => {
332
                let (changes, max_blob) = wire::decode_fetch(&body)?;
333
                ok(wire::encode_bundle(
334
                    &r.bundle_for_filtered(&changes, max_blob)?,
335
                ))
336
            }
337
            Endpoint::Objects => {
338
                let refs = wire::decode_hashes(&body)?;
339
                let bundle = oxy_core::protocol::Bundle {
340
                    objects: r.objects_for(&refs)?,
341
                    ..Default::default()
342
                };
343
                ok(wire::encode_bundle(&bundle))
344
            }
345
            Endpoint::Checkpoint => {
346
                let heads = wire::decode_hashes(&body)?;
347
                let lock = self.lock_for(name);
348
                let _guard = lock.lock().unwrap();
349
                let bundle = r.checkpoint_bundle_for(&heads)?;
350
                let _t = oxy_core::timing::phase("serve: encode the checkpoint");
351
                ok(wire::encode_bundle(&bundle))
352
            }
353
            Endpoint::CheckpointIndex => {
354
                let heads = wire::decode_hashes(&body)?;
355
                let lock = self.lock_for(name);
356
                let _guard = lock.lock().unwrap();
357
                ok(wire::encode_bundle(&r.checkpoint_index_for(&heads)?))
358
            }
359
            Endpoint::Shallow => {
360
                let (heads, depth) = wire::decode_shallow(&body)?;
361
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
362
            }
363
            Endpoint::Push => {
364
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
365
                // The host vets what the push adds before anything is stored
366
                // or bound: a refused push leaves the repository as it was.
367
                self.backend
368
                    .vet_push(name, &r, &bundle, &updates, headers)?;
369
                let lock = self.lock_for(name);
370
                let _guard = lock.lock().unwrap();
371
                if r.is_unbound() {
372
                    // The first push binds the repository to the pusher's id (spec §16.1).
373
                    match claimed {
374
                        Some(id) => r.bind_id(id)?,
375
                        None => {
376
                            return Err(Failure(
377
                                StatusCode::BAD_REQUEST,
378
                                format!(
379
                                    "this repository is unbound; push with a client that sends {}",
380
                                    oxy_core::protocol::REPO_ID_HEADER
381
                                ),
382
                            ))
383
                        }
384
                    }
385
                }
386
                let protected = self.backend.default_bookmark(name);
387
                let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| {
388
                    u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str())
389
                });
390
                let mut kept_tags = Vec::new();
391
                let mut withdrawals_refused = Vec::new();
392
                for t in tags {
393
                    match t
394
                        .is_withdrawal()
395
                        .then(|| self.backend.vet_tag_withdrawal(name, &t.name))
396
                    {
397
                        Some(Err(reason)) => withdrawals_refused.push((t.name, reason)),
398
                        _ => kept_tags.push(t),
399
                    }
400
                }
401
                let mut report = r.receive_push_report(bundle, updates, policy, kept_tags)?;
402
                // The request named references, all refused here: it was no
403
                // push of objects alone, whatever the repository saw.
404
                if !refused.is_empty() || !withdrawals_refused.is_empty() {
405
                    report
406
                        .results
407
                        .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT);
408
                }
409
                for u in refused {
410
                    report.results.push(oxy_core::protocol::RefResult {
411
                        name: u.name.clone(),
412
                        ok: false,
413
                        reason: format!(
414
                            "{:?} is this repository's default bookmark and cannot be deleted",
415
                            u.name
416
                        ),
417
                    });
418
                }
419
                for (tag, reason) in withdrawals_refused {
420
                    report.results.push(oxy_core::protocol::RefResult {
421
                        name: format!("tags/{tag}"),
422
                        ok: false,
423
                        reason,
424
                    });
425
                }
426
                for r in report.results.iter().filter(|r| !r.ok) {
427
                    eprintln!(
428
                        "oxy-server: push to {name}: {} refused: {}",
429
                        r.name, r.reason
430
                    );
431
                }
432
                for (reference, note) in self.backend.push_notes(name, &report, headers) {
433
                    if let Some(r) = report
434
                        .results
435
                        .iter_mut()
436
                        .find(|r| r.ok && r.name == reference)
437
                    {
438
                        r.reason = if r.reason.is_empty() {
439
                            note
440
                        } else {
441
                            format!("{}; {note}", r.reason)
442
                        };
443
                    }
444
                }
445
                self.backend.after_push(name, &report, headers);
446
                ok(wire::encode_push_response(&report.results))
447
            }
448
        })
449
    }
450
}
451
452
/// The backend of `oxy serve`: one repository per subdirectory of a root,
453
/// open reads, and pushes gated by a list of bearer tokens.
454
pub struct DirBackend {
455
    pub root: PathBuf,
456
    pub tokens: Vec<String>,
457
}
458
459
impl Backend for DirBackend {
460
    fn open(&self, name: &str) -> Result<Repo, Failure> {
461
        if !valid_repo_name(name) {
462
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
463
        }
464
        let dir = self.root.join(name);
465
        if !dir.join(".oxy").is_dir() {
466
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
467
        }
468
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
469
    }
470
471
    fn default_bookmark(&self, name: &str) -> Option<String> {
472
        self.open(name).ok().map(|r| r.config.bookmark.clone())
473
    }
474
475
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
476
        if access == Access::Read || self.tokens.is_empty() {
477
            return Ok(());
478
        }
479
        match bearer_token(headers) {
480
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
481
            _ => Err(Failure(
482
                StatusCode::UNAUTHORIZED,
483
                "a valid bearer token is required to push".into(),
484
            )),
485
        }
486
    }
487
}
488
489
fn hex_id(h: &str) -> Option<[u8; 16]> {
490
    let h = h.trim();
491
    if h.len() != 32 {
492
        return None;
493
    }
494
    let mut out = [0u8; 16];
495
    for (i, byte) in out.iter_mut().enumerate() {
496
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
497
    }
498
    Some(out)
499
}
500
501
/// The features a request declares in its `Oxy-Features` header, as the
502
/// header's text; `None` when it sent none (a client of the 0.5.0 era).
503
pub fn client_features(headers: &HeaderMap) -> Option<&str> {
504
    headers
505
        .get(oxy_core::protocol::FEATURES_HEADER)
506
        .and_then(|v| v.to_str().ok())
507
}
508
509
/// Tailor `refs` of `repo` to the client whose request carried `headers`:
510
/// the shared rule of [`Repo::refs_for_client`], which every host applies.
511
pub fn tailor_refs(repo: &Repo, refs: &mut oxy_core::protocol::RefsResponse, headers: &HeaderMap) {
512
    repo.refs_for_client(refs, client_features(headers));
513
}
514
515
/// The token of an `Authorization: Bearer` header, if any.
516
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
517
    headers
518
        .get(header::AUTHORIZATION)
519
        .and_then(|v| v.to_str().ok())
520
        .and_then(|v| v.strip_prefix("Bearer "))
521
        .map(str::trim)
522
}
523
524
async fn dispatch(
525
    State(server): State<Arc<Server>>,
526
    Path((repo, endpoint)): Path<(String, String)>,
527
    method: Method,
528
    headers: HeaderMap,
529
    body: Bytes,
530
) -> Response {
531
    match Endpoint::parse(&endpoint) {
532
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
533
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
534
    }
535
}
536
537
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
538
pub fn router(cfg: ServerConfig) -> Router {
539
    let server = Server::new(DirBackend {
540
        root: cfg.root,
541
        tokens: cfg.tokens,
542
    });
543
    Router::new()
544
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
545
        .with_state(server)
546
}
547
548
/// Serve on an already-bound listener until the process ends; HTTPS when
549
/// `cfg.tls` is set.
550
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
551
    listener.set_nonblocking(true)?;
552
    match cfg.tls.clone() {
553
        Some(tls) => {
554
            let _ = rustls::crypto::ring::default_provider().install_default();
555
            let rustls_cfg =
556
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
557
                    .await
558
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
559
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
560
                .serve(router(cfg).into_make_service())
561
                .await
562
        }
563
        None => {
564
            let listener = tokio::net::TcpListener::from_std(listener)?;
565
            axum::serve(listener, router(cfg)).await
566
        }
567
    }
568
}
569
570
/// Build a runtime and serve; for the CLI and for tests on a background thread.
571
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
572
    let rt = tokio::runtime::Builder::new_multi_thread()
573
        .enable_all()
574
        .build()?;
575
    rt.block_on(serve(listener, cfg))
576
}