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