forge
Explore
Log in

Don't you dare go Hollow

Forge-web page tests share their fixtures and merge into tables

Browse files at this commit

a7d2b6cc6dfb23c5f301ae0c34b206c86925623aAhmet Kaan GümüşParent: 7cded14
  • test
    • forge-web page tests share their fixtures and merge into tables
Show full message
✅ test: forge-web page tests share their fixtures and merge into tables

Counts for the four files (tests before -> after):
- settings_security.rs: 15 -> 6
- passkeys_tests.rs: 13 -> 7
- settings_keys.rs: 9 -> 3
- settings_gpg_tests.rs: 7 -> 2

Scenarios that share a fixture run in an order that keeps each assertion valid, and the
throttle-sensitive scenarios keep their own fixture. Every assertion is kept, and the
rejection cases of the SSH key parser are checked against their exact KeyProblem.
crates/forge-web/src/pages/passkeys_tests.rsmodified+117 -142
@@ -272,8 +272,10 @@ async fn audit_count(store: &Store, action: AuditAction) -> usize {
272 store.list_audit(&filter, None, 50).await.unwrap().len()272 store.list_audit(&filter, None, 50).await.unwrap().len()
273 }273 }
274 274
275+/// A passkey sign-in goes straight in even with two-factor on. Then, on the same account, an
276+/// answer naming another account is refused, and so is a suspended account.
275 #[tokio::test]277 #[tokio::test]
276-async fn register_then_sign_in_skips_the_second_factor() {278+async fn passkey_sign_in_succeeds_then_refuses_another_account_and_a_suspended_one() {
277 let fx = fixture().await;279 let fx = fixture().await;
278 // Two-factor is on, yet a passkey sign-in goes straight in.280 // Two-factor is on, yet a passkey sign-in goes straight in.
279 let sealed = forge_core::secret::seal(&fx.state.key, &forge_core::totp::new_secret()).unwrap();281 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() {
293 assert!(rows[0].last_used_at.is_none());295 assert!(rows[0].last_used_at.is_none());
294 assert_eq!(audit_count(&fx.store, AuditAction::PasskeyAdded).await, 1);296 assert_eq!(audit_count(&fx.store, AuditAction::PasskeyAdded).await, 1);
295 297
298+ // Sign-in succeeds with the owner's passkey.
296 let (cookie, precsrf) = login_tokens(&fx).await;299 let (cookie, precsrf) = login_tokens(&fx).await;
297 let (id, answer) = answer_login(300 let (id, answer) = answer_login(
298 &fx,301 &fx,
@@ -317,19 +320,10 @@ async fn register_then_sign_in_skips_the_second_factor() {
317 320
318 // The ceremony id works once.321 // The ceremony id works once.
319 let again = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;322 let again = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;
320- assert_eq!(again.status, 400);323+ assert_eq!(again.status, 400, "replayed ceremony");
321 assert!(!has_session(&again));324 assert!(!has_session(&again));
322-}
323 325
324-#[tokio::test]326+ // An answer whose user handle claims another account is refused.
325-async fn suspended_user_is_refused() {
326- let fx = fixture().await;
327- let mut token = register(&fx, "Laptop").await;
328- let rows = fx.store.list_passkeys(&fx.owner_id).await.unwrap();
329- fx.store
330- .suspend_user(&fx.owner_id, "testing", Some(&fx.admin_id))
331- .await
332- .unwrap();
333 let (cookie, precsrf) = login_tokens(&fx).await;327 let (cookie, precsrf) = login_tokens(&fx).await;
334 let (id, answer) = answer_login(328 let (id, answer) = answer_login(
335 &fx,329 &fx,
@@ -337,74 +331,70 @@ async fn suspended_user_is_refused() {
337 &precsrf,331 &precsrf,
338 &mut token,332 &mut token,
339 &rows[0].credential_id,333 &rows[0].credential_id,
340- &fx.owner_id,334+ &fx.other_id,
341 )335 )
342 .await;336 .await;
343 let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;337 let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;
344- assert_eq!(done.status, 403, "{}", done.body);338+ assert_eq!(done.status, 401, "{}", done.body);
345- assert!(done.body.contains("testing"));
346 assert!(!has_session(&done));339 assert!(!has_session(&done));
347 assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 1);340 assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 1);
348-}
349 341
350-#[tokio::test]342+ // A suspended account is refused even with a valid passkey answer.
351-async fn an_answer_naming_another_account_is_refused() {343+ fx.store
352- let fx = fixture().await;344+ .suspend_user(&fx.owner_id, "testing", Some(&fx.admin_id))
353- let mut token = register(&fx, "Laptop").await;345+ .await
354- let rows = fx.store.list_passkeys(&fx.owner_id).await.unwrap();346+ .unwrap();
355 let (cookie, precsrf) = login_tokens(&fx).await;347 let (cookie, precsrf) = login_tokens(&fx).await;
356- // A valid signature, but the user handle claims another account.
357 let (id, answer) = answer_login(348 let (id, answer) = answer_login(
358 &fx,349 &fx,
359 &cookie,350 &cookie,
360 &precsrf,351 &precsrf,
361 &mut token,352 &mut token,
362 &rows[0].credential_id,353 &rows[0].credential_id,
363- &fx.other_id,354+ &fx.owner_id,
364 )355 )
365 .await;356 .await;
366 let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;357 let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;
367- assert_eq!(done.status, 401, "{}", done.body);358+ assert_eq!(done.status, 403, "{}", done.body);
359+ assert!(done.body.contains("testing"));
368 assert!(!has_session(&done));360 assert!(!has_session(&done));
369- assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 1);361+ assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 2);
370 }362 }
371 363
364+/// A wrong pre-session token is refused. An IP that has failed too often gets 429.
372 #[tokio::test]365 #[tokio::test]
373-async fn sign_in_is_throttled_by_ip() {366+async fn sign_in_refuses_a_bad_pre_session_token_and_a_throttled_ip() {
374 let fx = fixture().await;367 let fx = fixture().await;
375 let (cookie, precsrf) = login_tokens(&fx).await;368 let (cookie, precsrf) = login_tokens(&fx).await;
376- let key = throttle::ip_key("passkey-ip", peer().ip());
377- for _ in 0..LOGIN_IP_LIMIT {
378- fx.state.throttle.record_failure(&key, Instant::now());
379- }
380 let begin = send(369 let begin = send(
381 &fx.router,370 &fx.router,
382 "POST",371 "POST",
383 "/login/passkey/begin",372 "/login/passkey/begin",
384- Some(cookie),373+ Some(cookie.clone()),
385- &[("precsrf", &precsrf)],374+ &[("precsrf", "wrong")],
386 )375 )
387 .await;376 .await;
388- assert_eq!(begin.status, 429);377+ assert_eq!(begin.status, 403, "wrong pre-session token");
389-}
390 378
391-#[tokio::test]379+ let key = throttle::ip_key("passkey-ip", peer().ip());
392-async fn sign_in_needs_the_pre_session_token() {380+ for _ in 0..LOGIN_IP_LIMIT {
393- let fx = fixture().await;381+ fx.state.throttle.record_failure(&key, Instant::now());
394- let (cookie, _precsrf) = login_tokens(&fx).await;382+ }
395 let begin = send(383 let begin = send(
396 &fx.router,384 &fx.router,
397 "POST",385 "POST",
398 "/login/passkey/begin",386 "/login/passkey/begin",
399 Some(cookie),387 Some(cookie),
400- &[("precsrf", "wrong")],388+ &[("precsrf", &precsrf)],
401 )389 )
402 .await;390 .await;
403- assert_eq!(begin.status, 403);391+ assert_eq!(begin.status, 429, "throttled ip");
404 }392 }
405 393
394+/// Passkeys are renamed and deleted by their owner only. Others get 404, a bad CSRF token
395+/// gets 403, and each change is audited.
406 #[tokio::test]396 #[tokio::test]
407-async fn delete_requires_ownership_and_is_audited() {397+async fn passkey_rename_and_delete_require_ownership() {
408 let fx = fixture().await;398 let fx = fixture().await;
409 register(&fx, "Laptop").await;399 register(&fx, "Laptop").await;
410 let row = fx400 let row = fx
@@ -413,106 +403,72 @@ async fn delete_requires_ownership_and_is_audited() {
413 .await403 .await
414 .unwrap()404 .unwrap()
415 .remove(0);405 .remove(0);
416- let uri = format!("/settings/security/passkeys/{}/delete", row.id);
417 406
407+ let rename = format!("/settings/security/passkeys/{}/rename", row.id);
418 let foreign = send(408 let foreign = send(
419 &fx.router,409 &fx.router,
420 "POST",410 "POST",
421- &uri,411+ &rename,
422 session_cookie(OTHER_TOKEN),412 session_cookie(OTHER_TOKEN),
423- &[("csrf", CSRF)],413+ &[("csrf", CSRF), ("name", "Mine")],
424- )
425- .await;
426- assert_eq!(foreign.status, 404);
427- assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1);
428-
429- let bad_csrf = send(
430- &fx.router,
431- "POST",
432- &uri,
433- session_cookie(OWNER_TOKEN),
434- &[("csrf", "nope")],
435 )414 )
436 .await;415 .await;
437- assert_eq!(bad_csrf.status, 403);416+ assert_eq!(foreign.status, 404, "rename by another user");
438- assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1);
439-
440 let own = send(417 let own = send(
441 &fx.router,418 &fx.router,
442 "POST",419 "POST",
443- &uri,420+ &rename,
444 session_cookie(OWNER_TOKEN),421 session_cookie(OWNER_TOKEN),
445- &[("csrf", CSRF)],422+ &[("csrf", CSRF), ("name", "Phone")],
446 )423 )
447 .await;424 .await;
448- assert_eq!(own.status, 303);425+ assert_eq!(own.status, 303, "rename by owner");
449- assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0);426+ assert_eq!(
450- assert_eq!(audit_count(&fx.store, AuditAction::PasskeyDeleted).await, 1);427+ fx.store.list_passkeys(&fx.owner_id).await.unwrap()[0].name,
451-}428+ "Phone"
429+ );
430+ assert_eq!(audit_count(&fx.store, AuditAction::PasskeyRenamed).await, 1);
452 431
453-#[tokio::test]432+ let delete = format!("/settings/security/passkeys/{}/delete", row.id);
454-async fn rename_requires_ownership() {
455- let fx = fixture().await;
456- register(&fx, "Laptop").await;
457- let row = fx
458- .store
459- .list_passkeys(&fx.owner_id)
460- .await
461- .unwrap()
462- .remove(0);
463- let uri = format!("/settings/security/passkeys/{}/rename", row.id);
464 let foreign = send(433 let foreign = send(
465 &fx.router,434 &fx.router,
466 "POST",435 "POST",
467- &uri,436+ &delete,
468 session_cookie(OTHER_TOKEN),437 session_cookie(OTHER_TOKEN),
469- &[("csrf", CSRF), ("name", "Mine")],438+ &[("csrf", CSRF)],
470 )439 )
471 .await;440 .await;
472- assert_eq!(foreign.status, 404);441+ assert_eq!(foreign.status, 404, "delete by another user");
473- let own = send(442+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1);
443+
444+ let bad_csrf = send(
474 &fx.router,445 &fx.router,
475 "POST",446 "POST",
476- &uri,447+ &delete,
477 session_cookie(OWNER_TOKEN),448 session_cookie(OWNER_TOKEN),
478- &[("csrf", CSRF), ("name", "Phone")],449+ &[("csrf", "nope")],
479 )450 )
480 .await;451 .await;
481- assert_eq!(own.status, 303);452+ assert_eq!(bad_csrf.status, 403, "delete with a bad csrf token");
482- assert_eq!(453+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1);
483- fx.store.list_passkeys(&fx.owner_id).await.unwrap()[0].name,
484- "Phone"
485- );
486- assert_eq!(audit_count(&fx.store, AuditAction::PasskeyRenamed).await, 1);
487-}
488 454
489-#[tokio::test]455+ let own = send(
490-async fn registration_ceremony_belongs_to_the_user_who_started_it() {
491- let fx = fixture().await;
492- let begin = send(
493 &fx.router,456 &fx.router,
494 "POST",457 "POST",
495- "/settings/security/passkeys/register/begin",458+ &delete,
496 session_cookie(OWNER_TOKEN),459 session_cookie(OWNER_TOKEN),
497- &[("csrf", CSRF), ("name", "Laptop")],460+ &[("csrf", CSRF)],
498- )
499- .await;
500- let id = begin.json()["id"].as_str().unwrap().to_owned();
501- // Someone else cannot finish it, even before the credential is looked at.
502- let finish = send(
503- &fx.router,
504- "POST",
505- "/settings/security/passkeys/register/finish",
506- session_cookie(OTHER_TOKEN),
507- &[("csrf", CSRF), ("id", &id), ("credential", "{}")],
508 )461 )
509 .await;462 .await;
510- assert_eq!(finish.status, 400);463+ assert_eq!(own.status, 303, "delete by owner");
511- assert_eq!(fx.store.passkey_count(&fx.other_id).await.unwrap(), 0);464+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0);
465+ assert_eq!(audit_count(&fx.store, AuditAction::PasskeyDeleted).await, 1);
512 }466 }
513 467
468+/// Registration starts refuse blank and over-long names, a bad CSRF token and anonymous
469+/// callers. A ceremony started by one user cannot be finished by another.
514 #[tokio::test]470 #[tokio::test]
515-async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() {471+async fn registration_starts_are_checked_and_owned_by_their_starter() {
516 let fx = fixture().await;472 let fx = fixture().await;
517 let uri = "/settings/security/passkeys/register/begin";473 let uri = "/settings/security/passkeys/register/begin";
518 let blank = send(474 let blank = send(
@@ -523,7 +479,7 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() {
523 &[("csrf", CSRF), ("name", " ")],479 &[("csrf", CSRF), ("name", " ")],
524 )480 )
525 .await;481 .await;
526- assert_eq!(blank.status, 400);482+ assert_eq!(blank.status, 400, "blank name");
527 let long = "x".repeat(41);483 let long = "x".repeat(41);
528 let too_long = send(484 let too_long = send(
529 &fx.router,485 &fx.router,
@@ -533,7 +489,7 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() {
533 &[("csrf", CSRF), ("name", &long)],489 &[("csrf", CSRF), ("name", &long)],
534 )490 )
535 .await;491 .await;
536- assert_eq!(too_long.status, 400);492+ assert_eq!(too_long.status, 400, "over-long name");
537 let bad = send(493 let bad = send(
538 &fx.router,494 &fx.router,
539 "POST",495 "POST",
@@ -542,7 +498,7 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() {
542 &[("csrf", "nope"), ("name", "Laptop")],498 &[("csrf", "nope"), ("name", "Laptop")],
543 )499 )
544 .await;500 .await;
545- assert_eq!(bad.status, 403);501+ assert_eq!(bad.status, 403, "bad csrf token");
546 let anon = send(502 let anon = send(
547 &fx.router,503 &fx.router,
548 "POST",504 "POST",
@@ -551,7 +507,28 @@ async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() {
551 &[("csrf", CSRF), ("name", "Laptop")],507 &[("csrf", CSRF), ("name", "Laptop")],
552 )508 )
553 .await;509 .await;
554- assert_eq!(anon.status, 303);510+ assert_eq!(anon.status, 303, "anonymous caller");
511+
512+ let begin = send(
513+ &fx.router,
514+ "POST",
515+ uri,
516+ session_cookie(OWNER_TOKEN),
517+ &[("csrf", CSRF), ("name", "Laptop")],
518+ )
519+ .await;
520+ let id = begin.json()["id"].as_str().unwrap().to_owned();
521+ // Someone else cannot finish it, even before the credential is looked at.
522+ let finish = send(
523+ &fx.router,
524+ "POST",
525+ "/settings/security/passkeys/register/finish",
526+ session_cookie(OTHER_TOKEN),
527+ &[("csrf", CSRF), ("id", &id), ("credential", "{}")],
528+ )
529+ .await;
530+ assert_eq!(finish.status, 400, "finish by another user");
531+ assert_eq!(fx.store.passkey_count(&fx.other_id).await.unwrap(), 0);
555 }532 }
556 533
557 #[tokio::test]534 #[tokio::test]
@@ -587,10 +564,15 @@ async fn insecure_base_url_turns_passkeys_off_with_a_message() {
587 assert!(!login.body.contains("data-passkey-signin"));564 assert!(!login.body.contains("data-passkey-signin"));
588 }565 }
589 566
567+/// The passkey controls show on the settings and sign-in pages. Admins can remove all of a
568+/// user's passkeys, with an audit entry, and others cannot.
590 #[tokio::test]569 #[tokio::test]
591-async fn pages_show_the_passkey_ui() {570+async fn passkey_pages_show_the_ui_and_admins_remove_all_passkeys() {
592 let fx = fixture().await;571 let fx = fixture().await;
593 register(&fx, "Laptop").await;572 register(&fx, "Laptop").await;
573+ register(&fx, "Phone").await;
574+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2);
575+
594 let page = send(576 let page = send(
595 &fx.router,577 &fx.router,
596 "GET",578 "GET",
@@ -606,35 +588,7 @@ async fn pages_show_the_passkey_ui() {
606 assert!(login.body.contains("data-passkey-signin"));588 assert!(login.body.contains("data-passkey-signin"));
607 assert!(login.body.contains("autocomplete=\"username webauthn\""));589 assert!(login.body.contains("autocomplete=\"username webauthn\""));
608 assert!(!login.body.contains('\u{2014}'));590 assert!(!login.body.contains('\u{2014}'));
609-}
610 591
611-#[test]
612-fn relying_party_needs_https_or_localhost() {
613- use super::passkeys::{Unavailable, relying_party};
614- assert!(relying_party("https://forge.example/").is_ok());
615- assert!(relying_party("https://forge.example:8443/").is_ok());
616- assert!(relying_party("http://localhost:7660").is_ok());
617- assert_eq!(
618- relying_party("http://forge.example").err(),
619- Some(Unavailable::NotHttps)
620- );
621- assert_eq!(
622- relying_party("http://127.0.0.1:7660").err(),
623- Some(Unavailable::NotHttps)
624- );
625- assert_eq!(
626- relying_party("https://127.0.0.1").err(),
627- Some(Unavailable::NoDomain)
628- );
629- assert_eq!(relying_party("nonsense").err(), Some(Unavailable::NoDomain));
630-}
631-
632-#[tokio::test]
633-async fn admin_removes_all_passkeys_with_an_audit_entry() {
634- let fx = fixture().await;
635- register(&fx, "Laptop").await;
636- register(&fx, "Phone").await;
637- assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2);
638 let detail = format!("/admin/users/{}", fx.owner_id);592 let detail = format!("/admin/users/{}", fx.owner_id);
639 let page = send(&fx.router, "GET", &detail, session_cookie(ADMIN_TOKEN), &[]).await;593 let page = send(&fx.router, "GET", &detail, session_cookie(ADMIN_TOKEN), &[]).await;
640 assert_eq!(page.status, 200);594 assert_eq!(page.status, 200);
@@ -649,7 +603,7 @@ async fn admin_removes_all_passkeys_with_an_audit_entry() {
649 &[("csrf", CSRF)],603 &[("csrf", CSRF)],
650 )604 )
651 .await;605 .await;
652- assert_eq!(denied.status, 404);606+ assert_eq!(denied.status, 404, "removal by a non-admin");
653 assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2);607 assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2);
654 608
655 let done = send(609 let done = send(
@@ -660,10 +614,31 @@ async fn admin_removes_all_passkeys_with_an_audit_entry() {
660 &[("csrf", CSRF)],614 &[("csrf", CSRF)],
661 )615 )
662 .await;616 .await;
663- assert_eq!(done.status, 303);617+ assert_eq!(done.status, 303, "removal by admin");
664 assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0);618 assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0);
665 assert_eq!(619 assert_eq!(
666 audit_count(&fx.store, AuditAction::PasskeysRemovedByAdmin).await,620 audit_count(&fx.store, AuditAction::PasskeysRemovedByAdmin).await,
667 1621 1
668 );622 );
669 }623 }
624+
625+#[test]
626+fn relying_party_needs_https_or_localhost() {
627+ use super::passkeys::{Unavailable, relying_party};
628+ assert!(relying_party("https://forge.example/").is_ok());
629+ assert!(relying_party("https://forge.example:8443/").is_ok());
630+ assert!(relying_party("http://localhost:7660").is_ok());
631+ assert_eq!(
632+ relying_party("http://forge.example").err(),
633+ Some(Unavailable::NotHttps)
634+ );
635+ assert_eq!(
636+ relying_party("http://127.0.0.1:7660").err(),
637+ Some(Unavailable::NotHttps)
638+ );
639+ assert_eq!(
640+ relying_party("https://127.0.0.1").err(),
641+ Some(Unavailable::NoDomain)
642+ );
643+ assert_eq!(relying_party("nonsense").err(), Some(Unavailable::NoDomain));
644+}
crates/forge-web/src/pages/settings_gpg_tests.rsmodified+58 -93
@@ -10,6 +10,7 @@ use crate::auth::SESSION_COOKIE;
10 const CSRF: &str = "gpg-test-csrf";10 const CSRF: &str = "gpg-test-csrf";
11 const TOKEN: &str = "gpg-test-token";11 const TOKEN: &str = "gpg-test-token";
12 const FINGERPRINT: &str = "ABCD1234ABCD1234ABCD1234ABCD1234ABCD1234";12 const FINGERPRINT: &str = "ABCD1234ABCD1234ABCD1234ABCD1234ABCD1234";
13+const BOB_FINGERPRINT: &str = "1234ABCD1234ABCD1234ABCD1234ABCD1234ABCD";
13 14
14 struct Site {15 struct Site {
15 router: Router,16 router: Router,
@@ -85,51 +86,41 @@ async fn call(
85 }86 }
86 }87 }
87 88
89+/// Anonymous and bad-CSRF requests are refused and change nothing; the owner sees the key
90+/// listed. Scenarios share one site and one signed-in session.
88 #[tokio::test]91 #[tokio::test]
89-async fn gpg_page_requires_login() {92+async fn gpg_refusals_and_the_listing_share_one_site() {
90- let (site, _) = site().await;93+ let (site, available) = site().await;
94+ let tahinli = site
95+ .store
96+ .create_user("tahinli", None, "h", false)
97+ .await
98+ .unwrap();
99+
100+ // Signed out, the page redirects to login.
91 let reply = call(&site, "GET", "/settings/gpg", None, None).await;101 let reply = call(&site, "GET", "/settings/gpg", None, None).await;
92- assert_eq!(reply.status, 303);102+ assert_eq!(reply.status, 303, "anonymous page");
93 assert!(103 assert!(
94 reply104 reply
95 .location105 .location
96 .as_deref()106 .as_deref()
97 .is_some_and(|l| l.starts_with("/login")),107 .is_some_and(|l| l.starts_with("/login")),
98- "redirects to login, got {:?}",108+ "anonymous page redirects to login, got {:?}",
99 reply.location109 reply.location
100 );110 );
101-}
102 111
103-#[tokio::test]112+ // Signed out, adding a key is refused the same way.
104-async fn adding_a_key_requires_login() {
105- let (site, _) = site().await;
106 let fields = [("csrf", CSRF), ("armored", "junk")];113 let fields = [("csrf", CSRF), ("armored", "junk")];
107 let reply = call(&site, "POST", "/settings/gpg", None, Some(&fields)).await;114 let reply = call(&site, "POST", "/settings/gpg", None, Some(&fields)).await;
108- assert_eq!(reply.status, 303);115+ assert_eq!(reply.status, 303, "anonymous add");
109-}
110 116
111-#[tokio::test]117+ // Signed in with a bad CSRF token, adding is forbidden.
112-async fn adding_a_key_rejects_a_bad_csrf_token() {
113- let (site, _) = site().await;
114- let tahinli = site
115- .store
116- .create_user("tahinli", None, "h", false)
117- .await
118- .unwrap();
119 let cookie = sign_in(&site.store, &tahinli.id).await;118 let cookie = sign_in(&site.store, &tahinli.id).await;
120- let fields = [("csrf", "wrong"), ("armored", "junk")];119+ let bad = [("csrf", "wrong"), ("armored", "junk")];
121- let reply = call(&site, "POST", "/settings/gpg", Some(&cookie), Some(&fields)).await;120+ let reply = call(&site, "POST", "/settings/gpg", Some(&cookie), Some(&bad)).await;
122- assert_eq!(reply.status, 403);121+ assert_eq!(reply.status, 403, "add with a bad csrf token");
123-}
124 122
125-#[tokio::test]123+ // Signed out or with a bad CSRF token, deleting is refused and the key stays.
126-async fn deleting_a_key_requires_login_and_csrf() {
127- let (site, _) = site().await;
128- let tahinli = site
129- .store
130- .create_user("tahinli", None, "h", false)
131- .await
132- .unwrap();
133 let key = site124 let key = site
134 .store125 .store
135 .add_gpg_key(126 .add_gpg_key(
@@ -140,29 +131,37 @@ async fn deleting_a_key_requires_login_and_csrf() {
140 )131 )
141 .await132 .await
142 .unwrap();133 .unwrap();
143- let fields = [("csrf", CSRF), ("id", key.id.as_str())];134+ let anon_fields = [("csrf", CSRF), ("id", key.id.as_str())];
144- let anon = call(&site, "POST", "/settings/gpg/delete", None, Some(&fields)).await;135+ let anon = call(&site, "POST", "/settings/gpg/delete", None, Some(&anon_fields)).await;
145- assert_eq!(anon.status, 303);136+ assert_eq!(anon.status, 303, "anonymous delete");
146-137+ let bad_delete = [("csrf", "wrong"), ("id", key.id.as_str())];
147- let cookie = sign_in(&site.store, &tahinli.id).await;
148- let bad = [("csrf", "wrong"), ("id", key.id.as_str())];
149 let reply = call(138 let reply = call(
150 &site,139 &site,
151 "POST",140 "POST",
152 "/settings/gpg/delete",141 "/settings/gpg/delete",
153 Some(&cookie),142 Some(&cookie),
154- Some(&bad),143+ Some(&bad_delete),
155 )144 )
156 .await;145 .await;
157- assert_eq!(reply.status, 403);146+ assert_eq!(reply.status, 403, "delete with a bad csrf token");
158 assert_eq!(147 assert_eq!(
159 site.store.list_gpg_keys(&tahinli.id).await.unwrap().len(),148 site.store.list_gpg_keys(&tahinli.id).await.unwrap().len(),
160- 1149+ 1,
150+ "the key survives refused deletes"
161 );151 );
152+
153+ // The page lists the key. The notice shows only when GPG is missing on this server.
154+ let reply = call(&site, "GET", "/settings/gpg", Some(&cookie), None).await;
155+ assert_eq!(reply.status, 200, "listing page");
156+ assert!(reply.body.contains(FINGERPRINT), "listing shows the fingerprint");
157+ assert!(reply.body.contains("tahinli@example.com"), "listing shows the email");
158+ let notice = "GPG verification is unavailable on this server";
159+ assert_eq!(reply.body.contains(notice), !available, "notice");
162 }160 }
163 161
162+/// Owners delete their own keys; another user's key answers 404 and stays put.
164 #[tokio::test]163 #[tokio::test]
165-async fn cannot_delete_another_users_key() {164+async fn owners_delete_their_own_keys_and_no_one_elses() {
166 let (site, _) = site().await;165 let (site, _) = site().await;
167 let tahinli = site166 let tahinli = site
168 .store167 .store
@@ -174,13 +173,24 @@ async fn cannot_delete_another_users_key() {
174 .create_user("bob", None, "h", false)173 .create_user("bob", None, "h", false)
175 .await174 .await
176 .unwrap();175 .unwrap();
177- let key = site176+ let bob_key = site
177+ .store
178+ .add_gpg_key(&bob.id, BOB_FINGERPRINT, "armored", &["bob@example.com".into()])
179+ .await
180+ .unwrap();
181+ let own_key = site
178 .store182 .store
179- .add_gpg_key(&bob.id, FINGERPRINT, "armored", &["bob@example.com".into()])183+ .add_gpg_key(
184+ &tahinli.id,
185+ FINGERPRINT,
186+ "armored",
187+ &["tahinli@example.com".into()],
188+ )
180 .await189 .await
181 .unwrap();190 .unwrap();
182 let cookie = sign_in(&site.store, &tahinli.id).await;191 let cookie = sign_in(&site.store, &tahinli.id).await;
183- let fields = [("csrf", CSRF), ("id", key.id.as_str())];192+
193+ let fields = [("csrf", CSRF), ("id", bob_key.id.as_str())];
184 let reply = call(194 let reply = call(
185 &site,195 &site,
186 "POST",196 "POST",
@@ -189,30 +199,10 @@ async fn cannot_delete_another_users_key() {
189 Some(&fields),199 Some(&fields),
190 )200 )
191 .await;201 .await;
192- assert_eq!(reply.status, 404);202+ assert_eq!(reply.status, 404, "another user's key");
193 assert_eq!(site.store.list_gpg_keys(&bob.id).await.unwrap().len(), 1);203 assert_eq!(site.store.list_gpg_keys(&bob.id).await.unwrap().len(), 1);
194-}
195 204
196-#[tokio::test]205+ let fields = [("csrf", CSRF), ("id", own_key.id.as_str())];
197-async fn owner_can_delete_their_own_key() {
198- let (site, _) = site().await;
199- let tahinli = site
200- .store
201- .create_user("tahinli", None, "h", false)
202- .await
203- .unwrap();
204- let key = site
205- .store
206- .add_gpg_key(
207- &tahinli.id,
208- FINGERPRINT,
209- "armored",
210- &["tahinli@example.com".into()],
211- )
212- .await
213- .unwrap();
214- let cookie = sign_in(&site.store, &tahinli.id).await;
215- let fields = [("csrf", CSRF), ("id", key.id.as_str())];
216 let reply = call(206 let reply = call(
217 &site,207 &site,
218 "POST",208 "POST",
@@ -221,38 +211,13 @@ async fn owner_can_delete_their_own_key() {
221 Some(&fields),211 Some(&fields),
222 )212 )
223 .await;213 .await;
224- assert_eq!(reply.status, 303);214+ assert_eq!(reply.status, 303, "own key");
225 assert!(215 assert!(
226 site.store216 site.store
227 .list_gpg_keys(&tahinli.id)217 .list_gpg_keys(&tahinli.id)
228 .await218 .await
229 .unwrap()219 .unwrap()
230- .is_empty()220+ .is_empty(),
221+ "own key is gone"
231 );222 );
232 }223 }
233-
234-#[tokio::test]
235-async fn page_lists_keys_and_shows_the_notice_only_when_gpg_is_missing() {
236- let (site, available) = site().await;
237- let tahinli = site
238- .store
239- .create_user("tahinli", None, "h", false)
240- .await
241- .unwrap();
242- site.store
243- .add_gpg_key(
244- &tahinli.id,
245- FINGERPRINT,
246- "armored",
247- &["tahinli@example.com".into()],
248- )
249- .await
250- .unwrap();
251- let cookie = sign_in(&site.store, &tahinli.id).await;
252- let reply = call(&site, "GET", "/settings/gpg", Some(&cookie), None).await;
253- assert_eq!(reply.status, 200);
254- assert!(reply.body.contains(FINGERPRINT));
255- assert!(reply.body.contains("tahinli@example.com"));
256- let notice = "GPG verification is unavailable on this server";
257- assert_eq!(reply.body.contains(notice), !available);
258-}
crates/forge-web/src/pages/settings_keys.rsmodified+39 -64
@@ -299,18 +299,24 @@ mod tests {
299 const ECDSA_FP: &str = "SHA256:0U8otw1ElxrQ6xL2P3888Sd6V2khCb8gXQZa0A2zRx4";299 const ECDSA_FP: &str = "SHA256:0U8otw1ElxrQ6xL2P3888Sd6V2khCb8gXQZa0A2zRx4";
300 300
301 #[test]301 #[test]
302- fn parses_ed25519_and_matches_ssh_keygen_fingerprint() {302+ fn parses_accepted_keys_and_matches_ssh_keygen_fingerprints() {
303- let parsed = parse_public_key(ED25519).unwrap();303+ // A bare line with padding has no comment, and the padding is ignored.
304- assert_eq!(parsed.algorithm, "ssh-ed25519");304+ let bare = ED25519
305- assert_eq!(parsed.comment, "test@forge");305+ .split_whitespace()
306- assert_eq!(parsed.fingerprint, ED25519_FP);306+ .take(2)
307- }307+ .collect::<Vec<_>>()
308-308+ .join(" ");
309- #[test]309+ let cases = [
310- fn parses_ecdsa_and_matches_ssh_keygen_fingerprint() {310+ ("ed25519 with comment", ED25519.to_owned(), "ssh-ed25519", "test@forge", ED25519_FP),
311- let parsed = parse_public_key(ECDSA).unwrap();311+ ("ed25519 bare and padded", format!(" {bare}\n"), "ssh-ed25519", "", ED25519_FP),
312- assert_eq!(parsed.algorithm, "ecdsa-sha2-nistp256");312+ ("ecdsa", ECDSA.to_owned(), "ecdsa-sha2-nistp256", "tahinli@tFedora", ECDSA_FP),
313- assert_eq!(parsed.fingerprint, ECDSA_FP);313+ ];
314+ for (name, input, algorithm, comment, fingerprint) in cases {
315+ let parsed = parse_public_key(&input).unwrap_or_else(|e| panic!("case {name}: {e:?}"));
316+ assert_eq!(parsed.algorithm, algorithm, "case {name}");
317+ assert_eq!(parsed.comment, comment, "case {name}");
318+ assert_eq!(parsed.fingerprint, fingerprint, "case {name}");
319+ }
314 }320 }
315 321
316 #[test]322 #[test]
@@ -323,60 +329,29 @@ mod tests {
323 }329 }
324 330
325 #[test]331 #[test]
326- fn accepts_the_surrounding_whitespace_and_no_comment() {332+ fn rejects_each_bad_line_with_its_reason() {
327- let bare = ED25519333+ // Length prefix claims 255 bytes but only 4 follow.
328- .split_whitespace()334+ let body = BASE64_STANDARD.encode([0u8, 0, 0, 255, b's', b's', b'h', b'!']);
329- .take(2)
330- .collect::<Vec<_>>()
331- .join(" ");
332- let parsed = parse_public_key(&format!(" {bare}\n")).unwrap();
333- assert_eq!(parsed.comment, "");
334- assert_eq!(parsed.fingerprint, ED25519_FP);
335- }
336-
337- #[test]
338- fn rejects_rsa_with_the_documented_message() {
339- let rsa = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn test@host";
340- assert_eq!(parse_public_key(rsa).unwrap_err(), KeyProblem::Rsa);
341- }
342-
343- #[test]
344- fn rejects_unsupported_types() {
345- let dss = "ssh-dss AAAAB3NzaC1kc3MAAACBAP test@host";
346- assert_eq!(
347- parse_public_key(dss).unwrap_err(),
348- KeyProblem::UnsupportedType("ssh-dss".into())
349- );
350- }
351-
352- #[test]
353- fn rejects_algorithm_that_does_not_match_the_blob() {
354 // Real ed25519 body, relabelled as ECDSA.335 // Real ed25519 body, relabelled as ECDSA.
355 let relabelled = ED25519.replacen("ssh-ed25519", "ecdsa-sha2-nistp256", 1);336 let relabelled = ED25519.replacen("ssh-ed25519", "ecdsa-sha2-nistp256", 1);
356- assert_eq!(
357- parse_public_key(&relabelled).unwrap_err(),
358- KeyProblem::Mismatch
359- );
360- }
361-
362- #[test]
363- fn rejects_bad_base64_truncated_and_empty_input() {
364- assert!(parse_public_key("ssh-ed25519 !!!notbase64").is_err());
365- assert_eq!(
366- parse_public_key("ssh-ed25519 AAAA").unwrap_err(),
367- KeyProblem::Truncated
368- );
369- assert!(parse_public_key(" ").is_err());
370- assert!(parse_public_key("ssh-ed25519").is_err());
371 let huge = format!("ssh-ed25519 {}", "A".repeat(MAX_KEY_CHARS));337 let huge = format!("ssh-ed25519 {}", "A".repeat(MAX_KEY_CHARS));
372- assert_eq!(parse_public_key(&huge).unwrap_err(), KeyProblem::TooLong);338+ let cases = [
373- }339+ ("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn test@host".to_owned(), KeyProblem::Rsa),
374-340+ (
375- #[test]341+ "dss",
376- fn rejects_a_length_prefix_past_the_end_of_the_blob() {342+ "ssh-dss AAAAB3NzaC1kc3MAAACBAP test@host".to_owned(),
377- // Length prefix claims 255 bytes but only 4 follow.343+ KeyProblem::UnsupportedType("ssh-dss".into()),
378- let body = BASE64_STANDARD.encode([0u8, 0, 0, 255, b's', b's', b'h', b'!']);344+ ),
379- let line = format!("ssh-ed25519 {body}");345+ ("relabelled", relabelled, KeyProblem::Mismatch),
380- assert!(parse_public_key(&line).is_err());346+ ("bad base64", "ssh-ed25519 !!!notbase64".to_owned(), KeyProblem::BadBase64),
347+ ("truncated", "ssh-ed25519 AAAA".to_owned(), KeyProblem::Truncated),
348+ ("length past the end", format!("ssh-ed25519 {body}"), KeyProblem::Truncated),
349+ ("empty", " ".to_owned(), KeyProblem::Empty),
350+ ("no key body", "ssh-ed25519".to_owned(), KeyProblem::MissingBody),
351+ ("too long", huge, KeyProblem::TooLong),
352+ ];
353+ for (name, input, want) in cases {
354+ assert_eq!(parse_public_key(&input).unwrap_err(), want, "case {name}");
355+ }
381 }356 }
382 }357 }
crates/forge-web/src/pages/settings_security.rsmodified+297 -360
@@ -1182,74 +1182,25 @@ mod tests {
1182 shared.to_vec()1182 shared.to_vec()
1183 }1183 }
1184 1184
1185+ /// Refusals on one fresh account, then the first email change. Each step is labelled.
1185 #[tokio::test]1186 #[tokio::test]
1186- async fn security_page_requires_a_session() {1187+ async fn security_page_guards_and_the_first_email_change() {
1187 let fx = fixture().await;1188 let fx = fixture().await;
1188- let reply = send(&fx.router, "GET", "/settings/security", false, "").await;1189+ // Signed out, the page sends the visitor to log in.
1189- assert_eq!(reply.status, 303);1190+ let anon = send(&fx.router, "GET", "/settings/security", false, "").await;
1190- assert!(reply.location.unwrap().starts_with("/login?next="));1191+ assert_eq!(anon.status, 303, "anonymous page");
1191- }
1192-
1193- #[tokio::test]
1194- async fn password_change_revokes_other_sessions_and_keeps_this_one() {
1195- let fx = fixture().await;
1196- let expiry = stamp_after(std::time::Duration::from_secs(3600));
1197- fx.state
1198- .store
1199- .create_session(
1200- &fx.user.id,
1201- &hash_token(OTHER_TOKEN),
1202- "other",
1203- &expiry,
1204- None,
1205- )
1206- .await
1207- .unwrap();
1208- let form = format!(
1209- "csrf={CSRF}&current_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1210- );
1211- let reply = send(
1212- &fx.router,
1213- "POST",
1214- "/settings/security/password",
1215- true,
1216- &form,
1217- )
1218- .await;
1219- assert_eq!(reply.status, 303);
1220- assert_eq!(
1221- reply.location.as_deref(),
1222- Some("/settings/security?saved=password")
1223- );
1224-
1225- let store = &fx.state.store;
1226 assert!(1192 assert!(
1227- store1193+ anon.location.unwrap().starts_with("/login?next="),
1228- .session_by_token_hash(&hash_token(TOKEN))1194+ "anonymous page"
1229- .await
1230- .unwrap()
1231- .is_some()
1232- );
1233- assert!(
1234- store
1235- .session_by_token_hash(&hash_token(OTHER_TOKEN))
1236- .await
1237- .unwrap()
1238- .is_none()
1239- );
1240- let fresh = store.user_by_id(&fx.user.id).await.unwrap().unwrap();
1241- assert!(
1242- crate::auth::verify_password_async("a brand new password".into(), fresh.password_hash)
1243- .await
1244- .unwrap()
1245 );1195 );
1246- }
1247 1196
1248- #[tokio::test]1197+ // Before any address is set, the Email row says so.
1249- async fn wrong_current_password_fails_and_changes_nothing() {1198+ let before = send(&fx.router, "GET", "/settings/security", true, "").await;
1250- let fx = fixture().await;1199+ assert!(before.body.contains("No email address"), "{}", before.body);
1200+
1201+ // A POST without the CSRF token is forbidden.
1251 let form = format!(1202 let form = format!(
1252- "csrf={CSRF}&current_password=wrong+one&new_password=a+brand+new+password&confirm_password=a+brand+new+password"1203+ "csrf=wrong&current_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1253 );1204 );
1254 let reply = send(1205 let reply = send(
1255 &fx.router,1206 &fx.router,
@@ -1259,64 +1210,9 @@ mod tests {
1259 &form,1210 &form,
1260 )1211 )
1261 .await;1212 .await;
1262- assert_eq!(reply.status, 200);1213+ assert_eq!(reply.status, 403, "password change without csrf");
1263- assert!(reply.body.contains("Current password is incorrect."));
1264- let fresh = fx
1265- .state
1266- .store
1267- .user_by_id(&fx.user.id)
1268- .await
1269- .unwrap()
1270- .unwrap();
1271- assert!(
1272- crate::auth::verify_password_async(PASSWORD.into(), fresh.password_hash)
1273- .await
1274- .unwrap()
1275- );
1276- }
1277-
1278- #[tokio::test]
1279- async fn wrong_current_passwords_count_toward_the_login_throttle() {
1280- let fx = fixture().await;
1281- let bad = format!(
1282- "csrf={CSRF}&current_password=wrong&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1283- );
1284- for _ in 0..LOGIN_USER_LIMIT {
1285- let reply = send(
1286- &fx.router,
1287- "POST",
1288- "/settings/security/password",
1289- true,
1290- &bad,
1291- )
1292- .await;
1293- assert_eq!(reply.status, 200);
1294- }
1295- assert!(
1296- fx.state
1297- .throttle
1298- .check(
1299- &user_key("tahinli"),
1300- LOGIN_USER_LIMIT,
1301- std::time::Instant::now()
1302- )
1303- .is_some()
1304- );
1305- let blocked = send(
1306- &fx.router,
1307- "POST",
1308- "/settings/security/password",
1309- true,
1310- &bad,
1311- )
1312- .await;
1313- assert_eq!(blocked.status, 429);
1314- assert!(blocked.body.contains("Too many attempts"));
1315- }
1316 1214
1317- #[tokio::test]1215+ // The new password must be long enough and match its confirmation.
1318- async fn new_password_length_and_confirmation_are_checked() {
1319- let fx = fixture().await;
1320 let short = format!(1216 let short = format!(
1321 "csrf={CSRF}&current_password={PASSWORD}&new_password=short&confirm_password=short"1217 "csrf={CSRF}&current_password={PASSWORD}&new_password=short&confirm_password=short"
1322 );1218 );
@@ -1328,7 +1224,10 @@ mod tests {
1328 &short,1224 &short,
1329 )1225 )
1330 .await;1226 .await;
1331- assert!(reply.body.contains("at least 10 characters"));1227+ assert!(
1228+ reply.body.contains("at least 10 characters"),
1229+ "short password"
1230+ );
1332 let mismatch = format!(1231 let mismatch = format!(
1333 "csrf={CSRF}&current_password={PASSWORD}&new_password=a+brand+new+one&confirm_password=a+brand+new+two"1232 "csrf={CSRF}&current_password={PASSWORD}&new_password=a+brand+new+one&confirm_password=a+brand+new+two"
1334 );1233 );
@@ -1340,13 +1239,10 @@ mod tests {
1340 &mismatch,1239 &mismatch,
1341 )1240 )
1342 .await;1241 .await;
1343- assert!(reply.body.contains("do not match"));1242+ assert!(reply.body.contains("do not match"), "mismatched confirmation");
1344- }
1345 1243
1346- #[tokio::test]1244+ // An SSH key puts the user's address into the allowed-signers file. With no address
1347- async fn email_change_needs_the_password_and_a_valid_address() {1245+ // yet, the username is the principal.
1348- let fx = fixture().await;
1349- // An SSH key puts the user's address into the allowed-signers file.
1350 fx.state1246 fx.state
1351 .store1247 .store
1352 .add_ssh_key(1248 .add_ssh_key(
@@ -1363,12 +1259,15 @@ mod tests {
1363 .unwrap();1259 .unwrap();
1364 let signers = fx.state.config.data_dir.join("run").join("allowed_signers");1260 let signers = fx.state.config.data_dir.join("run").join("allowed_signers");
1365 let before = std::fs::read_to_string(&signers).unwrap();1261 let before = std::fs::read_to_string(&signers).unwrap();
1366- // The fixture user has no email yet, so the username is the principal.
1367 assert!(before.starts_with("tahinli "), "{before}");1262 assert!(before.starts_with("tahinli "), "{before}");
1368 1263
1264+ // The email change needs the password and a valid address.
1369 let wrong = format!("csrf={CSRF}&email=me%40example.com&current_password=nope");1265 let wrong = format!("csrf={CSRF}&email=me%40example.com&current_password=nope");
1370 let reply = send(&fx.router, "POST", "/settings/security/email", true, &wrong).await;1266 let reply = send(&fx.router, "POST", "/settings/security/email", true, &wrong).await;
1371- assert!(reply.body.contains("Current password is incorrect."));1267+ assert!(
1268+ reply.body.contains("Current password is incorrect."),
1269+ "email change with a wrong password"
1270+ );
1372 let invalid = format!("csrf={CSRF}&email=not+an+email&current_password={PASSWORD}");1271 let invalid = format!("csrf={CSRF}&email=not+an+email&current_password={PASSWORD}");
1373 let reply = send(1272 let reply = send(
1374 &fx.router,1273 &fx.router,
@@ -1378,12 +1277,16 @@ mod tests {
1378 &invalid,1277 &invalid,
1379 )1278 )
1380 .await;1279 .await;
1381- assert!(reply.body.contains("Enter an email address"));1280+ assert!(
1281+ reply.body.contains("Enter an email address"),
1282+ "invalid address"
1283+ );
1382 let ok = format!("csrf={CSRF}&email=me%40example.com&current_password={PASSWORD}");1284 let ok = format!("csrf={CSRF}&email=me%40example.com&current_password={PASSWORD}");
1383 let reply = send(&fx.router, "POST", "/settings/security/email", true, &ok).await;1285 let reply = send(&fx.router, "POST", "/settings/security/email", true, &ok).await;
1384 assert_eq!(1286 assert_eq!(
1385 reply.location.as_deref(),1287 reply.location.as_deref(),
1386- Some("/settings/security?saved=email")1288+ Some("/settings/security?saved=email"),
1289+ "valid email change"
1387 );1290 );
1388 let fresh = fx1291 let fresh = fx
1389 .state1292 .state
@@ -1401,261 +1304,119 @@ mod tests {
1401 }1304 }
1402 1305
1403 #[tokio::test]1306 #[tokio::test]
1404- async fn enroll_confirm_then_disable_two_factor() {1307+ async fn password_change_revokes_other_sessions_and_keeps_this_one() {
1405 let fx = fixture().await;1308 let fx = fixture().await;
1406- let enable = format!("csrf={CSRF}");1309+ let expiry = stamp_after(std::time::Duration::from_secs(3600));
1407- let reply = send(1310+ fx.state
1408- &fx.router,
1409- "POST",
1410- "/settings/security/2fa/enable",
1411- true,
1412- &enable,
1413- )
1414- .await;
1415- assert_eq!(reply.status, 303);
1416- let pending = fx
1417- .state
1418 .store1311 .store
1419- .totp_state(&fx.user.id)1312+ .create_session(
1313+ &fx.user.id,
1314+ &hash_token(OTHER_TOKEN),
1315+ "other",
1316+ &expiry,
1317+ None,
1318+ )
1420 .await1319 .await
1421- .unwrap()
1422 .unwrap();1320 .unwrap();
1423- assert!(!pending.enabled);1321+ let form = format!(
1424- let sealed = pending.sealed_secret.expect("secret stored");1322+ "csrf={CSRF}&current_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1425- let shared = secret::open(&KEY, &sealed).unwrap();
1426-
1427- // The enrollment page shows the secret and the URI, not the codes.
1428- let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1429- assert!(page.body.contains(&totp::base32_encode(&shared)));
1430- assert!(page.body.contains("otpauth://totp/forge:tahinli?secret="));
1431-
1432- let confirm = format!("csrf={CSRF}&code={}", now_code(&shared));
1433- let reply = send(
1434- &fx.router,
1435- "POST",
1436- "/settings/security/2fa/confirm",
1437- true,
1438- &confirm,
1439- )
1440- .await;
1441- assert_eq!(reply.status, 200);
1442- assert!(reply.body.contains("Recovery codes"));
1443- let codes = reply
1444- .body
1445- .split("<code>")
1446- .skip(1)
1447- .filter_map(|chunk| chunk.split("</code>").next())
1448- .filter(|code| code.len() == 9 && code.as_bytes()[4] == b'-')
1449- .count();
1450- assert_eq!(codes, super::RECOVERY_CODE_COUNT);
1451- assert!(
1452- fx.state
1453- .store
1454- .totp_state(&fx.user.id)
1455- .await
1456- .unwrap()
1457- .unwrap()
1458- .enabled
1459- );
1460- assert_eq!(
1461- fx.state
1462- .store
1463- .unused_recovery_codes(&fx.user.id)
1464- .await
1465- .unwrap(),
1466- super::RECOVERY_CODE_COUNT as u64
1467- );
1468-
1469- // Disabling needs the password and a code. A wrong password is refused.
1470- let no_password = format!(
1471- "csrf={CSRF}&current_password=nope&code={}",
1472- now_code(&shared)
1473- );
1474- let reply = send(
1475- &fx.router,
1476- "POST",
1477- "/settings/security/2fa/disable",
1478- true,
1479- &no_password,
1480- )
1481- .await;
1482- assert!(reply.body.contains("Current password is incorrect."));
1483- assert!(
1484- fx.state
1485- .store
1486- .totp_state(&fx.user.id)
1487- .await
1488- .unwrap()
1489- .unwrap()
1490- .enabled
1491 );1323 );
1492-
1493- // The confirm step already used the current code, so disabling takes the next step's
1494- // code. Reusing the current one would be refused as a replay.
1495- let next = totp::code_at(&shared, totp::step_for(crate::auth::unix_now()) + 1);
1496- let disable = format!("csrf={CSRF}&current_password={PASSWORD}&code={next}");
1497 let reply = send(1324 let reply = send(
1498 &fx.router,1325 &fx.router,
1499 "POST",1326 "POST",
1500- "/settings/security/2fa/disable",1327+ "/settings/security/password",
1501 true,1328 true,
1502- &disable,1329+ &form,
1503 )1330 )
1504 .await;1331 .await;
1332+ assert_eq!(reply.status, 303);
1505 assert_eq!(1333 assert_eq!(
1506 reply.location.as_deref(),1334 reply.location.as_deref(),
1507- Some("/settings/security?saved=2fa-off")1335+ Some("/settings/security?saved=password")
1508 );1336 );
1509- let off = fx
1510- .state
1511- .store
1512- .totp_state(&fx.user.id)
1513- .await
1514- .unwrap()
1515- .unwrap();
1516- assert!(!off.enabled);
1517- assert_eq!(off.sealed_secret, None);
1518- }
1519 1337
1520- #[tokio::test]1338+ let store = &fx.state.store;
1521- async fn wrong_confirm_code_does_not_enable() {1339+ assert!(
1522- let fx = fixture().await;1340+ store
1523- send(1341+ .session_by_token_hash(&hash_token(TOKEN))
1524- &fx.router,
1525- "POST",
1526- "/settings/security/2fa/enable",
1527- true,
1528- &format!("csrf={CSRF}"),
1529- )
1530- .await;
1531- let reply = send(
1532- &fx.router,
1533- "POST",
1534- "/settings/security/2fa/confirm",
1535- true,
1536- &format!("csrf={CSRF}&code=000000"),
1537- )
1538- .await;
1539- // The chance that 000000 is the live code is about 1 in a million per window.
1540- if reply.status == 200 && !reply.body.contains("Recovery codes") {
1541- assert!(reply.body.contains("That code is not right"));
1542- }
1543- let state = fx
1544- .state
1545- .store
1546- .totp_state(&fx.user.id)
1547- .await
1548- .unwrap()
1549- .unwrap();
1550- if !state.enabled {
1551- assert!(state.sealed_secret.is_some());
1552- }
1553- }
1554-
1555- #[tokio::test]
1556- async fn regenerating_recovery_codes_requires_a_code_and_replaces_them() {
1557- let fx = fixture().await;
1558- let shared = enable_totp_directly(&fx).await;
1559- let bad = format!("csrf={CSRF}&code=123456x");
1560- let reply = send(
1561- &fx.router,
1562- "POST",
1563- "/settings/security/2fa/recovery",
1564- true,
1565- &bad,
1566- )
1567- .await;
1568- assert!(reply.body.contains("That code is not right"));
1569- assert_eq!(
1570- fx.state
1571- .store
1572- .unused_recovery_codes(&fx.user.id)
1573 .await1342 .await
1574- .unwrap(),1343+ .unwrap()
1575- 11344+ .is_some()
1576 );1345 );
1577-1346+ assert!(
1578- let good = format!("csrf={CSRF}&code={}", now_code(&shared));1347+ store
1579- let reply = send(1348+ .session_by_token_hash(&hash_token(OTHER_TOKEN))
1580- &fx.router,
1581- "POST",
1582- "/settings/security/2fa/recovery",
1583- true,
1584- &good,
1585- )
1586- .await;
1587- assert!(reply.body.contains("Recovery codes"));
1588- assert_eq!(
1589- fx.state
1590- .store
1591- .unused_recovery_codes(&fx.user.id)
1592 .await1349 .await
1593- .unwrap(),1350+ .unwrap()
1594- super::RECOVERY_CODE_COUNT as u641351+ .is_none()
1595 );1352 );
1353+ let fresh = store.user_by_id(&fx.user.id).await.unwrap().unwrap();
1596 assert!(1354 assert!(
1597- !fx.state1355+ crate::auth::verify_password_async("a brand new password".into(), fresh.password_hash)
1598- .store
1599- .consume_recovery_code(&fx.user.id, &totp::recovery_code_hash("aaaa-bbbb"))
1600 .await1356 .await
1601 .unwrap()1357 .unwrap()
1602 );1358 );
1603 }1359 }
1604 1360
1361+ /// Wrong current passwords are refused and counted against the login throttle, which then
1362+ /// answers 429. A wrong answer changes nothing.
1605 #[tokio::test]1363 #[tokio::test]
1606- async fn post_without_csrf_is_forbidden() {1364+ async fn wrong_current_passwords_are_refused_and_throttle_the_login() {
1607 let fx = fixture().await;1365 let fx = fixture().await;
1608- let form = format!(1366+ let bad = format!(
1609- "csrf=wrong&current_password={PASSWORD}&new_password=a+brand+new+password&confirm_password=a+brand+new+password"1367+ "csrf={CSRF}&current_password=wrong&new_password=a+brand+new+password&confirm_password=a+brand+new+password"
1610 );1368 );
1611- let reply = send(1369+ for _ in 0..LOGIN_USER_LIMIT {
1370+ let reply = send(
1371+ &fx.router,
1372+ "POST",
1373+ "/settings/security/password",
1374+ true,
1375+ &bad,
1376+ )
1377+ .await;
1378+ assert_eq!(reply.status, 200);
1379+ assert!(reply.body.contains("Current password is incorrect."));
1380+ }
1381+ assert!(
1382+ fx.state
1383+ .throttle
1384+ .check(
1385+ &user_key("tahinli"),
1386+ LOGIN_USER_LIMIT,
1387+ std::time::Instant::now()
1388+ )
1389+ .is_some()
1390+ );
1391+ let blocked = send(
1612 &fx.router,1392 &fx.router,
1613 "POST",1393 "POST",
1614 "/settings/security/password",1394 "/settings/security/password",
1615 true,1395 true,
1616- &form,1396+ &bad,
1617 )1397 )
1618 .await;1398 .await;
1619- assert_eq!(reply.status, 403);1399+ assert_eq!(blocked.status, 429);
1620- }1400+ assert!(blocked.body.contains("Too many attempts"));
1621 1401
1622- #[tokio::test]1402+ let fresh = fx
1623- async fn email_row_says_verified_once_the_address_is_verified() {
1624- let fx = fixture().await;
1625- fx.state
1626- .store
1627- .set_email(&fx.user.id, "tahinli@example.com")
1628- .await
1629- .unwrap();
1630- let token = fx
1631 .state1403 .state
1632 .store1404 .store
1633- .create_verify_token(&fx.user.id, "tahinli@example.com")1405+ .user_by_id(&fx.user.id)
1634 .await1406 .await
1407+ .unwrap()
1635 .unwrap();1408 .unwrap();
1636 assert!(1409 assert!(
1637- fx.state1410+ crate::auth::verify_password_async(PASSWORD.into(), fresh.password_hash)
1638- .store
1639- .redeem_verify_token(&token)
1640 .await1411 .await
1641 .unwrap()1412 .unwrap()
1642- .is_some()
1643- );
1644- let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1645- assert_eq!(page.status, 200);
1646- assert!(
1647- page.body.contains("tahinli@example.com</span> · Verified"),
1648- "{}",
1649- page.body
1650 );1413 );
1651 }1414 }
1652 1415
1416+ /// The Email row follows the address from unverified with a queued mail to verified.
1653 #[tokio::test]1417 #[tokio::test]
1654- async fn email_row_shows_the_queued_verification_mail_while_unverified() {1418+ async fn email_row_follows_the_address_from_queued_to_verified() {
1655 let fx = fixture().await;1419 let fx = fixture().await;
1656- let before = send(&fx.router, "GET", "/settings/security", true, "").await;
1657- assert!(before.body.contains("No email address"), "{}", before.body);
1658-
1659 fx.state1420 fx.state
1660 .store1421 .store
1661 .set_email(&fx.user.id, "tahinli@example.com")1422 .set_email(&fx.user.id, "tahinli@example.com")
@@ -1683,26 +1444,37 @@ mod tests {
1683 "{}",1444 "{}",
1684 page.body1445 page.body
1685 );1446 );
1686- }
1687 1447
1688- #[tokio::test]1448+ let token = fx
1689- async fn the_page_shows_the_device_and_warns_when_codes_run_low() {1449+ .state
1690- let fx = fixture().await;1450+ .store
1691- enable_totp_directly(&fx).await;1451+ .create_verify_token(&fx.user.id, "tahinli@example.com")
1452+ .await
1453+ .unwrap();
1454+ assert!(
1455+ fx.state
1456+ .store
1457+ .redeem_verify_token(&token)
1458+ .await
1459+ .unwrap()
1460+ .is_some()
1461+ );
1692 let page = send(&fx.router, "GET", "/settings/security", true, "").await;1462 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1693 assert_eq!(page.status, 200);1463 assert_eq!(page.status, 200);
1694- assert!(page.body.contains("Authenticator app"));1464+ assert!(
1695- assert!(page.body.contains("Added "), "{}", page.body);1465+ page.body.contains("tahinli@example.com</span> · Verified"),
1696- assert!(page.body.contains("1 of 10 recovery codes unused"));1466+ "{}",
1697- assert!(page.body.contains("Running low"));1467+ page.body
1698- assert!(page.body.contains("security-pill on"));1468+ );
1699 }1469 }
1700 1470
1471+ /// Enrollment: a wrong code and a bad device name do not enable two-factor, a good
1472+ /// confirmation does, and turning it off needs the password and then a fresh code.
1701 #[tokio::test]1473 #[tokio::test]
1702- async fn confirm_saves_the_device_name_and_refuses_a_bad_one() {1474+ async fn two_factor_enrollment_and_turn_off() {
1703 let fx = fixture().await;1475 let fx = fixture().await;
1704 let enable = format!("csrf={CSRF}");1476 let enable = format!("csrf={CSRF}");
1705- send(1477+ let reply = send(
1706 &fx.router,1478 &fx.router,
1707 "POST",1479 "POST",
1708 "/settings/security/2fa/enable",1480 "/settings/security/2fa/enable",
@@ -1710,18 +1482,53 @@ mod tests {
1710 &enable,1482 &enable,
1711 )1483 )
1712 .await;1484 .await;
1713- let sealed = fx1485+ assert_eq!(reply.status, 303, "enable");
1486+ let pending = fx
1714 .state1487 .state
1715 .store1488 .store
1716 .totp_state(&fx.user.id)1489 .totp_state(&fx.user.id)
1717 .await1490 .await
1718 .unwrap()1491 .unwrap()
1719- .unwrap()1492+ .unwrap();
1720- .sealed_secret1493+ assert!(!pending.enabled);
1721- .expect("secret stored");1494+ let sealed = pending.sealed_secret.expect("secret stored");
1722 let shared = secret::open(&KEY, &sealed).unwrap();1495 let shared = secret::open(&KEY, &sealed).unwrap();
1723 1496
1724- // An over-long name is refused, and the code is not spent on it.1497+ // The enrollment page shows the secret and the URI, not the codes.
1498+ let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1499+ assert!(page.body.contains(&totp::base32_encode(&shared)), "secret shown");
1500+ assert!(
1501+ page.body.contains("otpauth://totp/forge:tahinli?secret="),
1502+ "uri shown"
1503+ );
1504+
1505+ // A wrong code is refused. The chance that 000000 is the live code is about 1 in a
1506+ // million per window.
1507+ let wrong = format!("csrf={CSRF}&code=000000");
1508+ let reply = send(
1509+ &fx.router,
1510+ "POST",
1511+ "/settings/security/2fa/confirm",
1512+ true,
1513+ &wrong,
1514+ )
1515+ .await;
1516+ if reply.status == 200 && !reply.body.contains("Recovery codes") {
1517+ assert!(reply.body.contains("That code is not right"), "wrong code");
1518+ }
1519+ let state = fx
1520+ .state
1521+ .store
1522+ .totp_state(&fx.user.id)
1523+ .await
1524+ .unwrap()
1525+ .unwrap();
1526+ if !state.enabled {
1527+ assert!(state.sealed_secret.is_some(), "wrong code keeps the secret");
1528+ }
1529+
1530+ // An over-long device name is refused before the code is checked, so the code is
1531+ // not spent on it.
1725 let too_long = format!(1532 let too_long = format!(
1726 "csrf={CSRF}&code={}&name={}",1533 "csrf={CSRF}&code={}&name={}",
1727 now_code(&shared),1534 now_code(&shared),
@@ -1735,7 +1542,7 @@ mod tests {
1735 &too_long,1542 &too_long,
1736 )1543 )
1737 .await;1544 .await;
1738- assert!(reply.body.contains("at most 40 characters"));1545+ assert!(reply.body.contains("at most 40 characters"), "long name");
1739 assert!(1546 assert!(
1740 !fx.state1547 !fx.state
1741 .store1548 .store
@@ -1743,9 +1550,11 @@ mod tests {
1743 .await1550 .await
1744 .unwrap()1551 .unwrap()
1745 .unwrap()1552 .unwrap()
1746- .enabled1553+ .enabled,
1554+ "long name does not enable"
1747 );1555 );
1748 1556
1557+ // A good code and a name enable two-factor and issue ten recovery codes, once.
1749 let ok = format!("csrf={CSRF}&code={}&name=Work+phone", now_code(&shared));1558 let ok = format!("csrf={CSRF}&code={}&name=Work+phone", now_code(&shared));
1750 let reply = send(1559 let reply = send(
1751 &fx.router,1560 &fx.router,
@@ -1755,7 +1564,16 @@ mod tests {
1755 &ok,1564 &ok,
1756 )1565 )
1757 .await;1566 .await;
1758- assert!(reply.body.contains("Recovery codes"));1567+ assert_eq!(reply.status, 200);
1568+ assert!(reply.body.contains("Recovery codes"), "codes shown");
1569+ let codes = reply
1570+ .body
1571+ .split("<code>")
1572+ .skip(1)
1573+ .filter_map(|chunk| chunk.split("</code>").next())
1574+ .filter(|code| code.len() == 9 && code.as_bytes()[4] == b'-')
1575+ .count();
1576+ assert_eq!(codes, super::RECOVERY_CODE_COUNT, "recovery codes shown");
1759 let on = fx1577 let on = fx
1760 .state1578 .state
1761 .store1579 .store
@@ -1767,14 +1585,86 @@ mod tests {
1767 assert_eq!(on.name.as_deref(), Some("Work phone"));1585 assert_eq!(on.name.as_deref(), Some("Work phone"));
1768 assert!(on.created_at.is_some());1586 assert!(on.created_at.is_some());
1769 assert!(on.last_used_at.is_some());1587 assert!(on.last_used_at.is_some());
1588+ assert_eq!(
1589+ fx.state
1590+ .store
1591+ .unused_recovery_codes(&fx.user.id)
1592+ .await
1593+ .unwrap(),
1594+ super::RECOVERY_CODE_COUNT as u64
1595+ );
1770 let page = send(&fx.router, "GET", "/settings/security", true, "").await;1596 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1771- assert!(page.body.contains("Work phone"));1597+ assert!(page.body.contains("Work phone"), "device name shown");
1598+
1599+ // Turning off with a wrong password is refused and keeps two-factor on.
1600+ let no_password = format!(
1601+ "csrf={CSRF}&current_password=nope&code={}",
1602+ now_code(&shared)
1603+ );
1604+ let reply = send(
1605+ &fx.router,
1606+ "POST",
1607+ "/settings/security/2fa/disable",
1608+ true,
1609+ &no_password,
1610+ )
1611+ .await;
1612+ assert!(
1613+ reply.body.contains("Current password is incorrect."),
1614+ "turn off with a wrong password"
1615+ );
1616+ assert!(
1617+ fx.state
1618+ .store
1619+ .totp_state(&fx.user.id)
1620+ .await
1621+ .unwrap()
1622+ .unwrap()
1623+ .enabled
1624+ );
1625+
1626+ // The confirm step already used the current code, so disabling takes the next step's
1627+ // code. Reusing the current one would be refused as a replay.
1628+ let next = totp::code_at(&shared, totp::step_for(crate::auth::unix_now()) + 1);
1629+ let disable = format!("csrf={CSRF}&current_password={PASSWORD}&code={next}");
1630+ let reply = send(
1631+ &fx.router,
1632+ "POST",
1633+ "/settings/security/2fa/disable",
1634+ true,
1635+ &disable,
1636+ )
1637+ .await;
1638+ assert_eq!(
1639+ reply.location.as_deref(),
1640+ Some("/settings/security?saved=2fa-off"),
1641+ "turn off"
1642+ );
1643+ let off = fx
1644+ .state
1645+ .store
1646+ .totp_state(&fx.user.id)
1647+ .await
1648+ .unwrap()
1649+ .unwrap();
1650+ assert!(!off.enabled);
1651+ assert_eq!(off.sealed_secret, None);
1772 }1652 }
1773 1653
1654+ /// With two-factor on: the device and its code count show, a wrong password reopens only
1655+ /// the turn-off panel, and recovery codes need a real code and replace the old ones.
1774 #[tokio::test]1656 #[tokio::test]
1775- async fn a_wrong_password_on_turn_off_reopens_only_that_panel() {1657+ async fn enabled_account_shows_the_device_and_guards_its_panels() {
1776 let fx = fixture().await;1658 let fx = fixture().await;
1777 let shared = enable_totp_directly(&fx).await;1659 let shared = enable_totp_directly(&fx).await;
1660+ let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1661+ assert_eq!(page.status, 200);
1662+ assert!(page.body.contains("Authenticator app"));
1663+ assert!(page.body.contains("Added "), "{}", page.body);
1664+ assert!(page.body.contains("1 of 10 recovery codes unused"));
1665+ assert!(page.body.contains("Running low"));
1666+ assert!(page.body.contains("security-pill on"));
1667+
1778 let bad = format!(1668 let bad = format!(
1779 "csrf={CSRF}&current_password=nope&code={}",1669 "csrf={CSRF}&current_password=nope&code={}",
1780 now_code(&shared)1670 now_code(&shared)
@@ -1797,5 +1687,52 @@ mod tests {
1797 !reply.body.contains("security-action\" open"),1687 !reply.body.contains("security-action\" open"),
1798 "only the turn-off panel should be open"1688 "only the turn-off panel should be open"
1799 );1689 );
1690+
1691+ let bad_code = format!("csrf={CSRF}&code=123456x");
1692+ let reply = send(
1693+ &fx.router,
1694+ "POST",
1695+ "/settings/security/2fa/recovery",
1696+ true,
1697+ &bad_code,
1698+ )
1699+ .await;
1700+ assert!(reply.body.contains("That code is not right"), "bad code");
1701+ assert_eq!(
1702+ fx.state
1703+ .store
1704+ .unused_recovery_codes(&fx.user.id)
1705+ .await
1706+ .unwrap(),
1707+ 1,
1708+ "a refused code leaves the old codes"
1709+ );
1710+
1711+ let good = format!("csrf={CSRF}&code={}", now_code(&shared));
1712+ let reply = send(
1713+ &fx.router,
1714+ "POST",
1715+ "/settings/security/2fa/recovery",
1716+ true,
1717+ &good,
1718+ )
1719+ .await;
1720+ assert!(reply.body.contains("Recovery codes"), "new codes shown");
1721+ assert_eq!(
1722+ fx.state
1723+ .store
1724+ .unused_recovery_codes(&fx.user.id)
1725+ .await
1726+ .unwrap(),
1727+ super::RECOVERY_CODE_COUNT as u64
1728+ );
1729+ assert!(
1730+ !fx.state
1731+ .store
1732+ .consume_recovery_code(&fx.user.id, &totp::recovery_code_hash("aaaa-bbbb"))
1733+ .await
1734+ .unwrap(),
1735+ "the old recovery code is gone"
1736+ );
1800 }1737 }
1801 }1738 }