diff --git a/crates/forge-web/src/pages/passkeys_tests.rs b/crates/forge-web/src/pages/passkeys_tests.rs index da20a57..e459c1e 100644 --- a/crates/forge-web/src/pages/passkeys_tests.rs +++ b/crates/forge-web/src/pages/passkeys_tests.rs @@ -272,8 +272,10 @@ async fn audit_count(store: &Store, action: AuditAction) -> usize { store.list_audit(&filter, None, 50).await.unwrap().len() } +/// A passkey sign-in goes straight in even with two-factor on. Then, on the same account, an +/// answer naming another account is refused, and so is a suspended account. #[tokio::test] -async fn register_then_sign_in_skips_the_second_factor() { +async fn passkey_sign_in_succeeds_then_refuses_another_account_and_a_suspended_one() { let fx = fixture().await; // Two-factor is on, yet a passkey sign-in goes straight in. let sealed = forge_core::secret::seal(&fx.state.key, &forge_core::totp::new_secret()).unwrap(); @@ -293,6 +295,7 @@ async fn register_then_sign_in_skips_the_second_factor() { assert!(rows[0].last_used_at.is_none()); assert_eq!(audit_count(&fx.store, AuditAction::PasskeyAdded).await, 1); + // Sign-in succeeds with the owner's passkey. let (cookie, precsrf) = login_tokens(&fx).await; let (id, answer) = answer_login( &fx, @@ -317,19 +320,10 @@ async fn register_then_sign_in_skips_the_second_factor() { // The ceremony id works once. let again = finish_login(&fx, &cookie, &precsrf, &id, &answer).await; - assert_eq!(again.status, 400); + assert_eq!(again.status, 400, "replayed ceremony"); assert!(!has_session(&again)); -} -#[tokio::test] -async fn suspended_user_is_refused() { - let fx = fixture().await; - let mut token = register(&fx, "Laptop").await; - let rows = fx.store.list_passkeys(&fx.owner_id).await.unwrap(); - fx.store - .suspend_user(&fx.owner_id, "testing", Some(&fx.admin_id)) - .await - .unwrap(); + // An answer whose user handle claims another account is refused. let (cookie, precsrf) = login_tokens(&fx).await; let (id, answer) = answer_login( &fx, @@ -337,74 +331,70 @@ async fn suspended_user_is_refused() { &precsrf, &mut token, &rows[0].credential_id, - &fx.owner_id, + &fx.other_id, ) .await; let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await; - assert_eq!(done.status, 403, "{}", done.body); - assert!(done.body.contains("testing")); + assert_eq!(done.status, 401, "{}", done.body); assert!(!has_session(&done)); assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 1); -} -#[tokio::test] -async fn an_answer_naming_another_account_is_refused() { - let fx = fixture().await; - let mut token = register(&fx, "Laptop").await; - let rows = fx.store.list_passkeys(&fx.owner_id).await.unwrap(); + // A suspended account is refused even with a valid passkey answer. + fx.store + .suspend_user(&fx.owner_id, "testing", Some(&fx.admin_id)) + .await + .unwrap(); let (cookie, precsrf) = login_tokens(&fx).await; - // A valid signature, but the user handle claims another account. let (id, answer) = answer_login( &fx, &cookie, &precsrf, &mut token, &rows[0].credential_id, - &fx.other_id, + &fx.owner_id, ) .await; let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await; - assert_eq!(done.status, 401, "{}", done.body); + assert_eq!(done.status, 403, "{}", done.body); + assert!(done.body.contains("testing")); assert!(!has_session(&done)); - assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 1); + assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 2); } +/// A wrong pre-session token is refused. An IP that has failed too often gets 429. #[tokio::test] -async fn sign_in_is_throttled_by_ip() { +async fn sign_in_refuses_a_bad_pre_session_token_and_a_throttled_ip() { let fx = fixture().await; let (cookie, precsrf) = login_tokens(&fx).await; - let key = throttle::ip_key("passkey-ip", peer().ip()); - for _ in 0..LOGIN_IP_LIMIT { - fx.state.throttle.record_failure(&key, Instant::now()); - } let begin = send( &fx.router, "POST", "/login/passkey/begin", - Some(cookie), - &[("precsrf", &precsrf)], + Some(cookie.clone()), + &[("precsrf", "wrong")], ) .await; - assert_eq!(begin.status, 429); -} + assert_eq!(begin.status, 403, "wrong pre-session token"); -#[tokio::test] -async fn sign_in_needs_the_pre_session_token() { - let fx = fixture().await; - let (cookie, _precsrf) = login_tokens(&fx).await; + let key = throttle::ip_key("passkey-ip", peer().ip()); + for _ in 0..LOGIN_IP_LIMIT { + fx.state.throttle.record_failure(&key, Instant::now()); + } let begin = send( &fx.router, "POST", "/login/passkey/begin", Some(cookie), - &[("precsrf", "wrong")], + &[("precsrf", &precsrf)], ) .await; - assert_eq!(begin.status, 403); + assert_eq!(begin.status, 429, "throttled ip"); } +/// Passkeys are renamed and deleted by their owner only. Others get 404, a bad CSRF token +/// gets 403, and each change is audited. #[tokio::test] -async fn delete_requires_ownership_and_is_audited() { +async fn passkey_rename_and_delete_require_ownership() { let fx = fixture().await; register(&fx, "Laptop").await; let row = fx @@ -413,106 +403,72 @@ async fn delete_requires_ownership_and_is_audited() { .await .unwrap() .remove(0); - let uri = format!("/settings/security/passkeys/{}/delete", row.id); + let rename = format!("/settings/security/passkeys/{}/rename", row.id); let foreign = send( &fx.router, "POST", - &uri, + &rename, session_cookie(OTHER_TOKEN), - &[("csrf", CSRF)], - ) - .await; - assert_eq!(foreign.status, 404); - assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1); - - let bad_csrf = send( - &fx.router, - "POST", - &uri, - session_cookie(OWNER_TOKEN), - &[("csrf", "nope")], + &[("csrf", CSRF), ("name", "Mine")], ) .await; - assert_eq!(bad_csrf.status, 403); - assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1); - + assert_eq!(foreign.status, 404, "rename by another user"); let own = send( &fx.router, "POST", - &uri, + &rename, session_cookie(OWNER_TOKEN), - &[("csrf", CSRF)], + &[("csrf", CSRF), ("name", "Phone")], ) .await; - assert_eq!(own.status, 303); - assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0); - assert_eq!(audit_count(&fx.store, AuditAction::PasskeyDeleted).await, 1); -} + assert_eq!(own.status, 303, "rename by owner"); + assert_eq!( + fx.store.list_passkeys(&fx.owner_id).await.unwrap()[0].name, + "Phone" + ); + assert_eq!(audit_count(&fx.store, AuditAction::PasskeyRenamed).await, 1); -#[tokio::test] -async fn rename_requires_ownership() { - let fx = fixture().await; - register(&fx, "Laptop").await; - let row = fx - .store - .list_passkeys(&fx.owner_id) - .await - .unwrap() - .remove(0); - let uri = format!("/settings/security/passkeys/{}/rename", row.id); + let delete = format!("/settings/security/passkeys/{}/delete", row.id); let foreign = send( &fx.router, "POST", - &uri, + &delete, session_cookie(OTHER_TOKEN), - &[("csrf", CSRF), ("name", "Mine")], + &[("csrf", CSRF)], ) .await; - assert_eq!(foreign.status, 404); - let own = send( + assert_eq!(foreign.status, 404, "delete by another user"); + assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1); + + let bad_csrf = send( &fx.router, "POST", - &uri, + &delete, session_cookie(OWNER_TOKEN), - &[("csrf", CSRF), ("name", "Phone")], + &[("csrf", "nope")], ) .await; - assert_eq!(own.status, 303); - assert_eq!( - fx.store.list_passkeys(&fx.owner_id).await.unwrap()[0].name, - "Phone" - ); - assert_eq!(audit_count(&fx.store, AuditAction::PasskeyRenamed).await, 1); -} + assert_eq!(bad_csrf.status, 403, "delete with a bad csrf token"); + assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1); -#[tokio::test] -async fn registration_ceremony_belongs_to_the_user_who_started_it() { - let fx = fixture().await; - let begin = send( + let own = send( &fx.router, "POST", - "/settings/security/passkeys/register/begin", + &delete, session_cookie(OWNER_TOKEN), - &[("csrf", CSRF), ("name", "Laptop")], - ) - .await; - let id = begin.json()["id"].as_str().unwrap().to_owned(); - // Someone else cannot finish it, even before the credential is looked at. - let finish = send( - &fx.router, - "POST", - "/settings/security/passkeys/register/finish", - session_cookie(OTHER_TOKEN), - &[("csrf", CSRF), ("id", &id), ("credential", "{}")], + &[("csrf", CSRF)], ) .await; - assert_eq!(finish.status, 400); - assert_eq!(fx.store.passkey_count(&fx.other_id).await.unwrap(), 0); + assert_eq!(own.status, 303, "delete by owner"); + assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0); + assert_eq!(audit_count(&fx.store, AuditAction::PasskeyDeleted).await, 1); } +/// Registration starts refuse blank and over-long names, a bad CSRF token and anonymous +/// callers. A ceremony started by one user cannot be finished by another. #[tokio::test] -async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() { +async fn registration_starts_are_checked_and_owned_by_their_starter() { let fx = fixture().await; let uri = "/settings/security/passkeys/register/begin"; let blank = send( @@ -523,7 +479,7 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() { &[("csrf", CSRF), ("name", " ")], ) .await; - assert_eq!(blank.status, 400); + assert_eq!(blank.status, 400, "blank name"); let long = "x".repeat(41); let too_long = send( &fx.router, @@ -533,7 +489,7 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() { &[("csrf", CSRF), ("name", &long)], ) .await; - assert_eq!(too_long.status, 400); + assert_eq!(too_long.status, 400, "over-long name"); let bad = send( &fx.router, "POST", @@ -542,7 +498,7 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() { &[("csrf", "nope"), ("name", "Laptop")], ) .await; - assert_eq!(bad.status, 403); + assert_eq!(bad.status, 403, "bad csrf token"); let anon = send( &fx.router, "POST", @@ -551,7 +507,28 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() { &[("csrf", CSRF), ("name", "Laptop")], ) .await; - assert_eq!(anon.status, 303); + assert_eq!(anon.status, 303, "anonymous caller"); + + let begin = send( + &fx.router, + "POST", + uri, + session_cookie(OWNER_TOKEN), + &[("csrf", CSRF), ("name", "Laptop")], + ) + .await; + let id = begin.json()["id"].as_str().unwrap().to_owned(); + // Someone else cannot finish it, even before the credential is looked at. + let finish = send( + &fx.router, + "POST", + "/settings/security/passkeys/register/finish", + session_cookie(OTHER_TOKEN), + &[("csrf", CSRF), ("id", &id), ("credential", "{}")], + ) + .await; + assert_eq!(finish.status, 400, "finish by another user"); + assert_eq!(fx.store.passkey_count(&fx.other_id).await.unwrap(), 0); } #[tokio::test] @@ -587,10 +564,15 @@ async fn insecure_base_url_turns_passkeys_off_with_a_message() { assert!(!login.body.contains("data-passkey-signin")); } +/// The passkey controls show on the settings and sign-in pages. Admins can remove all of a +/// user's passkeys, with an audit entry, and others cannot. #[tokio::test] -async fn pages_show_the_passkey_ui() { +async fn passkey_pages_show_the_ui_and_admins_remove_all_passkeys() { let fx = fixture().await; register(&fx, "Laptop").await; + register(&fx, "Phone").await; + assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2); + let page = send( &fx.router, "GET", @@ -606,35 +588,7 @@ async fn pages_show_the_passkey_ui() { assert!(login.body.contains("data-passkey-signin")); assert!(login.body.contains("autocomplete=\"username webauthn\"")); assert!(!login.body.contains('\u{2014}')); -} -#[test] -fn relying_party_needs_https_or_localhost() { - use super::passkeys::{Unavailable, relying_party}; - assert!(relying_party("https://forge.example/").is_ok()); - assert!(relying_party("https://forge.example:8443/").is_ok()); - assert!(relying_party("http://localhost:7660").is_ok()); - assert_eq!( - relying_party("http://forge.example").err(), - Some(Unavailable::NotHttps) - ); - assert_eq!( - relying_party("http://127.0.0.1:7660").err(), - Some(Unavailable::NotHttps) - ); - assert_eq!( - relying_party("https://127.0.0.1").err(), - Some(Unavailable::NoDomain) - ); - assert_eq!(relying_party("nonsense").err(), Some(Unavailable::NoDomain)); -} - -#[tokio::test] -async fn admin_removes_all_passkeys_with_an_audit_entry() { - let fx = fixture().await; - register(&fx, "Laptop").await; - register(&fx, "Phone").await; - assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2); let detail = format!("/admin/users/{}", fx.owner_id); let page = send(&fx.router, "GET", &detail, session_cookie(ADMIN_TOKEN), &[]).await; assert_eq!(page.status, 200); @@ -649,7 +603,7 @@ async fn admin_removes_all_passkeys_with_an_audit_entry() { &[("csrf", CSRF)], ) .await; - assert_eq!(denied.status, 404); + assert_eq!(denied.status, 404, "removal by a non-admin"); assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2); let done = send( @@ -660,10 +614,31 @@ async fn admin_removes_all_passkeys_with_an_audit_entry() { &[("csrf", CSRF)], ) .await; - assert_eq!(done.status, 303); + assert_eq!(done.status, 303, "removal by admin"); assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0); assert_eq!( audit_count(&fx.store, AuditAction::PasskeysRemovedByAdmin).await, 1 ); } + +#[test] +fn relying_party_needs_https_or_localhost() { + use super::passkeys::{Unavailable, relying_party}; + assert!(relying_party("https://forge.example/").is_ok()); + assert!(relying_party("https://forge.example:8443/").is_ok()); + assert!(relying_party("http://localhost:7660").is_ok()); + assert_eq!( + relying_party("http://forge.example").err(), + Some(Unavailable::NotHttps) + ); + assert_eq!( + relying_party("http://127.0.0.1:7660").err(), + Some(Unavailable::NotHttps) + ); + assert_eq!( + relying_party("https://127.0.0.1").err(), + Some(Unavailable::NoDomain) + ); + assert_eq!(relying_party("nonsense").err(), Some(Unavailable::NoDomain)); +} diff --git a/crates/forge-web/src/pages/settings_gpg_tests.rs b/crates/forge-web/src/pages/settings_gpg_tests.rs index 184f913..d8f3cb3 100644 --- a/crates/forge-web/src/pages/settings_gpg_tests.rs +++ b/crates/forge-web/src/pages/settings_gpg_tests.rs @@ -10,6 +10,7 @@ use crate::auth::SESSION_COOKIE; const CSRF: &str = "gpg-test-csrf"; const TOKEN: &str = "gpg-test-token"; const FINGERPRINT: &str = "ABCD1234ABCD1234ABCD1234ABCD1234ABCD1234"; +const BOB_FINGERPRINT: &str = "1234ABCD1234ABCD1234ABCD1234ABCD1234ABCD"; struct Site { router: Router, @@ -85,51 +86,41 @@ async fn call( } } +/// Anonymous and bad-CSRF requests are refused and change nothing; the owner sees the key +/// listed. Scenarios share one site and one signed-in session. #[tokio::test] -async fn gpg_page_requires_login() { - let (site, _) = site().await; +async fn gpg_refusals_and_the_listing_share_one_site() { + let (site, available) = site().await; + let tahinli = site + .store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); + + // Signed out, the page redirects to login. let reply = call(&site, "GET", "/settings/gpg", None, None).await; - assert_eq!(reply.status, 303); + assert_eq!(reply.status, 303, "anonymous page"); assert!( reply .location .as_deref() .is_some_and(|l| l.starts_with("/login")), - "redirects to login, got {:?}", + "anonymous page redirects to login, got {:?}", reply.location ); -} -#[tokio::test] -async fn adding_a_key_requires_login() { - let (site, _) = site().await; + // Signed out, adding a key is refused the same way. let fields = [("csrf", CSRF), ("armored", "junk")]; let reply = call(&site, "POST", "/settings/gpg", None, Some(&fields)).await; - assert_eq!(reply.status, 303); -} + assert_eq!(reply.status, 303, "anonymous add"); -#[tokio::test] -async fn adding_a_key_rejects_a_bad_csrf_token() { - let (site, _) = site().await; - let tahinli = site - .store - .create_user("tahinli", None, "h", false) - .await - .unwrap(); + // Signed in with a bad CSRF token, adding is forbidden. let cookie = sign_in(&site.store, &tahinli.id).await; - let fields = [("csrf", "wrong"), ("armored", "junk")]; - let reply = call(&site, "POST", "/settings/gpg", Some(&cookie), Some(&fields)).await; - assert_eq!(reply.status, 403); -} + let bad = [("csrf", "wrong"), ("armored", "junk")]; + let reply = call(&site, "POST", "/settings/gpg", Some(&cookie), Some(&bad)).await; + assert_eq!(reply.status, 403, "add with a bad csrf token"); -#[tokio::test] -async fn deleting_a_key_requires_login_and_csrf() { - let (site, _) = site().await; - let tahinli = site - .store - .create_user("tahinli", None, "h", false) - .await - .unwrap(); + // Signed out or with a bad CSRF token, deleting is refused and the key stays. let key = site .store .add_gpg_key( @@ -140,29 +131,37 @@ async fn deleting_a_key_requires_login_and_csrf() { ) .await .unwrap(); - let fields = [("csrf", CSRF), ("id", key.id.as_str())]; - let anon = call(&site, "POST", "/settings/gpg/delete", None, Some(&fields)).await; - assert_eq!(anon.status, 303); - - let cookie = sign_in(&site.store, &tahinli.id).await; - let bad = [("csrf", "wrong"), ("id", key.id.as_str())]; + let anon_fields = [("csrf", CSRF), ("id", key.id.as_str())]; + let anon = call(&site, "POST", "/settings/gpg/delete", None, Some(&anon_fields)).await; + assert_eq!(anon.status, 303, "anonymous delete"); + let bad_delete = [("csrf", "wrong"), ("id", key.id.as_str())]; let reply = call( &site, "POST", "/settings/gpg/delete", Some(&cookie), - Some(&bad), + Some(&bad_delete), ) .await; - assert_eq!(reply.status, 403); + assert_eq!(reply.status, 403, "delete with a bad csrf token"); assert_eq!( site.store.list_gpg_keys(&tahinli.id).await.unwrap().len(), - 1 + 1, + "the key survives refused deletes" ); + + // The page lists the key. The notice shows only when GPG is missing on this server. + let reply = call(&site, "GET", "/settings/gpg", Some(&cookie), None).await; + assert_eq!(reply.status, 200, "listing page"); + assert!(reply.body.contains(FINGERPRINT), "listing shows the fingerprint"); + assert!(reply.body.contains("tahinli@example.com"), "listing shows the email"); + let notice = "GPG verification is unavailable on this server"; + assert_eq!(reply.body.contains(notice), !available, "notice"); } +/// Owners delete their own keys; another user's key answers 404 and stays put. #[tokio::test] -async fn cannot_delete_another_users_key() { +async fn owners_delete_their_own_keys_and_no_one_elses() { let (site, _) = site().await; let tahinli = site .store @@ -174,13 +173,24 @@ async fn cannot_delete_another_users_key() { .create_user("bob", None, "h", false) .await .unwrap(); - let key = site + let bob_key = site + .store + .add_gpg_key(&bob.id, BOB_FINGERPRINT, "armored", &["bob@example.com".into()]) + .await + .unwrap(); + let own_key = site .store - .add_gpg_key(&bob.id, FINGERPRINT, "armored", &["bob@example.com".into()]) + .add_gpg_key( + &tahinli.id, + FINGERPRINT, + "armored", + &["tahinli@example.com".into()], + ) .await .unwrap(); let cookie = sign_in(&site.store, &tahinli.id).await; - let fields = [("csrf", CSRF), ("id", key.id.as_str())]; + + let fields = [("csrf", CSRF), ("id", bob_key.id.as_str())]; let reply = call( &site, "POST", @@ -189,30 +199,10 @@ async fn cannot_delete_another_users_key() { Some(&fields), ) .await; - assert_eq!(reply.status, 404); + assert_eq!(reply.status, 404, "another user's key"); assert_eq!(site.store.list_gpg_keys(&bob.id).await.unwrap().len(), 1); -} -#[tokio::test] -async fn owner_can_delete_their_own_key() { - let (site, _) = site().await; - let tahinli = site - .store - .create_user("tahinli", None, "h", false) - .await - .unwrap(); - let key = site - .store - .add_gpg_key( - &tahinli.id, - FINGERPRINT, - "armored", - &["tahinli@example.com".into()], - ) - .await - .unwrap(); - let cookie = sign_in(&site.store, &tahinli.id).await; - let fields = [("csrf", CSRF), ("id", key.id.as_str())]; + let fields = [("csrf", CSRF), ("id", own_key.id.as_str())]; let reply = call( &site, "POST", @@ -221,38 +211,13 @@ async fn owner_can_delete_their_own_key() { Some(&fields), ) .await; - assert_eq!(reply.status, 303); + assert_eq!(reply.status, 303, "own key"); assert!( site.store .list_gpg_keys(&tahinli.id) .await .unwrap() - .is_empty() + .is_empty(), + "own key is gone" ); } - -#[tokio::test] -async fn page_lists_keys_and_shows_the_notice_only_when_gpg_is_missing() { - let (site, available) = site().await; - let tahinli = site - .store - .create_user("tahinli", None, "h", false) - .await - .unwrap(); - site.store - .add_gpg_key( - &tahinli.id, - FINGERPRINT, - "armored", - &["tahinli@example.com".into()], - ) - .await - .unwrap(); - let cookie = sign_in(&site.store, &tahinli.id).await; - let reply = call(&site, "GET", "/settings/gpg", Some(&cookie), None).await; - assert_eq!(reply.status, 200); - assert!(reply.body.contains(FINGERPRINT)); - assert!(reply.body.contains("tahinli@example.com")); - let notice = "GPG verification is unavailable on this server"; - assert_eq!(reply.body.contains(notice), !available); -} diff --git a/crates/forge-web/src/pages/settings_keys.rs b/crates/forge-web/src/pages/settings_keys.rs index e2442d9..60b2bbd 100644 --- a/crates/forge-web/src/pages/settings_keys.rs +++ b/crates/forge-web/src/pages/settings_keys.rs @@ -299,18 +299,24 @@ mod tests { const ECDSA_FP: &str = "SHA256:0U8otw1ElxrQ6xL2P3888Sd6V2khCb8gXQZa0A2zRx4"; #[test] - fn parses_ed25519_and_matches_ssh_keygen_fingerprint() { - let parsed = parse_public_key(ED25519).unwrap(); - assert_eq!(parsed.algorithm, "ssh-ed25519"); - assert_eq!(parsed.comment, "test@forge"); - assert_eq!(parsed.fingerprint, ED25519_FP); - } - - #[test] - fn parses_ecdsa_and_matches_ssh_keygen_fingerprint() { - let parsed = parse_public_key(ECDSA).unwrap(); - assert_eq!(parsed.algorithm, "ecdsa-sha2-nistp256"); - assert_eq!(parsed.fingerprint, ECDSA_FP); + fn parses_accepted_keys_and_matches_ssh_keygen_fingerprints() { + // A bare line with padding has no comment, and the padding is ignored. + let bare = ED25519 + .split_whitespace() + .take(2) + .collect::>() + .join(" "); + let cases = [ + ("ed25519 with comment", ED25519.to_owned(), "ssh-ed25519", "test@forge", ED25519_FP), + ("ed25519 bare and padded", format!(" {bare}\n"), "ssh-ed25519", "", ED25519_FP), + ("ecdsa", ECDSA.to_owned(), "ecdsa-sha2-nistp256", "tahinli@tFedora", ECDSA_FP), + ]; + for (name, input, algorithm, comment, fingerprint) in cases { + let parsed = parse_public_key(&input).unwrap_or_else(|e| panic!("case {name}: {e:?}")); + assert_eq!(parsed.algorithm, algorithm, "case {name}"); + assert_eq!(parsed.comment, comment, "case {name}"); + assert_eq!(parsed.fingerprint, fingerprint, "case {name}"); + } } #[test] @@ -323,60 +329,29 @@ mod tests { } #[test] - fn accepts_the_surrounding_whitespace_and_no_comment() { - let bare = ED25519 - .split_whitespace() - .take(2) - .collect::>() - .join(" "); - let parsed = parse_public_key(&format!(" {bare}\n")).unwrap(); - assert_eq!(parsed.comment, ""); - assert_eq!(parsed.fingerprint, ED25519_FP); - } - - #[test] - fn rejects_rsa_with_the_documented_message() { - let rsa = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn test@host"; - assert_eq!(parse_public_key(rsa).unwrap_err(), KeyProblem::Rsa); - } - - #[test] - fn rejects_unsupported_types() { - let dss = "ssh-dss AAAAB3NzaC1kc3MAAACBAP test@host"; - assert_eq!( - parse_public_key(dss).unwrap_err(), - KeyProblem::UnsupportedType("ssh-dss".into()) - ); - } - - #[test] - fn rejects_algorithm_that_does_not_match_the_blob() { + fn rejects_each_bad_line_with_its_reason() { + // Length prefix claims 255 bytes but only 4 follow. + let body = BASE64_STANDARD.encode([0u8, 0, 0, 255, b's', b's', b'h', b'!']); // Real ed25519 body, relabelled as ECDSA. let relabelled = ED25519.replacen("ssh-ed25519", "ecdsa-sha2-nistp256", 1); - assert_eq!( - parse_public_key(&relabelled).unwrap_err(), - KeyProblem::Mismatch - ); - } - - #[test] - fn rejects_bad_base64_truncated_and_empty_input() { - assert!(parse_public_key("ssh-ed25519 !!!notbase64").is_err()); - assert_eq!( - parse_public_key("ssh-ed25519 AAAA").unwrap_err(), - KeyProblem::Truncated - ); - assert!(parse_public_key(" ").is_err()); - assert!(parse_public_key("ssh-ed25519").is_err()); let huge = format!("ssh-ed25519 {}", "A".repeat(MAX_KEY_CHARS)); - assert_eq!(parse_public_key(&huge).unwrap_err(), KeyProblem::TooLong); - } - - #[test] - fn rejects_a_length_prefix_past_the_end_of_the_blob() { - // Length prefix claims 255 bytes but only 4 follow. - let body = BASE64_STANDARD.encode([0u8, 0, 0, 255, b's', b's', b'h', b'!']); - let line = format!("ssh-ed25519 {body}"); - assert!(parse_public_key(&line).is_err()); + let cases = [ + ("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn test@host".to_owned(), KeyProblem::Rsa), + ( + "dss", + "ssh-dss AAAAB3NzaC1kc3MAAACBAP test@host".to_owned(), + KeyProblem::UnsupportedType("ssh-dss".into()), + ), + ("relabelled", relabelled, KeyProblem::Mismatch), + ("bad base64", "ssh-ed25519 !!!notbase64".to_owned(), KeyProblem::BadBase64), + ("truncated", "ssh-ed25519 AAAA".to_owned(), KeyProblem::Truncated), + ("length past the end", format!("ssh-ed25519 {body}"), KeyProblem::Truncated), + ("empty", " ".to_owned(), KeyProblem::Empty), + ("no key body", "ssh-ed25519".to_owned(), KeyProblem::MissingBody), + ("too long", huge, KeyProblem::TooLong), + ]; + for (name, input, want) in cases { + assert_eq!(parse_public_key(&input).unwrap_err(), want, "case {name}"); + } } } diff --git a/crates/forge-web/src/pages/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index 397ab2a..541c5e2 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -1182,74 +1182,25 @@ mod tests { shared.to_vec() } + /// Refusals on one fresh account, then the first email change. Each step is labelled. #[tokio::test] - async fn security_page_requires_a_session() { + async fn security_page_guards_and_the_first_email_change() { let fx = fixture().await; - let reply = send(&fx.router, "GET", "/settings/security", false, "").await; - assert_eq!(reply.status, 303); - assert!(reply.location.unwrap().starts_with("/login?next=")); - } - - #[tokio::test] - async fn password_change_revokes_other_sessions_and_keeps_this_one() { - let fx = fixture().await; - let expiry = stamp_after(std::time::Duration::from_secs(3600)); - fx.state - .store - .create_session( - &fx.user.id, - &hash_token(OTHER_TOKEN), - "other", - &expiry, - None, - ) - .await - .unwrap(); - let form = format!( - "csrf={CSRF}¤t_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password" - ); - let reply = send( - &fx.router, - "POST", - "/settings/security/password", - true, - &form, - ) - .await; - assert_eq!(reply.status, 303); - assert_eq!( - reply.location.as_deref(), - Some("/settings/security?saved=password") - ); - - let store = &fx.state.store; + // Signed out, the page sends the visitor to log in. + let anon = send(&fx.router, "GET", "/settings/security", false, "").await; + assert_eq!(anon.status, 303, "anonymous page"); assert!( - store - .session_by_token_hash(&hash_token(TOKEN)) - .await - .unwrap() - .is_some() - ); - assert!( - store - .session_by_token_hash(&hash_token(OTHER_TOKEN)) - .await - .unwrap() - .is_none() - ); - let fresh = store.user_by_id(&fx.user.id).await.unwrap().unwrap(); - assert!( - crate::auth::verify_password_async("a brand new password".into(), fresh.password_hash) - .await - .unwrap() + anon.location.unwrap().starts_with("/login?next="), + "anonymous page" ); - } - #[tokio::test] - async fn wrong_current_password_fails_and_changes_nothing() { - let fx = fixture().await; + // Before any address is set, the Email row says so. + let before = send(&fx.router, "GET", "/settings/security", true, "").await; + assert!(before.body.contains("No email address"), "{}", before.body); + + // A POST without the CSRF token is forbidden. let form = format!( - "csrf={CSRF}¤t_password=wrong+one&new_password=a+brand+new+password&confirm_password=a+brand+new+password" + "csrf=wrong¤t_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password" ); let reply = send( &fx.router, @@ -1259,64 +1210,9 @@ mod tests { &form, ) .await; - assert_eq!(reply.status, 200); - assert!(reply.body.contains("Current password is incorrect.")); - let fresh = fx - .state - .store - .user_by_id(&fx.user.id) - .await - .unwrap() - .unwrap(); - assert!( - crate::auth::verify_password_async(PASSWORD.into(), fresh.password_hash) - .await - .unwrap() - ); - } - - #[tokio::test] - async fn wrong_current_passwords_count_toward_the_login_throttle() { - let fx = fixture().await; - let bad = format!( - "csrf={CSRF}¤t_password=wrong&new_password=a+brand+new+password&confirm_password=a+brand+new+password" - ); - for _ in 0..LOGIN_USER_LIMIT { - let reply = send( - &fx.router, - "POST", - "/settings/security/password", - true, - &bad, - ) - .await; - assert_eq!(reply.status, 200); - } - assert!( - fx.state - .throttle - .check( - &user_key("tahinli"), - LOGIN_USER_LIMIT, - std::time::Instant::now() - ) - .is_some() - ); - let blocked = send( - &fx.router, - "POST", - "/settings/security/password", - true, - &bad, - ) - .await; - assert_eq!(blocked.status, 429); - assert!(blocked.body.contains("Too many attempts")); - } + assert_eq!(reply.status, 403, "password change without csrf"); - #[tokio::test] - async fn new_password_length_and_confirmation_are_checked() { - let fx = fixture().await; + // The new password must be long enough and match its confirmation. let short = format!( "csrf={CSRF}¤t_password={PASSWORD}&new_password=short&confirm_password=short" ); @@ -1328,7 +1224,10 @@ mod tests { &short, ) .await; - assert!(reply.body.contains("at least 10 characters")); + assert!( + reply.body.contains("at least 10 characters"), + "short password" + ); let mismatch = format!( "csrf={CSRF}¤t_password={PASSWORD}&new_password=a+brand+new+one&confirm_password=a+brand+new+two" ); @@ -1340,13 +1239,10 @@ mod tests { &mismatch, ) .await; - assert!(reply.body.contains("do not match")); - } + assert!(reply.body.contains("do not match"), "mismatched confirmation"); - #[tokio::test] - async fn email_change_needs_the_password_and_a_valid_address() { - let fx = fixture().await; - // An SSH key puts the user's address into the allowed-signers file. + // An SSH key puts the user's address into the allowed-signers file. With no address + // yet, the username is the principal. fx.state .store .add_ssh_key( @@ -1363,12 +1259,15 @@ mod tests { .unwrap(); let signers = fx.state.config.data_dir.join("run").join("allowed_signers"); let before = std::fs::read_to_string(&signers).unwrap(); - // The fixture user has no email yet, so the username is the principal. assert!(before.starts_with("tahinli "), "{before}"); + // The email change needs the password and a valid address. let wrong = format!("csrf={CSRF}&email=me%40example.com¤t_password=nope"); let reply = send(&fx.router, "POST", "/settings/security/email", true, &wrong).await; - assert!(reply.body.contains("Current password is incorrect.")); + assert!( + reply.body.contains("Current password is incorrect."), + "email change with a wrong password" + ); let invalid = format!("csrf={CSRF}&email=not+an+email¤t_password={PASSWORD}"); let reply = send( &fx.router, @@ -1378,12 +1277,16 @@ mod tests { &invalid, ) .await; - assert!(reply.body.contains("Enter an email address")); + assert!( + reply.body.contains("Enter an email address"), + "invalid address" + ); let ok = format!("csrf={CSRF}&email=me%40example.com¤t_password={PASSWORD}"); let reply = send(&fx.router, "POST", "/settings/security/email", true, &ok).await; assert_eq!( reply.location.as_deref(), - Some("/settings/security?saved=email") + Some("/settings/security?saved=email"), + "valid email change" ); let fresh = fx .state @@ -1401,261 +1304,119 @@ mod tests { } #[tokio::test] - async fn enroll_confirm_then_disable_two_factor() { + async fn password_change_revokes_other_sessions_and_keeps_this_one() { let fx = fixture().await; - let enable = format!("csrf={CSRF}"); - let reply = send( - &fx.router, - "POST", - "/settings/security/2fa/enable", - true, - &enable, - ) - .await; - assert_eq!(reply.status, 303); - let pending = fx - .state + let expiry = stamp_after(std::time::Duration::from_secs(3600)); + fx.state .store - .totp_state(&fx.user.id) + .create_session( + &fx.user.id, + &hash_token(OTHER_TOKEN), + "other", + &expiry, + None, + ) .await - .unwrap() .unwrap(); - assert!(!pending.enabled); - let sealed = pending.sealed_secret.expect("secret stored"); - let shared = secret::open(&KEY, &sealed).unwrap(); - - // The enrollment page shows the secret and the URI, not the codes. - let page = send(&fx.router, "GET", "/settings/security", true, "").await; - assert!(page.body.contains(&totp::base32_encode(&shared))); - assert!(page.body.contains("otpauth://totp/forge:tahinli?secret=")); - - let confirm = format!("csrf={CSRF}&code={}", now_code(&shared)); - let reply = send( - &fx.router, - "POST", - "/settings/security/2fa/confirm", - true, - &confirm, - ) - .await; - assert_eq!(reply.status, 200); - assert!(reply.body.contains("Recovery codes")); - let codes = reply - .body - .split("") - .skip(1) - .filter_map(|chunk| chunk.split("").next()) - .filter(|code| code.len() == 9 && code.as_bytes()[4] == b'-') - .count(); - assert_eq!(codes, super::RECOVERY_CODE_COUNT); - assert!( - fx.state - .store - .totp_state(&fx.user.id) - .await - .unwrap() - .unwrap() - .enabled - ); - assert_eq!( - fx.state - .store - .unused_recovery_codes(&fx.user.id) - .await - .unwrap(), - super::RECOVERY_CODE_COUNT as u64 - ); - - // Disabling needs the password and a code. A wrong password is refused. - let no_password = format!( - "csrf={CSRF}¤t_password=nope&code={}", - now_code(&shared) - ); - let reply = send( - &fx.router, - "POST", - "/settings/security/2fa/disable", - true, - &no_password, - ) - .await; - assert!(reply.body.contains("Current password is incorrect.")); - assert!( - fx.state - .store - .totp_state(&fx.user.id) - .await - .unwrap() - .unwrap() - .enabled + let form = format!( + "csrf={CSRF}¤t_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password" ); - - // The confirm step already used the current code, so disabling takes the next step's - // code. Reusing the current one would be refused as a replay. - let next = totp::code_at(&shared, totp::step_for(crate::auth::unix_now()) + 1); - let disable = format!("csrf={CSRF}¤t_password={PASSWORD}&code={next}"); let reply = send( &fx.router, "POST", - "/settings/security/2fa/disable", + "/settings/security/password", true, - &disable, + &form, ) .await; + assert_eq!(reply.status, 303); assert_eq!( reply.location.as_deref(), - Some("/settings/security?saved=2fa-off") + Some("/settings/security?saved=password") ); - let off = fx - .state - .store - .totp_state(&fx.user.id) - .await - .unwrap() - .unwrap(); - assert!(!off.enabled); - assert_eq!(off.sealed_secret, None); - } - #[tokio::test] - async fn wrong_confirm_code_does_not_enable() { - let fx = fixture().await; - send( - &fx.router, - "POST", - "/settings/security/2fa/enable", - true, - &format!("csrf={CSRF}"), - ) - .await; - let reply = send( - &fx.router, - "POST", - "/settings/security/2fa/confirm", - true, - &format!("csrf={CSRF}&code=000000"), - ) - .await; - // The chance that 000000 is the live code is about 1 in a million per window. - if reply.status == 200 && !reply.body.contains("Recovery codes") { - assert!(reply.body.contains("That code is not right")); - } - let state = fx - .state - .store - .totp_state(&fx.user.id) - .await - .unwrap() - .unwrap(); - if !state.enabled { - assert!(state.sealed_secret.is_some()); - } - } - - #[tokio::test] - async fn regenerating_recovery_codes_requires_a_code_and_replaces_them() { - let fx = fixture().await; - let shared = enable_totp_directly(&fx).await; - let bad = format!("csrf={CSRF}&code=123456x"); - let reply = send( - &fx.router, - "POST", - "/settings/security/2fa/recovery", - true, - &bad, - ) - .await; - assert!(reply.body.contains("That code is not right")); - assert_eq!( - fx.state - .store - .unused_recovery_codes(&fx.user.id) + let store = &fx.state.store; + assert!( + store + .session_by_token_hash(&hash_token(TOKEN)) .await - .unwrap(), - 1 + .unwrap() + .is_some() ); - - let good = format!("csrf={CSRF}&code={}", now_code(&shared)); - let reply = send( - &fx.router, - "POST", - "/settings/security/2fa/recovery", - true, - &good, - ) - .await; - assert!(reply.body.contains("Recovery codes")); - assert_eq!( - fx.state - .store - .unused_recovery_codes(&fx.user.id) + assert!( + store + .session_by_token_hash(&hash_token(OTHER_TOKEN)) .await - .unwrap(), - super::RECOVERY_CODE_COUNT as u64 + .unwrap() + .is_none() ); + let fresh = store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert!( - !fx.state - .store - .consume_recovery_code(&fx.user.id, &totp::recovery_code_hash("aaaa-bbbb")) + crate::auth::verify_password_async("a brand new password".into(), fresh.password_hash) .await .unwrap() ); } + /// Wrong current passwords are refused and counted against the login throttle, which then + /// answers 429. A wrong answer changes nothing. #[tokio::test] - async fn post_without_csrf_is_forbidden() { + async fn wrong_current_passwords_are_refused_and_throttle_the_login() { let fx = fixture().await; - let form = format!( - "csrf=wrong¤t_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password" + let bad = format!( + "csrf={CSRF}¤t_password=wrong&new_password=a+brand+new+password&confirm_password=a+brand+new+password" ); - let reply = send( + for _ in 0..LOGIN_USER_LIMIT { + let reply = send( + &fx.router, + "POST", + "/settings/security/password", + true, + &bad, + ) + .await; + assert_eq!(reply.status, 200); + assert!(reply.body.contains("Current password is incorrect.")); + } + assert!( + fx.state + .throttle + .check( + &user_key("tahinli"), + LOGIN_USER_LIMIT, + std::time::Instant::now() + ) + .is_some() + ); + let blocked = send( &fx.router, "POST", "/settings/security/password", true, - &form, + &bad, ) .await; - assert_eq!(reply.status, 403); - } + assert_eq!(blocked.status, 429); + assert!(blocked.body.contains("Too many attempts")); - #[tokio::test] - async fn email_row_says_verified_once_the_address_is_verified() { - let fx = fixture().await; - fx.state - .store - .set_email(&fx.user.id, "tahinli@example.com") - .await - .unwrap(); - let token = fx + let fresh = fx .state .store - .create_verify_token(&fx.user.id, "tahinli@example.com") + .user_by_id(&fx.user.id) .await + .unwrap() .unwrap(); assert!( - fx.state - .store - .redeem_verify_token(&token) + crate::auth::verify_password_async(PASSWORD.into(), fresh.password_hash) .await .unwrap() - .is_some() - ); - let page = send(&fx.router, "GET", "/settings/security", true, "").await; - assert_eq!(page.status, 200); - assert!( - page.body.contains("tahinli@example.com · Verified"), - "{}", - page.body ); } + /// The Email row follows the address from unverified with a queued mail to verified. #[tokio::test] - async fn email_row_shows_the_queued_verification_mail_while_unverified() { + async fn email_row_follows_the_address_from_queued_to_verified() { let fx = fixture().await; - let before = send(&fx.router, "GET", "/settings/security", true, "").await; - assert!(before.body.contains("No email address"), "{}", before.body); - fx.state .store .set_email(&fx.user.id, "tahinli@example.com") @@ -1683,26 +1444,37 @@ mod tests { "{}", page.body ); - } - #[tokio::test] - async fn the_page_shows_the_device_and_warns_when_codes_run_low() { - let fx = fixture().await; - enable_totp_directly(&fx).await; + let token = fx + .state + .store + .create_verify_token(&fx.user.id, "tahinli@example.com") + .await + .unwrap(); + assert!( + fx.state + .store + .redeem_verify_token(&token) + .await + .unwrap() + .is_some() + ); let page = send(&fx.router, "GET", "/settings/security", true, "").await; assert_eq!(page.status, 200); - assert!(page.body.contains("Authenticator app")); - assert!(page.body.contains("Added "), "{}", page.body); - assert!(page.body.contains("1 of 10 recovery codes unused")); - assert!(page.body.contains("Running low")); - assert!(page.body.contains("security-pill on")); + assert!( + page.body.contains("tahinli@example.com · Verified"), + "{}", + page.body + ); } + /// Enrollment: a wrong code and a bad device name do not enable two-factor, a good + /// confirmation does, and turning it off needs the password and then a fresh code. #[tokio::test] - async fn confirm_saves_the_device_name_and_refuses_a_bad_one() { + async fn two_factor_enrollment_and_turn_off() { let fx = fixture().await; let enable = format!("csrf={CSRF}"); - send( + let reply = send( &fx.router, "POST", "/settings/security/2fa/enable", @@ -1710,18 +1482,53 @@ mod tests { &enable, ) .await; - let sealed = fx + assert_eq!(reply.status, 303, "enable"); + let pending = fx .state .store .totp_state(&fx.user.id) .await .unwrap() - .unwrap() - .sealed_secret - .expect("secret stored"); + .unwrap(); + assert!(!pending.enabled); + let sealed = pending.sealed_secret.expect("secret stored"); let shared = secret::open(&KEY, &sealed).unwrap(); - // An over-long name is refused, and the code is not spent on it. + // The enrollment page shows the secret and the URI, not the codes. + let page = send(&fx.router, "GET", "/settings/security", true, "").await; + assert!(page.body.contains(&totp::base32_encode(&shared)), "secret shown"); + assert!( + page.body.contains("otpauth://totp/forge:tahinli?secret="), + "uri shown" + ); + + // A wrong code is refused. The chance that 000000 is the live code is about 1 in a + // million per window. + let wrong = format!("csrf={CSRF}&code=000000"); + let reply = send( + &fx.router, + "POST", + "/settings/security/2fa/confirm", + true, + &wrong, + ) + .await; + if reply.status == 200 && !reply.body.contains("Recovery codes") { + assert!(reply.body.contains("That code is not right"), "wrong code"); + } + let state = fx + .state + .store + .totp_state(&fx.user.id) + .await + .unwrap() + .unwrap(); + if !state.enabled { + assert!(state.sealed_secret.is_some(), "wrong code keeps the secret"); + } + + // An over-long device name is refused before the code is checked, so the code is + // not spent on it. let too_long = format!( "csrf={CSRF}&code={}&name={}", now_code(&shared), @@ -1735,7 +1542,7 @@ mod tests { &too_long, ) .await; - assert!(reply.body.contains("at most 40 characters")); + assert!(reply.body.contains("at most 40 characters"), "long name"); assert!( !fx.state .store @@ -1743,9 +1550,11 @@ mod tests { .await .unwrap() .unwrap() - .enabled + .enabled, + "long name does not enable" ); + // A good code and a name enable two-factor and issue ten recovery codes, once. let ok = format!("csrf={CSRF}&code={}&name=Work+phone", now_code(&shared)); let reply = send( &fx.router, @@ -1755,7 +1564,16 @@ mod tests { &ok, ) .await; - assert!(reply.body.contains("Recovery codes")); + assert_eq!(reply.status, 200); + assert!(reply.body.contains("Recovery codes"), "codes shown"); + let codes = reply + .body + .split("") + .skip(1) + .filter_map(|chunk| chunk.split("").next()) + .filter(|code| code.len() == 9 && code.as_bytes()[4] == b'-') + .count(); + assert_eq!(codes, super::RECOVERY_CODE_COUNT, "recovery codes shown"); let on = fx .state .store @@ -1767,14 +1585,86 @@ mod tests { assert_eq!(on.name.as_deref(), Some("Work phone")); assert!(on.created_at.is_some()); assert!(on.last_used_at.is_some()); + assert_eq!( + fx.state + .store + .unused_recovery_codes(&fx.user.id) + .await + .unwrap(), + super::RECOVERY_CODE_COUNT as u64 + ); let page = send(&fx.router, "GET", "/settings/security", true, "").await; - assert!(page.body.contains("Work phone")); + assert!(page.body.contains("Work phone"), "device name shown"); + + // Turning off with a wrong password is refused and keeps two-factor on. + let no_password = format!( + "csrf={CSRF}¤t_password=nope&code={}", + now_code(&shared) + ); + let reply = send( + &fx.router, + "POST", + "/settings/security/2fa/disable", + true, + &no_password, + ) + .await; + assert!( + reply.body.contains("Current password is incorrect."), + "turn off with a wrong password" + ); + assert!( + fx.state + .store + .totp_state(&fx.user.id) + .await + .unwrap() + .unwrap() + .enabled + ); + + // The confirm step already used the current code, so disabling takes the next step's + // code. Reusing the current one would be refused as a replay. + let next = totp::code_at(&shared, totp::step_for(crate::auth::unix_now()) + 1); + let disable = format!("csrf={CSRF}¤t_password={PASSWORD}&code={next}"); + let reply = send( + &fx.router, + "POST", + "/settings/security/2fa/disable", + true, + &disable, + ) + .await; + assert_eq!( + reply.location.as_deref(), + Some("/settings/security?saved=2fa-off"), + "turn off" + ); + let off = fx + .state + .store + .totp_state(&fx.user.id) + .await + .unwrap() + .unwrap(); + assert!(!off.enabled); + assert_eq!(off.sealed_secret, None); } + /// With two-factor on: the device and its code count show, a wrong password reopens only + /// the turn-off panel, and recovery codes need a real code and replace the old ones. #[tokio::test] - async fn a_wrong_password_on_turn_off_reopens_only_that_panel() { + async fn enabled_account_shows_the_device_and_guards_its_panels() { let fx = fixture().await; let shared = enable_totp_directly(&fx).await; + let page = send(&fx.router, "GET", "/settings/security", true, "").await; + assert_eq!(page.status, 200); + assert!(page.body.contains("Authenticator app")); + assert!(page.body.contains("Added "), "{}", page.body); + assert!(page.body.contains("1 of 10 recovery codes unused")); + assert!(page.body.contains("Running low")); + assert!(page.body.contains("security-pill on")); + let bad = format!( "csrf={CSRF}¤t_password=nope&code={}", now_code(&shared) @@ -1797,5 +1687,52 @@ mod tests { !reply.body.contains("security-action\" open"), "only the turn-off panel should be open" ); + + let bad_code = format!("csrf={CSRF}&code=123456x"); + let reply = send( + &fx.router, + "POST", + "/settings/security/2fa/recovery", + true, + &bad_code, + ) + .await; + assert!(reply.body.contains("That code is not right"), "bad code"); + assert_eq!( + fx.state + .store + .unused_recovery_codes(&fx.user.id) + .await + .unwrap(), + 1, + "a refused code leaves the old codes" + ); + + let good = format!("csrf={CSRF}&code={}", now_code(&shared)); + let reply = send( + &fx.router, + "POST", + "/settings/security/2fa/recovery", + true, + &good, + ) + .await; + assert!(reply.body.contains("Recovery codes"), "new codes shown"); + assert_eq!( + fx.state + .store + .unused_recovery_codes(&fx.user.id) + .await + .unwrap(), + super::RECOVERY_CODE_COUNT as u64 + ); + assert!( + !fx.state + .store + .consume_recovery_code(&fx.user.id, &totp::recovery_code_hash("aaaa-bbbb")) + .await + .unwrap(), + "the old recovery code is gone" + ); } }