diff --git a/crates/forge-web/src/pages/account_tools_tests.rs b/crates/forge-web/src/pages/account_tools_tests.rs index bde7b5f..423f127 100644 --- a/crates/forge-web/src/pages/account_tools_tests.rs +++ b/crates/forge-web/src/pages/account_tools_tests.rs @@ -72,9 +72,11 @@ fn csrf(extra: &str) -> Option { } #[tokio::test] -async fn admin_pages_are_404_for_non_admins() { +async fn admin_account_tools() { let dir = tempfile::tempdir().unwrap(); let fx = fixture(dir.path(), None).await; + + // Admin pages and actions are 404 for anonymous visitors and plain users. let detail = format!("/admin/users/{}", fx.user_id); for uri in ["/admin/health", detail.as_str()] { assert_eq!( @@ -96,12 +98,8 @@ async fn admin_pages_are_404_for_non_admins() { .0, 404 ); -} -#[tokio::test] -async fn suspending_needs_csrf_and_is_audited() { - let dir = tempfile::tempdir().unwrap(); - let fx = fixture(dir.path(), None).await; + // Suspending needs the CSRF token, is audited, signs the user out and shows on their page. let uri = format!("/admin/users/{}/suspend", fx.user_id); let (status, _) = send( &fx.router, @@ -156,12 +154,8 @@ async fn suspending_needs_csrf_and_is_audited() { .await; assert_eq!(status, 303); assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none()); -} -#[tokio::test] -async fn the_last_admin_cannot_be_demoted_or_suspended_from_the_page() { - let dir = tempfile::tempdir().unwrap(); - let fx = fixture(dir.path(), None).await; + // The last administrator cannot be demoted from the page. let base = format!("/admin/users/{}", fx.admin_id); let (status, body) = send( &fx.router, @@ -175,12 +169,8 @@ async fn the_last_admin_cannot_be_demoted_or_suspended_from_the_page() { assert!(body.contains("last administrator"), "{body}"); let me = fx.store.user_by_id(&fx.admin_id).await.unwrap().unwrap(); assert!(me.is_admin); -} -#[tokio::test] -async fn reset_link_is_shown_once_and_signs_the_user_out() { - let dir = tempfile::tempdir().unwrap(); - let fx = fixture(dir.path(), None).await; + // The reset link is shown once and signs the user out. let (status, body) = send( &fx.router, "POST", @@ -203,12 +193,8 @@ async fn reset_link_is_shown_once_and_signs_the_user_out() { .unwrap() .is_empty() ); -} -#[tokio::test] -async fn disabling_two_factor_clears_it() { - let dir = tempfile::tempdir().unwrap(); - let fx = fixture(dir.path(), None).await; + // Disabling two-factor clears it. fx.store .set_totp_secret(&fx.user_id, "sealed") .await diff --git a/crates/forge-web/src/pages/admin_backups.rs b/crates/forge-web/src/pages/admin_backups.rs index d188b43..9102d99 100644 --- a/crates/forge-web/src/pages/admin_backups.rs +++ b/crates/forge-web/src/pages/admin_backups.rs @@ -415,13 +415,17 @@ mod tests { (status, String::from_utf8_lossy(&bytes).into_owned()) } + /// One configured instance serves every scenario below, since building it is the slow part. + /// The scenarios run in order: the run-count checks need the runs recorded so far. #[tokio::test] - async fn page_is_404_for_anonymous_and_non_admins() { + async fn backups_page_and_manual_runs() { let fx = fixture(true).await; + + // Anonymous visitors and plain users get a 404 for the page and for the run endpoint. let (anon, _) = send(&fx.router, "GET", "/admin/backups", None, None).await; - assert_eq!(anon, 404); + assert_eq!(anon, 404, "anonymous page"); let (user, _) = send(&fx.router, "GET", "/admin/backups", Some(USER_TOKEN), None).await; - assert_eq!(user, 404); + assert_eq!(user, 404, "plain user page"); let (posted, _) = send( &fx.router, "POST", @@ -430,46 +434,40 @@ mod tests { Some(format!("csrf={CSRF}")), ) .await; - assert_eq!(posted, 404); - } - - #[tokio::test] - async fn page_lists_runs_and_hides_the_healthcheck_token() { - let fx = fixture(true).await; - let mut config = (*fx.state.config).clone(); - config.backup.healthcheck_url = "https://hc.example.test/ping/SECRET-TOKEN".into(); - let mut state = fx.state.clone(); - state.config = std::sync::Arc::new(config); - let router = app_router(state.clone()); - - let id = state - .store - .start_run(RunKind::Backup, RunTrigger::Schedule) - .await - .expect("start"); - state - .store - .finish_run(&id, false, None, None, Some("disk full")) - .await - .expect("finish"); + assert_eq!(posted, 404, "plain user run"); - let (status, body) = send(&router, "GET", "/admin/backups", Some(ADMIN_TOKEN), None).await; - assert_eq!(status, 200); - assert!(body.contains("schedule")); - assert!(body.contains("disk full")); - assert!(body.contains("hc.example.test")); + // A backup already running refuses a second one, and the refusal records no run. + let held = fx.state.jobs.claim(RunKind::Backup).expect("claim"); + let (status, _) = send( + &fx.router, + "POST", + "/admin/backups/run", + Some(ADMIN_TOKEN), + Some(format!("csrf={CSRF}")), + ) + .await; + assert_eq!(status, 303, "busy run"); + let (_, page) = send( + &fx.router, + "GET", + "/admin/backups?notice=already%20running%3A%20x", + Some(ADMIN_TOKEN), + None, + ) + .await; + assert!(page.contains("already running"), "busy notice"); assert!( - !body.contains("SECRET-TOKEN"), - "the healthcheck token must not be shown" + fx.state + .store + .recent_runs(5) + .await + .expect("runs") + .is_empty(), + "busy run records nothing" ); - assert!(body.contains("Run backup now")); - assert!(body.contains("Run fsck now")); - } + drop(held); - #[tokio::test] - async fn post_starts_a_run_audits_it_and_records_it() { - let fx = fixture(true).await; - // Refused without the CSRF token. + // A POST without the CSRF token is refused. With it, fsck starts, is audited and recorded. let (bad, _) = send( &fx.router, "POST", @@ -478,7 +476,7 @@ mod tests { Some("csrf=wrong".into()), ) .await; - assert_eq!(bad, 403); + assert_eq!(bad, 403, "fsck without csrf"); let (status, _) = send( &fx.router, @@ -488,7 +486,7 @@ mod tests { Some(format!("csrf={CSRF}")), ) .await; - assert_eq!(status, 303); + assert_eq!(status, 303, "fsck with csrf"); // Wait for the background fsck to finish and record itself. let mut runs = Vec::new(); @@ -500,9 +498,9 @@ mod tests { tokio::time::sleep(std::time::Duration::from_millis(20)).await; } assert_eq!(runs.len(), 1, "{runs:?}"); - assert_eq!(runs[0].kind, RunKind::Fsck); - assert_eq!(runs[0].trigger, RunTrigger::Manual); - assert_eq!(runs[0].ok, Some(true)); + assert_eq!(runs[0].kind, RunKind::Fsck, "fsck run kind"); + assert_eq!(runs[0].trigger, RunTrigger::Manual, "fsck run trigger"); + assert_eq!(runs[0].ok, Some(true), "fsck run result"); let audit = fx .state @@ -510,42 +508,43 @@ mod tests { .list_audit(&Default::default(), None, 10) .await .expect("audit"); - assert!(audit.iter().any(|e| e.action == AuditAction::FsckStarted)); + assert!( + audit.iter().any(|e| e.action == AuditAction::FsckStarted), + "fsck is audited" + ); let (_, page) = send(&fx.router, "GET", "/admin/backups", Some(ADMIN_TOKEN), None).await; - assert!(page.contains("fsck")); - } + assert!(page.contains("fsck"), "fsck run is listed"); - #[tokio::test] - async fn a_backup_run_while_one_is_active_says_already_running() { - let fx = fixture(true).await; - let _held = fx.state.jobs.claim(RunKind::Backup).expect("claim"); - let (status, _) = send( - &fx.router, - "POST", - "/admin/backups/run", - Some(ADMIN_TOKEN), - Some(format!("csrf={CSRF}")), - ) - .await; - assert_eq!(status, 303); - let (_, page) = send( - &fx.router, - "GET", - "/admin/backups?notice=already%20running%3A%20x", - Some(ADMIN_TOKEN), - None, - ) - .await; - assert!(page.contains("already running")); + // The page lists runs, and the healthcheck URL is shown without its secret token. + let mut config = (*fx.state.config).clone(); + config.backup.healthcheck_url = "https://hc.example.test/ping/SECRET-TOKEN".into(); + let mut state = fx.state.clone(); + state.config = std::sync::Arc::new(config); + let router = app_router(state.clone()); + + let id = state + .store + .start_run(RunKind::Backup, RunTrigger::Schedule) + .await + .expect("start"); + state + .store + .finish_run(&id, false, None, None, Some("disk full")) + .await + .expect("finish"); + + let (status, body) = send(&router, "GET", "/admin/backups", Some(ADMIN_TOKEN), None).await; + assert_eq!(status, 200); + assert!(body.contains("schedule")); + assert!(body.contains("disk full")); + assert!(body.contains("hc.example.test")); assert!( - fx.state - .store - .recent_runs(5) - .await - .expect("runs") - .is_empty() + !body.contains("SECRET-TOKEN"), + "the healthcheck token must not be shown" ); + assert!(body.contains("Run backup now")); + assert!(body.contains("Run fsck now")); } #[tokio::test] diff --git a/crates/forge-web/src/pages/admin_replication.rs b/crates/forge-web/src/pages/admin_replication.rs index 836daba..15e0584 100644 --- a/crates/forge-web/src/pages/admin_replication.rs +++ b/crates/forge-web/src/pages/admin_replication.rs @@ -421,11 +421,15 @@ mod tests { (status, String::from_utf8_lossy(&bytes).into_owned()) } + /// One configured instance serves the page and reconcile scenarios below, since building it is + /// the slow part. The scenarios run in order, each asserting only its own result. #[tokio::test] - async fn page_and_reconcile_are_404_for_anonymous_and_non_admins() { + async fn replication_page_and_reconcile() { let fx = fixture(true).await; + + // Anonymous visitors and plain users get a 404 for the page and the reconcile endpoint. let (anon, _) = send(&fx.router, "GET", "/admin/replication", None, None).await; - assert_eq!(anon, 404); + assert_eq!(anon, 404, "anonymous page"); let (user, _) = send( &fx.router, "GET", @@ -434,7 +438,7 @@ mod tests { None, ) .await; - assert_eq!(user, 404); + assert_eq!(user, 404, "plain user page"); let (posted, _) = send( &fx.router, "POST", @@ -443,13 +447,10 @@ mod tests { Some(format!("csrf={CSRF}")), ) .await; - assert_eq!(posted, 404); + assert_eq!(posted, 404, "plain user reconcile"); assert!(!fx.state.replication.take_reconcile_request()); - } - #[tokio::test] - async fn page_shows_target_db_and_repo_health_without_secrets() { - let fx = fixture(true).await; + // The page shows the target and repo health, without secrets, and keeps stale rows visible. let store = &fx.state.store; store .record_replication_ok(DB_SUBJECT, None) @@ -482,21 +483,18 @@ mod tests { ); assert!(body.contains("pending cleanup")); assert!(body.contains("Reconcile now")); - } - #[tokio::test] - async fn unconfigured_page_says_so_and_reconcile_is_refused() { - let fx = fixture(false).await; - let (status, body) = send( + // A reconcile without the CSRF token is refused. With it, the request is queued and audited. + let (bad, _) = send( &fx.router, - "GET", - "/admin/replication", + "POST", + "/admin/replication/reconcile", Some(ADMIN_TOKEN), - None, + Some("csrf=wrong".into()), ) .await; - assert_eq!(status, 200); - assert!(body.contains("Replication is off")); + assert_eq!(bad, 403, "reconcile without csrf"); + assert!(!fx.state.replication.take_reconcile_request()); let (status, _) = send( &fx.router, @@ -506,8 +504,8 @@ mod tests { Some(format!("csrf={CSRF}")), ) .await; - assert_eq!(status, 303); - assert!(!fx.state.replication.take_reconcile_request()); + assert_eq!(status, 303, "reconcile with csrf"); + assert!(fx.state.replication.take_reconcile_request()); let audit = fx .state .store @@ -515,25 +513,26 @@ mod tests { .await .expect("audit"); assert!( - !audit + audit .iter() - .any(|e| e.action == AuditAction::ReplicationReconcileStarted) + .any(|e| e.action == AuditAction::ReplicationReconcileStarted), + "the request is audited" ); } #[tokio::test] - async fn reconcile_needs_csrf_and_is_audited() { - let fx = fixture(true).await; - let (bad, _) = send( + async fn unconfigured_page_says_so_and_reconcile_is_refused() { + let fx = fixture(false).await; + let (status, body) = send( &fx.router, - "POST", - "/admin/replication/reconcile", + "GET", + "/admin/replication", Some(ADMIN_TOKEN), - Some("csrf=wrong".into()), + None, ) .await; - assert_eq!(bad, 403); - assert!(!fx.state.replication.take_reconcile_request()); + assert_eq!(status, 200); + assert!(body.contains("Replication is off")); let (status, _) = send( &fx.router, @@ -544,7 +543,7 @@ mod tests { ) .await; assert_eq!(status, 303); - assert!(fx.state.replication.take_reconcile_request()); + assert!(!fx.state.replication.take_reconcile_request()); let audit = fx .state .store @@ -552,10 +551,9 @@ mod tests { .await .expect("audit"); assert!( - audit + !audit .iter() - .any(|e| e.action == AuditAction::ReplicationReconcileStarted), - "the request is audited" + .any(|e| e.action == AuditAction::ReplicationReconcileStarted) ); } diff --git a/crates/forge-web/src/pages/assets.rs b/crates/forge-web/src/pages/assets.rs index 4bee9a0..3f3d2be 100644 --- a/crates/forge-web/src/pages/assets.rs +++ b/crates/forge-web/src/pages/assets.rs @@ -261,8 +261,9 @@ mod tests { use topcoat::router::{Body, Router, RouterBuilderDiscoverExt, to_bytes}; #[tokio::test] - async fn bundled_fonts_are_served_as_immutable_woff2() { + async fn fonts_and_licenses_are_served() { let router: Router = Router::builder().discover().cookies().build(); + // Bundled fonts are immutable woff2 files. for uri in [ "/assets/fonts/figtree-5.3.0-latin-wght.woff2", "/assets/fonts/figtree-5.3.0-latin-ext-wght.woff2", @@ -287,11 +288,8 @@ mod tests { let body = to_bytes(res.into_body(), usize::MAX).await.unwrap(); assert!(body.starts_with(b"wOF2"), "{uri}"); } - } - #[tokio::test] - async fn font_licenses_are_served_as_text() { - let router: Router = Router::builder().discover().cookies().build(); + // Font licences are plain text. for uri in [ "/assets/fonts/Figtree-OFL.txt", "/assets/fonts/IBMPlexMono-OFL.txt", @@ -339,27 +337,33 @@ mod tests { } #[tokio::test] - async fn nav_script_is_served_as_immutable_javascript() { + async fn immutable_assets_are_served_with_long_cache() { let router: Router = Router::builder().discover().cookies().build(); - let req = Request::builder() - .method("GET") - .uri(crate::views::NAV_SCRIPT_HREF) - .body(Body::empty()) - .unwrap(); - let res = router.handle(req).await; - assert_eq!(res.status(), 200); - assert_eq!( - res.headers()["content-type"], - "text/javascript; charset=utf-8" - ); - assert!( - res.headers()["cache-control"] - .to_str() - .unwrap() - .contains("immutable") - ); - let body = to_bytes(res.into_body(), usize::MAX).await.unwrap(); - assert!(String::from_utf8_lossy(&body).contains("__forgeSoft")); + // Each bundle is immutable under its own type. Its body holds the marker, when one is given. + for (uri, kind, marker) in [ + ("/assets/main.css", "text/css; charset=utf-8", ""), + (crate::views::NAV_SCRIPT_HREF, "text/javascript; charset=utf-8", "__forgeSoft"), + (crate::views::highlight_href(), "text/css; charset=utf-8", ""), + ] { + let req = Request::builder() + .method("GET") + .uri(uri) + .body(Body::empty()) + .unwrap(); + let res = router.handle(req).await; + assert_eq!(res.status(), 200, "{uri}"); + assert_eq!(res.headers()["content-type"], kind, "{uri}"); + assert!( + res.headers()["cache-control"] + .to_str() + .unwrap() + .contains("immutable"), + "{uri}" + ); + let body = to_bytes(res.into_body(), usize::MAX).await.unwrap(); + assert!(!body.is_empty(), "{uri}"); + assert!(String::from_utf8_lossy(&body).contains(marker), "{uri}"); + } } #[tokio::test] @@ -412,27 +416,6 @@ mod tests { } } - #[tokio::test] - async fn highlight_css_is_served_with_long_cache() { - let router: Router = Router::builder().discover().cookies().build(); - let req = Request::builder() - .method("GET") - .uri(crate::views::highlight_href()) - .body(Body::empty()) - .unwrap(); - let res = router.handle(req).await; - assert_eq!(res.status(), 200); - assert_eq!(res.headers()["content-type"], "text/css; charset=utf-8"); - assert!( - res.headers()["cache-control"] - .to_str() - .unwrap() - .contains("immutable") - ); - let body = to_bytes(res.into_body(), usize::MAX).await.unwrap(); - assert!(!body.is_empty()); - } - #[tokio::test] async fn custom_css_keys_the_hue_choices_and_is_empty_without_one() { let router: Router = Router::builder().discover().cookies().build(); diff --git a/crates/forge-web/src/pages/audit_log.rs b/crates/forge-web/src/pages/audit_log.rs index dc7076d..7595530 100644 --- a/crates/forge-web/src/pages/audit_log.rs +++ b/crates/forge-web/src/pages/audit_log.rs @@ -365,17 +365,16 @@ mod tests { } #[tokio::test] - async fn admin_page_is_404_for_anonymous_and_non_admins() { + async fn audit_log_pages_and_recording() { let fx = fixture().await; + + // The admin page is 404 for anonymous visitors and plain users. let (anon, _) = send(&fx.router, "GET", "/admin/audit", None, None).await; assert_eq!(anon, 404); let (user, _) = send(&fx.router, "GET", "/admin/audit", Some(TOKEN), None).await; assert_eq!(user, 404); - } - #[tokio::test] - async fn admin_page_lists_entries_and_filters_by_action() { - let fx = fixture().await; + // The admin page lists entries and filters them by action. let admin = fx.store.create_user("root", None, "h", true).await.unwrap(); crate::test_support::create_session(&fx.store, &admin.id, ADMIN_TOKEN, ADMIN_CSRF).await; let mut entry = AuditEntry::new(AuditAction::LoginFailed); @@ -416,11 +415,8 @@ mod tests { ) .await; assert!(body.contains("There is no action named nonsense.")); - } - #[tokio::test] - async fn adding_an_ssh_key_is_recorded() { - let fx = fixture().await; + // Adding an SSH key is recorded in the audit log. let form = form_urlencoded::Serializer::new(String::new()) .append_pair("csrf", CSRF) .append_pair("title", "laptop") @@ -445,11 +441,8 @@ mod tests { assert_eq!(rows[0].actor_id.as_deref(), Some(fx.user.id.as_str())); assert_eq!(rows[0].target_name, "laptop"); assert_eq!(rows[0].target_kind, "ssh_key"); - } - #[tokio::test] - async fn own_log_shows_only_entries_about_the_viewer() { - let fx = fixture().await; + // The own log shows only entries about the viewer. let bob = fx.store.create_user("bob", None, "h", false).await.unwrap(); let mut mine = AuditEntry::new(AuditAction::LoginSuccess); mine.actor_id = Some(fx.user.id.clone()); @@ -477,15 +470,11 @@ mod tests { assert_eq!(status, 200); assert_eq!(body.matches("login_success").count(), 1); assert!(body.contains("password_reset_by_admin")); - } - #[tokio::test] - async fn own_log_requires_a_session() { - let fx = fixture().await; + // The own log needs a session. let (status, _) = send(&fx.router, "GET", "/settings/security/log", None, None).await; assert_eq!(status, 303); } - #[test] fn anonymous_actor_and_target_fallbacks() { let mut entry = AuditEntry::new(AuditAction::LoginFailed);