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