| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | pub mod auth; |
| 15 | pub mod blobs; |
| 16 | pub mod gc; |
| 17 | pub mod manifests; |
| 18 | |
| 19 | use forge_core::oci as rules; |
| 20 | use http::header::{CONTENT_TYPE, HeaderValue}; |
| 21 | use serde_json::{Value, json}; |
| 22 | use topcoat::context::{Cx, context}; |
| 23 | use topcoat::router::request::{headers, method, uri}; |
| 24 | use topcoat::router::response::Response; |
| 25 | use topcoat::router::{Body, StatusCode, path_param, route}; |
| 26 | |
| 27 | use crate::state::AppState; |
| 28 | use auth::{Caller, unix_now}; |
| 29 | |
| 30 | path_param!(*rest); |
| 31 | |
| 32 | |
| 33 | const API_VERSION: &str = "docker-distribution-api-version"; |
| 34 | |
| 35 | |
| 36 | pub fn oci_error(status: StatusCode, code: &str, message: &str) -> Response { |
| 37 | let body = json!({ "errors": [{ "code": code, "message": message, "detail": Value::Null }] }); |
| 38 | json_response(status, &body) |
| 39 | } |
| 40 | |
| 41 | fn json_response(status: StatusCode, value: &Value) -> Response { |
| 42 | let mut res = Response::new(Body::from(value.to_string())); |
| 43 | *res.status_mut() = status; |
| 44 | res.headers_mut() |
| 45 | .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); |
| 46 | res.headers_mut() |
| 47 | .insert(API_VERSION, HeaderValue::from_static("registry/2.0")); |
| 48 | res |
| 49 | } |
| 50 | |
| 51 | |
| 52 | #[derive(Debug, PartialEq, Eq)] |
| 53 | enum Op { |
| 54 | Tags { name: String }, |
| 55 | Manifest { name: String, reference: String }, |
| 56 | UploadStart { name: String }, |
| 57 | Upload { name: String, id: String }, |
| 58 | Blob { name: String, digest: String }, |
| 59 | } |
| 60 | |
| 61 | |
| 62 | |
| 63 | fn parse_op(segments: &[&str]) -> Option<Op> { |
| 64 | for (i, keyword) in segments.iter().enumerate().skip(1) { |
| 65 | let name = segments[..i].join("/"); |
| 66 | let rest = &segments[i + 1..]; |
| 67 | let op = match *keyword { |
| 68 | "tags" if rest == ["list"] => Op::Tags { name }, |
| 69 | "manifests" if rest.len() == 1 => Op::Manifest { |
| 70 | name, |
| 71 | reference: rest[0].to_owned(), |
| 72 | }, |
| 73 | "blobs" if rest == ["uploads"] => Op::UploadStart { name }, |
| 74 | "blobs" if rest.len() == 2 && rest[0] == "uploads" => Op::Upload { |
| 75 | name, |
| 76 | id: rest[1].to_owned(), |
| 77 | }, |
| 78 | "blobs" if rest.len() == 1 => Op::Blob { |
| 79 | name, |
| 80 | digest: rest[0].to_owned(), |
| 81 | }, |
| 82 | _ => continue, |
| 83 | }; |
| 84 | return Some(op); |
| 85 | } |
| 86 | None |
| 87 | } |
| 88 | |
| 89 | |
| 90 | fn query_pairs(cx: &Cx) -> Vec<(String, String)> { |
| 91 | uri(cx) |
| 92 | .query() |
| 93 | .map(|q| { |
| 94 | form_urlencoded::parse(q.as_bytes()) |
| 95 | .map(|(k, v)| (k.into_owned(), v.into_owned())) |
| 96 | .collect() |
| 97 | }) |
| 98 | .unwrap_or_default() |
| 99 | } |
| 100 | |
| 101 | fn query_value(pairs: &[(String, String)], key: &str) -> Option<String> { |
| 102 | pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) |
| 103 | } |
| 104 | |
| 105 | |
| 106 | #[route(GET "/v2/")] |
| 107 | async fn root(cx: &Cx) -> topcoat::Result<Response> { |
| 108 | let state = context::<AppState>(cx); |
| 109 | Ok(match auth::caller(cx).await { |
| 110 | Ok(Caller { user: Some(_) }) => json_response(StatusCode::OK, &json!({})), |
| 111 | Ok(_) => auth::challenge(state, None), |
| 112 | Err(res) => *res, |
| 113 | }) |
| 114 | } |
| 115 | |
| 116 | |
| 117 | |
| 118 | #[route(GET "/v2/token")] |
| 119 | async fn token(cx: &Cx) -> topcoat::Result<Response> { |
| 120 | let state = context::<AppState>(cx); |
| 121 | let caller = match auth::caller(cx).await { |
| 122 | Ok(caller) => caller, |
| 123 | Err(res) => return Ok(*res), |
| 124 | }; |
| 125 | let subject = caller.user.as_ref().map(|user| user.id.as_str()); |
| 126 | let now = unix_now(); |
| 127 | let token = forge_core::oci::issue_token(&state.key, subject, now + auth::TOKEN_TTL_SECS); |
| 128 | |
| 129 | let issued_at = time::OffsetDateTime::now_utc() |
| 130 | .format(&time::format_description::well_known::Rfc3339) |
| 131 | .unwrap_or_default(); |
| 132 | Ok(json_response( |
| 133 | StatusCode::OK, |
| 134 | &json!({ |
| 135 | "token": token, |
| 136 | "access_token": token, |
| 137 | "expires_in": auth::TOKEN_TTL_SECS, |
| 138 | "issued_at": issued_at, |
| 139 | }), |
| 140 | )) |
| 141 | } |
| 142 | |
| 143 | #[route(GET "/v2/{*rest}")] |
| 144 | async fn get_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 145 | Ok(dispatch(cx, body).await) |
| 146 | } |
| 147 | |
| 148 | #[route(POST "/v2/{*rest}")] |
| 149 | async fn post_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 150 | Ok(dispatch(cx, body).await) |
| 151 | } |
| 152 | |
| 153 | #[route(PUT "/v2/{*rest}")] |
| 154 | async fn put_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 155 | Ok(dispatch(cx, body).await) |
| 156 | } |
| 157 | |
| 158 | #[route(PATCH "/v2/{*rest}")] |
| 159 | async fn patch_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 160 | Ok(dispatch(cx, body).await) |
| 161 | } |
| 162 | |
| 163 | #[route(DELETE "/v2/{*rest}")] |
| 164 | async fn delete_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 165 | Ok(dispatch(cx, body).await) |
| 166 | } |
| 167 | |
| 168 | |
| 169 | |
| 170 | async fn dispatch(cx: &Cx, body: Body) -> Response { |
| 171 | let state = context::<AppState>(cx); |
| 172 | let segments: Vec<String> = rest(cx).map(str::to_owned).collect(); |
| 173 | let mut parts: Vec<&str> = segments.iter().map(String::as_str).collect(); |
| 174 | while parts.last() == Some(&"") { |
| 175 | parts.pop(); |
| 176 | } |
| 177 | let caller = match auth::caller(cx).await { |
| 178 | Ok(caller) => caller, |
| 179 | Err(res) => return *res, |
| 180 | }; |
| 181 | let method = method(cx).clone(); |
| 182 | let read = method == http::Method::GET || method == http::Method::HEAD; |
| 183 | let head = method == http::Method::HEAD; |
| 184 | let pairs = query_pairs(cx); |
| 185 | let headers = headers(cx).clone(); |
| 186 | let Some(op) = parse_op(&parts) else { |
| 187 | return oci_error(StatusCode::NOT_FOUND, "NAME_UNKNOWN", "not found"); |
| 188 | }; |
| 189 | match op { |
| 190 | Op::Tags { name } if read => { |
| 191 | let n = query_value(&pairs, "n").and_then(|v| v.parse::<u64>().ok()); |
| 192 | let last = query_value(&pairs, "last"); |
| 193 | manifests::list_tags(state, &caller, &name, n, last.as_deref()).await |
| 194 | } |
| 195 | Op::Manifest { name, reference } => match method { |
| 196 | http::Method::GET | http::Method::HEAD => { |
| 197 | manifests::get_manifest(state, &caller, &name, &reference, head).await |
| 198 | } |
| 199 | http::Method::PUT => { |
| 200 | let content_type = headers |
| 201 | .get(CONTENT_TYPE) |
| 202 | .and_then(|v| v.to_str().ok()) |
| 203 | .map(str::to_owned); |
| 204 | manifests::put_manifest( |
| 205 | state, |
| 206 | &caller, |
| 207 | &name, |
| 208 | &reference, |
| 209 | content_type.as_deref(), |
| 210 | body, |
| 211 | ) |
| 212 | .await |
| 213 | } |
| 214 | http::Method::DELETE => { |
| 215 | manifests::delete_manifest(state, &caller, &name, &reference).await |
| 216 | } |
| 217 | _ => unsupported(), |
| 218 | }, |
| 219 | Op::Blob { name, digest } => match method { |
| 220 | http::Method::GET | http::Method::HEAD => { |
| 221 | blobs::get_blob(state, &caller, &name, &digest, head).await |
| 222 | } |
| 223 | http::Method::DELETE => match auth::authorize(state, &caller, &name, true).await { |
| 224 | Ok(target) => blobs::delete_blob(state, &target, &digest).await, |
| 225 | Err(res) => *res, |
| 226 | }, |
| 227 | _ => unsupported(), |
| 228 | }, |
| 229 | Op::UploadStart { name } if method == http::Method::POST => { |
| 230 | start_upload(state, &caller, &name, &pairs, body).await |
| 231 | } |
| 232 | Op::Upload { name, id } => { |
| 233 | upload_step(state, &caller, &name, &id, &method, &headers, &pairs, body).await |
| 234 | } |
| 235 | _ => unsupported(), |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | fn unsupported() -> Response { |
| 240 | oci_error( |
| 241 | StatusCode::METHOD_NOT_ALLOWED, |
| 242 | "UNSUPPORTED", |
| 243 | "the operation is unsupported", |
| 244 | ) |
| 245 | } |
| 246 | |
| 247 | |
| 248 | |
| 249 | async fn start_upload( |
| 250 | state: &AppState, |
| 251 | caller: &Caller, |
| 252 | name: &str, |
| 253 | pairs: &[(String, String)], |
| 254 | body: Body, |
| 255 | ) -> Response { |
| 256 | let target = match auth::authorize(state, caller, name, true).await { |
| 257 | Ok(target) => target, |
| 258 | Err(res) => return *res, |
| 259 | }; |
| 260 | if let (Some(mount), Some(from)) = (query_value(pairs, "mount"), query_value(pairs, "from")) { |
| 261 | match blobs::try_mount(state, caller, &target, &mount, &from).await { |
| 262 | Ok(true) => { |
| 263 | let hex = rules::parse_digest(&mount).unwrap_or_default(); |
| 264 | state.packages_live.bump(&target.owner.id); |
| 265 | return blobs::created(name, hex); |
| 266 | } |
| 267 | Ok(false) => {} |
| 268 | Err(res) => return *res, |
| 269 | } |
| 270 | } |
| 271 | let data_dir = state.config.data_dir.clone(); |
| 272 | let id = match blobs::new_session(&data_dir, name).await { |
| 273 | Ok(id) => id, |
| 274 | Err(e) => return auth::internal(e), |
| 275 | }; |
| 276 | let Some(digest) = query_value(pairs, "digest") else { |
| 277 | return blobs::upload_progress(name, &id, 0); |
| 278 | }; |
| 279 | let hex = match blobs::digest_arg(&digest) { |
| 280 | Ok(hex) => hex.to_owned(), |
| 281 | Err(res) => { |
| 282 | blobs::remove_session(&data_dir, &id).await; |
| 283 | return *res; |
| 284 | } |
| 285 | }; |
| 286 | if let Err(res) = blobs::append(&data_dir, &id, body, None).await { |
| 287 | blobs::remove_session(&data_dir, &id).await; |
| 288 | return *res; |
| 289 | } |
| 290 | finish_upload(state, &target, name, &id, &hex).await |
| 291 | } |
| 292 | |
| 293 | |
| 294 | |
| 295 | async fn finish_upload( |
| 296 | state: &AppState, |
| 297 | target: &auth::Target, |
| 298 | name: &str, |
| 299 | id: &str, |
| 300 | hex: &str, |
| 301 | ) -> Response { |
| 302 | let data_dir = state.config.data_dir.clone(); |
| 303 | let path = blobs::uploads_dir(&data_dir).join(id); |
| 304 | let actual = match blobs::file_sha256(&path).await { |
| 305 | Ok(actual) => actual, |
| 306 | Err(e) => return auth::internal(e), |
| 307 | }; |
| 308 | if actual != hex { |
| 309 | blobs::remove_session(&data_dir, id).await; |
| 310 | return oci_error( |
| 311 | StatusCode::BAD_REQUEST, |
| 312 | "DIGEST_INVALID", |
| 313 | "the content does not match the digest", |
| 314 | ); |
| 315 | } |
| 316 | let size = match tokio::fs::metadata(&path).await { |
| 317 | Ok(meta) => meta.len(), |
| 318 | Err(e) => return auth::internal(e), |
| 319 | }; |
| 320 | let package = match blobs::write_package(state, target).await { |
| 321 | Ok(package) => package, |
| 322 | Err(res) => return *res, |
| 323 | }; |
| 324 | if let Err(res) = blobs::link(state, &package, hex, size, Some(&path)).await { |
| 325 | blobs::remove_session(&data_dir, id).await; |
| 326 | return *res; |
| 327 | } |
| 328 | blobs::remove_session(&data_dir, id).await; |
| 329 | state.packages_live.bump(&target.owner.id); |
| 330 | blobs::created(name, hex) |
| 331 | } |
| 332 | |
| 333 | |
| 334 | |
| 335 | #[allow(clippy::too_many_arguments)] |
| 336 | async fn upload_step( |
| 337 | state: &AppState, |
| 338 | caller: &Caller, |
| 339 | name: &str, |
| 340 | id: &str, |
| 341 | method: &http::Method, |
| 342 | headers: &http::HeaderMap, |
| 343 | pairs: &[(String, String)], |
| 344 | body: Body, |
| 345 | ) -> Response { |
| 346 | let data_dir = state.config.data_dir.clone(); |
| 347 | let target = match auth::authorize(state, caller, name, true).await { |
| 348 | Ok(target) => target, |
| 349 | Err(res) => return *res, |
| 350 | }; |
| 351 | if !blobs::session_belongs_to(&data_dir, id, name).await { |
| 352 | return oci_error( |
| 353 | StatusCode::NOT_FOUND, |
| 354 | "BLOB_UPLOAD_UNKNOWN", |
| 355 | "blob upload unknown to registry", |
| 356 | ); |
| 357 | } |
| 358 | match *method { |
| 359 | http::Method::GET => match blobs::session_size(&data_dir, id).await { |
| 360 | Ok(size) => { |
| 361 | let mut res = Response::new(Body::empty()); |
| 362 | *res.status_mut() = StatusCode::NO_CONTENT; |
| 363 | blobs::insert( |
| 364 | &mut res, |
| 365 | "location", |
| 366 | &format!("/v2/{name}/blobs/uploads/{id}"), |
| 367 | ); |
| 368 | blobs::insert(&mut res, "docker-upload-uuid", id); |
| 369 | blobs::insert(&mut res, "range", &blobs::range_of(size)); |
| 370 | res |
| 371 | } |
| 372 | Err(e) => auth::internal(e), |
| 373 | }, |
| 374 | http::Method::PATCH => { |
| 375 | if let Err(res) = |
| 376 | blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await |
| 377 | { |
| 378 | return *res; |
| 379 | } |
| 380 | match blobs::session_size(&data_dir, id).await { |
| 381 | Ok(size) => blobs::upload_progress(name, id, size), |
| 382 | Err(e) => auth::internal(e), |
| 383 | } |
| 384 | } |
| 385 | http::Method::PUT => { |
| 386 | let Some(digest) = query_value(pairs, "digest") else { |
| 387 | return oci_error( |
| 388 | StatusCode::BAD_REQUEST, |
| 389 | "DIGEST_INVALID", |
| 390 | "digest is required", |
| 391 | ); |
| 392 | }; |
| 393 | let hex = match blobs::digest_arg(&digest) { |
| 394 | Ok(hex) => hex.to_owned(), |
| 395 | Err(res) => return *res, |
| 396 | }; |
| 397 | if let Err(res) = |
| 398 | blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await |
| 399 | { |
| 400 | return *res; |
| 401 | } |
| 402 | finish_upload(state, &target, name, id, &hex).await |
| 403 | } |
| 404 | http::Method::DELETE => { |
| 405 | blobs::remove_session(&data_dir, id).await; |
| 406 | let mut res = Response::new(Body::empty()); |
| 407 | *res.status_mut() = StatusCode::NO_CONTENT; |
| 408 | res |
| 409 | } |
| 410 | _ => unsupported(), |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | #[cfg(test)] |
| 415 | mod tests { |
| 416 | use super::*; |
| 417 | |
| 418 | #[test] |
| 419 | fn nested_names_parse_up_to_the_keyword() { |
| 420 | assert_eq!( |
| 421 | parse_op(&["tahinli", "app", "manifests", "latest"]), |
| 422 | Some(Op::Manifest { |
| 423 | name: "tahinli/app".into(), |
| 424 | reference: "latest".into(), |
| 425 | }) |
| 426 | ); |
| 427 | assert_eq!( |
| 428 | parse_op(&["tahinli", "a", "b", "blobs", "uploads"]), |
| 429 | Some(Op::UploadStart { |
| 430 | name: "tahinli/a/b".into(), |
| 431 | }) |
| 432 | ); |
| 433 | assert_eq!( |
| 434 | parse_op(&["tahinli", "app", "tags", "list"]), |
| 435 | Some(Op::Tags { |
| 436 | name: "tahinli/app".into(), |
| 437 | }) |
| 438 | ); |
| 439 | } |
| 440 | |
| 441 | #[test] |
| 442 | fn a_keyword_inside_the_name_is_not_taken_for_one() { |
| 443 | assert_eq!( |
| 444 | parse_op(&["tahinli", "blobs", "x", "manifests", "v1"]), |
| 445 | Some(Op::Manifest { |
| 446 | name: "tahinli/blobs/x".into(), |
| 447 | reference: "v1".into(), |
| 448 | }) |
| 449 | ); |
| 450 | } |
| 451 | |
| 452 | #[test] |
| 453 | fn upload_and_blob_paths_are_told_apart() { |
| 454 | assert_eq!( |
| 455 | parse_op(&["tahinli", "app", "blobs", "uploads", "ID1"]), |
| 456 | Some(Op::Upload { |
| 457 | name: "tahinli/app".into(), |
| 458 | id: "ID1".into(), |
| 459 | }) |
| 460 | ); |
| 461 | assert!(matches!( |
| 462 | parse_op(&["tahinli", "app", "blobs", "sha256:abc"]), |
| 463 | Some(Op::Blob { .. }) |
| 464 | )); |
| 465 | assert_eq!(parse_op(&["tahinli"]), None); |
| 466 | } |
| 467 | } |