Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 131 additions & 19 deletions crates/twigpine-node/src/api/issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,26 +145,34 @@ pub async fn list_issues(
State(state): State<AppState>,
Path((owner, repo)): Path<(String, String)>,
auth: Option<Extension<AuthenticatedDid>>,
crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr,
headers: axum::http::HeaderMap,
) -> Result<Json<serde_json::Value>> {
let caller = auth.as_ref().map(|e| e.0 .0.as_str());
let (record, _rules) =
crate::api::authorize_repo_read(&state, &owner, &repo, caller, "/").await?;

let disk_path = state
.repo_store
.acquire(&record.owner_did, &record.name)
.await
.map_err(|e| AppError::Git(e.to_string()))?;

let raw_issues =
git_issues::list_issues(&disk_path).map_err(|e| AppError::Git(e.to_string()))?;

let mut issues: Vec<serde_json::Value> = Vec::new();
for raw in raw_issues {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {
issues.push(v);
}
}
let issues: Vec<serde_json::Value> = super::repos::run_repo_git_read(
&state,
&headers,
peer,
&record,
"issues",
|git_bin, path, deadline| {
let raw_issues = git_issues::list_issues(git_bin, path, deadline).map_err(|err| {
if err.is::<crate::git::smart_http::GitServiceTimeout>() {
AppError::Timeout("git service timed out".into())
} else {
AppError::Git(err.to_string())
}
})?;
Ok(raw_issues
.into_iter()
.filter_map(|raw| serde_json::from_str(&raw).ok())
.collect())
},
)
.await?;

Ok(Json(serde_json::json!({ "issues": issues })))
}
Expand Down Expand Up @@ -1701,7 +1709,12 @@ mod lock_pool_shed_tests {
"a failed archive upload must refuse the write"
);

let issues = git_issues::list_issues(&disk.path().join("repo.git")).expect("list issues");
let issues = git_issues::list_issues(
"git",
&disk.path().join("repo.git"),
std::time::Instant::now() + std::time::Duration::from_secs(30),
)
.expect("list issues");
assert!(
issues.is_empty(),
"the local issue ref must be rolled back after a refused publish, got {issues:?}"
Expand Down Expand Up @@ -1752,7 +1765,12 @@ mod lock_pool_shed_tests {
res.is_err(),
"a stamped-and-expired hold deadline must refuse the create"
);
let issues = git_issues::list_issues(&live).expect("list issues");
let issues = git_issues::list_issues(
"git",
&live,
std::time::Instant::now() + std::time::Duration::from_secs(30),
)
.expect("list issues");
assert!(
issues.is_empty(),
"no issue ref may be left on disk after the refused create, got {issues:?}"
Expand Down Expand Up @@ -1813,7 +1831,12 @@ mod lock_pool_shed_tests {
StatusCode::SERVICE_UNAVAILABLE,
"the refusal is the retryable 503 the refresh path uses"
);
let issues = git_issues::list_issues(&live).expect("list issues");
let issues = git_issues::list_issues(
"git",
&live,
std::time::Instant::now() + std::time::Duration::from_secs(30),
)
.expect("list issues");
assert!(
issues.is_empty(),
"no issue ref may be written once the hold deadline expired, got {issues:?}"
Expand Down Expand Up @@ -2434,7 +2457,12 @@ exec git "$@"
"no stray refs/gitlawb/issues/{{prefix}} may be minted beside the \
canonical ref: the prefix must still resolve to the full id"
);
let issues = git_issues::list_issues(&live).expect("list issues");
let issues = git_issues::list_issues(
"git",
&live,
std::time::Instant::now() + std::time::Duration::from_secs(30),
)
.expect("list issues");
assert_eq!(
issues.len(),
1,
Expand Down Expand Up @@ -2687,6 +2715,8 @@ mod corrupt_store_tests {
State(state),
Path((owner.to_string(), "corrupt-list".to_string())),
None,
crate::rate_limit::PeerAddr(None),
axum::http::HeaderMap::new(),
)
.await
.expect_err("a corrupt store must error, not under-report");
Expand All @@ -2696,6 +2726,88 @@ mod corrupt_store_tests {
);
}

#[sqlx::test]
async fn list_issues_skips_malformed_json_and_preserves_ref_order(pool: PgPool) {
let owner = "did:key:zISSUELISTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
let dir = TempDir::new().unwrap();
let state = state_with_repos_dir(&pool, dir.path()).await;
state
.db
.create_repo(&seed_repo(owner, "list"))
.await
.unwrap();
let (path, id) = bare_repo_with_issue(dir.path(), owner, "list");
git_issues::create_issue(&path, "bbbb", "invalid json").unwrap();
git_issues::create_issue(&path, "cccc", r#"{"title":"second"}"#).unwrap();

let Json(body) = list_issues(
State(state),
Path((owner.to_string(), "list".to_string())),
None,
crate::rate_limit::PeerAddr(None),
axum::http::HeaderMap::new(),
)
.await
.unwrap();
assert_eq!(
body,
serde_json::json!({"issues": [
{"id": id, "title": "t", "status": "open"},
{"title": "second"},
]})
);
}

#[cfg(unix)]
#[sqlx::test]
async fn list_issues_timed_out_batch_is_504_not_empty(pool: PgPool) {
use std::os::unix::fs::PermissionsExt;

let owner = "did:key:zISSUELISTBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
let dir = TempDir::new().unwrap();
let mut state = state_with_repos_dir(&pool, dir.path()).await;
std::sync::Arc::make_mut(&mut state.config).git_service_timeout_secs = 1;
state
.db
.create_repo(&seed_repo(owner, "slow"))
.await
.unwrap();
let (path, _) = bare_repo_with_issue(dir.path(), owner, "slow");
let shim = dir.path().join("git-shim");
std::fs::write(
&shim,
"#!/bin/sh\nif [ \"$1\" = cat-file ]; then echo $$ > batch.pid; exec sleep 30; fi\nexec git \"$@\"\n",
)
.unwrap();
std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o700)).unwrap();
state.git_bin = shim.to_str().unwrap().to_string();

let err = list_issues(
State(state),
Path((owner.to_string(), "slow".to_string())),
None,
crate::rate_limit::PeerAddr(None),
axum::http::HeaderMap::new(),
)
.await
.expect_err("a timed out batch must not return an empty issue list");
assert_eq!(err.into_response().status(), StatusCode::GATEWAY_TIMEOUT);
let pid: libc::pid_t = std::fs::read_to_string(path.join("batch.pid"))
.unwrap()
.trim()
.parse()
.unwrap();
assert_eq!(
unsafe { libc::kill(pid, 0) },
-1,
"git child must be reaped"
);
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::ESRCH)
);
}

/// Must-not direction: a genuinely absent issue still gets the 404.
#[sqlx::test]
async fn get_issue_on_absent_ref_still_returns_404(pool: PgPool) {
Expand Down
2 changes: 1 addition & 1 deletion crates/twigpine-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ fn git_read_app_error(err: &anyhow::Error, repo: &str) -> AppError {
/// `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<T, F>(
pub(super) async fn run_repo_git_read<T, F>(
state: &AppState,
headers: &axum::http::HeaderMap,
peer: Option<std::net::SocketAddr>,
Expand Down
111 changes: 51 additions & 60 deletions crates/twigpine-node/src/git/issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use anyhow::{Context, Result};
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use std::process::Command;

/// Write a JSON blob for an issue and set the ref.
pub fn create_issue(repo_path: &Path, issue_id: &str, json: &str) -> Result<()> {
Expand Down Expand Up @@ -289,27 +289,33 @@ pub fn delete_issue_ref(
Ok(())
}

/// List all issue refs and return their JSON content.
pub fn list_issues(repo_path: &Path) -> Result<Vec<String>> {
// List all refs under refs/gitlawb/issues/
let list_output = Command::new("git")
.args([
/// List all issue refs and return their JSON content under one deadline.
pub fn list_issues(
git_bin: &str,
repo_path: &Path,
deadline: std::time::Instant,
) -> Result<Vec<String>> {
let check_deadline = || {
anyhow::ensure!(
std::time::Instant::now() < deadline,
crate::git::smart_http::GitServiceTimeout
);
Ok(())
};
check_deadline()?;
let list_output = crate::git::visibility_pack::run_bounded_git(
git_bin,
&[
"for-each-ref",
"--format=%(refname)",
"refs/gitlawb/issues/",
])
.current_dir(repo_path)
.output()
.context("failed to run git for-each-ref")?;

// for-each-ref exits 0 with empty output when no refs match, so a nonzero
// exit is a real enumeration failure, not "no issues yet".
if !list_output.status.success() {
let stderr = String::from_utf8_lossy(&list_output.stderr);
anyhow::bail!("git for-each-ref failed: {}", stderr.trim());
}
],
repo_path,
b"",
deadline,
)?;

let refs_str = String::from_utf8_lossy(&list_output.stdout);
let refs_str = String::from_utf8_lossy(&list_output);
let refs: Vec<_> = refs_str
.lines()
.map(str::trim)
Expand All @@ -319,7 +325,7 @@ pub fn list_issues(repo_path: &Path) -> Result<Vec<String>> {
return Ok(Vec::new());
}

let mut input = Vec::with_capacity(list_output.stdout.len());
let mut input = Vec::with_capacity(list_output.len());
for ref_name in &refs {
if !issue_ref_name_is_safe(ref_name) {
anyhow::bail!("refusing issue ref outside the issues namespace: {ref_name}");
Expand All @@ -328,51 +334,28 @@ pub fn list_issues(repo_path: &Path) -> Result<Vec<String>> {
input.push(b'\n');
}

// allow-unbounded-git: listing retains the existing unbounded read path.
let mut child = Command::new("git")
.args(["cat-file", "--batch"])
.current_dir(repo_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("failed to spawn git cat-file --batch")?;

let stdin = child.stdin.take();
let output = std::thread::scope(|scope| {
// Drain output while writing requests so neither side blocks on a full pipe.
let writer = std::thread::Builder::new().spawn_scoped(scope, move || {
stdin
.context("git cat-file --batch stdin unavailable")?
.write_all(&input)
.context("failed to write ref names to git cat-file stdin")
});
let output = child
.wait_with_output()
.context("git cat-file --batch failed")?;
writer
.context("failed to spawn git cat-file stdin writer")?
.join()
.map_err(|_| anyhow::anyhow!("git cat-file stdin writer panicked"))??;
Ok::<_, anyhow::Error>(output)
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("git cat-file --batch failed: {}", stderr.trim());
}

let mut stdout = output.stdout.as_slice();
check_deadline()?;
let output = crate::git::visibility_pack::run_bounded_git(
git_bin,
&["cat-file", "--batch"],
repo_path,
&input,
deadline,
)?;
let mut stdout = output.as_slice();
let mut issues = Vec::with_capacity(refs.len());
for ref_name in refs {
// Read the blob content. A ref that vanished between for-each-ref and
// here is skipped; a ref that resolves but fails to read propagates so
// a degraded object store errors the listing instead of under-reporting.
match read_batch_record(ref_name, &mut stdout)? {
Some(content) => issues.push(content),
None if ref_name_resolves(repo_path, ref_name)? => {
anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}");
None => {
check_deadline()?;
if ref_name_resolves_bounded(git_bin, repo_path, ref_name, deadline)? {
anyhow::bail!("issue ref resolves but its object is unreadable: {ref_name}");
}
}
None => {}
}
}
anyhow::ensure!(
Expand Down Expand Up @@ -840,7 +823,7 @@ mod tests {
let dir = TempDir::new().unwrap();
let not_a_repo = dir.path().join("not-a-repo");
std::fs::create_dir_all(&not_a_repo).unwrap();
assert!(list_issues(&not_a_repo).is_err());
assert!(list_issues("git", &not_a_repo, bounded_deadline()).is_err());
}

// #426: the same enumeration failure inside resolve_issue_id must reach
Expand All @@ -867,7 +850,7 @@ mod tests {

assert!(get_issue(dir.path(), full_id).is_err());
assert!(close_issue(dir.path(), full_id).is_err());
assert!(list_issues(dir.path()).is_err());
assert!(list_issues("git", dir.path(), bounded_deadline()).is_err());
}

fn bounded_deadline() -> std::time::Instant {
Expand Down Expand Up @@ -1027,8 +1010,16 @@ mod tests {
let second = "not valid JSON\n";
create_issue(dir.path(), "bbb00000-0000-0000-0000-000000000000", second).unwrap();
create_issue(dir.path(), "aaa00000-0000-0000-0000-000000000000", &first).unwrap();
assert_eq!(list_issues(dir.path()).unwrap().len(), 2);
assert_eq!(list_issues(dir.path()).unwrap(), [first.as_str(), second]);
assert_eq!(
list_issues("git", dir.path(), bounded_deadline())
.unwrap()
.len(),
2
);
assert_eq!(
list_issues("git", dir.path(), bounded_deadline()).unwrap(),
[first.as_str(), second]
);
}

#[test]
Expand Down
7 changes: 6 additions & 1 deletion crates/twigpine-node/src/test_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4383,7 +4383,12 @@ mod tests {
shim.parent().unwrap().join("committed").exists(),
"the ref write must have committed before the failure, or this proves nothing"
);
let issues = crate::git::issues::list_issues(&live).expect("list issues");
let issues = crate::git::issues::list_issues(
"git",
&live,
std::time::Instant::now() + Duration::from_secs(30),
)
.expect("list issues");
assert!(
issues.is_empty(),
"no issue ref may survive a refused create, got {issues:?}"
Expand Down