diff --git a/README.md b/README.md index 33eea9bb..c6c62464 100644 --- a/README.md +++ b/README.md @@ -341,6 +341,7 @@ GET /api/v1/stats GET /api/v1/contracts GET /api/v1/repos GET /api/v1/repos/{owner}/{repo} +GET /api/v1/repos/{owner}/{repo}/tags GET /api/v1/repos/{owner}/{repo}/tree GET /api/v1/repos/{owner}/{repo}/blob/{path} GET /api/v1/repos/{owner}/{repo}/issues @@ -356,6 +357,7 @@ Signed write routes include: POST /api/v1/repos POST /api/register POST /api/v1/repos/{owner}/{repo}/fork +PUT /api/v1/repos/{owner}/{repo}/homepage POST /api/v1/repos/{owner}/{repo}/issues POST /api/v1/repos/{owner}/{repo}/pulls POST /api/v1/repos/{owner}/{repo}/pulls/{number}/merge diff --git a/crates/twigpine-node/src/api/mod.rs b/crates/twigpine-node/src/api/mod.rs index 75a560be..b72fba24 100644 --- a/crates/twigpine-node/src/api/mod.rs +++ b/crates/twigpine-node/src/api/mod.rs @@ -249,6 +249,8 @@ mod authz_guard { (labels, "add_label", "require_repo_owner("), (labels, "remove_label", "authorize_repo_read("), (labels, "remove_label", "require_repo_owner("), + (repos, "set_homepage", "authorize_repo_read("), + (repos, "set_homepage", "require_repo_owner("), // Bucket A' — owner OR author (did_matches against the author), // also behind the shared read gate first. (pulls, "close_pr", "authorize_repo_read("), @@ -348,6 +350,7 @@ mod authz_guard { (webhooks, "delete_webhook", "require_repo_owner("), (labels, "add_label", "require_repo_owner("), (labels, "remove_label", "require_repo_owner("), + (repos, "set_homepage", "require_repo_owner("), (pulls, "close_pr", "did_matches("), (issues, "close_issue", "did_matches("), (protect, "protect_branch", "did_matches("), diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index 105237f3..8a6304e3 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -240,6 +240,16 @@ pub struct RepoResponse { pub forked_from: Option, } +/// `GET /api/v1/repos/:owner/:repo`: the repo plus its owner-set homepage. +/// Only this route carries `homepage`; the list, federated, create, and fork +/// responses keep `RepoResponse` as is. +#[derive(Debug, Serialize)] +pub struct RepoDetailResponse { + #[serde(flatten)] + repo: RepoResponse, + homepage: Option, +} + #[derive(Debug, Deserialize)] pub struct InfoRefsQuery { pub service: Option, @@ -504,38 +514,372 @@ pub async fn get_repo( State(state): State, Path((owner, name)): Path<(String, String)>, auth: Option>, -) -> Result> { +) -> Result> { let caller = auth.as_ref().map(|e| e.0 .0.as_str()); let (record, _rules) = crate::api::authorize_repo_read(&state, &owner, &name, caller, "/").await?; - let count = state.db.count_stars(&record.id).await.unwrap_or(0); - Ok(Json(to_response(&record, &state, count))) + let (count, homepage) = tokio::join!( + state.db.count_stars(&record.id), + state.db.get_repo_homepage(&record.id), + ); + let count = count.unwrap_or(0); + let homepage = homepage?; + Ok(Json(RepoDetailResponse { + repo: to_response(&record, &state, count), + homepage, + })) +} + +/// Body of `PUT /api/v1/repos/:owner/:repo/homepage`. A null or absent +/// `homepage` clears it. Unknown fields are refused, so a typo such as +/// `homepage_url` is an error instead of a silent clear. The impl is written +/// by hand because a derived `Deserialize` also accepts a JSON array through +/// `visit_seq`, so `[null]` would read as a clear. +#[derive(Debug)] +pub struct HomepageRequest { + homepage: Option, +} + +impl<'de> Deserialize<'de> for HomepageRequest { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + struct HomepageVisitor; + + impl<'de> serde::de::Visitor<'de> for HomepageVisitor { + type Value = HomepageRequest; + + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("an object with a \"homepage\" string or null") + } + + fn visit_map(self, mut map: A) -> std::result::Result + where + A: serde::de::MapAccess<'de>, + { + let mut homepage = None; + let mut seen_homepage = false; + while let Some(key) = map.next_key::()? { + if key == "homepage" { + if seen_homepage { + return Err(serde::de::Error::duplicate_field("homepage")); + } + seen_homepage = true; + homepage = map.next_value()?; + } else { + return Err(serde::de::Error::unknown_field(&key, &["homepage"])); + } + } + Ok(HomepageRequest { homepage }) + } + } + + deserializer.deserialize_map(HomepageVisitor) + } +} + +/// Write the homepage for an already-gated repo. Zero rows matched means the +/// repo was deleted after the gate ran, which reads as the missing-repo 404 +/// rather than a success. +pub(crate) async fn store_homepage( + db: &crate::db::Db, + record: &RepoRecord, + homepage: Option<&str>, +) -> Result<()> { + if db.set_repo_homepage(&record.id, homepage).await? == 0 { + return Err(AppError::RepoNotFound(format!( + "{}/{}", + record.owner_did, record.name + ))); + } + Ok(()) +} + +/// PUT /api/v1/repos/:owner/:repo/homepage +/// +/// Owner-only. The body is checked first because that check reads no repo +/// state, so a malformed request answers the same for every caller and repo. +/// Then the read gate (an unreadable repo is the missing-repo 404), then the +/// owner gate (403), then the write. +pub async fn set_homepage( + State(state): State, + Extension(auth): Extension, + Path((owner, name)): Path<(String, String)>, + body: Bytes, +) -> Result> { + // Parsed here rather than by the `Json` extractor, which answers a wrong + // field type or an unknown field with 422 and a wrong content type with + // 415; every malformed body is the same 400. + let req: HomepageRequest = serde_json::from_slice(&body) + .map_err(|_| AppError::BadRequest("body must be {\"homepage\": string | null}".into()))?; + let homepage = req.homepage.as_deref().map(validate_homepage).transpose()?; + + let (record, _rules) = + crate::api::authorize_repo_read(&state, &owner, &name, Some(auth.0.as_str()), "/").await?; + crate::api::require_repo_owner(&record, &auth.0)?; + + // A mirror row (slash-form id) belongs to the node that owns the repo; an + // edit here would be overwritten by the next sync. + if record.id.contains('/') { + return Err(AppError::Conflict( + "a mirrored repo's homepage is set on its origin node".into(), + )); + } + + store_homepage(&state.db, &record, homepage).await?; + Ok(Json(serde_json::json!({ "homepage": homepage }))) +} + +const DEFAULT_COMMITS_PAGE: i64 = 30; +const MAX_COMMITS_PAGE: i64 = 100; +/// The one message for every `before` that cannot name a position in the served +/// history: malformed, unknown, not a commit, or a commit the head does not reach. +const BAD_BEFORE_MESSAGE: &str = + "before must be the full id of a commit in the served head's history"; +const GIT_READ_FAILED_MESSAGE: &str = "git read failed"; +/// Cap on the git-read deadline so the `Instant` addition cannot overflow. +const MAX_GIT_READ_DEADLINE: std::time::Duration = std::time::Duration::from_secs(365 * 24 * 3600); + +/// Query of `GET /api/v1/repos/:owner/:repo/commits`. Unknown keys are ignored on +/// purpose: `gl repo commits` sends `branch`, which the server has never honored. +#[derive(Debug, Deserialize)] +pub struct CommitsQuery { + #[serde(default)] + limit: Option, + #[serde(default)] + before: Option, +} + +/// 40 or 64 ASCII hex digits: a full SHA-1 or SHA-256 object id and nothing else, +/// so a revision expression or option never gets past the shape check. +fn is_full_hex_object_id(s: &str) -> bool { + (s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Map a bounded git read failure to a client error: a deadline is a 504, anything +/// else a fixed-message 500 with the detail logged, never sent. +fn git_read_app_error(err: &anyhow::Error, repo: &str) -> AppError { + if err + .downcast_ref::() + .is_some() + { + tracing::warn!(repo = %repo, "git read timed out"); + AppError::Timeout("git service timed out".into()) + } else { + tracing::error!(repo = %repo, err = %format!("{err:#}"), "git read failed"); + AppError::Git(GIT_READ_FAILED_MESSAGE.into()) + } +} + +/// Run `work` against a repo's disk path under the same admission the clone path +/// uses: the per-caller read permit, then the shared read permit (a refusal of +/// either is a 503), then the repo acquire bounded by `git_acquire_timeout_secs`. +/// `work` runs on a blocking thread with one deadline of `git_service_timeout_secs` +/// and owns both permits, so they are released only after its last git child is +/// reaped, even when the client disconnects first. +async fn run_repo_git_read( + state: &AppState, + headers: &axum::http::HeaderMap, + peer: Option, + record: &RepoRecord, + handler: &str, + work: F, +) -> Result +where + T: Send + 'static, + F: FnOnce(&str, &std::path::Path, std::time::Instant) -> Result + Send + 'static, +{ + let caller_key = read_caller_key(headers, peer, state.push_limiter_trust); + let caller_permit = acquire_read_caller_permit( + &state.git_read_per_caller, + caller_key.as_deref(), + &record.name, + handler, + )?; + let permit = git_permit(&state.git_read_semaphore)?; + + let acquire_deadline = std::time::Duration::from_secs(state.config.git_acquire_timeout_secs); + let disk_path = tokio::time::timeout( + acquire_deadline, + state.repo_store.acquire(&record.owner_did, &record.name), + ) + .await + .map_err(|_elapsed| { + tracing::warn!(repo = %record.name, "repo acquire timed out; shedding with 503"); + AppError::Overloaded("git service acquisition timed out, retry shortly".into()) + })? + .map_err(|e| { + if is_expected_transient_acquire_failure(&e) { + tracing::warn!(repo = %record.name, err = %format!("{e:#}"), "repo acquire failed"); + } else { + tracing::error!(repo = %record.name, err = %format!("{e:#}"), "repo acquire failed"); + } + // A typed refusal is a retryable 503 with a fixed body, the same as the + // clone path; anything else is the fixed-message 500, detail logged only. + if e.is::() { + AppError::from(e) + } else { + AppError::Git(GIT_READ_FAILED_MESSAGE.into()) + } + })?; + + // The gate authorized this row, but the disk identity is owner+name only: + // a row deleted and recreated under the same name since then would serve a + // different repo on this authorization. Re-read and require the same row; + // anything else answers like the missing-repo case the gate produces. + match state.db.get_repo(&record.owner_did, &record.name).await { + Ok(Some(current)) if current.id == record.id => {} + Ok(_) => { + return Err(AppError::RepoNotFound(format!( + "{}/{}", + record.owner_did, record.name + ))); + } + Err(e) => { + tracing::error!(repo = %record.name, err = %format!("{e:#}"), "repo row re-check failed"); + return Err(AppError::Git(GIT_READ_FAILED_MESSAGE.into())); + } + } + + let git_bin = state.git_bin.clone(); + let budget = std::time::Duration::from_secs(state.config.git_service_timeout_secs) + .min(MAX_GIT_READ_DEADLINE); + let deadline = std::time::Instant::now() + budget; + let repo = record.name.clone(); + tokio::task::spawn_blocking(move || { + let _held = (permit, caller_permit); + work(&git_bin, &disk_path, deadline) + }) + .await + .map_err(|e| { + tracing::error!(repo = %repo, err = %e, "git read task failed"); + AppError::Git(GIT_READ_FAILED_MESSAGE.into()) + })? } /// GET /api/v1/repos/:owner/:repo/commits +/// +/// `limit` (default 30, clamped into 1..=100) and `before=`. `before` +/// is a position in the served head's own history order: the page is what follows +/// that commit in the order an unpaged listing prints. Within one head the walk +/// visits every commit once, including history reachable only through a merge's +/// second parent. Paging is not a snapshot: each request resolves the head again, +/// so a head change between pages can skip or repeat commits. `before` is compared +/// against `git rev-list` output and never handed to git. Head resolution, +/// position lookup and the page read run under one deadline on a blocking thread +/// that holds the read permits. pub async fn list_commits( State(state): State, Path((owner, name)): Path<(String, String)>, + Query(query): Query, auth: Option>, + crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr, + headers: axum::http::HeaderMap, ) -> Result> { let caller = auth.as_ref().map(|e| e.0 .0.as_str()); let (record, _rules) = crate::api::authorize_repo_read(&state, &owner, &name, caller, "/").await?; - let disk_path = state - .repo_store - .acquire(&record.owner_did, &record.name) - .await - .map_err(|e| AppError::Git(e.to_string()))?; - let head_ref = store::resolve_head(&disk_path, &record.default_branch); - // A read failure is not an empty history: report it rather than answering - // a 200 with no commits (#400). - let commits = - store::log(&disk_path, &head_ref, 30).map_err(|e| AppError::Git(e.to_string()))?; + let limit = query + .limit + .unwrap_or(DEFAULT_COMMITS_PAGE) + .clamp(1, MAX_COMMITS_PAGE) as usize; + let before = match query.before { + Some(b) if is_full_hex_object_id(&b) => Some(b.to_ascii_lowercase()), + Some(_) => return Err(AppError::BadRequest(BAD_BEFORE_MESSAGE.into())), + None => None, + }; + + let default_branch = record.default_branch.clone(); + let repo = record.name.clone(); + let commits = run_repo_git_read( + &state, + &headers, + peer, + &record, + "commits", + move |git_bin, path, deadline| { + let fail = |e: anyhow::Error| git_read_app_error(&e, &repo); + let bad_before = || AppError::BadRequest(BAD_BEFORE_MESSAGE.into()); + // A read failure is not an empty history (#400): only an unborn head + // is empty, and it has no commit a `before` could name. + let Some(head) = + store::resolve_head_id_bounded(git_bin, path, &default_branch, deadline) + .map_err(fail)? + else { + return match before { + Some(_) => Err(bad_before()), + None => Ok(Vec::new()), + }; + }; + let skip = match &before { + Some(b) => { + match store::commit_position_bounded(git_bin, path, &head, b, deadline) + .map_err(fail)? + { + Some(position) => position + 1, + None => return Err(bad_before()), + } + } + None => 0, + }; + store::log_bounded(git_bin, path, &head, skip, limit, deadline).map_err(fail) + }, + ) + .await?; Ok(Json(serde_json::json!({ "commits": commits }))) } +/// Most tags one listing returns; `truncated` is set when more exist. +const MAX_TAGS: usize = 500; + +/// GET /api/v1/repos/:owner/:repo/tags +/// +/// `{"tags": [{name, target, target_type, annotated}], "truncated": bool}`, newest +/// version first by name and capped at 500. An annotated tag reports the object +/// its tag object names (one level: a tag of a tag reports the inner tag object +/// with `target_type` `tag`). Same read gate and admission as the commits listing. +pub async fn list_tags( + State(state): State, + Path((owner, name)): Path<(String, String)>, + auth: Option>, + crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr, + headers: axum::http::HeaderMap, +) -> Result> { + let caller = auth.as_ref().map(|e| e.0 .0.as_str()); + let (record, rules) = + crate::api::authorize_repo_read(&state, &owner, &name, caller, "/").await?; + + let repo = record.name.clone(); + let (mut tags, truncated) = run_repo_git_read( + &state, + &headers, + peer, + &record, + "tags", + move |git_bin, path, deadline| { + store::list_tags_bounded(git_bin, path, MAX_TAGS, deadline) + .map_err(|e| git_read_app_error(&e, &repo)) + }, + ) + .await?; + + // The id of a tree or blob can name content a path rule withholds, so a repo + // with any rule lists commit targets only, for every caller. A tag of a tag + // reports a tag object and is dropped with the rest. `truncated` stays as git + // reported it (driven by its record count, before this filter), so a + // rule-bearing repo can return fewer than MAX_TAGS rows with it set. + if !rules.is_empty() { + tags.retain(|t| t.target_type == "commit"); + } + + Ok(Json( + serde_json::json!({ "tags": tags, "truncated": truncated }), + )) +} + /// GET /api/v1/repos/:owner/:repo/blob/*path pub async fn get_blob( State(state): State, @@ -6269,10 +6613,148 @@ fn dedupe_canonical_repos(rows: Vec<(RepoRecord, i64)>) -> Vec<(RepoRecord, i64) .collect() } +const MAX_HOMEPAGE_BYTES: usize = 2048; + +/// Accept a repo homepage only when it is an absolute http(s) URL on a public +/// host, at most `MAX_HOMEPAGE_BYTES`, with no credentials and no control, +/// whitespace, backslash, or bidi-format characters. Returns the input +/// unchanged: callers store these exact bytes, because `Url::parse` silently +/// strips tabs and newlines, so storing a normalized form (or validating one +/// and storing another) would let a value through that was never checked. +fn validate_homepage(raw: &str) -> Result<&str> { + let bad = |why: &str| AppError::BadRequest(format!("homepage {why}")); + if raw.is_empty() { + return Err(bad("must not be empty")); + } + if raw.len() > MAX_HOMEPAGE_BYTES { + return Err(bad(&format!("must be at most {MAX_HOMEPAGE_BYTES} bytes"))); + } + // A backslash is refused outright: the WHATWG parser reads + // `https://example.com\@127.0.0.1/` as host `example.com`, while an RFC 3986 + // parser reads host `127.0.0.1`, and a consumer of the stored string may + // use either. + if raw.chars().any(|c| { + c.is_control() + || c.is_whitespace() + || c == '\\' + || twigpine_core::sanitize::is_bidi_format(c) + }) { + return Err(bad( + "must not contain control, whitespace, backslash, or bidi-format characters", + )); + } + let url = reqwest::Url::parse(raw).map_err(|_| bad("must be an absolute http or https URL"))?; + if !matches!(url.scheme(), "http" | "https") { + return Err(bad("must be an absolute http or https URL")); + } + if !url.username().is_empty() || url.password().is_some() { + return Err(bad("must not contain credentials")); + } + if !crate::api::peers::is_public_http_url(raw) { + return Err(bad(crate::api::peers::PUBLIC_HTTP_URL_REQUIREMENT)); + } + let lower = raw.to_ascii_lowercase(); + if !lower.starts_with("http://") && !lower.starts_with("https://") { + return Err(bad("must be an absolute http or https URL")); + } + Ok(raw) +} + #[cfg(test)] mod tests { use super::*; + // ── Homepage validation ────────────────────────────────────────────────── + + fn homepage_rejected(raw: &str) -> bool { + matches!(validate_homepage(raw), Err(AppError::BadRequest(_))) + } + + #[test] + fn homepage_accepts_public_http_urls_unchanged() { + for ok in [ + "https://example.com", + "http://example.com/docs?ref=twigpine#start", + "HTTPS://Example.com", + ] { + assert_eq!(validate_homepage(ok).unwrap(), ok, "{ok}"); + } + } + + #[test] + fn homepage_rejects_non_http_schemes_and_relative_urls() { + for bad in [ + "javascript:alert(1)", + "data:text/html,x", + "file:///etc/passwd", + "ftp://example.com", + "//example.com", + "example.com", + "https:example.com/docs", + "http:example.com", + "https:/example.com", + ] { + assert!(homepage_rejected(bad), "{bad}"); + } + } + + #[test] + fn homepage_rejects_embedded_credentials() { + for bad in ["https://user:pw@example.com", "https://user@example.com"] { + assert!(homepage_rejected(bad), "{bad}"); + } + } + + #[test] + fn homepage_rejects_control_whitespace_and_bidi_characters() { + for bad in [ + "https://exam\nple.com", + " https://example.com", + "https://example.com\t", + "https://exam\u{202E}ple.com", + "https://example.com/a b", + "https://example.com/\u{0}", + ] { + assert!(homepage_rejected(bad), "{bad:?}"); + } + } + + #[test] + fn homepage_rejects_a_backslash_anywhere() { + for bad in [ + "https://example.com\\@127.0.0.1/", + "https://example.com\\@evil.internal/", + "https://example.com/a\\b", + ] { + assert!(homepage_rejected(bad), "{bad}"); + } + } + + #[test] + fn homepage_rejects_non_public_hosts() { + for bad in [ + "http://localhost", + "http://127.0.0.1", + "http://10.0.0.1", + "http://169.254.169.254", + "http://intranet", + "http://box.internal", + ] { + assert!(homepage_rejected(bad), "{bad}"); + } + } + + #[test] + fn homepage_enforces_length_cap_and_rejects_empty() { + assert!(homepage_rejected("")); + let prefix = "https://example.com/"; + let at_cap = format!("{prefix}{}", "a".repeat(MAX_HOMEPAGE_BYTES - prefix.len())); + assert_eq!(at_cap.len(), MAX_HOMEPAGE_BYTES); + assert_eq!(validate_homepage(&at_cap).unwrap(), at_cap); + let over = format!("{at_cap}a"); + assert!(homepage_rejected(&over)); + } + /// #374: the fork path builds its own `git clone --mirror` argv. Driven /// through real git so a missing or misplaced `--` fails, matching the /// coverage on the `twigpine clone`, `twigpine mirror`, and sync sinks. @@ -19467,7 +19949,13 @@ exit 0 super::list_commits( axum::extract::State(state), axum::extract::Path((owner.to_string(), name)), + axum::extract::Query(super::CommitsQuery { + limit: None, + before: None, + }), None, + crate::rate_limit::PeerAddr(None), + axum::http::HeaderMap::new(), ) .await } @@ -19507,6 +19995,93 @@ exit 0 "a damaged ref must surface as a git error, not an empty listing" ); } + + /// The record the read gate authorized is only an owner+name on disk: if the + /// row is deleted and recreated under that name before the acquire, serving + /// would hand the new row's git data out on the old row's authorization. + /// The helper must answer with the same opaque not-found the gate returns + /// for a missing repo, and the read itself must never run. + #[sqlx::test] + async fn run_repo_git_read_refuses_a_stale_record(pool: sqlx::PgPool) { + let owner = "did:key:zSTALEGITREADAAAAAAAAAAAAAAAAAAAAAAA"; + let dir = tempfile::TempDir::new().unwrap(); + let mut state = crate::test_support::test_state(pool.clone()).await; + state.repo_store = + crate::git::repo_store::RepoStore::for_testing(dir.path().to_path_buf(), pool.clone()); + let now = chrono::Utc::now(); + let seed = |name: &str| crate::db::RepoRecord { + id: uuid::Uuid::new_v4().to_string(), + name: name.to_string(), + owner_did: owner.to_string(), + description: None, + is_public: true, + default_branch: "main".to_string(), + created_at: now, + updated_at: now, + disk_path: format!("/tmp/{name}"), + forked_from: None, + machine_id: None, + }; + let name = "stale"; + let repo_dir = dir + .path() + .join(owner.replace([':', '/'], "_")) + .join(format!("{name}.git")); + std::fs::create_dir_all(&repo_dir).unwrap(); + assert!(std::process::Command::new("git") + .args(["init", "-q", "-b", "main"]) + .current_dir(&repo_dir) + .status() + .unwrap() + .success()); + + let stale = seed(name); + state.db.create_repo(&stale).await.unwrap(); + // The authorized row is replaced by a new row under the same owner/name. + state.db.delete_repo_by_id(&stale.id).await.unwrap(); + let fresh = seed(name); + state.db.create_repo(&fresh).await.unwrap(); + + let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let ran_inner = ran.clone(); + let res: Result<()> = super::run_repo_git_read( + &state, + &axum::http::HeaderMap::new(), + None, + &stale, + "test", + move |_git_bin, _path, _deadline| { + ran_inner.store(true, std::sync::atomic::Ordering::SeqCst); + Ok(()) + }, + ) + .await; + assert!( + matches!(res, Err(crate::error::AppError::RepoNotFound(_))), + "a stale record must get the missing-repo response; got {res:?}" + ); + assert!( + !ran.load(std::sync::atomic::Ordering::SeqCst), + "the read must never run on a stale record" + ); + + let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let ran_inner = ran.clone(); + super::run_repo_git_read::<(), _>( + &state, + &axum::http::HeaderMap::new(), + None, + &fresh, + "test", + move |_git_bin, _path, _deadline| { + ran_inner.store(true, std::sync::atomic::Ordering::SeqCst); + Ok(()) + }, + ) + .await + .expect("the live record runs the read"); + assert!(ran.load(std::sync::atomic::Ordering::SeqCst)); + } /// #282 REPRO (RED on main): a push's write guard pins one dedicated /// lock-pool connection for the WHOLE op: taken at `acquire_write`, held /// across `smart_http::receive_pack` under `git_service_timeout_secs` @@ -20081,3 +20656,1196 @@ mod push_event_wiring_tests { ); } } + +/// Handler tests for the paged commits listing and the tags listing, driven through +/// a real router so extractors, the read gate, both permits and the error mapping +/// are all in the path. +#[cfg(test)] +mod commits_tags_tests { + use crate::auth::AuthenticatedDid; + use crate::state::AppState; + use axum::body::Body; + use axum::extract::ConnectInfo; + use axum::http::{HeaderMap, Request, StatusCode}; + use std::net::SocketAddr; + use std::path::{Path, PathBuf}; + use std::sync::Arc; + use tower::ServiceExt; + + const OWNER: &str = "did:key:zCTOwner0000000000000000000000000000000000"; + const OWNER_SHORT: &str = "zCTOwner0000000000000000000000000000000000"; + const STRANGER: &str = "did:key:zCTStranger000000000000000000000000000000"; + const T0: i64 = 1_700_000_000; + const PEER: &str = "203.0.113.5:4000"; + + struct Fx { + dir: tempfile::TempDir, + state: AppState, + } + + impl Fx { + async fn new(pool: sqlx::PgPool) -> Fx { + let dir = tempfile::TempDir::new().unwrap(); + let mut state = crate::test_support::test_state(pool.clone()).await; + state.repo_store = crate::git::repo_store::RepoStore::for_testing( + dir.path().to_path_buf(), + pool.clone(), + ); + state.push_limiter_trust = crate::rate_limit::TrustedProxy::None; + Fx { dir, state } + } + + /// Seed a repo row plus an initialized working repo at its disk path. + async fn repo(&self, name: &str, is_public: bool) -> PathBuf { + let now = chrono::Utc::now(); + self.state + .db + .create_repo(&crate::db::RepoRecord { + id: uuid::Uuid::new_v4().to_string(), + name: name.to_string(), + owner_did: OWNER.to_string(), + description: None, + is_public, + default_branch: "main".to_string(), + created_at: now, + updated_at: now, + disk_path: format!("/tmp/{name}"), + forked_from: None, + machine_id: None, + }) + .await + .unwrap(); + let record = self + .state + .db + .get_repo(OWNER_SHORT, name) + .await + .unwrap() + .unwrap(); + let path = + crate::git::store::repo_disk_path(self.dir.path(), &record.owner_did, &record.name); + std::fs::create_dir_all(&path).unwrap(); + git_at(&path, &["init", "-q", "-b", "main"], T0); + path + } + + async fn repo_id(&self, name: &str) -> String { + self.state + .db + .get_repo(OWNER_SHORT, name) + .await + .unwrap() + .unwrap() + .id + } + + fn set_deadline_secs(&mut self, secs: u64) { + let mut cfg = (*self.state.config).clone(); + cfg.git_service_timeout_secs = secs; + self.state.config = Arc::new(cfg); + } + } + + fn git_at(dir: &Path, args: &[&str], date: i64) -> String { + let when = format!("{date} +0000"); + let out = std::process::Command::new("git") + .args(args) + .current_dir(dir) + .env("GIT_AUTHOR_NAME", "Test Author") + .env("GIT_AUTHOR_EMAIL", "author@example.com") + .env("GIT_COMMITTER_NAME", "Test Committer") + .env("GIT_COMMITTER_EMAIL", "committer@example.com") + .env("GIT_AUTHOR_DATE", &when) + .env("GIT_COMMITTER_DATE", &when) + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + fn commit_at(dir: &Path, subject: &str, t: i64) -> String { + git_at(dir, &["commit", "--allow-empty", "-q", "-m", subject], t); + git_at(dir, &["rev-parse", "HEAD"], t) + } + + /// c1..c5 on main, c5 newest. Returns the ids in that order. + fn linear(dir: &Path) -> Vec { + (1..=5) + .map(|i| commit_at(dir, &format!("c{i}"), T0 + i * 100)) + .collect() + } + + /// base, then A1 and A2 on branch a and B1 and B2 on branch b with dates + /// interleaved, then main = A2 merged with B2. Returns the ids in the order an + /// unpaged listing prints them: M, B2, A2, B1, A1, base. + fn merge_history(dir: &Path) -> Vec { + let base = commit_at(dir, "base", T0 + 100); + git_at(dir, &["checkout", "-q", "-b", "a"], T0 + 150); + let a1 = commit_at(dir, "A1", T0 + 200); + git_at(dir, &["checkout", "-q", "-b", "b", &base], T0 + 250); + let b1 = commit_at(dir, "B1", T0 + 300); + git_at(dir, &["checkout", "-q", "a"], T0 + 350); + let a2 = commit_at(dir, "A2", T0 + 400); + git_at(dir, &["checkout", "-q", "b"], T0 + 450); + let b2 = commit_at(dir, "B2", T0 + 500); + git_at(dir, &["checkout", "-q", "-B", "main", "a"], T0 + 550); + git_at(dir, &["merge", "--no-ff", "-q", "-m", "M", "b"], T0 + 600); + let m = git_at(dir, &["rev-parse", "HEAD"], T0 + 600); + vec![m, b2, a2, b1, a1, base] + } + + /// `n` linear commits on main through `git fast-import`. + fn fast_import_linear(dir: &Path, n: i64) { + use std::io::Write; + let mut stream = String::new(); + for i in 1..=n { + let msg = format!("c{i}"); + stream.push_str(&format!( + "commit refs/heads/main\nmark :{i}\ncommitter T {} +0000\ndata {}\n{msg}\n", + T0 + i, + msg.len() + )); + if i > 1 { + stream.push_str(&format!("from :{}\n", i - 1)); + } + stream.push('\n'); + } + let mut child = std::process::Command::new("git") + .args(["fast-import", "--quiet"]) + .current_dir(dir) + .stdin(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(stream.as_bytes()) + .unwrap(); + assert!(child.wait().unwrap().success()); + } + + #[cfg(unix)] + fn fake_git(dir: &Path, body: &str) -> String { + use std::os::unix::fs::PermissionsExt; + let p = dir.join("fakegit"); + std::fs::write(&p, body).unwrap(); + let mut perm = std::fs::metadata(&p).unwrap().permissions(); + perm.set_mode(0o755); + std::fs::set_permissions(&p, perm).unwrap(); + p.to_str().unwrap().to_string() + } + + fn router(state: &AppState, did: Option<&str>) -> axum::Router { + let mut r = axum::Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/commits", + axum::routing::get(super::list_commits), + ) + .route( + "/api/v1/repos/{owner}/{repo}/tags", + axum::routing::get(super::list_tags), + ) + .with_state(state.clone()); + if let Some(d) = did { + r = r.layer(axum::Extension(AuthenticatedDid(d.to_string()))); + } + r + } + + async fn call( + state: &AppState, + did: Option<&str>, + peer: Option<&str>, + uri: &str, + ) -> (StatusCode, HeaderMap, String) { + let mut req = Request::builder().uri(uri).body(Body::empty()).unwrap(); + if let Some(p) = peer { + req.extensions_mut() + .insert(ConnectInfo(p.parse::().unwrap())); + } + let resp = router(state, did).oneshot(req).await.unwrap(); + let status = resp.status(); + let headers = resp.headers().clone(); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + ( + status, + headers, + String::from_utf8_lossy(&bytes).into_owned(), + ) + } + + fn commits_uri(repo: &str, query: &str) -> String { + let sep = if query.is_empty() { "" } else { "?" }; + format!("/api/v1/repos/{OWNER_SHORT}/{repo}/commits{sep}{query}") + } + + async fn commits(fx: &Fx, repo: &str, query: &str) -> (StatusCode, HeaderMap, String) { + call(&fx.state, None, Some(PEER), &commits_uri(repo, query)).await + } + + fn hashes(body: &str) -> Vec { + let v: serde_json::Value = serde_json::from_str(body).unwrap(); + v["commits"] + .as_array() + .unwrap_or_else(|| panic!("no commits array in {body}")) + .iter() + .map(|c| c["hash"].as_str().unwrap().to_string()) + .collect() + } + + /// Page `limit` at a time, feeding each page's last hash back as `before`. + async fn page_to_exhaustion(fx: &Fx, repo: &str, limit: usize) -> Vec> { + let mut pages = Vec::new(); + let mut before: Option = None; + loop { + let query = match &before { + Some(b) => format!("limit={limit}&before={b}"), + None => format!("limit={limit}"), + }; + let (status, _, body) = commits(fx, repo, &query).await; + assert_eq!(status, StatusCode::OK, "{query}: {body}"); + let page = hashes(&body); + let done = page.is_empty(); + if let Some(last) = page.last() { + before = Some(last.clone()); + } + pages.push(page); + assert!(pages.len() < 50, "paging did not terminate"); + if done { + return pages; + } + } + } + + #[sqlx::test] + async fn commits_without_parameters_return_30_rows_with_the_known_keys(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("many", true).await; + fast_import_linear(&dir, 150); + let (status, _, body) = commits(&fx, "many", "").await; + assert_eq!(status, StatusCode::OK, "{body}"); + let v: serde_json::Value = serde_json::from_str(&body).unwrap(); + let rows = v["commits"].as_array().unwrap(); + assert_eq!(rows.len(), 30); + let mut keys: Vec<&str> = rows[0] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + keys.sort_unstable(); + assert_eq!(keys, ["author", "date", "hash", "message"]); + assert_eq!(rows[0]["message"], "c150", "newest first"); + assert_eq!( + v.as_object().unwrap().len(), + 1, + "response stays {{commits}} only" + ); + } + + #[sqlx::test] + async fn commits_limit_is_clamped_into_one_to_one_hundred(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("many", true).await; + fast_import_linear(&dir, 150); + for (query, want) in [ + ("limit=10", 10), + ("limit=1", 1), + ("limit=0", 1), + ("limit=-5", 1), + ("limit=100", 100), + ("limit=101", 100), + ("limit=100000", 100), + ("limit=9223372036854775807", 100), + ("limit=-9223372036854775808", 1), + ("limit=20&branch=dev", 20), + ] { + let (status, _, body) = commits(&fx, "many", query).await; + assert_eq!(status, StatusCode::OK, "{query}: {body}"); + assert_eq!(hashes(&body).len(), want, "{query}"); + } + } + + #[sqlx::test] + async fn commits_unparseable_limit_is_400(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("many", true).await; + commit_at(&dir, "c1", T0); + for query in [ + "limit=abc", + "limit=", + "limit=99999999999999999999", + "limit=1.5", + ] { + let (status, _, body) = commits(&fx, "many", query).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{query}: {body}"); + } + } + + #[sqlx::test] + async fn commits_paging_a_linear_history_returns_every_commit_once(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("lin", true).await; + let ids = linear(&dir); + let pages = page_to_exhaustion(&fx, "lin", 2).await; + assert_eq!( + pages, + vec![ + vec![ids[4].clone(), ids[3].clone()], + vec![ids[2].clone(), ids[1].clone()], + vec![ids[0].clone()], + vec![], + ] + ); + } + + #[sqlx::test] + async fn commits_paging_a_merge_history_returns_every_commit_once(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("merge", true).await; + // order: M, B2, A2, B1, A1, base + let ids = merge_history(&dir); + let (status, _, body) = commits(&fx, "merge", "").await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + hashes(&body), + ids, + "the unpaged order is what paging follows" + ); + let pages = page_to_exhaustion(&fx, "merge", 2).await; + assert_eq!( + pages, + vec![ + vec![ids[0].clone(), ids[1].clone()], + vec![ids[2].clone(), ids[3].clone()], + vec![ids[4].clone(), ids[5].clone()], + vec![], + ] + ); + } + + #[sqlx::test] + async fn commits_before_the_last_commit_is_an_empty_200_and_case_is_ignored( + pool: sqlx::PgPool, + ) { + let fx = Fx::new(pool).await; + let dir = fx.repo("lin", true).await; + let ids = linear(&dir); + let (status, _, body) = commits(&fx, "lin", &format!("before={}", ids[0])).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert!(hashes(&body).is_empty()); + + let lower = commits(&fx, "lin", &format!("limit=2&before={}", ids[3])).await; + let upper = commits( + &fx, + "lin", + &format!("limit=2&before={}", ids[3].to_ascii_uppercase()), + ) + .await; + assert_eq!(lower.0, StatusCode::OK); + assert_eq!(hashes(&lower.2), vec![ids[2].clone(), ids[1].clone()]); + assert_eq!(upper.0, StatusCode::OK); + assert_eq!(upper.2, lower.2); + } + + #[sqlx::test] + async fn commits_hostile_before_values_are_400_even_with_the_pool_exhausted( + pool: sqlx::PgPool, + ) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("lin", true).await; + let ids = linear(&dir); + fx.state.git_read_semaphore = Arc::new(tokio::sync::Semaphore::new(0)); + let short = &ids[3][..7]; + let too_long = format!("{}a", ids[3]); + let non_hex = "g".repeat(40); + for before in [ + "HEAD", + "main~1", + "--all", + "-n1", + short, + too_long.as_str(), + non_hex.as_str(), + "", + ] { + let (status, _, body) = commits(&fx, "lin", &format!("before={before}")).await; + assert_eq!( + status, + StatusCode::BAD_REQUEST, + "before={before:?} must be 400, never 503 or a page: {body}" + ); + } + } + + #[sqlx::test] + async fn commits_before_that_is_not_in_history_order_is_the_same_400(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("lin", true).await; + let ids = linear(&dir); + let tree = git_at(&dir, &["rev-parse", &format!("{}^{{tree}}", ids[4])], T0); + let blob = { + std::fs::write(dir.join("f.txt"), "hello").unwrap(); + git_at(&dir, &["hash-object", "-w", "f.txt"], T0) + }; + git_at( + &dir, + &["tag", "-a", "-m", "release", "v1", &ids[2]], + T0 + 900, + ); + let tag_object = git_at(&dir, &["rev-parse", "refs/tags/v1"], T0); + // AE: a commit that lived on a branch the owner deleted. + git_at(&dir, &["checkout", "-q", "-b", "doomed"], T0 + 950); + let doomed = commit_at(&dir, "doomed", T0 + 1000); + git_at(&dir, &["checkout", "-q", "main"], T0 + 1100); + git_at(&dir, &["branch", "-D", "doomed"], T0 + 1100); + // A commit on another live branch that main does not contain. + git_at(&dir, &["checkout", "-q", "-b", "other"], T0 + 1150); + let other = commit_at(&dir, "other", T0 + 1200); + git_at(&dir, &["checkout", "-q", "main"], T0 + 1300); + + let absent = "0123456789abcdef0123456789abcdef01234567"; + let (status, _, baseline) = commits(&fx, "lin", &format!("before={absent}")).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{baseline}"); + for (what, before) in [ + ("tree", tree), + ("blob", blob), + ("annotated tag object", tag_object), + ("commit only on a deleted branch", doomed), + ("commit only on another live branch", other), + ] { + let (status, _, body) = commits(&fx, "lin", &format!("before={before}")).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{what}: {body}"); + assert_eq!(body, baseline, "{what}: same body as an unknown sha"); + } + } + + #[sqlx::test] + async fn commits_before_on_an_empty_repo_or_without_a_branch_is_400_not_empty_or_500( + pool: sqlx::PgPool, + ) { + let fx = Fx::new(pool).await; + fx.repo("empty", true).await; + let (status, _, body) = commits(&fx, "empty", "").await; + assert_eq!(status, StatusCode::OK); + assert!(hashes(&body).is_empty(), "unborn HEAD lists nothing"); + let (status, _, body) = commits( + &fx, + "empty", + "before=0123456789abcdef0123456789abcdef01234567", + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + + // Only branch deleted: the commit still exists in the object store. + let dir = fx.repo("nobranch", true).await; + let ids = linear(&dir); + git_at(&dir, &["update-ref", "-d", "refs/heads/main"], T0); + let (status, _, body) = commits(&fx, "nobranch", &format!("before={}", ids[2])).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + let (status, _, body) = commits(&fx, "nobranch", "").await; + assert_eq!(status, StatusCode::OK); + assert!(hashes(&body).is_empty()); + } + + #[sqlx::test] + async fn commits_malformed_query_is_400_for_every_repo_but_before_head_follows_the_gate( + pool: sqlx::PgPool, + ) { + let fx = Fx::new(pool).await; + let dir = fx.repo("pub", true).await; + commit_at(&dir, "c1", T0); + fx.repo("priv", false).await; + let bad_limit: Vec<_> = { + let mut v = Vec::new(); + for repo in ["priv", "nothing", "pub"] { + v.push(commits(&fx, repo, "limit=abc").await); + } + v + }; + for r in &bad_limit { + assert_eq!(r.0, StatusCode::BAD_REQUEST); + assert_eq!(r.2, bad_limit[0].2, "same body whatever the repo"); + } + assert_eq!( + commits(&fx, "priv", "before=HEAD").await.0, + StatusCode::NOT_FOUND + ); + assert_eq!( + commits(&fx, "nothing", "before=HEAD").await.0, + StatusCode::NOT_FOUND + ); + assert_eq!( + commits(&fx, "pub", "before=HEAD").await.0, + StatusCode::BAD_REQUEST + ); + } + + #[sqlx::test] + async fn commits_shed_503_with_retry_after_when_the_read_pool_is_exhausted(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("lin", true).await; + linear(&dir); + fx.state.git_read_semaphore = Arc::new(tokio::sync::Semaphore::new(0)); + let (status, headers, _) = commits(&fx, "lin", "").await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(headers.get("retry-after").is_some()); + } + + #[sqlx::test] + async fn commits_one_caller_at_its_cap_is_shed_while_another_is_served(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("lin", true).await; + linear(&dir); + fx.state.git_read_per_caller = crate::rate_limit::PerCallerConcurrency::new(1, 100); + let _held = fx + .state + .git_read_per_caller + .try_acquire("203.0.113.9") + .expect("fill the caller's only slot"); + let uri = commits_uri("lin", ""); + let capped = call(&fx.state, None, Some("203.0.113.9:5000"), &uri).await; + assert_eq!(capped.0, StatusCode::SERVICE_UNAVAILABLE, "{}", capped.2); + assert!(capped.1.get("retry-after").is_some()); + let other = call(&fx.state, None, Some("203.0.113.10:5000"), &uri).await; + assert_eq!(other.0, StatusCode::OK, "{}", other.2); + } + + /// Requests that must read exactly like a missing repo: private, hidden by a + /// visibility rule, quarantined. `suffix` picks the route, `queries` the query + /// variants, `token` is a string present in each repo's git data that must not + /// appear in any response body. + async fn assert_denied_like_missing( + fx: &Fx, + route: &str, + queries: &[String], + tokens: &[String], + ) { + let uri = |repo: &str, q: &str| { + let sep = if q.is_empty() { "" } else { "?" }; + format!("/api/v1/repos/{OWNER_SHORT}/{repo}/{route}{sep}{q}") + }; + let missing = call(&fx.state, None, Some(PEER), &uri("ct-nothing", "")).await; + assert_eq!(missing.0, StatusCode::NOT_FOUND); + assert!(missing.2.contains("repo_not_found"), "{}", missing.2); + let expected = missing.2.replace("ct-nothing", ""); + for repo in ["ct-private", "ct-hidden", "ct-quar", "ct-nothing"] { + for did in [None, Some(STRANGER)] { + for q in queries { + let (status, headers, body) = + call(&fx.state, did, Some(PEER), &uri(repo, q)).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{repo} {did:?} {q}: {body}"); + assert_eq!(body.replace(repo, ""), expected, "{repo} {did:?} {q}"); + let headers = format!("{headers:?}"); + for token in tokens { + assert!( + !body.contains(token), + "{repo} {did:?} {q}: body leaks {token}" + ); + assert!(!headers.contains(token), "{repo}: headers leak {token}"); + } + } + } + } + } + + /// Seed the three unreadable repos with a commit carrying `token` in its + /// subject. Returns the commit ids so the caller can assert none leaks. + async fn seed_unreadable(fx: &Fx, token: &str) -> Vec { + use crate::db::VisibilityMode; + let mut ids = Vec::new(); + for (name, public) in [ + ("ct-private", false), + ("ct-hidden", true), + ("ct-quar", true), + ] { + let dir = fx.repo(name, public).await; + ids.push(commit_at(&dir, token, T0)); + } + let hidden = fx.repo_id("ct-hidden").await; + fx.state + .db + .set_visibility_rule(&hidden, "/", VisibilityMode::B, &[], OWNER) + .await + .unwrap(); + let quar = fx.repo_id("ct-quar").await; + fx.state.db.set_repo_quarantine(&quar, true).await.unwrap(); + ids + } + + #[sqlx::test] + async fn commits_unreadable_repos_read_exactly_like_a_missing_one(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let token = "private-fixture-token-7731"; + let ids = seed_unreadable(&fx, token).await; + let mut queries = vec![String::new(), format!("before={}", ids[0])]; + queries.push("limit=5".to_string()); + let mut tokens = vec![token.to_string()]; + tokens.extend(ids); + assert_denied_like_missing(&fx, "commits", &queries, &tokens).await; + } + + #[sqlx::test] + async fn commits_a_corrupt_head_ref_is_a_fixed_500_without_the_path(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("badref", true).await; + commit_at(&dir, "c1", T0); + std::fs::write(dir.join(".git/refs/heads/main"), b"garbage-ref-content\n").unwrap(); + let (status, _, body) = commits(&fx, "badref", "").await; + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}"); + assert!(body.contains("git_error"), "{body}"); + assert!(body.contains("git read failed"), "{body}"); + let path = dir.to_string_lossy().to_string(); + assert!(!body.contains(&path), "body leaks the repo path: {body}"); + assert!(!body.contains("garbage-ref-content"), "{body}"); + assert!(!body.contains("refs/heads"), "{body}"); + // The same through a page request. + let (status, _, body) = commits(&fx, "badref", "limit=3").await; + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}"); + } + + #[cfg(unix)] + #[sqlx::test] + async fn commits_a_git_child_past_the_deadline_is_504_in_head_resolution(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("slow", true).await; + linear(&dir); + let shim = tempfile::TempDir::new().unwrap(); + fx.state.git_bin = fake_git( + shim.path(), + "#!/bin/sh\ncase \" $*\" in *rev-parse*) sleep 30;; esac\nexec git \"$@\"\n", + ); + fx.set_deadline_secs(1); + let started = std::time::Instant::now(); + let (status, _, body) = commits(&fx, "slow", "").await; + assert_eq!(status, StatusCode::GATEWAY_TIMEOUT, "{body}"); + assert!(started.elapsed() < std::time::Duration::from_secs(20)); + } + + fn tags_uri(repo: &str) -> String { + format!("/api/v1/repos/{OWNER_SHORT}/{repo}/tags") + } + + async fn tags(fx: &Fx, repo: &str) -> (StatusCode, HeaderMap, String) { + call(&fx.state, None, Some(PEER), &tags_uri(repo)).await + } + + async fn tags_ok(fx: &Fx, repo: &str) -> serde_json::Value { + let (status, _, body) = tags(fx, repo).await; + assert_eq!(status, StatusCode::OK, "{body}"); + serde_json::from_str(&body).unwrap() + } + + fn tag_row<'a>(v: &'a serde_json::Value, name: &str) -> &'a serde_json::Value { + v["tags"] + .as_array() + .unwrap() + .iter() + .find(|t| t["name"] == name) + .unwrap_or_else(|| panic!("no tag {name} in {v}")) + } + + fn tag_names(v: &serde_json::Value) -> Vec { + v["tags"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap().to_string()) + .collect() + } + + /// Point `refs/tags/` at `sha` without git's tag-name checks, so awkward + /// and non-UTF-8 names can exist. + #[cfg(unix)] + fn raw_tag(dir: &Path, name: &[u8], sha: &str) { + use std::os::unix::ffi::OsStrExt; + let mut refname = b"refs/tags/".to_vec(); + refname.extend_from_slice(name); + let out = std::process::Command::new("git") + .arg("update-ref") + .arg(std::ffi::OsStr::from_bytes(&refname)) + .arg(sha) + .current_dir(dir) + .output() + .unwrap(); + assert!( + out.status.success(), + "update-ref failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + } + + #[sqlx::test] + async fn tags_report_lightweight_and_annotated_tags_by_their_target(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("t", true).await; + let c = commit_at(&dir, "c1", T0); + git_at(&dir, &["tag", "v1"], T0); + git_at(&dir, &["tag", "-a", "-m", "second", "v2"], T0 + 10); + let tag_object = git_at(&dir, &["rev-parse", "refs/tags/v2"], T0); + assert_ne!(tag_object, c, "fixture: v2 is a real tag object"); + let v = tags_ok(&fx, "t").await; + assert_eq!( + v, + serde_json::json!({ + "tags": [ + {"name": "v2", "target": c, "target_type": "commit", "annotated": true}, + {"name": "v1", "target": c, "target_type": "commit", "annotated": false}, + ], + "truncated": false, + }) + ); + } + + #[sqlx::test] + async fn tags_on_a_tree_a_blob_and_another_tag_report_what_git_peels(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("t", true).await; + let c = commit_at(&dir, "c1", T0); + let tree = git_at(&dir, &["rev-parse", &format!("{c}^{{tree}}")], T0); + std::fs::write(dir.join("f.txt"), "hello").unwrap(); + let blob = git_at(&dir, &["hash-object", "-w", "f.txt"], T0); + git_at(&dir, &["tag", "on-tree", &tree], T0); + git_at(&dir, &["tag", "on-blob", &blob], T0); + git_at(&dir, &["tag", "-a", "-m", "inner", "inner", &c], T0 + 10); + let inner_object = git_at(&dir, &["rev-parse", "refs/tags/inner"], T0); + git_at( + &dir, + &["tag", "-a", "-m", "outer", "outer", &inner_object], + T0 + 20, + ); + let v = tags_ok(&fx, "t").await; + assert_eq!( + *tag_row(&v, "on-tree"), + serde_json::json!({"name": "on-tree", "target": tree, "target_type": "tree", "annotated": false}) + ); + assert_eq!( + *tag_row(&v, "on-blob"), + serde_json::json!({"name": "on-blob", "target": blob, "target_type": "blob", "annotated": false}) + ); + assert_eq!( + *tag_row(&v, "inner"), + serde_json::json!({"name": "inner", "target": c, "target_type": "commit", "annotated": true}) + ); + // git 2.43 peels one level: a tag of a tag reports the inner tag object. + assert_eq!( + *tag_row(&v, "outer"), + serde_json::json!({"name": "outer", "target": inner_object, "target_type": "tag", "annotated": true}) + ); + } + + #[sqlx::test] + async fn tags_on_a_repo_with_path_rules_list_only_commit_targets(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("t", true).await; + let c = commit_at(&dir, "c1", T0); + let tree = git_at(&dir, &["rev-parse", &format!("{c}^{{tree}}")], T0); + std::fs::write(dir.join("f.txt"), "hello rule fixture").unwrap(); + let blob = git_at(&dir, &["hash-object", "-w", "f.txt"], T0); + git_at(&dir, &["tag", "light", &c], T0); + git_at(&dir, &["tag", "-a", "-m", "ann", "ann", &c], T0 + 10); + git_at(&dir, &["tag", "on-tree", &tree], T0); + git_at(&dir, &["tag", "on-blob", &blob], T0); + let inner_object = git_at(&dir, &["rev-parse", "refs/tags/ann"], T0); + git_at( + &dir, + &["tag", "-a", "-m", "outer", "outer", &inner_object], + T0 + 20, + ); + + // No rules: tree and blob tags are listed as before. + let v = tags_ok(&fx, "t").await; + let mut names = tag_names(&v); + names.sort(); + assert_eq!(names, ["ann", "light", "on-blob", "on-tree", "outer"]); + + let id = fx.repo_id("t").await; + fx.state + .db + .set_visibility_rule(&id, "/secret/**", crate::db::VisibilityMode::B, &[], OWNER) + .await + .unwrap(); + + for caller in [None, Some(STRANGER), Some(OWNER)] { + let (status, _, body) = call(&fx.state, caller, Some(PEER), &tags_uri("t")).await; + assert_eq!(status, StatusCode::OK, "{caller:?}: {body}"); + let v: serde_json::Value = serde_json::from_str(&body).unwrap(); + let mut names = tag_names(&v); + names.sort(); + assert_eq!(names, ["ann", "light"], "{caller:?}: {body}"); + assert_eq!(v["truncated"], false, "{caller:?}"); + for hidden in [&tree, &blob] { + assert!( + !body.contains(hidden.as_str()), + "{caller:?}: body names a non-commit object: {body}" + ); + } + } + } + + #[sqlx::test] + async fn tags_come_back_newest_version_first(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("t", true).await; + commit_at(&dir, "c1", T0); + for name in ["v1.9", "v2.0", "v1.10"] { + git_at(&dir, &["tag", name], T0); + } + let v = tags_ok(&fx, "t").await; + assert_eq!(tag_names(&v), ["v2.0", "v1.10", "v1.9"]); + } + + #[cfg(unix)] + #[sqlx::test] + async fn tags_with_awkward_names_are_listed_as_named_and_non_utf8_names_are_omitted( + pool: sqlx::PgPool, + ) { + let fx = Fx::new(pool).await; + let dir = fx.repo("t", true).await; + let c = commit_at(&dir, "c1", T0); + raw_tag(&dir, b"-n", &c); + raw_tag(&dir, b"a/b", &c); + raw_tag(&dir, "v\u{202E}x".as_bytes(), &c); + raw_tag(&dir, b"bad\xffname", &c); + let v = tags_ok(&fx, "t").await; + let mut names = tag_names(&v); + names.sort(); + assert_eq!(names, ["-n", "a/b", "v\u{202E}x"]); + } + + #[sqlx::test] + async fn tags_of_a_repo_with_none_or_no_commits_is_an_empty_200(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("some", true).await; + commit_at(&dir, "c1", T0); + fx.repo("empty", true).await; + for repo in ["some", "empty"] { + let (status, _, body) = tags(&fx, repo).await; + assert_eq!(status, StatusCode::OK, "{repo}: {body}"); + assert_eq!( + serde_json::from_str::(&body).unwrap(), + serde_json::json!({"tags": [], "truncated": false}), + "{repo}" + ); + } + } + + fn make_tags(dir: &Path, sha: &str, n: usize) { + use std::io::Write; + let mut script = String::new(); + for i in 1..=n { + script.push_str(&format!("create refs/tags/t{i:04} {sha}\n")); + } + let mut child = std::process::Command::new("git") + .args(["update-ref", "--stdin"]) + .current_dir(dir) + .stdin(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(script.as_bytes()) + .unwrap(); + assert!(child.wait().unwrap().success()); + } + + #[sqlx::test] + async fn tags_are_capped_at_500_and_truncated_is_set_only_past_the_cap(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let at_cap = fx.repo("cap", true).await; + let c = commit_at(&at_cap, "c1", T0); + make_tags(&at_cap, &c, 500); + let v = tags_ok(&fx, "cap").await; + assert_eq!(v["tags"].as_array().unwrap().len(), 500); + assert_eq!(v["truncated"], false); + + let over = fx.repo("over", true).await; + let c = commit_at(&over, "c1", T0); + make_tags(&over, &c, 501); + let v = tags_ok(&fx, "over").await; + let names = tag_names(&v); + assert_eq!(names.len(), 500); + assert_eq!(v["truncated"], true); + assert_eq!(names.first().unwrap(), "t0501", "newest first"); + assert_eq!(names.last().unwrap(), "t0002", "the oldest is the one cut"); + } + + #[cfg(unix)] + #[sqlx::test] + async fn tags_a_ref_to_a_missing_object_is_never_a_silent_drop(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("ghost", true).await; + let c = commit_at(&dir, "c1", T0); + git_at(&dir, &["tag", "good"], T0); + std::fs::write( + dir.join(".git/refs/tags/ghost"), + b"0123456789abcdef0123456789abcdef01234567\n", + ) + .unwrap(); + let (status, _, body) = tags(&fx, "ghost").await; + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}"); + assert!(body.contains("git read failed"), "{body}"); + assert!( + !body.contains("ghost"), + "no ref name or path in the body: {body}" + ); + assert!(!body.contains(&c), "{body}"); + } + + #[sqlx::test] + async fn tags_shed_503_when_the_read_pool_is_exhausted(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("t", true).await; + commit_at(&dir, "c1", T0); + fx.state.git_read_semaphore = Arc::new(tokio::sync::Semaphore::new(0)); + let (status, headers, _) = tags(&fx, "t").await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(headers.get("retry-after").is_some()); + } + + #[sqlx::test] + async fn tags_one_caller_at_its_cap_is_shed_while_another_is_served(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("t", true).await; + commit_at(&dir, "c1", T0); + fx.state.git_read_per_caller = crate::rate_limit::PerCallerConcurrency::new(1, 100); + let _held = fx + .state + .git_read_per_caller + .try_acquire("203.0.113.9") + .expect("fill the caller's only slot"); + let uri = tags_uri("t"); + let capped = call(&fx.state, None, Some("203.0.113.9:5000"), &uri).await; + assert_eq!(capped.0, StatusCode::SERVICE_UNAVAILABLE, "{}", capped.2); + let other = call(&fx.state, None, Some("203.0.113.10:5000"), &uri).await; + assert_eq!(other.0, StatusCode::OK, "{}", other.2); + } + + #[cfg(unix)] + #[sqlx::test] + async fn tags_a_git_child_past_the_deadline_is_504(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("slow", true).await; + commit_at(&dir, "c1", T0); + let shim = tempfile::TempDir::new().unwrap(); + fx.state.git_bin = fake_git( + shim.path(), + "#!/bin/sh\ncase \" $*\" in *for-each-ref*) sleep 30;; esac\nexec git \"$@\"\n", + ); + fx.set_deadline_secs(1); + let started = std::time::Instant::now(); + let (status, _, body) = tags(&fx, "slow").await; + assert_eq!(status, StatusCode::GATEWAY_TIMEOUT, "{body}"); + assert!(started.elapsed() < std::time::Duration::from_secs(20)); + } + + /// A body that must not name where the repo lives or what the store said. + fn assert_no_repo_detail(body: &str, dir: &Path) { + let path = dir.to_string_lossy().to_string(); + assert!(!body.contains(&path), "body leaks the repo path: {body}"); + assert!( + !body.contains("quarantine"), + "body leaks store detail: {body}" + ); + } + + /// A live tree whose quarantine sidecar cannot be parsed: the store refuses it + /// with a typed `RepoUnavailable` that no reconciliation can lift. + fn quarantine_unreadable(dir: &Path) { + let marker = crate::git::repo_store::quarantine_path(dir).expect("sidecar path"); + std::fs::write(marker, b"not json").unwrap(); + } + + /// The status, header and body the clone path gives for the same refusal. + fn assert_repo_unavailable_503(status: StatusCode, headers: &HeaderMap, body: &str) { + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}"); + assert_eq!( + headers.get("retry-after").map(|v| v.to_str().unwrap()), + Some("1"), + "{body}" + ); + assert!(body.contains("repo_unavailable"), "{body}"); + assert!( + body.contains("repository is temporarily unavailable, retry"), + "{body}" + ); + } + + #[sqlx::test] + async fn commits_an_unreconcilable_quarantined_tree_is_a_retryable_503(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("held", true).await; + linear(&dir); + quarantine_unreadable(&dir); + for query in ["", "limit=3"] { + let (status, headers, body) = commits(&fx, "held", query).await; + assert_repo_unavailable_503(status, &headers, &body); + assert_no_repo_detail(&body, &dir); + } + } + + #[sqlx::test] + async fn tags_an_unreconcilable_quarantined_tree_is_a_retryable_503(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("held", true).await; + commit_at(&dir, "c1", T0); + quarantine_unreadable(&dir); + let (status, headers, body) = tags(&fx, "held").await; + assert_repo_unavailable_503(status, &headers, &body); + assert_no_repo_detail(&body, &dir); + } + + /// An acquire failure with no typed marker keeps the fixed-message 500. + #[sqlx::test] + async fn an_unexpected_acquire_error_stays_a_fixed_500_without_detail(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let dir = fx.repo("gone", true).await; + commit_at(&dir, "c1", T0); + // A live path that is a file, not a directory: an acquire failure with no + // typed marker. + std::fs::remove_dir_all(&dir).unwrap(); + std::fs::write(&dir, b"not a repo").unwrap(); + let path = dir.to_string_lossy().to_string(); + let (status, _, body) = commits(&fx, "gone", "").await; + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}"); + assert!(body.contains("git read failed"), "{body}"); + assert!(!body.contains(&path), "body leaks the repo path: {body}"); + let (status, _, body) = tags(&fx, "gone").await; + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}"); + assert!(body.contains("git read failed"), "{body}"); + assert!(!body.contains(&path), "body leaks the repo path: {body}"); + } + + /// Pool and per-caller limits of one, so both guards read as taken or free. + fn single_slot_pools(fx: &mut Fx) { + fx.state.git_read_semaphore = Arc::new(tokio::sync::Semaphore::new(1)); + fx.state.git_read_per_caller = crate::rate_limit::PerCallerConcurrency::new(1, 100); + } + + fn caller_slot_is_taken(fx: &Fx) -> bool { + fx.state + .git_read_per_caller + .try_acquire("203.0.113.5") + .is_none() + } + + #[sqlx::test] + async fn a_served_read_returns_both_permits(pool: sqlx::PgPool) { + let mut fx = Fx::new(pool).await; + let dir = fx.repo("lin", true).await; + linear(&dir); + single_slot_pools(&mut fx); + for uri in [commits_uri("lin", ""), tags_uri("lin")] { + let (status, _, body) = call(&fx.state, None, Some(PEER), &uri).await; + assert_eq!(status, StatusCode::OK, "{uri}: {body}"); + assert_eq!(fx.state.git_read_semaphore.available_permits(), 1, "{uri}"); + assert!(!caller_slot_is_taken(&fx), "{uri}"); + } + } + + /// The permits belong to the blocking work, not the handler future: a client that + /// disconnects while git is running must not free the slots until git has exited. + #[cfg(unix)] + #[sqlx::test] + async fn a_disconnect_keeps_both_permits_until_the_git_child_exits(pool: sqlx::PgPool) { + use std::time::Duration; + let mut fx = Fx::new(pool).await; + let dir = fx.repo("slow", true).await; + commit_at(&dir, "c1", T0); + single_slot_pools(&mut fx); + fx.set_deadline_secs(30); + let shim = tempfile::TempDir::new().unwrap(); + let pid_file = shim.path().join("pid"); + fx.state.git_bin = fake_git( + shim.path(), + &format!( + "#!/bin/sh\ncase \" $*\" in *for-each-ref*) echo $$ > {}; sleep 2;; esac\nexec git \"$@\"\n", + pid_file.display() + ), + ); + + let uri = tags_uri("slow"); + let mut fut = Box::pin(call(&fx.state, None, Some(PEER), &uri)); + let mut spawned = false; + for _ in 0..500 { + if tokio::time::timeout(Duration::from_millis(20), &mut fut) + .await + .is_ok() + { + panic!("the request finished before the git child could be observed"); + } + if pid_file.exists() { + spawned = true; + break; + } + } + assert!(spawned, "the fake git child must have started"); + let pid: i32 = std::fs::read_to_string(&pid_file) + .unwrap() + .trim() + .parse() + .unwrap(); + assert_eq!(fx.state.git_read_semaphore.available_permits(), 0); + assert!(caller_slot_is_taken(&fx)); + + // The client disconnects: the handler future is dropped mid-request. + drop(fut); + for _ in 0..10 { + tokio::task::yield_now().await; + } + assert!( + unsafe { libc::kill(pid, 0) } == 0, + "precondition: the git child must still be running, or this proves nothing" + ); + assert_eq!( + fx.state.git_read_semaphore.available_permits(), + 0, + "dropping the handler future must not free the shared read permit" + ); + assert!( + caller_slot_is_taken(&fx), + "dropping the handler future must not free the per-caller slot" + ); + + let mut freed = false; + for _ in 0..400 { + if fx.state.git_read_semaphore.available_permits() == 1 && !caller_slot_is_taken(&fx) { + freed = true; + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(freed, "both permits must return once the git child is done"); + assert!( + unsafe { libc::kill(pid, 0) } != 0, + "the permits must not be freed before the child has exited" + ); + } + + #[sqlx::test] + async fn tags_unreadable_repos_read_exactly_like_a_missing_one(pool: sqlx::PgPool) { + let fx = Fx::new(pool).await; + let token = "private-fixture-token-5521"; + let ids = seed_unreadable(&fx, token).await; + for name in ["ct-private", "ct-hidden", "ct-quar"] { + let dir = crate::git::store::repo_disk_path(fx.dir.path(), OWNER, name); + git_at( + &dir, + &["tag", "-a", "-m", token, "secret-tag-name-9917"], + T0 + 5, + ); + } + let mut tokens = vec![token.to_string(), "secret-tag-name-9917".to_string()]; + tokens.extend(ids); + assert_denied_like_missing(&fx, "tags", &[String::new()], &tokens).await; + } +} diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index b0d32a88..15785bee 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2820,6 +2820,12 @@ const MIGRATIONS: &[Migration] = &[ "CREATE INDEX IF NOT EXISTS idx_model_durability_jobs_pending ON model_durability_jobs (state, created_at)", ], }, + + Migration { + version: 50, + name: "repos_homepage", + stmts: &["ALTER TABLE repos ADD COLUMN IF NOT EXISTS homepage TEXT"], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── @@ -3382,6 +3388,49 @@ impl Db { Ok(row.map(row_to_repo)) } + /// The owner-set homepage of one repo, or `None` when unset or the id is + /// unknown. Read separately from `RepoRecord` so the many repo queries do + /// not carry a column most callers never use. + pub async fn get_repo_homepage(&self, repo_id: &str) -> Result> { + let row: Option> = + sqlx::query_scalar("SELECT homepage FROM repos WHERE id = $1") + .bind(repo_id) + .fetch_optional(&self.pool) + .await?; + Ok(row.flatten()) + } + + /// Homepages for a set of repos in one query, keyed by repo id. Repos with + /// no homepage, and unknown ids, are absent from the map. + pub async fn list_repo_homepages( + &self, + repo_ids: &[String], + ) -> Result> { + if repo_ids.is_empty() { + return Ok(std::collections::HashMap::new()); + } + let rows: Vec<(String, String)> = sqlx::query_as( + "SELECT id, homepage FROM repos WHERE id = ANY($1) AND homepage IS NOT NULL", + ) + .bind(repo_ids) + .fetch_all(&self.pool) + .await?; + Ok(rows.into_iter().collect()) + } + + /// Set (`Some`) or clear (`None`) a repo's homepage and bump `updated_at`. + /// Returns the number of rows matched, so a caller can tell a repo deleted + /// after its gate from a successful write. + pub async fn set_repo_homepage(&self, repo_id: &str, homepage: Option<&str>) -> Result { + let res = sqlx::query("UPDATE repos SET homepage = $2, updated_at = $3 WHERE id = $1") + .bind(repo_id) + .bind(homepage) + .bind(Utc::now().to_rfc3339()) + .execute(&self.pool) + .await?; + Ok(res.rows_affected()) + } + /// Fetch a repo by its stable `id`. Used by the `/ipfs/{cid}` provenance path, /// which resolves a pin straight to its ONE source repo (#173) instead of /// paging the whole repo table. `id` is exact, so unlike `get_repo`'s fuzzy @@ -14555,6 +14604,200 @@ mod migration_tests { .await .unwrap(); } + + // ── Repo homepage (v50) ────────────────────────────────────────────────── + + /// The version this branch's migration claims; the upgrade test derives its + /// rollback target from `MIGRATIONS` so a renumber is a one-line change. + const V50: i64 = 50; + + fn homepage_repo(id: &str, name: &str) -> super::RepoRecord { + let now = chrono::Utc::now(); + super::RepoRecord { + id: id.to_string(), + name: name.to_string(), + owner_did: "did:key:z6MkHomepageOwnerFixture".to_string(), + description: None, + is_public: true, + default_branch: "main".to_string(), + created_at: now, + updated_at: now, + disk_path: format!("/srv/{id}"), + forked_from: None, + machine_id: None, + } + } + + /// Upgrade path: a fresh `#[sqlx::test]` database runs the whole chain, so + /// only a simulated existing node proves the column arrives through its own + /// entry rather than an already-applied one. + #[sqlx::test] + async fn migration_v50_upgrade_path_adds_nullable_homepage(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + + sqlx::query("ALTER TABLE repos DROP COLUMN IF EXISTS homepage") + .execute(&db.pool) + .await + .unwrap(); + sqlx::query("DELETE FROM schema_migrations WHERE version >= $1") + .bind(V50) + .execute(&db.pool) + .await + .unwrap(); + let prior = MIGRATIONS + .iter() + .map(|m| m.version) + .filter(|v| *v < V50) + .max() + .expect("MIGRATIONS must declare a version below 50"); + let recorded_max: i64 = sqlx::query_scalar("SELECT MAX(version) FROM schema_migrations") + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!( + recorded_max, prior, + "the simulated node must sit at the highest version below {V50}" + ); + + let legacy = homepage_repo("11111111-1111-1111-1111-111111111111", "legacy"); + db.create_repo(&legacy).await.unwrap(); + assert!(!column_exists(&db, "repos", "homepage").await); + + db.migrate().await.unwrap(); + + assert!( + column_exists(&db, "repos", "homepage").await, + "homepage missing after upgrade on an existing node" + ); + let col: (String, String) = sqlx::query_as( + "SELECT data_type, is_nullable FROM information_schema.columns + WHERE table_name = 'repos' AND column_name = 'homepage'", + ) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(col.0, "text"); + assert_eq!(col.1, "YES", "homepage must be nullable"); + + assert_eq!(db.get_repo_homepage(&legacy.id).await.unwrap(), None); + + let recorded: (i64,) = sqlx::query_scalar::<_, i64>( + "SELECT COUNT(*) FROM schema_migrations WHERE version = $1", + ) + .bind(V50) + .fetch_one(&db.pool) + .await + .map(|n| (n,)) + .unwrap(); + assert_eq!(recorded.0, 1, "v50 must be recorded as applied once"); + + db.migrate().await.unwrap(); + let again: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM schema_migrations WHERE version = $1") + .bind(V50) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(again, 1, "a second migrate must change nothing"); + } + + #[sqlx::test] + async fn homepage_round_trips_through_single_and_batched_reads(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + let a = homepage_repo("aaaaaaaa-0000-0000-0000-000000000001", "a"); + let b = homepage_repo("aaaaaaaa-0000-0000-0000-000000000002", "b"); + db.create_repo(&a).await.unwrap(); + db.create_repo(&b).await.unwrap(); + + // Unset for a new repo. + assert_eq!(db.get_repo_homepage(&a.id).await.unwrap(), None); + + let url = "https://example.com/project?x=1#frag"; + assert_eq!(db.set_repo_homepage(&a.id, Some(url)).await.unwrap(), 1); + assert_eq!( + db.get_repo_homepage(&a.id).await.unwrap().as_deref(), + Some(url) + ); + + // Batched read: only the repo with a homepage appears; an unknown id and + // the unset repo are absent. + let ids = vec![a.id.clone(), b.id.clone(), "no-such-id".to_string()]; + let map = db.list_repo_homepages(&ids).await.unwrap(); + assert_eq!(map.len(), 1); + assert_eq!(map.get(&a.id).map(String::as_str), Some(url)); + assert!(db.list_repo_homepages(&[]).await.unwrap().is_empty()); + + // Setting the same value twice still matches the row. + assert_eq!(db.set_repo_homepage(&a.id, Some(url)).await.unwrap(), 1); + + // Clearing returns the field to null. + assert_eq!(db.set_repo_homepage(&a.id, None).await.unwrap(), 1); + assert_eq!(db.get_repo_homepage(&a.id).await.unwrap(), None); + assert!(db.list_repo_homepages(&ids).await.unwrap().is_empty()); + } + + #[sqlx::test] + async fn set_homepage_on_unknown_repo_affects_no_rows(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + let n = db + .set_repo_homepage("missing", Some("https://example.com")) + .await + .unwrap(); + assert_eq!(n, 0); + } + + #[sqlx::test] + async fn set_homepage_bumps_updated_at(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + let mut r = homepage_repo("bbbbbbbb-0000-0000-0000-000000000001", "t"); + r.updated_at = chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00+00:00") + .unwrap() + .with_timezone(&chrono::Utc); + db.create_repo(&r).await.unwrap(); + db.set_repo_homepage(&r.id, Some("https://example.com")) + .await + .unwrap(); + let after = db.get_repo_by_id(&r.id).await.unwrap().unwrap(); + assert!(after.updated_at > r.updated_at); + } + + #[sqlx::test] + async fn upsert_mirror_repo_leaves_canonical_homepage_untouched(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + let canon = homepage_repo("cccccccc-0000-0000-0000-000000000001", "shared"); + db.create_repo(&canon).await.unwrap(); + db.set_repo_homepage(&canon.id, Some("https://example.com/keep")) + .await + .unwrap(); + + db.upsert_mirror_repo("z6MkOther", "shared", "/srv/mirror", None, false) + .await + .unwrap(); + db.upsert_mirror_repo( + "z6MkHomepageOwnerFixture", + "shared", + "/srv/mirror2", + None, + false, + ) + .await + .unwrap(); + + assert_eq!( + db.get_repo_homepage(&canon.id).await.unwrap().as_deref(), + Some("https://example.com/keep") + ); + assert_eq!( + db.get_repo_homepage("z6MkOther/shared").await.unwrap(), + None, + "a mirror row never carries a homepage" + ); + } } #[cfg(test)] diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index c296eb0b..56db0b94 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -886,13 +886,7 @@ fn ref_is_genuinely_absent(repo_path: &Path, refname: &str) -> Result { /// Get commit log for a ref (up to `limit` entries). pub fn log(repo_path: &Path, refname: &str, limit: usize) -> Result> { let output = Command::new("git") - .args([ - "log", - "--format=%H%n%an%n%ae%n%at%n%s", - "-n", - &limit.to_string(), - refname, - ]) + .args(["log", LOG_FORMAT, "-n", &limit.to_string(), refname]) .current_dir(repo_path) .output() .context("failed to run git log")?; @@ -931,7 +925,13 @@ pub fn log(repo_path: &Path, refname: &str, limit: usize) -> Result Vec { + let stdout = String::from_utf8_lossy(stdout); let mut commits = Vec::new(); let mut lines = stdout.lines(); @@ -954,7 +954,346 @@ pub fn log(repo_path: &Path, refname: &str, limit: usize) -> Result Result> { + let spec = format!("{name}^{{commit}}"); + let (status, out, err) = crate::git::visibility_pack::run_bounded_git_raw( + git_bin, + &["rev-parse", "--verify", "--quiet", &spec], + repo_path, + b"", + deadline, + )?; + match status.code() { + Some(0) => { + let id = String::from_utf8_lossy(&out).trim().to_string(); + if id.len() != 40 && id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { + bail!("git rev-parse printed an unexpected object id for {name}"); + } + Ok(Some(id)) + } + Some(1) => Ok(None), + _ => bail!( + "git rev-parse failed for {name}: {}", + String::from_utf8_lossy(&err).trim() + ), + } +} + +/// Bounded form of [`ref_is_genuinely_absent`], for the head ref only. +fn head_is_genuinely_absent_bounded( + git_bin: &str, + repo_path: &Path, + deadline: std::time::Instant, +) -> Result { + use crate::git::visibility_pack::run_bounded_git_raw; + let (status, out, _) = run_bounded_git_raw( + git_bin, + &["symbolic-ref", "-q", "HEAD"], + repo_path, + b"", + deadline, + )?; + if !status.success() { + return Ok(false); + } + let target = String::from_utf8_lossy(&out).trim().to_string(); + if !target.starts_with("refs/") { + return Ok(true); + } + let (status, out, err) = run_bounded_git_raw( + git_bin, + &["for-each-ref", "--format=%(refname)", &target], + repo_path, + b"", + deadline, + )?; + if !status.success() { + bail!( + "git for-each-ref failed for {target}: {}", + String::from_utf8_lossy(&err).trim() + ); + } + // for-each-ref matches `target` as a pattern, so it also lists refs below + // `target/`. Only a line equal to `target` proves the ref itself exists. + let exact = String::from_utf8_lossy(&out) + .lines() + .any(|l| l.trim() == target); + Ok(!exact && err.iter().all(u8::is_ascii_whitespace)) +} + +/// Resolve the served head to one commit id, every git child bounded by `deadline`. +/// +/// Decision order is [`resolve_head`]'s: HEAD, then `refs/heads/`, +/// then the branch scan (main, master, develop, else the first branch). `None` +/// means the head ref is genuinely absent (an unborn branch); a head that is +/// present but unreadable is an error, as in [`log`] (#400). Both later steps of a +/// paged read use the returned id, so a push between them cannot shift the page. +pub fn resolve_head_id_bounded( + git_bin: &str, + repo_path: &Path, + preferred_branch: &str, + deadline: std::time::Instant, +) -> Result> { + if let Some(id) = rev_parse_commit_bounded(git_bin, repo_path, "HEAD", deadline)? { + return Ok(Some(id)); + } + if !head_is_genuinely_absent_bounded(git_bin, repo_path, deadline)? { + bail!("git log failed for HEAD: ref is present but unreadable"); + } + let preferred = format!("refs/heads/{preferred_branch}"); + if let Some(id) = rev_parse_commit_bounded(git_bin, repo_path, &preferred, deadline)? { + return Ok(Some(id)); + } + let listed = crate::git::visibility_pack::run_bounded_git( + git_bin, + &["for-each-ref", "--format=%(refname)", "refs/heads/"], + repo_path, + b"", + deadline, + )?; + let listed = String::from_utf8_lossy(&listed); + let branches: Vec<&str> = listed + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .collect(); + let chosen = ["refs/heads/main", "refs/heads/master", "refs/heads/develop"] + .into_iter() + .find(|name| branches.contains(name)) + .or_else(|| branches.first().copied()); + if let Some(name) = chosen { + return match rev_parse_commit_bounded(git_bin, repo_path, name, deadline)? { + Some(id) => Ok(Some(id)), + None => bail!("{name} is present but does not resolve to a commit"), + }; + } + if head_is_genuinely_absent_bounded(git_bin, repo_path, deadline)? { + return Ok(None); + } + bail!("git log failed for HEAD: ref is present but unreadable") +} + +/// Longest line a `rev-list` of object ids can have (a SHA-256 id is 64 hex +/// digits). Anything longer without a line break is not rev-list output. +const MAX_REV_LIST_LINE: usize = 128; + +/// Line scanner for `rev-list` output: finds the zero-based line equal to a target +/// id while holding at most one partial line, however long the output is. +struct PositionScan<'a> { + target: &'a [u8], + line: usize, + partial: Vec, + found: Option, +} + +impl<'a> PositionScan<'a> { + fn new(target: &'a [u8]) -> Self { + Self { + target, + line: 0, + partial: Vec::new(), + found: None, + } + } + + /// Feed the next chunk. `Ok(false)` means the target was found and the caller + /// can stop reading. + fn feed(&mut self, chunk: &[u8]) -> Result { + let mut rest = chunk; + while let Some(nl) = rest.iter().position(|b| *b == b'\n') { + let (head, tail) = rest.split_at(nl); + rest = &tail[1..]; + let matched = if self.partial.is_empty() { + head == self.target + } else { + self.partial.extend_from_slice(head); + let m = self.partial == self.target; + self.partial.clear(); + m + }; + if matched { + self.found = Some(self.line); + return Ok(false); + } + self.line += 1; + } + if self.partial.len() + rest.len() > MAX_REV_LIST_LINE { + bail!("git rev-list printed a line longer than an object id"); + } + self.partial.extend_from_slice(rest); + Ok(true) + } + + /// Account for a final line with no trailing line break. + fn finish(&mut self) { + if self.found.is_none() && !self.partial.is_empty() && self.partial == self.target { + self.found = Some(self.line); + } + } + + fn found(&self) -> Option { + self.found + } +} + +/// Zero-based position of `commit_id` in the order of `git rev-list `, +/// which is the order [`log_bounded`] pages in. `None` means the id is not in that +/// history: an id naming nothing, a non-commit, or a commit the head does not +/// contain. `commit_id` is compared here against output lines and never passed to +/// git. The output is read as it arrives and the child is killed as soon as the +/// id is found, so memory stays at one chunk however long the history is; a +/// history that never contains the id is read to its end or to `deadline`. +pub fn commit_position_bounded( + git_bin: &str, + repo_path: &Path, + head_id: &str, + commit_id: &str, + deadline: std::time::Instant, +) -> Result> { + let mut scan = PositionScan::new(commit_id.as_bytes()); + let mut scan_error = None; + let (status, err, _stopped) = crate::git::visibility_pack::run_bounded_git_streaming( + git_bin, + &["rev-list", head_id], + repo_path, + deadline, + &mut |chunk| match scan.feed(chunk) { + Ok(keep_reading) => keep_reading, + Err(e) => { + scan_error = Some(e); + false + } + }, + )?; + if let Some(e) = scan_error { + return Err(e); + } + if scan.found().is_some() { + return Ok(scan.found()); + } + if !status.success() { + bail!( + "git rev-list failed: {}", + String::from_utf8_lossy(&err).trim() + ); + } + scan.finish(); + Ok(scan.found()) +} + +/// One page of commits reachable from `head_id`: skip `skip`, then take `limit`. +/// `head_id` is an id from [`resolve_head_id_bounded`], so a failing `git log` is a +/// read failure and never an empty page; the absent-ref case was settled there. +pub fn log_bounded( + git_bin: &str, + repo_path: &Path, + head_id: &str, + skip: usize, + limit: usize, + deadline: std::time::Instant, +) -> Result> { + let (status, out, err) = crate::git::visibility_pack::run_bounded_git_raw( + git_bin, + &[ + "log", + LOG_FORMAT, + &format!("--skip={skip}"), + "-n", + &limit.to_string(), + head_id, + ], + repo_path, + b"", + deadline, + )?; + if !status.success() { + bail!( + "git log failed for {head_id}: {}", + String::from_utf8_lossy(&err).trim() + ); + } + Ok(parse_log_output(&out)) +} + +/// One row of a tag listing. `target` and `target_type` are what the tag points +/// at: for an annotated tag, the object the tag object names (one level, as +/// `for-each-ref` peels it, so a tag of a tag reports the inner tag object with +/// type `tag`), not the tag object itself. +#[derive(Debug, Clone, serde::Serialize)] +pub struct TagInfo { + pub name: String, + pub target: String, + pub target_type: String, + pub annotated: bool, +} + +/// List up to `max` tags, newest version first by tag name, and whether more +/// exist. One bounded `for-each-ref` child; it is asked for `max + 1` rows so the +/// extra one only sets the flag. `version:refname` sorts on names alone, so the +/// cost does not grow with tag-object reads. Tags on trees and blobs are listed +/// with their type and never dereferenced. A name that is not UTF-8 cannot be +/// carried in JSON and is left out. A ref whose object is missing makes git fail, +/// which is an error here rather than a listing without that tag. +pub fn list_tags_bounded( + git_bin: &str, + repo_path: &Path, + max: usize, + deadline: std::time::Instant, +) -> Result<(Vec, bool)> { + let out = crate::git::visibility_pack::run_bounded_git( + git_bin, + &[ + "for-each-ref", + "--sort=-version:refname", + &format!("--count={}", max + 1), + "--format=%(refname:strip=2)%00%(objectname)%00%(objecttype)%00%(*objectname)%00%(*objecttype)", + "refs/tags", + ], + repo_path, + b"", + deadline, + )?; + let mut records: Vec<&[u8]> = out + .split(|b| *b == b'\n') + .filter(|l| !l.is_empty()) + .collect(); + let truncated = records.len() > max; + records.truncate(max); + let mut tags = Vec::with_capacity(records.len()); + for record in records { + let fields: Vec<&[u8]> = record.split(|b| *b == 0).collect(); + let [name, object, object_type, peeled, peeled_type] = fields[..] else { + bail!("git for-each-ref printed an unexpected tag record"); + }; + let Ok(name) = std::str::from_utf8(name) else { + continue; + }; + let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); + let annotated = !peeled.is_empty(); + let (target, target_type) = if annotated { + (text(peeled), text(peeled_type)) + } else { + (text(object), text(object_type)) + }; + tags.push(TagInfo { + name: name.to_string(), + target, + target_type, + annotated, + }); + } + Ok((tags, truncated)) } /// List files in a tree at the given ref and path. @@ -3816,4 +4155,474 @@ mod tests { "a rev-parse probe failure must not read as an empty repo" ); } + + // ---- bounded head resolution, position lookup, and paged log ---- + + fn far_deadline() -> std::time::Instant { + std::time::Instant::now() + std::time::Duration::from_secs(60) + } + + /// Run real git in `dir` with fixed identity and a fixed commit date, and + /// return trimmed stdout. + fn git_at(dir: &Path, args: &[&str], date: i64) -> String { + let when = format!("{date} +0000"); + let out = Command::new("git") + .args(args) + .current_dir(dir) + .env("GIT_AUTHOR_NAME", "Test Author") + .env("GIT_AUTHOR_EMAIL", "author@example.com") + .env("GIT_COMMITTER_NAME", "Test Committer") + .env("GIT_COMMITTER_EMAIL", "committer@example.com") + .env("GIT_AUTHOR_DATE", &when) + .env("GIT_COMMITTER_DATE", &when) + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + /// Empty commit with `subject` at time `t`; returns its id. + fn commit_at(dir: &Path, subject: &str, t: i64) -> String { + git_at(dir, &["commit", "--allow-empty", "-q", "-m", subject], t); + git_at(dir, &["rev-parse", "HEAD"], t) + } + + const T0: i64 = 1_700_000_000; + + /// A working repo with `main` holding c1..c5 (c5 newest). Returns the + /// tempdir, the repo's git dir (laid out like a bare repo for the + /// functions under test), and the ids c1..c5 in that order. + fn linear_repo() -> (tempfile::TempDir, std::path::PathBuf, Vec) { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().to_path_buf(); + git_at(&work, &["init", "-q", "-b", "main"], T0); + let ids = (1..=5) + .map(|i| commit_at(&work, &format!("c{i}"), T0 + i * 100)) + .collect(); + let git_dir = work.join(".git"); + (td, git_dir, ids) + } + + fn hashes(commits: Vec) -> Vec { + commits.into_iter().map(|c| c.hash).collect() + } + + #[test] + fn bounded_log_pages_a_linear_history_by_position() { + let (_td, git_dir, ids) = linear_repo(); + let head = super::resolve_head_id_bounded("git", &git_dir, "main", far_deadline()) + .unwrap() + .expect("a populated repo has a head"); + assert_eq!(head, ids[4], "head is the newest commit"); + + let page = |skip: usize, limit: usize| { + hashes(super::log_bounded("git", &git_dir, &head, skip, limit, far_deadline()).unwrap()) + }; + let pos = |id: &str| { + super::commit_position_bounded("git", &git_dir, &head, id, far_deadline()).unwrap() + }; + + assert_eq!(page(0, 2), vec![ids[4].clone(), ids[3].clone()]); + assert_eq!(pos(&ids[3]), Some(1)); + assert_eq!(page(2, 2), vec![ids[2].clone(), ids[1].clone()]); + assert_eq!(pos(&ids[1]), Some(3)); + assert_eq!(page(4, 2), vec![ids[0].clone()]); + assert_eq!(pos(&ids[0]), Some(4)); + assert_eq!(page(5, 2), Vec::::new()); + assert_eq!(pos(&ids[4]), Some(0)); + + // The row format is the one `log` serves. + let first = super::log_bounded("git", &git_dir, &head, 0, 1, far_deadline()).unwrap(); + assert_eq!(first.len(), 1); + assert_eq!(first[0].subject, "c5"); + assert_eq!(first[0].author_name, "Test Author"); + assert_eq!(first[0].author_email, "author@example.com"); + assert_eq!(first[0].timestamp, T0 + 500); + } + + #[test] + fn bounded_log_matches_the_unbounded_log_rows() { + let (_td, git_dir, ids) = linear_repo(); + let head = super::resolve_head_id_bounded("git", &git_dir, "main", far_deadline()) + .unwrap() + .unwrap(); + let bounded = super::log_bounded("git", &git_dir, &head, 0, 3, far_deadline()).unwrap(); + let unbounded = super::log(&git_dir, "HEAD", 3).unwrap(); + assert_eq!(hashes(bounded.clone()), hashes(unbounded.clone())); + assert_eq!( + hashes(bounded), + vec![ids[4].clone(), ids[3].clone(), ids[2].clone()] + ); + for (b, u) in super::log_bounded("git", &git_dir, &head, 0, 3, far_deadline()) + .unwrap() + .iter() + .zip(unbounded.iter()) + { + assert_eq!( + (&b.author_name, &b.author_email, b.timestamp, &b.subject), + (&u.author_name, &u.author_email, u.timestamp, &u.subject) + ); + } + } + + /// base, then A1/A2 on branch `a` and B1/B2 on `main`, then merge M of `a` + /// into `main`. Committer dates make the history order exactly + /// M, B2, A2, B1, A1, base. Returns [M, B2, A2, B1, A1, base] ids. + fn merge_repo() -> (tempfile::TempDir, std::path::PathBuf, Vec) { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().to_path_buf(); + git_at(&work, &["init", "-q", "-b", "main"], T0); + let base = commit_at(&work, "base", T0 + 100); + git_at(&work, &["checkout", "-q", "-b", "a"], T0 + 110); + let a1 = commit_at(&work, "A1", T0 + 200); + git_at(&work, &["checkout", "-q", "main"], T0 + 210); + let b1 = commit_at(&work, "B1", T0 + 300); + git_at(&work, &["checkout", "-q", "a"], T0 + 310); + let a2 = commit_at(&work, "A2", T0 + 400); + git_at(&work, &["checkout", "-q", "main"], T0 + 410); + let b2 = commit_at(&work, "B2", T0 + 500); + git_at(&work, &["merge", "--no-ff", "-q", "-m", "M", "a"], T0 + 600); + let m = git_at(&work, &["rev-parse", "HEAD"], T0 + 600); + let git_dir = work.join(".git"); + (td, git_dir, vec![m, b2, a2, b1, a1, base]) + } + + #[test] + fn bounded_log_pages_a_merge_history_exactly_once_each() { + let (_td, git_dir, order) = merge_repo(); + let head = super::resolve_head_id_bounded("git", &git_dir, "main", far_deadline()) + .unwrap() + .unwrap(); + assert_eq!(head, order[0]); + + // The positions are the documented order, not derived from the code. + for (i, id) in order.iter().enumerate() { + assert_eq!( + super::commit_position_bounded("git", &git_dir, &head, id, far_deadline()).unwrap(), + Some(i), + "position of {id}" + ); + } + + // Page by the last row's id, as a client would. + let mut seen: Vec> = Vec::new(); + let mut skip = 0usize; + loop { + let page = hashes( + super::log_bounded("git", &git_dir, &head, skip, 2, far_deadline()).unwrap(), + ); + if page.is_empty() { + seen.push(page); + break; + } + let last = page.last().unwrap().clone(); + seen.push(page); + skip = super::commit_position_bounded("git", &git_dir, &head, &last, far_deadline()) + .unwrap() + .unwrap() + + 1; + } + assert_eq!( + seen, + vec![ + vec![order[0].clone(), order[1].clone()], + vec![order[2].clone(), order[3].clone()], + vec![order[4].clone(), order[5].clone()], + vec![], + ] + ); + } + + #[test] + fn commit_position_is_not_found_for_commits_outside_the_head_history() { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().to_path_buf(); + git_at(&work, &["init", "-q", "-b", "main"], T0); + commit_at(&work, "m1", T0 + 100); + // A commit only on a branch that is then deleted: it stays in the object store. + git_at(&work, &["checkout", "-q", "-b", "gone"], T0 + 150); + let deleted = commit_at(&work, "gone1", T0 + 200); + // A commit on another live branch that main does not contain. + git_at(&work, &["checkout", "-q", "main"], T0 + 250); + git_at(&work, &["checkout", "-q", "-b", "other"], T0 + 260); + let other = commit_at(&work, "other1", T0 + 300); + git_at(&work, &["checkout", "-q", "main"], T0 + 350); + let m2 = commit_at(&work, "m2", T0 + 400); + git_at(&work, &["branch", "-D", "gone"], T0 + 450); + let tree = git_at(&work, &["rev-parse", "HEAD^{tree}"], T0); + let git_dir = work.join(".git"); + + // The ids really are in the store, so "not found" is about history, not absence. + assert_eq!(git_at(&work, &["cat-file", "-t", &deleted], T0), "commit"); + assert_eq!(git_at(&work, &["cat-file", "-t", &other], T0), "commit"); + assert_eq!(git_at(&work, &["cat-file", "-t", &tree], T0), "tree"); + + let head = super::resolve_head_id_bounded("git", &git_dir, "main", far_deadline()) + .unwrap() + .unwrap(); + assert_eq!(head, m2); + for (label, id) in [ + ("deleted branch", deleted.as_str()), + ("other live branch", other.as_str()), + ("tree id", tree.as_str()), + ("well-formed id naming nothing", &"a".repeat(40)), + ] { + assert_eq!( + super::commit_position_bounded("git", &git_dir, &head, id, far_deadline()).unwrap(), + None, + "{label} must read as not found" + ); + } + // Control: a commit in the history is found. + assert!( + super::commit_position_bounded("git", &git_dir, &head, &m2, far_deadline()) + .unwrap() + .is_some() + ); + } + + #[test] + fn resolve_head_id_follows_head_then_preferred_then_the_branch_scan() { + // HEAD resolves: it wins over the preferred branch. + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().to_path_buf(); + git_at(&work, &["init", "-q", "-b", "main"], T0); + let main_id = commit_at(&work, "m", T0 + 100); + git_at(&work, &["checkout", "-q", "-b", "side"], T0 + 150); + let side_id = commit_at(&work, "s", T0 + 200); + git_at(&work, &["checkout", "-q", "main"], T0 + 250); + let git_dir = work.join(".git"); + let resolve = |preferred: &str| { + super::resolve_head_id_bounded("git", &git_dir, preferred, far_deadline()).unwrap() + }; + assert_eq!(resolve("side"), Some(main_id.clone())); + + // HEAD unborn: the preferred branch is used when it exists. + std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/unborn\n").unwrap(); + assert_eq!(resolve("side"), Some(side_id.clone())); + // Preferred missing: the scan prefers main over other names. + assert_eq!(resolve("nope"), Some(main_id.clone())); + // No main/master/develop: the first branch alphabetically. + git_at(&work, &["branch", "-m", "main", "zeta"], T0 + 300); + git_at(&work, &["branch", "-m", "side", "alpha"], T0 + 310); + assert_eq!(resolve("nope"), Some(side_id)); + let _ = main_id; + } + + #[test] + fn resolve_head_id_head_ref_present_but_commit_missing_is_an_error() { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().to_path_buf(); + git_at(&work, &["init", "-q", "-b", "main"], T0); + let main_id = commit_at(&work, "m", T0 + 100); + git_at(&work, &["checkout", "-q", "-b", "side"], T0 + 150); + let side_id = commit_at(&work, "s", T0 + 200); + git_at(&work, &["checkout", "-q", "main"], T0 + 250); + let git_dir = work.join(".git"); + + // main's ref still names the commit, but the object is gone: HEAD is + // present yet unreadable, which is an error (#400), not a fallback to + // the preferred branch's history. + let (dir, file) = main_id.split_at(2); + std::fs::remove_file(git_dir.join("objects").join(dir).join(file)).unwrap(); + + let out = super::resolve_head_id_bounded("git", &git_dir, "side", far_deadline()); + assert!( + out.is_err(), + "a present-but-unreadable HEAD must not serve another branch: {out:?}" + ); + let _ = side_id; + } + + #[test] + fn resolve_head_id_unborn_head_with_an_absent_ref_is_none() { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().to_path_buf(); + git_at(&work, &["init", "-q", "-b", "main"], T0); + let git_dir = work.join(".git"); + assert_eq!( + super::resolve_head_id_bounded("git", &git_dir, "main", far_deadline()).unwrap(), + None, + "an unborn HEAD is an empty history, not an error" + ); + } + + #[test] + fn resolve_head_id_ref_file_holding_garbage_is_an_error_not_empty() { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().to_path_buf(); + git_at(&work, &["init", "-q", "-b", "main"], T0); + commit_at(&work, "c1", T0 + 100); + let git_dir = work.join(".git"); + std::fs::write(git_dir.join("refs/heads/main"), b"garbage\n").unwrap(); + let out = super::resolve_head_id_bounded("git", &git_dir, "main", far_deadline()); + assert!( + out.is_err(), + "a damaged branch ref must not read as an empty history: {out:?}" + ); + } + + #[test] + fn resolve_head_id_on_a_non_repo_is_an_error_not_empty() { + let td = tempfile::TempDir::new().unwrap(); + let not_a_repo = td.path().join("not-a-repo"); + std::fs::create_dir_all(¬_a_repo).unwrap(); + let out = super::resolve_head_id_bounded("git", ¬_a_repo, "main", far_deadline()); + assert!( + out.is_err(), + "a failed probe must not read as empty: {out:?}" + ); + } + + #[test] + fn log_bounded_failure_is_an_error_not_an_empty_page() { + let (_td, git_dir, _ids) = linear_repo(); + let missing = "b".repeat(40); + let out = super::log_bounded("git", &git_dir, &missing, 0, 5, far_deadline()); + assert!(out.is_err(), "an unreadable head is an error: {out:?}"); + let out = + super::commit_position_bounded("git", &git_dir, &missing, &missing, far_deadline()); + assert!(out.is_err(), "a failed rev-list is an error: {out:?}"); + } + + /// Fake git that sleeps on `slow` and hands every other subcommand to real git. + #[cfg(unix)] + fn slow_on(dir: &Path, slow: &str) -> String { + let p = dir.join("slowgit"); + write_fake_git( + &p, + &format!( + "#!/bin/sh\ncase \"$1\" in\n {slow}) sleep 30 ;;\n *) exec git \"$@\" ;;\nesac\n" + ), + ); + p.to_str().unwrap().to_string() + } + + #[cfg(unix)] + fn is_service_timeout(err: &anyhow::Error) -> bool { + err.downcast_ref::() + .is_some() + } + + #[cfg(unix)] + #[test] + fn head_resolution_times_out_when_rev_parse_hangs() { + let (td, git_dir, _ids) = linear_repo(); + let fake = slow_on(td.path(), "rev-parse"); + let started = std::time::Instant::now(); + let err = super::resolve_head_id_bounded( + &fake, + &git_dir, + "main", + std::time::Instant::now() + std::time::Duration::from_secs(1), + ) + .expect_err("a hung rev-parse must time out"); + assert!(is_service_timeout(&err), "got: {err:#}"); + assert!(started.elapsed() < std::time::Duration::from_secs(10)); + } + + #[cfg(unix)] + #[test] + fn position_scan_times_out_when_rev_list_hangs() { + let (td, git_dir, ids) = linear_repo(); + let fake = slow_on(td.path(), "rev-list"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + let head = super::resolve_head_id_bounded(&fake, &git_dir, "main", deadline) + .unwrap() + .unwrap(); + let started = std::time::Instant::now(); + let err = super::commit_position_bounded(&fake, &git_dir, &head, &ids[0], deadline) + .expect_err("a hung rev-list must time out"); + assert!(is_service_timeout(&err), "got: {err:#}"); + assert!(started.elapsed() < std::time::Duration::from_secs(10)); + } + + #[cfg(unix)] + #[test] + fn log_page_times_out_when_log_hangs() { + let (td, git_dir, _ids) = linear_repo(); + let fake = slow_on(td.path(), "log"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + let head = super::resolve_head_id_bounded(&fake, &git_dir, "main", deadline) + .unwrap() + .unwrap(); + let started = std::time::Instant::now(); + let err = super::log_bounded(&fake, &git_dir, &head, 0, 5, deadline) + .expect_err("a hung log must time out"); + assert!(is_service_timeout(&err), "got: {err:#}"); + assert!(started.elapsed() < std::time::Duration::from_secs(10)); + } + + /// A rev-list that prints the target on its second line and then never stops: + /// the scan must return as soon as it sees the target, not read to the deadline. + #[cfg(unix)] + #[test] + fn position_scan_stops_reading_once_the_commit_is_found() { + let td = tempfile::TempDir::new().unwrap(); + let fake = td.path().join("endless"); + write_fake_git( + &fake, + "#!/bin/sh\ncase \"$1\" in\n rev-list) echo aaaa; echo bbbb; exec yes cccc ;;\nesac\n", + ); + let started = std::time::Instant::now(); + let found = super::commit_position_bounded( + fake.to_str().unwrap(), + td.path(), + "head", + "bbbb", + std::time::Instant::now() + std::time::Duration::from_secs(20), + ) + .unwrap(); + assert_eq!(found, Some(1)); + assert!( + started.elapsed() < std::time::Duration::from_secs(10), + "the scan kept reading after it found the commit" + ); + } + + /// Output with no line break cannot be a rev-list: the scan must fail rather + /// than buffer it without bound. + #[cfg(unix)] + #[test] + fn position_scan_rejects_an_unbounded_line_instead_of_buffering_it() { + let td = tempfile::TempDir::new().unwrap(); + let fake = td.path().join("noline"); + write_fake_git( + &fake, + "#!/bin/sh\ncase \"$1\" in\n rev-list) yes x | tr -d '\\n' ;;\nesac\n", + ); + let started = std::time::Instant::now(); + let err = super::commit_position_bounded( + fake.to_str().unwrap(), + td.path(), + "head", + "bbbb", + std::time::Instant::now() + std::time::Duration::from_secs(20), + ) + .expect_err("a line with no end must be refused"); + assert!(!is_service_timeout(&err), "got: {err:#}"); + assert!(started.elapsed() < std::time::Duration::from_secs(10)); + } + + #[test] + fn position_scan_matches_a_line_split_across_chunks() { + let mut scan = super::PositionScan::new(b"bbb"); + for byte in b"aa\nbb" { + assert!(scan.feed(&[*byte]).unwrap()); + } + assert!(scan.feed(b"b").unwrap()); + // The id is complete but its line has not ended: not yet a match. + assert_eq!(scan.found(), None); + assert!(!scan.feed(b"\ncc\n").unwrap()); + assert_eq!(scan.found(), Some(1)); + + // A longer line that merely starts with the target is not a match. + let mut scan = super::PositionScan::new(b"bbb"); + assert!(!scan.feed(b"bbbb\nbbb\n").unwrap()); + assert_eq!(scan.found(), Some(1)); + } } diff --git a/crates/twigpine-node/src/git/visibility_pack.rs b/crates/twigpine-node/src/git/visibility_pack.rs index adbb9da1..5528d78f 100644 --- a/crates/twigpine-node/src/git/visibility_pack.rs +++ b/crates/twigpine-node/src/git/visibility_pack.rs @@ -137,6 +137,39 @@ fn run_bounded_git_raw_impl( isolated_https: bool, isolated_config: &[(&str, &str)], ) -> Result<(std::process::ExitStatus, Vec, Vec)> { + let mut out = Vec::new(); + let (status, err, _stopped) = run_bounded_git_sink_impl( + git_bin, + args, + repo_path, + stdin_bytes, + deadline, + isolated_https, + isolated_config, + &mut |chunk| { + out.extend_from_slice(chunk); + true + }, + )?; + Ok((status, out, err)) +} + +/// The bounded runner proper. Stdout is handed to `on_chunk` as it arrives; when +/// it returns false the child's whole process group is SIGKILLed at once and the +/// call returns `stopped == true` with whatever status the killed child had. A +/// stop is a result, never a timeout. +#[cfg(unix)] +#[allow(clippy::too_many_arguments)] +fn run_bounded_git_sink_impl( + git_bin: &str, + args: &[&str], + repo_path: &Path, + stdin_bytes: &[u8], + deadline: Instant, + isolated_https: bool, + isolated_config: &[(&str, &str)], + on_chunk: &mut dyn FnMut(&[u8]) -> bool, +) -> Result<(std::process::ExitStatus, Vec, bool)> { use std::io::{Read, Write}; use std::os::unix::process::CommandExt; use std::sync::mpsc::RecvTimeoutError; @@ -208,14 +241,35 @@ fn run_bounded_git_raw_impl( err }); let mut stdout = child.stdout.take().context("git stdout was not piped")?; - let mut out = Vec::new(); // Blocking drain, unblocked by the child closing stdout on exit. The watchdog's // SIGTERM/SIGKILL is what makes a hung child exit; a git wedged in uninterruptible // (D-state) I/O survives even SIGKILL, so this drain and the wait below can block // until the kernel returns, pinning the walk thread and its permit. That residual // is unreachable in userspace (no signal reaps a D-state process) and matches the // async `reap_group_on_timeout`, which likewise only warns and gives up there. - let read_result = stdout.read_to_end(&mut out); + let mut stopped = false; + let mut read_result: std::io::Result<()> = Ok(()); + let mut buf = [0u8; 64 * 1024]; + loop { + match stdout.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + if !on_chunk(&buf[..n]) { + // The caller has what it needs. SIGKILL the group now: the + // leader is still unreaped, so the pgid cannot be recycled. + stopped = true; + // SAFETY: kill(2) takes only integers and borrows no Rust memory. + unsafe { libc::kill(-pgid, libc::SIGKILL) }; + break; + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) => { + read_result = Err(e); + break; + } + } + } // The drain has returned, but that only means all stdout write ends are closed — // NOT that the child has exited. A group member, or the leader itself, can close // stdout and keep running; standing the watchdog down on the drain alone (as the @@ -247,10 +301,10 @@ fn run_bounded_git_raw_impl( // deadline. A child that exited on its own (success) is not a timeout even if the // watchdog fired late; only a child that did not exit successfully is a genuine // timeout, which keeps a walk completing at its budget from a spurious 504. - if killed && !status.success() { + if killed && !status.success() && !stopped { return Err(crate::git::smart_http::GitServiceTimeout.into()); } - Ok((status, out, err)) + Ok((status, err, stopped)) } pub(crate) fn run_bounded_git_raw( @@ -263,6 +317,47 @@ pub(crate) fn run_bounded_git_raw( run_bounded_git_raw_impl(git_bin, args, repo_path, stdin_bytes, deadline, false, &[]) } +/// Bounded git whose stdout is handed to `on_chunk` as it arrives instead of +/// being collected, so a caller that only needs a prefix of a long output holds +/// none of the rest in memory. `on_chunk` returns false to stop: the child is +/// then killed with its process group and the third tuple element is true. +/// Returns the status, the child's stderr, and whether the sink stopped it. The +/// deadline and teardown are those of [`run_bounded_git_raw`]. +#[cfg(unix)] +pub(crate) fn run_bounded_git_streaming( + git_bin: &str, + args: &[&str], + repo_path: &Path, + deadline: Instant, + on_chunk: &mut dyn FnMut(&[u8]) -> bool, +) -> Result<(std::process::ExitStatus, Vec, bool)> { + run_bounded_git_sink_impl( + git_bin, + args, + repo_path, + b"", + deadline, + false, + &[], + on_chunk, + ) +} + +/// Non-Unix fallback: the bounded runner there buffers, so the output is +/// delivered to the sink in one piece after the child exits. +#[cfg(not(unix))] +pub(crate) fn run_bounded_git_streaming( + git_bin: &str, + args: &[&str], + repo_path: &Path, + deadline: Instant, + on_chunk: &mut dyn FnMut(&[u8]) -> bool, +) -> Result<(std::process::ExitStatus, Vec, bool)> { + let (status, out, err) = run_bounded_git_raw(git_bin, args, repo_path, b"", deadline)?; + let stopped = !on_chunk(&out); + Ok((status, err, stopped)) +} + /// Run a bounded Git child without inheriting ambient Git/proxy/credential /// configuration. Reserved for owner-selected external HTTPS destinations; /// ordinary local Git operations retain their existing environment. @@ -6588,4 +6683,118 @@ esac\n"; got {direct_recipients:?}" ); } + + /// The streaming runner hands every byte to the sink, in order, and reports + /// the child's own status when the sink never stops it. + #[cfg(unix)] + #[test] + fn run_bounded_git_streaming_delivers_all_output_when_the_sink_continues() { + let tmp = TempDir::new().unwrap(); + let git_bin = write_fake_git(tmp.path(), "#!/bin/sh\nprintf 'one\\ntwo\\n'\n"); + let mut got = Vec::new(); + let (status, _err, stopped) = run_bounded_git_streaming( + &git_bin, + &["rev-list"], + tmp.path(), + Instant::now() + SH_STARTUP_HEADROOM, + &mut |chunk| { + got.extend_from_slice(chunk); + true + }, + ) + .unwrap(); + assert!(status.success()); + assert!(!stopped); + assert_eq!(got, b"one\ntwo\n"); + } + + /// A sink that stops ends an endless child at once, and the child's whole + /// process group is gone afterwards, including a descendant that ignores + /// SIGTERM and has closed its inherited stdout and stderr. This is not a + /// timeout. A stop path that killed only the leader would leave that descendant + /// alive, and its group with it. + #[cfg(unix)] + #[test] + fn run_bounded_git_streaming_stops_and_reaps_an_endless_child() { + use std::time::Duration; + let tmp = TempDir::new().unwrap(); + // The leader starts the descendant and waits for it to record its pid before + // it begins to produce output, so the stop can never beat the descendant's + // start. The descendant's loop is bounded so a broken stop path cannot leak + // a permanent orphan; the assertion fires well before then. + let body = "#!/bin/sh\n\ +echo $$ > pid\n\ +sh -c 'trap \"\" TERM; echo $$ > desc.pid; exec 1>&- 2>&-; i=0; while [ $i -lt 30 ]; do sleep 1; i=$((i+1)); done' &\n\ +while [ ! -s desc.pid ]; do sleep 0.01; done\n\ +exec yes abcdefgh\n"; + let git_bin = write_fake_git(tmp.path(), body); + let started = Instant::now(); + let mut seen = 0usize; + let (_status, _err, stopped) = run_bounded_git_streaming( + &git_bin, + &["rev-list"], + tmp.path(), + Instant::now() + Duration::from_secs(30), + &mut |chunk| { + seen += chunk.len(); + seen < 1000 + }, + ) + .expect("a sink stop is a result, not an error"); + assert!(stopped); + assert!(seen >= 1000); + assert!(started.elapsed() < Duration::from_secs(10)); + let read_pid = |name: &str| -> i32 { + std::fs::read_to_string(tmp.path().join(name)) + .unwrap() + .trim() + .parse() + .unwrap() + }; + let pgid = read_pid("pid"); + let desc = read_pid("desc.pid"); + assert_ne!(pgid, desc, "the descendant must be a separate process"); + let mut gone = false; + for _ in 0..300 { + // SAFETY: kill(2) with signal 0 only probes existence; ESRCH means no + // process is left in the group. + let rc = unsafe { libc::kill(-pgid, 0) }; + if rc != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) { + gone = true; + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + // Kill whatever is left so a RED run leaks no orphan. + unsafe { + libc::kill(desc, libc::SIGKILL); + libc::kill(-pgid, libc::SIGKILL); + } + assert!( + gone, + "the stopped child's process group (pgid {pgid}, descendant {desc}) must be gone, \ + not just its leader" + ); + } + + #[cfg(unix)] + #[test] + fn run_bounded_git_streaming_times_out_a_silent_child() { + use std::time::Duration; + let tmp = TempDir::new().unwrap(); + let git_bin = write_fake_git(tmp.path(), "#!/bin/sh\nsleep 30\n"); + let started = Instant::now(); + let err = run_bounded_git_streaming( + &git_bin, + &["rev-list"], + tmp.path(), + Instant::now() + SH_STARTUP_HEADROOM, + &mut |_| true, + ) + .expect_err("a silent child must hit the deadline"); + assert!(err + .downcast_ref::() + .is_some()); + assert!(started.elapsed() < Duration::from_secs(10)); + } } diff --git a/crates/twigpine-node/src/graphql/query.rs b/crates/twigpine-node/src/graphql/query.rs index ba3d9522..341ae53b 100644 --- a/crates/twigpine-node/src/graphql/query.rs +++ b/crates/twigpine-node/src/graphql/query.rs @@ -7,14 +7,23 @@ use crate::db::{Db, RepoRecord, MAX_VISIBLE_REPO_PAGE_SIZE, MAX_VISIBLE_TASK_PAG use super::types::{AgentTaskReadType, RefUpdateType, RepoPageType, RepoType, TaskPageType}; -fn repo_type(repo: RepoRecord) -> RepoType { - RepoType { - name: repo.name, - owner_did: repo.owner_did, - description: repo.description, - default_branch: repo.default_branch, - created_at: repo.created_at.to_rfc3339(), - } +async fn repo_types(db: &Db, repos: Vec) -> Result> { + let ids: Vec = repos.iter().map(|r| r.id.clone()).collect(); + let mut homepages = db + .list_repo_homepages(&ids) + .await + .map_err(crate::graphql::graphql_db_err)?; + Ok(repos + .into_iter() + .map(|repo| RepoType { + homepage: homepages.remove(&repo.id), + name: repo.name, + owner_did: repo.owner_did, + description: repo.description, + default_branch: repo.default_branch, + created_at: repo.created_at.to_rfc3339(), + }) + .collect()) } fn repo_cursor(repo: &RepoRecord) -> String { @@ -91,7 +100,7 @@ impl QueryRoot { } // Preserve the legacy activity ordering for complete, small lists. repos.sort_by_key(|repo| std::cmp::Reverse(repo.updated_at)); - Ok(repos.into_iter().map(repo_type).collect()) + repo_types(db, repos).await } /// Bounded visible repositories ordered by owner and name. Continue with @@ -137,7 +146,7 @@ impl QueryRoot { repos.truncate(limit as usize); let end_cursor = repos.last().map(repo_cursor); Ok(RepoPageType { - nodes: repos.into_iter().map(repo_type).collect(), + nodes: repo_types(db, repos).await?, has_next_page, end_cursor, }) @@ -535,6 +544,122 @@ mod tests { assert_eq!(p201["endCursor"], p200["endCursor"]); } + #[sqlx::test] + async fn repos_carry_their_own_homepage_and_a_private_one_stays_out(pool: PgPool) { + let db = db(pool).await; + let private_token = "https://private-fixture-token-6602.example.com"; + for (id, public) in [ + ("hp-a", true), + ("hp-b", true), + ("hp-none", true), + ("hp-priv", false), + ] { + db.create_repo(&repo(id, OWNER, id, public)).await.unwrap(); + } + for (id, url) in [ + ("hp-a", "https://a.example.com/one"), + ("hp-b", "https://b.example.com/two"), + ("hp-priv", private_token), + ] { + assert_eq!(db.set_repo_homepage(id, Some(url)).await.unwrap(), 1); + } + let schema = schema(db); + + let homepages = |json: &serde_json::Value, field: &str| -> Vec<(String, Option)> { + let rows = if field == "repos" { + json["repos"].as_array().unwrap().clone() + } else { + json["reposPage"]["nodes"].as_array().unwrap().clone() + }; + let mut out: Vec<_> = rows + .iter() + .map(|r| { + ( + r["name"].as_str().unwrap().to_owned(), + r["homepage"].as_str().map(str::to_owned), + ) + }) + .collect(); + out.sort(); + out + }; + let expected = vec![ + ( + "hp-a".to_owned(), + Some("https://a.example.com/one".to_owned()), + ), + ( + "hp-b".to_owned(), + Some("https://b.example.com/two".to_owned()), + ), + ("hp-none".to_owned(), None), + ]; + + // Anonymous: each public repo carries its own homepage, null where + // unset, and the private repo and its homepage are nowhere. + let resp = anon(&schema, "{ repos { name homepage } }").await; + assert!(resp.errors.is_empty(), "{:?}", resp.errors); + let json = resp.data.into_json().unwrap(); + assert_eq!(homepages(&json, "repos"), expected); + assert!(!json.to_string().contains("6602")); + assert!(!json.to_string().contains("hp-priv")); + + let resp = anon(&schema, "{ reposPage { nodes { name homepage } } }").await; + assert!(resp.errors.is_empty(), "{:?}", resp.errors); + let json = resp.data.into_json().unwrap(); + assert_eq!(homepages(&json, "reposPage"), expected); + assert!(!json.to_string().contains("6602")); + assert!(!json.to_string().contains("hp-priv")); + + // A signed stranger sees what an anonymous caller sees. + for query in [ + "{ repos { name homepage } }", + "{ reposPage { nodes { name homepage } } }", + ] { + let resp = authed(&schema, query, "did:key:zStranger").await; + assert!(resp.errors.is_empty(), "{:?}", resp.errors); + assert!(!resp.data.into_json().unwrap().to_string().contains("6602")); + } + + // The owner, signed, sees the private repo with its homepage. + let resp = authed(&schema, "{ repos { name homepage } }", OWNER).await; + assert!(resp.errors.is_empty(), "{:?}", resp.errors); + let json = resp.data.into_json().unwrap(); + assert!(homepages(&json, "repos") + .contains(&("hp-priv".to_owned(), Some(private_token.to_owned())))); + + // limit: 1 pages: every node carries its own repo's homepage. + let mut cursor: Option = None; + let mut seen = Vec::new(); + loop { + let resp = schema + .execute( + async_graphql::Request::new( + "query($after: String) { reposPage(limit: 1, after: $after) { nodes { name homepage } hasNextPage endCursor } }", + ) + .variables(async_graphql::Variables::from_json( + serde_json::json!({ "after": cursor }), + )), + ) + .await; + assert!(resp.errors.is_empty(), "{:?}", resp.errors); + let json = resp.data.into_json().unwrap(); + let page = &json["reposPage"]; + let nodes = page["nodes"].as_array().unwrap(); + assert_eq!(nodes.len(), 1); + seen.push(( + nodes[0]["name"].as_str().unwrap().to_owned(), + nodes[0]["homepage"].as_str().map(str::to_owned), + )); + if !page["hasNextPage"].as_bool().unwrap() { + break; + } + cursor = Some(page["endCursor"].as_str().unwrap().to_owned()); + } + seen.sort(); + assert_eq!(seen, expected); + } + #[sqlx::test] async fn repos_page_visibility_matches_the_shared_gate(pool: PgPool) { use crate::db::VisibilityMode; diff --git a/crates/twigpine-node/src/graphql/types.rs b/crates/twigpine-node/src/graphql/types.rs index 506f36fe..fb4613bf 100644 --- a/crates/twigpine-node/src/graphql/types.rs +++ b/crates/twigpine-node/src/graphql/types.rs @@ -9,6 +9,8 @@ pub struct RepoType { pub description: Option, pub default_branch: String, pub created_at: String, + /// Absolute http(s) URL the repo's owner set, or null. + pub homepage: Option, } #[derive(SimpleObject)] diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 64c6f56a..d76676ae 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -324,6 +324,10 @@ pub fn build_router(state: AppState) -> Router { "/api/v1/repos/{owner}/{repo}/labels/{label}", axum::routing::delete(labels::remove_label), ) + .route( + "/api/v1/repos/{owner}/{repo}/homepage", + axum::routing::put(repos::set_homepage), + ) .route( "/api/v1/repos/{owner}/{repo}/visibility", axum::routing::put(visibility::set_visibility) @@ -634,6 +638,7 @@ pub fn build_router(state: AppState) -> Router { "/api/v1/repos/{owner}/{repo}/commits", get(repos::list_commits), ) + .route("/api/v1/repos/{owner}/{repo}/tags", get(repos::list_tags)) .route( "/api/v1/repos/{owner}/{repo}/tree", get(repos::get_tree_root), diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 0d8cb5db..5988094e 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -19385,6 +19385,587 @@ mod tests { assert!(labels.contains(&"bug".to_string())); } + // ── PUT /repos/{owner}/{repo}/homepage ─────────────────────────────── + + const HP_OWNER: &str = "did:key:zHPOwner0000000000000000000000000000000000"; + const HP_OWNER_SHORT: &str = "zHPOwner0000000000000000000000000000000000"; + const HP_STRANGER: &str = "did:key:zHPStranger000000000000000000000000000000"; + + fn homepage_router(state: &crate::state::AppState) -> Router { + Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/homepage", + axum::routing::put(crate::api::repos::set_homepage), + ) + .with_state(state.clone()) + } + + fn put_homepage(did: &str, owner: &str, repo: &str, body: &str) -> Request { + signed_request_as( + did, + Method::PUT, + &format!("/api/v1/repos/{owner}/{repo}/homepage"), + Body::from(body.to_owned()), + ) + } + + async fn stored_homepage( + state: &crate::state::AppState, + owner: &str, + repo: &str, + ) -> Option { + let id = state.db.get_repo(owner, repo).await.unwrap().unwrap().id; + state.db.get_repo_homepage(&id).await.unwrap() + } + + #[sqlx::test] + async fn set_homepage_owner_sets_clears_and_resets(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&seed_repo(HP_OWNER, "hp-owner")) + .await + .unwrap(); + let url = "https://example.com/project?ref=1#top"; + let body = format!(r#"{{"homepage":"{url}"}}"#); + + // Full did:key form and the bare key form both own the repo, and + // setting the same value twice is not an error. + for did in [HP_OWNER, HP_OWNER_SHORT, HP_OWNER] { + let resp = homepage_router(&state) + .oneshot(put_homepage(did, HP_OWNER_SHORT, "hp-owner", &body)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK, "caller {did}"); + assert_eq!( + body_json(resp).await, + serde_json::json!({ "homepage": url }) + ); + assert_eq!( + stored_homepage(&state, HP_OWNER_SHORT, "hp-owner") + .await + .as_deref(), + Some(url), + "the exact submitted bytes are stored" + ); + } + + // Clearing: an explicit null, then an empty object, each from a set value. + for clear in [r#"{"homepage":null}"#, "{}"] { + let resp = homepage_router(&state) + .oneshot(put_homepage(HP_OWNER, HP_OWNER_SHORT, "hp-owner", &body)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let resp = homepage_router(&state) + .oneshot(put_homepage(HP_OWNER, HP_OWNER_SHORT, "hp-owner", clear)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK, "{clear}"); + assert_eq!( + body_json(resp).await, + serde_json::json!({ "homepage": null }), + "{clear}" + ); + assert_eq!( + stored_homepage(&state, HP_OWNER_SHORT, "hp-owner").await, + None + ); + } + } + + #[sqlx::test] + async fn set_homepage_bad_body_is_400_for_every_caller_and_repo(pool: PgPool) { + let state = test_state(pool).await; + let kept = "https://kept.example.com"; + state + .db + .create_repo(&seed_repo(HP_OWNER, "hp-body")) + .await + .unwrap(); + state + .db + .create_repo(&seed_private_repo(HP_OWNER, "hp-body-priv")) + .await + .unwrap(); + let id = state + .db + .get_repo(HP_OWNER_SHORT, "hp-body") + .await + .unwrap() + .unwrap() + .id; + assert_eq!( + state.db.set_repo_homepage(&id, Some(kept)).await.unwrap(), + 1 + ); + + let bad_bodies = [ + r#"{"homepage":"javascript:alert(1)"}"#, + r#"{"homepage":"http://localhost"}"#, + r#"{"homepage":"https://user:pw@example.com"}"#, + r#"{"homepage":""}"#, + r#"{"homepage":"https://x.example","description":"y"}"#, + r#"{"homepage":7}"#, + "not json", + "", + "null", + "7", + "\"x\"", + "[null]", + r#"["https://x.example"]"#, + ]; + for bad in bad_bodies { + let mut seen: Vec<(StatusCode, Vec)> = Vec::new(); + // Owner on a public repo, stranger on a public repo, stranger on a + // private repo, and a repo that does not exist: the check consults + // no repo state, so all four answer identically. + for (did, repo) in [ + (HP_OWNER, "hp-body"), + (HP_STRANGER, "hp-body"), + (HP_STRANGER, "hp-body-priv"), + (HP_STRANGER, "hp-body-missing"), + ] { + let resp = homepage_router(&state) + .oneshot(put_homepage(did, HP_OWNER_SHORT, repo, bad)) + .await + .unwrap(); + seen.push(status_and_bytes(resp).await); + } + for (status, _) in &seen { + assert_eq!(*status, StatusCode::BAD_REQUEST, "{bad}"); + } + // Bodies for the validator rejections are byte-identical across callers. + if bad.contains("homepage\":\"") && !bad.contains("description") { + assert!(seen.windows(2).all(|w| w[0].1 == w[1].1), "{bad}"); + } + } + assert_eq!( + stored_homepage(&state, HP_OWNER_SHORT, "hp-body") + .await + .as_deref(), + Some(kept), + "a rejected body leaves the stored value unchanged" + ); + } + + #[sqlx::test] + async fn set_homepage_non_owner_gets_403_and_nothing_is_written(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&seed_repo(HP_OWNER, "hp-pub")) + .await + .unwrap(); + let resp = homepage_router(&state) + .oneshot(put_homepage( + HP_STRANGER, + HP_OWNER_SHORT, + "hp-pub", + r#"{"homepage":"https://stranger.example.com"}"#, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::FORBIDDEN); + let body = body_json(resp).await; + assert_eq!(body["error"], "forbidden"); + assert_eq!(body["message"], crate::api::REPO_OWNER_ONLY_MESSAGE); + assert_eq!( + stored_homepage(&state, HP_OWNER_SHORT, "hp-pub").await, + None + ); + } + + #[sqlx::test] + async fn set_homepage_stranger_gets_the_missing_repo_404(pool: PgPool) { + use crate::db::VisibilityMode; + let state = test_state(pool).await; + let secret = "https://private-fixture-token-8841.example.com"; + let attempt = r#"{"homepage":"https://stranger-attempt-5520.example.com"}"#; + + state + .db + .create_repo(&seed_private_repo(HP_OWNER, "hp-private")) + .await + .unwrap(); + state + .db + .create_repo(&seed_repo(HP_OWNER, "hp-hidden")) + .await + .unwrap(); + state + .db + .create_repo(&seed_repo(HP_OWNER, "hp-quar")) + .await + .unwrap(); + let hidden_id = state + .db + .get_repo(HP_OWNER_SHORT, "hp-hidden") + .await + .unwrap() + .unwrap() + .id; + state + .db + .set_visibility_rule(&hidden_id, "/", VisibilityMode::B, &[], HP_OWNER) + .await + .unwrap(); + let quar_id = state + .db + .get_repo(HP_OWNER_SHORT, "hp-quar") + .await + .unwrap() + .unwrap() + .id; + state.db.set_repo_quarantine(&quar_id, true).await.unwrap(); + for repo in ["hp-private", "hp-hidden", "hp-quar"] { + let id = state + .db + .get_repo(HP_OWNER_SHORT, repo) + .await + .unwrap() + .unwrap() + .id; + assert_eq!( + state.db.set_repo_homepage(&id, Some(secret)).await.unwrap(), + 1 + ); + } + + // The missing-repo body, normalized by the requested name. + let missing = homepage_router(&state) + .oneshot(put_homepage( + HP_STRANGER, + HP_OWNER_SHORT, + "hp-nothing", + attempt, + )) + .await + .unwrap(); + assert_eq!(missing.status(), StatusCode::NOT_FOUND); + let missing_body = String::from_utf8(status_and_bytes(missing).await.1).unwrap(); + assert!(missing_body.contains("repo_not_found"), "{missing_body}"); + let expected = missing_body.replace("hp-nothing", ""); + + for repo in ["hp-private", "hp-hidden", "hp-quar"] { + let resp = homepage_router(&state) + .oneshot(put_homepage(HP_STRANGER, HP_OWNER_SHORT, repo, attempt)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{repo}"); + let headers = format!("{:?}", resp.headers()); + let body = String::from_utf8(status_and_bytes(resp).await.1).unwrap(); + assert_eq!(body.replace(repo, ""), expected, "{repo}"); + for token in ["private-fixture-token-8841", "stranger-attempt-5520"] { + assert!(!body.contains(token), "{repo} body leaks {token}"); + assert!(!headers.contains(token), "{repo} headers leak {token}"); + } + assert_eq!( + stored_homepage(&state, HP_OWNER_SHORT, repo) + .await + .as_deref(), + Some(secret), + "{repo} homepage unchanged" + ); + } + } + + #[sqlx::test] + async fn set_homepage_unsigned_request_is_401_before_any_lookup(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&seed_repo(HP_OWNER, "hp-anon")) + .await + .unwrap(); + // One request for a real repo and one for a missing repo: identical 401. + let mut bodies = Vec::new(); + for repo in ["hp-anon", "hp-anon-missing"] { + let resp = crate::server::build_router(state.clone()) + .oneshot( + Request::builder() + .method(Method::PUT) + .uri(format!("/api/v1/repos/{HP_OWNER_SHORT}/{repo}/homepage")) + .header("content-type", "application/json") + .body(Body::from(r#"{"homepage":"https://example.com"}"#)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "{repo}"); + bodies.push(String::from_utf8(status_and_bytes(resp).await.1).unwrap()); + } + assert_eq!(bodies[0], bodies[1]); + assert_eq!( + stored_homepage(&state, HP_OWNER_SHORT, "hp-anon").await, + None + ); + } + + #[sqlx::test] + async fn set_homepage_refuses_a_mirror_only_row_with_409(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .upsert_mirror_repo( + "z6MkHPMirrorOwner", + "hp-mirror", + "/tmp/hp-mirror", + None, + true, + ) + .await + .unwrap(); + let record = state + .db + .get_repo("z6MkHPMirrorOwner", "hp-mirror") + .await + .unwrap() + .unwrap(); + assert!(record.id.contains('/'), "fixture must be a slash-form id"); + state + .db + .set_repo_quarantine(&record.id, false) + .await + .unwrap(); + + let resp = homepage_router(&state) + .oneshot(put_homepage( + "did:key:z6MkHPMirrorOwner", + "z6MkHPMirrorOwner", + "hp-mirror", + r#"{"homepage":"https://example.com"}"#, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::CONFLICT); + assert_eq!(state.db.get_repo_homepage(&record.id).await.unwrap(), None); + } + + #[sqlx::test] + async fn store_homepage_on_a_removed_repo_is_404_not_success(pool: PgPool) { + let state = test_state(pool).await; + let gone = RepoRecord { + id: "deleted-after-the-gate".to_string(), + ..seed_repo(HP_OWNER, "hp-gone") + }; + let err = crate::api::repos::store_homepage(&state.db, &gone, Some("https://example.com")) + .await + .unwrap_err(); + assert!( + matches!(err, crate::error::AppError::RepoNotFound(_)), + "{err:?}" + ); + } + + #[sqlx::test] + async fn fork_does_not_inherit_the_source_homepage(pool: PgPool) { + use twigpine_core::http_sig::sign_request; + + let kp = Keypair::generate(); + let owner_did = kp.did().to_string(); + let short = owner_did.split(':').next_back().unwrap().to_string(); + let repos_dir = std::path::PathBuf::from("/tmp"); + let owner_dir = repos_dir.join(owner_did.replace([':', '/'], "_")); + let _cleanup = OwnerDirGuard(owner_dir.clone()); + + let state = test_state_with(pool, |cfg| cfg.repos_dir = repos_dir.clone()).await; + let source = seed_repo(&owner_did, "hp-fork-src"); + state.db.create_repo(&source).await.unwrap(); + assert_eq!( + state + .db + .set_repo_homepage(&source.id, Some("https://example.com/src")) + .await + .unwrap(), + 1 + ); + std::fs::create_dir_all(&owner_dir).unwrap(); + crate::git::store::init_bare(&crate::git::store::repo_disk_path( + &repos_dir, + &owner_did, + "hp-fork-src", + )) + .unwrap(); + + let path = format!("/api/v1/repos/{short}/hp-fork-src/fork"); + let body = serde_json::to_vec(&serde_json::json!({ "name": "hp-fork-copy" })).unwrap(); + let signed = sign_request(&kp, "POST", &path, &body); + let req = Request::builder() + .method(Method::POST) + .uri(&path) + .header("content-type", "application/json") + .header("content-digest", signed.content_digest) + .header("signature-input", signed.signature_input) + .header("signature", signed.signature) + .body(Body::from(body)) + .unwrap(); + let resp = crate::server::build_router(state.clone()) + .oneshot(req) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::CREATED); + let fork_body = body_json(resp).await; + assert!( + fork_body.get("homepage").is_none(), + "a fork response keeps its current shape: {fork_body}" + ); + assert_eq!(stored_homepage(&state, &short, "hp-fork-copy").await, None); + assert_eq!( + stored_homepage(&state, &short, "hp-fork-src") + .await + .as_deref(), + Some("https://example.com/src") + ); + } + + // ── GET /repos/{owner}/{repo} carries the homepage ─────────────────── + + fn get_repo_router(state: &crate::state::AppState) -> Router { + Router::new() + .route( + "/api/v1/repos/{owner}/{repo}", + axum::routing::get(crate::api::repos::get_repo), + ) + .route( + "/api/v1/repos", + axum::routing::get(crate::api::repos::list_repos), + ) + .with_state(state.clone()) + } + + fn contains_key_anywhere(v: &serde_json::Value, key: &str) -> bool { + match v { + serde_json::Value::Object(m) => { + m.contains_key(key) || m.values().any(|c| contains_key_anywhere(c, key)) + } + serde_json::Value::Array(a) => a.iter().any(|c| contains_key_anywhere(c, key)), + _ => false, + } + } + + #[sqlx::test] + async fn get_repo_always_has_a_homepage_key_and_returns_the_stored_bytes(pool: PgPool) { + let state = test_state(pool).await; + let repo = seed_repo(HP_OWNER, "hp-get"); + state.db.create_repo(&repo).await.unwrap(); + let uri = format!("/api/v1/repos/{HP_OWNER_SHORT}/hp-get"); + + // No homepage: the key is present and null, not absent. + let resp = get_repo_router(&state) + .oneshot(anon_get(&uri)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = body_json(resp).await; + assert!(body.as_object().unwrap().contains_key("homepage"), "{body}"); + assert!(body["homepage"].is_null(), "{body}"); + assert_eq!( + body["name"], "hp-get", + "the existing fields are still there" + ); + assert!(body["clone_url"].is_string(), "{body}"); + + // Set through the owner route, then read back anonymously. + let url = "HTTPS://Example.com/Docs?ref=twigpine#start"; + let resp = homepage_router(&state) + .oneshot(put_homepage( + HP_OWNER, + HP_OWNER_SHORT, + "hp-get", + &format!(r#"{{"homepage":"{url}"}}"#), + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = body_json( + get_repo_router(&state) + .oneshot(anon_get(&uri)) + .await + .unwrap(), + ) + .await; + assert_eq!(body["homepage"], url, "exact stored bytes"); + + // Cleared again: back to null, key still present. + state.db.set_repo_homepage(&repo.id, None).await.unwrap(); + let body = body_json( + get_repo_router(&state) + .oneshot(anon_get(&uri)) + .await + .unwrap(), + ) + .await; + assert!(body.as_object().unwrap().contains_key("homepage")); + assert!(body["homepage"].is_null()); + } + + #[sqlx::test] + async fn get_repo_denial_does_not_leak_the_homepage(pool: PgPool) { + let state = test_state(pool).await; + let token = "https://private-fixture-token-7713.example.com"; + let repo = seed_private_repo(HP_OWNER, "hp-get-priv"); + state.db.create_repo(&repo).await.unwrap(); + state + .db + .set_repo_homepage(&repo.id, Some(token)) + .await + .unwrap(); + let uri = format!("/api/v1/repos/{HP_OWNER_SHORT}/hp-get-priv"); + + for caller in [None, Some(HP_STRANGER)] { + let req = match caller { + None => anon_get(&uri), + Some(did) => signed_request_as(did, Method::GET, &uri, Body::empty()), + }; + let resp = get_repo_router(&state).oneshot(req).await.unwrap(); + assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{caller:?}"); + let headers = format!("{:?}", resp.headers()); + let body = String::from_utf8(status_and_bytes(resp).await.1).unwrap(); + assert!(!body.contains("7713"), "{caller:?} body leaks the homepage"); + assert!( + !headers.contains("7713"), + "{caller:?} headers leak the homepage" + ); + } + + // The owner reads it. + let resp = get_repo_router(&state) + .oneshot(signed_request_as( + HP_OWNER, + Method::GET, + &uri, + Body::empty(), + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!(body_json(resp).await["homepage"], token); + } + + #[sqlx::test] + async fn repo_list_rows_do_not_carry_a_homepage_key(pool: PgPool) { + let state = test_state(pool).await; + let repo = seed_repo(HP_OWNER, "hp-list"); + state.db.create_repo(&repo).await.unwrap(); + state + .db + .set_repo_homepage(&repo.id, Some("https://example.com/list")) + .await + .unwrap(); + let resp = get_repo_router(&state) + .oneshot(anon_get("/api/v1/repos")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = body_json(resp).await; + assert!( + body.to_string().contains("hp-list"), + "fixture repo must be in the listing: {body}" + ); + assert!(!contains_key_anywhere(&body, "homepage"), "{body}"); + } + #[sqlx::test] async fn list_repo_bounties_gate_denies_anon_on_private(pool: PgPool) { let state = test_state(pool).await; diff --git a/crates/twigpine-node/tests/deny_harness.rs b/crates/twigpine-node/tests/deny_harness.rs index 26b0c0d7..a2213ca0 100644 --- a/crates/twigpine-node/tests/deny_harness.rs +++ b/crates/twigpine-node/tests/deny_harness.rs @@ -1406,6 +1406,7 @@ mod completeness { ("create_webhook", NotDrivenReason::ReadGatingMutation), ("delete_webhook", NotDrivenReason::ReadGatingMutation), ("set_visibility", NotDrivenReason::ReadGatingMutation), + ("set_homepage", NotDrivenReason::ReadGatingMutation), ("remove_visibility", NotDrivenReason::ReadGatingMutation), ("protect_branch", NotDrivenReason::ReadGatingMutation), ("unprotect_branch", NotDrivenReason::ReadGatingMutation), diff --git a/crates/twigpine-node/tests/support/routes.rs b/crates/twigpine-node/tests/support/routes.rs index 61ddf428..d7a1053f 100644 --- a/crates/twigpine-node/tests/support/routes.rs +++ b/crates/twigpine-node/tests/support/routes.rs @@ -408,6 +408,20 @@ pub fn deny_bearing_routes() -> &'static [Row] { id_source: IdSource::Fixed, anon_read: AnonRead::Deny404, }, + Row { + method: "PUT", + path: "/api/v1/repos/{owner}/{repo}/homepage", + gate: GateClass::OwnerGate, + handler: "repos::set_homepage", + // The owner twin really writes this; the stranger probes never reach + // the write. + body: Some(r#"{"homepage":"https://example.com/project"}"#), + needs: NO_ENTITY, + reach: Reach::None, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, Row { method: "POST", path: "/api/v1/repos/{owner}/{repo}/branches/{branch}/protect", @@ -562,6 +576,18 @@ pub fn deny_bearing_routes() -> &'static [Row] { id_source: IdSource::Fixed, anon_read: AnonRead::Deny404, }, + Row { + method: "GET", + path: "/api/v1/repos/{owner}/{repo}/tags", + gate: GateClass::ReadGate, + handler: "repos::list_tags", + body: None, + needs: NO_ENTITY, + reach: Reach::ReaderReads, + principals: NO_PRINCIPAL, + id_source: IdSource::Fixed, + anon_read: AnonRead::Deny404, + }, Row { method: "GET", path: "/api/v1/repos/{owner}/{repo}/tree",