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