forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·10.2 MiB·3cdd794·Tahinli·24 minutes ago·331 commits
| 1 | use forge_core::{Repo, Visibility}; |
| 2 | use futures_util::TryStreamExt; |
| 3 | use http_body::Frame; |
| 4 | use http_body_util::StreamBody; |
| 5 | use tokio_util::io::ReaderStream; |
| 6 | use topcoat::context::{Cx, context}; |
| 7 | use topcoat::router::request::method; |
| 8 | use topcoat::router::response::Response; |
| 9 | use topcoat::router::{ |
| 10 | Body, Method, RouteFuture, StatusCode, parse_query_params, path_param_segment, |
| 11 | path_param_segments, |
| 12 | }; |
| 13 | |
| 14 | use crate::lfs::{has_object, object_path}; |
| 15 | use crate::lfs_pointer; |
| 16 | use crate::raw::{ |
| 17 | CACHE_NONE, Lookup, Meta, OCTET, TokenQuery, encode_path, finish, lookup, plain, resolve_repo, |
| 18 | signed_url, |
| 19 | }; |
| 20 | use crate::state::AppState; |
| 21 | |
| 22 | pub fn media_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String { |
| 23 | let encoded = format!( |
| 24 | "{}/{}/-/media/{}/{}", |
| 25 | encode_path(&repo.owner_name), |
| 26 | encode_path(&repo.name), |
| 27 | encode_path(rev), |
| 28 | encode_path(path) |
| 29 | ); |
| 30 | signed_url( |
| 31 | state, |
| 32 | &encoded, |
| 33 | &repo.id, |
| 34 | matches!(repo.visibility, Visibility::Private), |
| 35 | ) |
| 36 | } |
| 37 | |
| 38 | pub fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> { |
| 39 | Box::pin(async move { Ok(serve(cx).await) }) |
| 40 | } |
| 41 | |
| 42 | async fn serve(cx: &Cx) -> Response { |
| 43 | let state = context::<AppState>(cx).clone(); |
| 44 | let owner = path_param_segment(cx, "owner").to_owned(); |
| 45 | let name = path_param_segment(cx, "repo").to_owned(); |
| 46 | let rest = path_param_segments(cx, "rest") |
| 47 | .collect::<Vec<&str>>() |
| 48 | .join("/"); |
| 49 | let is_head = method(cx) == Method::HEAD; |
| 50 | let token = parse_query_params::<TokenQuery>(cx) |
| 51 | .ok() |
| 52 | .and_then(|query| query.token); |
| 53 | |
| 54 | let (repo, repo_dir, cache) = match resolve_repo(&state, &owner, &name, token.as_deref()).await |
| 55 | { |
| 56 | Ok(found) => found, |
| 57 | Err(response) => return response, |
| 58 | }; |
| 59 | |
| 60 | let looked = tokio::task::spawn_blocking(move || lookup(&repo_dir, &rest, None)).await; |
| 61 | let data = match looked { |
| 62 | Ok(Ok(Lookup::Inline { |
| 63 | symlink: false, |
| 64 | data, |
| 65 | .. |
| 66 | })) => data, |
| 67 | Ok(Ok(_)) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None), |
| 68 | Ok(Err(e)) => { |
| 69 | tracing::error!(error = %e, "media: lookup failed"); |
| 70 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 71 | } |
| 72 | Err(e) => { |
| 73 | tracing::error!(error = %e, "media: lookup task failed"); |
| 74 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 75 | } |
| 76 | }; |
| 77 | |
| 78 | let Some(pointer) = lfs_pointer::parse(&data) else { |
| 79 | return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); |
| 80 | }; |
| 81 | let size = match has_object(&state, &repo.id, &pointer.oid).await { |
| 82 | Ok(Some(size)) => size, |
| 83 | Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None), |
| 84 | Err(e) => { |
| 85 | tracing::error!(error = %e, "media: object link lookup failed"); |
| 86 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 87 | } |
| 88 | }; |
| 89 | |
| 90 | let file = match tokio::fs::File::open(object_path(&state.config.data_dir, &pointer.oid)).await |
| 91 | { |
| 92 | Ok(file) => file, |
| 93 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 94 | return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); |
| 95 | } |
| 96 | Err(e) => { |
| 97 | tracing::error!(error = %e, "media: failed to open object"); |
| 98 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 99 | } |
| 100 | }; |
| 101 | let on_disk = match file.metadata().await { |
| 102 | Ok(meta) => meta.len(), |
| 103 | Err(e) => { |
| 104 | tracing::error!(error = %e, "media: object metadata failed"); |
| 105 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 106 | } |
| 107 | }; |
| 108 | if on_disk != size { |
| 109 | tracing::error!(oid = %pointer.oid, on_disk, size, "media: object size differs from its link"); |
| 110 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 111 | } |
| 112 | |
| 113 | let meta = Meta { |
| 114 | content_type: OCTET, |
| 115 | attachment: true, |
| 116 | len: size, |
| 117 | }; |
| 118 | if is_head { |
| 119 | return finish( |
| 120 | StatusCode::OK, |
| 121 | Body::empty(), |
| 122 | &pointer.oid, |
| 123 | cache, |
| 124 | Some(meta), |
| 125 | ); |
| 126 | } |
| 127 | let chunks = ReaderStream::new(file).map_ok(Frame::data); |
| 128 | let body = Body::new(StreamBody::new(chunks)); |
| 129 | finish(StatusCode::OK, body, &pointer.oid, cache, Some(meta)) |
| 130 | } |
| 131 | |
| 132 | #[cfg(test)] |
| 133 | mod tests { |
| 134 | use super::*; |
| 135 | |
| 136 | use crate::raw::now_unix; |
| 137 | use forge_core::raw_token::{sign_raw, verify_raw}; |
| 138 | use sha2::{Digest, Sha256}; |
| 139 | use topcoat::router::Router; |
| 140 | use topcoat::router::request::Request; |
| 141 | |
| 142 | use crate::raw::router; |
| 143 | |
| 144 | const POINTER_HEADER: &str = "version https://git-lfs.github.com/spec/v1"; |
| 145 | |
| 146 | struct Fixture { |
| 147 | _tmp: tempfile::TempDir, |
| 148 | state: AppState, |
| 149 | router: Router, |
| 150 | public: Repo, |
| 151 | private: Repo, |
| 152 | object: Vec<u8>, |
| 153 | oid: String, |
| 154 | } |
| 155 | |
| 156 | fn sha256_hex(data: &[u8]) -> String { |
| 157 | hex::encode(Sha256::digest(data)) |
| 158 | } |
| 159 | |
| 160 | fn pointer_text(oid: &str, size: usize) -> Vec<u8> { |
| 161 | format!("{POINTER_HEADER}\noid sha256:{oid}\nsize {size}\n").into_bytes() |
| 162 | } |
| 163 | |
| 164 | fn git(dir: &std::path::Path, args: &[&str]) { |
| 165 | let out = std::process::Command::new("git") |
| 166 | .arg("-C") |
| 167 | .arg(dir) |
| 168 | .args(["-c", "commit.gpgsign=false"]) |
| 169 | .args(args) |
| 170 | .env("GIT_AUTHOR_NAME", "test") |
| 171 | .env("GIT_AUTHOR_EMAIL", "test@example.com") |
| 172 | .env("GIT_COMMITTER_NAME", "test") |
| 173 | .env("GIT_COMMITTER_EMAIL", "test@example.com") |
| 174 | .output() |
| 175 | .expect("git runs"); |
| 176 | assert!( |
| 177 | out.status.success(), |
| 178 | "git {args:?} failed: {}", |
| 179 | String::from_utf8_lossy(&out.stderr) |
| 180 | ); |
| 181 | } |
| 182 | |
| 183 | fn populate(work: &std::path::Path, bare: &std::path::Path, files: &[(&str, Vec<u8>)]) { |
| 184 | std::fs::create_dir_all(work).expect("mkdir work"); |
| 185 | git(work, &["init", "-q", "-b", "main"]); |
| 186 | for (rel, contents) in files { |
| 187 | std::fs::write(work.join(rel), contents).expect("write file"); |
| 188 | } |
| 189 | git(work, &["add", "-A"]); |
| 190 | git(work, &["commit", "-q", "-m", "init"]); |
| 191 | git(work, &["push", "-q", bare.to_str().expect("utf8"), "main"]); |
| 192 | } |
| 193 | |
| 194 | async fn fixture() -> Fixture { |
| 195 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 196 | let data_dir = tmp.path().join("data"); |
| 197 | std::fs::create_dir_all(&data_dir).expect("data dir"); |
| 198 | let data_dir = data_dir.canonicalize().expect("canonical data dir"); |
| 199 | let mut config = crate::test_support::test_config(&data_dir); |
| 200 | config.user_content_base_url = "http://127.0.0.1:7661".into(); |
| 201 | let state = AppState { |
| 202 | config: std::sync::Arc::new(config), |
| 203 | ..crate::test_support::test_state(&data_dir).await |
| 204 | }; |
| 205 | let store = state.store.clone(); |
| 206 | let owner = store |
| 207 | .create_user("tahinli", None, "unused", false) |
| 208 | .await |
| 209 | .expect("user"); |
| 210 | let public = store |
| 211 | .create_repo(&owner.id, "pub", "", forge_core::Visibility::Public, "main") |
| 212 | .await |
| 213 | .expect("public repo"); |
| 214 | let private = store |
| 215 | .create_repo( |
| 216 | &owner.id, |
| 217 | "priv", |
| 218 | "", |
| 219 | forge_core::Visibility::Private, |
| 220 | "main", |
| 221 | ) |
| 222 | .await |
| 223 | .expect("private repo"); |
| 224 | for repo in [&public, &private] { |
| 225 | let bare = forge_git::repo::repo_path(&data_dir, &repo.id).expect("repo path"); |
| 226 | forge_git::repo::init_bare(&state.git, &bare, "main") |
| 227 | .await |
| 228 | .expect("init bare"); |
| 229 | } |
| 230 | |
| 231 | let object = b"lfs object bytes\n".to_vec(); |
| 232 | let oid = sha256_hex(&object); |
| 233 | let missing_oid = sha256_hex(b"never stored"); |
| 234 | let stored_pointer = pointer_text(&oid, object.len()); |
| 235 | let missing_pointer = pointer_text(&missing_oid, 12); |
| 236 | let files: Vec<(&str, Vec<u8>)> = vec![ |
| 237 | ("big.bin", stored_pointer.clone()), |
| 238 | ("missing.bin", missing_pointer), |
| 239 | ("plain.txt", b"just text\n".to_vec()), |
| 240 | ]; |
| 241 | let pub_bare = forge_git::repo::repo_path(&data_dir, &public.id).expect("path"); |
| 242 | populate(&tmp.path().join("work-pub"), &pub_bare, &files); |
| 243 | let priv_bare = forge_git::repo::repo_path(&data_dir, &private.id).expect("path"); |
| 244 | populate( |
| 245 | &tmp.path().join("work-priv"), |
| 246 | &priv_bare, |
| 247 | &[("big.bin", stored_pointer)], |
| 248 | ); |
| 249 | |
| 250 | for repo in [&public, &private] { |
| 251 | store |
| 252 | .insert_lfs_object(&repo.id, &oid, object.len() as u64) |
| 253 | .await |
| 254 | .expect("link object"); |
| 255 | } |
| 256 | let path = object_path(&data_dir, &oid); |
| 257 | std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir objects"); |
| 258 | std::fs::write(&path, &object).expect("write object"); |
| 259 | |
| 260 | let router = router(state.clone()); |
| 261 | Fixture { |
| 262 | _tmp: tmp, |
| 263 | state, |
| 264 | router, |
| 265 | public, |
| 266 | private, |
| 267 | object, |
| 268 | oid, |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | async fn get(router: &Router, method: &str, uri: &str) -> Response { |
| 273 | let req = Request::builder() |
| 274 | .method(method) |
| 275 | .uri(uri) |
| 276 | .body(Body::empty()) |
| 277 | .expect("request"); |
| 278 | router.handle(req).await |
| 279 | } |
| 280 | |
| 281 | fn header_str(res: &Response, name: &str) -> String { |
| 282 | res.headers() |
| 283 | .get(name) |
| 284 | .and_then(|v| v.to_str().ok()) |
| 285 | .unwrap_or_default() |
| 286 | .to_owned() |
| 287 | } |
| 288 | |
| 289 | async fn body_bytes(res: Response) -> Vec<u8> { |
| 290 | topcoat::router::to_bytes(res.into_body(), usize::MAX) |
| 291 | .await |
| 292 | .expect("body") |
| 293 | .to_vec() |
| 294 | } |
| 295 | |
| 296 | #[tokio::test] |
| 297 | async fn public_media_serves_downloads_heads_and_404s() { |
| 298 | let fx = fixture().await; |
| 299 | |
| 300 | let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/big.bin").await; |
| 301 | assert_eq!(res.status(), StatusCode::OK, "linked object"); |
| 302 | assert_eq!( |
| 303 | header_str(&res, "content-disposition"), |
| 304 | "attachment", |
| 305 | "linked object disposition" |
| 306 | ); |
| 307 | assert_eq!( |
| 308 | header_str(&res, "x-content-type-options"), |
| 309 | "nosniff", |
| 310 | "linked object nosniff" |
| 311 | ); |
| 312 | assert_eq!( |
| 313 | header_str(&res, "content-type"), |
| 314 | OCTET, |
| 315 | "linked object content type" |
| 316 | ); |
| 317 | assert_eq!( |
| 318 | header_str(&res, "content-length"), |
| 319 | fx.object.len().to_string(), |
| 320 | "linked object length" |
| 321 | ); |
| 322 | assert_eq!( |
| 323 | header_str(&res, "etag"), |
| 324 | format!("\"{}\"", fx.oid), |
| 325 | "linked object etag" |
| 326 | ); |
| 327 | assert_eq!(body_bytes(res).await, fx.object, "linked object body"); |
| 328 | |
| 329 | let res = get(&fx.router, "HEAD", "/tahinli/pub/-/media/main/big.bin").await; |
| 330 | assert_eq!(res.status(), StatusCode::OK, "head"); |
| 331 | assert_eq!( |
| 332 | header_str(&res, "content-length"), |
| 333 | fx.object.len().to_string(), |
| 334 | "head length" |
| 335 | ); |
| 336 | assert!(body_bytes(res).await.is_empty(), "head body"); |
| 337 | |
| 338 | let res = get(&fx.router, "GET", "/tahinli/pub/-/media/main/missing.bin").await; |
| 339 | assert_eq!(res.status(), StatusCode::NOT_FOUND, "unlinked object"); |
| 340 | |
| 341 | let text = get(&fx.router, "GET", "/tahinli/pub/-/media/main/plain.txt").await; |
| 342 | assert_eq!(text.status(), StatusCode::NOT_FOUND, "non-pointer"); |
| 343 | let absent = get(&fx.router, "GET", "/tahinli/pub/-/media/main/nope.bin").await; |
| 344 | assert_eq!(absent.status(), StatusCode::NOT_FOUND, "absent path"); |
| 345 | let unknown_repo = get(&fx.router, "GET", "/tahinli/nope/-/media/main/big.bin").await; |
| 346 | assert_eq!(unknown_repo.status(), StatusCode::NOT_FOUND, "unknown repo"); |
| 347 | } |
| 348 | |
| 349 | #[tokio::test] |
| 350 | async fn private_media_needs_a_valid_token_and_urls_sign_private_repos_only() { |
| 351 | let fx = fixture().await; |
| 352 | let path = "/tahinli/priv/-/media/main/big.bin"; |
| 353 | |
| 354 | let none = get(&fx.router, "GET", path).await; |
| 355 | assert_eq!(none.status(), StatusCode::NOT_FOUND, "no token"); |
| 356 | |
| 357 | let now = now_unix(); |
| 358 | let valid = sign_raw(&fx.state.key, &fx.private.id, now + 60); |
| 359 | let ok = get(&fx.router, "GET", &format!("{path}?token={valid}")).await; |
| 360 | assert_eq!(ok.status(), StatusCode::OK, "valid token"); |
| 361 | assert_eq!(body_bytes(ok).await, fx.object, "valid token body"); |
| 362 | |
| 363 | let expired = sign_raw(&fx.state.key, &fx.private.id, now - 1); |
| 364 | let res = get(&fx.router, "GET", &format!("{path}?token={expired}")).await; |
| 365 | assert_eq!(res.status(), StatusCode::NOT_FOUND, "expired token"); |
| 366 | |
| 367 | let other = sign_raw(&fx.state.key, &fx.public.id, now + 60); |
| 368 | let res = get(&fx.router, "GET", &format!("{path}?token={other}")).await; |
| 369 | assert_eq!( |
| 370 | res.status(), |
| 371 | StatusCode::NOT_FOUND, |
| 372 | "token for another repo" |
| 373 | ); |
| 374 | |
| 375 | let public = media_url(&fx.state, &fx.public, "main", "a b/big.bin"); |
| 376 | assert_eq!( |
| 377 | public, "http://127.0.0.1:7661/tahinli/pub/-/media/main/a%20b/big.bin", |
| 378 | "public url" |
| 379 | ); |
| 380 | |
| 381 | let private = media_url(&fx.state, &fx.private, "main", "big.bin"); |
| 382 | assert!( |
| 383 | private.starts_with("http://127.0.0.1:7661/tahinli/priv/-/media/main/big.bin?token="), |
| 384 | "private url prefix" |
| 385 | ); |
| 386 | let token = private |
| 387 | .split_once("?token=") |
| 388 | .map(|(_, t)| t) |
| 389 | .unwrap_or_default(); |
| 390 | assert!( |
| 391 | verify_raw(&fx.state.key, token, &fx.private.id, now_unix()), |
| 392 | "private url token" |
| 393 | ); |
| 394 | } |
| 395 | |
| 396 | #[tokio::test] |
| 397 | async fn branch_named_media_does_not_shadow_the_media_route() { |
| 398 | let fx = fixture().await; |
| 399 | let work = fx._tmp.path().join("work-pub"); |
| 400 | let bare = forge_git::repo::repo_path(&fx.state.config.data_dir, &fx.public.id) |
| 401 | .expect("repo path"); |
| 402 | git(&work, &["checkout", "-q", "-b", "media"]); |
| 403 | std::fs::write(work.join("README.md"), "# On a media branch\n").expect("write README"); |
| 404 | git(&work, &["add", "-A"]); |
| 405 | git(&work, &["commit", "-q", "-m", "media branch"]); |
| 406 | git( |
| 407 | &work, |
| 408 | &["push", "-q", bare.to_str().expect("utf8"), "media"], |
| 409 | ); |
| 410 | |
| 411 | let readme = get(&fx.router, "GET", "/tahinli/pub/media/README.md").await; |
| 412 | assert_eq!(readme.status(), StatusCode::OK, "branch raw file"); |
| 413 | assert_eq!( |
| 414 | body_bytes(readme).await, |
| 415 | b"# On a media branch\n".to_vec(), |
| 416 | "branch raw body" |
| 417 | ); |
| 418 | |
| 419 | let dash = get(&fx.router, "GET", "/tahinli/pub/-/README.md").await; |
| 420 | assert_eq!(dash.status(), StatusCode::NOT_FOUND, "dash is not a ref"); |
| 421 | |
| 422 | let url = media_url(&fx.state, &fx.public, "main", "big.bin"); |
| 423 | let path = url |
| 424 | .strip_prefix("http://127.0.0.1:7661") |
| 425 | .expect("configured base"); |
| 426 | let media = get(&fx.router, "GET", path).await; |
| 427 | assert_eq!(media.status(), StatusCode::OK, "media route still wins"); |
| 428 | assert_eq!(body_bytes(media).await, fx.object, "media body"); |
| 429 | } |
| 430 | } |