use crate::common::{ BOB_CMD, Http, PW, TAHINLI_CMD, boot_forge, commit_file, create_repo, create_token, csrf_for, describe, git, git_env, head_sha, login, ok, path_str, set_identity, tool_on_path, }; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use reqwest::header::WWW_AUTHENTICATE; fn rejected(out: &Output, what: &str) -> String { assert!( !out.status.success(), "{what} unexpectedly succeeded:\n{}", describe(out) ); describe(out) } fn ssh_opts(key: &Path, ssh_port: u16) -> Vec { [ "-i", path_str(key), "-o", "IdentitiesOnly=yes", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "BatchMode=yes", "-o", "LogLevel=ERROR", "-p", ] .iter() .map(|s| (*s).to_owned()) .chain(std::iter::once(ssh_port.to_string())) .collect() } fn ssh_command(key: &Path, ssh_port: u16) -> String { format!("ssh {}", ssh_opts(key, ssh_port).join(" ")) } fn gen_key(path: &Path) { let out = Command::new("ssh-keygen") .args(["-t", "ed25519", "-N", "", "-q", "-f"]) .arg(path) .output() .expect("run ssh-keygen"); ok(&out, "ssh-keygen"); } fn find_file(dir: &Path, name: &str) -> bool { std::fs::read_dir(dir).is_ok_and(|entries| { entries.flatten().any(|entry| { entry.file_name() == name || (entry.path().is_dir() && find_file(&entry.path(), name)) }) }) } fn read(path: PathBuf) -> String { fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())) } async fn add_key(http: &Http, session: &str, public_key: &str) { let csrf = csrf_for(http, "/settings/keys", session).await; let res = http .post_form( "/settings/keys", &[ ("csrf", &csrf), ("title", "e2e"), ("public_key", public_key), ], Some(session), ) .await; assert_eq!(res.status, 303, "add SSH key: {}", res.body); } #[tokio::test] async fn git_end_to_end() { for tool in ["git", "ssh", "ssh-keygen"] { if !tool_on_path(tool) { eprintln!( "SKIP git_e2e: `{tool}` was not found on PATH, so the end-to-end test is skipped" ); return; } } let root = crate::common::temp_dir("fe2e"); let dir = root.path().to_path_buf(); let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; let http = Http::new(ports.http); let (http_port, ssh_port) = (ports.http, ports.ssh); let tahinli = login(&http, "tahinli", PW).await; let tahinli_token = create_token(&http, &tahinli, "e2e-token").await; let key = dir.join("id"); gen_key(&key); let public_key = fs::read_to_string(dir.join("id.pub")).expect("read id.pub"); add_key(&http, &tahinli, public_key.trim()).await; create_repo(&http, &tahinli, "pub", "public").await; create_repo(&http, &tahinli, "priv", "private").await; let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git"); let pub_work = dir.join("pub-work"); ok( &git(&dir, &["clone", &pub_url, path_str(&pub_work)]), "https clone of empty public repo", ); commit_file(&pub_work, "hello.txt", "hello over https\n", "https commit"); ok( &git(&pub_work, &["push", "origin", "HEAD:main"]), "https push", ); let pushed_main = head_sha(&pub_work); let pub_verify = dir.join("pub-verify"); ok( &git(&dir, &["clone", &pub_url, path_str(&pub_verify)]), "https fresh clone", ); assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n"); let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git"); let pub_anon = dir.join("pub-anon"); ok( &git(&dir, &["clone", &anon_url, path_str(&pub_anon)]), "anonymous clone of public repo", ); assert_eq!(read(pub_anon.join("hello.txt")), "hello over https\n"); let pub_shallow = dir.join("pub-shallow"); ok( &git( &dir, &["clone", "--depth", "1", &anon_url, path_str(&pub_shallow)], ), "anonymous shallow clone", ); let ssh_cmd = ssh_command(&key, ssh_port); let ssh_env = [("GIT_SSH_COMMAND", ssh_cmd.as_str())]; let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git"); let priv_work = dir.join("priv-work"); ok( &git_env( &dir, &["clone", &priv_ssh_url, path_str(&priv_work)], &ssh_env, ), "ssh clone of empty private repo", ); commit_file(&priv_work, "secret.txt", "over ssh\n", "ssh commit"); ok( &git_env(&priv_work, &["push", "origin", "HEAD:main"], &ssh_env), "ssh push", ); let priv_verify = dir.join("priv-verify"); ok( &git_env( &dir, &["clone", &priv_ssh_url, path_str(&priv_verify)], &ssh_env, ), "ssh fresh clone", ); assert_eq!(read(priv_verify.join("secret.txt")), "over ssh\n"); let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git"); rejected( &git(&dir, &["clone", &priv_https_anon, "anon-priv"]), "anonymous clone of private repo", ); let refs_path = "/tahinli/priv.git/info/refs?service=git-upload-pack"; let anon_refs = http.get(refs_path, None).await; assert_eq!(anon_refs.status, 401, "anonymous info/refs on private repo"); assert!( anon_refs.header(WWW_AUTHENTICATE).is_some(), "401 must carry WWW-Authenticate" ); let bob = login(&http, "bob", PW).await; let bob_page = http.get_cookie("/tahinli/priv", &bob).await; assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv"); let bob_token = create_token(&http, &bob, "bob-token").await; let bob_refs = http.get_basic(refs_path, "bob", &bob_token).await; assert_eq!(bob_refs.status, 404, "bob's info/refs on tahinli/priv"); let wrong = http .get_basic(refs_path, "tahinli", "forge_notarealtoken") .await; assert_eq!(wrong.status, 401, "wrong token on info/refs"); let wrong_url = format!("http://tahinli:forge_notarealtoken@127.0.0.1:{http_port}/tahinli/priv.git"); rejected( &git(&dir, &["clone", &wrong_url, "wrong-token-clone"]), "clone with wrong token", ); let delete = git(&pub_verify, &["push", "origin", "--delete", "main"]); let text = rejected(&delete, "deleting main"); assert!( text.contains("deleting protected branch 'main' is not allowed"), "delete message: {text}" ); set_identity(&pub_verify); ok( &git( &pub_verify, &[ "-c", "commit.gpgsign=false", "commit", "--amend", "-q", "-m", "rewritten", ], ), "amend commit", ); let force = git(&pub_verify, &["push", "-f", "origin", "HEAD:main"]); let text = rejected(&force, "force-push to main"); assert!( text.contains("force-push to protected branch 'main' is not allowed"), "force-push message: {text}" ); let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"]); ok(&ls, "ls-remote main"); let remote_main = String::from_utf8_lossy(&ls.stdout); assert!( remote_main.starts_with(&pushed_main), "main moved after rejected pushes: {remote_main}" ); ok( &git(&pub_verify, &["push", "origin", "HEAD:refs/heads/scratch"]), "push scratch", ); let overwritten = head_sha(&pub_verify); let page = format!("/tahinli/pub/commit/{overwritten}"); assert_eq!( http.get(&page, None).await.status, 200, "commit on a branch" ); ok( &git( &pub_verify, &[ "-c", "commit.gpgsign=false", "commit", "--amend", "-q", "-m", "rewritten again", ], ), "amend again", ); ok( &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"]), "force-push scratch", ); assert_eq!( http.get(&page, None).await.status, 404, "overwritten commit" ); assert!( find_file(&dir, "forge-prune-due"), "the force push marks the repo for pruning" ); let rogue = dir.join("rogue"); gen_key(&rogue); let rogue_cmd = ssh_command(&rogue, ssh_port); let rogue_env = [("GIT_SSH_COMMAND", rogue_cmd.as_str())]; let text = rejected( &git_env(&dir, &["clone", &priv_ssh_url, "rogue-clone"], &rogue_env), "clone with unregistered key", ); assert!( text.contains("Permission denied"), "rogue key message: {text}" ); let injected = Command::new("ssh") .args(ssh_opts(&key, ssh_port)) .arg("git@127.0.0.1") .arg("git-upload-pack '../../etc'") .output() .expect("run ssh"); rejected(&injected, "ssh exec with injected path"); let no_csrf = http .post_form( "/new", &[ ("name", "nocsrf"), ("visibility", "public"), ("default_branch", "main"), ], Some(&tahinli), ) .await; assert_eq!(no_csrf.status, 403, "POST /new without csrf"); let dumb = http.get("/tahinli/pub.git/info/refs", None).await; assert_eq!(dumb.status, 403, "info/refs without service"); assert!( dumb.body.contains("dumb protocol"), "dumb body: {}", dumb.body ); } #[tokio::test] async fn suspended_user_token_is_refused_over_http_git() { if !tool_on_path("git") { eprintln!("SKIP git_e2e: `git` was not found on PATH"); return; } let root = crate::common::temp_dir("fe2s"); let dir = root.path().to_path_buf(); let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; let http = Http::new(ports.http); let bob = login(&http, "bob", PW).await; let bob_token = create_token(&http, &bob, "suspend-token").await; let csrf = csrf_for(&http, "/new", &bob).await; let created = http .post_form( "/new", &[ ("csrf", &csrf), ("name", "bobrepo"), ("description", ""), ("visibility", "private"), ("default_branch", "main"), ], Some(&bob), ) .await; assert_eq!(created.status, 303, "create repo: {}", created.body); let url = format!( "http://bob:{bob_token}@127.0.0.1:{}/bob/bobrepo.git", ports.http ); let work = dir.join("work"); ok( &git(&dir, &["clone", &url, path_str(&work)]), "clone before suspension", ); commit_file(&work, "a.txt", "one\n", "first"); ok( &git(&work, &["push", "origin", "HEAD:main"]), "push before suspension", ); let tahinli = login(&http, "tahinli", PW).await; let list = http.get_cookie("/admin/users", &tahinli).await; assert_eq!(list.status, 200, "GET /admin/users"); let doc = scraper::Html::parse_document(&list.body); let link = scraper::Selector::parse("a[href^=\"/admin/users/\"]").expect("selector"); let name = scraper::Selector::parse(".name").expect("selector"); let bob_href = doc .select(&link) .find(|a| { a.select(&name) .next() .is_some_and(|n| n.text().collect::().trim() == "bob") }) .and_then(|a| a.value().attr("href")) .expect("bob's admin link") .to_owned(); let detail = http.get_cookie(&bob_href, &tahinli).await; assert_eq!(detail.status, 200, "GET {bob_href}"); let csrf = csrf_for(&http, &bob_href, &tahinli).await; let res = http .post_form( &format!("{bob_href}/suspend"), &[("csrf", &csrf), ("reason", "e2e")], Some(&tahinli), ) .await; assert_eq!(res.status, 303, "suspend bob: {}", res.body); commit_file(&work, "b.txt", "two\n", "second"); rejected( &git(&work, &["push", "origin", "HEAD:main"]), "push with a suspended user's token", ); let again = dir.join("again"); rejected( &git(&dir, &["clone", &url, path_str(&again)]), "clone with a suspended user's token", ); }