From 75640ff0003200fbe2262e1ef0f12f373db8be77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 13:23:21 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20site=20announcement=20banne?= =?UTF-8?q?r,=20admin=20health=20page,=20nav=20and=20styles?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Includes: ✨ feat: suspend users, admin flag, reset link and 2FA reset; password change notice --- .../migrations/0055_user_suspensions.sql | 10 + crates/forge-core/src/audit.rs | 19 +- crates/forge-core/src/config.rs | 65 +++ crates/forge-core/src/server_settings.rs | 40 ++ crates/forge-core/src/store/health.rs | 67 +++ crates/forge-core/src/store/migrate.rs | 4 + crates/forge-core/src/store/mod.rs | 17 +- crates/forge-core/src/store/suspension.rs | 263 +++++++++++ crates/forge-web/src/i18n/accounts.rs | 238 ++++++++++ crates/forge-web/src/i18n/mod.rs | 1 + crates/forge-web/src/mail/account.rs | 27 ++ crates/forge-web/src/mail/templates.rs | 12 + .../src/pages/account_tools_tests.rs | 347 +++++++++++++++ crates/forge-web/src/pages/admin_health.rs | 332 ++++++++++++++ .../forge-web/src/pages/admin_user_detail.rs | 421 ++++++++++++++++++ crates/forge-web/src/pages/admin_users.rs | 8 +- crates/forge-web/src/pages/banner.rs | 133 ++++++ crates/forge-web/src/pages/login.rs | 34 +- crates/forge-web/src/pages/mod.rs | 5 + .../forge-web/src/pages/settings_security.rs | 10 + crates/forge-web/src/test_support.rs | 1 + crates/forge-web/src/views/mod.rs | 24 + style/_account_admin.scss | 172 +++++++ style/main.scss | 2 + 24 files changed, 2242 insertions(+), 10 deletions(-) create mode 100644 crates/forge-core/migrations/0055_user_suspensions.sql create mode 100644 crates/forge-core/src/store/health.rs create mode 100644 crates/forge-core/src/store/suspension.rs create mode 100644 crates/forge-web/src/i18n/accounts.rs create mode 100644 crates/forge-web/src/pages/account_tools_tests.rs create mode 100644 crates/forge-web/src/pages/admin_health.rs create mode 100644 crates/forge-web/src/pages/admin_user_detail.rs create mode 100644 crates/forge-web/src/pages/banner.rs create mode 100644 style/_account_admin.scss diff --git a/crates/forge-core/migrations/0055_user_suspensions.sql b/crates/forge-core/migrations/0055_user_suspensions.sql new file mode 100644 index 0000000..425bb9b --- /dev/null +++ b/crates/forge-core/migrations/0055_user_suspensions.sql @@ -0,0 +1,10 @@ +-- A suspended account cannot sign in, its sessions, tokens and SSH keys stop working, and git +-- access is refused. One row per suspended user; deleting the row lifts the suspension. +-- Applied by store/migrate.rs. + +CREATE TABLE user_suspensions ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + reason TEXT NOT NULL DEFAULT '', + suspended_at TEXT NOT NULL, + suspended_by TEXT +); diff --git a/crates/forge-core/src/audit.rs b/crates/forge-core/src/audit.rs index 38dae44..fa84a4f 100644 --- a/crates/forge-core/src/audit.rs +++ b/crates/forge-core/src/audit.rs @@ -103,6 +103,11 @@ pub enum AuditAction { EmailVerified, InviteSent, InviteAccepted, + UserSuspended, + UserUnsuspended, + AdminGranted, + AdminRevoked, + TotpDisabledByAdmin, } impl AuditAction { @@ -202,6 +207,11 @@ impl AuditAction { AuditAction::EmailVerified, AuditAction::InviteSent, AuditAction::InviteAccepted, + AuditAction::UserSuspended, + AuditAction::UserUnsuspended, + AuditAction::AdminGranted, + AuditAction::AdminRevoked, + AuditAction::TotpDisabledByAdmin, ]; pub fn as_str(self) -> &'static str { @@ -300,6 +310,11 @@ impl AuditAction { AuditAction::EmailVerified => "email_verified", AuditAction::InviteSent => "invite_sent", AuditAction::InviteAccepted => "invite_accepted", + AuditAction::UserSuspended => "user_suspended", + AuditAction::UserUnsuspended => "user_unsuspended", + AuditAction::AdminGranted => "admin_granted", + AuditAction::AdminRevoked => "admin_revoked", + AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin", } } @@ -396,13 +411,13 @@ mod tests { #[test] fn names_are_unique_and_round_trip() { let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); - assert_eq!(names.len(), 94); + assert_eq!(names.len(), 99); for action in AuditAction::ALL { assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); } names.sort(); names.dedup(); - assert_eq!(names.len(), 94); + assert_eq!(names.len(), 99); assert_eq!(AuditAction::parse("nope"), None); } diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index 6f3807a..a9ac1fe 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -105,6 +105,71 @@ pub struct Config { /// Self-update after a green CI run of the forge's own repo, from the `[self_update]` section. #[serde(default)] pub self_update: SelfUpdateConfig, + /// Site announcement shown under every page header, from the `[banner]` section. + #[serde(default)] + pub banner: BannerConfig, +} + +/// Site announcement banner. An empty `message` shows nothing. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct BannerConfig { + /// One line of text. Empty turns the banner off. + pub message: String, + /// `info` or `warning`. + pub level: String, + /// UTC time as `YYYY-MM-DD HH:MM` after which the banner disappears. Empty for never. + pub expires: String, +} + +impl Default for BannerConfig { + fn default() -> Self { + BannerConfig { + message: String::new(), + level: "info".into(), + expires: String::new(), + } + } +} + +impl BannerConfig { + /// Unix seconds of `expires`, or `None` when unset or malformed. + pub fn expires_unix(&self) -> Option { + parse_banner_expiry(&self.expires) + } + + /// Whether the banner shows at `now` (unix seconds). + pub fn active_at(&self, now: i64) -> bool { + !self.message.trim().is_empty() && self.expires_unix().is_none_or(|t| now < t) + } +} + +/// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds. +pub fn parse_banner_expiry(raw: &str) -> Option { + let raw = raw.trim(); + let (date, time) = raw.split_once(' ')?; + let mut d = date.split('-'); + let (y, m, day): (i64, i64, i64) = ( + d.next()?.parse().ok()?, + d.next()?.parse().ok()?, + d.next()?.parse().ok()?, + ); + if d.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&day) { + return None; + } + let (hh, mm) = time.split_once(':')?; + let (hh, mm): (i64, i64) = (hh.parse().ok()?, mm.parse().ok()?); + if !(0..24).contains(&hh) || !(0..60).contains(&mm) || y < 1970 { + return None; + } + // Days from civil (Howard Hinnant). + let y2 = if m <= 2 { y - 1 } else { y }; + let era = y2 / 400; + let yoe = y2 - era * 400; + let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Some(days * 86_400 + hh * 3_600 + mm * 60) } /// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo` diff --git a/crates/forge-core/src/server_settings.rs b/crates/forge-core/src/server_settings.rs index 0927b75..e5078be 100644 --- a/crates/forge-core/src/server_settings.rs +++ b/crates/forge-core/src/server_settings.rs @@ -121,6 +121,7 @@ use Group::{Backups, General, Integrations, Limits, Storage}; use Kind::{Live as L, ReadOnly as R, Restart as X}; const REGISTRATION: &[&str] = &["closed", "invite", "open"]; +const BANNER_LEVEL: &[&str] = &["info", "warning"]; const ORG_CREATION: &[&str] = &["all", "admin"]; const MAIL_TRANSPORT: &[&str] = &["smtp", "log"]; const BACKEND: &[&str] = &["fs", "s3", "r2"]; @@ -146,6 +147,30 @@ pub static FIELDS: &[Field] = &[ "Organization creation", "Who may create an organization: all signed-in people, or admins only.", ), + f( + "banner.message", + General, + L, + Ty::Text, + "Announcement banner", + "One line shown under the header on every page. Empty hides it.", + ), + f( + "banner.level", + General, + L, + Ty::Choice(BANNER_LEVEL), + "Banner level", + "info or warning.", + ), + f( + "banner.expires", + General, + L, + Ty::Text, + "Banner expires (UTC)", + "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.", + ), f( "trusted_proxies", General, @@ -639,6 +664,15 @@ pub fn normalize(field: &Field, raw: &str) -> Result { "must be one line of at most 1024 characters", )); } + if field.key == "banner.expires" + && !raw.is_empty() + && crate::config::parse_banner_expiry(raw).is_none() + { + return Err(invalid(field, "must look like 2026-12-31 18:00")); + } + if field.key == "banner.message" && raw.chars().count() > 300 { + return Err(invalid(field, "must be at most 300 characters")); + } Ok(raw.to_owned()) } Ty::List => { @@ -714,6 +748,9 @@ pub fn get(cfg: &Config, key: &str) -> String { .map(ToString::to_string) .collect::>() .join(", "), + "banner.message" => cfg.banner.message.clone(), + "banner.level" => cfg.banner.level.clone(), + "banner.expires" => cfg.banner.expires.clone(), "base_url" => cfg.base_url.clone(), "user_content_base_url" => cfg.user_content_base_url.clone(), "ssh_public_host" => cfg.ssh_public_host.clone(), @@ -817,6 +854,9 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { }) .collect() } + "banner.message" => cfg.banner.message = s(), + "banner.level" => cfg.banner.level = s(), + "banner.expires" => cfg.banner.expires = s(), "base_url" => cfg.base_url = s(), "user_content_base_url" => cfg.user_content_base_url = s(), "ssh_public_host" => cfg.ssh_public_host = s(), diff --git a/crates/forge-core/src/store/health.rs b/crates/forge-core/src/store/health.rs new file mode 100644 index 0000000..df5c53f --- /dev/null +++ b/crates/forge-core/src/store/health.rs @@ -0,0 +1,67 @@ +//! Cheap counts for the admin health page. + +use super::{Store, col_int, fetch_opt}; +use crate::error::{Error, Result}; +use crate::time::stamp_ago; + +/// Window in which a runner's last report counts as online. +pub const RUNNER_ONLINE_SECS: u64 = 90; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct HealthCounts { + pub repos: i64, + pub users: i64, + pub queued_jobs: i64, + pub runners_online: i64, + pub runners_total: i64, +} + +impl Store { + /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries. + pub async fn health_counts(&self) -> Result { + let conn = self.read_conn().await; + let since = stamp_ago(std::time::Duration::from_secs(RUNNER_ONLINE_SECS)); + let plain = |sql: &'static str| { + let conn = &conn; + async move { + Ok::( + fetch_opt(conn, sql, (), |row| col_int(row, 0)) + .await? + .unwrap_or(0), + ) + } + }; + let online = fetch_opt( + &conn, + "SELECT COUNT(*) FROM ci_runners WHERE disabled = 0 AND last_seen_at > ?1", + (since,), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + Ok(HealthCounts { + repos: plain("SELECT COUNT(*) FROM repos").await?, + users: plain("SELECT COUNT(*) FROM users WHERE kind = 'user'").await?, + queued_jobs: plain("SELECT COUNT(*) FROM ci_jobs WHERE state = 'queued'").await?, + runners_online: online, + runners_total: plain("SELECT COUNT(*) FROM ci_runners").await?, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn counts_a_fresh_store() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("f.db")).await.unwrap(); + store.create_user("tahinli", None, "h", true).await.unwrap(); + let c = store.health_counts().await.unwrap(); + assert_eq!( + (c.repos, c.users, c.queued_jobs, c.runners_online), + (0, 1, 0, 0) + ); + } +} diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 6767394..bea319f 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -91,6 +91,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 54, include_str!("../../migrations/0054_ci_schedule_state.sql"), ), + ( + 55, + include_str!("../../migrations/0055_user_suspensions.sql"), + ), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 7cc9915..52fb329 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -11,6 +11,7 @@ pub mod contributions; pub mod discussions; pub mod edit_history_read; pub mod exports; +pub mod health; pub mod imports; pub mod issues; pub mod labels; @@ -37,6 +38,7 @@ pub mod signatures; pub mod snapshot; pub mod snippets; pub mod suggest; +pub mod suspension; pub mod transfers; pub mod ui_prefs; pub mod user_delete; @@ -378,7 +380,10 @@ impl Store { let conn = self.read_conn().await; fetch_opt( &conn, - &format!("SELECT {SESSION_COLS} FROM sessions WHERE token_hash = ?1 AND expires_at > ?2 LIMIT 1"), + &format!( + "SELECT {SESSION_COLS} FROM sessions WHERE token_hash = ?1 AND expires_at > ?2 \ + AND user_id NOT IN (SELECT user_id FROM user_suspensions) LIMIT 1" + ), (token_hash.to_string(), now_stamp()), map_session, ) @@ -470,7 +475,10 @@ impl Store { let conn = self.read_conn().await; fetch_opt( &conn, - &format!("SELECT {SSH_KEY_COLS} FROM ssh_keys WHERE key_blob = ?1 LIMIT 1"), + &format!( + "SELECT {SSH_KEY_COLS} FROM ssh_keys WHERE key_blob = ?1 \ + AND user_id NOT IN (SELECT user_id FROM user_suspensions) LIMIT 1" + ), (key_blob.to_vec(),), map_ssh_key, ) @@ -557,7 +565,8 @@ impl Store { &conn, &format!( "SELECT {TOKEN_COLS} FROM access_tokens \ - WHERE token_hash = ?1 AND (expires_at IS NULL OR expires_at > ?2) LIMIT 1" + WHERE token_hash = ?1 AND (expires_at IS NULL OR expires_at > ?2) \ + AND user_id NOT IN (SELECT user_id FROM user_suspensions) LIMIT 1" ), (token_hash.to_string(), now_stamp()), map_token, @@ -1016,7 +1025,7 @@ fn col_blob(row: &Row, i: usize) -> Result> { } } -fn col_int(row: &Row, i: usize) -> Result { +pub(crate) fn col_int(row: &Row, i: usize) -> Result { match row.get_value(i).map_err(db_err)? { Value::Integer(n) => Ok(n), _ => Err(Error::Database(format!("column {i} is not an integer"))), diff --git a/crates/forge-core/src/store/suspension.rs b/crates/forge-core/src/store/suspension.rs new file mode 100644 index 0000000..7aa30cd --- /dev/null +++ b/crates/forge-core/src/store/suspension.rs @@ -0,0 +1,263 @@ +//! Account suspension and the admin-only account facts (migration 0059). +//! +//! A suspended user keeps their data but cannot sign in. The session, token and SSH key lookups +//! in `store/mod.rs` skip a suspended owner, so every transport stops at once. + +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt}; +use crate::error::{Error, Result}; +use crate::time::now_stamp; + +/// Longest accepted suspension reason, in characters. +pub const MAX_REASON_CHARS: usize = 300; + +/// Why and when an account was suspended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Suspension { + pub reason: String, + pub suspended_at: String, +} + +/// Facts the admin user page shows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountFacts { + pub repo_count: i64, + /// RFC 3339 stamp of the last successful sign-in in the audit log. + pub last_login: Option, + pub two_factor: bool, +} + +impl Store { + /// The suspension of `user_id`, if any. + pub async fn suspension(&self, user_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT reason, suspended_at FROM user_suspensions WHERE user_id = ?1 LIMIT 1", + (user_id.to_string(),), + |row| { + Ok(Suspension { + reason: col_text(row, 0)?, + suspended_at: col_text(row, 1)?, + }) + }, + ) + .await + } + + /// Suspends `user_id` and signs out every session. Refused for an organization and for the + /// last administrator who is not suspended. + pub async fn suspend_user(&self, user_id: &str, reason: &str, by: Option<&str>) -> Result<()> { + let reason = reason.trim(); + if reason.chars().count() > MAX_REASON_CHARS || reason.chars().any(char::is_control) { + return Err(Error::Invalid(format!( + "the reason must be one line of at most {MAX_REASON_CHARS} characters" + ))); + } + let conn = self.inner.conn.lock().await; + let uid = user_id.to_string(); + let row = fetch_opt( + &conn, + "SELECT is_admin, kind FROM users WHERE id = ?1 LIMIT 1", + (uid.clone(),), + |row| Ok((col_int(row, 0)? != 0, col_text(row, 1)?)), + ) + .await? + .ok_or(Error::NotFound)?; + if row.1 == "org" { + return Err(Error::Invalid("an organization cannot be suspended".into())); + } + if row.0 { + let others = fetch_opt( + &conn, + "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 \ + AND id NOT IN (SELECT user_id FROM user_suspensions)", + (uid.clone(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if others == 0 { + return Err(Error::Conflict( + "cannot suspend the last active administrator".into(), + )); + } + } + conn.execute( + "INSERT INTO user_suspensions (user_id, reason, suspended_at, suspended_by) \ + VALUES (?1, ?2, ?3, ?4) ON CONFLICT(user_id) DO UPDATE SET reason = excluded.reason", + ( + uid.clone(), + reason.to_string(), + now_stamp(), + by.map(str::to_string), + ), + ) + .await + .map_err(db_err)?; + conn.execute("DELETE FROM sessions WHERE user_id = ?1", (uid,)) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Lifts a suspension. Returns whether one existed. + pub async fn unsuspend_user(&self, user_id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "DELETE FROM user_suspensions WHERE user_id = ?1", + (user_id.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(n > 0) + } + + /// Grants or revokes the admin flag. Revoking is refused for the last administrator. + pub async fn set_admin(&self, user_id: &str, admin: bool) -> Result<()> { + let conn = self.inner.conn.lock().await; + let uid = user_id.to_string(); + let kind = fetch_opt( + &conn, + "SELECT kind FROM users WHERE id = ?1 LIMIT 1", + (uid.clone(),), + |row| col_text(row, 0), + ) + .await? + .ok_or(Error::NotFound)?; + if kind == "org" { + return Err(Error::Invalid( + "an organization cannot be an administrator".into(), + )); + } + if !admin { + let others = fetch_opt( + &conn, + "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 AND kind = 'user'", + (uid.clone(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if others == 0 { + return Err(Error::Conflict( + "cannot remove the last administrator".into(), + )); + } + } + conn.execute( + "UPDATE users SET is_admin = ?2 WHERE id = ?1", + (uid, i64::from(admin)), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Repo count, last sign-in and 2FA state for the admin user page. + pub async fn account_facts(&self, user_id: &str) -> Result { + let conn = self.read_conn().await; + let uid = user_id.to_string(); + let repo_count = fetch_opt( + &conn, + "SELECT COUNT(*) FROM repos WHERE owner_id = ?1", + (uid.clone(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + let last_login = fetch_opt( + &conn, + "SELECT MAX(at) FROM audit_log WHERE actor_id = ?1 AND action = 'login_success'", + (uid.clone(),), + |row| col_opt_text(row, 0), + ) + .await? + .flatten(); + let two_factor = fetch_opt( + &conn, + "SELECT totp_enabled FROM users WHERE id = ?1 LIMIT 1", + (uid,), + |row| Ok(col_int(row, 0)? != 0), + ) + .await? + .unwrap_or(false); + Ok(AccountFacts { + repo_count, + last_login, + two_factor, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn fixture() -> ( + Store, + crate::model::User, + crate::model::User, + tempfile::TempDir, + ) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("f.db")).await.unwrap(); + let admin = store.create_user("tahinli", None, "h", true).await.unwrap(); + let other = store.create_user("carol", None, "h", false).await.unwrap(); + (store, admin, other, dir) + } + + #[tokio::test] + async fn suspension_blocks_sessions_and_lifts() { + let (store, _admin, other, _d) = fixture().await; + store + .create_session(&other.id, "th", "csrf", "2999-01-01T00:00:00Z", None) + .await + .unwrap(); + assert!(store.session_by_token_hash("th").await.unwrap().is_some()); + store.suspend_user(&other.id, "spam", None).await.unwrap(); + assert!(store.session_by_token_hash("th").await.unwrap().is_none()); + assert_eq!( + store.suspension(&other.id).await.unwrap().unwrap().reason, + "spam" + ); + assert!(store.unsuspend_user(&other.id).await.unwrap()); + assert!(store.suspension(&other.id).await.unwrap().is_none()); + } + + #[tokio::test] + async fn last_admin_cannot_be_demoted_or_suspended() { + let (store, admin, other, _d) = fixture().await; + assert!(matches!( + store.set_admin(&admin.id, false).await, + Err(Error::Conflict(_)) + )); + assert!(matches!( + store.suspend_user(&admin.id, "", None).await, + Err(Error::Conflict(_)) + )); + store.set_admin(&other.id, true).await.unwrap(); + store.set_admin(&admin.id, false).await.unwrap(); + } + + #[tokio::test] + async fn suspension_stops_tokens_and_ssh_keys() { + let (store, _admin, other, _d) = fixture().await; + store + .create_token(&other.id, "ci", "tokhash", &["repo".to_owned()], None) + .await + .unwrap(); + store + .add_ssh_key(&other.id, "laptop", "ssh-ed25519", b"blob", "SHA256:x") + .await + .unwrap(); + assert!(store.token_by_hash("tokhash").await.unwrap().is_some()); + assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_some()); + store.suspend_user(&other.id, "", None).await.unwrap(); + assert!(store.token_by_hash("tokhash").await.unwrap().is_none()); + assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_none()); + store.unsuspend_user(&other.id).await.unwrap(); + assert!(store.token_by_hash("tokhash").await.unwrap().is_some()); + assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_some()); + } +} diff --git a/crates/forge-web/src/i18n/accounts.rs b/crates/forge-web/src/i18n/accounts.rs new file mode 100644 index 0000000..f351c9e --- /dev/null +++ b/crates/forge-web/src/i18n/accounts.rs @@ -0,0 +1,238 @@ +//! Strings for admin account tools, the announcement banner and the health page. + +use super::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum A { + Status, + Active, + Suspended, + LastLogin, + Repositories, + TwoFactor, + On, + Off, + Administrator, + Suspend, + Unsuspend, + SuspendReason, + SuspendHelp, + GrantAdmin, + RevokeAdmin, + AdminHelp, + ResetPassword, + GenerateLink, + ResetHelp, + ResetLinkReady, + Disable2fa, + Disable2faHelp, + Actions, + OkSuspended, + OkUnsuspended, + OkAdminOn, + OkAdminOff, + Ok2faDisabled, + ErrSelf, + ErrNoEmail, + AccountSuspended, + Dismiss, + Health, + DataDirectory, + BackupDirectory, + DatabaseFile, + RepoStorage, + Free, + CiQueue, + QueuedJobs, + RunnersOnline, + MailQueue, + Pending, + Failed, + LastBackup, + Replication, + Uptime, + Version, + NotConfigured, + Unavailable, + Never, + Ok, + Error, + Lagging, + HealthIntro, +} + +pub fn t(lang: Lang, key: A) -> &'static str { + use A::*; + use Lang::*; + match (key, lang) { + (Status, En) => "Status", + (Status, Tr) => "Durum", + (Active, En) => "Active", + (Active, Tr) => "Etkin", + (Suspended, En) => "Suspended", + (Suspended, Tr) => "Askıda", + (LastLogin, En) => "Last sign-in", + (LastLogin, Tr) => "Son giriş", + (Repositories, En) => "Repositories", + (Repositories, Tr) => "Depolar", + (TwoFactor, En) => "Two-factor", + (TwoFactor, Tr) => "İki adımlı doğrulama", + (On, En) => "On", + (On, Tr) => "Açık", + (Off, En) => "Off", + (Off, Tr) => "Kapalı", + (Administrator, En) => "Administrator", + (Administrator, Tr) => "Yönetici", + (Suspend, En) => "Suspend", + (Suspend, Tr) => "Askıya al", + (Unsuspend, En) => "Lift suspension", + (Unsuspend, Tr) => "Askıyı kaldır", + (SuspendReason, En) => "Reason shown on the login page", + (SuspendReason, Tr) => "Giriş sayfasında gösterilen neden", + (SuspendHelp, En) => { + "Signs the user out everywhere and stops their tokens and keys, including git over SSH and HTTP." + } + (SuspendHelp, Tr) => { + "Kullanıcının tüm oturumlarını kapatır; belirteçlerini ve anahtarlarını (SSH ve HTTP üzerinden git dahil) durdurur." + } + (GrantAdmin, En) => "Make administrator", + (GrantAdmin, Tr) => "Yönetici yap", + (RevokeAdmin, En) => "Remove administrator", + (RevokeAdmin, Tr) => "Yöneticiliği kaldır", + (AdminHelp, En) => "The last administrator cannot be demoted.", + (AdminHelp, Tr) => "Son yönetici yetkisiz bırakılamaz.", + (ResetPassword, En) => "Reset password", + (ResetPassword, Tr) => "Parolayı sıfırla", + (GenerateLink, En) => "Generate reset link", + (GenerateLink, Tr) => "Sıfırlama bağlantısı üret", + (ResetHelp, En) => { + "Makes a one-time link that works for an hour. Their current sessions are signed out." + } + (ResetHelp, Tr) => { + "Bir saat geçerli, tek kullanımlık bir bağlantı üretir. Mevcut oturumları kapatılır." + } + (ResetLinkReady, En) => "One-time reset link. It is shown only now:", + (ResetLinkReady, Tr) => "Tek kullanımlık sıfırlama bağlantısı. Yalnızca şimdi gösterilir:", + (Disable2fa, En) => "Disable two-factor", + (Disable2fa, Tr) => "İki adımlı doğrulamayı kapat", + (Disable2faHelp, En) => "For a locked-out user. Clears the secret and the recovery codes.", + (Disable2faHelp, Tr) => { + "Hesabına giremeyen kullanıcı için. Sırrı ve kurtarma kodlarını siler." + } + (Actions, En) => "Actions", + (Actions, Tr) => "İşlemler", + (OkSuspended, En) => "Account suspended.", + (OkSuspended, Tr) => "Hesap askıya alındı.", + (OkUnsuspended, En) => "Suspension lifted.", + (OkUnsuspended, Tr) => "Askı kaldırıldı.", + (OkAdminOn, En) => "Administrator rights granted.", + (OkAdminOn, Tr) => "Yönetici yetkisi verildi.", + (OkAdminOff, En) => "Administrator rights removed.", + (OkAdminOff, Tr) => "Yönetici yetkisi kaldırıldı.", + (Ok2faDisabled, En) => "Two-factor disabled.", + (Ok2faDisabled, Tr) => "İki adımlı doğrulama kapatıldı.", + (ErrSelf, En) => "You cannot do this to your own account.", + (ErrSelf, Tr) => "Bunu kendi hesabınıza yapamazsınız.", + (ErrNoEmail, En) => "Nothing to do.", + (ErrNoEmail, Tr) => "Yapılacak bir şey yok.", + (AccountSuspended, En) => "This account is suspended.", + (AccountSuspended, Tr) => "Bu hesap askıya alındı.", + (Dismiss, En) => "Dismiss", + (Dismiss, Tr) => "Kapat", + (Health, En) => "Health", + (Health, Tr) => "Sağlık", + (DataDirectory, En) => "Data directory", + (DataDirectory, Tr) => "Veri dizini", + (BackupDirectory, En) => "Backup directory", + (BackupDirectory, Tr) => "Yedek dizini", + (DatabaseFile, En) => "Database file", + (DatabaseFile, Tr) => "Veritabanı dosyası", + (RepoStorage, En) => "Repositories on disk", + (RepoStorage, Tr) => "Diskteki depolar", + (Free, En) => "free of", + (Free, Tr) => "boş, toplam", + (CiQueue, En) => "CI queue", + (CiQueue, Tr) => "CI kuyruğu", + (QueuedJobs, En) => "queued jobs", + (QueuedJobs, Tr) => "bekleyen iş", + (RunnersOnline, En) => "runners online", + (RunnersOnline, Tr) => "çalıştırıcı çevrimiçi", + (MailQueue, En) => "Mail queue", + (MailQueue, Tr) => "Posta kuyruğu", + (Pending, En) => "pending", + (Pending, Tr) => "bekleyen", + (Failed, En) => "failed", + (Failed, Tr) => "başarısız", + (LastBackup, En) => "Last backup", + (LastBackup, Tr) => "Son yedek", + (Replication, En) => "Replication", + (Replication, Tr) => "Çoğaltma", + (Uptime, En) => "Uptime", + (Uptime, Tr) => "Çalışma süresi", + (Version, En) => "Version", + (Version, Tr) => "Sürüm", + (NotConfigured, En) => "Not configured", + (NotConfigured, Tr) => "Ayarlanmamış", + (Unavailable, En) => "Unavailable", + (Unavailable, Tr) => "Alınamadı", + (Never, En) => "Never", + (Never, Tr) => "Hiç", + (Ok, En) => "OK", + (Ok, Tr) => "Tamam", + (Error, En) => "Error", + (Error, Tr) => "Hata", + (Lagging, En) => "Lagging", + (Lagging, Tr) => "Geride", + (HealthIntro, En) => "Read when the page loads. Reload the page for fresh numbers.", + (HealthIntro, Tr) => "Sayfa açılırken okunur. Güncel değerler için sayfayı yenileyin.", + } +} + +/// The login page message for a suspended account, with the admin's reason when there is one. +pub fn suspended_message(lang: Lang, reason: &str) -> String { + let base = t(lang, A::AccountSuspended); + if reason.is_empty() { + base.to_owned() + } else { + match lang { + Lang::En => format!("{base} Reason: {reason}"), + Lang::Tr => format!("{base} Neden: {reason}"), + } + } +} + +/// `3d 4h`, `5h 2m` or `7m`, for the uptime tile. +pub fn duration_short(secs: u64) -> String { + let (d, h, m) = (secs / 86_400, secs % 86_400 / 3_600, secs % 3_600 / 60); + if d > 0 { + format!("{d}d {h}h") + } else if h > 0 { + format!("{h}h {m}m") + } else { + format!("{m}m") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn duration_short_picks_the_two_largest_units() { + assert_eq!(duration_short(90_000), "1d 1h"); + assert_eq!(duration_short(7_500), "2h 5m"); + assert_eq!(duration_short(420), "7m"); + } + + #[test] + fn suspended_message_carries_the_reason() { + assert_eq!( + suspended_message(Lang::En, "spam"), + "This account is suspended. Reason: spam" + ); + assert_eq!( + suspended_message(Lang::En, ""), + "This account is suspended." + ); + } +} diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index cf437fa..9f1e184 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -18,6 +18,7 @@ use topcoat::router::request::headers; use forge_core::User; pub mod accents; +pub mod accounts; pub mod admin; pub mod authoring; pub mod browse; diff --git a/crates/forge-web/src/mail/account.rs b/crates/forge-web/src/mail/account.rs index 400b91a..2220359 100644 --- a/crates/forge-web/src/mail/account.rs +++ b/crates/forge-web/src/mail/account.rs @@ -76,3 +76,30 @@ pub async fn send_invite( .await?; Ok(()) } + +/// Queues a notice that the password changed, to the user's verified address. A user without a +/// verified address gets nothing. `stamp` keeps two changes from sharing one queue key. +pub async fn send_password_changed( + state: &AppState, + user: &User, + stamp: &str, +) -> forge_core::Result<()> { + let Some(address) = user.email.as_deref() else { + return Ok(()); + }; + if !state.store.email_is_verified(&user.id).await? { + return Ok(()); + } + let (subject, body) = templates::password_changed(&user.username); + enqueue( + state, + &format!("pwchanged:{}:{stamp}", user.id), + MailKind::Other, + Some(&user.id), + address, + &subject, + &body, + ) + .await?; + Ok(()) +} diff --git a/crates/forge-web/src/mail/templates.rs b/crates/forge-web/src/mail/templates.rs index f95fa56..7ebfb5c 100644 --- a/crates/forge-web/src/mail/templates.rs +++ b/crates/forge-web/src/mail/templates.rs @@ -133,6 +133,18 @@ pub fn password_reset(username: &str, link: &str) -> (String, String) { ) } +/// The notice sent after a password change. +pub fn password_changed(username: &str) -> (String, String) { + ( + "Your forge password was changed".to_owned(), + format!( + "Hi {username},\n\nThe password of your forge account was just changed and your \ + other sessions were signed out. If that was you, nothing more to do. If it was \ + not you, reset your password now and contact the administrator.\n" + ), + ) +} + /// The email verification mail. The link works once and for 24 hours. pub fn email_verify(username: &str, link: &str) -> (String, String) { ( diff --git a/crates/forge-web/src/pages/account_tools_tests.rs b/crates/forge-web/src/pages/account_tools_tests.rs new file mode 100644 index 0000000..bde7b5f --- /dev/null +++ b/crates/forge-web/src/pages/account_tools_tests.rs @@ -0,0 +1,347 @@ +//! Tests for admin account tools: suspension, admin flag, reset link, 2FA reset, the announcement +//! banner and the health page. + +use forge_core::Store; +use forge_core::config::BannerConfig; +use topcoat::router::request::Request; +use topcoat::router::{Body, Router, to_bytes}; + +use crate::auth::SESSION_COOKIE; +use crate::test_support::{app_router, create_session, test_state}; + +const ADMIN_TOKEN: &str = "tools-admin-session"; +const USER_TOKEN: &str = "tools-user-session"; +const CSRF: &str = "tools-csrf"; + +struct Fx { + store: Store, + router: Router, + user_id: String, + admin_id: String, +} + +async fn fixture(dir: &std::path::Path, banner: Option) -> Fx { + let mut state = test_state(dir).await; + if let Some(banner) = banner { + let mut config = (*state.config).clone(); + config.banner = banner; + state.set_config(config); + } + let store = state.store.clone(); + let admin = store.create_user("root", None, "h", true).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); + create_session(&store, &admin.id, ADMIN_TOKEN, CSRF).await; + create_session(&store, &user.id, USER_TOKEN, CSRF).await; + Fx { + store, + router: app_router(state), + user_id: user.id, + admin_id: admin.id, + } +} + +async fn send( + router: &Router, + method: &str, + uri: &str, + token: Option<&str>, + form: Option, +) -> (u16, String) { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(token) = token { + builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); + } + let body = match form { + Some(form) => { + builder = builder.header("content-type", "application/x-www-form-urlencoded"); + Body::from(form) + } + None => Body::empty(), + }; + let res = router.handle(builder.body(body).unwrap()).await; + let status = res.status().as_u16(); + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); + (status, String::from_utf8_lossy(&bytes).into_owned()) +} + +fn csrf(extra: &str) -> Option { + Some(format!("csrf={CSRF}{extra}")) +} + +#[tokio::test] +async fn admin_pages_are_404_for_non_admins() { + let dir = tempfile::tempdir().unwrap(); + let fx = fixture(dir.path(), None).await; + let detail = format!("/admin/users/{}", fx.user_id); + for uri in ["/admin/health", detail.as_str()] { + assert_eq!( + send(&fx.router, "GET", uri, Some(USER_TOKEN), None).await.0, + 404 + ); + assert_eq!(send(&fx.router, "GET", uri, None, None).await.0, 404); + assert_eq!( + send(&fx.router, "GET", uri, Some(ADMIN_TOKEN), None) + .await + .0, + 200 + ); + } + let suspend = format!("{detail}/suspend"); + assert_eq!( + send(&fx.router, "POST", &suspend, Some(USER_TOKEN), csrf("")) + .await + .0, + 404 + ); +} + +#[tokio::test] +async fn suspending_needs_csrf_and_is_audited() { + let dir = tempfile::tempdir().unwrap(); + let fx = fixture(dir.path(), None).await; + let uri = format!("/admin/users/{}/suspend", fx.user_id); + let (status, _) = send( + &fx.router, + "POST", + &uri, + Some(ADMIN_TOKEN), + Some("csrf=wrong&reason=spam".into()), + ) + .await; + assert_eq!(status, 403); + assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none()); + + let (status, _) = send( + &fx.router, + "POST", + &uri, + Some(ADMIN_TOKEN), + csrf("&reason=spam"), + ) + .await; + assert_eq!(status, 303); + let suspension = fx.store.suspension(&fx.user_id).await.unwrap().unwrap(); + assert_eq!(suspension.reason, "spam"); + // The user's session is gone and a settings page now bounces them. + let (status, _) = send( + &fx.router, + "GET", + "/settings/security", + Some(USER_TOKEN), + None, + ) + .await; + assert_ne!(status, 200); + let page = send( + &fx.router, + "GET", + &format!("/admin/users/{}", fx.user_id), + Some(ADMIN_TOKEN), + None, + ) + .await + .1; + assert!(page.contains("spam")); + + let (status, _) = send( + &fx.router, + "POST", + &format!("/admin/users/{}/unsuspend", fx.user_id), + Some(ADMIN_TOKEN), + csrf(""), + ) + .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; + let base = format!("/admin/users/{}", fx.admin_id); + let (status, body) = send( + &fx.router, + "POST", + &format!("{base}/admin"), + Some(ADMIN_TOKEN), + csrf("&admin=0"), + ) + .await; + assert_eq!(status, 200); + 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; + let (status, body) = send( + &fx.router, + "POST", + &format!("/admin/users/{}/reset-link", fx.user_id), + Some(ADMIN_TOKEN), + csrf(""), + ) + .await; + assert_eq!(status, 200); + let at = body.find("https://forge.test/reset/").expect("reset link"); + let token: String = body[at + "https://forge.test/reset/".len()..] + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + assert!(fx.store.reset_token_is_live(&token).await.unwrap()); + assert!( + fx.store + .list_sessions(&fx.user_id) + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn disabling_two_factor_clears_it() { + let dir = tempfile::tempdir().unwrap(); + let fx = fixture(dir.path(), None).await; + fx.store + .set_totp_secret(&fx.user_id, "sealed") + .await + .unwrap(); + fx.store + .enable_totp(&fx.user_id, 1, &["h1".to_owned()]) + .await + .unwrap(); + let (status, _) = send( + &fx.router, + "POST", + &format!("/admin/users/{}/disable-2fa", fx.user_id), + Some(ADMIN_TOKEN), + csrf(""), + ) + .await; + assert_eq!(status, 303); + assert!( + !fx.store + .account_facts(&fx.user_id) + .await + .unwrap() + .two_factor + ); +} + +#[tokio::test] +async fn suspended_user_sees_the_reason_on_the_login_page() { + let dir = tempfile::tempdir().unwrap(); + let state = test_state(dir.path()).await; + let hash = crate::auth::hash_password_async("correct horse battery".into()) + .await + .unwrap(); + let store = state.store.clone(); + let admin = store.create_user("root", None, &hash, true).await.unwrap(); + let user = store + .create_user("tahinli", None, &hash, false) + .await + .unwrap(); + store + .suspend_user(&user.id, "abuse of CI", Some(&admin.id)) + .await + .unwrap(); + let router = app_router(state); + let req = Request::builder() + .method("GET") + .uri("/login") + .body(Body::empty()) + .unwrap(); + let res = router.handle(req).await; + let cookie = res + .headers() + .get_all("set-cookie") + .iter() + .filter_map(|v| v.to_str().ok()) + .find(|raw| raw.starts_with("__Host-forge_precsrf")) + .map(|raw| raw.split(';').next().unwrap().to_owned()) + .unwrap(); + let html = + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned(); + let marker = "name=\"precsrf\" value=\""; + let start = html.find(marker).unwrap() + marker.len(); + let precsrf = &html[start..start + html[start..].find('"').unwrap()]; + let form = + format!("username=tahinli&password=correct%20horse%20battery&next=%2F&precsrf={precsrf}"); + let req = Request::builder() + .method("POST") + .uri("/login") + .header("cookie", cookie) + .header("content-type", "application/x-www-form-urlencoded") + .body(Body::from(form)) + .unwrap(); + let res = router.handle(req).await; + assert_eq!(res.status().as_u16(), 200); + let html = + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned(); + assert!(html.contains("abuse of CI"), "{html}"); + assert!(store.list_sessions(&user.id).await.unwrap().is_empty()); +} + +#[tokio::test] +async fn banner_shows_on_pages_and_a_dismissal_hides_it() { + let dir = tempfile::tempdir().unwrap(); + let banner = BannerConfig { + message: "Maintenance tonight".into(), + level: "warning".into(), + expires: String::new(), + }; + let fx = fixture(dir.path(), Some(banner)).await; + for token in [None, Some(USER_TOKEN)] { + let (status, body) = send(&fx.router, "GET", "/explore", token, None).await; + assert_eq!(status, 200); + assert!(body.contains("site-banner warning"), "{body}"); + assert!(body.contains("Maintenance tonight")); + } + let hash = crate::pages::banner::banner_hash("Maintenance tonight", "warning"); + let req = Request::builder() + .method("GET") + .uri("/explore") + .header("cookie", format!("forge_banner={hash}")) + .body(Body::empty()) + .unwrap(); + let res = fx.router.handle(req).await; + let body = + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned(); + assert!(!body.contains("Maintenance tonight")); + + let req = Request::builder() + .method("POST") + .uri("/-/banner/dismiss") + .header("content-type", "application/x-www-form-urlencoded") + .body(Body::from(format!("hash={hash}&back=%2Fexplore"))) + .unwrap(); + let res = fx.router.handle(req).await; + assert_eq!(res.status().as_u16(), 303); + let set = res + .headers() + .get_all("set-cookie") + .iter() + .filter_map(|v| v.to_str().ok()) + .any(|c| c.starts_with(&format!("forge_banner={hash}"))); + assert!(set); +} + +#[tokio::test] +async fn expired_banner_is_not_shown() { + let dir = tempfile::tempdir().unwrap(); + let banner = BannerConfig { + message: "Old news".into(), + level: "info".into(), + expires: "2020-01-01 00:00".into(), + }; + let fx = fixture(dir.path(), Some(banner)).await; + let (_, body) = send(&fx.router, "GET", "/explore", None, None).await; + assert!(!body.contains("Old news")); +} diff --git a/crates/forge-web/src/pages/admin_health.rs b/crates/forge-web/src/pages/admin_health.rs new file mode 100644 index 0000000..a5029d6 --- /dev/null +++ b/crates/forge-web/src/pages/admin_health.rs @@ -0,0 +1,332 @@ +//! Page: instance health for admins (`/admin/health`). A compact grid of tiles, read when the page +//! loads. Every number is a cheap query or a short external probe (`df`, `du`), so there is no +//! polling; reloading the page, or opening it again, reads fresh values. Non-admins get 404. + +use std::path::Path; +use std::time::Duration; + +use forge_core::mail::MailState; +use forge_core::store::backup_runs::RunKind; +use forge_core::store::replication::DB_SUBJECT; +use forge_core::time::stamp_to_unix; +use forge_core::tz::format_in_tz; +use tokio::process::Command; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::page; +use topcoat::view::{View, component, view}; + +use crate::i18n::accounts::{A, duration_short, t as at}; +use crate::i18n::{self, Lang}; +use crate::pages::admin_users::admin_only; +use crate::state::AppState; +use crate::views::{human_size, now_unix, relative_time, shell}; + +/// One cell of the grid. +struct Tile { + title: &'static str, + big: String, + sub: String, + /// `""`, `ok` or `bad`. + tone: &'static str, + /// Percent of a meter to fill, for disk tiles. + meter: Option, +} + +fn tile(title: &'static str, big: impl Into, sub: impl Into) -> Tile { + Tile { + title, + big: big.into(), + sub: sub.into(), + tone: "", + meter: None, + } +} + +/// `(total, available)` bytes from `df -Pk ` output. +fn parse_df(output: &str) -> Option<(u64, u64)> { + let line = output.lines().nth(1)?; + let fields: Vec<&str> = line.split_whitespace().collect(); + let total: u64 = fields.get(1)?.parse().ok()?; + let avail: u64 = fields.get(3)?.parse().ok()?; + Some((total.saturating_mul(1024), avail.saturating_mul(1024))) +} + +/// Kilobytes from `du -sk ` output, as bytes. +fn parse_du(output: &str) -> Option { + let kb: u64 = output.split_whitespace().next()?.parse().ok()?; + Some(kb.saturating_mul(1024)) +} + +async fn probe(program: &str, args: &[&str], path: &Path, limit: Duration) -> Option { + let run = Command::new(program) + .args(args) + .arg(path) + .stdin(std::process::Stdio::null()) + .kill_on_drop(true) + .output(); + let output = tokio::time::timeout(limit, run).await.ok()?.ok()?; + // `du` exits non-zero on one unreadable entry but still prints a total. + String::from_utf8(output.stdout).ok() +} + +async fn disk(path: &Path) -> Option<(u64, u64)> { + parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?) +} + +async fn tree_size(path: &Path) -> Option { + parse_du(&probe("du", &["-sk"], path, Duration::from_secs(4)).await?) +} + +/// Seconds since the process started, from `/proc` (Linux). `None` elsewhere. +fn uptime_secs() -> Option { + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; + // Fields after the `)` that closes the command name; starttime is field 22 overall. + let rest = stat.rsplit_once(')')?.1; + let start_ticks: f64 = rest.split_whitespace().nth(19)?.parse().ok()?; + let system: f64 = std::fs::read_to_string("/proc/uptime") + .ok()? + .split_whitespace() + .next()? + .parse() + .ok()?; + // The kernel's clock tick is 100 Hz on every Linux target this runs on. + Some((system - start_ticks / 100.0).max(0.0) as u64) +} + +fn disk_tile(lang: Lang, title: &'static str, space: Option<(u64, u64)>, label: &str) -> Tile { + match space { + Some((total, avail)) => { + let used = total.saturating_sub(avail); + let pct = used + .saturating_mul(100) + .checked_div(total) + .map_or(0, |p| u8::try_from(p).unwrap_or(100)); + Tile { + title, + big: human_size(lang, avail), + sub: format!( + "{} {} - {label}", + at(lang, A::Free), + human_size(lang, total) + ), + tone: if pct >= 90 { "bad" } else { "" }, + meter: Some(pct), + } + } + None => tile(title, at(lang, A::Unavailable), label), + } +} + +async fn tiles(state: &AppState, lang: Lang, tz: &str) -> Result> { + let live = state.live(); + let now = now_unix(); + let data_dir = live.data_dir.clone(); + let repos_dir = data_dir.join("repos"); + let backup_dir = live.backup.dir.clone(); + let database = live.database.clone(); + let backup_on = !backup_dir.as_os_str().is_empty(); + let (data_space, repo_bytes, backup_space) = + tokio::join!(disk(&data_dir), tree_size(&repos_dir), async { + if backup_on { + disk(&backup_dir).await + } else { + None + } + }); + let counts = state.store.health_counts().await?; + let mail = state + .store + .mail_state_counts(&forge_core::time::now_stamp()) + .await?; + let mail_n = |states: &[MailState]| -> u32 { + mail.iter() + .filter(|(s, _)| states.contains(s)) + .map(|(_, n)| *n) + .sum() + }; + let pending = mail_n(&[MailState::Queued, MailState::Retrying, MailState::Sending]); + let failed = mail_n(&[MailState::Failed]); + let db_bytes = std::fs::metadata(&database).map(|m| m.len()).ok(); + + let mut out = Vec::new(); + out.push(disk_tile( + lang, + at(lang, A::DataDirectory), + data_space, + &data_dir.to_string_lossy(), + )); + out.push(if backup_on { + disk_tile( + lang, + at(lang, A::BackupDirectory), + backup_space, + &backup_dir.to_string_lossy(), + ) + } else { + tile(at(lang, A::BackupDirectory), at(lang, A::NotConfigured), "") + }); + out.push(tile( + at(lang, A::DatabaseFile), + db_bytes.map_or_else( + || at(lang, A::Unavailable).to_owned(), + |b| human_size(lang, b), + ), + database.to_string_lossy(), + )); + out.push(tile( + at(lang, A::Repositories), + counts.repos.to_string(), + match repo_bytes { + Some(b) => format!("{}: {}", at(lang, A::RepoStorage), human_size(lang, b)), + None => at(lang, A::Unavailable).to_owned(), + }, + )); + out.push(tile( + at(lang, A::CiQueue), + format!("{} {}", counts.queued_jobs, at(lang, A::QueuedJobs)), + format!( + "{} / {} {}", + counts.runners_online, + counts.runners_total, + at(lang, A::RunnersOnline) + ), + )); + let mut mail_tile = tile( + at(lang, A::MailQueue), + format!("{pending} {}", at(lang, A::Pending)), + format!("{failed} {}", at(lang, A::Failed)), + ); + if failed > 0 { + mail_tile.tone = "bad"; + } + out.push(mail_tile); + + let backup = if backup_on { + state.store.last_run(RunKind::Backup).await? + } else { + None + }; + out.push(match backup { + Some(run) => { + let at_unix = stamp_to_unix(&run.started_at).unwrap_or(0); + let mut t = tile( + at(lang, A::LastBackup), + match run.ok { + Some(true) => at(lang, A::Ok), + Some(false) => at(lang, A::Failed), + None => at(lang, A::Pending), + }, + format!( + "{} ({})", + format_in_tz(at_unix, tz), + relative_time(lang, at_unix, now) + ), + ); + t.tone = match run.ok { + Some(true) => "ok", + Some(false) => "bad", + None => "", + }; + t + } + None if backup_on => tile(at(lang, A::LastBackup), at(lang, A::Never), ""), + None => tile(at(lang, A::LastBackup), at(lang, A::NotConfigured), ""), + }); + + let replicating = !live.replication.target.trim().is_empty(); + out.push(if replicating { + match state.store.replication_status(DB_SUBJECT).await? { + Some(status) => { + let ok_unix = status.last_ok_at.as_deref().and_then(stamp_to_unix); + let window = live.replication.db_snapshot_minutes.saturating_mul(120); + let lagging = ok_unix.is_none_or(|t| (now - t).max(0) as u64 > window); + let errored = status.last_error.is_some(); + let mut t = tile( + at(lang, A::Replication), + if errored { + at(lang, A::Error) + } else if lagging { + at(lang, A::Lagging) + } else { + at(lang, A::Ok) + }, + ok_unix.map_or_else( + || at(lang, A::Never).to_owned(), + |t| relative_time(lang, t, now), + ), + ); + t.tone = if errored || lagging { "bad" } else { "ok" }; + t + } + None => tile(at(lang, A::Replication), at(lang, A::Never), ""), + } + } else { + tile(at(lang, A::Replication), at(lang, A::NotConfigured), "") + }); + out.push(tile( + at(lang, A::Uptime), + uptime_secs().map_or_else(|| at(lang, A::Unavailable).to_owned(), duration_short), + "", + )); + out.push(tile( + at(lang, A::Version), + env!("CARGO_PKG_VERSION"), + env!("FORGE_BUILD_SHA"), + )); + Ok(out) +} + +#[component] +async fn health_view(lang: Lang, tiles: Vec) -> Result { + Ok(view! { +
+

(at(lang, A::Health))

+

(at(lang, A::HealthIntro))

+
+
+ for t in tiles.into_iter() { +
+

(t.title)

+
(t.big.as_str())
+ if !t.sub.is_empty() { +
(t.sub.as_str())
+ } + if let Some(pct) = t.meter { + + } +
+ } +
+ }) +} + +#[page("/admin/health")] +async fn health_page(cx: &Cx) -> Result { + let viewer = admin_only(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let tiles = tiles(state, lang, &viewer.0.timezone).await?; + let title = at(lang, A::Health); + Ok(view! { + shell(title: title, viewer: Some(&viewer), health_view(lang: lang, tiles: tiles)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn df_output_parses_to_bytes() { + let out = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/sda1 1000 400 600 40% /\n"; + assert_eq!(parse_df(out), Some((1000 * 1024, 600 * 1024))); + assert_eq!(parse_df("garbage"), None); + } + + #[test] + fn du_output_parses_to_bytes() { + assert_eq!(parse_du("12\t/data/repos\n"), Some(12 * 1024)); + assert_eq!(parse_du(""), None); + } +} diff --git a/crates/forge-web/src/pages/admin_user_detail.rs b/crates/forge-web/src/pages/admin_user_detail.rs new file mode 100644 index 0000000..f4265ce --- /dev/null +++ b/crates/forge-web/src/pages/admin_user_detail.rs @@ -0,0 +1,421 @@ +//! Page: one account for admins (`/admin/users/{id}`). Facts, suspend or lift, admin flag, a +//! one-time password reset link and disabling two-factor for a locked-out user. Every action is +//! audited. Non-admins get 404, like the rest of the admin area. + +use forge_core::names::normalize_name; +use forge_core::store::suspension::{AccountFacts, Suspension}; +use forge_core::store::user_delete::GHOST_USERNAME; +use forge_core::tz::format_in_tz; +use forge_core::{AuditAction, User}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{forbidden, not_found, see_other}; +use topcoat::router::{page, path_param_segment, query_params}; +use topcoat::view::{View, component, view}; + +use crate::audit::{self, Actor, Target}; +use crate::auth::{check_csrf, two_factor_enabled}; +use crate::i18n::accounts::{A, t as at}; +use crate::i18n::admin::{self as g, K}; +use crate::i18n::{self, Key, Lang}; +use crate::pages::admin_users::admin_only; +use crate::pages::issues_list::stamp_unix; +use crate::state::AppState; +use crate::views::{alert, enc, shell, user_facing_message}; + +#[query_params(error = bad_request)] +pub(crate) struct DoneQuery { + done: Option, +} + +#[derive(Deserialize)] +struct ActionForm { + #[serde(default)] + csrf: String, + #[serde(default)] + reason: String, + /// `1` grants administrator rights, anything else removes them. + #[serde(default)] + admin: String, +} + +struct Detail { + target: User, + facts: AccountFacts, + suspension: Option, +} + +/// What the page says above the facts after an action. +#[derive(Default)] +struct Notice { + done: Option<&'static str>, + error: Option, + link: Option, +} + +#[derive(Clone, Copy)] +enum Action { + Suspend, + Unsuspend, + SetAdmin, + ResetLink, + Disable2fa, +} + +fn is_ghost(user: &User) -> bool { + normalize_name(&user.username) == GHOST_USERNAME +} + +async fn load(cx: &Cx) -> Result { + let store = &app_context::(cx).store; + let id = path_param_segment(cx, "user_id").to_owned(); + let Some(target) = store.user_by_id(&id).await? else { + return Err(not_found().into()); + }; + if target.is_org() || is_ghost(&target) { + return Err(not_found().into()); + } + Ok(Detail { + facts: store.account_facts(&target.id).await?, + suspension: store.suspension(&target.id).await?, + target, + }) +} + +fn done_text(lang: Lang, done: &str) -> Option<&'static str> { + Some(match done { + "suspended" => at(lang, A::OkSuspended), + "unsuspended" => at(lang, A::OkUnsuspended), + "admin_on" => at(lang, A::OkAdminOn), + "admin_off" => at(lang, A::OkAdminOff), + "tfa_off" => at(lang, A::Ok2faDisabled), + _ => return None, + }) +} + +fn when(stamp: Option<&str>, tz: &str, lang: Lang) -> String { + match stamp { + Some(s) => format_in_tz(stamp_unix(s), tz), + None => at(lang, A::Never).to_owned(), + } +} + +#[component] +async fn detail_body( + lang: Lang, + csrf: &str, + tz: &str, + viewer_id: &str, + detail: Detail, + notice: Notice, +) -> Result { + let Detail { + target, + facts, + suspension, + } = detail; + let base = format!("/admin/users/{}", enc(&target.id)); + let own = target.id == viewer_id; + let created = format_in_tz(stamp_unix(&target.created_at), tz); + let last_login = when(facts.last_login.as_deref(), tz, lang); + let repos = facts.repo_count.to_string(); + let suspended = suspension.is_some(); + let status = if suspended { + at(lang, A::Suspended) + } else { + at(lang, A::Active) + }; + let tfa = if facts.two_factor { + at(lang, A::On) + } else { + at(lang, A::Off) + }; + let role = if target.is_admin { + at(lang, A::Administrator) + } else { + g::t(lang, K::RoleUser) + }; + let reason = suspension + .as_ref() + .map(|s| s.reason.clone()) + .unwrap_or_default(); + let email = target.email.clone().unwrap_or_default(); + let is_admin = target.is_admin; + let tfa_on = facts.two_factor; + let suspend_action = format!("{base}/suspend"); + let unsuspend_action = format!("{base}/unsuspend"); + let admin_action = format!("{base}/admin"); + let reset_action = format!("{base}/reset-link"); + let tfa_action = format!("{base}/disable-2fa"); + let delete_href = format!("{base}/delete"); + let Notice { done, error, link } = notice; + Ok(view! { +
+

(target.username.as_str())

+
+
+ if let Some(message) = done { +

(message)

+ } + if let Some(message) = error { + alert(message: message.as_str()) + } + if let Some(link) = link { +

(at(lang, A::ResetLinkReady))

+ (link.as_str()) + } +
+
(at(lang, A::Status))
(status)
+
(i18n::t(lang, Key::Email))
(email.as_str())
+
(g::t(lang, K::Role))
(role)
+
(i18n::t(lang, Key::Created))
(created.as_str())
+
(at(lang, A::LastLogin))
(last_login.as_str())
+
(at(lang, A::Repositories))
(repos.as_str())
+
(at(lang, A::TwoFactor))
(tfa)
+
+
+
+

(at(lang, A::Actions))

+
+
+

(if suspended { at(lang, A::Unsuspend) } else { at(lang, A::Suspend) })

+ if suspended { +

(reason.as_str())

+
+ + +
+ } else if own { +

(at(lang, A::ErrSelf))

+ } else { +

(at(lang, A::SuspendHelp))

+
+ + + +
+ } +
+
+

(at(lang, A::Administrator))

+

(at(lang, A::AdminHelp))

+
+ + + +
+
+
+

(at(lang, A::ResetPassword))

+

(at(lang, A::ResetHelp))

+
+ + +
+
+
+

(at(lang, A::Disable2fa))

+

(at(lang, A::Disable2faHelp))

+ if tfa_on { +
+ + +
+ } else { +

(at(lang, A::Off))

+ } +
+
+ +
+ }) +} + +#[page("/admin/users/{user_id}")] +async fn detail_page(cx: &Cx) -> Result { + let viewer = admin_only(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let query = query_params::(cx)?; + let detail = load(cx).await?; + let notice = Notice { + done: query.done.as_deref().and_then(|d| done_text(lang, d)), + ..Notice::default() + }; + let csrf = viewer.1.csrf_token.clone(); + let title = detail.target.username.clone(); + Ok(view! { + shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), tz: viewer.0.timezone.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) + }) +} + +/// Outcome of an action: a redirect key on success, or a message to show on the page. +enum Outcome { + Done(&'static str), + Link(String), + Refused(String), +} + +async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome, Detail)> { + let viewer = admin_only(cx).await?; + if !check_csrf(&viewer.1, &form.csrf) { + return Err(forbidden().into()); + } + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let store = &state.store; + let detail = load(cx).await?; + let target = &detail.target; + let audit = |action: AuditAction, data: serde_json::Value| { + audit::record( + store, + Some(cx), + Actor::User(&viewer.0), + action, + Target { + kind: "user", + id: &target.id, + name: &target.username, + }, + data, + ) + }; + let refused = |e: forge_core::Error| -> Result { + match user_facing_message(&e) { + Some(message) => Ok(Outcome::Refused(message)), + None => Err(e.into()), + } + }; + let outcome = match action { + Action::Suspend => { + if target.id == viewer.0.id { + Outcome::Refused(at(lang, A::ErrSelf).to_owned()) + } else { + match store + .suspend_user(&target.id, &form.reason, Some(&viewer.0.id)) + .await + { + Ok(()) => { + audit( + AuditAction::UserSuspended, + serde_json::json!({ "reason": form.reason.trim() }), + ) + .await; + Outcome::Done("suspended") + } + Err(e) => refused(e)?, + } + } + } + Action::Unsuspend => { + if store.unsuspend_user(&target.id).await? { + audit(AuditAction::UserUnsuspended, serde_json::Value::Null).await; + } + Outcome::Done("unsuspended") + } + Action::SetAdmin => { + let grant = form.admin == "1"; + match store.set_admin(&target.id, grant).await { + Ok(()) => { + let kind = if grant { + AuditAction::AdminGranted + } else { + AuditAction::AdminRevoked + }; + audit(kind, serde_json::Value::Null).await; + Outcome::Done(if grant { "admin_on" } else { "admin_off" }) + } + Err(e) => refused(e)?, + } + } + Action::ResetLink => { + let token = store.create_reset_token(&target.id).await?; + store.delete_user_sessions(&target.id).await?; + audit( + AuditAction::PasswordResetByAdmin, + serde_json::json!({ "method": "link" }), + ) + .await; + let base = state.config.base_url.trim_end_matches('/'); + Outcome::Link(format!("{base}/reset/{token}")) + } + Action::Disable2fa => { + if two_factor_enabled(store, &target.id).await? { + store.disable_totp(&target.id).await?; + audit(AuditAction::TotpDisabledByAdmin, serde_json::Value::Null).await; + Outcome::Done("tfa_off") + } else { + Outcome::Refused(at(lang, A::ErrNoEmail).to_owned()) + } + } + }; + let detail = if matches!(outcome, Outcome::Done(_)) { + detail + } else { + // Reload so a refused or link outcome shows the current state. + load(cx).await? + }; + Ok((outcome, detail)) +} + +/// Redirects to the detail page after a success, or renders it with a message. +async fn respond(cx: &Cx, form: ActionForm, action: Action) -> Result { + // `view!` expects the `__cx` binding that `#[page]` provides. + let __cx = cx; + let (outcome, detail) = perform(cx, &form, action).await?; + let viewer = admin_only(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let notice = match outcome { + Outcome::Done(key) => { + let id = enc(&detail.target.id).to_string(); + return Err(see_other(format!("/admin/users/{id}?done={key}")).into()); + } + Outcome::Link(link) => Notice { + link: Some(link), + ..Notice::default() + }, + Outcome::Refused(message) => Notice { + error: Some(message), + ..Notice::default() + }, + }; + let csrf = viewer.1.csrf_token.clone(); + let title = detail.target.username.clone(); + Ok(view! { + shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), tz: viewer.0.timezone.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) + }) +} + +#[page(POST "/admin/users/{user_id}/suspend")] +async fn suspend(cx: &Cx, Form(form): Form) -> Result { + respond(cx, form, Action::Suspend).await +} + +#[page(POST "/admin/users/{user_id}/unsuspend")] +async fn unsuspend(cx: &Cx, Form(form): Form) -> Result { + respond(cx, form, Action::Unsuspend).await +} + +#[page(POST "/admin/users/{user_id}/admin")] +async fn set_admin(cx: &Cx, Form(form): Form) -> Result { + respond(cx, form, Action::SetAdmin).await +} + +#[page(POST "/admin/users/{user_id}/reset-link")] +async fn reset_link(cx: &Cx, Form(form): Form) -> Result { + respond(cx, form, Action::ResetLink).await +} + +#[page(POST "/admin/users/{user_id}/disable-2fa")] +async fn disable_2fa(cx: &Cx, Form(form): Form) -> Result { + respond(cx, form, Action::Disable2fa).await +} diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index 87e5f8f..3c6078d 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -73,7 +73,13 @@ async fn users_view( for user in users.into_iter() { - (user.username.clone()) + + if user.is_org() || is_ghost(&user) { + (user.username.clone()) + } else { + (user.username.clone()) + } + (user.email.clone().unwrap_or_default()) (if user.is_org() { g::t(lang, K::RoleOrganization) } else if user.is_admin { g::t(lang, K::RoleAdmin) } else { g::t(lang, K::RoleUser) }) (format_in_tz(stamp_unix(&user.created_at), tz)) diff --git a/crates/forge-web/src/pages/banner.rs b/crates/forge-web/src/pages/banner.rs new file mode 100644 index 0000000..d1e6909 --- /dev/null +++ b/crates/forge-web/src/pages/banner.rs @@ -0,0 +1,133 @@ +//! The site announcement banner. The admin sets it in the server settings (`banner.*`, live), and +//! the shell shows it under the header on every page. A visitor dismisses it with +//! `POST /-/banner/dismiss`, which stores the hash of the message in the `forge_banner` cookie, so a +//! changed message shows again. + +use std::time::Duration; + +use forge_core::config::BannerConfig; +use forge_core::token::hash_token; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, try_app_context}; +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::route; + +use crate::pages::theme_cookie::safe_back; +use crate::state::AppState; + +/// Name of the dismissal cookie. +pub const BANNER_COOKIE: &str = "forge_banner"; + +const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60); + +/// What the shell draws. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BannerView { + pub message: String, + pub warning: bool, + pub hash: String, +} + +/// Short stable id of a message and level. +pub fn banner_hash(message: &str, level: &str) -> String { + hash_token(&format!("{level}\n{message}"))[..16].to_owned() +} + +/// The banner to show at `now`, or `None` when it is off, expired or dismissed (`dismissed` is the +/// cookie value). +pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option { + if !config.active_at(now) { + return None; + } + let message = config.message.trim().to_owned(); + let hash = banner_hash(&message, &config.level); + if dismissed == Some(hash.as_str()) { + return None; + } + Some(BannerView { + message, + warning: config.level == "warning", + hash, + }) +} + +/// The banner for this request, read from the live settings and the cookie. +pub fn current(cx: &Cx) -> Option { + let state = try_app_context::(cx)?; + let live = state.live(); + if live.banner.message.trim().is_empty() { + return None; + } + let cookie = cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()); + view_for(&live.banner, crate::views::now_unix(), cookie.as_deref()) +} + +#[derive(Deserialize)] +struct DismissForm { + #[serde(default)] + hash: String, + #[serde(default)] + back: String, +} + +#[route(POST "/-/banner/dismiss")] +async fn dismiss(cx: &Cx, Form(form): Form) -> Result { + let hash_ok = form.hash.len() == 16 && form.hash.bytes().all(|b| b.is_ascii_hexdigit()); + if hash_ok { + let max_age = + time::Duration::seconds(i64::try_from(BANNER_COOKIE_TTL.as_secs()).unwrap_or(i64::MAX)); + cookies(cx).add( + Cookie::build((BANNER_COOKIE, form.hash)) + .path("/") + .secure(true) + .http_only(true) + .same_site(SameSite::Lax) + .max_age(max_age) + .build(), + ); + } + Ok(see_other(safe_back(&form.back))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(message: &str, level: &str, expires: &str) -> BannerConfig { + BannerConfig { + message: message.into(), + level: level.into(), + expires: expires.into(), + } + } + + #[test] + fn empty_and_expired_banners_are_hidden() { + assert!(view_for(&config("", "info", ""), 0, None).is_none()); + let expiry = forge_core::config::parse_banner_expiry("2026-12-31 18:00").unwrap(); + let cfg = config("maintenance", "warning", "2026-12-31 18:00"); + assert!(view_for(&cfg, expiry - 1, None).is_some()); + assert!(view_for(&cfg, expiry, None).is_none()); + } + + #[test] + fn a_dismissed_hash_hides_only_that_message() { + let cfg = config("maintenance tonight", "info", ""); + let shown = view_for(&cfg, 0, None).unwrap(); + assert!(view_for(&cfg, 0, Some(&shown.hash)).is_none()); + let changed = config("maintenance tomorrow", "info", ""); + assert!(view_for(&changed, 0, Some(&shown.hash)).is_some()); + } + + #[test] + fn expiry_parses_utc_minutes() { + assert_eq!( + forge_core::config::parse_banner_expiry("1970-01-02 00:01"), + Some(86_400 + 60) + ); + assert!(forge_core::config::parse_banner_expiry("tomorrow").is_none()); + } +} diff --git a/crates/forge-web/src/pages/login.rs b/crates/forge-web/src/pages/login.rs index 9b35e40..8ff12a4 100644 --- a/crates/forge-web/src/pages/login.rs +++ b/crates/forge-web/src/pages/login.rs @@ -154,7 +154,10 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result json!({ "reason": "throttled" }), ) .await; - (StatusCode::TOO_MANY_REQUESTS, t(lang, Key::ErrThrottled)) + ( + StatusCode::TOO_MANY_REQUESTS, + t(lang, Key::ErrThrottled).to_owned(), + ) } else { // The store folds the name, so the lookup is case-insensitive. // An organization is treated like an unknown name: it never signs in. @@ -169,7 +172,32 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result }; let password_ok = verify_password_async(form.password.clone(), hash).await?; + // Only someone who knows the password learns that the account is suspended. + let suspension = match &user { + Some(user) if password_ok => state.store.suspension(&user.id).await?, + _ => None, + }; match user { + Some(user) if password_ok && suspension.is_some() => { + let reason = suspension.map(|s| s.reason).unwrap_or_default(); + audit::record( + &state.store, + Some(cx), + Actor::Anonymous, + AuditAction::LoginFailed, + Target { + kind: "user", + id: &user.id, + name: &user.username, + }, + json!({ "reason": "suspended" }), + ) + .await; + ( + StatusCode::OK, + crate::i18n::accounts::suspended_message(lang, &reason), + ) + } Some(user) if password_ok => { limiter.clear(&user_key); // With two-factor on, no session yet: park the login until the code is checked. @@ -215,7 +243,7 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result serde_json::Value::Null, ) .await; - (StatusCode::OK, t(lang, Key::ErrInvalidLogin)) + (StatusCode::OK, t(lang, Key::ErrInvalidLogin).to_owned()) } } }; @@ -227,7 +255,7 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result Ok(view! { (status) (headers) - shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: username.as_str(), precsrf: precsrf.as_str(), error: Some(message.to_owned()))) + shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: username.as_str(), precsrf: precsrf.as_str(), error: Some(message))) }) } diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 01838a0..8a3b629 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -1,10 +1,14 @@ //! Server-rendered pages. +#[cfg(test)] +mod account_tools_tests; pub mod admin_backups; +pub mod admin_health; pub mod admin_mail; pub mod admin_replication; pub mod admin_runners; pub mod admin_server; +pub mod admin_user_detail; pub mod admin_users; pub mod archive; pub mod assets; @@ -13,6 +17,7 @@ pub mod authoring; #[cfg(test)] mod authoring_tests; pub mod avatars; +pub mod banner; pub mod blame; pub mod blob; pub mod branches; diff --git a/crates/forge-web/src/pages/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index d0e8116..9ca02e7 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -726,6 +726,15 @@ async fn password_change(cx: &Cx, Form(form): Form) -> Result Config { mail: Default::default(), orgs: Default::default(), self_update: Default::default(), + banner: Default::default(), } } diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 73da7ea..791bd78 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -163,6 +163,9 @@ pub async fn shell( let theme_csrf = viewer.map(|(_, session)| session.csrf_token.clone()); let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); + let banner = crate::pages::banner::current(__cx); + let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); + let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); // The admin area and the user settings swap the global links for their own list. Signed-in only. let mut section = if signed_in { section_for(lang, uri(__cx).path()) @@ -339,6 +342,18 @@ pub async fn shell( (t(lang, Key::LogIn)) } + if let Some(banner) = banner { +
+

(banner.message.as_str())

+
+ + + +
+
+ }
if signed_in {