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