| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 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 |
|
| 29 |
pub root: PathBuf, |
| 30 |
|
| 31 |
pub tokens: Vec<String>, |
| 32 |
|
| 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 |
|
| 43 |
|
| 44 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 45 |
pub enum Access { |
| 46 |
Read, |
| 47 |
Push, |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
pub trait Backend: Send + Sync + 'static { |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
fn open(&self, name: &str) -> Result<Repo, Failure>; |
| 58 |
|
| 59 |
|
| 60 |
fn authorize(&self, name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure>; |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
fn after_push(&self, _name: &str, _report: &oxy_core::repo::PushReport, _headers: &HeaderMap) {} |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
fn default_bookmark(&self, _name: &str) -> Option<String> { |
| 70 |
None |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
pub struct Server { |
| 77 |
backend: Box<dyn Backend>, |
| 78 |
locks: Mutex<HashMap<String, Arc<Mutex<()>>>>, |
| 79 |
} |
| 80 |
|
| 81 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 188 |
|
| 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 |
|
| 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 |
|
| 306 |
|
| 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 default_bookmark(&self, name: &str) -> Option<String> { |
| 325 |
self.open(name).ok().map(|r| r.config.bookmark.clone()) |
| 326 |
} |
| 327 |
|
| 328 |
fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> { |
| 329 |
if access == Access::Read || self.tokens.is_empty() { |
| 330 |
return Ok(()); |
| 331 |
} |
| 332 |
match bearer_token(headers) { |
| 333 |
Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()), |
| 334 |
_ => Err(Failure( |
| 335 |
StatusCode::UNAUTHORIZED, |
| 336 |
"a valid bearer token is required to push".into(), |
| 337 |
)), |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
fn hex_id(h: &str) -> Option<[u8; 16]> { |
| 343 |
let h = h.trim(); |
| 344 |
if h.len() != 32 { |
| 345 |
return None; |
| 346 |
} |
| 347 |
let mut out = [0u8; 16]; |
| 348 |
for (i, byte) in out.iter_mut().enumerate() { |
| 349 |
*byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?; |
| 350 |
} |
| 351 |
Some(out) |
| 352 |
} |
| 353 |
|
| 354 |
|
| 355 |
pub fn bearer_token(headers: &HeaderMap) -> Option<&str> { |
| 356 |
headers |
| 357 |
.get(header::AUTHORIZATION) |
| 358 |
.and_then(|v| v.to_str().ok()) |
| 359 |
.and_then(|v| v.strip_prefix("Bearer ")) |
| 360 |
.map(str::trim) |
| 361 |
} |
| 362 |
|
| 363 |
async fn dispatch( |
| 364 |
State(server): State<Arc<Server>>, |
| 365 |
Path((repo, endpoint)): Path<(String, String)>, |
| 366 |
method: Method, |
| 367 |
headers: HeaderMap, |
| 368 |
body: Bytes, |
| 369 |
) -> Response { |
| 370 |
match Endpoint::parse(&endpoint) { |
| 371 |
Some(e) => server.handle(repo, e, &method, &headers, body).await, |
| 372 |
None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(), |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
|
| 377 |
pub fn router(cfg: ServerConfig) -> Router { |
| 378 |
let server = Server::new(DirBackend { |
| 379 |
root: cfg.root, |
| 380 |
tokens: cfg.tokens, |
| 381 |
}); |
| 382 |
Router::new() |
| 383 |
.route("/{repo}/oxy/v1/{endpoint}", any(dispatch)) |
| 384 |
.with_state(server) |
| 385 |
} |
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> { |
| 390 |
listener.set_nonblocking(true)?; |
| 391 |
match cfg.tls.clone() { |
| 392 |
Some(tls) => { |
| 393 |
let _ = rustls::crypto::ring::default_provider().install_default(); |
| 394 |
let rustls_cfg = |
| 395 |
axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key) |
| 396 |
.await |
| 397 |
.map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?; |
| 398 |
axum_server::from_tcp_rustls(listener, rustls_cfg)? |
| 399 |
.serve(router(cfg).into_make_service()) |
| 400 |
.await |
| 401 |
} |
| 402 |
None => { |
| 403 |
let listener = tokio::net::TcpListener::from_std(listener)?; |
| 404 |
axum::serve(listener, router(cfg)).await |
| 405 |
} |
| 406 |
} |
| 407 |
} |
| 408 |
|
| 409 |
|
| 410 |
pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> { |
| 411 |
let rt = tokio::runtime::Builder::new_multi_thread() |
| 412 |
.enable_all() |
| 413 |
.build()?; |
| 414 |
rt.block_on(serve(listener, cfg)) |
| 415 |
} |