From 3284645bcd2429c4f86a8d5b7916fa1ba56d71e4 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:15:41 -0600 Subject: [PATCH] fix(node): bound the issue close git children by the lock-hold deadline The close handler ran resolve_issue_id, get_issue and close_issue as bare git children under the write guard with no deadline, so one wedged git on an attacker-reachable close could pin the lock-pool session past the hold. Compute the guard's hold deadline once, immediately after acquire, refuse with the existing retryable 503 when it is already spent, and fund every under-lock git child from it through new *_bounded variants in git::issues that run on the shared bounded runner. The resolution rules are shared with the unbounded path (exact-id wins, dangling-exact fallthrough, ambiguous prefix, id validation). A child killed at the deadline surfaces as GitServiceTimeout and maps to RepoUnavailable, never a 500 git_error, and the publish-refusal rollback runs on the same deadline. A failed close that may have committed its update-ref first rewrites the pre-close JSON inside the hold budget, else drops the guard so the tree quarantines. Docs updated for the now-bounded close and the operator guidance on tightening the hold from the push-duration histogram. Closes #282 --- .env.example | 10 +- README.md | 2 +- crates/twigpine-node/src/api/issues.rs | 269 ++++++++++++-- crates/twigpine-node/src/config.rs | 4 +- crates/twigpine-node/src/git/issues.rs | 427 +++++++++++++++++++--- crates/twigpine-node/src/test_git_shim.rs | 6 +- crates/twigpine-node/src/test_support.rs | 2 +- 7 files changed, 619 insertions(+), 101 deletions(-) diff --git a/.env.example b/.env.example index 17a96959..5a356585 100644 --- a/.env.example +++ b/.env.example @@ -104,12 +104,14 @@ TWIGPINE_LOCK_HELD_TRANSFER_TIMEOUT_SECS=300 # process group dies, or merge writes, which take their guards without this # deadline: their git runs unbounded under the lock, and their refresh, # publish and unlock keep their own bounds, so a slow merge is never rolled -# back for overrunning it. Issue writes keep the deadline: an expired one refuses the -# write before the ref is touched, and a create's git is clamped to it, but a -# close's git runs unbounded once started. Unset, the +# back for overrunning it (merge is owner-only, and a stamped deadline +# mid-merge would rewind a completed merge). Issue writes keep the deadline: +# an expired one refuses the write before the ref is touched, and both the +# create's and the close's git children are clamped to it. Unset, the # effective bound is TWIGPINE_GIT_SERVICE_TIMEOUT_SECS itself (600 by # default), so it tracks the git budget up or down. Set it only to tighten -# the hold below the git budget; a value above +# the hold below the git budget; the gitlawb_push_duration_seconds histogram +# is the evidence for how far real pushes actually run. A value above # TWIGPINE_GIT_SERVICE_TIMEOUT_SECS is rejected at boot. #TWIGPINE_WRITE_LOCK_HOLD_TIMEOUT_SECS=300 # Seconds a request waits for a pool connection before failing with 503. diff --git a/README.md b/README.md index 33eea9bb..16ae00dc 100644 --- a/README.md +++ b/README.md @@ -434,7 +434,7 @@ Important node settings: | `TWIGPINE_MODEL_HOSTING_ENABLED` | Enable experimental model hosting (signed releases, block storage). Off by default; see `docs/RUN-A-NODE.md` for the quota and block-store knobs. | | `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. On the path-scoped upload-pack path the classification walk and the pack serve share ONE deadline, so this value bounds their combined duration rather than granting each stage a full budget: a walk that consumes it leaves the serve nothing and the clone gets a 504. Serving large path-scoped repos may therefore need a higher value than they did when each stage was budgeted separately. Accepted range is 1 to 3153600000 (100 years), since the node derives deadlines from this value and a larger one cannot be represented. | | `TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS` | Max seconds the storage-acquisition phase (Tigris HEAD/GET, push advisory-lock) of a served git op may run before the request is shed with a 503, separate from the git-run timeout. The concurrency permit is released on expiry so a stalled backend cannot pin the pool. Default 30. | -| `TWIGPINE_WRITE_LOCK_HOLD_TIMEOUT_SECS` | Max seconds a repo write guard may hold its advisory-lock pool connection, measured from lock-take. One deadline covers every phase under the lock: the under-lock refresh, the caller's under-lock work (for a push, the whole `receive-pack` subprocess, clamped to the lesser of `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), and the release-side upload/unlock. It bounds the lock-pool slot's hold, so a slow push cannot starve other writers for the sum of every per-phase bound. It does not bound the acquire-side lock wait (`TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS`), post-git outcome bookkeeping, the few seconds the detached reaper holds the session while the git process group dies, or merge writes, which take their guards without this deadline: their git runs unbounded under the lock, and their refresh, publish and unlock keep their own bounds, so a slow merge is never rolled back for overrunning it. Issue writes keep the deadline: an expired one refuses the write before the ref is touched, and a create's git is clamped to it, but a close's git runs unbounded once started. Unset, the effective bound is `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` itself (600 by default), tracking the git budget; set it only to tighten the hold below the git budget. An explicit value above `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` is rejected at boot. | +| `TWIGPINE_WRITE_LOCK_HOLD_TIMEOUT_SECS` | Max seconds a repo write guard may hold its advisory-lock pool connection, measured from lock-take. One deadline covers every phase under the lock: the under-lock refresh, the caller's under-lock work (for a push, the whole `receive-pack` subprocess, clamped to the lesser of `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), and the release-side upload/unlock. It bounds the lock-pool slot's hold, so a slow push cannot starve other writers for the sum of every per-phase bound. It does not bound the acquire-side lock wait (`TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS`), post-git outcome bookkeeping, the few seconds the detached reaper holds the session while the git process group dies, or merge writes, which take their guards without this deadline: their git runs unbounded under the lock, and their refresh, publish and unlock keep their own bounds, so a slow merge is never rolled back for overrunning it. Issue writes keep the deadline: an expired one refuses the write before the ref is touched, and both the create's and the close's git children are clamped to it. Unset, the effective bound is `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` itself (600 by default), tracking the git budget. The `gitlawb_push_duration_seconds` histogram is the evidence for tightening it below that: set the hold near the tail latency your pushes actually need, not lower. Merge is intentionally not bounded by it: it is owner-only, and a stamped deadline mid-merge would rewind a completed merge, so merge keeps its own per-phase bounds instead. An explicit value above `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` is rejected at boot. | | `TWIGPINE_MAX_CONCURRENT_GIT_OPS` | Max concurrent served git READ ops (upload-pack and its `info/refs` advertisement) across all callers; over-cap sheds a 503 + Retry-After. Anonymous reads draw from this pool, so pair it with `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER`. Pushes and the receive-pack advertisement have their own pools, so a read flood cannot shed an authenticated push. Default 128. | | `TWIGPINE_MAX_CONCURRENT_GIT_PUSHES` | Max concurrent `git-receive-pack` POST operations, in a pool separate from the read pool. The anon receive-pack `info/refs` advertisement runs in a third pool of the same size, disjoint from both, so an advertisement flood cannot shed a push either. Two per-source push caps are derived from this value (`/8`, floor 1) and have no env var of their own. Over-cap sheds a 503 + Retry-After. Default 32. | | `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER` | Max concurrent read ops a single caller may hold, so one caller cannot monopolize the read pool. Keyed on the resolved source IP, never the DID, and only as granular as `TWIGPINE_TRUSTED_PROXY`: left unset, a node behind an edge or NAT keys every caller on the edge IP and this collapses to one global cap. Default 16. | diff --git a/crates/twigpine-node/src/api/issues.rs b/crates/twigpine-node/src/api/issues.rs index db62b935..6d0d6d76 100644 --- a/crates/twigpine-node/src/api/issues.rs +++ b/crates/twigpine-node/src/api/issues.rs @@ -471,6 +471,19 @@ pub async fn close_issue( .map_err(|e| crate::api::repos::acquire_write_app_error(&e, &repo))?; let disk_path = guard.path().to_path_buf(); + // ONE lock-hold deadline funds every git child under the guard: the + // re-authorize re-read, the rollback snapshot, the close itself and the + // publish-refusal rollback. An expired deadline refuses before anything + // runs; a child killed at it surfaces as GitServiceTimeout, which the arms + // below map to the retryable 503 rather than a 500 git_error. + let git_timeout = std::time::Duration::from_secs(state.config.git_service_timeout_secs); + let Some(hold_deadline) = guard.hold_deadline(git_timeout) else { + let _ = guard.release(false).await; + tracing::warn!(repo = %repo, "lock-hold deadline expired before the issue close; refusing"); + return Err(AppError::RepoUnavailable); + }; + let git_bin = state.git_bin.clone(); + // Re-read under the guard and RE-AUTHORIZE against what we read, rather than // only confirming the issue still exists. The pre-lock read decided whether to // take the lock; it cannot be the authorization decision, because acquire_write @@ -478,7 +491,7 @@ pub async fn close_issue( // than the one the author was read from. Checking existence alone would leave the // whole decision resting on the earlier read of a tree we are no longer looking // at. The blob is already in hand here, so this costs a deserialize. - match git_issues::get_issue(&disk_path, &issue_id) { + match git_issues::get_issue_bounded(&git_bin, &disk_path, &issue_id, hold_deadline) { Ok(Some(raw)) => { let author_now: Option = serde_json::from_str::(&raw) .ok() @@ -512,40 +525,36 @@ pub async fn close_issue( } Err(e) => { let _ = guard.release(false).await; - return Err(AppError::Git(e.to_string())); + // A re-read that could not answer is not an authorization answer: + // a child killed at the hold deadline is the retryable refusal, + // never the 403/404 an unanswered check would otherwise fall into. + return Err(close_git_app_error(e)); } } // Snapshot the issue's pre-close JSON so a failed durable upload can roll // the close back on local disk, mirroring create_issue. Best-effort: if the // snapshot read fails we proceed without a rollback closure (the close still - // applies and a failed upload still surfaces as a 5xx below). + // applies and a failed upload still surfaces as a 5xx below). A snapshot + // read that hits the deadline is swallowed the same way: the bounded close + // below then fails at once on its own first child. // // Resolve first so the compensating rewrite below lands on the SAME ref the // close mutates. The path id may be an 8-char prefix, and rewriting // refs/gitlawb/issues/{prefix} with the pre-close content would leave the // canonical {full_id} ref closed while the client saw a 5xx. - let full_issue_id = git_issues::resolve_issue_id(&disk_path, &issue_id) - .ok() - .flatten(); - let prior_json = full_issue_id - .as_deref() - .and_then(|id| git_issues::get_issue(&disk_path, id).ok().flatten()); - - // An expired lock-hold deadline refuses before the ref is touched. The - // close's own git children are not clamped to it (there is no bounded - // close), so this bounds when the write may START, not how long it runs. - if guard - .hold_deadline(std::time::Duration::from_secs( - state.config.git_service_timeout_secs, - )) - .is_none() - { - let _ = guard.release(false).await; - tracing::warn!(repo = %repo, "lock-hold deadline expired before the issue close; refusing"); - return Err(AppError::RepoUnavailable); - } - let close_result = git_issues::close_issue(&disk_path, &issue_id); + let full_issue_id = + git_issues::resolve_issue_id_bounded(&git_bin, &disk_path, &issue_id, hold_deadline) + .ok() + .flatten(); + let prior_json = full_issue_id.as_deref().and_then(|id| { + git_issues::get_issue_bounded(&git_bin, &disk_path, id, hold_deadline) + .ok() + .flatten() + }); + + let close_result = + git_issues::close_issue_bounded(&git_bin, &disk_path, &issue_id, hold_deadline); // Always release the advisory lock — even on error; upload to Tigris only on success. // Same short-circuit as create_issue, and before the 200 body below. With a @@ -553,26 +562,56 @@ pub async fn close_issue( // content instead of leaving the local repo closed while the client saw 5xx. let release_result = match (close_result.is_ok(), prior_json, full_issue_id) { (true, Some(json), Some(resolved_id)) => { - let git_bin = state.git_bin.clone(); - let deadline = std::time::Instant::now() - + std::time::Duration::from_secs(state.config.git_service_timeout_secs); guard .release_compensating(true, move |path| { // Same bounded-write strategy create_issue's compensator - // uses: the rollback rewrites the ref with the pre-close - // content through the deadline-aware runner, so a hung git - // cannot stall the guard past git_service_timeout. - git_issues::create_issue_bounded(&git_bin, path, &resolved_id, &json, deadline) + // uses, funded by the SAME hold deadline the close ran on: + // the rollback rewrites the ref with the pre-close content + // through the deadline-aware runner, so a hung git cannot + // stall the guard past the lock hold. + git_issues::create_issue_bounded( + &git_bin, + path, + &resolved_id, + &json, + hold_deadline, + ) }) .await .into_result() } + (false, Some(json), Some(resolved_id)) => { + // A bounded close that erred may have committed its update-ref + // before the kill, the same uncertainty create's cleanup covers. + // Rewrite the pre-close JSON on the same hold budget before + // releasing; when the hold is spent or the rewrite fails, drop the + // guard unreleased so the tree quarantines rather than serve or + // publish an unacknowledged close. + let restored = git_issues::create_issue_bounded( + &git_bin, + &disk_path, + &resolved_id, + &json, + hold_deadline, + ) + .map_err(|e| { + tracing::warn!(repo = %repo, err = %e, "could not restore the issue ref after a failed close"); + }) + .is_ok(); + if restored { + guard.release(false).await.into_result() + } else { + tracing::warn!(repo = %repo, "failed-close rollback did not finish inside the lock-hold budget; quarantining the tree"); + drop(guard); + Ok(()) + } + } _ => guard.release(close_result.is_ok()).await.into_result(), }; release_result?; let updated = close_result - .map_err(|e| AppError::Git(e.to_string()))? + .map_err(close_git_app_error)? .ok_or_else(|| AppError::RepoNotFound(format!("issue {issue_id} not found")))?; let issue: serde_json::Value = serde_json::from_str(&updated) @@ -583,6 +622,19 @@ pub async fn close_issue( Ok(Json(issue)) } +/// Map a bounded-git failure under the close guard to the error the client +/// should see: a child killed at the lock-hold deadline is the retryable 503 +/// the refresh path uses, anything else keeps the git 500 it has always been. +fn close_git_app_error(e: anyhow::Error) -> AppError { + if e.downcast_ref::() + .is_some() + { + AppError::RepoUnavailable + } else { + AppError::Git(e.to_string()) + } +} + #[cfg(test)] mod tests { use super::*; @@ -1816,6 +1868,159 @@ mod lock_pool_shed_tests { ); } + /// #282: a git child of the close that hangs is torn down at the lock-hold + /// deadline instead of pinning the lock-pool connection for the shim's own + /// 30s sleep. The handler must answer the retryable 503 inside the bound, + /// the session must come back (a second write on a one-connection lock pool + /// succeeds), and the issue ref must still be open. + #[sqlx::test] + async fn close_issue_bounded_git_cannot_outlive_the_lock_hold(pool: PgPool) { + use crate::test_support::git_shim; + + let owner = "did:key:zISSUEHANGCLOSEAAAAAAAAAAAAAAAAAAAA"; + let repo_name = "hangclose"; + let mut state = crate::test_support::test_state(pool.clone()).await; + let disk = tempfile::TempDir::new().unwrap(); + let live = crate::git::repo_store::validated_repo_disk_path(disk.path(), owner, repo_name) + .expect("repo path"); + let mut seeded = seed_repo(owner, repo_name); + seeded.disk_path = live.to_string_lossy().to_string(); + state.db.create_repo(&seeded).await.expect("seed repo"); + crate::git::store::init_bare(&live).expect("init bare repo"); + let full_id = "abc12345-0000-0000-0000-000000000000"; + let open_json = serde_json::to_string(&IssueRecord { + id: full_id.to_string(), + title: "seeded".to_string(), + body: Some(String::new()), + author: Some(owner.to_string()), + created_at: chrono::Utc::now().to_rfc3339(), + status: "open".to_string(), + signed_payload: None, + }) + .expect("serialize seeded issue"); + git_issues::create_issue(&live, full_id, &open_json).expect("seed issue"); + + // One lock-pool connection, so a session still pinned by the wedged + // close would shed or stall the probe write below. + state.repo_store = crate::git::repo_store::RepoStore::for_testing( + disk.path().to_path_buf(), + crate::git::repo_store::build_lock_pool(&pool, 1, std::time::Duration::from_secs(1)), + ) + .with_lock_hold_timeout(std::time::Duration::from_secs(2)); + // Every bounded git child the close spawns has the live repo as its + // cwd, so a repo-scoped hang stalls the first one under the guard. + let shim = git_shim::create( + "gl-close-hang-git", + git_shim::Behavior::HangRepo("hangclose.git"), + ); + state.git_bin = shim.to_str().unwrap().to_string(); + + let started = std::time::Instant::now(); + let res = close_issue( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path(( + owner.to_string(), + repo_name.to_string(), + full_id.to_string(), + )), + axum::http::HeaderMap::new(), + crate::rate_limit::PeerAddr(None), + crate::auth::LedgerTicket::already_spent(), + ) + .await; + let elapsed = started.elapsed(); + + let err = res.expect_err("a hung under-lock git must refuse the close"); + assert_eq!( + err.into_response().status(), + StatusCode::SERVICE_UNAVAILABLE, + "a child killed at the hold deadline is the retryable 503, not a 500" + ); + assert!( + elapsed < std::time::Duration::from_secs(15), + "the close must stop at the 2s hold deadline plus teardown, not run the shim's 30s hang (took {elapsed:?})" + ); + + // The lock-pool session came back: a fresh write on the one-connection + // pool acquires instead of shedding as busy. + let second = state + .repo_store + .acquire_write(owner, repo_name) + .await + .expect("the hung close must not keep the lock-pool slot"); + second + .release(false) + .await + .into_result() + .expect("probe release"); + + assert_eq!( + git_issues::get_issue(&live, full_id) + .expect("read the ref") + .as_deref(), + Some(open_json.as_str()), + "the issue must still be open: the killed child wrote nothing" + ); + } + + /// The positive twin of the hold tests: a normal close on a store whose + /// hold deadline is generous still runs to completion and returns the + /// closed issue. + #[sqlx::test] + async fn close_issue_under_a_generous_hold_deadline_still_closes(pool: PgPool) { + let owner = "did:key:zISSUECLOSEBOUNDOKAAAAAAAAAAAAAAAAA"; + let repo_name = "boundclose-ok"; + let mut state = crate::test_support::test_state(pool.clone()).await; + let disk = tempfile::TempDir::new().unwrap(); + let live = crate::git::repo_store::validated_repo_disk_path(disk.path(), owner, repo_name) + .expect("repo path"); + let mut seeded = seed_repo(owner, repo_name); + seeded.disk_path = live.to_string_lossy().to_string(); + state.db.create_repo(&seeded).await.expect("seed repo"); + crate::git::store::init_bare(&live).expect("init bare repo"); + let full_id = "def99999-0000-0000-0000-000000000000"; + let open_json = serde_json::to_string(&IssueRecord { + id: full_id.to_string(), + title: "seeded".to_string(), + body: Some(String::new()), + author: Some(owner.to_string()), + created_at: chrono::Utc::now().to_rfc3339(), + status: "open".to_string(), + signed_payload: None, + }) + .expect("serialize seeded issue"); + git_issues::create_issue(&live, full_id, &open_json).expect("seed issue"); + state.repo_store = crate::git::repo_store::RepoStore::for_testing( + disk.path().to_path_buf(), + crate::git::repo_store::build_lock_pool(&pool, 2, std::time::Duration::from_secs(1)), + ) + .with_lock_hold_timeout(std::time::Duration::from_secs(60)); + + let res = close_issue( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path(( + owner.to_string(), + repo_name.to_string(), + full_id.to_string(), + )), + axum::http::HeaderMap::new(), + crate::rate_limit::PeerAddr(None), + crate::auth::LedgerTicket::already_spent(), + ) + .await; + let Json(issue) = res.expect("a normal close must succeed under the hold bound"); + assert_eq!(issue["status"], "closed"); + let stored: serde_json::Value = serde_json::from_str( + &git_issues::get_issue(&live, full_id) + .expect("read the ref") + .expect("ref still present"), + ) + .expect("stored issue parses"); + assert_eq!(stored["status"], "closed"); + } + /// The compensating rewrite after a refused publish must land on the ref the /// close actually mutated. A close addressed by an 8-char prefix resolves to /// the full id and closes `refs/gitlawb/issues/{full_id}`; a compensator diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index 59084b4f..cb488ba8 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -548,8 +548,8 @@ pub struct Config { /// the process group dies, or merge writes, which take their guards /// without this deadline and run unbounded git under them. Issue writes /// keep the deadline: an expired one refuses the write before the ref is - /// touched, and a create's git is clamped to it, but a close's git runs - /// unbounded once started. Must be positive and at most + /// touched, and both the create's and the close's git children are clamped + /// to it. Must be positive and at most /// `git_service_timeout_secs` (a hold bound above the git timeout can /// never bind before it). Unset (the default) the effective bound is /// `git_service_timeout_secs` itself (600s shipped), so every push keeps diff --git a/crates/twigpine-node/src/git/issues.rs b/crates/twigpine-node/src/git/issues.rs index 0fc843f3..a944a361 100644 --- a/crates/twigpine-node/src/git/issues.rs +++ b/crates/twigpine-node/src/git/issues.rs @@ -73,6 +73,13 @@ fn issue_ref_name_is_safe(ref_name: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') } +/// True iff `ref_name` appears verbatim in a `for-each-ref` listing. +fn ref_listed(for_each_ref_stdout: &[u8], ref_name: &str) -> bool { + String::from_utf8_lossy(for_each_ref_stdout) + .lines() + .any(|line| line.trim() == ref_name) +} + /// Resolve a ref name without putting it on a command line: enumerate refs /// (constant argv) and match in memory. A nonzero exit propagates, so "cannot /// determine" is an error rather than a quiet `false`. @@ -87,8 +94,53 @@ fn ref_name_resolves(repo_path: &Path, ref_name: &str) -> Result { let stderr = String::from_utf8_lossy(&out.stderr); anyhow::bail!("git for-each-ref failed: {}", stderr.trim()); } - let stdout = String::from_utf8_lossy(&out.stdout); - Ok(stdout.lines().any(|line| line.trim() == ref_name)) + Ok(ref_listed(&out.stdout, ref_name)) +} + +/// Deadline-bounded variant of [`ref_name_resolves`], same semantics on the +/// shared runner: a nonzero enumeration is an error, never a quiet `false`. +fn ref_name_resolves_bounded( + git_bin: &str, + repo_path: &Path, + ref_name: &str, + deadline: std::time::Instant, +) -> Result { + let out = crate::git::visibility_pack::run_bounded_git( + git_bin, + &["for-each-ref", "--format=%(refname)"], + repo_path, + b"", + deadline, + )?; + Ok(ref_listed(&out, ref_name)) +} + +/// The " blob " header parse and body slice of `cat-file --batch` +/// output, shared by the unbounded and bounded readers. The caller handles the +/// " missing" line first; anything else here is one object's answer. +fn catfile_batch_body(ref_name: &str, stdout: &[u8]) -> Result> { + // Header: " \n" then exactly bytes plus a newline. + let header_end = stdout + .iter() + .position(|b| *b == b'\n') + .context("unexpected git cat-file --batch output")?; + let header = String::from_utf8_lossy(&stdout[..header_end]); + let mut parts = header.split(' '); + parts.next(); + let obj_type = parts.next().unwrap_or(""); + if obj_type != "blob" { + anyhow::bail!("issue ref {ref_name} resolves to a non-blob object"); + } + let size: usize = parts + .next() + .and_then(|s| s.parse().ok()) + .context("unexpected git cat-file --batch header")?; + let body = &stdout[header_end + 1..]; + anyhow::ensure!( + body.len() >= size, + "truncated git cat-file --batch body for {ref_name}" + ); + Ok(Some(String::from_utf8_lossy(&body[..size]).to_string())) } /// Read the blob behind an issue ref. @@ -149,29 +201,43 @@ fn read_issue_blob(repo_path: &Path, ref_name: &str) -> Result> { }; } - // Header: " \n" then exactly bytes plus a newline. - let header_end = output - .stdout - .iter() - .position(|b| *b == b'\n') - .context("unexpected git cat-file --batch output")?; - let header = String::from_utf8_lossy(&output.stdout[..header_end]); - let mut parts = header.split(' '); - parts.next(); - let obj_type = parts.next().unwrap_or(""); - if obj_type != "blob" { - anyhow::bail!("issue ref {ref_name} resolves to a non-blob object"); + catfile_batch_body(ref_name, &output.stdout) +} + +/// Deadline-bounded variant of [`read_issue_blob`]: the same missing-vs-error +/// split and the same body parse, with the `cat-file` child and the +/// failure-path recheck on the shared bounded runner. +fn read_issue_blob_bounded( + git_bin: &str, + repo_path: &Path, + ref_name: &str, + deadline: std::time::Instant, +) -> Result> { + if !issue_ref_name_is_safe(ref_name) { + anyhow::bail!("refusing issue ref outside the issues namespace: {ref_name}"); } - let size: usize = parts - .next() - .and_then(|s| s.parse().ok()) - .context("unexpected git cat-file --batch header")?; - let body = &output.stdout[header_end + 1..]; - anyhow::ensure!( - body.len() >= size, - "truncated git cat-file --batch body for {ref_name}" - ); - Ok(Some(String::from_utf8_lossy(&body[..size]).to_string())) + + let mut spec = ref_name.as_bytes().to_vec(); + spec.push(b'\n'); + let stdout = crate::git::visibility_pack::run_bounded_git( + git_bin, + &["cat-file", "--batch"], + repo_path, + &spec, + deadline, + )?; + + // Same disambiguation as the unbounded reader: "missing" covers an absent + // ref and an unreadable object; only a ref that still resolves is an error. + let missing = format!("{ref_name} missing\n"); + if stdout.as_slice() == missing.as_bytes() { + return match ref_name_resolves_bounded(git_bin, repo_path, ref_name, deadline)? { + true => anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}"), + false => Ok(None), + }; + } + + catfile_batch_body(ref_name, &stdout) } /// Deadline-bounded variant of [`create_issue`] for compensation paths: the @@ -267,12 +333,12 @@ pub fn list_issues(repo_path: &Path) -> Result> { Ok(issues) } -/// Resolve an issue ID or 8-char prefix to the full UUID stored in git refs. -/// Returns Ok(Some(full_id)) on unique match, Ok(None) if not found, -/// Err if the prefix is ambiguous (matches more than one issue). -pub fn resolve_issue_id(repo_path: &Path, id_or_prefix: &str) -> Result> { +/// The (exact ref, enumeration glob) an issue id or prefix resolves through, or +/// `None` when the input is not a possible issue id at all. Shared by the +/// unbounded and bounded resolvers so both apply the same id validation. +fn issue_lookup_refs(id_or_prefix: &str) -> Option<(String, String)> { // The id comes from the request path and is spliced into a git revision and a - // for-each-ref pattern below. Issue ids are UUIDs, so accept only ASCII + // for-each-ref pattern. Issue ids are UUIDs, so accept only ASCII // alphanumerics and '-': anything else (`^{blob}`, `@{0}`, `*`, `/`, `..`) is // revision or glob syntax, never an issue id, and is reported as not found. if id_or_prefix.is_empty() @@ -280,28 +346,25 @@ pub fn resolve_issue_id(repo_path: &Path, id_or_prefix: &str) -> Result Result, +) -> Result> { + let output = String::from_utf8_lossy(for_each_ref_stdout); let matches: Vec<&str> = output .lines() .map(str::trim) @@ -312,14 +375,7 @@ pub fn resolve_issue_id(repo_path: &Path, id_or_prefix: &str) -> Result { - let check = Command::new("git") - .args(["cat-file", "-e", m]) - .current_dir(repo_path) - .output() - .context("failed to run git cat-file -e")?; - check.status.success().then_some(*m) - } + Some(m) => exact_object_exists(m)?.then_some(*m), None => None, }; let found = match exact { @@ -342,6 +398,86 @@ pub fn resolve_issue_id(repo_path: &Path, id_or_prefix: &str) -> Result Result> { + let Some((exact_ref, prefix_glob)) = issue_lookup_refs(id_or_prefix) else { + return Ok(None); + }; + + // allow-unbounded-git: this module's spawns predate the bounded runner; + // under-lock callers use resolve_issue_id_bounded. + let list = Command::new("git") + .args(["for-each-ref", "--format=%(refname)", &prefix_glob]) + .current_dir(repo_path) + .output() + .context("failed to run git for-each-ref")?; + + // for-each-ref exits 0 with empty output when nothing matches, so a + // nonzero exit is a real enumeration failure (e.g. not a repo), not + // "issue not found". + if !list.status.success() { + let stderr = String::from_utf8_lossy(&list.stderr); + anyhow::bail!("git for-each-ref failed: {}", stderr.trim()); + } + + resolve_issue_match(id_or_prefix, &exact_ref, &list.stdout, |m| { + // allow-unbounded-git: same pre-lock path as above; under-lock callers + // use resolve_issue_id_bounded. + let check = Command::new("git") + .args(["cat-file", "-e", m]) + .current_dir(repo_path) + .output() + .context("failed to run git cat-file -e")?; + Ok(check.status.success()) + }) +} + +/// Deadline-bounded variant of [`resolve_issue_id`]: the same lookup and the +/// same exact-id-wins, dangling-exact-fallthrough and ambiguous-prefix rules, +/// but every git child runs through the shared bounded runner so a hung git +/// cannot outlive the lock-hold deadline it is called under. +pub fn resolve_issue_id_bounded( + git_bin: &str, + repo_path: &Path, + id_or_prefix: &str, + deadline: std::time::Instant, +) -> Result> { + let Some((exact_ref, prefix_glob)) = issue_lookup_refs(id_or_prefix) else { + return Ok(None); + }; + + let stdout = crate::git::visibility_pack::run_bounded_git( + git_bin, + &["for-each-ref", "--format=%(refname)", &prefix_glob], + repo_path, + b"", + deadline, + )?; + + resolve_issue_match(id_or_prefix, &exact_ref, &stdout, |m| { + // The raw runner, not the bailing wrapper: the exact-existence check + // classifies a nonzero exit as "dangling", not as a failure. + let (status, _, _) = crate::git::visibility_pack::run_bounded_git_raw( + git_bin, + &["cat-file", "-e", m], + repo_path, + b"", + deadline, + )?; + Ok(status.success()) + }) +} + +/// The status flip a close applies to an issue's stored JSON. +fn closed_issue_json(raw: &str) -> Result { + let mut issue: serde_json::Value = + serde_json::from_str(raw).context("invalid issue JSON in git ref")?; + issue["status"] = serde_json::Value::String("closed".to_string()); + serde_json::to_string(&issue).context("failed to serialize updated issue") +} + /// Close an issue by updating its status to "closed" in the git ref. /// Returns the updated JSON, or None if the issue doesn't exist. pub fn close_issue(repo_path: &Path, issue_id: &str) -> Result> { @@ -357,15 +493,35 @@ pub fn close_issue(repo_path: &Path, issue_id: &str) -> Result> { None => return Ok(None), }; - let mut issue: serde_json::Value = - serde_json::from_str(&raw).context("invalid issue JSON in git ref")?; - issue["status"] = serde_json::Value::String("closed".to_string()); - - let updated = serde_json::to_string(&issue).context("failed to serialize updated issue")?; + let updated = closed_issue_json(&raw)?; create_issue(repo_path, &full_id, &updated)?; Ok(Some(updated)) } +/// Deadline-bounded variant of [`close_issue`], for the under-lock close path: +/// the same resolve, read and status flip, with every git child on the bounded +/// runner so a hung git cannot pin the lock-pool slot past the hold deadline. +pub fn close_issue_bounded( + git_bin: &str, + repo_path: &Path, + issue_id: &str, + deadline: std::time::Instant, +) -> Result> { + let full_id = match resolve_issue_id_bounded(git_bin, repo_path, issue_id, deadline)? { + Some(id) => id, + None => return Ok(None), + }; + + let raw = match get_issue_bounded(git_bin, repo_path, &full_id, deadline)? { + Some(raw) => raw, + None => return Ok(None), + }; + + let updated = closed_issue_json(&raw)?; + create_issue_bounded(git_bin, repo_path, &full_id, &updated, deadline)?; + Ok(Some(updated)) +} + /// Get a single issue by ID or 8-char prefix. pub fn get_issue(repo_path: &Path, issue_id: &str) -> Result> { let full_id = match resolve_issue_id(repo_path, issue_id)? { @@ -377,6 +533,23 @@ pub fn get_issue(repo_path: &Path, issue_id: &str) -> Result> { read_issue_blob(repo_path, &ref_name) } +/// Deadline-bounded variant of [`get_issue`], for reads that run under the +/// write guard and must not outlive its lock-hold deadline. +pub fn get_issue_bounded( + git_bin: &str, + repo_path: &Path, + issue_id: &str, + deadline: std::time::Instant, +) -> Result> { + let full_id = match resolve_issue_id_bounded(git_bin, repo_path, issue_id, deadline)? { + Some(id) => id, + None => return Ok(None), + }; + + let ref_name = format!("refs/gitlawb/issues/{full_id}"); + read_issue_blob_bounded(git_bin, repo_path, &ref_name, deadline) +} + #[cfg(test)] mod tests { use super::*; @@ -650,6 +823,144 @@ mod tests { assert!(list_issues(dir.path()).is_err()); } + fn bounded_deadline() -> std::time::Instant { + std::time::Instant::now() + std::time::Duration::from_secs(30) + } + + #[test] + fn test_bounded_resolve_exact_id_wins_over_longer_id() { + let dir = TempDir::new().unwrap(); + init_repo(&dir); + create_issue(dir.path(), "abc12345", r#"{"status":"open"}"#).unwrap(); + create_issue(dir.path(), "abc12345-0000", r#"{"status":"open"}"#).unwrap(); + let resolved = + resolve_issue_id_bounded("git", dir.path(), "abc12345", bounded_deadline()).unwrap(); + assert_eq!(resolved, Some("abc12345".to_string())); + } + + #[test] + fn test_bounded_resolve_prefix_matches_unique() { + let dir = TempDir::new().unwrap(); + init_repo(&dir); + let full_id = "abc12345-0000-0000-0000-000000000000"; + create_issue(dir.path(), full_id, r#"{"status":"open"}"#).unwrap(); + let resolved = + resolve_issue_id_bounded("git", dir.path(), "abc12345", bounded_deadline()).unwrap(); + assert_eq!(resolved, Some(full_id.to_string())); + } + + #[test] + fn test_bounded_resolve_ambiguous_prefix_errors() { + let dir = TempDir::new().unwrap(); + init_repo(&dir); + create_issue( + dir.path(), + "abc12345-aaaa-0000-0000-000000000000", + r#"{"status":"open"}"#, + ) + .unwrap(); + create_issue( + dir.path(), + "abc12345-bbbb-0000-0000-000000000000", + r#"{"status":"open"}"#, + ) + .unwrap(); + let err = resolve_issue_id_bounded("git", dir.path(), "abc12345", bounded_deadline()) + .unwrap_err(); + assert!(err.to_string().contains("ambiguous")); + } + + #[test] + fn test_bounded_resolve_rejects_revision_syntax() { + let dir = TempDir::new().unwrap(); + init_repo(&dir); + let full_id = "abc12345-0000-0000-0000-000000000000"; + create_issue(dir.path(), full_id, r#"{"status":"open"}"#).unwrap(); + // The bounded lookup applies the same id validation: none of these may + // reach git as a revision or a glob. + for crafted in [ + "abc12345-0000-0000-0000-000000000000^{blob}", + "abc12345-0000-0000-0000-000000000000~0", + "*", + "", + "..", + ] { + assert_eq!( + resolve_issue_id_bounded("git", dir.path(), crafted, bounded_deadline()).unwrap(), + None, + "{crafted:?}" + ); + assert_eq!( + get_issue_bounded("git", dir.path(), crafted, bounded_deadline()).unwrap(), + None, + "{crafted:?}" + ); + } + } + + #[test] + fn test_bounded_get_and_close_missing_issue_return_none() { + let dir = TempDir::new().unwrap(); + init_repo(&dir); + assert_eq!( + get_issue_bounded("git", dir.path(), "nosuch00", bounded_deadline()).unwrap(), + None + ); + assert_eq!( + close_issue_bounded("git", dir.path(), "nosuch00", bounded_deadline()).unwrap(), + None + ); + } + + #[test] + fn test_bounded_close_issue_via_prefix() { + let dir = TempDir::new().unwrap(); + init_repo(&dir); + let full_id = "def99999-0000-0000-0000-000000000000"; + create_issue( + dir.path(), + full_id, + r#"{"id":"def99999-0000-0000-0000-000000000000","status":"open"}"#, + ) + .unwrap(); + + let updated = close_issue_bounded("git", dir.path(), "def99999", bounded_deadline()) + .unwrap() + .unwrap(); + let v: serde_json::Value = serde_json::from_str(&updated).unwrap(); + assert_eq!(v["status"], "closed"); + } + + // A deadline already spent must not let a git child run out its own clock: + // the watchdog kills it immediately and the call surfaces GitServiceTimeout + // rather than hanging for the shim's full sleep. + #[test] + fn test_bounded_calls_abort_an_expired_deadline() { + use crate::test_support::git_shim; + + let dir = TempDir::new().unwrap(); + init_repo(&dir); + create_issue(dir.path(), "abc12345", r#"{"status":"open"}"#).unwrap(); + let shim = git_shim::create("gl-issues-expired-git", git_shim::Behavior::Hang); + let spent = std::time::Instant::now() + .checked_sub(std::time::Duration::from_secs(1)) + .unwrap_or_else(std::time::Instant::now); + let git_bin = shim.to_str().unwrap().to_string(); + + let started = std::time::Instant::now(); + let err = resolve_issue_id_bounded(&git_bin, dir.path(), "abc12345", spent) + .expect_err("a spent deadline must fail the lookup"); + assert!( + err.downcast_ref::() + .is_some(), + "the killed child must surface as GitServiceTimeout, got: {err:#}" + ); + assert!( + started.elapsed() < std::time::Duration::from_secs(15), + "an expired deadline must abort at once, not after the shim's 30s hang" + ); + } + #[test] fn test_list_issues_returns_all() { let dir = TempDir::new().unwrap(); diff --git a/crates/twigpine-node/src/test_git_shim.rs b/crates/twigpine-node/src/test_git_shim.rs index 5aeb5e63..e088bc2a 100644 --- a/crates/twigpine-node/src/test_git_shim.rs +++ b/crates/twigpine-node/src/test_git_shim.rs @@ -7,7 +7,7 @@ use std::sync::OnceLock; /// The fixture delays or hangs in its own process, so the production watchdog /// can terminate it without depending on a shell or descendant process support. #[allow(dead_code)] -pub(super) enum Behavior<'a> { +pub(crate) enum Behavior<'a> { Delay(u64), Hang, HangOid(&'a str), @@ -19,7 +19,7 @@ pub(super) enum Behavior<'a> { } #[allow(dead_code)] -pub(super) struct GitShim { +pub(crate) struct GitShim { _directory: tempfile::TempDir, executable: PathBuf, } @@ -33,7 +33,7 @@ impl Deref for GitShim { } #[allow(dead_code)] -pub(super) fn create(name: &str, behavior: Behavior<'_>) -> GitShim { +pub(crate) fn create(name: &str, behavior: Behavior<'_>) -> GitShim { static COMPILED: OnceLock = OnceLock::new(); let compiled = COMPILED.get_or_init(|| { let directory = tempfile::tempdir().expect("native Git fixture directory"); diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 0d8cb5db..26c62399 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -29,7 +29,7 @@ use crate::auth::AuthenticatedDid; use crate::state::AppState; #[path = "test_git_shim.rs"] -mod git_shim; +pub(crate) mod git_shim; /// Build an [`AppState`] over a real, migrated Postgres pool (from `#[sqlx::test]`). /// Runs the schema migrations first, because the per-test database starts empty.