| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | | pub mod witness; |
| 15 | |
|
| 16 | | use axum::body::Bytes; |
| 17 | | use axum::extract::{Path, State}; |
| 18 | | use axum::http::{header, HeaderMap, Method, StatusCode}; |
| 19 | | use axum::response::{IntoResponse, Response}; |
| 20 | | use axum::routing::any; |
| 21 | | use axum::Router; |
| 22 | | use oxy_core::protocol::{wire, CONTENT_TYPE}; |
| 23 | | use oxy_core::repo::Repo; |
| 24 | | use std::collections::HashMap; |
| 25 | | use std::path::PathBuf; |
| 26 | | use std::sync::{Arc, Mutex}; |
| 27 | |
|
| 28 | | #[derive(Clone, Debug)] |
| 29 | | pub struct ServerConfig { |
| 30 | | |
| 31 | | pub root: PathBuf, |
| 32 | | |
| 33 | | pub tokens: Vec<String>, |
| 34 | | |
| 35 | | pub tls: Option<TlsFiles>, |
| 36 | | } |
| 37 | |
|
| 38 | | #[derive(Clone, Debug)] |
| 39 | | pub struct TlsFiles { |
| 40 | | pub cert: PathBuf, |
| 41 | | pub key: PathBuf, |
| 42 | | } |
| 43 | |
|
| 44 | |
|
| 45 | |
|
| 46 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 47 | | pub enum Access { |
| 48 | | Read, |
| 49 | | Push, |
| 50 | | } |
| 51 | |
|
| 52 | |
|
| 53 | |
|
| 54 | |
|
| 55 | | pub trait Backend: Send + Sync + 'static { |
| 56 | | |
| 57 | | |
| 58 | | |
| 59 | | fn open(&self, name: &str) -> Result<Repo, Failure>; |
| 60 | |
|
| 61 | | |
| 62 | | fn authorize(&self, name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure>; |
| 63 | |
|
| 64 | | |
| 65 | | |
| 66 | | |
| 67 | 29× | fn after_push(&self, _name: &str, _report: &oxy_core::repo::PushReport, _headers: &HeaderMap) {} |
| 68 | |
|
| 69 | | |
| 70 | | |
| 71 | | |
| 72 | | |
| 73 | | |
| 74 | | |
| 75 | | |
| 76 | | |
| 77 | | |
| 78 | | |
| 79 | 29× | fn vet_push( |
| 80 | 29× | &self, |
| 81 | 29× | _name: &str, |
| 82 | 29× | _repo: &Repo, |
| 83 | 29× | _bundle: &oxy_core::protocol::Bundle, |
| 84 | 29× | _updates: &[oxy_core::protocol::RefUpdate], |
| 85 | 29× | _headers: &HeaderMap, |
| 86 | 29× | ) -> Result<(), Failure> { |
| 87 | 29× | Ok(()) |
| 88 | 29× | } |
| 89 | |
|
| 90 | | |
| 91 | | |
| 92 | | |
| 93 | 119× | fn add_log(&self, _name: &str, _refs: &mut oxy_core::protocol::RefsResponse) {} |
| 94 | |
|
| 95 | | |
| 96 | | |
| 97 | 8× | fn default_bookmark(&self, _name: &str) -> Option<String> { |
| 98 | 8× | None |
| 99 | 8× | } |
| 100 | | } |
| 101 | |
|
| 102 | |
|
| 103 | |
|
| 104 | | pub struct Server { |
| 105 | | backend: Box<dyn Backend>, |
| 106 | | locks: Mutex<HashMap<String, Arc<Mutex<()>>>>, |
| 107 | | } |
| 108 | |
|
| 109 | |
|
| 110 | | #[derive(Debug)] |
| 111 | | pub struct Failure(pub StatusCode, pub String); |
| 112 | |
|
| 113 | | impl IntoResponse for Failure { |
| 114 | 9× | fn into_response(self) -> Response { |
| 115 | 9× | (self.0, self.1).into_response() |
| 116 | 9× | } |
| 117 | | } |
| 118 | |
|
| 119 | | impl From<oxy_core::repo::RepoError> for Failure { |
| 120 | 0× | fn from(e: oxy_core::repo::RepoError) -> Failure { |
| 121 | | use oxy_core::repo::RepoError; |
| 122 | | |
| 123 | 0× | let status = match &e { |
| 124 | 0× | RepoError::Io(_) | RepoError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR, |
| 125 | 0× | _ => StatusCode::BAD_REQUEST, |
| 126 | | }; |
| 127 | 0× | Failure(status, e.to_string()) |
| 128 | 0× | } |
| 129 | | } |
| 130 | |
|
| 131 | |
|
| 132 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 133 | | pub enum Endpoint { |
| 134 | | Capabilities, |
| 135 | | Refs, |
| 136 | | Negotiate, |
| 137 | | Fetch, |
| 138 | | Objects, |
| 139 | | Checkpoint, |
| 140 | | Shallow, |
| 141 | | Push, |
| 142 | | } |
| 143 | |
|
| 144 | | impl Endpoint { |
| 145 | 373× | pub fn parse(name: &str) -> Option<Endpoint> { |
| 146 | 373× | Some(match name { |
| 147 | 373× | "capabilities" => Endpoint::Capabilities, |
| 148 | 248× | "refs" => Endpoint::Refs, |
| 149 | 129× | "negotiate" => Endpoint::Negotiate, |
| 150 | 83× | "fetch" => Endpoint::Fetch, |
| 151 | 37× | "objects" => Endpoint::Objects, |
| 152 | 36× | "checkpoint" => Endpoint::Checkpoint, |
| 153 | 36× | "shallow" => Endpoint::Shallow, |
| 154 | 36× | "push" => Endpoint::Push, |
| 155 | 0× | _ => return None, |
| 156 | | }) |
| 157 | 373× | } |
| 158 | |
|
| 159 | 3× | pub fn name(self) -> &'static str { |
| 160 | 3× | match self { |
| 161 | 2× | Endpoint::Capabilities => "capabilities", |
| 162 | 0× | Endpoint::Refs => "refs", |
| 163 | 0× | Endpoint::Negotiate => "negotiate", |
| 164 | 0× | Endpoint::Fetch => "fetch", |
| 165 | 0× | Endpoint::Objects => "objects", |
| 166 | 0× | Endpoint::Checkpoint => "checkpoint", |
| 167 | 0× | Endpoint::Shallow => "shallow", |
| 168 | 1× | Endpoint::Push => "push", |
| 169 | | } |
| 170 | 3× | } |
| 171 | |
|
| 172 | | |
| 173 | 373× | pub fn method(self) -> Method { |
| 174 | 373× | match self { |
| 175 | 244× | Endpoint::Capabilities | Endpoint::Refs => Method::GET, |
| 176 | 129× | _ => Method::POST, |
| 177 | | } |
| 178 | 373× | } |
| 179 | |
|
| 180 | 373× | fn access(self) -> Access { |
| 181 | 373× | match self { |
| 182 | 36× | Endpoint::Push => Access::Push, |
| 183 | 337× | _ => Access::Read, |
| 184 | | } |
| 185 | 373× | } |
| 186 | | } |
| 187 | |
|
| 188 | 364× | fn ok(body: Vec<u8>) -> Response { |
| 189 | 364× | ([(header::CONTENT_TYPE, CONTENT_TYPE)], body).into_response() |
| 190 | 364× | } |
| 191 | |
|
| 192 | 497× | pub fn valid_repo_name(name: &str) -> bool { |
| 193 | 497× | !name.is_empty() |
| 194 | 497× | && !name.starts_with('.') |
| 195 | 496× | && name |
| 196 | 496× | .chars() |
| 197 | 2715× | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) |
| 198 | 497× | } |
| 199 | |
|
| 200 | | impl Server { |
| 201 | 13× | pub fn new(backend: impl Backend) -> Arc<Server> { |
| 202 | 13× | Arc::new(Server { |
| 203 | 13× | backend: Box::new(backend), |
| 204 | 13× | locks: Mutex::new(HashMap::new()), |
| 205 | 13× | }) |
| 206 | 13× | } |
| 207 | |
|
| 208 | 0× | pub fn backend(&self) -> &dyn Backend { |
| 209 | 0× | self.backend.as_ref() |
| 210 | 0× | } |
| 211 | |
|
| 212 | 30× | fn lock_for(&self, name: &str) -> Arc<Mutex<()>> { |
| 213 | 30× | self.locks |
| 214 | 30× | .lock() |
| 215 | 30× | .unwrap() |
| 216 | 30× | .entry(name.to_string()) |
| 217 | 30× | .or_default() |
| 218 | 30× | .clone() |
| 219 | 30× | } |
| 220 | |
|
| 221 | | |
| 222 | | |
| 223 | 373× | pub async fn handle( |
| 224 | 373× | self: &Arc<Self>, |
| 225 | 373× | name: String, |
| 226 | 373× | endpoint: Endpoint, |
| 227 | 373× | method: &Method, |
| 228 | 373× | headers: &HeaderMap, |
| 229 | 373× | body: Bytes, |
| 230 | 373× | ) -> Response { |
| 231 | 373× | if *method != endpoint.method() { |
| 232 | 0× | return Failure( |
| 233 | 0× | StatusCode::METHOD_NOT_ALLOWED, |
| 234 | 0× | format!("{} is {}", endpoint.name(), endpoint.method()), |
| 235 | 0× | ) |
| 236 | 0× | .into_response(); |
| 237 | 373× | } |
| 238 | 373× | if let Err(f) = self.backend.authorize(&name, endpoint.access(), headers) { |
| 239 | 6× | return f.into_response(); |
| 240 | 367× | } |
| 241 | 367× | let claimed = headers |
| 242 | 367× | .get(oxy_core::protocol::REPO_ID_HEADER) |
| 243 | 367× | .and_then(|v| v.to_str().ok()) |
| 244 | 367× | .and_then(hex_id); |
| 245 | 367× | let server = Arc::clone(self); |
| 246 | 367× | let request_headers = headers.clone(); |
| 247 | 367× | let repo = name.clone(); |
| 248 | 367× | let result = tokio::task::spawn_blocking(move || { |
| 249 | 367× | server.respond(&repo, endpoint, body, claimed, &request_headers) |
| 250 | 367× | }) |
| 251 | 367× | .await; |
| 252 | 367× | let failure = match result { |
| 253 | 364× | Ok(Ok(r)) => return r, |
| 254 | 3× | Ok(Err(f)) => f, |
| 255 | 0× | Err(e) => Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), |
| 256 | | }; |
| 257 | | |
| 258 | 3× | let f = Failure( |
| 259 | 3× | failure.0, |
| 260 | 3× | format!("{} of {name}: {}", endpoint.name(), failure.1), |
| 261 | 3× | ); |
| 262 | 3× | eprintln!("oxy-server: {}: {}", f.0.as_u16(), f.1); |
| 263 | 3× | f.into_response() |
| 264 | 373× | } |
| 265 | |
|
| 266 | 367× | fn respond( |
| 267 | 367× | &self, |
| 268 | 367× | name: &str, |
| 269 | 367× | endpoint: Endpoint, |
| 270 | 367× | body: Bytes, |
| 271 | 367× | claimed: Option<[u8; 16]>, |
| 272 | 367× | headers: &HeaderMap, |
| 273 | 367× | ) -> Result<Response, Failure> { |
| 274 | 367× | let r = self.backend.open(name)?; |
| 275 | 365× | Ok(match endpoint { |
| 276 | 122× | Endpoint::Capabilities => ok(wire::encode_capabilities(r.id()?)), |
| 277 | | Endpoint::Refs => { |
| 278 | 119× | let mut refs = r.remote_refs()?; |
| 279 | 119× | if let Some(d) = self.backend.default_bookmark(name) { |
| 280 | 113× | refs.default_bookmark = Some(d); |
| 281 | 113× | } |
| 282 | 119× | self.backend.add_log(name, &mut refs); |
| 283 | 119× | ok(wire::encode_refs(r.id()?, &refs)) |
| 284 | | } |
| 285 | | Endpoint::Negotiate => { |
| 286 | 46× | let (have, want) = wire::decode_negotiate(&body)?; |
| 287 | 46× | ok(wire::encode_hashes(&r.negotiate(&have, &want)?)) |
| 288 | | } |
| 289 | | Endpoint::Fetch => { |
| 290 | 46× | let (changes, max_blob) = wire::decode_fetch(&body)?; |
| 291 | 46× | ok(wire::encode_bundle( |
| 292 | 46× | &r.bundle_for_filtered(&changes, max_blob)?, |
| 293 | | )) |
| 294 | | } |
| 295 | | Endpoint::Objects => { |
| 296 | 1× | let refs = wire::decode_hashes(&body)?; |
| 297 | 1× | let bundle = oxy_core::protocol::Bundle { |
| 298 | 1× | objects: r.objects_for(&refs)?, |
| 299 | 1× | ..Default::default() |
| 300 | | }; |
| 301 | 1× | ok(wire::encode_bundle(&bundle)) |
| 302 | | } |
| 303 | | Endpoint::Checkpoint => { |
| 304 | 0× | let heads = wire::decode_hashes(&body)?; |
| 305 | 0× | let lock = self.lock_for(name); |
| 306 | 0× | let _guard = lock.lock().unwrap(); |
| 307 | 0× | ok(wire::encode_bundle(&r.checkpoint_bundle_for(&heads)?)) |
| 308 | | } |
| 309 | | Endpoint::Shallow => { |
| 310 | 0× | let (heads, depth) = wire::decode_shallow(&body)?; |
| 311 | 0× | ok(wire::encode_hashes(&r.shallow_changes(&heads, depth)?)) |
| 312 | | } |
| 313 | | Endpoint::Push => { |
| 314 | 31× | let (bundle, updates, policy, tags) = wire::decode_push(&body)?; |
| 315 | | |
| 316 | | |
| 317 | 31× | self.backend |
| 318 | 31× | .vet_push(name, &r, &bundle, &updates, headers)?; |
| 319 | 30× | let lock = self.lock_for(name); |
| 320 | 30× | let _guard = lock.lock().unwrap(); |
| 321 | 30× | if r.is_unbound() { |
| 322 | | |
| 323 | 3× | match claimed { |
| 324 | 3× | Some(id) => r.bind_id(id)?, |
| 325 | | None => { |
| 326 | 0× | return Err(Failure( |
| 327 | 0× | StatusCode::BAD_REQUEST, |
| 328 | 0× | format!( |
| 329 | 0× | "this repository is unbound; push with a client that sends {}", |
| 330 | 0× | oxy_core::protocol::REPO_ID_HEADER |
| 331 | 0× | ), |
| 332 | 0× | )) |
| 333 | | } |
| 334 | | } |
| 335 | 27× | } |
| 336 | 30× | let protected = self.backend.default_bookmark(name); |
| 337 | 30× | let (refused, updates): (Vec<_>, Vec<_>) = updates.into_iter().partition(|u| { |
| 338 | 30× | u.new_state.is_zero() && protected.as_deref() == Some(u.name.as_str()) |
| 339 | 30× | }); |
| 340 | 30× | let mut report = r.receive_push_report(bundle, updates, policy, tags)?; |
| 341 | | |
| 342 | | |
| 343 | 30× | if !refused.is_empty() { |
| 344 | 1× | report |
| 345 | 1× | .results |
| 346 | 1× | .retain(|r| r.name != oxy_core::repo::OBJECTS_RESULT); |
| 347 | 29× | } |
| 348 | 30× | for u in refused { |
| 349 | 1× | report.results.push(oxy_core::protocol::RefResult { |
| 350 | 1× | name: u.name.clone(), |
| 351 | 1× | ok: false, |
| 352 | 1× | reason: format!( |
| 353 | 1× | "{:?} is this repository's default bookmark and cannot be deleted", |
| 354 | 1× | u.name |
| 355 | 1× | ), |
| 356 | 1× | }); |
| 357 | 1× | } |
| 358 | 31× | for r in report.results.iter().filter(|r| !r.ok) { |
| 359 | 9× | eprintln!( |
| 360 | 9× | "oxy-server: push to {name}: {} refused: {}", |
| 361 | 9× | r.name, r.reason |
| 362 | 9× | ); |
| 363 | 9× | } |
| 364 | 30× | self.backend.after_push(name, &report, headers); |
| 365 | 30× | ok(wire::encode_push_response(&report.results)) |
| 366 | | } |
| 367 | | }) |
| 368 | 367× | } |
| 369 | | } |
| 370 | |
|
| 371 | |
|
| 372 | |
|
| 373 | | pub struct DirBackend { |
| 374 | | pub root: PathBuf, |
| 375 | | pub tokens: Vec<String>, |
| 376 | | } |
| 377 | |
|
| 378 | | impl Backend for DirBackend { |
| 379 | 497× | fn open(&self, name: &str) -> Result<Repo, Failure> { |
| 380 | 497× | if !valid_repo_name(name) { |
| 381 | 1× | return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into())); |
| 382 | 496× | } |
| 383 | 496× | let dir = self.root.join(name); |
| 384 | 496× | if !dir.join(".oxy").is_dir() { |
| 385 | 1× | return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into())); |
| 386 | 495× | } |
| 387 | 495× | Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())) |
| 388 | 497× | } |
| 389 | |
|
| 390 | 141× | fn default_bookmark(&self, name: &str) -> Option<String> { |
| 391 | 141× | self.open(name).ok().map(|r| r.config.bookmark.clone()) |
| 392 | 141× | } |
| 393 | |
|
| 394 | 360× | fn authorize(&self, _name: &str, access: Access, headers: &HeaderMap) -> Result<(), Failure> { |
| 395 | 360× | if access == Access::Read || self.tokens.is_empty() { |
| 396 | 354× | return Ok(()); |
| 397 | 6× | } |
| 398 | 6× | match bearer_token(headers) { |
| 399 | 5× | Some(t) if self.tokens.iter().any(|x| x == t) => Ok(()), |
| 400 | 4× | _ => Err(Failure( |
| 401 | 4× | StatusCode::UNAUTHORIZED, |
| 402 | 4× | "a valid bearer token is required to push".into(), |
| 403 | 4× | )), |
| 404 | | } |
| 405 | 360× | } |
| 406 | | } |
| 407 | |
|
| 408 | 344× | fn hex_id(h: &str) -> Option<[u8; 16]> { |
| 409 | 344× | let h = h.trim(); |
| 410 | 344× | if h.len() != 32 { |
| 411 | 0× | return None; |
| 412 | 344× | } |
| 413 | 344× | let mut out = [0u8; 16]; |
| 414 | 5504× | for (i, byte) in out.iter_mut().enumerate() { |
| 415 | 5504× | *byte = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).ok()?; |
| 416 | | } |
| 417 | 344× | Some(out) |
| 418 | 344× | } |
| 419 | |
|
| 420 | |
|
| 421 | 19× | pub fn bearer_token(headers: &HeaderMap) -> Option<&str> { |
| 422 | 19× | headers |
| 423 | 19× | .get(header::AUTHORIZATION) |
| 424 | 19× | .and_then(|v| v.to_str().ok()) |
| 425 | 19× | .and_then(|v| v.strip_prefix("Bearer ")) |
| 426 | 19× | .map(str::trim) |
| 427 | 19× | } |
| 428 | |
|
| 429 | 354× | async fn dispatch( |
| 430 | 354× | State(server): State<Arc<Server>>, |
| 431 | 354× | Path((repo, endpoint)): Path<(String, String)>, |
| 432 | 354× | method: Method, |
| 433 | 354× | headers: HeaderMap, |
| 434 | 354× | body: Bytes, |
| 435 | 354× | ) -> Response { |
| 436 | 354× | match Endpoint::parse(&endpoint) { |
| 437 | 354× | Some(e) => server.handle(repo, e, &method, &headers, body).await, |
| 438 | 0× | None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(), |
| 439 | | } |
| 440 | 354× | } |
| 441 | |
|
| 442 | |
|
| 443 | 11× | pub fn router(cfg: ServerConfig) -> Router { |
| 444 | 11× | let server = Server::new(DirBackend { |
| 445 | 11× | root: cfg.root, |
| 446 | 11× | tokens: cfg.tokens, |
| 447 | 11× | }); |
| 448 | 11× | Router::new() |
| 449 | 11× | .route("/{repo}/oxy/v1/{endpoint}", any(dispatch)) |
| 450 | 11× | .with_state(server) |
| 451 | 11× | } |
| 452 | |
|
| 453 | |
|
| 454 | |
|
| 455 | 11× | pub async fn serve(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> { |
| 456 | 11× | listener.set_nonblocking(true)?; |
| 457 | 11× | match cfg.tls.clone() { |
| 458 | 1× | Some(tls) => { |
| 459 | 1× | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 460 | 1× | let rustls_cfg = |
| 461 | 1× | axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key) |
| 462 | 1× | .await |
| 463 | 1× | .map_err(|e| std::io::Error::other(format!("loading TLS files: {e}")))?; |
| 464 | 1× | axum_server::from_tcp_rustls(listener, rustls_cfg)? |
| 465 | 1× | .serve(router(cfg).into_make_service()) |
| 466 | 1× | .await |
| 467 | | } |
| 468 | | None => { |
| 469 | 10× | let listener = tokio::net::TcpListener::from_std(listener)?; |
| 470 | 10× | axum::serve(listener, router(cfg)).await |
| 471 | | } |
| 472 | | } |
| 473 | 0× | } |
| 474 | |
|
| 475 | |
|
| 476 | 11× | pub fn run_blocking(listener: std::net::TcpListener, cfg: ServerConfig) -> std::io::Result<()> { |
| 477 | 11× | let rt = tokio::runtime::Builder::new_multi_thread() |
| 478 | 11× | .enable_all() |
| 479 | 11× | .build()?; |
| 480 | 11× | rt.block_on(serve(listener, cfg)) |
| 481 | 11× | } |