| 1 | |
| 2 | |
| 3 | |
| 4 | pub mod media; |
| 5 | pub mod snippet_raw; |
| 6 | |
| 7 | use std::path::Path; |
| 8 | use std::process::Stdio; |
| 9 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 10 | |
| 11 | use bytes::Bytes; |
| 12 | use forge_core::raw_token::{sign_raw, verify_raw}; |
| 13 | use forge_core::{Repo, Visibility}; |
| 14 | use forge_git::GitCommand; |
| 15 | use forge_git::browse::{self, EntryKind}; |
| 16 | use futures_util::{StreamExt, TryStreamExt, stream}; |
| 17 | use http_body::Frame; |
| 18 | use http_body_util::StreamBody; |
| 19 | use serde::Deserialize; |
| 20 | use tokio::io::AsyncReadExt; |
| 21 | use tokio::process::Child; |
| 22 | use tokio_util::io::ReaderStream; |
| 23 | use topcoat::context::{Cx, context}; |
| 24 | use topcoat::router::request::{headers, method}; |
| 25 | use topcoat::router::response::Response; |
| 26 | use topcoat::router::{ |
| 27 | Body, Compression, HeaderName, HeaderValue, Method, RouteFn, RouteFuture, Router, StatusCode, |
| 28 | header, parse_query_params, path_param_segment, path_param_segments, |
| 29 | }; |
| 30 | |
| 31 | use crate::internal::is_valid_oid; |
| 32 | use crate::state::AppState; |
| 33 | |
| 34 | |
| 35 | const MAX_INLINE_BYTES: u64 = 8 * 1024 * 1024; |
| 36 | |
| 37 | const SNIFF_BYTES: usize = 8000; |
| 38 | |
| 39 | pub const LINK_TTL_SECS: i64 = 600; |
| 40 | |
| 41 | const CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox"; |
| 42 | const CORP: &str = "cross-origin"; |
| 43 | |
| 44 | |
| 45 | pub const CACHE_PRIVATE: &str = "private, no-cache"; |
| 46 | pub const CACHE_PUBLIC: &str = "public, no-cache"; |
| 47 | pub const CACHE_NONE: &str = "no-store"; |
| 48 | const TEXT: &str = "text/plain; charset=utf-8"; |
| 49 | pub const OCTET: &str = "application/octet-stream"; |
| 50 | |
| 51 | |
| 52 | |
| 53 | pub fn raw_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String { |
| 54 | let base = state.config.user_content_base_url.trim_end_matches('/'); |
| 55 | let mut url = format!( |
| 56 | "{base}/{}/{}/{}", |
| 57 | encode_path(&repo.owner_name), |
| 58 | encode_path(&repo.name), |
| 59 | encode_path(rev) |
| 60 | ); |
| 61 | if !path.is_empty() { |
| 62 | url.push('/'); |
| 63 | url.push_str(&encode_path(path)); |
| 64 | } |
| 65 | if matches!(repo.visibility, Visibility::Private) { |
| 66 | let expires = now_unix().saturating_add(LINK_TTL_SECS); |
| 67 | url.push_str("?token="); |
| 68 | url.push_str(&sign_raw(&state.key, &repo.id, expires)); |
| 69 | } |
| 70 | url |
| 71 | } |
| 72 | |
| 73 | |
| 74 | pub fn encode_path(value: &str) -> String { |
| 75 | value |
| 76 | .split('/') |
| 77 | .map(encode_segment) |
| 78 | .collect::<Vec<_>>() |
| 79 | .join("/") |
| 80 | } |
| 81 | |
| 82 | |
| 83 | fn encode_segment(segment: &str) -> String { |
| 84 | let mut out = String::with_capacity(segment.len()); |
| 85 | for byte in segment.bytes() { |
| 86 | if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { |
| 87 | out.push(char::from(byte)); |
| 88 | } else { |
| 89 | out.push_str(&format!("%{byte:02X}")); |
| 90 | } |
| 91 | } |
| 92 | out |
| 93 | } |
| 94 | |
| 95 | |
| 96 | pub fn router(state: AppState) -> Router { |
| 97 | Router::builder() |
| 98 | .route(RouteFn::new( |
| 99 | vec![Method::GET, Method::HEAD], |
| 100 | "/{owner}/{repo}/{*rest}", |
| 101 | raw_file, |
| 102 | )) |
| 103 | |
| 104 | |
| 105 | |
| 106 | .route(RouteFn::new( |
| 107 | vec![Method::GET, Method::HEAD], |
| 108 | "/{owner}/{repo}/-/media/{*rest}", |
| 109 | crate::raw::media::media_file, |
| 110 | )) |
| 111 | |
| 112 | .route(RouteFn::new( |
| 113 | vec![Method::GET, Method::HEAD], |
| 114 | "/-/snippets/{id}/{*rest}", |
| 115 | crate::raw::snippet_raw::snippet_file, |
| 116 | )) |
| 117 | .route(RouteFn::new(Method::GET, "/healthz", healthz)) |
| 118 | |
| 119 | .with(Compression::disable()) |
| 120 | .with(state) |
| 121 | .build() |
| 122 | } |
| 123 | |
| 124 | #[derive(Deserialize)] |
| 125 | struct TokenQuery { |
| 126 | token: Option<String>, |
| 127 | } |
| 128 | |
| 129 | fn healthz(_cx: &Cx, _body: topcoat::router::Body) -> RouteFuture<'_> { |
| 130 | Box::pin(async { |
| 131 | let mut res = Response::new(Body::from("ok")); |
| 132 | *res.status_mut() = StatusCode::OK; |
| 133 | Ok(res) |
| 134 | }) |
| 135 | } |
| 136 | |
| 137 | fn raw_file(cx: &Cx, _body: topcoat::router::Body) -> RouteFuture<'_> { |
| 138 | Box::pin(async move { Ok(serve(cx).await) }) |
| 139 | } |
| 140 | |
| 141 | |
| 142 | async fn serve(cx: &Cx) -> Response { |
| 143 | let state = context::<AppState>(cx).clone(); |
| 144 | let owner = path_param_segment(cx, "owner").to_owned(); |
| 145 | let name = path_param_segment(cx, "repo").to_owned(); |
| 146 | let rest = path_param_segments(cx, "rest") |
| 147 | .collect::<Vec<&str>>() |
| 148 | .join("/"); |
| 149 | |
| 150 | |
| 151 | if rest.split('/').next() == Some("-") { |
| 152 | return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); |
| 153 | } |
| 154 | let is_head = method(cx) == Method::HEAD; |
| 155 | let token = parse_query_params::<TokenQuery>(cx) |
| 156 | .ok() |
| 157 | .and_then(|query| query.token); |
| 158 | let if_none_match = headers(cx) |
| 159 | .get(header::IF_NONE_MATCH) |
| 160 | .and_then(|v| v.to_str().ok()) |
| 161 | .map(str::to_owned); |
| 162 | |
| 163 | let repo = match state.store.repo_by_owner_and_name(&owner, &name).await { |
| 164 | Ok(Some(repo)) => repo, |
| 165 | |
| 166 | Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None), |
| 167 | Err(e) => { |
| 168 | tracing::error!(error = %e, "raw: repo lookup failed"); |
| 169 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 170 | } |
| 171 | }; |
| 172 | let cache = match repo.visibility { |
| 173 | Visibility::Public => CACHE_PUBLIC, |
| 174 | Visibility::Private => { |
| 175 | let valid = token |
| 176 | .as_deref() |
| 177 | .is_some_and(|t| verify_raw(&state.key, t, &repo.id, now_unix())); |
| 178 | if !valid { |
| 179 | return plain(StatusCode::NOT_FOUND, CACHE_NONE, None); |
| 180 | } |
| 181 | CACHE_PRIVATE |
| 182 | } |
| 183 | }; |
| 184 | |
| 185 | let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { |
| 186 | Ok(path) => path, |
| 187 | Err(e) => { |
| 188 | tracing::error!(error = %e, "raw: repo path failed"); |
| 189 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 190 | } |
| 191 | }; |
| 192 | |
| 193 | let lookup_dir = repo_dir.clone(); |
| 194 | let lookup_rest = rest.clone(); |
| 195 | let looked = tokio::task::spawn_blocking(move || { |
| 196 | lookup(&lookup_dir, &lookup_rest, if_none_match.as_deref()) |
| 197 | }) |
| 198 | .await; |
| 199 | let looked = match looked { |
| 200 | Ok(Ok(found)) => found, |
| 201 | Ok(Err(e)) => { |
| 202 | tracing::error!(error = %e, "raw: lookup failed"); |
| 203 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 204 | } |
| 205 | Err(e) => { |
| 206 | tracing::error!(error = %e, "raw: lookup task failed"); |
| 207 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 208 | } |
| 209 | }; |
| 210 | |
| 211 | let file_name = rest.rsplit('/').next().unwrap_or(""); |
| 212 | match looked { |
| 213 | Lookup::Missing => plain(StatusCode::NOT_FOUND, CACHE_NONE, None), |
| 214 | Lookup::NotModified { oid } => { |
| 215 | finish(StatusCode::NOT_MODIFIED, Body::empty(), &oid, cache, None) |
| 216 | } |
| 217 | Lookup::Inline { oid, symlink, data } => { |
| 218 | let (content_type, attachment) = if symlink { |
| 219 | (TEXT, false) |
| 220 | } else { |
| 221 | classify(file_name, &data, true) |
| 222 | }; |
| 223 | let meta = Meta { |
| 224 | content_type, |
| 225 | attachment, |
| 226 | len: data.len() as u64, |
| 227 | }; |
| 228 | let body = if is_head { |
| 229 | Body::empty() |
| 230 | } else { |
| 231 | Body::from(Bytes::from(data)) |
| 232 | }; |
| 233 | finish(StatusCode::OK, body, &oid, cache, Some(meta)) |
| 234 | } |
| 235 | Lookup::Stream { oid, size } => { |
| 236 | let mut child = match spawn_cat_file(&state, &repo_dir, &oid) { |
| 237 | Ok(child) => child, |
| 238 | Err(e) => { |
| 239 | tracing::error!(error = %e, "raw: failed to start git cat-file"); |
| 240 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 241 | } |
| 242 | }; |
| 243 | let Some(mut stdout) = child.stdout.take() else { |
| 244 | tracing::error!("raw: git cat-file has no stdout"); |
| 245 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 246 | }; |
| 247 | let mut sample = Vec::with_capacity(SNIFF_BYTES); |
| 248 | if let Err(e) = (&mut stdout) |
| 249 | .take(SNIFF_BYTES as u64) |
| 250 | .read_to_end(&mut sample) |
| 251 | .await |
| 252 | { |
| 253 | tracing::error!(error = %e, "raw: reading blob sample failed"); |
| 254 | return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None); |
| 255 | } |
| 256 | let (content_type, attachment) = classify(file_name, &sample, false); |
| 257 | let meta = Meta { |
| 258 | content_type, |
| 259 | attachment, |
| 260 | len: size, |
| 261 | }; |
| 262 | if is_head { |
| 263 | |
| 264 | drop(child); |
| 265 | return finish(StatusCode::OK, Body::empty(), &oid, cache, Some(meta)); |
| 266 | } |
| 267 | |
| 268 | let chunks = stream::iter([Ok::<Bytes, std::io::Error>(Bytes::from(sample))]) |
| 269 | .chain(ReaderStream::new(stdout)) |
| 270 | .map_ok(Frame::data) |
| 271 | .map(move |chunk| { |
| 272 | let _ = &child; |
| 273 | chunk |
| 274 | }); |
| 275 | let body = Body::new(StreamBody::new(chunks)); |
| 276 | finish(StatusCode::OK, body, &oid, cache, Some(meta)) |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | |
| 282 | pub enum Lookup { |
| 283 | Missing, |
| 284 | NotModified { |
| 285 | oid: String, |
| 286 | }, |
| 287 | Inline { |
| 288 | oid: String, |
| 289 | symlink: bool, |
| 290 | data: Vec<u8>, |
| 291 | }, |
| 292 | Stream { |
| 293 | oid: String, |
| 294 | size: u64, |
| 295 | }, |
| 296 | } |
| 297 | |
| 298 | |
| 299 | pub fn lookup( |
| 300 | repo_dir: &Path, |
| 301 | rest: &str, |
| 302 | if_none_match: Option<&str>, |
| 303 | ) -> forge_git::Result<Lookup> { |
| 304 | let Some((_ref_name, commit, path)) = browse::split_ref_and_path(repo_dir, rest)? else { |
| 305 | return Ok(Lookup::Missing); |
| 306 | }; |
| 307 | if path.is_empty() { |
| 308 | return Ok(Lookup::Missing); |
| 309 | } |
| 310 | let (parent, name) = path.rsplit_once('/').unwrap_or(("", path.as_str())); |
| 311 | let Some(entries) = browse::read_tree(repo_dir, &commit, parent)? else { |
| 312 | return Ok(Lookup::Missing); |
| 313 | }; |
| 314 | let Some(entry) = entries.into_iter().find(|e| e.name == name) else { |
| 315 | return Ok(Lookup::Missing); |
| 316 | }; |
| 317 | let symlink = match entry.kind { |
| 318 | EntryKind::Blob | EntryKind::Executable => false, |
| 319 | EntryKind::Symlink => true, |
| 320 | EntryKind::Tree | EntryKind::Submodule => return Ok(Lookup::Missing), |
| 321 | }; |
| 322 | let oid = entry.oid; |
| 323 | let etag = format!("\"{oid}\""); |
| 324 | if if_none_match.is_some_and(|value| etag_matches(value, &etag)) { |
| 325 | return Ok(Lookup::NotModified { oid }); |
| 326 | } |
| 327 | if !symlink |
| 328 | && let Some(size) = entry.size |
| 329 | && size > MAX_INLINE_BYTES |
| 330 | { |
| 331 | return Ok(Lookup::Stream { oid, size }); |
| 332 | } |
| 333 | let max_bytes = usize::try_from(MAX_INLINE_BYTES).unwrap_or(usize::MAX); |
| 334 | let Some(blob) = browse::read_blob(repo_dir, &commit, &path, max_bytes)? else { |
| 335 | return Ok(Lookup::Missing); |
| 336 | }; |
| 337 | Ok(Lookup::Inline { |
| 338 | oid: blob.oid, |
| 339 | symlink, |
| 340 | data: blob.data, |
| 341 | }) |
| 342 | } |
| 343 | |
| 344 | |
| 345 | fn spawn_cat_file(state: &AppState, repo_dir: &Path, oid: &str) -> std::io::Result<Child> { |
| 346 | if !is_valid_oid(oid) { |
| 347 | return Err(std::io::Error::other("invalid object id")); |
| 348 | } |
| 349 | let mut cmd = GitCommand::new(&state.git, "cat-file") |
| 350 | .git_dir(repo_dir) |
| 351 | .arg("blob") |
| 352 | .user_arg(oid) |
| 353 | .map_err(|e| std::io::Error::other(e.to_string()))? |
| 354 | .into_tokio(); |
| 355 | cmd.stdout(Stdio::piped()).stderr(Stdio::null()); |
| 356 | cmd.spawn() |
| 357 | } |
| 358 | |
| 359 | |
| 360 | fn classify(file_name: &str, sample: &[u8], complete: bool) -> (&'static str, bool) { |
| 361 | let ext = file_name |
| 362 | .rsplit_once('.') |
| 363 | .map(|(_, ext)| ext.to_ascii_lowercase()) |
| 364 | .unwrap_or_default(); |
| 365 | if let Some(image) = image_type(&ext) { |
| 366 | return (image, false); |
| 367 | } |
| 368 | let attachment = matches!(ext.as_str(), "svg" | "html" | "htm" | "xhtml" | "xml"); |
| 369 | if is_text(sample, complete) { |
| 370 | (TEXT, attachment) |
| 371 | } else { |
| 372 | (OCTET, true) |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | fn image_type(ext: &str) -> Option<&'static str> { |
| 377 | Some(match ext { |
| 378 | "png" => "image/png", |
| 379 | "jpg" | "jpeg" => "image/jpeg", |
| 380 | "gif" => "image/gif", |
| 381 | "webp" => "image/webp", |
| 382 | "avif" => "image/avif", |
| 383 | "ico" => "image/vnd.microsoft.icon", |
| 384 | _ => return None, |
| 385 | }) |
| 386 | } |
| 387 | |
| 388 | |
| 389 | |
| 390 | fn is_text(sample: &[u8], complete: bool) -> bool { |
| 391 | let probe = &sample[..sample.len().min(SNIFF_BYTES)]; |
| 392 | if probe.contains(&0) { |
| 393 | return false; |
| 394 | } |
| 395 | match std::str::from_utf8(sample) { |
| 396 | Ok(_) => true, |
| 397 | Err(e) => !complete && e.error_len().is_none(), |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | |
| 402 | fn etag_matches(header_value: &str, etag: &str) -> bool { |
| 403 | header_value.split(',').map(str::trim).any(|candidate| { |
| 404 | candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag |
| 405 | }) |
| 406 | } |
| 407 | |
| 408 | pub struct Meta { |
| 409 | pub content_type: &'static str, |
| 410 | pub attachment: bool, |
| 411 | pub len: u64, |
| 412 | } |
| 413 | |
| 414 | |
| 415 | pub fn finish( |
| 416 | status: StatusCode, |
| 417 | body: Body, |
| 418 | oid: &str, |
| 419 | cache: &'static str, |
| 420 | meta: Option<Meta>, |
| 421 | ) -> Response { |
| 422 | let mut res = Response::new(body); |
| 423 | *res.status_mut() = status; |
| 424 | let h = res.headers_mut(); |
| 425 | h.insert( |
| 426 | HeaderName::from_static("x-content-type-options"), |
| 427 | HeaderValue::from_static("nosniff"), |
| 428 | ); |
| 429 | h.insert( |
| 430 | header::CONTENT_SECURITY_POLICY, |
| 431 | HeaderValue::from_static(CSP), |
| 432 | ); |
| 433 | h.insert( |
| 434 | HeaderName::from_static("cross-origin-resource-policy"), |
| 435 | HeaderValue::from_static(CORP), |
| 436 | ); |
| 437 | h.insert( |
| 438 | header::REFERRER_POLICY, |
| 439 | HeaderValue::from_static("no-referrer"), |
| 440 | ); |
| 441 | h.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); |
| 442 | if let Ok(etag) = HeaderValue::from_str(&format!("\"{oid}\"")) { |
| 443 | h.insert(header::ETAG, etag); |
| 444 | } |
| 445 | if let Some(meta) = meta { |
| 446 | h.insert( |
| 447 | header::CONTENT_TYPE, |
| 448 | HeaderValue::from_static(meta.content_type), |
| 449 | ); |
| 450 | h.insert(header::CONTENT_LENGTH, HeaderValue::from(meta.len)); |
| 451 | if meta.attachment { |
| 452 | h.insert( |
| 453 | header::CONTENT_DISPOSITION, |
| 454 | HeaderValue::from_static("attachment"), |
| 455 | ); |
| 456 | } |
| 457 | } |
| 458 | res |
| 459 | } |
| 460 | |
| 461 | |
| 462 | pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str>) -> Response { |
| 463 | let text = body.unwrap_or(match status { |
| 464 | StatusCode::NOT_FOUND => "not found", |
| 465 | _ => "internal error", |
| 466 | }); |
| 467 | let mut res = finish(status, Body::from(text), "", cache, None); |
| 468 | res.headers_mut().remove(header::ETAG); |
| 469 | res.headers_mut() |
| 470 | .insert(header::CONTENT_TYPE, HeaderValue::from_static(TEXT)); |
| 471 | res |
| 472 | } |
| 473 | |
| 474 | pub fn now_unix() -> i64 { |
| 475 | SystemTime::now() |
| 476 | .duration_since(UNIX_EPOCH) |
| 477 | .ok() |
| 478 | .and_then(|d| i64::try_from(d.as_secs()).ok()) |
| 479 | .unwrap_or(0) |
| 480 | } |
| 481 | |
| 482 | #[cfg(test)] |
| 483 | mod tests { |
| 484 | use super::*; |
| 485 | |
| 486 | use topcoat::router::Body as RouterBody; |
| 487 | use topcoat::router::request::Request; |
| 488 | |
| 489 | const KEY: [u8; 32] = [7; 32]; |
| 490 | |
| 491 | struct Fixture { |
| 492 | _tmp: tempfile::TempDir, |
| 493 | state: AppState, |
| 494 | router: Router, |
| 495 | public: Repo, |
| 496 | private: Repo, |
| 497 | } |
| 498 | |
| 499 | fn git(dir: &Path, args: &[&str]) { |
| 500 | let out = std::process::Command::new("git") |
| 501 | .arg("-C") |
| 502 | .arg(dir) |
| 503 | .args(["-c", "commit.gpgsign=false"]) |
| 504 | .args(args) |
| 505 | .env("GIT_AUTHOR_NAME", "test") |
| 506 | .env("GIT_AUTHOR_EMAIL", "test@example.com") |
| 507 | .env("GIT_COMMITTER_NAME", "test") |
| 508 | .env("GIT_COMMITTER_EMAIL", "test@example.com") |
| 509 | .output() |
| 510 | .expect("git runs"); |
| 511 | assert!( |
| 512 | out.status.success(), |
| 513 | "git {args:?} failed: {}", |
| 514 | String::from_utf8_lossy(&out.stderr) |
| 515 | ); |
| 516 | } |
| 517 | |
| 518 | |
| 519 | fn populate(work: &Path, bare: &Path, files: &[(&str, Vec<u8>)]) { |
| 520 | std::fs::create_dir_all(work).expect("mkdir work"); |
| 521 | git(work, &["init", "-q", "-b", "main"]); |
| 522 | for (rel, contents) in files { |
| 523 | let path = work.join(rel); |
| 524 | std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); |
| 525 | std::fs::write(&path, contents).expect("write file"); |
| 526 | } |
| 527 | std::os::unix::fs::symlink("hello.txt", work.join("link")).expect("symlink"); |
| 528 | git(work, &["add", "-A"]); |
| 529 | git(work, &["commit", "-q", "-m", "init"]); |
| 530 | git(work, &["push", "-q", bare.to_str().expect("utf8"), "main"]); |
| 531 | } |
| 532 | |
| 533 | async fn fixture() -> Fixture { |
| 534 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 535 | let data_dir = tmp.path().join("data"); |
| 536 | std::fs::create_dir_all(&data_dir).expect("data dir"); |
| 537 | let data_dir = data_dir.canonicalize().expect("canonical data dir"); |
| 538 | let mut config = crate::test_support::test_config(&data_dir); |
| 539 | config.user_content_base_url = "http://127.0.0.1:7661".into(); |
| 540 | let state = crate::state::AppState { |
| 541 | config: std::sync::Arc::new(config), |
| 542 | ..crate::test_support::test_state(&data_dir).await |
| 543 | }; |
| 544 | let store = state.store.clone(); |
| 545 | let owner = store |
| 546 | .create_user("tahinli", None, "unused", false) |
| 547 | .await |
| 548 | .expect("user"); |
| 549 | let public = store |
| 550 | .create_repo(&owner.id, "pub", "", forge_core::Visibility::Public, "main") |
| 551 | .await |
| 552 | .expect("public repo"); |
| 553 | let private = store |
| 554 | .create_repo( |
| 555 | &owner.id, |
| 556 | "priv", |
| 557 | "", |
| 558 | forge_core::Visibility::Private, |
| 559 | "main", |
| 560 | ) |
| 561 | .await |
| 562 | .expect("private repo"); |
| 563 | let git_env = state.git.clone(); |
| 564 | for repo in [&public, &private] { |
| 565 | let bare = forge_git::repo::repo_path(&data_dir, &repo.id).expect("repo path"); |
| 566 | forge_git::repo::init_bare(&git_env, &bare, "main") |
| 567 | .await |
| 568 | .expect("init bare"); |
| 569 | } |
| 570 | |
| 571 | let big: Vec<u8> = b"0123456789abcdef\n" |
| 572 | .iter() |
| 573 | .cycle() |
| 574 | .take(9 * 1024 * 1024) |
| 575 | .copied() |
| 576 | .collect(); |
| 577 | let pub_bare = forge_git::repo::repo_path(&data_dir, &public.id).expect("path"); |
| 578 | populate( |
| 579 | &tmp.path().join("work-pub"), |
| 580 | &pub_bare, |
| 581 | &[ |
| 582 | ("hello.txt", b"hello raw\n".to_vec()), |
| 583 | ( |
| 584 | "page.html", |
| 585 | b"<html><script>alert(1)</script></html>".to_vec(), |
| 586 | ), |
| 587 | ( |
| 588 | "pic.png", |
| 589 | vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0], |
| 590 | ), |
| 591 | ("sub/a.txt", b"nested\n".to_vec()), |
| 592 | ("big.txt", big), |
| 593 | ], |
| 594 | ); |
| 595 | let priv_bare = forge_git::repo::repo_path(&data_dir, &private.id).expect("path"); |
| 596 | populate( |
| 597 | &tmp.path().join("work-priv"), |
| 598 | &priv_bare, |
| 599 | &[("hello.txt", b"secret\n".to_vec())], |
| 600 | ); |
| 601 | |
| 602 | let router = router(state.clone()); |
| 603 | Fixture { |
| 604 | _tmp: tmp, |
| 605 | state, |
| 606 | router, |
| 607 | public, |
| 608 | private, |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | async fn get( |
| 613 | router: &Router, |
| 614 | method: &str, |
| 615 | uri: &str, |
| 616 | if_none_match: Option<&str>, |
| 617 | ) -> Response { |
| 618 | let mut builder = Request::builder().method(method).uri(uri); |
| 619 | if let Some(value) = if_none_match { |
| 620 | builder = builder.header("if-none-match", value); |
| 621 | } |
| 622 | let req = builder.body(RouterBody::empty()).expect("request"); |
| 623 | router.handle(req).await |
| 624 | } |
| 625 | |
| 626 | async fn body_bytes(res: Response) -> Vec<u8> { |
| 627 | topcoat::router::to_bytes(res.into_body(), usize::MAX) |
| 628 | .await |
| 629 | .expect("body") |
| 630 | .to_vec() |
| 631 | } |
| 632 | |
| 633 | fn header_str(res: &Response, name: &str) -> String { |
| 634 | res.headers() |
| 635 | .get(name) |
| 636 | .and_then(|v| v.to_str().ok()) |
| 637 | .unwrap_or("") |
| 638 | .to_owned() |
| 639 | } |
| 640 | |
| 641 | fn assert_security_headers(res: &Response) { |
| 642 | assert_eq!(header_str(res, "x-content-type-options"), "nosniff"); |
| 643 | assert!(header_str(res, "content-security-policy").contains("sandbox")); |
| 644 | assert_eq!( |
| 645 | header_str(res, "cross-origin-resource-policy"), |
| 646 | "cross-origin" |
| 647 | ); |
| 648 | assert_eq!(header_str(res, "referrer-policy"), "no-referrer"); |
| 649 | } |
| 650 | |
| 651 | |
| 652 | #[tokio::test] |
| 653 | async fn raw_serves_every_scenario_from_one_fixture() { |
| 654 | let fx = fixture().await; |
| 655 | |
| 656 | { |
| 657 | let res = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; |
| 658 | assert_eq!(res.status(), 200); |
| 659 | assert_eq!(header_str(&res, "content-type"), TEXT); |
| 660 | assert_eq!(header_str(&res, "content-disposition"), ""); |
| 661 | assert_eq!(header_str(&res, "cache-control"), CACHE_PUBLIC); |
| 662 | assert_security_headers(&res); |
| 663 | assert_eq!(body_bytes(res).await, b"hello raw\n"); |
| 664 | } |
| 665 | |
| 666 | |
| 667 | { |
| 668 | let res = get(&fx.router, "GET", "/tahinli/pub/main/sub/a.txt", None).await; |
| 669 | assert_eq!(res.status(), 200); |
| 670 | assert_eq!(body_bytes(res).await, b"nested\n"); |
| 671 | } |
| 672 | |
| 673 | |
| 674 | { |
| 675 | |
| 676 | let cases = [ |
| 677 | ("/tahinli/pub/main/page.html", TEXT, "attachment"), |
| 678 | ("/tahinli/pub/main/pic.png", "image/png", ""), |
| 679 | ]; |
| 680 | for (uri, content_type, disposition) in cases { |
| 681 | let res = get(&fx.router, "GET", uri, None).await; |
| 682 | assert_eq!(res.status(), 200, "case {uri}"); |
| 683 | assert_eq!(header_str(&res, "content-type"), content_type, "case {uri}"); |
| 684 | assert_eq!( |
| 685 | header_str(&res, "content-disposition"), |
| 686 | disposition, |
| 687 | "case {uri}" |
| 688 | ); |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | |
| 693 | { |
| 694 | let res = get(&fx.router, "GET", "/tahinli/pub/main/link", None).await; |
| 695 | assert_eq!(res.status(), 200); |
| 696 | assert_eq!(header_str(&res, "content-type"), TEXT); |
| 697 | assert_eq!(body_bytes(res).await, b"hello.txt"); |
| 698 | } |
| 699 | |
| 700 | |
| 701 | { |
| 702 | let path = "/tahinli/priv/main/hello.txt"; |
| 703 | let now = now_unix(); |
| 704 | |
| 705 | let none = get(&fx.router, "GET", path, None).await; |
| 706 | assert_eq!(none.status(), 404); |
| 707 | assert_eq!(header_str(&none, "cache-control"), CACHE_NONE); |
| 708 | |
| 709 | let valid = sign_raw(&KEY, &fx.private.id, now + 600); |
| 710 | let res = get(&fx.router, "GET", &format!("{path}?token={valid}"), None).await; |
| 711 | assert_eq!(res.status(), 200); |
| 712 | assert_eq!(header_str(&res, "cache-control"), CACHE_PRIVATE); |
| 713 | assert_eq!(body_bytes(res).await, b"secret\n"); |
| 714 | |
| 715 | let expired = sign_raw(&KEY, &fx.private.id, now - 1); |
| 716 | let res = get(&fx.router, "GET", &format!("{path}?token={expired}"), None).await; |
| 717 | assert_eq!(res.status(), 404); |
| 718 | |
| 719 | let other = sign_raw(&KEY, &fx.public.id, now + 600); |
| 720 | let res = get(&fx.router, "GET", &format!("{path}?token={other}"), None).await; |
| 721 | assert_eq!(res.status(), 404); |
| 722 | } |
| 723 | |
| 724 | |
| 725 | { |
| 726 | for uri in [ |
| 727 | "/tahinli/nope/main/hello.txt", |
| 728 | "/tahinli/pub/main/sub", |
| 729 | "/tahinli/pub/main", |
| 730 | ] { |
| 731 | let res = get(&fx.router, "GET", uri, None).await; |
| 732 | assert_eq!(res.status(), 404, "case {uri}"); |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | |
| 737 | { |
| 738 | let first = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; |
| 739 | let etag = header_str(&first, "etag"); |
| 740 | assert!(etag.starts_with('"') && etag.ends_with('"'), "etag {etag}"); |
| 741 | let again = get( |
| 742 | &fx.router, |
| 743 | "GET", |
| 744 | "/tahinli/pub/main/hello.txt", |
| 745 | Some(&etag), |
| 746 | ) |
| 747 | .await; |
| 748 | assert_eq!(again.status(), 304); |
| 749 | assert_eq!(header_str(&again, "etag"), etag); |
| 750 | } |
| 751 | |
| 752 | |
| 753 | { |
| 754 | let res = get(&fx.router, "HEAD", "/tahinli/pub/main/hello.txt", None).await; |
| 755 | assert_eq!(res.status(), 200); |
| 756 | assert_eq!(header_str(&res, "content-type"), TEXT); |
| 757 | assert_eq!(header_str(&res, "content-length"), "10"); |
| 758 | assert!(body_bytes(res).await.is_empty()); |
| 759 | } |
| 760 | |
| 761 | |
| 762 | { |
| 763 | let res = get(&fx.router, "GET", "/tahinli/pub/main/big.txt", None).await; |
| 764 | assert_eq!(res.status(), 200); |
| 765 | assert_eq!(header_str(&res, "content-length"), "9437184"); |
| 766 | let expected: Vec<u8> = b"0123456789abcdef\n" |
| 767 | .iter() |
| 768 | .cycle() |
| 769 | .take(9 * 1024 * 1024) |
| 770 | .copied() |
| 771 | .collect(); |
| 772 | let body = body_bytes(res).await; |
| 773 | assert!(body == expected, "streamed body differs"); |
| 774 | } |
| 775 | |
| 776 | |
| 777 | { |
| 778 | for path in ["/login", "/settings/keys", "/tahinli/pub/tree/main"] { |
| 779 | let res = get(&fx.router, "GET", path, None).await; |
| 780 | assert_eq!(res.status(), 404, "{path} is reachable"); |
| 781 | } |
| 782 | let health = get(&fx.router, "GET", "/healthz", None).await; |
| 783 | assert_eq!(health.status(), 200); |
| 784 | } |
| 785 | |
| 786 | |
| 787 | { |
| 788 | let url = raw_url(&fx.state, &fx.public, "main", "my file#1.txt"); |
| 789 | assert_eq!( |
| 790 | url, |
| 791 | "http://127.0.0.1:7661/tahinli/pub/main/my%20file%231.txt" |
| 792 | ); |
| 793 | let private = raw_url(&fx.state, &fx.private, "feature/x", "a b/c#d.txt"); |
| 794 | assert!( |
| 795 | private.starts_with( |
| 796 | "http://127.0.0.1:7661/tahinli/priv/feature/x/a%20b/c%23d.txt?token=" |
| 797 | ), |
| 798 | "{private}" |
| 799 | ); |
| 800 | let token = private.rsplit_once("?token=").map(|(_, t)| t).unwrap_or(""); |
| 801 | assert!(verify_raw(&KEY, token, &fx.private.id, now_unix())); |
| 802 | } |
| 803 | } |
| 804 | } |