OXYGENHUB
# 227dde3b2387 oxygen / crates / oxy-server / src / lib.rs
12.9 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 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), 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>,
71
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
72
}
73
74
/// An error response: a status and a plain-text body.
75
#[derive(Debug)]
76
pub struct Failure(pub StatusCode, pub String);
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
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
147
fn ok(body: Vec<u8>) -> Response {
148
    ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response()
149
}
150
151
pub fn valid_repo_name(name: &str) -> bool {
152
    !name.is_empty()
153
        && !name.starts_with('.')
154
        && name
155
            .chars()
156
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
157
}
158
159
impl Server {
160
    pub fn new(backend: impl Backend) -> Arc<Server> {
161
        Arc::new(Server {
162
            backend: Box::new(backend),
163
            locks: Mutex::new(HashMap::new()),
164
        })
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<()>> {
172
        self.locks
173
            .lock()
174
            .unwrap()
175
            .entry(name.to_string())
176
            .or_default()
177
            .clone()
178
    }
179
180
    /// Answer one protocol request for repository `name`. `method` is
181
    /// checked against the endpoint; the body is the raw CBOR request.
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 {
190
        if *method != endpoint.method() {
191
            return Failure(
192
                StatusCode::METHOD_NOT_ALLOWED,
193
                format!("{} is {}", endpoint.name(), endpoint.method()),
194
            )
195
            .into_response();
196
        }
197
        if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) {
198
            return f.into_response();
199
        }
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);
204
        let server = Arc::clone(self);
205
        let result =
206
            tokio::task::spawn_blocking(move || server.respond(&name, endpoint, body, claimed)).await;
207
        match result {
208
            Ok(Ok(r)) => r,
209
            Ok(Err(f)) => f.into_response(),
210
            Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
211
        }
212
    }
213
214
    fn respond(&self, name: &str, endpoint: Endpoint, body: Bytes, claimed: Option<[u8; 16]>) -> Result<Response, Failure> {
215
        let r = self.backend.open(name)?;
216
        Ok(match endpoint {
217
            Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)),
218
            Endpoint::Refs => ok(wire::encode_refs(r.id()?, &r.remote_refs()?)),
219
            Endpoint::Negotiate => {
220
                let (have, want) = wire::decode_negotiate(&body)?;
221
                ok(wire::encode_hashes(&r.negotiate(&have, &want)?))
222
            }
223
            Endpoint::Fetch => {
224
                let (changes, max_blob) = wire::decode_fetch(&body)?;
225
                ok(wire::encode_bundle(
226
                    &r.bundle_for_filtered(&changes, max_blob)?,
227
                ))
228
            }
229
            Endpoint::Objects => {
230
                let refs = wire::decode_hashes(&body)?;
231
                let bundle = oxy_core::protocol::Bundle {
232
                    objects: r.objects_for(&refs)?,
233
                    ..Default::default()
234
                };
235
                ok(wire::encode_bundle(&bundle))
236
            }
237
            Endpoint::Checkpoint => {
238
                let heads = wire::decode_hashes(&body)?;
239
                let lock = self.lock_for(name);
240
                let _guard = lock.lock().unwrap();
241
                ok(wire::encode_bundle(&r.checkpoint_bundle_for(&heads)?))
242
            }
243
            Endpoint::Shallow => {
244
                let (heads, depth) = wire::decode_shallow(&body)?;
245
                ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?))
246
            }
247
            Endpoint::Push => {
248
                let (bundle, updates, policy, tags) = wire::decode_push(&body)?;
249
                let lock = self.lock_for(name);
250
                let _guard = lock.lock().unwrap();
251
                if r.is_unbound() {
252
                    // The first push binds the repository to the pusher's id (spec §16.1).
253
                    match claimed {
254
                        Some(id) => r.bind_id(id)?,
255
                        None => {
256
                            return Err(Failure(
257
                                StatusCode::BAD_REQUEST,
258
                                format!("this repository is unbound; push with a client that sends {}", oxy_core::protocol::REPO_ID_HEADER),
259
                            ))
260
                        }
261
                    }
262
                }
263
                let results = r.receive_push(bundle, updates, policy, tags)?;
264
                self.backend.after_push(name, &results);
265
                ok(wire::encode_push_response(&results))
266
            }
267
        })
268
    }
269
}
270
271
/// The backend of `oxy serve`: one repository per subdirectory of a root,
272
/// open reads, and pushes gated by a list of bearer tokens.
273
pub struct DirBackend {
274
    pub root: PathBuf,
275
    pub tokens: Vec<String>,
276
}
277
278
impl Backend for DirBackend {
279
    fn open(&self, name: &str) -> Result<Repo, Failure> {
280
        if !valid_repo_name(name) {
281
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
282
        }
283
        let dir = self.root.join(name);
284
        if !dir.join(".oxy").is_dir() {
285
            return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
286
        }
287
        Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
288
    }
289
290
    fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> {
291
        if access == Access::Read || self.tokens.is_empty() {
292
            return Ok(());
293
        }
294
        match bearer_token(headers) {
295
            Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()),
296
            _ => Err(Failure(
297
                StatusCode::UNAUTHORIZED,
298
                "a valid bearer token is required to push".into(),
299
            )),
300
        }
301
    }
302
}
303
304
fn hex_id(h: &str) -> Option<[u8; 16]> {
305
    let h = h.trim();
306
    if h.len() != 32 {
307
        return None;
308
    }
309
    let mut out = [0u8; 16];
310
    for (i, byte) in out.iter_mut().enumerate() {
311
        *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?;
312
    }
313
    Some(out)
314
}
315
316
/// The token of an `Authorization: Bearer` header, if any.
317
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
318
    headers
319
        .get(header::AUTHORIZATION)
320
        .and_then(|v| v.to_str().ok())
321
        .and_then(|v| v.strip_prefix("Bearer "))
322
        .map(str::trim)
323
}
324
325
async fn dispatch(
326
    State(server): State<Arc<Server>>,
327
    Path((repo, endpoint)): Path<(String, String)>,
328
    method: Method,
329
    headers: HeaderMap,
330
    body: Bytes,
331
) -> Response {
332
    match Endpoint::parse(&endpoint) {
333
        Some(e) => server.handle(repo, e, &method, &headers, body).await,
334
        None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
335
    }
336
}
337
338
/// The router of `oxy serve`: `/{repo}/oxy/v1/{endpoint}` over a [`DirBackend`].
339
pub fn router(cfg: ServerConfig) -> Router {
340
    let server = Server::new(DirBackend {
341
        root: cfg.root,
342
        tokens: cfg.tokens,
343
    });
344
    Router::new()
345
        .route("/{repo}/oxy/v1/{endpoint}", any(dispatch))
346
        .with_state(server)
347
}
348
349
/// Serve on an already-bound listener until the process ends; HTTPS when
350
/// `cfg.tls` is set.
351
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
352
    listener.set_nonblocking(true)?;
353
    match cfg.tls.clone() {
354
        Some(tls) => {
355
            let _ = rustls::crypto::ring::default_provider().install_default();
356
            let rustls_cfg =
357
                axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
358
                    .await
359
                    .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?;
360
            axum_server::from_tcp_rustls(listener, rustls_cfg)?
361
                .serve(router(cfg).into_make_service())
362
                .await
363
        }
364
        None => {
365
            let listener = tokio::net::TcpListener::from_std(listener)?;
366
            axum::serve(listener, router(cfg)).await
367
        }
368
    }
369
}
370
371
/// Build a runtime and serve; for the CLI and for tests on a background thread.
372
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> {
373
    let rt = tokio::runtime::Builder::new_multi_thread()
374
        .enable_all()
375
        .build()?;
376
    rt.block_on(serve(listener, cfg))
377
}