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