use super::*;
use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
use arks_repo::Repository;
use arks_store::{ObjectFormat, ObjectStore};
use std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;
use tempfile::TempDir;
fn seed_bare(root: &std::path::Path) -> (std::path::PathBuf, arks_oid::Oid) {
let git = root.to_path_buf();
std::fs::create_dir_all(git.join("objects")).unwrap();
std::fs::create_dir_all(git.join("refs/heads")).unwrap();
std::fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
let mut repo = Repository::open(&git).unwrap();
let blob = RawObject::new(ObjectKind::Blob, b"hello server\n".to_vec());
let blob_oid = repo.store_mut().put(ObjectFormat::Sha1, &blob).unwrap();
let tree = Tree::new(vec![TreeEntry {
mode: TreeMode::File,
name: "hello.txt".into(),
oid: blob_oid,
}])
.unwrap();
let tree_obj = RawObject::new(ObjectKind::Tree, tree.encode().unwrap());
let tree_oid = repo.store_mut().put(ObjectFormat::Sha1, &tree_obj).unwrap();
let sig = Signature {
name: "arks".into(),
email: "arks@example.com".into(),
timestamp: 1_700_000_000,
timezone: "+0000".into(),
};
let commit = Commit {
tree: tree_oid,
parents: Vec::new(),
author: sig.clone(),
committer: sig,
gpgsig: None,
message: "initial\n".into(),
};
let commit_obj = RawObject::new(ObjectKind::Commit, commit.encode().unwrap());
let commit_oid = repo
.store_mut()
.put(ObjectFormat::Sha1, &commit_obj)
.unwrap();
repo.refs_mut()
.update("refs/heads/main", &commit_oid, None)
.unwrap();
(git, commit_oid)
}
#[test]
fn upload_advertisement_includes_main() {
let dir = TempDir::new().unwrap();
let (git, oid) = seed_bare(dir.path());
let repo = Repository::open(&git).unwrap();
let body = upload_advertisement(&repo).unwrap();
let text = String::from_utf8_lossy(&body);
assert!(text.contains("git-upload-pack"));
assert!(text.contains(&oid.to_hex()));
assert!(text.contains("refs/heads/main"));
assert!(text.contains("side-band-64k"));
assert!(!text.contains("agent=git/"));
}
#[test]
fn receive_advertises_delete_refs_and_report_status_v2() {
let dir = TempDir::new().unwrap();
let (git, _) = seed_bare(dir.path());
let repo = Repository::open(&git).unwrap();
let body = receive_advertisement(&repo).unwrap();
let text = String::from_utf8_lossy(&body);
assert!(text.contains("report-status"));
assert!(text.contains("report-status-v2"));
assert!(text.contains("delete-refs"));
assert!(text.contains("push-options"));
assert!(!text.contains("proc-receive"));
}
#[test]
fn receive_advertises_proc_receive_when_hook_present() {
let dir = TempDir::new().unwrap();
let (git, _) = seed_bare(dir.path());
let hooks = git.join("hooks");
std::fs::create_dir_all(&hooks).unwrap();
let hook = hooks.join("proc-receive");
std::fs::write(&hook, b"#!/bin/sh\nexit 0\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&hook).unwrap().permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&hook, perms).unwrap();
}
let repo = Repository::open(&git).unwrap();
let body = receive_advertisement(&repo).unwrap();
let text = String::from_utf8_lossy(&body);
assert!(
text.contains("proc-receive"),
"FS2 must advertise proc-receive when hook is runnable: {text}"
);
}
#[test]
fn smart_http_info_refs_upload() {
let dir = TempDir::new().unwrap();
let (git, _) = seed_bare(dir.path());
let mut repo = Repository::open(&git).unwrap();
let req = HttpRequest {
method: "GET".into(),
path: "/repo.git/info/refs".into(),
query: "service=git-upload-pack".into(),
body: Vec::new(),
git_protocol: None,
authorization: None,
destination: None,
lock_token: None,
host: None,
cookie: None,
origin: None,
forwarded_proto: None,
};
let resp = handle_smart_http(&mut repo, &req).unwrap();
assert_eq!(resp.status, 200);
assert!(resp.content_type.contains("git-upload-pack-advertisement"));
}
#[test]
fn smart_http_basic_auth_challenge_and_accept() {
let dir = TempDir::new().unwrap();
let (git, _) = seed_bare(dir.path());
let mut repo = Repository::open(&git).unwrap();
let cfg = BasicAuthConfig::single("alice", "s3cret");
let denied = HttpRequest {
method: "GET".into(),
path: "/info/refs".into(),
query: "service=git-upload-pack".into(),
body: Vec::new(),
git_protocol: None,
authorization: None,
destination: None,
lock_token: None,
host: None,
cookie: None,
origin: None,
forwarded_proto: None,
};
let resp = handle_smart_http_auth(&mut repo, &denied, Some(&cfg)).unwrap();
assert_eq!(resp.status, 401);
assert_eq!(
resp.www_authenticate.as_deref(),
Some("Basic realm=\"arks\"")
);
let ok = HttpRequest {
method: "GET".into(),
path: "/info/refs".into(),
query: "service=git-upload-pack".into(),
body: Vec::new(),
git_protocol: None,
authorization: Some(basic_authorization_header("alice", "s3cret")),
destination: None,
lock_token: None,
host: None,
cookie: None,
origin: None,
forwarded_proto: None,
};
let resp = handle_smart_http_auth(&mut repo, &ok, Some(&cfg)).unwrap();
assert_eq!(resp.status, 200);
assert!(resp.content_type.contains("git-upload-pack-advertisement"));
}
#[test]
fn loopback_serves_info_refs() {
let dir = TempDir::new().unwrap();
let (git, _) = seed_bare(dir.path());
let (addr, stop, handle) = spawn_loopback(git).unwrap();
thread::sleep(Duration::from_millis(50));
let url = format!("http://{addr}/info/refs?service=git-upload-pack");
let body = ureq_get(&url);
stop.store(true, Ordering::SeqCst);
let _ = handle.join();
assert!(body.contains("refs/heads/main") || body.contains("# service=git-upload-pack"));
}
fn ureq_get(url: &str) -> String {
use std::io::{Read, Write};
use std::net::TcpStream;
let url = url.strip_prefix("http://").unwrap();
let (hostport, path) = url.split_once('/').unwrap();
let mut stream = TcpStream::connect(hostport).unwrap();
let req = format!("GET /{path} HTTP/1.1\r\nHost: {hostport}\r\nConnection: close\r\n\r\n");
stream.write_all(req.as_bytes()).unwrap();
let mut buf = Vec::new();
stream.read_to_end(&mut buf).unwrap();
String::from_utf8_lossy(&buf).into_owned()
}
fn zero_oid() -> String {
"0".repeat(40)
}
fn receive_create_branch_body(new_oid: &arks_oid::Oid, refname: &str) -> Vec<u8> {
use arks_protocol::{Packet, encode_packet};
let line = format!("{} {} {}\n", zero_oid(), new_oid.to_hex(), refname);
let mut body = encode_packet(&Packet::Data(line.into_bytes())).unwrap();
body.extend(encode_packet(&Packet::Flush).unwrap());
body
}
fn install_hook(git: &std::path::Path, name: &str, script: &str) {
let hooks = git.join("hooks");
std::fs::create_dir_all(&hooks).unwrap();
let path = hooks.join(name);
std::fs::write(&path, script).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&path).unwrap().permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&path, perms).unwrap();
}
}
#[test]
fn receive_pre_receive_hook_rejects_entire_push() {
let dir = TempDir::new().unwrap();
let (git, oid) = seed_bare(dir.path());
install_hook(&git, "pre-receive", "#!/bin/sh\nexit 1\n");
let mut repo = Repository::open(&git).unwrap();
let body = receive_create_branch_body(&oid, "refs/heads/topic");
let out = receive_pack(&mut repo, &body).unwrap();
let text = String::from_utf8_lossy(&out);
assert!(
text.contains("pre-receive hook declined"),
"expected decline in {text}"
);
assert!(repo.refs().resolve("refs/heads/topic").is_err());
}
#[test]
fn receive_update_hook_rejects_one_ref() {
let dir = TempDir::new().unwrap();
let (git, oid) = seed_bare(dir.path());
install_hook(&git, "update", "#!/bin/sh\nexit 1\n");
let mut repo = Repository::open(&git).unwrap();
let body = receive_create_branch_body(&oid, "refs/heads/topic");
let out = receive_pack(&mut repo, &body).unwrap();
let text = String::from_utf8_lossy(&out);
assert!(text.contains("hook declined"), "expected decline in {text}");
assert!(repo.refs().resolve("refs/heads/topic").is_err());
}
#[test]
fn receive_post_receive_runs_after_success() {
let dir = TempDir::new().unwrap();
let (git, oid) = seed_bare(dir.path());
let marker = git.join("post-receive-ran");
install_hook(
&git,
"post-receive",
"#!/bin/sh\ncat > \"$GIT_DIR/post-receive-ran\"\n",
);
let mut repo = Repository::open(&git).unwrap();
let body = receive_create_branch_body(&oid, "refs/heads/topic");
let out = receive_pack(&mut repo, &body).unwrap();
let text = String::from_utf8_lossy(&out);
assert!(
text.contains("ok refs/heads/topic"),
"expected ok in {text}"
);
assert_eq!(repo.refs().resolve("refs/heads/topic").unwrap(), oid);
assert!(
marker.is_file(),
"post-receive should have written {}",
marker.display()
);
}
#[test]
fn v2_advertises_and_serves_bundle_uri() {
let dir = TempDir::new().unwrap();
let (git, _) = seed_bare(dir.path());
std::fs::write(
git.join("arks-bundle-uris"),
"https://example.test/seed.bundle\n",
)
.unwrap();
let lines = v2_capability_lines();
assert!(
lines.iter().any(|l| l == "bundle-uri"),
"G3 must advertise bundle-uri: {lines:?}"
);
let repo = Repository::open(&git).unwrap();
let mut body = arks_protocol::encode_text_line("command=bundle-uri").unwrap();
body.extend(arks_protocol::encode_packet(&arks_protocol::Packet::Flush).unwrap());
let out = handle_v2_request(&repo, &body, true).unwrap();
let text = String::from_utf8_lossy(&out);
assert!(text.contains("bundle.version=1"), "{text}");
assert!(
text.contains("bundle.seed1.uri=https://example.test/seed.bundle"),
"{text}"
);
}
struct RefuseNamed(&'static str);
impl PushPolicy for RefuseNamed {
fn check(&self, _: &Repository, pusher: &Pusher, updates: &[RefUpdate]) -> Vec<Option<String>> {
assert_eq!(pusher.transport, "local");
updates
.iter()
.map(|u| (u.name == self.0).then(|| format!("rule says no\nfor {}", u.name)))
.collect()
}
}
#[test]
fn receive_push_policy_refuses_one_ref_and_keeps_the_other() {
use arks_protocol::{Packet, encode_packet};
let dir = TempDir::new().unwrap();
let (git, oid) = seed_bare(dir.path());
let mut repo = Repository::open(&git).unwrap();
let mut body = Vec::new();
for name in ["refs/heads/a", "refs/heads/b"] {
let line = format!("{} {} {name}\n", zero_oid(), oid.to_hex());
body.extend(encode_packet(&Packet::Data(line.into_bytes())).unwrap());
}
body.extend(encode_packet(&Packet::Flush).unwrap());
let policy = RefuseNamed("refs/heads/b");
let out = receive_pack_with(&mut repo, &body, &Pusher::local(), Some(&policy)).unwrap();
let text = String::from_utf8_lossy(&out);
assert!(text.contains("ok refs/heads/a"), "{text}");
assert!(
text.contains("ng refs/heads/b rule says no for refs/heads/b\n"),
"{text}"
);
assert_eq!(repo.refs().resolve("refs/heads/a").unwrap(), oid);
assert!(repo.refs().resolve("refs/heads/b").is_err());
}
struct WrongArity;
impl PushPolicy for WrongArity {
fn check(&self, _: &Repository, _: &Pusher, _: &[RefUpdate]) -> Vec<Option<String>> {
Vec::new()
}
}
#[test]
fn receive_push_policy_wrong_arity_fails_closed() {
let dir = TempDir::new().unwrap();
let (git, oid) = seed_bare(dir.path());
let mut repo = Repository::open(&git).unwrap();
let body = receive_create_branch_body(&oid, "refs/heads/topic");
let out = receive_pack_with(&mut repo, &body, &Pusher::local(), Some(&WrongArity)).unwrap();
let text = String::from_utf8_lossy(&out);
assert!(
text.contains("ng refs/heads/topic push policy error"),
"{text}"
);
assert!(repo.refs().resolve("refs/heads/topic").is_err());
}
#[test]
fn basic_auth_reports_the_authorized_user() {
let cfg = BasicAuthConfig::single("alice", "s3cret");
let ok = basic_authorization_header("alice", "s3cret");
assert_eq!(cfg.authorized_user(Some(&ok)).as_deref(), Some("alice"));
let bad = basic_authorization_header("alice", "nope");
assert_eq!(cfg.authorized_user(Some(&bad)), None);
}
fn put_tag(repo: &mut Repository, name: &str, target: arks_oid::Oid) -> arks_oid::Oid {
let body = format!(
"object {}\ntype commit\ntag {name}\ntagger arks <arks@example.com> 1700000000 +0000\n\n{name}\n",
target.to_hex()
);
let oid = repo
.store_mut()
.put(
ObjectFormat::Sha1,
&RawObject::new(ObjectKind::Tag, body.into_bytes()),
)
.unwrap();
repo.refs_mut()
.update(&format!("refs/tags/{name}"), &oid, None)
.unwrap();
oid
}
fn pack_object_count(reply: &[u8]) -> u32 {
let at = reply
.windows(4)
.position(|w| w == b"PACK")
.expect("PACK header in reply");
u32::from_be_bytes(reply[at + 8..at + 12].try_into().unwrap())
}
fn want_request(oid: &arks_oid::Oid, caps: &str) -> Vec<u8> {
use arks_protocol::{Packet, encode_packet};
let mut body = encode_packet(&Packet::Data(
format!("want {} {caps}\n", oid.to_hex()).into_bytes(),
))
.unwrap();
body.extend(encode_packet(&Packet::Flush).unwrap());
body.extend(encode_packet(&Packet::Data(b"done\n".to_vec())).unwrap());
body
}
#[test]
fn upload_pack_include_tag_adds_tags_pointing_into_the_pack() {
let dir = TempDir::new().unwrap();
let (git, commit) = seed_bare(dir.path());
let mut repo = Repository::open(&git).unwrap();
put_tag(&mut repo, "v1", commit);
let sig = Signature {
name: "arks".into(),
email: "arks@example.com".into(),
timestamp: 1_700_000_001,
timezone: "+0000".into(),
};
let tree = repo.get_object(&commit).unwrap();
let tree_oid = Commit::decode(&tree.payload).unwrap().tree;
let other = Commit {
tree: tree_oid,
parents: Vec::new(),
author: sig.clone(),
committer: sig,
gpgsig: None,
message: "unrelated\n".into(),
};
let other_oid = repo
.store_mut()
.put(
ObjectFormat::Sha1,
&RawObject::new(ObjectKind::Commit, other.encode().unwrap()),
)
.unwrap();
put_tag(&mut repo, "elsewhere", other_oid);
let advert = String::from_utf8_lossy(&upload_advertisement(&repo).unwrap()).to_string();
assert!(advert.contains("include-tag"), "{advert}");
let without = upload_pack_result(&repo, &want_request(&commit, "ofs-delta")).unwrap();
assert_eq!(pack_object_count(&without), 3, "blob, tree, commit");
let with = upload_pack_result(&repo, &want_request(&commit, "ofs-delta include-tag")).unwrap();
assert_eq!(pack_object_count(&with), 4, "plus the v1 tag object only");
}
#[test]
fn transient_accept_error_classifies_emfile_and_aborted_without_exiting() {
use std::io::{Error, ErrorKind};
assert!(crate::serve::is_transient_accept_error(&Error::new(
ErrorKind::WouldBlock,
"would block"
)));
assert!(crate::serve::is_transient_accept_error(&Error::new(
ErrorKind::Interrupted,
"eintr"
)));
assert!(crate::serve::is_transient_accept_error(&Error::new(
ErrorKind::ConnectionAborted,
"aborted"
)));
assert!(crate::serve::is_transient_accept_error(&Error::new(
ErrorKind::ConnectionReset,
"reset"
)));
#[cfg(unix)]
{
assert!(crate::serve::is_transient_accept_error(
&Error::from_raw_os_error(24)
));
assert!(crate::serve::is_transient_accept_error(
&Error::from_raw_os_error(23)
));
assert!(!crate::serve::is_transient_accept_error(
&Error::from_raw_os_error(9)
));
}
#[cfg(windows)]
{
assert!(crate::serve::is_transient_accept_error(
&Error::from_raw_os_error(10024)
));
assert!(!crate::serve::is_transient_accept_error(
&Error::from_raw_os_error(10009)
));
}
}
#[test]
fn slowloris_header_dribble_evicted_with_408_request_timeout() {
use std::io::{Read, Write};
use std::net::TcpStream;
let dir = TempDir::new().unwrap();
let (git, _) = seed_bare(dir.path());
let opts = ServeHttpOptions {
header_timeout: Some(Duration::from_millis(600)),
..ServeHttpOptions::default()
};
let (addr, stop, handle) = spawn_loopback_with_opts(git, opts).unwrap();
let mut sock = TcpStream::connect(addr).unwrap();
sock.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
sock.write_all(b"GET /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nX-Slow: ")
.unwrap();
for _ in 0..3 {
thread::sleep(Duration::from_millis(120));
if sock.write_all(b"a").is_err() {
break;
}
}
let mut reply = Vec::new();
let _ = sock.read_to_end(&mut reply);
let reply_text = String::from_utf8_lossy(&reply);
assert!(
reply_text.starts_with("HTTP/1.1 408 Request Timeout"),
"expected HTTP 408 Request Timeout on Slowloris dribble, got: {reply_text:?}"
);
assert!(
reply_text.contains("Connection: close"),
"408 response must close connection: {reply_text:?}"
);
stop.store(true, Ordering::SeqCst);
handle.join().unwrap().unwrap();
}
#[test]
fn atomic_concurrency_slot_reservation_never_exceeds_limit() {
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, Barrier};
let limit = 6usize;
let base = crate::serve::active_http_connections();
let cap = base + limit;
let barrier = Arc::new(Barrier::new(24));
let granted = Arc::new(AtomicUsize::new(0));
let peak = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for _ in 0..24 {
let b = barrier.clone();
let g = granted.clone();
let p = peak.clone();
handles.push(thread::spawn(move || {
b.wait();
if let Some(_guard) = crate::serve::try_reserve_http_slot_with_limit(cap) {
let cur = crate::serve::active_http_connections();
p.fetch_max(cur, Ordering::SeqCst);
g.fetch_add(1, Ordering::SeqCst);
thread::sleep(Duration::from_millis(80));
}
}));
}
for h in handles {
h.join().unwrap();
}
assert!(
granted.load(Ordering::SeqCst) <= limit,
"granted {} > limit {limit}",
granted.load(Ordering::SeqCst)
);
assert!(
peak.load(Ordering::SeqCst) <= cap,
"peak {} > cap {cap}",
peak.load(Ordering::SeqCst)
);
}
#[test]
fn forgestore_startup_gc_sweeps_dead_pid_temps_only() {
let dir = TempDir::new().unwrap();
let forge_dir = dir.path().join("arks-forge");
std::fs::create_dir_all(&forge_dir).unwrap();
let canonical = forge_dir.join("store.json");
let dead1 = forge_dir.join(".store.json.999991.12.tmp");
let dead2 = forge_dir.join(".store.json.999992.34.tmp");
let live = forge_dir.join(".store.json.424242.7.tmp");
let unrelated = forge_dir.join("other.tmp");
std::fs::write(&canonical, b"{\"issues\":[]}").unwrap();
std::fs::write(&dead1, b"partial-1").unwrap();
std::fs::write(&dead2, b"partial-2").unwrap();
std::fs::write(&live, b"in-flight").unwrap();
std::fs::write(&unrelated, b"keep-me").unwrap();
let removed =
crate::web_ui::store::sweep_stale_temps_in_dir_with(&forge_dir, |pid, _| pid == 424_242);
assert_eq!(
removed, 2,
"must remove exactly the two dead-PID temp files"
);
assert!(canonical.exists(), "canonical store.json must stay intact");
assert!(!dead1.exists(), "dead1 temp file must be swept");
assert!(!dead2.exists(), "dead2 temp file must be swept");
assert!(live.exists(), "live PID temp file must NOT be removed");
assert!(unrelated.exists(), "unrelated file must NOT be removed");
}
#[test]
fn forgestore_load_shared_reuses_arc_and_invalidates_on_commit() {
use std::sync::Arc;
let dir = TempDir::new().unwrap();
let mut tx = crate::web_ui::store::ForgeStore::lock_mut(dir.path());
tx.create_issue("First".into(), "body".into(), "alice".into(), vec![], None);
tx.commit().unwrap();
let s1 = crate::web_ui::store::ForgeStore::load_shared(dir.path());
let s2 = crate::web_ui::store::ForgeStore::load_shared(dir.path());
assert!(
Arc::ptr_eq(&s1, &s2),
"cached load_shared must share the same Arc without deep-cloning ForgeStore"
);
assert_eq!(s1.issues.len(), 1);
let mut tx2 = crate::web_ui::store::ForgeStore::lock_mut(dir.path());
tx2.create_issue("Second".into(), "body".into(), "bob".into(), vec![], None);
tx2.commit().unwrap();
let s3 = crate::web_ui::store::ForgeStore::load_shared(dir.path());
assert!(
!Arc::ptr_eq(&s1, &s3),
"committing a new transaction must refresh the cached Arc snapshot"
);
assert_eq!(s3.issues.len(), 2);
}
#[test]
fn unified_api_get_and_non_api_routes_never_block_on_forgestore_write_lock() {
use std::sync::mpsc;
let dir = TempDir::new().unwrap();
let (repo_dir, _head) = seed_bare(dir.path());
{
let mut tx = crate::web_ui::store::ForgeStore::lock_mut(&repo_dir);
tx.create_issue("Warm".into(), "body".into(), "alice".into(), vec![], None);
tx.commit().unwrap();
}
let _warm = crate::web_ui::store::ForgeStore::load_shared(&repo_dir);
let _held_write_lock = crate::web_ui::store::ForgeStore::lock_mut(&repo_dir);
let repo_dir_bg = repo_dir.clone();
let (tx_done, rx_done) = mpsc::channel();
let handle = std::thread::spawn(move || {
let r_web = crate::web_ui::handle_web_ui(
&repo_dir_bg,
&crate::http::HttpRequest::new("GET", "/issues", "", Vec::new()),
)
.expect("GET /issues must return a response");
assert_eq!(r_web.status, 200);
let r_api = crate::web_ui::handle_web_ui(
&repo_dir_bg,
&crate::http::HttpRequest::new("GET", "/api/v1/issues", "", Vec::new()),
)
.expect("GET /api/v1/issues must return a response");
assert_eq!(r_api.status, 200);
let parsed: serde_json::Value = serde_json::from_slice(&r_api.body).unwrap();
assert_eq!(parsed.as_array().unwrap().len(), 1);
let _ = tx_done.send(());
});
rx_done
.recv_timeout(Duration::from_secs(2))
.expect("GET /issues and GET /api/v1/issues deadlocked on ForgeStore write lock!");
drop(_held_write_lock);
handle.join().unwrap();
}