From 5137546bd223b1ff41369645c24f80daf79f7202 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 23 Oct 2026 07:04:34 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20test:=20forge-web=20page=20tests=20?= =?UTF-8?q?share=20their=20fixtures=20and=20merge=20into=20tables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per-file test counts before and after: - git_auth.rs: 9 -> 1 (basic auth cases in one table) - git_http.rs: 10 -> 9 (git protocol value cases in one table) - internal.rs: 10 -> 9 (ref name cases in one table) - lfs/route_tests.rs: 12 -> 11 (path-without-.git check moved onto the batch fixture) - notify.rs: 18 -> 16 (mention parsing cases in one table) - raw.rs: 11 -> 1 (read-only scenarios share one 9 MB fixture) - signatures.rs: 7 -> 4 (ssh badge scenarios share one fixture, key listing cases in one table) - webhooks/client.rs: 10 -> 9 (CIDR and hostname accept cases in one loop) - webhooks/payload.rs: 7 -> 7 (no duplicates found) Every assertion is kept and labelled with its case. Scoped run: 115 passed. --- crates/forge-web/src/git_auth.rs | 120 ++++------ crates/forge-web/src/git_http.rs | 36 +-- crates/forge-web/src/internal.rs | 36 +-- crates/forge-web/src/lfs/route_tests.rs | 7 +- crates/forge-web/src/notify.rs | 40 ++-- crates/forge-web/src/raw.rs | 279 ++++++++++++------------ crates/forge-web/src/signatures.rs | 92 +++++--- crates/forge-web/src/webhooks/client.rs | 35 +-- 8 files changed, 318 insertions(+), 327 deletions(-) diff --git a/crates/forge-web/src/git_auth.rs b/crates/forge-web/src/git_auth.rs index be5c907..2ae83ac 100644 --- a/crates/forge-web/src/git_auth.rs +++ b/crates/forge-web/src/git_auth.rs @@ -99,81 +99,49 @@ mod tests { } #[test] - fn parses_user_and_token() { - let headers = headers_with(&basic("tahinli:forge_abc")); - assert_eq!( - parse_basic_auth(&headers), - Some(("tahinli".to_owned(), "forge_abc".to_owned())) - ); - } - - #[test] - fn scheme_is_case_insensitive() { - let value = format!("bAsIc {}", BASE64_STANDARD.encode("tahinli:t")); - let headers = headers_with(&value); - assert_eq!( - parse_basic_auth(&headers), - Some(("tahinli".into(), "t".into())) - ); - } - - #[test] - fn password_may_contain_colons() { - let headers = headers_with(&basic("tahinli:a:b:c")); - assert_eq!( - parse_basic_auth(&headers), - Some(("tahinli".into(), "a:b:c".into())) - ); - } - - #[test] - fn empty_password_is_parsed_but_user_is_not_resolved_here() { - let headers = headers_with(&basic("tahinli:")); - assert_eq!( - parse_basic_auth(&headers), - Some(("tahinli".into(), String::new())) - ); - } - - #[test] - fn rejects_wrong_scheme() { - let value = format!("Bearer {}", BASE64_STANDARD.encode("tahinli:t")); - assert_eq!(parse_basic_auth(&headers_with(&value)), None); - } - - #[test] - fn rejects_missing_colon() { - assert_eq!( - parse_basic_auth(&headers_with(&basic("tahinlitoken"))), - None - ); - } - - #[test] - fn rejects_bad_base64() { - assert_eq!( - parse_basic_auth(&headers_with("Basic !!!not-base64!!!")), - None - ); - } - - #[test] - fn rejects_extra_spaces_and_empty_value() { - let encoded = BASE64_STANDARD.encode("tahinli:t"); - assert_eq!( - parse_basic_auth(&headers_with(&format!("Basic {encoded}"))), - None - ); - assert_eq!(parse_basic_auth(&headers_with("Basic ")), None); - assert_eq!(parse_basic_auth(&HeaderMap::new()), None); - } - - #[test] - fn rejects_non_utf8_credentials() { - let encoded = BASE64_STANDARD.encode([0xff_u8, 0xfe, b':', b'x']); - assert_eq!( - parse_basic_auth(&headers_with(&format!("Basic {encoded}"))), - None - ); + fn parse_basic_auth_cases() { + // One labelled table: each case keeps its own input and expected result. + let t = BASE64_STANDARD.encode("tahinli:t"); + let cases: Vec<(&str, String, Option<(&str, &str)>)> = vec![ + ( + "user and token", + basic("tahinli:forge_abc"), + Some(("tahinli", "forge_abc")), + ), + ( + "scheme is case insensitive", + format!("bAsIc {t}"), + Some(("tahinli", "t")), + ), + ( + "password may contain colons", + basic("tahinli:a:b:c"), + Some(("tahinli", "a:b:c")), + ), + ( + "empty password is parsed", + basic("tahinli:"), + Some(("tahinli", "")), + ), + ("wrong scheme", format!("Bearer {t}"), None), + ("missing colon", basic("tahinlitoken"), None), + ("bad base64", "Basic !!!not-base64!!!".to_owned(), None), + ("extra space", format!("Basic {t}"), None), + ("empty value", "Basic ".to_owned(), None), + ( + "non utf8 credentials", + format!( + "Basic {}", + BASE64_STANDARD.encode([0xff_u8, 0xfe, b':', b'x']) + ), + None, + ), + ]; + for (name, value, want) in cases { + let got = parse_basic_auth(&headers_with(&value)); + let want = want.map(|(user, pass)| (user.to_owned(), pass.to_owned())); + assert_eq!(got, want, "case {name}"); + } + assert_eq!(parse_basic_auth(&HeaderMap::new()), None, "case no header"); } } diff --git a/crates/forge-web/src/git_http.rs b/crates/forge-web/src/git_http.rs index 20dd509..c1bec6b 100644 --- a/crates/forge-web/src/git_http.rs +++ b/crates/forge-web/src/git_http.rs @@ -457,21 +457,27 @@ mod tests { use super::*; #[test] - fn git_protocol_accepts_documented_charset() { - assert!(valid_git_protocol("version=2")); - assert!(valid_git_protocol("version=2:object-format=sha1")); - assert!(valid_git_protocol("a.b,c_d-e:f")); - } - - #[test] - fn git_protocol_rejects_bad_values() { - assert!(!valid_git_protocol("")); - assert!(!valid_git_protocol("Version=2")); - assert!(!valid_git_protocol("version 2")); - assert!(!valid_git_protocol("version=2;x")); - assert!(!valid_git_protocol("version=2\n")); - assert!(!valid_git_protocol(&"a".repeat(65))); - assert!(valid_git_protocol(&"a".repeat(64))); + fn git_protocol_value_charset_and_length() { + // (name, value, expected validity); accepted charset first, then rejects and the length limit. + let cases: Vec<(&str, String, bool)> = vec![ + ("documented version", "version=2".into(), true), + ( + "object format pair", + "version=2:object-format=sha1".into(), + true, + ), + ("punctuation charset", "a.b,c_d-e:f".into(), true), + ("empty", String::new(), false), + ("uppercase key", "Version=2".into(), false), + ("space", "version 2".into(), false), + ("semicolon", "version=2;x".into(), false), + ("newline", "version=2\n".into(), false), + ("65 chars", "a".repeat(65), false), + ("64 chars", "a".repeat(64), true), + ]; + for (name, value, want) in cases { + assert_eq!(valid_git_protocol(&value), want, "case {name}"); + } } #[test] diff --git a/crates/forge-web/src/internal.rs b/crates/forge-web/src/internal.rs index 9f54556..f360c52 100644 --- a/crates/forge-web/src/internal.rs +++ b/crates/forge-web/src/internal.rs @@ -679,23 +679,25 @@ mod tests { use topcoat::router::RouterBuilderDiscoverExt; #[test] - fn ref_names_must_live_under_refs() { - assert!(is_valid_ref_name("refs/heads/main")); - assert!(is_valid_ref_name("refs/tags/v1.0")); - assert!(!is_valid_ref_name("HEAD")); - assert!(!is_valid_ref_name("heads/main")); - assert!(!is_valid_ref_name("refs/")); - } - - #[test] - fn ref_names_reject_dotdot_dash_components_and_control_chars() { - assert!(!is_valid_ref_name("refs/heads/a..b")); - assert!(!is_valid_ref_name("refs/heads/-evil")); - assert!(!is_valid_ref_name("refs/-evil/main")); - assert!(is_valid_ref_name("refs/heads/a-b")); - assert!(!is_valid_ref_name("refs/heads/a\nb")); - assert!(!is_valid_ref_name("refs/heads/a\0b")); - assert!(!is_valid_ref_name("refs/heads/a\x7fb")); + fn ref_name_validity_cases() { + // (ref name, expected validity): must live under refs/, no dotdot or leading dash, no control chars. + let cases: [(&str, bool); 12] = [ + ("refs/heads/main", true), + ("refs/tags/v1.0", true), + ("HEAD", false), + ("heads/main", false), + ("refs/", false), + ("refs/heads/a..b", false), + ("refs/heads/-evil", false), + ("refs/-evil/main", false), + ("refs/heads/a-b", true), + ("refs/heads/a\nb", false), + ("refs/heads/a\0b", false), + ("refs/heads/a\x7fb", false), + ]; + for (name, want) in cases { + assert_eq!(is_valid_ref_name(name), want, "case {name:?}"); + } } #[test] diff --git a/crates/forge-web/src/lfs/route_tests.rs b/crates/forge-web/src/lfs/route_tests.rs index 1570434..d3879cd 100644 --- a/crates/forge-web/src/lfs/route_tests.rs +++ b/crates/forge-web/src/lfs/route_tests.rs @@ -195,11 +195,8 @@ async fn batch_download_returns_action_for_stored_object() { now(), )); assert_eq!(body["objects"][1]["error"]["code"], 404); -} -#[tokio::test] -async fn batch_accepts_the_path_without_dot_git() { - let fx = fixture(Visibility::Public).await; + // Same router: the batch path without the `.git` suffix also answers (second object, same repo). let oid = upload_with_pat(&fx, b"bare path\n").await; let reply = send( &fx.router, @@ -209,7 +206,7 @@ async fn batch_accepts_the_path_without_dot_git() { batch_body("download", &[(oid.clone(), 9)]), ) .await; - assert_eq!(reply.status, 200); + assert_eq!(reply.status, 200, "path without .git"); assert!(reply.json()["objects"][0]["actions"]["download"].is_object()); } diff --git a/crates/forge-web/src/notify.rs b/crates/forge-web/src/notify.rs index b7e8648..beab2f5 100644 --- a/crates/forge-web/src/notify.rs +++ b/crates/forge-web/src/notify.rs @@ -754,26 +754,26 @@ mod tests { } #[test] - fn mentions_skip_code_links_and_emails() { - let text = "hi @Tahinli and @bob. mail a@b.com `@code`\n\n\ - ```\n@blocked\n```\n[@linked](https://x.test) @tahinli again"; - assert_eq!(mentioned_usernames(text), vec!["tahinli", "bob"]); - } - - #[test] - fn mentions_in_html_blocks_are_found() { - let text = "
\n@carol\n
\n"; - assert_eq!(mentioned_usernames(text), vec!["carol"]); - } - - #[test] - fn mentions_are_deduped_case_insensitively() { - assert_eq!( - mentioned_usernames("@Bob @bob @BOB"), - vec!["bob"], - "one name however it is cased" - ); - assert!(mentioned_usernames("no mentions here").is_empty()); + fn mentioned_usernames_cases() { + // (name, markdown, expected usernames): code, links, emails, HTML, dedupe and no-mention cases. + let cases: Vec<(&str, &str, Vec<&str>)> = vec![ + ( + "skips code, links and emails", + "hi @Tahinli and @bob. mail a@b.com `@code`\n\n\ + ```\n@blocked\n```\n[@linked](https://x.test) @tahinli again", + vec!["tahinli", "bob"], + ), + ( + "found inside html blocks", + "
\n@carol\n
\n", + vec!["carol"], + ), + ("deduped case-insensitively", "@Bob @bob @BOB", vec!["bob"]), + ("no mentions", "no mentions here", vec![]), + ]; + for (name, text, want) in cases { + assert_eq!(mentioned_usernames(text), want, "case {name}"); + } } #[tokio::test] diff --git a/crates/forge-web/src/raw.rs b/crates/forge-web/src/raw.rs index 3447fc2..8203c7d 100644 --- a/crates/forge-web/src/raw.rs +++ b/crates/forge-web/src/raw.rs @@ -647,162 +647,157 @@ mod tests { assert_eq!(header_str(res, "referrer-policy"), "no-referrer"); } + /// One fixture (one 9 MB repo, private repo and signer) serves every read-only scenario below. #[tokio::test] - async fn public_text_file_is_plain_and_sandboxed() { + async fn raw_serves_every_scenario_from_one_fixture() { let fx = fixture().await; - let res = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; - assert_eq!(res.status(), 200); - assert_eq!(header_str(&res, "content-type"), TEXT); - assert_eq!(header_str(&res, "content-disposition"), ""); - assert_eq!(header_str(&res, "cache-control"), CACHE_PUBLIC); - assert_security_headers(&res); - assert_eq!(body_bytes(res).await, b"hello raw\n"); - } + // Scenario: a public text file is plain and sandboxed. + { + let res = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; + assert_eq!(res.status(), 200); + assert_eq!(header_str(&res, "content-type"), TEXT); + assert_eq!(header_str(&res, "content-disposition"), ""); + assert_eq!(header_str(&res, "cache-control"), CACHE_PUBLIC); + assert_security_headers(&res); + assert_eq!(body_bytes(res).await, b"hello raw\n"); + } - #[tokio::test] - async fn nested_path_resolves() { - let fx = fixture().await; - let res = get(&fx.router, "GET", "/tahinli/pub/main/sub/a.txt", None).await; - assert_eq!(res.status(), 200); - assert_eq!(body_bytes(res).await, b"nested\n"); - } + // Scenario: a nested path resolves. + { + let res = get(&fx.router, "GET", "/tahinli/pub/main/sub/a.txt", None).await; + assert_eq!(res.status(), 200); + assert_eq!(body_bytes(res).await, b"nested\n"); + } - #[tokio::test] - async fn html_is_forced_to_attachment_and_png_is_an_image() { - let fx = fixture().await; - // (path, want content-type, want content-disposition) - let cases = [ - ("/tahinli/pub/main/page.html", TEXT, "attachment"), - ("/tahinli/pub/main/pic.png", "image/png", ""), - ]; - for (uri, content_type, disposition) in cases { - let res = get(&fx.router, "GET", uri, None).await; - assert_eq!(res.status(), 200, "case {uri}"); - assert_eq!(header_str(&res, "content-type"), content_type, "case {uri}"); - assert_eq!( - header_str(&res, "content-disposition"), - disposition, - "case {uri}" - ); + // Scenario: html is forced to an attachment and png is an image. + { + // (path, want content-type, want content-disposition) + let cases = [ + ("/tahinli/pub/main/page.html", TEXT, "attachment"), + ("/tahinli/pub/main/pic.png", "image/png", ""), + ]; + for (uri, content_type, disposition) in cases { + let res = get(&fx.router, "GET", uri, None).await; + assert_eq!(res.status(), 200, "case {uri}"); + assert_eq!(header_str(&res, "content-type"), content_type, "case {uri}"); + assert_eq!( + header_str(&res, "content-disposition"), + disposition, + "case {uri}" + ); + } } - } - #[tokio::test] - async fn symlink_is_served_as_its_target_text() { - let fx = fixture().await; - let res = get(&fx.router, "GET", "/tahinli/pub/main/link", None).await; - assert_eq!(res.status(), 200); - assert_eq!(header_str(&res, "content-type"), TEXT); - assert_eq!(body_bytes(res).await, b"hello.txt"); - } + // Scenario: a symlink is served as its target text. + { + let res = get(&fx.router, "GET", "/tahinli/pub/main/link", None).await; + assert_eq!(res.status(), 200); + assert_eq!(header_str(&res, "content-type"), TEXT); + assert_eq!(body_bytes(res).await, b"hello.txt"); + } - #[tokio::test] - async fn private_repo_requires_a_valid_token() { - let fx = fixture().await; - let path = "/tahinli/priv/main/hello.txt"; - let now = now_unix(); - - let none = get(&fx.router, "GET", path, None).await; - assert_eq!(none.status(), 404); - assert_eq!(header_str(&none, "cache-control"), CACHE_NONE); - - let valid = sign_raw(&KEY, &fx.private.id, now + 600); - let res = get(&fx.router, "GET", &format!("{path}?token={valid}"), None).await; - assert_eq!(res.status(), 200); - assert_eq!(header_str(&res, "cache-control"), CACHE_PRIVATE); - assert_eq!(body_bytes(res).await, b"secret\n"); - - let expired = sign_raw(&KEY, &fx.private.id, now - 1); - let res = get(&fx.router, "GET", &format!("{path}?token={expired}"), None).await; - assert_eq!(res.status(), 404); - - let other = sign_raw(&KEY, &fx.public.id, now + 600); - let res = get(&fx.router, "GET", &format!("{path}?token={other}"), None).await; - assert_eq!(res.status(), 404); - } + // Scenario: a private repo requires a valid, unexpired token for that repo. + { + let path = "/tahinli/priv/main/hello.txt"; + let now = now_unix(); - #[tokio::test] - async fn missing_repos_and_directories_are_404() { - let fx = fixture().await; - for uri in [ - "/tahinli/nope/main/hello.txt", - "/tahinli/pub/main/sub", - "/tahinli/pub/main", - ] { - let res = get(&fx.router, "GET", uri, None).await; - assert_eq!(res.status(), 404, "case {uri}"); + let none = get(&fx.router, "GET", path, None).await; + assert_eq!(none.status(), 404); + assert_eq!(header_str(&none, "cache-control"), CACHE_NONE); + + let valid = sign_raw(&KEY, &fx.private.id, now + 600); + let res = get(&fx.router, "GET", &format!("{path}?token={valid}"), None).await; + assert_eq!(res.status(), 200); + assert_eq!(header_str(&res, "cache-control"), CACHE_PRIVATE); + assert_eq!(body_bytes(res).await, b"secret\n"); + + let expired = sign_raw(&KEY, &fx.private.id, now - 1); + let res = get(&fx.router, "GET", &format!("{path}?token={expired}"), None).await; + assert_eq!(res.status(), 404); + + let other = sign_raw(&KEY, &fx.public.id, now + 600); + let res = get(&fx.router, "GET", &format!("{path}?token={other}"), None).await; + assert_eq!(res.status(), 404); } - } - #[tokio::test] - async fn etag_gives_304() { - let fx = fixture().await; - let first = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; - let etag = header_str(&first, "etag"); - assert!(etag.starts_with('"') && etag.ends_with('"'), "etag {etag}"); - let again = get( - &fx.router, - "GET", - "/tahinli/pub/main/hello.txt", - Some(&etag), - ) - .await; - assert_eq!(again.status(), 304); - assert_eq!(header_str(&again, "etag"), etag); - } + // Scenario: missing repos and directories are 404. + { + for uri in [ + "/tahinli/nope/main/hello.txt", + "/tahinli/pub/main/sub", + "/tahinli/pub/main", + ] { + let res = get(&fx.router, "GET", uri, None).await; + assert_eq!(res.status(), 404, "case {uri}"); + } + } - #[tokio::test] - async fn head_has_headers_and_no_body() { - let fx = fixture().await; - let res = get(&fx.router, "HEAD", "/tahinli/pub/main/hello.txt", None).await; - assert_eq!(res.status(), 200); - assert_eq!(header_str(&res, "content-type"), TEXT); - assert_eq!(header_str(&res, "content-length"), "10"); - assert!(body_bytes(res).await.is_empty()); - } + // Scenario: a matching etag gives 304. + { + let first = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await; + let etag = header_str(&first, "etag"); + assert!(etag.starts_with('"') && etag.ends_with('"'), "etag {etag}"); + let again = get( + &fx.router, + "GET", + "/tahinli/pub/main/hello.txt", + Some(&etag), + ) + .await; + assert_eq!(again.status(), 304); + assert_eq!(header_str(&again, "etag"), etag); + } - #[tokio::test] - async fn large_file_streams_intact() { - let fx = fixture().await; - let res = get(&fx.router, "GET", "/tahinli/pub/main/big.txt", None).await; - assert_eq!(res.status(), 200); - assert_eq!(header_str(&res, "content-length"), "9437184"); - let expected: Vec = b"0123456789abcdef\n" - .iter() - .cycle() - .take(9 * 1024 * 1024) - .copied() - .collect(); - let body = body_bytes(res).await; - assert!(body == expected, "streamed body differs"); - } + // Scenario: HEAD has headers and no body. + { + let res = get(&fx.router, "HEAD", "/tahinli/pub/main/hello.txt", None).await; + assert_eq!(res.status(), 200); + assert_eq!(header_str(&res, "content-type"), TEXT); + assert_eq!(header_str(&res, "content-length"), "10"); + assert!(body_bytes(res).await.is_empty()); + } - #[tokio::test] - async fn app_routes_are_not_on_the_raw_origin() { - let fx = fixture().await; - for path in ["/login", "/settings/keys", "/tahinli/pub/tree/main"] { - let res = get(&fx.router, "GET", path, None).await; - assert_eq!(res.status(), 404, "{path} is reachable"); + // Scenario: a large file streams intact. + { + let res = get(&fx.router, "GET", "/tahinli/pub/main/big.txt", None).await; + assert_eq!(res.status(), 200); + assert_eq!(header_str(&res, "content-length"), "9437184"); + let expected: Vec = b"0123456789abcdef\n" + .iter() + .cycle() + .take(9 * 1024 * 1024) + .copied() + .collect(); + let body = body_bytes(res).await; + assert!(body == expected, "streamed body differs"); } - let health = get(&fx.router, "GET", "/healthz", None).await; - assert_eq!(health.status(), 200); - } - #[tokio::test] - async fn raw_url_encodes_and_signs() { - let fx = fixture().await; - let url = raw_url(&fx.state, &fx.public, "main", "my file#1.txt"); - assert_eq!( - url, - "http://127.0.0.1:7661/tahinli/pub/main/my%20file%231.txt" - ); - let private = raw_url(&fx.state, &fx.private, "feature/x", "a b/c#d.txt"); - assert!( - private - .starts_with("http://127.0.0.1:7661/tahinli/priv/feature/x/a%20b/c%23d.txt?token="), - "{private}" - ); - let token = private.rsplit_once("?token=").map(|(_, t)| t).unwrap_or(""); - assert!(verify_raw(&KEY, token, &fx.private.id, now_unix())); + // Scenario: app routes are not on the raw origin, but healthz is. + { + for path in ["/login", "/settings/keys", "/tahinli/pub/tree/main"] { + let res = get(&fx.router, "GET", path, None).await; + assert_eq!(res.status(), 404, "{path} is reachable"); + } + let health = get(&fx.router, "GET", "/healthz", None).await; + assert_eq!(health.status(), 200); + } + + // Scenario: raw URLs are encoded, and private ones are signed. + { + let url = raw_url(&fx.state, &fx.public, "main", "my file#1.txt"); + assert_eq!( + url, + "http://127.0.0.1:7661/tahinli/pub/main/my%20file%231.txt" + ); + let private = raw_url(&fx.state, &fx.private, "feature/x", "a b/c#d.txt"); + assert!( + private.starts_with( + "http://127.0.0.1:7661/tahinli/priv/feature/x/a%20b/c%23d.txt?token=" + ), + "{private}" + ); + let token = private.rsplit_once("?token=").map(|(_, t)| t).unwrap_or(""); + assert!(verify_raw(&KEY, token, &fx.private.id, now_unix())); + } } } diff --git a/crates/forge-web/src/signatures.rs b/crates/forge-web/src/signatures.rs index 1e29b57..b010b25 100644 --- a/crates/forge-web/src/signatures.rs +++ b/crates/forge-web/src/signatures.rs @@ -697,45 +697,47 @@ mod tests { } #[tokio::test] - async fn ssh_signature_by_a_user_with_matching_email_is_verified() { + async fn ssh_badges_per_commit_scenarios() { + // One fixture (one repo and one signer) for three commits: each scenario pushes its own + // commit and checks only that commit's badge. The cache test below stays separate because + // it deletes the signer's key. let f = fixture().await; - let oid = signed_commit(&f, "tahinli@example.com"); - let badges = badges(&f.state, &f.repo, &[f.base_oid.clone(), oid.clone()]).await; - assert_eq!(badges.len(), 1, "the unsigned base commit has no badge"); + // Scenario: a signature by a user whose email matches the committer is verified. + let oid = signed_commit(&f, "tahinli@example.com"); + let got = badges(&f.state, &f.repo, &[f.base_oid.clone(), oid.clone()]).await; + assert_eq!(got.len(), 1, "the unsigned base commit has no badge"); assert_eq!( - badges.get(&oid), + got.get(&oid), Some(&SigBadge::Verified { signer: "tahinli".into(), key: ssh_fingerprint(&f.pub_path), - }) + }), + "matching email" ); - } - #[tokio::test] - async fn committer_email_mismatch_is_unverified() { - let f = fixture().await; + // Scenario: a committer email that differs from the signer is unverified. let oid = signed_commit(&f, "bob@example.com"); - - let badges = badges(&f.state, &f.repo, std::slice::from_ref(&oid)).await; + let got = badges(&f.state, &f.repo, std::slice::from_ref(&oid)).await; assert!( - matches!(badges.get(&oid), Some(SigBadge::Unverified { .. })), - "{badges:?}" + matches!(got.get(&oid), Some(SigBadge::Unverified { .. })), + "mismatched email: {got:?}" ); - } - #[tokio::test] - async fn unsigned_commits_are_omitted() { - let f = fixture().await; - let badges = badges(&f.state, &f.repo, std::slice::from_ref(&f.base_oid)).await; - assert!(badges.is_empty()); + // Scenario: an unsigned commit gets no badge and is cached as unsigned. + let got = badges(&f.state, &f.repo, std::slice::from_ref(&f.base_oid)).await; + assert!(got.is_empty(), "unsigned commit"); let cached = f .state .store .cached_signatures(&f.repo.id, std::slice::from_ref(&f.base_oid)) .await .unwrap(); - assert_eq!(cached[&f.base_oid].status, SigStatus::Unsigned); + assert_eq!( + cached[&f.base_oid].status, + SigStatus::Unsigned, + "unsigned cache" + ); } #[tokio::test] @@ -789,24 +791,44 @@ mod tests { } #[test] - fn key_listing_yields_primary_fingerprint_and_emails() { - let listing = "pub:u:255:22:ABCDEF0123456789ABCDEF0123456789ABCDEF01:1700000000::::::23::0:\n\ + fn key_listing_parses_one_key_or_rejects() { + // (name, colon listing, expected Some((primary fingerprint, emails)) or None for rejection) + let cases: Vec<(&str, &str, Option<(&str, Vec<&str>)>)> = vec![ + ( + "primary fingerprint and emails", + "pub:u:255:22:ABCDEF0123456789ABCDEF0123456789ABCDEF01:1700000000::::::23::0:\n\ fpr:::::::::ABCDEF0123456789ABCDEF0123456789ABCDEF01:\n\ uid:u::::1700000000::HASH::Tahinli ::::::::::0:\n\ uid:u::::1700000000::HASH::Tahinli Work ::::::::::0:\n\ sub:u:255:18:1111111111111111111111111111111111111111:1700000000:::::e::::::23:\n\ -fpr:::::::::1111111111111111111111111111111111111111:\n"; - let (fp, emails) = parse_key_listing(listing).unwrap(); - assert_eq!(fp, "ABCDEF0123456789ABCDEF0123456789ABCDEF01"); - assert_eq!(emails, vec!["tahinli@example.com", "work@example.org"]); - } - - #[test] - fn key_listing_rejects_two_keys_and_missing_email() { - let two = "pub:u:255:22:AAAA:1::::::23::0:\nfpr:::::::::AAAA:\npub:u:255:22:BBBB:1::::::23::0:\nfpr:::::::::BBBB:\n"; - assert!(parse_key_listing(two).is_err()); - let no_mail = "pub:u:255:22:AAAA:1::::::23::0:\nfpr:::::::::AAAA:\nuid:u::::1::HASH::Nobody::::::::::0:\n"; - assert!(parse_key_listing(no_mail).is_err()); +fpr:::::::::1111111111111111111111111111111111111111:\n", + Some(( + "ABCDEF0123456789ABCDEF0123456789ABCDEF01", + vec!["tahinli@example.com", "work@example.org"], + )), + ), + ( + "two keys", + "pub:u:255:22:AAAA:1::::::23::0:\nfpr:::::::::AAAA:\npub:u:255:22:BBBB:1::::::23::0:\nfpr:::::::::BBBB:\n", + None, + ), + ( + "missing email", + "pub:u:255:22:AAAA:1::::::23::0:\nfpr:::::::::AAAA:\nuid:u::::1::HASH::Nobody::::::::::0:\n", + None, + ), + ]; + for (name, listing, want) in cases { + let got = parse_key_listing(listing); + match want { + Some((fp, emails)) => { + let (got_fp, got_emails) = got.unwrap_or_else(|e| panic!("case {name}: {e}")); + assert_eq!(got_fp, fp, "case {name}"); + assert_eq!(got_emails, emails, "case {name}"); + } + None => assert!(got.is_err(), "case {name}"), + } + } } /// Runs `gpg` against `home` with `--batch`, asserting success. Returns stdout. diff --git a/crates/forge-web/src/webhooks/client.rs b/crates/forge-web/src/webhooks/client.rs index 3bc3011..5f95b21 100644 --- a/crates/forge-web/src/webhooks/client.rs +++ b/crates/forge-web/src/webhooks/client.rs @@ -606,23 +606,24 @@ mod tests { } #[tokio::test] - async fn send_accepts_allowed_loopback_cidr() { - let addr = serve(ok_response()).await; - let client = HookClient::new(policy(true, &["127.0.0.1/32"])).expect("client"); - let outcome = post(&client, &format!("http://127.0.0.1:{}/hook", addr.port())).await; - assert_eq!(outcome.error, None); - assert_eq!(outcome.status, Some(200)); - assert_eq!(outcome.body, "ok"); - assert!(outcome.headers.iter().any(|(k, _)| k == "content-type")); - } - - #[tokio::test] - async fn send_accepts_allowed_hostname() { - let addr = serve(ok_response()).await; - let client = HookClient::new(policy(true, &["localhost"])).expect("client"); - let outcome = post(&client, &format!("http://localhost:{}/hook", addr.port())).await; - assert_eq!(outcome.error, None); - assert_eq!(outcome.status, Some(200)); + async fn send_accepts_allowed_cidr_and_hostname() { + // (name, allowed entry, host used in the URL); both must deliver the same response. + let cases = [ + ("loopback cidr", "127.0.0.1/32", "127.0.0.1"), + ("hostname", "localhost", "localhost"), + ]; + for (name, allowed, host) in cases { + let addr = serve(ok_response()).await; + let client = HookClient::new(policy(true, &[allowed])).expect("client"); + let outcome = post(&client, &format!("http://{host}:{}/hook", addr.port())).await; + assert_eq!(outcome.error, None, "case {name}"); + assert_eq!(outcome.status, Some(200), "case {name}"); + assert_eq!(outcome.body, "ok", "case {name}"); + assert!( + outcome.headers.iter().any(|(k, _)| k == "content-type"), + "case {name}" + ); + } } #[tokio::test]