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