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