From 7cded1477fc6dbc239f4d8a92c4c5bd068f1773c 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 06:51:31 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20test:=20page=20tests=20share=20thei?= =?UTF-8?q?r=20fixtures=20and=20merge=20into=20tables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per file, test count before -> after: - login.rs: 12 -> 4 (password throttles on one app, audit kept pristine, two-factor flows on one app, two-factor expiry and limit on one app) - issue_pin_tests.rs: 7 -> 2 (write rules in order on one repo, read views on one repo) - edit_history.rs: 7 -> 2 (public scenarios share one fixture, private repo kept separate) - discussion_live_tests.rs: 4 -> 2 (public writes share one seed, streams test kept) - labels_page.rs: 4 -> 1 (defaults button and adding in order on one site) - labels_css.rs: 4 -> 4 (unchanged, no shared fixture to merge) Total: 38 -> 15. Every assertion is kept, with the scenario name in its message. --- .../src/pages/discussion_live_tests.rs | 53 ++- crates/forge-web/src/pages/edit_history.rs | 269 +++++++------- crates/forge-web/src/pages/issue_pin_tests.rs | 147 ++++---- crates/forge-web/src/pages/labels_page.rs | 73 ++-- crates/forge-web/src/pages/login.rs | 333 ++++++++++-------- 5 files changed, 454 insertions(+), 421 deletions(-) diff --git a/crates/forge-web/src/pages/discussion_live_tests.rs b/crates/forge-web/src/pages/discussion_live_tests.rs index 907b8ce..da653fc 100644 --- a/crates/forge-web/src/pages/discussion_live_tests.rs +++ b/crates/forge-web/src/pages/discussion_live_tests.rs @@ -122,10 +122,14 @@ async fn seeded(visibility: Visibility) -> Seed { } } +/// Writes on a public repo bump the topics they reach. Each write gets fresh subscriptions opened +/// after the earlier writes, so a receiver only sees the changes made after it was opened. #[tokio::test] -async fn a_comment_bumps_the_list_and_the_discussion_only() { +async fn writes_bump_the_topics_they_reach() { let seed = seeded(Visibility::Public).await; let site = &seed.site; + + // A comment bumps the list and its discussion, and not an unrelated discussion. let list = site .live .subscribe(&Topic::Discussions(seed.repo_id.clone())); @@ -133,7 +137,6 @@ async fn a_comment_bumps_the_list_and_the_discussion_only() { .live .subscribe(&Topic::Discussion(seed.discussion_id.clone())); let other = site.live.subscribe(&Topic::Discussion("other".to_owned())); - let status = post( site, "/tahinli/forge/discussions/1/comments", @@ -141,31 +144,31 @@ async fn a_comment_bumps_the_list_and_the_discussion_only() { &[("csrf", CSRF), ("body", "A reply")], ) .await; - - assert_ne!(status, 404, "the comment was refused"); + assert_ne!(status, 404, "comment: the comment was refused"); let comments = site .store .list_discussion_comments(&seed.discussion_id) .await .expect("comments"); - assert_eq!(comments.len(), 1, "the comment was stored"); - assert!(list.has_changed().expect("open"), "the list was bumped"); + assert_eq!(comments.len(), 1, "comment: the comment was stored"); + assert!( + list.has_changed().expect("open"), + "comment: the list was bumped" + ); assert!( item.has_changed().expect("open"), - "the discussion was bumped" + "comment: the discussion was bumped" + ); + assert!( + !other.has_changed().expect("open"), + "comment: an unrelated discussion was not bumped" ); - assert!(!other.has_changed().expect("open")); -} -#[tokio::test] -async fn a_new_discussion_bumps_the_list() { - let seed = seeded(Visibility::Public).await; - let site = &seed.site; + // A new discussion bumps the list. let list = site .live .subscribe(&Topic::Discussions(seed.repo_id.clone())); let category = DiscussionCategory::General.as_str(); - let status = post( site, "/tahinli/forge/discussions/new", @@ -178,20 +181,17 @@ async fn a_new_discussion_bumps_the_list() { ], ) .await; + assert_ne!(status, 404, "new discussion: the discussion was refused"); + assert!( + list.has_changed().expect("open"), + "new discussion: the list was bumped" + ); - assert_ne!(status, 404, "the discussion was refused"); - assert!(list.has_changed().expect("open"), "the list was bumped"); -} - -#[tokio::test] -async fn a_refused_write_still_bumps_so_the_page_reads_the_truth() { - let seed = seeded(Visibility::Public).await; - let site = &seed.site; + // A refused write still bumps, so the page reads the truth. A blank comment is refused by the + // handler; the write layer bumps after the handler either way. let item = site .live .subscribe(&Topic::Discussion(seed.discussion_id.clone())); - - // A blank comment is refused by the handler. The write layer bumps after the handler either way. let status = post( site, "/tahinli/forge/discussions/1/comments", @@ -199,11 +199,10 @@ async fn a_refused_write_still_bumps_so_the_page_reads_the_truth() { &[("csrf", CSRF), ("body", "")], ) .await; - - assert_ne!(status, 404, "the discussion page answered"); + assert_ne!(status, 404, "refused write: the discussion page answered"); assert!( item.has_changed().expect("open"), - "the discussion was bumped" + "refused write: the discussion was bumped" ); } diff --git a/crates/forge-web/src/pages/edit_history.rs b/crates/forge-web/src/pages/edit_history.rs index 64dc936..ca93e11 100644 --- a/crates/forge-web/src/pages/edit_history.rs +++ b/crates/forge-web/src/pages/edit_history.rs @@ -370,11 +370,15 @@ mod tests { std::iter::repeat_n(c, 40).collect() } + /// Every scenario on the public repo shares one fixture. Each makes its own issue or pull and + /// reads its numbers from the store, so no scenario depends on another's data. #[tokio::test] - async fn comment_edited_twice_shows_marker_and_diffs() { + async fn public_histories_show_diffs_markers_and_refusals() { let fx = Fixture::new(Visibility::Public).await; let owner = tahinli(&fx).await; let id = repo_id(&fx).await; + + // A comment edited twice: a marker on the item page and two versions with diffs. let issue = fx .store .create_issue(&id, &owner.id, "bug", "body") @@ -393,170 +397,154 @@ mod tests { .edit_comment(&comment.id, &owner.id, "one\nTWO\nthree\nfour") .await .unwrap(); - - let (status, page) = send(&fx.router, "/tahinli/demo/issues/1", None).await; - assert_eq!(status, 200); - let link = format!("/tahinli/demo/issues/1/history/comment/{}", comment.id); - assert!(page.contains("issue-edited"), "{page}"); - assert!(page.contains(&format!("href=\"{link}\"")), "{page}"); + let item = format!("/tahinli/demo/issues/{}", issue.number); + let link = format!("{item}/history/comment/{}", comment.id); + + let (status, page) = send(&fx.router, &item, None).await; + assert_eq!(status, 200, "edited comment: item page"); + assert!( + page.contains("issue-edited"), + "edited comment: marker {page}" + ); + assert!( + page.contains(&format!("href=\"{link}\"")), + "edited comment: link {page}" + ); let (status, history) = send(&fx.router, &link, None).await; - assert_eq!(status, 200); - assert_eq!(history.matches(" String { format!("{PIN_PATH}{number}/pin") } +/// Write rules on one repo, run in order because the pin count only grows: triage pins and unpins +/// (the timeline records both); a read-only collaborator and an anonymous viewer are refused; a +/// missing CSRF token changes nothing; a bad value is 400 and an unknown issue is 404; and the +/// fourth pin is refused with the limit shown. #[tokio::test] -async fn triage_pins_and_unpins_and_records_the_timeline() { +async fn pin_writes_follow_the_rules_in_order() { let s = seeded().await; + let store = &s.site.store; let (issue_id, number) = s.issues[0].clone(); let uri = pin_uri(number); + // Triage pins, then unpins. let reply = call( &s.site, "POST", @@ -163,20 +169,21 @@ async fn triage_pins_and_unpins_and_records_the_timeline() { Some(pin_fields("1").as_slice()), ) .await; - assert_eq!(reply.status, 303); + assert_eq!(reply.status, 303, "triage pin"); assert_eq!( reply.location.as_deref(), - Some(format!("{PIN_PATH}{number}").as_str()) + Some(format!("{PIN_PATH}{number}").as_str()), + "triage pin redirect" ); assert!( - s.site - .store + store .is_pinned(&s.repo_id, &issue_id) .await - .expect("pinned") + .expect("pinned"), + "triage pin stored" ); - let events = s.site.store.list_events(&issue_id).await.expect("events"); - assert!(events.iter().any(|e| e.kind == "pinned")); + let events = store.list_events(&issue_id).await.expect("events"); + assert!(events.iter().any(|e| e.kind == "pinned"), "pinned event"); let reply = call( &s.site, @@ -186,24 +193,21 @@ async fn triage_pins_and_unpins_and_records_the_timeline() { Some(pin_fields("0").as_slice()), ) .await; - assert_eq!(reply.status, 303); + assert_eq!(reply.status, 303, "triage unpin"); assert!( - !s.site - .store + !store .is_pinned(&s.repo_id, &issue_id) .await - .expect("pinned") + .expect("pinned"), + "triage unpin stored" + ); + let events = store.list_events(&issue_id).await.expect("events"); + assert!( + events.iter().any(|e| e.kind == "unpinned"), + "unpinned event" ); - let events = s.site.store.list_events(&issue_id).await.expect("events"); - assert!(events.iter().any(|e| e.kind == "unpinned")); -} - -#[tokio::test] -async fn read_only_collaborator_and_anonymous_are_forbidden() { - let s = seeded().await; - let (issue_id, number) = s.issues[0].clone(); - let uri = pin_uri(number); + // A read-only collaborator and an anonymous viewer are refused. let reply = call( &s.site, "POST", @@ -212,7 +216,7 @@ async fn read_only_collaborator_and_anonymous_are_forbidden() { Some(pin_fields("1").as_slice()), ) .await; - assert_eq!(reply.status, 403); + assert_eq!(reply.status, 403, "read-only pin"); let reply = call( &s.site, "POST", @@ -221,52 +225,48 @@ async fn read_only_collaborator_and_anonymous_are_forbidden() { Some(pin_fields("1").as_slice()), ) .await; - assert!(reply.status == 403 || reply.status == 303); assert!( - !s.site - .store + reply.status == 403 || reply.status == 303, + "anonymous pin: {}", + reply.status + ); + assert!( + !store .is_pinned(&s.repo_id, &issue_id) .await - .expect("pinned") + .expect("pinned"), + "refused pins stored nothing" ); -} -#[tokio::test] -async fn missing_csrf_is_forbidden_and_changes_nothing() { - let s = seeded().await; - let (issue_id, number) = s.issues[0].clone(); + // A missing CSRF token is forbidden and changes nothing. let no_token: &[(&str, &str)] = &[("pinned", "1")]; let reply = call( &s.site, "POST", - &pin_uri(number), + &uri, Some(s.tahinli_cookie.as_str()), Some(no_token), ) .await; - assert_eq!(reply.status, 403); + assert_eq!(reply.status, 403, "missing csrf"); assert!( - !s.site - .store + !store .is_pinned(&s.repo_id, &issue_id) .await - .expect("pinned") + .expect("pinned"), + "missing csrf stored nothing" ); -} -#[tokio::test] -async fn bad_pinned_value_is_rejected_and_unknown_issue_is_404() { - let s = seeded().await; - let (_, number) = s.issues[0].clone(); + // A bad pinned value is 400; an unknown issue is 404. let reply = call( &s.site, "POST", - &pin_uri(number), + &uri, Some(s.carol_cookie.as_str()), Some(&[("csrf", CSRF), ("pinned", "yes")][..]), ) .await; - assert_eq!(reply.status, 400); + assert_eq!(reply.status, 400, "bad pinned value"); let reply = call( &s.site, "POST", @@ -275,14 +275,11 @@ async fn bad_pinned_value_is_rejected_and_unknown_issue_is_404() { Some(pin_fields("1").as_slice()), ) .await; - assert_eq!(reply.status, 404); -} + assert_eq!(reply.status, 404, "unknown issue"); -#[tokio::test] -async fn fourth_pin_shows_the_limit_and_pins_nothing() { - let s = seeded().await; + // Three pins fill the limit; the fourth is shown the limit and pins nothing. for (id, _) in &s.issues[..3] { - s.site.store.pin_issue(&s.repo_id, id).await.expect("pin"); + store.pin_issue(&s.repo_id, id).await.expect("pin"); } let (fourth_id, fourth_number) = s.issues[3].clone(); let reply = call( @@ -293,50 +290,56 @@ async fn fourth_pin_shows_the_limit_and_pins_nothing() { Some(pin_fields("1").as_slice()), ) .await; - assert_eq!(reply.status, 200); - assert!(reply.body.contains("already has 3 pinned issues")); + assert_eq!(reply.status, 200, "fourth pin"); assert!( - !s.site - .store + reply.body.contains("already has 3 pinned issues"), + "fourth pin: limit shown" + ); + assert!( + !store .is_pinned(&s.repo_id, &fourth_id) .await - .expect("pinned") + .expect("pinned"), + "fourth pin stored nothing" ); } +/// The read side on its own repo: the issue page offers pin to triage only, and the issue list +/// shows pinned cards above the list. #[tokio::test] -async fn issue_list_shows_pinned_cards_above_the_list() { +async fn pin_controls_and_cards_show_for_the_right_viewers() { let s = seeded().await; - let (_, number) = s.issues[1].clone(); + let (issue_id, number) = s.issues[1].clone(); s.site .store - .pin_issue(&s.repo_id, &s.issues[1].0) + .pin_issue(&s.repo_id, &issue_id) .await .expect("pin"); + let reply = call(&s.site, "GET", "/tahinli/forge/issues", None, None).await; - assert_eq!(reply.status, 200); - assert!(reply.body.contains("pinned-card")); + assert_eq!(reply.status, 200, "issue list"); + assert!(reply.body.contains("pinned-card"), "pinned card shown"); assert!( reply .body - .contains(&format!("/tahinli/forge/issues/{number}\"")) + .contains(&format!("/tahinli/forge/issues/{number}\"")), + "pinned card links the pinned issue" ); let card_at = reply.body.find("pinned-card").expect("card"); let list_at = reply.body.find("issue-list").expect("list"); - assert!(card_at < list_at); -} + assert!(card_at < list_at, "pinned cards sit above the list"); -#[tokio::test] -async fn issue_page_offers_pin_to_triage_only() { - let s = seeded().await; - let (_, number) = s.issues[0].clone(); - let page = format!("{PIN_PATH}{number}"); + let (_, first_number) = s.issues[0].clone(); + let page = format!("{PIN_PATH}{first_number}"); let reply = call(&s.site, "GET", &page, Some(s.carol_cookie.as_str()), None).await; - assert_eq!(reply.status, 200); - assert!(reply.body.contains("Pin issue")); - assert!(reply.body.contains(&format!("{page}/pin"))); + assert_eq!(reply.status, 200, "triage issue page"); + assert!(reply.body.contains("Pin issue"), "triage sees pin"); + assert!( + reply.body.contains(&format!("{page}/pin")), + "triage pin form" + ); let reply = call(&s.site, "GET", &page, Some(s.bob_cookie.as_str()), None).await; - assert_eq!(reply.status, 200); - assert!(!reply.body.contains("Pin issue")); + assert_eq!(reply.status, 200, "read issue page"); + assert!(!reply.body.contains("Pin issue"), "read-only has no pin"); } diff --git a/crates/forge-web/src/pages/labels_page.rs b/crates/forge-web/src/pages/labels_page.rs index 28d4063..8715fb8 100644 --- a/crates/forge-web/src/pages/labels_page.rs +++ b/crates/forge-web/src/pages/labels_page.rs @@ -423,51 +423,15 @@ mod tests { .len() } + /// One repo, run in order because the label count only grows. The button shows to triage + /// holders while there are no labels. A read-only viewer and a bad CSRF token add nothing. A + /// triage holder adds the defaults once, and a repeated submit adds nothing. #[tokio::test] - async fn triage_adds_defaults_once_and_repeat_adds_nothing() { + async fn defaults_button_and_adding_follow_the_rules() { let site = site().await; let url = "/tahinli/forge/labels/defaults"; - let (status, _) = send(&site, "POST", url, Some(&site.carol), CSRF).await; - assert_eq!(status, 303); - assert_eq!(label_count(&site).await, 9); - let (status, _) = send(&site, "POST", url, Some(&site.carol), CSRF).await; - assert_eq!(status, 303); - assert_eq!(label_count(&site).await, 9); - } - #[tokio::test] - async fn read_only_viewer_cannot_add_defaults() { - let site = site().await; - let (status, _) = send( - &site, - "POST", - "/tahinli/forge/labels/defaults", - Some(&site.bob), - CSRF, - ) - .await; - assert_eq!(status, 403); - assert_eq!(label_count(&site).await, 0); - } - - #[tokio::test] - async fn defaults_need_a_valid_csrf_token() { - let site = site().await; - let (status, _) = send( - &site, - "POST", - "/tahinli/forge/labels/defaults", - Some(&site.carol), - "wrong", - ) - .await; - assert_ne!(status, 303); - assert_eq!(label_count(&site).await, 0); - } - - #[tokio::test] - async fn button_shows_only_for_triage_when_no_labels() { - let site = site().await; + // No labels yet: triage sees the button, read-only does not. let (status, body) = send( &site, "GET", @@ -476,11 +440,30 @@ mod tests { CSRF, ) .await; - assert_eq!(status, 200); - assert!(body.contains("/tahinli/forge/labels/defaults")); + assert_eq!(status, 200, "triage labels page"); + assert!(body.contains(url), "triage sees the defaults button"); let (status, body) = send(&site, "GET", "/tahinli/forge/labels", Some(&site.bob), CSRF).await; - assert_eq!(status, 200); - assert!(!body.contains("/labels/defaults")); + assert_eq!(status, 200, "read-only labels page"); + assert!( + !body.contains("/labels/defaults"), + "read-only has no button" + ); + + // A read-only viewer is refused; a bad CSRF token is refused. Neither adds labels. + let (status, _) = send(&site, "POST", url, Some(&site.bob), CSRF).await; + assert_eq!(status, 403, "read-only add"); + assert_eq!(label_count(&site).await, 0, "read-only add stored nothing"); + let (status, _) = send(&site, "POST", url, Some(&site.carol), "wrong").await; + assert_ne!(status, 303, "bad csrf"); + assert_eq!(label_count(&site).await, 0, "bad csrf stored nothing"); + + // Triage adds the defaults once; a repeat adds nothing. + let (status, _) = send(&site, "POST", url, Some(&site.carol), CSRF).await; + assert_eq!(status, 303, "first add"); + assert_eq!(label_count(&site).await, 9, "defaults added"); + let (status, _) = send(&site, "POST", url, Some(&site.carol), CSRF).await; + assert_eq!(status, 303, "repeat add"); + assert_eq!(label_count(&site).await, 9, "repeat added nothing"); } } diff --git a/crates/forge-web/src/pages/login.rs b/crates/forge-web/src/pages/login.rs index 0dc9f7a..e748522 100644 --- a/crates/forge-web/src/pages/login.rs +++ b/crates/forge-web/src/pages/login.rs @@ -493,27 +493,96 @@ mod tests { tempfile::tempdir().expect("tempdir") } + /// Password-step throttles on one app. The throttle counts per user and per address, so each + /// scenario uses its own address and username and cannot reach another scenario's limit. #[tokio::test] - async fn eleventh_attempt_for_a_user_is_throttled_even_with_the_right_password() { - let tmp = scratch("user-limit"); + async fn password_throttles_are_per_user_and_per_address() { + let tmp = scratch("password-throttles"); let (router, state) = app(tmp.path()).await; - with_user(&state, "tahinli").await; + for name in ["tahinli", "bob", "frank", "erin", "gus"] { + with_user(&state, name).await; + } + + // Ten wrong passwords lock the user, and the right password is then refused too. let from = peer(10); let token = login_page(&router, from).await; - for _ in 0..10 { let (status, body) = post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await; - assert_eq!(status, 200); - assert!(body.contains("invalid username or password")); + assert_eq!(status, 200, "user limit: wrong password"); + assert!( + body.contains("invalid username or password"), + "user limit: generic message" + ); } let (status, body) = post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; - assert_eq!(status, 429); - assert!(body.contains("Too many attempts. Try again later.")); - assert!(!body.contains("invalid username or password")); + assert_eq!(status, 429, "user limit: right password while locked"); + assert!( + body.contains("Too many attempts. Try again later."), + "user limit: message" + ); + assert!( + !body.contains("invalid username or password"), + "user limit: not the generic message" + ); + + // Another user from an address that is already failing still logs in. + let from = peer(11); + let token = login_page(&router, from).await; + for _ in 0..10 { + post_login(&router, from, (&token.0, &token.1), "frank", "wrong").await; + } + let (status, _) = post_login(&router, from, (&token.0, &token.1), "bob", PASSWORD).await; + assert_eq!(status, 303, "other user from the same address logs in"); + + // A successful login resets the user's counter: 9 failures, a success, 9 more, a success. + let from = peer(12); + let token = login_page(&router, from).await; + for _ in 0..9 { + post_login(&router, from, (&token.0, &token.1), "erin", "wrong").await; + } + let (status, _) = post_login(&router, from, (&token.0, &token.1), "erin", PASSWORD).await; + assert_eq!(status, 303, "reset: first success"); + for _ in 0..9 { + post_login(&router, from, (&token.0, &token.1), "erin", "wrong").await; + } + let (status, _) = post_login(&router, from, (&token.0, &token.1), "erin", PASSWORD).await; + assert_eq!(status, 303, "reset: second success after the counter reset"); + + // The address limit applies across usernames: 30 failures for ghosts, then a 31st is refused. + let from = peer(13); + let token = login_page(&router, from).await; + for i in 0..30 { + let name = format!("ghost{i}"); + let (status, _) = post_login(&router, from, (&token.0, &token.1), &name, "x").await; + assert_eq!(status, 200, "address limit: attempt {i}"); + } + let (status, body) = + post_login(&router, from, (&token.0, &token.1), "ghost-new", "x").await; + assert_eq!(status, 429, "address limit: 31st attempt"); + assert!( + body.contains("Too many attempts. Try again later."), + "address limit: message" + ); + + // Known and unknown users get the same generic answer. The body echoes the typed username, + // so only the status and the generic message are compared. + let from = peer(14); + let token = login_page(&router, from).await; + for name in ["gus", "nobody"] { + let (status, body) = + post_login(&router, from, (&token.0, &token.1), name, "wrong").await; + assert_eq!(status, 200, "uniform: {name}"); + assert!( + body.contains("invalid username or password"), + "uniform: generic message for {name}" + ); + } } + /// Audit rows for failed and successful logins, without the password. This needs an empty + /// audit log, so it runs on its own app. #[tokio::test] async fn failed_and_successful_logins_are_audited_without_the_password() { use forge_core::{AuditAction, AuditFilter}; @@ -572,79 +641,6 @@ mod tests { } } - #[tokio::test] - async fn other_users_from_the_same_ip_still_log_in() { - let tmp = scratch("other-user"); - let (router, state) = app(tmp.path()).await; - with_user(&state, "tahinli").await; - with_user(&state, "bob").await; - let from = peer(11); - let token = login_page(&router, from).await; - - for _ in 0..10 { - post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await; - } - let (status, _) = post_login(&router, from, (&token.0, &token.1), "bob", PASSWORD).await; - assert_eq!(status, 303); - } - - #[tokio::test] - async fn successful_login_resets_the_user_counter() { - let tmp = scratch("reset"); - let (router, state) = app(tmp.path()).await; - with_user(&state, "tahinli").await; - let from = peer(12); - let token = login_page(&router, from).await; - - for _ in 0..9 { - post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await; - } - let (status, _) = - post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; - assert_eq!(status, 303); - for _ in 0..9 { - post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await; - } - let (status, _) = - post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; - assert_eq!(status, 303); - } - - #[tokio::test] - async fn ip_limit_applies_across_usernames() { - let tmp = scratch("ip-limit"); - let (router, _state) = app(tmp.path()).await; - let from = peer(13); - let token = login_page(&router, from).await; - - for i in 0..30 { - let name = format!("ghost{i}"); - let (status, _) = post_login(&router, from, (&token.0, &token.1), &name, "x").await; - assert_eq!(status, 200); - } - let (status, body) = - post_login(&router, from, (&token.0, &token.1), "ghost-new", "x").await; - assert_eq!(status, 429); - assert!(body.contains("Too many attempts. Try again later.")); - } - - #[tokio::test] - async fn unknown_and_known_users_get_the_same_response() { - let tmp = scratch("uniform"); - let (router, state) = app(tmp.path()).await; - with_user(&state, "tahinli").await; - let from = peer(14); - let token = login_page(&router, from).await; - - // The body echoes the typed username, so compare status and the generic message only. - for name in ["tahinli", "nobody"] { - let (status, body) = - post_login(&router, from, (&token.0, &token.1), name, "wrong").await; - assert_eq!(status, 200); - assert!(body.contains("invalid username or password")); - } - } - /// Reply parts the tests look at. struct Reply { status: u16, @@ -751,20 +747,33 @@ mod tests { format!("{pending}; {precsrf_cookie}") } + /// The two-factor login flow on one app, with one user per scenario: the pending cookie and no + /// session after the password step; a page with no pending cookie goes to login; a wrong code + /// fails, the right code logs in, and a replay of that code fails; a recovery code works once. #[tokio::test] - async fn totp_user_gets_a_pending_cookie_and_no_session() { - let tmp = scratch("totp-pending"); + async fn two_factor_login_steps_and_recovery_codes() { + let tmp = scratch("totp-flows"); let (router, state) = app(tmp.path()).await; - totp_user(&state, "tahinli").await; + + // Pending cookie, no session, and the second-factor page with the pending cookie. + totp_user(&state, "ada").await; let from = peer(20); let (cookie, precsrf) = login_page(&router, from).await; - - let reply = password_step(&router, from, (&cookie, &precsrf), "tahinli", PASSWORD).await; - assert_eq!(reply.status, 303); - assert_eq!(reply.location.as_deref(), Some("/login/2fa")); - assert!(pair(&reply, "__Host-forge_2fa").is_some()); - assert!(pair(&reply, "__Host-forge_session").is_none()); - + let reply = password_step(&router, from, (&cookie, &precsrf), "ada", PASSWORD).await; + assert_eq!(reply.status, 303, "pending: password step"); + assert_eq!( + reply.location.as_deref(), + Some("/login/2fa"), + "pending: redirect" + ); + assert!( + pair(&reply, "__Host-forge_2fa").is_some(), + "pending: cookie set" + ); + assert!( + pair(&reply, "__Host-forge_session").is_none(), + "pending: no session yet" + ); let page = send( &router, Request::builder() @@ -779,14 +788,10 @@ mod tests { .unwrap(), ) .await; - assert_eq!(page.status, 200); - assert!(page.body.contains("Two-factor check")); - } + assert_eq!(page.status, 200, "pending: second-factor page"); + assert!(page.body.contains("Two-factor check"), "pending: page text"); - #[tokio::test] - async fn two_factor_page_without_pending_cookie_goes_to_login() { - let tmp = scratch("totp-no-pending"); - let (router, _state) = app(tmp.path()).await; + // The second-factor page without a pending cookie goes back to login. let reply = send( &router, Request::builder() @@ -797,24 +802,26 @@ mod tests { .unwrap(), ) .await; - assert_eq!(reply.status, 303); - assert_eq!(reply.location.as_deref(), Some("/login")); - } + assert_eq!(reply.status, 303, "no pending: status"); + assert_eq!( + reply.location.as_deref(), + Some("/login"), + "no pending: redirect" + ); - #[tokio::test] - async fn wrong_code_fails_right_code_logs_in_and_replay_fails() { - let tmp = scratch("totp-flow"); - let (router, state) = app(tmp.path()).await; - let shared = totp_user(&state, "tahinli").await; + // A wrong code fails, the right code logs in, and the same code again is a replay. + let shared = totp_user(&state, "grace").await; let from = peer(22); let (cookie, precsrf) = login_page(&router, from).await; - - let step = password_step(&router, from, (&cookie, &precsrf), "tahinli", PASSWORD).await; + let step = password_step(&router, from, (&cookie, &precsrf), "grace", PASSWORD).await; let pending = both(&pair(&step, "__Host-forge_2fa").unwrap(), &cookie); let wrong = second_factor_step(&router, from, &pending, &precsrf, "000000").await; // The chance that 000000 is the live code is about 1 in a million per window. if wrong.status == 200 { - assert!(wrong.body.contains("That code is not right")); + assert!( + wrong.body.contains("That code is not right"), + "wrong code: message" + ); } let now_step = totp::step_for( @@ -825,59 +832,77 @@ mod tests { ); let code = totp::code_at(&shared, now_step); let ok = second_factor_step(&router, from, &pending, &precsrf, &code).await; - assert_eq!(ok.status, 303, "body {}", ok.body); - assert_eq!(ok.location.as_deref(), Some("/dash")); - assert!(pair(&ok, "__Host-forge_session").is_some()); - assert!(ok.cookies.iter().any(|c| c.starts_with("__Host-forge_2fa=") - && c.len() == "__Host-forge_2fa=".len())); + assert_eq!(ok.status, 303, "right code: body {}", ok.body); + assert_eq!( + ok.location.as_deref(), + Some("/dash"), + "right code: redirect" + ); + assert!( + pair(&ok, "__Host-forge_session").is_some(), + "right code: session" + ); + assert!( + ok.cookies.iter().any(|c| c.starts_with("__Host-forge_2fa=") + && c.len() == "__Host-forge_2fa=".len()), + "right code: pending cookie cleared" + ); - // The same code again, from a fresh password step, is a replay and must fail. let (cookie2, precsrf2) = login_page(&router, from).await; - let step2 = password_step(&router, from, (&cookie2, &precsrf2), "tahinli", PASSWORD).await; + let step2 = password_step(&router, from, (&cookie2, &precsrf2), "grace", PASSWORD).await; let pending2 = both(&pair(&step2, "__Host-forge_2fa").unwrap(), &cookie2); let replay = second_factor_step(&router, from, &pending2, &precsrf2, &code).await; - assert_eq!(replay.status, 200); - assert!(replay.body.contains("That code is not right")); - assert!(pair(&replay, "__Host-forge_session").is_none()); - } + assert_eq!(replay.status, 200, "replay: status"); + assert!( + replay.body.contains("That code is not right"), + "replay: message" + ); + assert!( + pair(&replay, "__Host-forge_session").is_none(), + "replay: no session" + ); - #[tokio::test] - async fn recovery_code_works_once() { - let tmp = scratch("totp-recovery"); - let (router, state) = app(tmp.path()).await; - totp_user(&state, "tahinli").await; + // A recovery code works once. + totp_user(&state, "linus").await; let from = peer(23); let (cookie, precsrf) = login_page(&router, from).await; - - let step = password_step(&router, from, (&cookie, &precsrf), "tahinli", PASSWORD).await; + let step = password_step(&router, from, (&cookie, &precsrf), "linus", PASSWORD).await; let pending = both(&pair(&step, "__Host-forge_2fa").unwrap(), &cookie); let first = second_factor_step(&router, from, &pending, &precsrf, "AAAA-bbbb").await; - assert_eq!(first.status, 303); - assert!(pair(&first, "__Host-forge_session").is_some()); + assert_eq!(first.status, 303, "recovery: first use"); + assert!( + pair(&first, "__Host-forge_session").is_some(), + "recovery: session" + ); let (cookie2, precsrf2) = login_page(&router, from).await; - let step2 = password_step(&router, from, (&cookie2, &precsrf2), "tahinli", PASSWORD).await; + let step2 = password_step(&router, from, (&cookie2, &precsrf2), "linus", PASSWORD).await; let pending2 = both(&pair(&step2, "__Host-forge_2fa").unwrap(), &cookie2); let second = second_factor_step(&router, from, &pending2, &precsrf2, "aaaabbbb").await; - assert_eq!(second.status, 200); - assert!(pair(&second, "__Host-forge_session").is_none()); + assert_eq!(second.status, 200, "recovery: second use"); + assert!( + pair(&second, "__Host-forge_session").is_none(), + "recovery: no session" + ); } + /// Two-factor expiry and the per-user limit on one app, one user per scenario. #[tokio::test] - async fn expired_pending_cookie_is_rejected() { - let tmp = scratch("totp-expired"); + async fn two_factor_expiry_and_per_user_limit() { + let tmp = scratch("totp-expiry-limit"); let (router, state) = app(tmp.path()).await; - let shared = totp_user(&state, "tahinli").await; + + // A correctly sealed pending cookie whose expiry is in the past is rejected, even with a + // valid code. + let shared = totp_user(&state, "margaret").await; let user = state .store - .user_by_username("tahinli") + .user_by_username("margaret") .await .unwrap() .unwrap(); let from = peer(24); let (cookie, precsrf) = login_page(&router, from).await; - - // A correctly sealed pending cookie whose expiry is in the past. let stale = secret::seal(&state.key, format!("1|{}|/", user.id).as_bytes()).unwrap(); let pending = format!("__Host-forge_2fa={stale}"); let code = totp::code_at( @@ -891,24 +916,26 @@ mod tests { ); let reply = second_factor_step(&router, from, &both(&pending, &cookie), &precsrf, &code).await; - assert_eq!(reply.status, 303); - assert_eq!(reply.location.as_deref(), Some("/login")); - assert!(pair(&reply, "__Host-forge_session").is_none()); - } + assert_eq!(reply.status, 303, "expired: status"); + assert_eq!( + reply.location.as_deref(), + Some("/login"), + "expired: redirect" + ); + assert!( + pair(&reply, "__Host-forge_session").is_none(), + "expired: no session" + ); - #[tokio::test] - async fn second_factor_attempts_are_throttled_per_user() { - let tmp = scratch("totp-throttle"); - let (router, state) = app(tmp.path()).await; - let shared = totp_user(&state, "tahinli").await; + // Wrong codes until the user limit; then even the right code is refused. + let shared = totp_user(&state, "ken").await; let from = peer(25); let (cookie, precsrf) = login_page(&router, from).await; - let step = password_step(&router, from, (&cookie, &precsrf), "tahinli", PASSWORD).await; + let step = password_step(&router, from, (&cookie, &precsrf), "ken", PASSWORD).await; let pending = both(&pair(&step, "__Host-forge_2fa").unwrap(), &cookie); - for _ in 0..TWO_FACTOR_USER_LIMIT { let reply = second_factor_step(&router, from, &pending, &precsrf, "111111").await; - assert_eq!(reply.status, 200); + assert_eq!(reply.status, 200, "limit: wrong code"); } let code = totp::code_at( &shared, @@ -920,7 +947,7 @@ mod tests { ), ); let blocked = second_factor_step(&router, from, &pending, &precsrf, &code).await; - assert_eq!(blocked.status, 429); - assert!(blocked.body.contains("Too many attempts")); + assert_eq!(blocked.status, 429, "limit: right code while locked"); + assert!(blocked.body.contains("Too many attempts"), "limit: message"); } }