diff --git a/Cargo.lock b/Cargo.lock index c8c5852..ab2ccc5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -608,7 +608,7 @@ dependencies = [ "aes-gcm", "base64 0.22.1", "hkdf", - "hmac", + "hmac 0.12.1", "percent-encoding", "rand 0.8.8", "sha2 0.10.9", @@ -1306,7 +1306,7 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" dependencies = [ - "hmac", + "hmac 0.12.1", ] [[package]] @@ -1318,6 +1318,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "home" version = "0.5.12" @@ -1648,10 +1657,12 @@ dependencies = [ "chacha20poly1305", "ed25519-dalek", "hex", + "hmac 0.13.0", "ipnet", "rand 0.10.3", "serde", "serde_json", + "sha1 0.11.0", "sha2 0.11.1", "subtle", "tempfile", @@ -1668,12 +1679,15 @@ dependencies = [ name = "im-web" version = "0.1.0" dependencies = [ + "base64 0.23.1", "futures-util", "grass", "hex", "http", "im-core", + "qrcode", "serde", + "serde_json", "sha2 0.11.1", "tempfile", "tokio", @@ -2435,6 +2449,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + [[package]] name = "quote" version = "1.0.47" @@ -2833,6 +2853,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -3821,7 +3852,7 @@ dependencies = [ "httparse", "log", "rand 0.9.5", - "sha1", + "sha1 0.10.7", "thiserror", ] diff --git a/Cargo.toml b/Cargo.toml index 23f6f16..ae234ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,11 +18,14 @@ ed25519-dalek = { version = "3.0.0", features = ["rand_core"] } futures-util = "0.3.34" grass = "0.13.4" hex = "0.4.3" +hmac = "0.13.0" http = "1.5.0" ipnet = "2.12.2" +qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } rand = "0.10.3" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" +sha1 = "0.11.0" sha2 = "0.11.1" subtle = "2.6.1" thiserror = "2.0.21" diff --git a/config/im.example.toml b/config/im.example.toml index 79d1c2b..7d7521c 100644 --- a/config/im.example.toml +++ b/config/im.example.toml @@ -31,3 +31,9 @@ interval_hours = 24 keep = 7 # Dead-man URL pinged after each run. Empty for none. healthcheck_url = "" + +[policy] +# An administrator without two-factor sign-in is sent to enrol it after signing in. +require_2fa_for_admins = true +# Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. +max_sessions = 10 diff --git a/crates/im-core/Cargo.toml b/crates/im-core/Cargo.toml index fdba214..ca4fdc0 100644 --- a/crates/im-core/Cargo.toml +++ b/crates/im-core/Cargo.toml @@ -14,10 +14,12 @@ base64.workspace = true chacha20poly1305.workspace = true ed25519-dalek.workspace = true hex.workspace = true +hmac.workspace = true ipnet.workspace = true rand.workspace = true serde.workspace = true serde_json.workspace = true +sha1.workspace = true sha2.workspace = true subtle.workspace = true thiserror.workspace = true diff --git a/crates/im-core/src/config.rs b/crates/im-core/src/config.rs index 9cec896..72a7393 100644 --- a/crates/im-core/src/config.rs +++ b/crates/im-core/src/config.rs @@ -73,6 +73,28 @@ impl BackupConfig { } } +/// Sign-in policy. These are the file values; a value saved in the admin UI wins over them once that +/// UI exists (`docs/architecture.md` section 7). +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct PolicyConfig { + /// An administrator without two-factor sign-in is sent to enrol it after signing in, and cannot + /// reach the admin pages until they do. + pub require_2fa_for_admins: bool, + /// Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. + /// At least 1. + pub max_sessions: u32, +} + +impl Default for PolicyConfig { + fn default() -> Self { + Self { + require_2fa_for_admins: true, + max_sessions: 10, + } + } +} + /// The whole file. Field names are the TOML keys. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] @@ -96,6 +118,9 @@ pub struct Config { /// Scheduled backups. #[serde(default)] pub backup: BackupConfig, + /// Sign-in policy. + #[serde(default)] + pub policy: PolicyConfig, } impl Config { @@ -144,6 +169,9 @@ impl Config { return Err(Error::Config("[backup] keep must be at least 1".into())); } } + if self.policy.max_sessions == 0 { + return Err(Error::Config("[policy] max_sessions must be at least 1".into())); + } let hc = &self.backup.healthcheck_url; if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { return Err(Error::Config( diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs index 8f89589..7c0adc3 100644 --- a/crates/im-core/src/lib.rs +++ b/crates/im-core/src/lib.rs @@ -5,10 +5,13 @@ pub mod config; pub mod error; +pub mod model; +pub mod names; pub mod password; pub mod secret; pub mod store; pub mod time; pub mod token; +pub mod totp; pub use error::{Error, Result}; diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs new file mode 100644 index 0000000..a6bf9f5 --- /dev/null +++ b/crates/im-core/src/model.rs @@ -0,0 +1,161 @@ +//! Plain data types of the accounts and sessions, as the store returns them. +//! +//! These structs hold what is in the rows and nothing more. Rules that decide what a person may +//! do with them live in the store (as single conditional statements) or in the web layer. +//! Timestamps are the stored text form from `time.rs`. + +/// A person who can sign in. `id` is the OIDC `sub` once OIDC exists, and is never reused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct User { + /// ULID. + pub id: String, + /// The normalised address (trimmed, lowercased). Unique. + pub email: String, + /// Display name, 1 to 100 characters. + pub name: String, + /// Argon2id PHC string. + pub password_hash: String, + /// Instance administrator. + pub is_admin: bool, + /// Set when the account is disabled. A disabled account cannot sign in. + pub disabled_at: Option, + /// The sealed TOTP secret, kept after two-factor sign-in is enabled. + pub totp_secret_sealed: Option, + /// Set when two-factor sign-in is on. + pub totp_enabled_at: Option, + /// The last TOTP step that was accepted. A code of this step or an earlier one is refused. + pub totp_last_step: Option, + /// `en` or `tr`. + pub locale: String, + /// IANA time zone name. + pub zoneinfo: String, + /// `system`, `light` or `dark`. + pub theme: String, + /// MIME type of the stored photo, when there is one. + pub photo_mime: Option, + /// Bumps when the photo changes, so caches can tell two photos apart. + pub picture_version: i64, + /// Creation time. + pub created_at: String, + /// Last change of the row. + pub updated_at: String, +} + +impl User { + /// True when two-factor sign-in is on: the secret is stored and enrolment was confirmed. + pub fn totp_enabled(&self) -> bool { + self.totp_enabled_at.is_some() && self.totp_secret_sealed.is_some() + } + + /// True when the account is disabled. + pub fn is_disabled(&self) -> bool { + self.disabled_at.is_some() + } +} + +/// How a session was authenticated. Stored in `sessions.amr`, and the CHECK constraint accepts +/// exactly these three values. +pub mod amr { + /// Password only. + pub const PASSWORD: &str = "pwd"; + /// Password and a TOTP code. + pub const PASSWORD_TOTP: &str = "pwd otp"; + /// Password and a recovery code. + pub const PASSWORD_RECOVERY: &str = "pwd rc"; +} + +/// A browser session. The cookie holds the token; the row holds only its hash. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Session { + /// ULID. This is the OIDC `sid` once OIDC exists. + pub id: String, + /// The owner. + pub user_id: String, + /// Hex SHA-256 of the cookie token. + pub token_hash: String, + /// Per-session CSRF token. Every state-changing form carries it. + pub csrf_token: String, + /// Creation time (the sign-in time). + pub created_at: String, + /// Absolute expiry. + pub expires_at: String, + /// Last time the session was used. Written at most once every five minutes. + pub last_seen_at: String, + /// Address the session was created from. + pub ip: Option, + /// The `User-Agent` at sign-in, truncated. + pub user_agent: Option, + /// Time of the authentication that created the session. + pub auth_time: String, + /// One of the [`amr`] values. + pub amr: String, +} + +/// What an audit entry is about. The variants are the values stored in `audit_log.action`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AuditAction { + /// The first administrator was created. + SetupDone, + /// A sign-in succeeded (password, or password and a second factor). + LoginSuccess, + /// A sign-in was refused. The data says why. + LoginFailed, + /// A second-factor check was refused. + Login2faFailed, + /// The person signed out. + Logout, + /// The password was changed. + PasswordChanged, + /// Two-factor sign-in was turned on. + TotpEnabled, + /// Two-factor sign-in was turned off. + TotpDisabled, + /// A new set of recovery codes was issued. + RecoveryCodesIssued, + /// One session was ended by its owner. + SessionRevoked, + /// Every session except the current one was ended. + SessionsRevoked, +} + +impl AuditAction { + /// The stored text of the action. + pub fn as_str(self) -> &'static str { + match self { + AuditAction::SetupDone => "setup.done", + AuditAction::LoginSuccess => "login.success", + AuditAction::LoginFailed => "login.failed", + AuditAction::Login2faFailed => "login.2fa_failed", + AuditAction::Logout => "logout", + AuditAction::PasswordChanged => "password.changed", + AuditAction::TotpEnabled => "totp.enabled", + AuditAction::TotpDisabled => "totp.disabled", + AuditAction::RecoveryCodesIssued => "recovery.issued", + AuditAction::SessionRevoked => "session.revoked", + AuditAction::SessionsRevoked => "sessions.revoked", + } + } +} + +/// One row of the audit log. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuditEntry { + /// ULID. Ordered by `(at, id)` together. + pub id: String, + /// When the change was made. + pub at: String, + /// Who acted, when known. Not a foreign key, so the trail outlives the account. + pub actor_id: Option, + /// `user`, `client`, `cli`, `system` or `anonymous`. + pub actor_kind: String, + /// The action, as [`AuditAction::as_str`] or a later kind. + pub action: String, + /// What the action is about, such as `user`. + pub target_kind: Option, + /// The id of that thing. + pub target_id: Option, + /// Client address, when known. + pub ip: Option, + /// JSON with extra detail. Never holds a secret. + pub data: Option, +} diff --git a/crates/im-core/src/names.rs b/crates/im-core/src/names.rs new file mode 100644 index 0000000..901bfa2 --- /dev/null +++ b/crates/im-core/src/names.rs @@ -0,0 +1,121 @@ +//! Email addresses: normalisation and the shape check. +//! +//! An address has one stored form: trimmed and lowercased. The same string is the `email` and the +//! `email_folded` of a user, so lookups are case-insensitive by construction. The shape check +//! accepts ASCII only. Look-alike characters from other scripts would otherwise let a second +//! account look exactly like the first one. +//! +//! The check is a sanity check on the text, not proof that the address exists or receives mail. + +use crate::error::{Error, Result}; + +/// Longest address accepted, in bytes (RFC 5321 path limit). +pub const MAX_EMAIL_LEN: usize = 254; + +/// Longest local part (the part before `@`), in bytes (RFC 5321). +pub const MAX_LOCAL_LEN: usize = 64; + +/// Longest domain label, in bytes (RFC 1035). +const MAX_LABEL_LEN: usize = 63; + +/// The stored form of an address: surrounding whitespace removed, then lowercased. +pub fn normalize_email(input: &str) -> String { + input.trim().to_lowercase() +} + +/// Normalises `input` and checks its shape. Returns the stored form. +/// +/// Rules: at most 254 bytes; exactly one `@`; a local part of 1 to 64 characters from the RFC 5322 +/// `atext` set (no leading, trailing or doubled dot); a domain of dot-separated labels, at least +/// one dot, each label 1 to 63 letters, digits or hyphens without a leading or trailing hyphen. +/// Anything else, including whitespace and control characters, is refused. +pub fn parse_email(input: &str) -> Result { + let email = normalize_email(input); + check_shape(&email)?; + Ok(email) +} + +/// The shape rules of [`parse_email`], for text that is already normalised. +fn check_shape(email: &str) -> Result<()> { + let invalid = || Error::Invalid("email address is not valid".into()); + if email.len() > MAX_EMAIL_LEN { + return Err(invalid()); + } + let (local, domain) = email.split_once('@').ok_or_else(invalid)?; + if local.is_empty() + || local.len() > MAX_LOCAL_LEN + || local.starts_with('.') + || local.ends_with('.') + || local.contains("..") + || !local.bytes().all(is_atext) + { + return Err(invalid()); + } + if !domain.contains('.') { + return Err(invalid()); + } + for label in domain.split('.') { + let well_formed = !label.is_empty() + && label.len() <= MAX_LABEL_LEN + && !label.starts_with('-') + && !label.ends_with('-') + && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + if !well_formed { + return Err(invalid()); + } + } + Ok(()) +} + +/// RFC 5322 `atext` restricted to ASCII. The dot is handled by the caller. +fn is_atext(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~.".contains(&byte) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_normal_address_is_trimmed_and_lowercased() { + assert_eq!( + parse_email(" Ada.Lovelace@Example.COM ").unwrap(), + "ada.lovelace@example.com" + ); + } + + #[test] + fn attack_strings_are_refused() { + let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1)); + let long_total = format!("a@{}.com", "b".repeat(250)); + for bad in [ + "", + "ada", + "@example.com", + "ada@", + "ada@@example.com", + "ada@example", + "ada@.example.com", + "ada@example..com", + "ada@example.com.", + "ada@-example.com", + "ada@example-.com", + "a da@example.com", + "ada@exam\nple.com", + "ada\u{0}@example.com", + "ada\u{202e}@example.com", + "\u{ff41}da@example.com", + "ada@exam\u{430}le.com", + ".ada@example.com", + "ada.@example.com", + "ada..x@example.com", + "ada@example.c om", + "ada@example.com/", + "ada@ex\tample.com", + &long_local, + &long_total, + ] { + assert!(parse_email(bad).is_err(), "accepted {bad:?}"); + } + } +} diff --git a/crates/im-core/src/password.rs b/crates/im-core/src/password.rs index 053cf08..3e2e0bf 100644 --- a/crates/im-core/src/password.rs +++ b/crates/im-core/src/password.rs @@ -55,25 +55,35 @@ pub async fn verify_password_async(pw: String, hash: String) -> Result { .map_err(|e| Error::Crypto(format!("verify task failed: {e}"))) } +/// Why a new password is refused by [`check_policy`]. The web layer maps each reason to a +/// translated message, so the reasons are kept apart from any text. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PolicyViolation { + /// Fewer than [`MIN_PASSWORD_CHARS`] characters. + TooShort, + /// More than [`MAX_PASSWORD_CHARS`] characters. + TooLong, + /// Contains the email local part or a word of the name. + ContainsIdentity, +} + /// Checks a new password against the policy. /// /// Rules: 10 to 256 characters; it must not contain the email local part (when that is at least /// [`MIN_FORBIDDEN_WORD_CHARS`] long) or any word of the name that is at least that long, compared /// case-insensitively. The rule that the password differs from the current one needs the stored /// hash and is checked by the caller. -/// -/// Returns `Error::Invalid` with a message that is safe to show the user. -pub fn check_policy(password: &str, email: &str, name: &str) -> Result<()> { +pub fn check_policy( + password: &str, + email: &str, + name: &str, +) -> std::result::Result<(), PolicyViolation> { let chars = password.chars().count(); if chars < MIN_PASSWORD_CHARS { - return Err(Error::Invalid(format!( - "password must be at least {MIN_PASSWORD_CHARS} characters" - ))); + return Err(PolicyViolation::TooShort); } if chars > MAX_PASSWORD_CHARS { - return Err(Error::Invalid(format!( - "password must be at most {MAX_PASSWORD_CHARS} characters" - ))); + return Err(PolicyViolation::TooLong); } let lowered = password.to_lowercase(); @@ -84,9 +94,7 @@ pub fn check_policy(password: &str, email: &str, name: &str) -> Result<()> { .filter(|word| word.chars().count() >= MIN_FORBIDDEN_WORD_CHARS); for word in forbidden { if lowered.contains(&word) { - return Err(Error::Invalid( - "password must not contain your email address or name".into(), - )); + return Err(PolicyViolation::ContainsIdentity); } } Ok(()) diff --git a/crates/im-core/src/store/audit.rs b/crates/im-core/src/store/audit.rs new file mode 100644 index 0000000..f1410ce --- /dev/null +++ b/crates/im-core/src/store/audit.rs @@ -0,0 +1,182 @@ +//! The audit log: append-only records of changes, and their listing with keyset paging. +//! +//! Entries are never updated or deleted here. The only removal is the operator's purge command +//! (`docs/architecture.md` section 10), which is not part of this module. Entries sort by +//! `(at, id)`; both parts are fixed-width text, so a cursor can name a position exactly. + +use crate::error::Result; +use crate::model::AuditEntry; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, new_id}; +use crate::time::now_stamp; + +/// The columns of an audit row, in the order [`map_entry`] reads them. +const ENTRY_COLS: &str = "id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data"; + +/// Maps a row selected with [`ENTRY_COLS`]. +fn map_entry(row: &turso::Row) -> Result { + Ok(AuditEntry { + id: col_text(row, 0)?, + at: col_text(row, 1)?, + actor_id: col_opt_text(row, 2)?, + actor_kind: col_text(row, 3)?, + action: col_text(row, 4)?, + target_kind: col_opt_text(row, 5)?, + target_id: col_opt_text(row, 6)?, + ip: col_opt_text(row, 7)?, + data: col_opt_text(row, 8)?, + }) +} + +/// One entry to append. `data` is JSON text or `None`; it must never hold a secret. +#[derive(Debug, Clone, Copy)] +pub struct NewAudit<'a> { + /// Who acted, when known. + pub actor_id: Option<&'a str>, + /// `user`, `client`, `cli`, `system` or `anonymous`. + pub actor_kind: &'a str, + /// The action text, as `model::AuditAction::as_str`. + pub action: &'a str, + /// What the action is about, such as `user`. + pub target_kind: Option<&'a str>, + /// The id of that thing. + pub target_id: Option<&'a str>, + /// Client address, when known. + pub ip: Option<&'a str>, + /// Extra detail as JSON text. + pub data: Option<&'a str>, +} + +/// Filters of a listing. `None` leaves that field unrestricted. `from` is inclusive and `to` is +/// exclusive, both as stored stamps. +#[derive(Debug, Clone, Default)] +pub struct AuditFilter { + /// Only this action. + pub action: Option, + /// Only this actor. + pub actor_id: Option, + /// Only this target id. + pub target_id: Option, + /// Entries at or after this stamp. + pub from: Option, + /// Entries before this stamp. + pub to: Option, +} + +/// The position after the last entry of a page: the next page starts strictly before it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuditCursor { + /// The `at` of the last entry of the page. + pub at: String, + /// The `id` of the last entry of the page. + pub id: String, +} + +impl Store { + /// Appends an entry, stamped with the current time. + pub async fn record_audit(&self, entry: &NewAudit<'_>) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO audit_log (id, at, actor_id, actor_kind, action, target_kind, target_id, \ + ip, data) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + ( + new_id(), + now_stamp(), + entry.actor_id.map(str::to_owned), + entry.actor_kind.to_owned(), + entry.action.to_owned(), + entry.target_kind.map(str::to_owned), + entry.target_id.map(str::to_owned), + entry.ip.map(str::to_owned), + entry.data.map(str::to_owned), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// One page of the log, newest first, after `after` when given. Returns at most `limit` + /// entries. When the page is full, the cursor for the next page is the last entry's position. + /// + /// Keyset paging: a cursor names a position, so entries written while the reader pages do not + /// shift the pages, and there is no offset to scan. + pub async fn list_audit( + &self, + filter: &AuditFilter, + after: Option<&AuditCursor>, + limit: u32, + ) -> Result<(Vec, Option)> { + let limit = limit.clamp(1, 200); + let conn = self.read_conn().await; + let entries = fetch_all( + &conn, + &format!( + "SELECT {ENTRY_COLS} FROM audit_log \ + WHERE (?1 IS NULL OR action = ?1) \ + AND (?2 IS NULL OR actor_id = ?2) \ + AND (?3 IS NULL OR target_id = ?3) \ + AND (?4 IS NULL OR at >= ?4) \ + AND (?5 IS NULL OR at < ?5) \ + AND (?6 IS NULL OR at < ?6 OR (at = ?6 AND id < ?7)) \ + ORDER BY at DESC, id DESC LIMIT ?8" + ), + ( + filter.action.clone(), + filter.actor_id.clone(), + filter.target_id.clone(), + filter.from.clone(), + filter.to.clone(), + after.map(|c| c.at.clone()), + after.map(|c| c.id.clone()), + i64::from(limit), + ), + map_entry, + ) + .await?; + let next = if entries.len() == usize::try_from(limit).unwrap_or(usize::MAX) { + entries.last().map(|last| AuditCursor { + at: last.at.clone(), + id: last.id.clone(), + }) + } else { + None + }; + Ok((entries, next)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn entries_page_newest_first_with_a_cursor() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + for _ in 0..5 { + store + .record_audit(&NewAudit { + actor_id: Some("user-1"), + actor_kind: "user", + action: "logout", + target_kind: None, + target_id: None, + ip: None, + data: None, + }) + .await + .unwrap(); + } + let filter = AuditFilter { + actor_id: Some("user-1".into()), + ..AuditFilter::default() + }; + let (first, cursor) = store.list_audit(&filter, None, 3).await.unwrap(); + assert_eq!(first.len(), 3); + let cursor = cursor.expect("a full page has a cursor"); + let (second, cursor) = store.list_audit(&filter, Some(&cursor), 3).await.unwrap(); + assert_eq!(second.len(), 2); + assert!(cursor.is_none(), "a short page ends the listing"); + assert!(first[2].at >= second[0].at); + } +} diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 89ea73b..9c543fd 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -6,8 +6,11 @@ //! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values //! in effect are logged at boot. +pub mod audit; pub mod migrate; +pub mod sessions; pub mod snapshot; +pub mod users; use std::path::Path; use std::sync::Arc; @@ -153,6 +156,12 @@ pub async fn finish(tx: Transaction<'_>, outcome: Result) -> Result { } } +/// A fresh ULID as text. Ids are ULIDs everywhere, so their text order is their creation order +/// within a millisecond. +pub(crate) fn new_id() -> String { + ulid::Ulid::generate().to_string() +} + /// Converts a Turso error to the crate error. pub(crate) fn db_err(e: turso::Error) -> Error { Error::Database(e.to_string()) @@ -257,6 +266,24 @@ pub(crate) fn col_int(row: &Row, i: usize) -> Result { } } +/// Reads a nullable text column. SQL NULL is `None`. +pub(crate) fn col_opt_text(row: &Row, i: usize) -> Result> { + match row.get_value(i).map_err(db_err)? { + Value::Null => Ok(None), + Value::Text(s) => Ok(Some(s)), + _ => Err(Error::Database(format!("column {i} is not text"))), + } +} + +/// Reads a nullable integer column. SQL NULL is `None`. +pub(crate) fn col_opt_int(row: &Row, i: usize) -> Result> { + match row.get_value(i).map_err(db_err)? { + Value::Null => Ok(None), + Value::Integer(n) => Ok(Some(n)), + _ => Err(Error::Database(format!("column {i} is not an integer"))), + } +} + /// Reads a column as text, accepting integers too. Used for PRAGMA results, which are text for /// some pragmas and integers for others. pub(crate) fn col_to_string(row: &Row, i: usize) -> Result { diff --git a/crates/im-core/src/store/sessions.rs b/crates/im-core/src/store/sessions.rs new file mode 100644 index 0000000..59d84a6 --- /dev/null +++ b/crates/im-core/src/store/sessions.rs @@ -0,0 +1,331 @@ +//! Browser sessions: creation with the per-user cap, lookup by token hash, touch, listing and +//! ending. +//! +//! A session row is the sign-in. Its cookie carries a random token; the row holds only the SHA-256 +//! of it. Ended sessions are deleted, and their ids are returned to the caller, so that later +//! back-channel logout jobs can be queued for them before the rows are gone. + +use std::time::Duration; + +use turso::Connection; + +use crate::error::Result; +use crate::model::Session; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::time::{now_stamp, stamp_after, stamp_before}; + +/// The least time between two writes of `last_seen_at` for one session, in seconds. Every request +/// reads the session; only one of them in this window writes it. +const TOUCH_INTERVAL: Duration = Duration::from_secs(5 * 60); + +/// The columns of a session row, in the order [`map_session`] reads them. +const SESSION_COLS: &str = "id, user_id, token_hash, csrf_token, created_at, expires_at, \ + last_seen_at, ip, user_agent, auth_time, amr"; + +/// Maps a row selected with [`SESSION_COLS`]. +fn map_session(row: &turso::Row) -> Result { + Ok(Session { + id: col_text(row, 0)?, + user_id: col_text(row, 1)?, + token_hash: col_text(row, 2)?, + csrf_token: col_text(row, 3)?, + created_at: col_text(row, 4)?, + expires_at: col_text(row, 5)?, + last_seen_at: col_text(row, 6)?, + ip: col_opt_text(row, 7)?, + user_agent: col_opt_text(row, 8)?, + auth_time: col_text(row, 9)?, + amr: col_text(row, 10)?, + }) +} + +/// What is needed to create a session. `token_hash` is the hash of the cookie token; the token +/// itself never reaches the store. +#[derive(Debug, Clone)] +pub struct NewSession<'a> { + /// Owner of the session. + pub user_id: &'a str, + /// Hex SHA-256 of the token that goes in the cookie. + pub token_hash: &'a str, + /// The per-session CSRF token. + pub csrf_token: &'a str, + /// One of the `model::amr` values. + pub amr: &'a str, + /// Client address at sign-in. + pub ip: Option<&'a str>, + /// User agent at sign-in, already truncated by the caller. + pub user_agent: Option<&'a str>, + /// How long the session lives from now. + pub ttl: Duration, +} + +/// The result of creating a session: the new row, and the ids of the sessions that were ended to +/// make room under the cap. The caller queues back-channel logout for `ended`. +#[derive(Debug, Clone)] +pub struct CreatedSession { + /// The new session. + pub session: Session, + /// Ids of the sessions ended because the user was at the cap, oldest first. + pub ended: Vec, +} + +/// Deletes the sessions of `user_id` matching `keep` (none keeps nothing), and returns their ids. +/// Runs inside the caller's transaction. +async fn end_sessions( + conn: &Connection, + user_id: &str, + keep: Option<&str>, + now: &str, +) -> Result> { + // Only sessions that were still live count as ended. Expired rows are removed by the sweeper. + let ids = fetch_all( + conn, + "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 AND id IS NOT ?3 \ + ORDER BY created_at ASC, id ASC", + (user_id.to_string(), now.to_string(), keep.map(str::to_owned)), + |row| col_text(row, 0), + ) + .await?; + for id in &ids { + conn.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),)) + .await + .map_err(db_err)?; + } + Ok(ids) +} + +impl Store { + /// Creates a session for a user who has just proved who they are. + /// + /// In one transaction: if the user already has `max_sessions` live sessions, the oldest ones + /// are ended until there is room for the new one, then the new row is inserted. The check and + /// the insert are in the same transaction, so two parallel sign-ins cannot both exceed the cap. + pub async fn create_session( + &self, + new: &NewSession<'_>, + max_sessions: u32, + ) -> Result { + let now = now_stamp(); + let expires_at = stamp_after(new.ttl); + let cap = usize::try_from(max_sessions.max(1)).unwrap_or(usize::MAX); + let session = Session { + id: new_id(), + user_id: new.user_id.to_owned(), + token_hash: new.token_hash.to_owned(), + csrf_token: new.csrf_token.to_owned(), + created_at: now.clone(), + expires_at, + last_seen_at: now.clone(), + ip: new.ip.map(str::to_owned), + user_agent: new.user_agent.map(str::to_owned), + auth_time: now.clone(), + amr: new.amr.to_owned(), + }; + + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let live = fetch_all( + &tx, + "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 \ + ORDER BY created_at ASC, id ASC", + (new.user_id.to_string(), now.clone()), + |row| col_text(row, 0), + ) + .await?; + // Room for the new one: at most cap - 1 live sessions may remain. + let overflow = live.len().saturating_sub(cap - 1); + let mut ended = Vec::with_capacity(overflow); + for id in live.into_iter().take(overflow) { + tx.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),)) + .await + .map_err(db_err)?; + ended.push(id); + } + tx.execute( + "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, \ + last_seen_at, ip, user_agent, auth_time, amr) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + ( + session.id.clone(), + session.user_id.clone(), + session.token_hash.clone(), + session.csrf_token.clone(), + session.created_at.clone(), + session.expires_at.clone(), + session.last_seen_at.clone(), + session.ip.clone(), + session.user_agent.clone(), + session.auth_time.clone(), + session.amr.clone(), + ), + ) + .await + .map_err(db_err)?; + Ok(CreatedSession { + session: session.clone(), + ended, + }) + } + .await; + finish(tx, outcome).await + } + + /// The live session of this token hash, or `None`. A session is live when it has not expired + /// and its user is not disabled. A disabled user is signed out by the next request, with no + /// extra step. + pub async fn session_by_token_hash(&self, token_hash: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {SESSION_COLS} FROM sessions \ + WHERE token_hash = ?1 AND expires_at > ?2 \ + AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)" + ), + (token_hash.to_string(), now_stamp()), + map_session, + ) + .await + } + + /// True when the session with this id is still live (same rules as + /// [`Store::session_by_token_hash`]). The live stream checks this after every change. + pub async fn session_is_live(&self, session_id: &str) -> Result { + let conn = self.read_conn().await; + let found = fetch_opt( + &conn, + "SELECT 1 FROM sessions WHERE id = ?1 AND expires_at > ?2 \ + AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)", + (session_id.to_string(), now_stamp()), + |_row| Ok(()), + ) + .await?; + Ok(found.is_some()) + } + + /// Records that the session was used. Writes `last_seen_at` only when the stored value is more + /// than five minutes old, so a busy page does not write on every request. Returns whether it + /// wrote. + pub async fn touch_session(&self, session_id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE sessions SET last_seen_at = ?2 WHERE id = ?1 AND last_seen_at < ?3", + ( + session_id.to_string(), + now_stamp(), + stamp_before(TOUCH_INTERVAL), + ), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// The live sessions of a user, most recently used first. + pub async fn list_sessions(&self, user_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {SESSION_COLS} FROM sessions WHERE user_id = ?1 AND expires_at > ?2 \ + ORDER BY last_seen_at DESC, id DESC" + ), + (user_id.to_string(), now_stamp()), + map_session, + ) + .await + } + + /// Ends one session, only if it belongs to `user_id`. Returns false when there was nothing to + /// end, which is also the answer for another user's session: the caller cannot tell them apart. + pub async fn end_session(&self, user_id: &str, session_id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "DELETE FROM sessions WHERE id = ?1 AND user_id = ?2", + (session_id.to_string(), user_id.to_string()), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// Ends every live session of `user_id` except `keep_session_id`. Returns the ids ended. + pub async fn end_other_sessions( + &self, + user_id: &str, + keep_session_id: &str, + ) -> Result> { + self.end_matching(user_id, Some(keep_session_id)).await + } + + /// Ends every live session of `user_id`. Returns the ids ended. + pub async fn end_all_sessions(&self, user_id: &str) -> Result> { + self.end_matching(user_id, None).await + } + + async fn end_matching(&self, user_id: &str, keep: Option<&str>) -> Result> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let now = now_stamp(); + let outcome: Result> = end_sessions(&tx, user_id, keep, &now).await; + finish(tx, outcome).await + } + + /// Deletes the sessions that have expired. Returns how many were removed. Run by the sweeper. + pub async fn sweep_expired_sessions(&self) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM sessions WHERE expires_at <= ?1", + (now_stamp(),), + ) + .await + .map_err(db_err) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn the_cap_ends_the_oldest_sessions_in_the_same_write() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + let user = store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .unwrap(); + let mut ids: Vec = Vec::new(); + for n in 0..3 { + let token = format!("hash-{n}"); + let created = store + .create_session( + &NewSession { + user_id: &user.id, + token_hash: &token, + csrf_token: "csrf", + amr: "pwd", + ip: None, + user_agent: None, + ttl: Duration::from_secs(3600), + }, + 2, + ) + .await + .unwrap(); + if n < 2 { + assert!(created.ended.is_empty()); + } else { + assert_eq!(created.ended, vec![ids[0].clone()]); + } + ids.push(created.session.id); + } + let live = store.list_sessions(&user.id).await.unwrap(); + assert_eq!(live.len(), 2); + assert!(store.session_by_token_hash("hash-0").await.unwrap().is_none()); + assert!(store.session_by_token_hash("hash-2").await.unwrap().is_some()); + } +} diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs new file mode 100644 index 0000000..b09559d --- /dev/null +++ b/crates/im-core/src/store/users.rs @@ -0,0 +1,468 @@ +//! User accounts: creation, lookup, profile and password, and the two-factor state. +//! +//! Rules that must hold under concurrency are single conditional statements, so two requests cannot +//! both win: +//! +//! - the first administrator exists only if no user does (`create_first_admin`); +//! - a TOTP step is accepted once (`accept_totp_step`, `totp_last_step` is only ever raised); +//! - a recovery code is spent once (`consume_recovery_code`, `used_at IS NULL`). +//! +//! A TOTP secret that is being enrolled is not written to the user row. It waits in the `settings` +//! table under `totp_pending:`, sealed like any other secret, and moves to the row only +//! when a code from it is confirmed. So re-enrolling while two-factor is on never switches the +//! second factor off, and an abandoned enrolment changes nothing. + +use turso::{Connection, Row}; + +use crate::error::{Error, Result}; +use crate::model::User; +use crate::store::{Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id}; +use crate::time::now_stamp; + +/// The columns of a user row, in the order [`map_user`] reads them. +const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ + totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ + photo_mime, picture_version, created_at, updated_at"; + +/// Maps a row selected with [`USER_COLS`]. +fn map_user(row: &Row) -> Result { + Ok(User { + id: col_text(row, 0)?, + email: col_text(row, 1)?, + name: col_text(row, 2)?, + password_hash: col_text(row, 3)?, + is_admin: col_int(row, 4)? != 0, + disabled_at: col_opt_text(row, 5)?, + totp_secret_sealed: col_opt_text(row, 6)?, + totp_enabled_at: col_opt_text(row, 7)?, + totp_last_step: col_opt_int(row, 8)?, + locale: col_text(row, 9)?, + zoneinfo: col_text(row, 10)?, + theme: col_text(row, 11)?, + photo_mime: col_opt_text(row, 12)?, + picture_version: col_int(row, 13)?, + created_at: col_text(row, 14)?, + updated_at: col_text(row, 15)?, + }) +} + +/// Maps an insert error. A UNIQUE violation is a conflict for the person; anything else is a +/// database failure. +fn insert_error(e: turso::Error) -> Error { + let text = e.to_string(); + if text.contains("UNIQUE") { + Error::Conflict("that email address is already registered".into()) + } else { + db_err(e) + } +} + +/// The settings key that holds a TOTP secret waiting for its first confirmed code. +fn pending_key(user_id: &str) -> String { + format!("totp_pending:{user_id}") +} + +/// Replaces the recovery codes of a user with `hashes`. Runs inside the caller's transaction. +async fn replace_codes(conn: &Connection, user_id: &str, hashes: &[String]) -> Result<()> { + conn.execute( + "DELETE FROM recovery_codes WHERE user_id = ?1", + (user_id.to_string(),), + ) + .await + .map_err(db_err)?; + for hash in hashes { + conn.execute( + "INSERT INTO recovery_codes (user_id, code_hash, used_at) VALUES (?1, ?2, NULL)", + (user_id.to_string(), hash.clone()), + ) + .await + .map_err(db_err)?; + } + Ok(()) +} + +impl Store { + /// Creates the first administrator, and only if there is no user at all. + /// + /// The check and the insert are one statement, so two parallel setups cannot both succeed. The + /// second one gets [`Error::Conflict`]. `email` must already be normalised. + pub async fn create_first_admin( + &self, + email: &str, + name: &str, + password_hash: &str, + ) -> Result { + let id = new_id(); + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ + created_at, updated_at) \ + SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \ + WHERE NOT EXISTS (SELECT 1 FROM users)", + ( + id.clone(), + email.to_string(), + name.to_string(), + password_hash.to_string(), + now, + ), + ) + .await + .map_err(insert_error)?; + drop(conn); + if changed == 0 { + return Err(Error::Conflict("setup is already complete".into())); + } + self.user_by_id(&id).await?.ok_or(Error::NotFound) + } + + /// Creates an account. `email` must already be normalised. Fails with a conflict when the + /// address is taken. + pub async fn create_user( + &self, + email: &str, + name: &str, + password_hash: &str, + is_admin: bool, + ) -> Result { + let id = new_id(); + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ + created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", + ( + id.clone(), + email.to_string(), + name.to_string(), + password_hash.to_string(), + i64::from(is_admin), + now, + ), + ) + .await + .map_err(insert_error)?; + drop(conn); + self.user_by_id(&id).await?.ok_or(Error::NotFound) + } + + /// The user with this id, or `None`. + pub async fn user_by_id(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {USER_COLS} FROM users WHERE id = ?1"), + (id.to_string(),), + map_user, + ) + .await + } + + /// The user with this normalised address, or `None`. Callers normalise the input first. + pub async fn user_by_email_folded(&self, folded: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {USER_COLS} FROM users WHERE email_folded = ?1"), + (folded.to_string(),), + map_user, + ) + .await + } + + /// Changes the display name. The schema keeps it at 1 to 100 characters. + pub async fn update_name(&self, id: &str, name: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE users SET name = ?2, updated_at = ?3 WHERE id = ?1", + (id.to_string(), name.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Changes the language, time zone and theme. The schema rejects unknown languages and themes. + pub async fn update_preferences( + &self, + id: &str, + locale: &str, + zoneinfo: &str, + theme: &str, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE users SET locale = ?2, zoneinfo = ?3, theme = ?4, updated_at = ?5 \ + WHERE id = ?1", + ( + id.to_string(), + locale.to_string(), + zoneinfo.to_string(), + theme.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Stores a new argon2id hash. The caller has checked the policy and the current password. + pub async fn set_password_hash(&self, id: &str, password_hash: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1", + (id.to_string(), password_hash.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an + /// earlier unconfirmed secret of the same user. The user row is not touched. + pub async fn set_totp_pending(&self, user_id: &str, sealed_secret: &str) -> Result<()> { + self.set_setting(&pending_key(user_id), sealed_secret).await + } + + /// The sealed secret of an enrolment that is waiting for its confirming code, or `None`. + pub async fn totp_pending(&self, user_id: &str) -> Result> { + self.setting(&pending_key(user_id)).await + } + + /// Turns two-factor sign-in on: stores the confirmed secret, records the step that confirmed + /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. + /// One transaction. + pub async fn enable_totp( + &self, + user_id: &str, + sealed_secret: &str, + step: u64, + recovery_hashes: &[String], + ) -> Result<()> { + let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let changed = tx + .execute( + "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ + totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", + ( + user_id.to_string(), + sealed_secret.to_string(), + now, + step, + ), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + replace_codes(&tx, user_id, recovery_hashes).await?; + tx.execute("DELETE FROM settings WHERE key = ?1", (pending_key(user_id),)) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Turns two-factor sign-in off: clears the secret, the step and the recovery codes, and drops + /// any pending enrolment. One transaction. + pub async fn disable_totp(&self, user_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let changed = tx + .execute( + "UPDATE users SET totp_secret_sealed = NULL, totp_enabled_at = NULL, \ + totp_last_step = NULL, updated_at = ?2 WHERE id = ?1", + (user_id.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + tx.execute( + "DELETE FROM recovery_codes WHERE user_id = ?1", + (user_id.to_string(),), + ) + .await + .map_err(db_err)?; + tx.execute("DELETE FROM settings WHERE key = ?1", (pending_key(user_id),)) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard + /// forward. A step that is not later than the recorded one, or any step while two-factor is off, + /// returns false. This is the replay guard: a code is spent by this single statement. + pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result { + let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE users SET totp_last_step = ?2 \ + WHERE id = ?1 AND totp_enabled_at IS NOT NULL \ + AND (totp_last_step IS NULL OR totp_last_step < ?2)", + (user_id.to_string(), step), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// Replaces every recovery code of the user with `hashes`, all unused. One transaction. + pub async fn replace_recovery_codes(&self, user_id: &str, hashes: &[String]) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = replace_codes(&tx, user_id, hashes).await; + finish(tx, outcome).await + } + + /// Spends a recovery code. Returns true only for the first use of an existing, unused code. + pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE recovery_codes SET used_at = ?3 \ + WHERE user_id = ?1 AND code_hash = ?2 AND used_at IS NULL", + (user_id.to_string(), code_hash.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// How many recovery codes of the user are still unused. + pub async fn unused_recovery_codes(&self, user_id: &str) -> Result { + let conn = self.read_conn().await; + let count = fetch_opt( + &conn, + "SELECT COUNT(*) FROM recovery_codes WHERE user_id = ?1 AND used_at IS NULL", + (user_id.to_string(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + u64::try_from(count).map_err(|_| Error::Database("negative count".into())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::password::hash_password; + + async fn store() -> (tempfile::TempDir, Store) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + (dir, store) + } + + #[tokio::test] + async fn the_first_admin_can_be_created_once() { + let (_dir, store) = store().await; + let hash = hash_password("correct horse battery").unwrap(); + let admin = store + .create_first_admin("ada@example.com", "Ada", &hash) + .await + .unwrap(); + assert!(admin.is_admin); + assert_eq!(store.user_count().await.unwrap(), 1); + + let second = store + .create_first_admin("bob@example.com", "Bob", &hash) + .await; + assert!(matches!(second, Err(Error::Conflict(_))), "{second:?}"); + assert_eq!(store.user_count().await.unwrap(), 1); + } + + #[tokio::test] + async fn a_totp_step_is_accepted_once_and_only_while_enabled() { + let (_dir, store) = store().await; + let user = store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .unwrap(); + assert!(!store.accept_totp_step(&user.id, 100).await.unwrap()); + + store.set_totp_pending(&user.id, "v1:sealed").await.unwrap(); + assert_eq!( + store.totp_pending(&user.id).await.unwrap().as_deref(), + Some("v1:sealed") + ); + store + .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()]) + .await + .unwrap(); + assert!(store.totp_pending(&user.id).await.unwrap().is_none()); + + assert!(store.accept_totp_step(&user.id, 101).await.unwrap()); + // The same step again, and an older one, are refused: the replay guard. + assert!(!store.accept_totp_step(&user.id, 101).await.unwrap()); + assert!(!store.accept_totp_step(&user.id, 100).await.unwrap()); + assert!(store.accept_totp_step(&user.id, 102).await.unwrap()); + } + + #[tokio::test] + async fn a_recovery_code_works_once() { + let (_dir, store) = store().await; + let user = store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .unwrap(); + store + .set_totp_pending(&user.id, "v1:sealed") + .await + .unwrap(); + store + .enable_totp(&user.id, "v1:sealed", 5, &["code-a".to_string(), "code-b".to_string()]) + .await + .unwrap(); + assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2); + + assert!(store.consume_recovery_code(&user.id, "code-a").await.unwrap()); + assert!(!store.consume_recovery_code(&user.id, "code-a").await.unwrap()); + assert!(!store.consume_recovery_code(&user.id, "unknown").await.unwrap()); + assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 1); + } + + #[tokio::test] + async fn emails_are_unique_and_found_by_their_normalised_form() { + let (_dir, store) = store().await; + store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .unwrap(); + let dup = store + .create_user("ada@example.com", "Ada again", "hash", false) + .await; + assert!(matches!(dup, Err(Error::Conflict(_))), "{dup:?}"); + assert!(store.user_by_email_folded("ada@example.com").await.unwrap().is_some()); + assert!(store.user_by_email_folded("ADA@example.com").await.unwrap().is_none()); + } +} diff --git a/crates/im-core/src/totp.rs b/crates/im-core/src/totp.rs new file mode 100644 index 0000000..cca7b30 --- /dev/null +++ b/crates/im-core/src/totp.rs @@ -0,0 +1,229 @@ +//! Second-factor helpers: TOTP (RFC 6238 over HMAC-SHA1, 6 digits, 30-second steps), RFC 4648 +//! base32 for the shared secret, the `otpauth://` link that authenticator apps import, and +//! recovery codes. +//! +//! This module keeps no state. A code is accepted at the current step and one step either side. +//! [`verify`] returns the step it matched; the caller stores that step as the replay guard with a +//! conditional update (`Store::accept_totp_step`), so two requests with the same code cannot both +//! succeed. + +use hmac::{Hmac, KeyInit, Mac}; +use sha1::Sha1; +use sha2::{Digest, Sha256}; + +use crate::token::{constant_time_eq, random_readable}; + +/// Shared secret length in bytes: 160 bits, the RFC 4226 recommendation. +pub const SECRET_LEN: usize = 20; + +/// Seconds per time step. RFC 6238 default and what authenticator apps assume. +pub const STEP_SECS: u64 = 30; + +/// Digits in a code. Six is what every authenticator app defaults to. +pub const DIGITS: usize = 6; + +/// Steps accepted on each side of the current one, to allow for clock drift of up to 30 seconds. +pub const SKEW_STEPS: i64 = 1; + +/// Issuer name shown by authenticator apps next to the account. +pub const ISSUER: &str = "im"; + +const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + +type HmacSha1 = Hmac; + +/// A fresh random secret of [`SECRET_LEN`] bytes. +pub fn new_secret() -> [u8; SECRET_LEN] { + let mut secret = [0u8; SECRET_LEN]; + rand::fill(&mut secret); + secret +} + +/// HOTP (RFC 4226) with HMAC-SHA1, reduced to [`DIGITS`] digits. +pub fn hotp(secret: &[u8], counter: u64) -> u32 { + // HMAC accepts a key of any length, so construction cannot fail. + let mut mac = + ::new_from_slice(secret).expect("HMAC takes any key length"); + mac.update(&counter.to_be_bytes()); + let tag = mac.finalize().into_bytes(); + // Dynamic truncation (RFC 4226 section 5.3): the low nibble of the last byte picks a window. + let offset = usize::from(tag[tag.len() - 1] & 0x0f); + let binary = u32::from_be_bytes([ + tag[offset] & 0x7f, + tag[offset + 1], + tag[offset + 2], + tag[offset + 3], + ]); + binary % 10u32.pow(DIGITS as u32) +} + +/// The time step that contains `unix_secs`. +pub fn step_for(unix_secs: u64) -> u64 { + unix_secs / STEP_SECS +} + +/// The zero-padded code for one step. +pub fn code_at(secret: &[u8], step: u64) -> String { + format!("{:0width$}", hotp(secret, step), width = DIGITS) +} + +/// Checks `code` against the steps around `now_step`. +/// +/// Returns the matched step when it is later than `last_step` (the replay guard; `None` means no +/// code was ever used). Malformed input returns `None` without any HMAC work. Every candidate +/// step is compared, so timing does not reveal which one matched. +pub fn verify(secret: &[u8], code: &str, now_step: u64, last_step: Option) -> Option { + if code.len() != DIGITS || !code.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let now = i64::try_from(now_step).ok()?; + let mut matched = None; + for delta in -SKEW_STEPS..=SKEW_STEPS { + let Some(step) = now.checked_add(delta).and_then(|s| u64::try_from(s).ok()) else { + continue; + }; + let expected = code_at(secret, step); + if constant_time_eq(expected.as_bytes(), code.as_bytes()) && matched.is_none() { + matched = Some(step); + } + } + matched.filter(|&step| last_step.is_none_or(|last| step > last)) +} + +/// RFC 4648 base32, uppercase, without padding. This is the form authenticator apps expect. +pub fn base32_encode(data: &[u8]) -> String { + let mut out = String::with_capacity(data.len().div_ceil(5) * 8); + let mut buffer: u64 = 0; + let mut bits: u32 = 0; + for &byte in data { + buffer = (buffer << 8) | u64::from(byte); + bits += 8; + while bits >= 5 { + bits -= 5; + out.push(char::from( + BASE32_ALPHABET[((buffer >> bits) & 31) as usize], + )); + } + } + if bits > 0 { + out.push(char::from( + BASE32_ALPHABET[((buffer << (5 - bits)) & 31) as usize], + )); + } + out +} + +/// The `otpauth://` link that authenticator apps import, for the account `account` (the email +/// address). The label and the issuer are percent-encoded, so an address with `+` or `@` survives. +pub fn otpauth_uri(account: &str, secret: &[u8]) -> String { + let label = format!("{ISSUER}:{account}"); + format!( + "otpauth://totp/{}?secret={}&issuer={}&algorithm=SHA1&digits={DIGITS}&period={STEP_SECS}", + encode_component(&label), + base32_encode(secret), + encode_component(ISSUER), + ) +} + +/// Percent-encodes everything except RFC 3986 unreserved characters. +fn encode_component(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for byte in text.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(char::from(byte)); + } + _ => out.push_str(&format!("%{byte:02X}")), + } + } + out +} + +/// A new recovery code, shown to the person as `xxxx-xxxx` from the readable alphabet. +pub fn new_recovery_code() -> String { + let raw = random_readable(8); + format!("{}-{}", &raw[..4], &raw[4..]) +} + +/// Hex SHA-256 of a recovery code after normalisation: lowercase, without dashes and spaces. The +/// stored hash and the checked input go through the same normalisation, so how the person types +/// the code does not matter. +pub fn recovery_code_hash(code: &str) -> String { + let normalized: String = code + .chars() + .filter(|c| !c.is_whitespace() && *c != '-') + .map(|c| c.to_ascii_lowercase()) + .collect(); + hex::encode(Sha256::digest(normalized.as_bytes())) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// RFC 6238 appendix B, SHA-1 row: the 8-digit reference values reduce to these 6-digit codes. + const RFC_KEY: &[u8] = b"12345678901234567890"; + + #[test] + fn rfc6238_sha1_test_vectors() { + let vectors: [(u64, &str); 6] = [ + (59, "287082"), + (1_111_111_109, "081804"), + (1_111_111_111, "050471"), + (1_234_567_890, "005924"), + (2_000_000_000, "279037"), + (20_000_000_000, "353130"), + ]; + for (time, expected) in vectors { + assert_eq!(code_at(RFC_KEY, time / STEP_SECS), expected, "time {time}"); + } + } + + #[test] + fn a_code_is_accepted_once_within_the_skew_window() { + let now = 1_000; + let code = code_at(RFC_KEY, now + 1); + assert_eq!(verify(RFC_KEY, &code, now, None), Some(now + 1)); + // The same step is refused after it was recorded as used (the replay guard). + assert_eq!(verify(RFC_KEY, &code, now, Some(now + 1)), None); + assert_eq!(verify(RFC_KEY, &code_at(RFC_KEY, now + 2), now, None), None); + assert_eq!(verify(RFC_KEY, "12345", now, None), None); + } + + #[test] + fn base32_matches_the_rfc4648_vectors() { + let cases = [ + ("", ""), + ("f", "MY"), + ("fo", "MZXQ"), + ("foo", "MZXW6"), + ("foob", "MZXW6YQ"), + ("fooba", "MZXW6YTB"), + ("foobar", "MZXW6YTBOI"), + ]; + for (plain, encoded) in cases { + assert_eq!(base32_encode(plain.as_bytes()), encoded); + } + } + + #[test] + fn the_link_encodes_the_label_and_carries_the_secret() { + let uri = otpauth_uri("ada+1@example.com", b"foobar"); + assert_eq!( + uri, + "otpauth://totp/im%3Aada%2B1%40example.com?secret=MZXW6YTBOI&issuer=im\ + &algorithm=SHA1&digits=6&period=30" + ); + } + + #[test] + fn recovery_codes_ignore_case_dashes_and_spaces() { + let code = new_recovery_code(); + assert_eq!(code.len(), 9); + assert_eq!(code.as_bytes()[4], b'-'); + assert_eq!( + recovery_code_hash(&code), + recovery_code_hash(&code.to_uppercase().replace('-', " ")) + ); + } +} diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml index c993af1..28800f6 100644 --- a/crates/im-web/Cargo.toml +++ b/crates/im-web/Cargo.toml @@ -10,10 +10,13 @@ name = "im" path = "src/main.rs" [dependencies] +base64.workspace = true futures-util.workspace = true http.workspace = true im-core.workspace = true +qrcode.workspace = true serde.workspace = true +serde_json.workspace = true # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout. tokio = { workspace = true, features = ["net", "signal", "time"] } topcoat.workspace = true diff --git a/crates/im-web/assets/nav.js b/crates/im-web/assets/nav.js index 219f017..2faf606 100644 --- a/crates/im-web/assets/nav.js +++ b/crates/im-web/assets/nav.js @@ -169,9 +169,17 @@ }; } - /** Holds /-/alive. It only drives the restart bar; the server sends nothing else on it yet. */ + /** + * Holds /-/alive. It drives the restart bar, and it carries the account events of a signed-in + * browser: `account` when the person's sessions or security changed, and `signed_out` when this + * browser's session is gone, which sends the page to sign-in. + */ function holdAlive() { hold(ALIVE_PATH, { + events: { + account: () => scheduleRefresh(), + signed_out: () => location.assign("/login"), + }, lost: () => { serverDown = true; updateRestartBar(); diff --git a/crates/im-web/src/audit.rs b/crates/im-web/src/audit.rs new file mode 100644 index 0000000..6ca4874 --- /dev/null +++ b/crates/im-web/src/audit.rs @@ -0,0 +1,57 @@ +//! The audit writer of the web layer. Every change of an account, a session or a sign-in goes +//! through [`record`]. +//! +//! The entry is written after the change has committed. A failed write is logged and never fails +//! the request: a person who has just signed in should not see an error because the log was busy. +//! Nothing secret goes in `data`; callers pass counts, reasons and ids only. + +use im_core::model::AuditAction; +use im_core::store::audit::NewAudit; +use serde_json::Value; +use topcoat::context::{Cx, app_context}; + +use crate::client_ip::client_addr; +use crate::state::AppState; + +/// Who performed the action. +#[derive(Clone, Copy)] +pub enum Actor<'a> { + /// A signed-in person, by their id. + User(&'a str), + /// Nobody is signed in: a failed sign-in, for example. + Anonymous, +} + +/// Appends one entry. `target` is the kind and id of what the action was about; `data` is JSON +/// (`Value::Null` for none). +pub async fn record( + cx: &Cx, + actor: Actor<'_>, + action: AuditAction, + target: Option<(&str, &str)>, + data: Value, +) { + let state = app_context::(cx); + let ip = client_addr(cx).to_string(); + let (actor_id, actor_kind) = match actor { + Actor::User(id) => (Some(id), "user"), + Actor::Anonymous => (None, "anonymous"), + }; + let data_text = (!data.is_null()).then(|| data.to_string()); + let entry = NewAudit { + actor_id, + actor_kind, + action: action.as_str(), + target_kind: target.map(|(kind, _)| kind), + target_id: target.map(|(_, id)| id), + ip: Some(ip.as_str()), + data: data_text.as_deref(), + }; + if let Err(error) = state.store.record_audit(&entry).await { + tracing::error!( + error = %error, + action = action.as_str(), + "audit entry was not written" + ); + } +} diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs new file mode 100644 index 0000000..44ed886 --- /dev/null +++ b/crates/im-web/src/auth.rs @@ -0,0 +1,470 @@ +//! Sessions and the signed-in person: the session cookie, the guards every page calls, the CSRF +//! checks, the token that protects pre-session forms, the sealed pending-login cookie between the +//! password and the second factor, and the guard on every `next` redirect. +//! +//! The browser holds the session token in `__Host-im_session`. The database holds only its SHA-256, +//! so a leaked row cannot be replayed as a cookie. Every guard here answers before any side effect, +//! and a state-changing handler calls [`require_csrf`] or [`check_pre_csrf`] first. + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use im_core::model::{Session, User, amr}; +use im_core::secret; +use im_core::store::Store; +use im_core::store::sessions::NewSession; +use im_core::token::{constant_time_eq, generate_token, hash_token}; +use im_core::totp; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; +use topcoat::router::error::{forbidden, not_found, see_other}; +use topcoat::router::request::{headers, uri}; + +use crate::client_ip::client_addr; +use crate::live::Topic; +use crate::state::AppState; + +/// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-im_session`. +pub const SESSION_COOKIE: &str = "im_session"; + +/// How long a session lives, from sign-in. Both the row and the cookie use it. +pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); + +/// Logical name of the pre-session CSRF cookie, used by the pages that run before a session exists. +pub const PRE_CSRF_COOKIE: &str = "im_precsrf"; + +/// How long the pre-session CSRF token stays valid in the browser. +const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60); + +/// Logical name of the pending-login cookie, set between the password and the second factor. +pub const PENDING_COOKIE: &str = "im_pending"; + +/// How long a password-verified sign-in may wait for its second factor. Five minutes is long enough +/// to fetch a code from an app, and short enough that a stolen cookie is of little use. +pub const PENDING_TTL: Duration = Duration::from_secs(5 * 60); + +/// The longest `next` value accepted, in bytes. +const MAX_NEXT_LEN: usize = 2048; + +/// The signed-in person and the session they signed in with. +#[derive(Clone)] +pub struct Viewer { + /// The account. Not disabled. + pub user: User, + /// The session the request presented. Its `csrf_token` checks forms. + pub session: Session, +} + +/// The cookie jar that forces the `__Host-` prefix: `Secure`, `Path=/` and no `Domain`. +fn jar(cx: &Cx) -> impl Cookies + '_ { + cookies(cx).override_prefix_host() +} + +/// The session the request presented, if it is still live. +async fn presented_session(cx: &Cx) -> Result> { + let Some(cookie) = jar(cx).get(SESSION_COOKIE) else { + return Ok(None); + }; + let store = &app_context::(cx).store; + Ok(store + .session_by_token_hash(&hash_token(cookie.value())) + .await?) +} + +/// The signed-in person, or `None` when there is no live session. Refreshes `last_seen` (at most +/// once in five minutes; the store decides). +pub async fn current_user(cx: &Cx) -> Result> { + let Some(session) = presented_session(cx).await? else { + return Ok(None); + }; + let store = &app_context::(cx).store; + let Some(user) = store + .user_by_id(&session.user_id) + .await? + .filter(|user| !user.is_disabled()) + else { + return Ok(None); + }; + store.touch_session(&session.id).await?; + Ok(Some(Viewer { user, session })) +} + +/// The signed-in person. Anyone else is sent to `/login`, with the page they asked for as `next`. +pub async fn require_user(cx: &Cx) -> Result { + match current_user(cx).await? { + Some(viewer) => Ok(viewer), + None => { + let path = uri(cx).path_and_query().map_or("/", |p| p.as_str()); + let target = format!("/login?next={}", percent_encode(path)); + Err(see_other(target).into()) + } + } +} + +/// The signed-in administrator. A person who is not an administrator gets 404, the same answer as a +/// page that does not exist. An administrator without two-factor sign-in, while the policy requires +/// it, is sent to the security page instead. +/// +/// Not every handler needs it yet; the admin pages that use it come after the account pages. +#[allow(dead_code)] +pub async fn require_admin(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + if !viewer.user.is_admin { + return Err(not_found().into()); + } + let state = app_context::(cx); + if state.config.policy.require_2fa_for_admins && !viewer.user.totp_enabled() { + return Err(see_other("/account/security?notice=enrol").into()); + } + Ok(viewer) +} + +/// The signed-in person, when the submitted `csrf` field matches their session. Returns 403 for a +/// wrong or missing token. Call it first in every state-changing handler. +pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result { + let viewer = require_user(cx).await?; + if check_csrf(&viewer.session, submitted) { + Ok(viewer) + } else { + Err(forbidden().into()) + } +} + +/// True only when `submitted` is the session's CSRF token, compared in constant time. An empty +/// stored token never matches, not even an empty submission. +pub fn check_csrf(session: &Session, submitted: &str) -> bool { + !session.csrf_token.is_empty() + && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) +} + +/// Creates a session for `user`, authenticated by `amr`, and sets the cookie. +/// +/// A session the browser already presented for the same person is ended first, so a sign-in always +/// rotates the session id. The cap of the policy is applied inside the store, in the same write. +pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { + let state = app_context::(cx); + if let Some(old) = presented_session(cx) + .await? + .filter(|old| old.user_id == user.id) + { + state.store.end_session(&user.id, &old.id).await?; + } + let token = generate_token(); + let csrf = generate_token(); + let ip = client_addr(cx).to_string(); + let user_agent = user_agent(cx); + let created = state + .store + .create_session( + &NewSession { + user_id: &user.id, + token_hash: &hash_token(&token), + csrf_token: &csrf, + amr, + ip: Some(ip.as_str()), + user_agent: user_agent.as_deref(), + ttl: SESSION_TTL, + }, + state.config.policy.max_sessions, + ) + .await?; + // Sessions ended by the cap are not signed out elsewhere yet; their back-channel logout is queued + // once the OpenID provider exists. + state.live.bump(&Topic::Account(user.id.clone())); + let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX)); + jar(cx).add( + Cookie::build((SESSION_COOKIE, token)) + .path("/") + .secure(true) + .http_only(true) + .same_site(SameSite::Lax) + .max_age(max_age) + .build(), + ); + Ok(created.session) +} + +/// Ends the session of `viewer` and clears its cookie. Other sessions of the person are untouched. +pub async fn end_current_session(cx: &Cx, viewer: &Viewer) -> Result<()> { + let state = app_context::(cx); + state + .store + .end_session(&viewer.user.id, &viewer.session.id) + .await?; + state.live.bump(&Topic::Account(viewer.user.id.clone())); + jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); + Ok(()) +} + +/// The pre-session CSRF token. Login, setup and the second-factor page use it, because no session +/// exists yet. An existing cookie is reused, so two open tabs both keep working. +pub fn pre_csrf_token(cx: &Cx) -> String { + if let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) { + let value = cookie.value(); + if !value.is_empty() { + return value.to_owned(); + } + } + let token = generate_token(); + jar(cx).add(pre_csrf_cookie(token.clone())); + token +} + +/// True only when the submitted `precsrf` equals the pre-session cookie. Call it before any other +/// work in a pre-session POST. +pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool { + let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) else { + return false; + }; + !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes()) +} + +/// Removes the pre-session CSRF cookie after a successful sign-in or setup. +pub fn clear_pre_csrf(cx: &Cx) { + jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/")); +} + +fn pre_csrf_cookie(token: String) -> Cookie<'static> { + Cookie::build((PRE_CSRF_COOKIE, token)) + .path("/") + .secure(true) + .http_only(true) + .same_site(SameSite::Strict) + .max_age(time::Duration::seconds( + i64::try_from(PRE_CSRF_TTL.as_secs()).unwrap_or(i64::MAX), + )) + .build() +} + +/// A password-verified sign-in that waits for its second factor. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pending { + /// The person who passed the password step. + pub user_id: String, + /// The authentication method so far. Always the password. + pub amr: String, + /// Where to go after the second factor. Checked again with [`safe_next`] before use. + pub next: String, +} + +/// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance +/// key, so the browser can neither change the person nor extend the expiry. +pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> Result<()> { + let expires = unix_now() + PENDING_TTL.as_secs(); + let payload = format!("{user_id}|{expires}|{}|{next}", amr::PASSWORD); + let sealed = secret::seal(key, payload.as_bytes())?; + let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0)); + jar(cx).add( + Cookie::build((PENDING_COOKIE, sealed)) + .path("/") + .secure(true) + .http_only(true) + .same_site(SameSite::Strict) + .max_age(max_age) + .build(), + ); + Ok(()) +} + +/// The pending sign-in, or `None` when the cookie is missing, tampered with, malformed or expired. +/// `next` is the field as it was set; the caller applies [`safe_next`]. +pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option { + let cookie = jar(cx).get(PENDING_COOKIE)?; + let plain = secret::open(key, cookie.value()).ok()?; + let text = String::from_utf8(plain).ok()?; + // `next` comes last, so a `|` inside it cannot shift the other fields. + let mut parts = text.splitn(4, '|'); + let user_id = parts.next()?; + let expires: u64 = parts.next()?.parse().ok()?; + let amr = parts.next()?; + let next = parts.next()?; + if unix_now() >= expires { + return None; + } + Some(Pending { + user_id: user_id.to_owned(), + amr: amr.to_owned(), + next: next.to_owned(), + }) +} + +/// Removes the pending-login cookie. +pub fn clear_pending_login(cx: &Cx) { + jar(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/")); +} + +/// Checks one six-digit TOTP code for `user`, with the replay guard. True only when the code is +/// valid and its step was not used before. Returns false when two-factor sign-in is off. +pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) -> Result { + let Some(sealed) = user.totp_secret_sealed.as_deref() else { + return Ok(false); + }; + if !user.totp_enabled() { + return Ok(false); + } + let shared = secret::open(key, sealed)?; + let last = user + .totp_last_step + .and_then(|step| u64::try_from(step).ok()); + match totp::verify(&shared, code, totp::step_for(unix_now()), last) { + Some(step) => Ok(store.accept_totp_step(&user.id, step).await?), + None => Ok(false), + } +} + +/// Checks a second factor: six digits are a TOTP code, anything else is a recovery code, which is +/// spent on success. Returns the authentication method that was proved, or `None`. +pub async fn check_second_factor( + store: &Store, + key: &[u8; 32], + user: &User, + input: &str, +) -> Result> { + let input = input.trim(); + if input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()) { + let ok = verify_totp(store, key, user, input).await?; + return Ok(ok.then_some(amr::PASSWORD_TOTP)); + } + if !user.totp_enabled() { + return Ok(None); + } + let spent = store + .consume_recovery_code(&user.id, &totp::recovery_code_hash(input)) + .await?; + Ok(spent.then_some(amr::PASSWORD_RECOVERY)) +} + +/// Where a person goes after signing in. An administrator without two-factor sign-in goes to the +/// security page to enrol it, while the policy requires that. Anyone else goes to `next`. +pub fn after_sign_in(state: &AppState, user: &User, next: &str) -> String { + if user.is_admin && state.config.policy.require_2fa_for_admins && !user.totp_enabled() { + "/account/security?notice=enrol".to_owned() + } else { + safe_next(Some(next)).to_owned() + } +} + +/// Returns `next` only when it is a same-site path: one leading `/`, then no `/` or `\` that would +/// make a browser treat it as another host, no control characters, at most 2048 bytes. Anything else +/// is `/`. +pub fn safe_next(next: Option<&str>) -> &str { + match next { + Some(next) if is_local_path(next) => next, + _ => "/", + } +} + +fn is_local_path(path: &str) -> bool { + path.len() <= MAX_NEXT_LEN + && path.starts_with('/') + && !path.starts_with("//") + && !path.starts_with("/\\") + && path.chars().all(|c| !c.is_control()) +} + +/// Percent-encodes everything except RFC 3986 unreserved characters and `/`. +pub fn percent_encode(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + for byte in input.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { + out.push(char::from(byte)); + } + _ => out.push_str(&format!("%{byte:02X}")), + } + } + out +} + +/// The `User-Agent` of the request, truncated to 512 characters. +pub fn user_agent(cx: &Cx) -> Option { + headers(cx) + .get(http::header::USER_AGENT) + .and_then(|value| value.to_str().ok()) + .map(|text| text.chars().take(512).collect()) +} + +/// Seconds since the Unix epoch. A clock before the epoch reads as 0, which only makes every +/// pending sign-in expire at once. +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn next_accepts_only_local_paths() { + assert_eq!(safe_next(Some("/")), "/"); + assert_eq!( + safe_next(Some("/account/security?x=1")), + "/account/security?x=1" + ); + assert_eq!(safe_next(None), "/"); + } + + #[test] + fn next_refuses_every_attack_string() { + let overlong = format!("/{}", "a".repeat(MAX_NEXT_LEN)); + for bad in [ + "", + "https://evil.example/", + "http://evil.example", + "//evil.example/", + "/\\evil.example/", + "\\\\evil.example", + "\\/evil.example", + "evil.example", + "javascript:alert(1)", + "/\n/evil.example", + "/\r\nSet-Cookie: x=1", + "/\t", + "/\u{0}", + " //evil.example", + overlong.as_str(), + ] { + assert_eq!(safe_next(Some(bad)), "/", "accepted {bad:?}"); + } + } + + #[test] + fn percent_encoding_keeps_slashes_and_encodes_the_rest() { + assert_eq!(percent_encode("/a/b-c_d.e~f"), "/a/b-c_d.e~f"); + assert_eq!(percent_encode("/s?x=1&y=2"), "/s%3Fx%3D1%26y%3D2"); + } + + #[tokio::test] + async fn a_recovery_code_signs_in_once() { + use crate::boot::test_state; + let (_dir, state) = test_state().await; + let user = state + .store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .expect("user"); + let sealed = secret::seal(&state.key, &totp::new_secret()).expect("seal"); + let code = totp::new_recovery_code(); + state + .store + .enable_totp(&user.id, &sealed, 1, &[totp::recovery_code_hash(&code)]) + .await + .expect("enable"); + let user = state + .store + .user_by_id(&user.id) + .await + .expect("query") + .expect("user"); + let first = check_second_factor(&state.store, &state.key, &user, &code) + .await + .expect("check"); + assert_eq!(first, Some(amr::PASSWORD_RECOVERY)); + let second = check_second_factor(&state.store, &state.key, &user, &code) + .await + .expect("check"); + assert_eq!(second, None); + } +} diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index cb9cae4..a1de538 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -22,6 +22,7 @@ use crate::live::LiveHub; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; +use crate::throttle::Throttle; /// Name of the instance key file inside the data directory. const KEY_FILE: &str = "im.key"; @@ -81,6 +82,7 @@ async fn open_state(config: Config) -> im_core::Result { store, key: Arc::new(key), live: Arc::new(LiveHub::default()), + throttle: Arc::new(Throttle::default()), }) } @@ -155,6 +157,7 @@ mod tests { store, key: Arc::new(key), live: Arc::new(LiveHub::default()), + throttle: Arc::new(Throttle::default()), }; (dir, state) } @@ -171,7 +174,8 @@ mod tests { #[tokio::test] async fn a_page_carries_the_content_security_policy_and_nosniff() { let (_dir, state) = test_state().await; - let response = get(state, "/", Some("text/html")).await; + // No user yet, so the setup page answers. + let response = get(state, "/setup", Some("text/html")).await; assert_eq!(response.status(), 200); assert_eq!( response.headers()[CONTENT_SECURITY_POLICY] diff --git a/crates/im-web/src/client_ip.rs b/crates/im-web/src/client_ip.rs new file mode 100644 index 0000000..301b8e6 --- /dev/null +++ b/crates/im-web/src/client_ip.rs @@ -0,0 +1,124 @@ +//! The client address of a request, for throttling and for the audit log. +//! +//! The TCP peer is the client, unless the peer is in `trusted_proxies`. Only then is +//! `X-Forwarded-For` read: from the right, skipping trusted hops, the first untrusted address is the +//! client. Any unusable header falls back to the peer, so a spoofed header from an untrusted peer is +//! never believed. IPv6 is bucketed by /64 for throttling, so one client holding a /64 cannot +//! multiply its attempt budget. + +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +use topcoat::context::{Cx, app_context}; +use topcoat::router::IpNet; +use topcoat::router::request::{headers, remote_addr}; + +use crate::state::AppState; + +/// The header a trusted proxy appends the client address to. +const FORWARDED_FOR: &str = "x-forwarded-for"; + +/// The client address for throttling: the exact address, with IPv6 bucketed by /64. +pub fn client_ip(cx: &Cx) -> IpAddr { + bucket(client_addr(cx)) +} + +/// The exact client address of this request, normalised but not bucketed. Used for the audit log +/// and the session list. A request without a peer address (not possible over TCP) maps to the +/// unspecified address. +pub fn client_addr(cx: &Cx) -> IpAddr { + let trusted = &app_context::(cx).config.trusted_proxies; + let peer = remote_addr(cx).map(|addr| addr.ip()); + let forwarded = headers(cx) + .get_all(FORWARDED_FOR) + .iter() + .filter_map(|value| value.to_str().ok()) + .collect::>() + .join(","); + resolve_addr(peer, &forwarded, trusted) +} + +/// Pure form of [`client_addr`]. `forwarded` is the combined `X-Forwarded-For` value, or empty. +pub fn resolve_addr(peer: Option, forwarded: &str, trusted: &[IpNet]) -> IpAddr { + let Some(peer) = peer.map(normalize) else { + return IpAddr::V4(Ipv4Addr::UNSPECIFIED); + }; + if !is_trusted(peer, trusted) { + return peer; + } + for entry in forwarded.rsplit(',') { + let Ok(ip) = entry.trim().parse::() else { + return peer; + }; + let ip = normalize(ip); + if !is_trusted(ip, trusted) { + return ip; + } + } + peer +} + +fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool { + trusted.iter().any(|net| net.contains(&ip)) +} + +/// IPv4-mapped IPv6 addresses are reported as the IPv4 address they carry. +fn normalize(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4), + IpAddr::V4(_) => ip, + } +} + +/// Clears the host half of an IPv6 address, so every address of a /64 shares one bucket. +fn bucket(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V4(_) => ip, + IpAddr::V6(v6) => { + let mut octets = v6.octets(); + octets[8..].fill(0); + IpAddr::V6(Ipv6Addr::from(octets)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ip(text: &str) -> IpAddr { + text.parse().unwrap() + } + + #[test] + fn forwarded_for_counts_only_from_a_trusted_peer() { + let trusted: [IpNet; 1] = ["127.0.0.0/8".parse().unwrap()]; + // An untrusted peer's header is ignored. 127.0.0.0/8 is the trusted proxy range. + assert_eq!( + resolve_addr(Some(ip("203.0.113.9")), "198.51.100.7", &trusted), + ip("203.0.113.9") + ); + // A trusted proxy's header names the client, skipping trusted hops from the right. + assert_eq!( + resolve_addr( + Some(ip("127.0.0.1")), + "1.2.3.4, 198.51.100.7, 127.0.0.2", + &trusted + ), + ip("198.51.100.7") + ); + // An unusable header falls back to the peer. + assert_eq!( + resolve_addr(Some(ip("127.0.0.1")), "garbage", &trusted), + ip("127.0.0.1") + ); + } + + #[test] + fn ipv6_is_bucketed_by_slash_64_and_mapped_addresses_are_ipv4() { + let a = bucket(ip("2001:db8:1:2:aaaa::1")); + assert_eq!(a, bucket(ip("2001:db8:1:2:bbbb::9"))); + assert_ne!(a, bucket(ip("2001:db8:1:3::1"))); + assert_eq!(a, ip("2001:db8:1:2::")); + assert_eq!(normalize(ip("::ffff:192.0.2.5")), ip("192.0.2.5")); + } +} diff --git a/crates/im-web/src/i18n/account.rs b/crates/im-web/src/i18n/account.rs new file mode 100644 index 0000000..8714c58 --- /dev/null +++ b/crates/im-web/src/i18n/account.rs @@ -0,0 +1,415 @@ +//! Strings of the accounts area: setup, sign-in, the two-factor step, the account home, security +//! and sessions. Each key has an English and a Turkish text in [`text`]; the match is exhaustive, +//! so a key without a translation does not compile. +//! +//! Sentences with values go through the small helpers below, not through concatenation in views, +//! because word order differs between the two languages. + +use super::Lang; + +/// One variant per phrase of the accounts area. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Txt { + /// The field label of an email address. + Email, + /// The field label of a display name. + Name, + /// The field label of a password. + Password, + /// The field label of a one-time code. + Code, + /// The field label of the current password. + CurrentPassword, + /// The field label of a new password. + NewPassword, + /// The field label of the repeated new password. + NewPasswordAgain, + /// Hint under the password field of setup and password change. + PasswordHint, + /// Shown while the throttle holds an account or an address back. + ErrThrottled, + /// The password of the current account is wrong. + ErrWrongPassword, + /// The two new passwords do not match. + ErrPasswordsDiffer, + /// The new password is the current one. + ErrPasswordSame, + /// The new password contains the email address or a word of the name. + ErrPasswordIdentity, + /// The name is empty or too long. + ErrNameInvalid, + /// The email address does not have a valid shape. + ErrEmailInvalid, + /// A second-factor code is wrong or already used. + ErrCodeInvalid, + /// A second-factor code is required and was not given. + ErrCodeMissing, + /// The enrolment was not kept (it expired or was replaced); the person must start again. + ErrNoPending, + /// The sign-in failed. Used for unknown email, wrong password and disabled account alike. + ErrInvalidLogin, + /// The title of the first-run setup page. + SetupTitle, + /// The sentence under the setup title. + SetupIntro, + /// The button that creates the first administrator. + CreateAdmin, + /// The button that signs in. + SignIn, + /// The button and menu item that end the session. + SignOut, + /// The title of the second-factor page. + TwoFactorTitle, + /// The sentence under the second-factor title. + TwoFactorIntro, + /// The button that checks the code. + Verify, + /// The title of the account home. + HomeTitle, + /// The label of the two-factor status on the account home. + TwoFactorStatus, + /// The status word for two-factor on. + On, + /// The status word for two-factor off. + Off, + /// The title of the security page, and the menu item that opens it. + SecurityTitle, + /// The account home link text that opens the security page. + SecurityLinkText, + /// The title of the sessions page, and the menu item that opens it. + SessionsTitle, + /// The account home link text that opens the sessions page. + SessionsLinkText, + /// The title of the administration section on the account home. + AdminArea, + /// The account home link text that opens the administration section. + AdminLinkText, + /// The heading of the password section. + PasswordSection, + /// The button that changes the password. + ChangePassword, + /// Says that changing the password signs out the other sessions. + PasswordHelp, + /// The heading of the two-factor section. + TwoFactorSection, + /// The status text when two-factor sign-in is on. + TwoFactorOnText, + /// The status text when two-factor sign-in is off. + TwoFactorOffText, + /// The heading above a secret that waits for its first code. + PendingTitle, + /// The instructions above a secret that waits for its first code. + PendingHelp, + /// The label of the base32 secret. + SecretKey, + /// The label of the otpauth link. + SetupLink, + /// The alternative text of the QR code. + QrAlt, + /// The button that turns two-factor sign-in on. + TurnOn, + /// The heading of the section that replaces the authenticator of an active account. + ReplaceTitle, + /// The instructions of the replacement section. + ReplaceHelp, + /// The button that starts a replacement enrolment. + ReplaceButton, + /// The label of the code typed from the authenticator app. + CodeFromApp, + /// The heading of the turn-off section. + DisableTitle, + /// The instructions of the turn-off section. + DisableHelp, + /// The button that turns two-factor sign-in off. + TurnOff, + /// The heading of the recovery codes section. + RecoveryTitle, + /// Explains what the recovery codes are for. + RecoveryHelp, + /// The button that issues new recovery codes. + RegenerateCodes, + /// Says that issuing new codes ends the old ones. + RegenerateHelp, + /// The heading above a freshly issued set of codes. + NewCodesTitle, + /// The warning above a freshly issued set of codes. + CodesShownOnce, + /// Notice: the password was changed. + SavedPassword, + /// Notice: two-factor sign-in was turned on. + Saved2faOn, + /// Notice: two-factor sign-in was turned off. + Saved2faOff, + /// Notice: one session was signed out. + SavedSession, + /// Notice: the other sessions were signed out. + SavedOthers, + /// Notice on the security page: an administrator must enrol. + EnrolSecurityNotice, + /// The sentence at the top of the sessions page. + SessionsIntro, + /// The badge of the session in use. + ThisSession, + /// The label of the sign-in time. + SignedInAt, + /// The label of the last use. + LastSeen, + /// The label of the address a session was created from. + AddressLabel, + /// The button that ends one session. + SignOutSession, + /// The button that ends every other session. + SignOutOthers, + /// Shown when the person has no other session. + NoOthers, + /// The browser name when the user agent is missing or unknown. + UnknownBrowser, + /// The system name when the user agent is missing or unknown. + UnknownSystem, + /// The label of the account menu. + AccountMenu, +} + +/// The text of `key` in `lang`. +pub fn text(lang: Lang, key: Txt) -> &'static str { + match (key, lang) { + (Txt::Email, Lang::En) => "Email address", + (Txt::Email, Lang::Tr) => "E-posta adresi", + (Txt::Name, Lang::En) => "Name", + (Txt::Name, Lang::Tr) => "Ad soyad", + (Txt::Password, Lang::En) => "Password", + (Txt::Password, Lang::Tr) => "Parola", + (Txt::Code, Lang::En) => "Code", + (Txt::Code, Lang::Tr) => "Kod", + (Txt::CurrentPassword, Lang::En) => "Current password", + (Txt::CurrentPassword, Lang::Tr) => "Mevcut parola", + (Txt::NewPassword, Lang::En) => "New password", + (Txt::NewPassword, Lang::Tr) => "Yeni parola", + (Txt::NewPasswordAgain, Lang::En) => "New password, again", + (Txt::NewPasswordAgain, Lang::Tr) => "Yeni parola, tekrar", + (Txt::PasswordHint, Lang::En) => { + "At least 10 characters. Do not use your name or your email address." + } + (Txt::PasswordHint, Lang::Tr) => { + "En az 10 karakter. Adınızı ya da e-posta adresinizi kullanmayın." + } + (Txt::ErrThrottled, Lang::En) => "Too many attempts. Wait a few minutes, then try again.", + (Txt::ErrThrottled, Lang::Tr) => { + "Çok fazla deneme yapıldı. Birkaç dakika bekleyip yeniden deneyin." + } + (Txt::ErrWrongPassword, Lang::En) => "The password is wrong.", + (Txt::ErrWrongPassword, Lang::Tr) => "Parola yanlış.", + (Txt::ErrPasswordsDiffer, Lang::En) => "The two new passwords do not match.", + (Txt::ErrPasswordsDiffer, Lang::Tr) => "Yeni parolalar eşleşmiyor.", + (Txt::ErrPasswordSame, Lang::En) => "The new password must differ from the current one.", + (Txt::ErrPasswordSame, Lang::Tr) => "Yeni parola, mevcut parolanızdan farklı olmalıdır.", + (Txt::ErrPasswordIdentity, Lang::En) => { + "The password must not contain your email address or your name." + } + (Txt::ErrPasswordIdentity, Lang::Tr) => { + "Parola e-posta adresinizi ya da adınızı içermemelidir." + } + (Txt::ErrNameInvalid, Lang::En) => "Enter your name, at most 100 characters.", + (Txt::ErrNameInvalid, Lang::Tr) => "Adınızı girin, en fazla 100 karakter.", + (Txt::ErrEmailInvalid, Lang::En) => "Enter a valid email address.", + (Txt::ErrEmailInvalid, Lang::Tr) => "Geçerli bir e-posta adresi girin.", + (Txt::ErrCodeInvalid, Lang::En) => "The code is wrong, or it was already used.", + (Txt::ErrCodeInvalid, Lang::Tr) => "Kod yanlış ya da daha önce kullanılmış.", + (Txt::ErrCodeMissing, Lang::En) => "Enter the code from your authenticator app.", + (Txt::ErrCodeMissing, Lang::Tr) => "Kimlik doğrulama uygulamanızdaki kodu girin.", + (Txt::ErrNoPending, Lang::En) => "The setup was not kept. Start the setup again.", + (Txt::ErrNoPending, Lang::Tr) => "Kurulum saklanmadı. Kurulumu yeniden başlatın.", + (Txt::ErrInvalidLogin, Lang::En) => "The email address or the password is wrong.", + (Txt::ErrInvalidLogin, Lang::Tr) => "E-posta adresi ya da parola yanlış.", + (Txt::SetupTitle, Lang::En) => "Set up im", + (Txt::SetupTitle, Lang::Tr) => "im kurulumu", + (Txt::SetupIntro, Lang::En) => { + "Create the first administrator. This page closes as soon as an account exists." + } + (Txt::SetupIntro, Lang::Tr) => { + "İlk yöneticiyi oluşturun. Bir hesap oluşturulduğunda bu sayfa kapanır." + } + (Txt::CreateAdmin, Lang::En) => "Create administrator", + (Txt::CreateAdmin, Lang::Tr) => "Yöneticiyi oluştur", + (Txt::SignIn, Lang::En) => "Sign in", + (Txt::SignIn, Lang::Tr) => "Oturum aç", + (Txt::SignOut, Lang::En) => "Sign out", + (Txt::SignOut, Lang::Tr) => "Oturumu kapat", + (Txt::TwoFactorTitle, Lang::En) => "Two-step sign-in", + (Txt::TwoFactorTitle, Lang::Tr) => "İki adımlı giriş", + (Txt::TwoFactorIntro, Lang::En) => { + "Enter the 6-digit code from your authenticator app, or one of your recovery codes." + } + (Txt::TwoFactorIntro, Lang::Tr) => { + "Kimlik doğrulama uygulamanızdaki 6 haneli kodu ya da kurtarma kodlarınızdan birini girin." + } + (Txt::Verify, Lang::En) => "Verify", + (Txt::Verify, Lang::Tr) => "Doğrula", + (Txt::HomeTitle, Lang::En) => "Your account", + (Txt::HomeTitle, Lang::Tr) => "Hesabınız", + (Txt::TwoFactorStatus, Lang::En) => "Two-step sign-in", + (Txt::TwoFactorStatus, Lang::Tr) => "İki adımlı giriş", + (Txt::On, Lang::En) => "On", + (Txt::On, Lang::Tr) => "Açık", + (Txt::Off, Lang::En) => "Off", + (Txt::Off, Lang::Tr) => "Kapalı", + (Txt::SecurityTitle, Lang::En) => "Security", + (Txt::SecurityTitle, Lang::Tr) => "Güvenlik", + (Txt::SecurityLinkText, Lang::En) => "Password and two-step sign-in", + (Txt::SecurityLinkText, Lang::Tr) => "Parola ve iki adımlı giriş", + (Txt::SessionsTitle, Lang::En) => "Sessions", + (Txt::SessionsTitle, Lang::Tr) => "Oturumlar", + (Txt::SessionsLinkText, Lang::En) => "Where you are signed in", + (Txt::SessionsLinkText, Lang::Tr) => "Oturumunuzun açık olduğu yerler", + (Txt::AdminArea, Lang::En) => "Administration", + (Txt::AdminArea, Lang::Tr) => "Yönetim", + (Txt::AdminLinkText, Lang::En) => "Users, settings and the audit log", + (Txt::AdminLinkText, Lang::Tr) => "Kullanıcılar, ayarlar ve denetim günlüğü", + (Txt::PasswordSection, Lang::En) => "Password", + (Txt::PasswordSection, Lang::Tr) => "Parola", + (Txt::ChangePassword, Lang::En) => "Change password", + (Txt::ChangePassword, Lang::Tr) => "Parolayı değiştir", + (Txt::PasswordHelp, Lang::En) => "Changing it signs out your other sessions.", + (Txt::PasswordHelp, Lang::Tr) => "Parolayı değiştirmek diğer oturumlarınızı kapatır.", + (Txt::TwoFactorSection, Lang::En) => "Two-step sign-in", + (Txt::TwoFactorSection, Lang::Tr) => "İki adımlı giriş", + (Txt::TwoFactorOnText, Lang::En) => { + "On. Signing in asks for a code from your authenticator app." + } + (Txt::TwoFactorOnText, Lang::Tr) => { + "Açık. Girişte kimlik doğrulama uygulamanızdan bir kod istenir." + } + (Txt::TwoFactorOffText, Lang::En) => "Off. Signing in needs only your password.", + (Txt::TwoFactorOffText, Lang::Tr) => "Kapalı. Girişte yalnızca parolanız istenir.", + (Txt::PendingTitle, Lang::En) => "Add this key to your authenticator app", + (Txt::PendingTitle, Lang::Tr) => "Bu anahtarı kimlik doğrulama uygulamanıza ekleyin", + (Txt::PendingHelp, Lang::En) => { + "Scan the code, or type the key by hand. Then enter the 6-digit code the app shows, to turn two-step sign-in on." + } + (Txt::PendingHelp, Lang::Tr) => { + "Kodu tarayın ya da anahtarı elle yazın. Ardından iki adımlı girişi açmak için uygulamanın gösterdiği 6 haneli kodu girin." + } + (Txt::SecretKey, Lang::En) => "Key", + (Txt::SecretKey, Lang::Tr) => "Anahtar", + (Txt::SetupLink, Lang::En) => "Setup link", + (Txt::SetupLink, Lang::Tr) => "Kurulum bağlantısı", + (Txt::QrAlt, Lang::En) => "QR code for your authenticator app", + (Txt::QrAlt, Lang::Tr) => "Kimlik doğrulama uygulamanız için QR kodu", + (Txt::TurnOn, Lang::En) => "Turn on", + (Txt::TurnOn, Lang::Tr) => "Aç", + (Txt::ReplaceTitle, Lang::En) => "Set up a new authenticator", + (Txt::ReplaceTitle, Lang::Tr) => "Yeni kimlik doğrulama uygulaması kur", + (Txt::ReplaceHelp, Lang::En) => { + "Enter a current code. Your present setup keeps working until the new one is confirmed." + } + (Txt::ReplaceHelp, Lang::Tr) => { + "Güncel bir kod girin. Yenisi onaylanana kadar mevcut kurulumunuz çalışmaya devam eder." + } + (Txt::ReplaceButton, Lang::En) => "Start a new setup", + (Txt::ReplaceButton, Lang::Tr) => "Yeni kurulumu başlat", + (Txt::CodeFromApp, Lang::En) => "Code from the app", + (Txt::CodeFromApp, Lang::Tr) => "Uygulamadaki kod", + (Txt::DisableTitle, Lang::En) => "Turn off two-step sign-in", + (Txt::DisableTitle, Lang::Tr) => "İki adımlı girişi kapat", + (Txt::DisableHelp, Lang::En) => "Enter your password and a current code.", + (Txt::DisableHelp, Lang::Tr) => "Parolanızı ve güncel bir kodu girin.", + (Txt::TurnOff, Lang::En) => "Turn off", + (Txt::TurnOff, Lang::Tr) => "Kapat", + (Txt::RecoveryTitle, Lang::En) => "Recovery codes", + (Txt::RecoveryTitle, Lang::Tr) => "Kurtarma kodları", + (Txt::RecoveryHelp, Lang::En) => { + "When you cannot use your app, each code signs you in once. Keep them somewhere safe." + } + (Txt::RecoveryHelp, Lang::Tr) => { + "Uygulamanızı kullanamadığınızda her kod sizi bir kez giriş yaptırır. Güvenli bir yerde saklayın." + } + (Txt::RegenerateCodes, Lang::En) => "Get new recovery codes", + (Txt::RegenerateCodes, Lang::Tr) => "Yeni kurtarma kodları al", + (Txt::RegenerateHelp, Lang::En) => "The codes you have now stop working.", + (Txt::RegenerateHelp, Lang::Tr) => "Şu anki kodlarınız çalışmaz hâle gelir.", + (Txt::NewCodesTitle, Lang::En) => "Your new recovery codes", + (Txt::NewCodesTitle, Lang::Tr) => "Yeni kurtarma kodlarınız", + (Txt::CodesShownOnce, Lang::En) => "Save these now. They are not shown again.", + (Txt::CodesShownOnce, Lang::Tr) => "Bunları şimdi kaydedin. Bir daha gösterilmez.", + (Txt::SavedPassword, Lang::En) => "Your password was changed.", + (Txt::SavedPassword, Lang::Tr) => "Parolanız değiştirildi.", + (Txt::Saved2faOn, Lang::En) => "Two-step sign-in is on.", + (Txt::Saved2faOn, Lang::Tr) => "İki adımlı giriş açıldı.", + (Txt::Saved2faOff, Lang::En) => "Two-step sign-in is off.", + (Txt::Saved2faOff, Lang::Tr) => "İki adımlı giriş kapatıldı.", + (Txt::SavedSession, Lang::En) => "The session was signed out.", + (Txt::SavedSession, Lang::Tr) => "Oturum kapatıldı.", + (Txt::SavedOthers, Lang::En) => "The other sessions were signed out.", + (Txt::SavedOthers, Lang::Tr) => "Diğer oturumlar kapatıldı.", + (Txt::EnrolSecurityNotice, Lang::En) => { + "Administrators must turn on two-step sign-in before they can use the administration pages." + } + (Txt::EnrolSecurityNotice, Lang::Tr) => { + "Yöneticiler yönetim sayfalarını kullanmadan önce iki adımlı girişi açmalıdır." + } + (Txt::SessionsIntro, Lang::En) => "Browsers and devices where you are signed in.", + (Txt::SessionsIntro, Lang::Tr) => "Oturumunuzun açık olduğu tarayıcılar ve cihazlar.", + (Txt::ThisSession, Lang::En) => "This session", + (Txt::ThisSession, Lang::Tr) => "Bu oturum", + (Txt::SignedInAt, Lang::En) => "Signed in", + (Txt::SignedInAt, Lang::Tr) => "Oturum açıldı", + (Txt::LastSeen, Lang::En) => "Last seen", + (Txt::LastSeen, Lang::Tr) => "Son görülme", + (Txt::AddressLabel, Lang::En) => "Address", + (Txt::AddressLabel, Lang::Tr) => "Adres", + (Txt::SignOutSession, Lang::En) => "Sign out", + (Txt::SignOutSession, Lang::Tr) => "Kapat", + (Txt::SignOutOthers, Lang::En) => "Sign out all other sessions", + (Txt::SignOutOthers, Lang::Tr) => "Diğer tüm oturumları kapat", + (Txt::NoOthers, Lang::En) => "You have no other sessions.", + (Txt::NoOthers, Lang::Tr) => "Başka bir oturumunuz yok.", + (Txt::UnknownBrowser, Lang::En) => "Unknown browser", + (Txt::UnknownBrowser, Lang::Tr) => "Bilinmeyen tarayıcı", + (Txt::UnknownSystem, Lang::En) => "unknown system", + (Txt::UnknownSystem, Lang::Tr) => "bilinmeyen sistem", + (Txt::AccountMenu, Lang::En) => "Account menu", + (Txt::AccountMenu, Lang::Tr) => "Hesap menüsü", + } +} + +/// "The password must be at least 10 characters." +pub fn password_too_short(lang: Lang, min: usize) -> String { + match lang { + Lang::En => format!("The password must be at least {min} characters."), + Lang::Tr => format!("Parola en az {min} karakter olmalıdır."), + } +} + +/// "The password must be at most 256 characters." +pub fn password_too_long(lang: Lang, max: usize) -> String { + match lang { + Lang::En => format!("The password must be at most {max} characters."), + Lang::Tr => format!("Parola en fazla {max} karakter olmalıdır."), + } +} + +/// "3 unused recovery codes are left." +pub fn recovery_left(lang: Lang, unused: u64) -> String { + match lang { + Lang::En => format!("{unused} unused recovery codes are left."), + Lang::Tr => format!("{unused} kullanılmamış kurtarma kodu kaldı."), + } +} + +/// The name of a device for a session list: "Chrome on Linux", or "Chrome (Linux)" in Turkish. +pub fn device_label(lang: Lang, browser: &str, system: &str) -> String { + match lang { + Lang::En => format!("{browser} on {system}"), + Lang::Tr => format!("{browser} ({system})"), + } +} + +/// The message for a password that the policy refuses. +pub fn policy_problem(lang: Lang, violation: im_core::password::PolicyViolation) -> String { + use im_core::password::{MAX_PASSWORD_CHARS, MIN_PASSWORD_CHARS, PolicyViolation}; + match violation { + PolicyViolation::TooShort => password_too_short(lang, MIN_PASSWORD_CHARS), + PolicyViolation::TooLong => password_too_long(lang, MAX_PASSWORD_CHARS), + PolicyViolation::ContainsIdentity => text(lang, Txt::ErrPasswordIdentity).to_owned(), + } +} diff --git a/crates/im-web/src/i18n/mod.rs b/crates/im-web/src/i18n/mod.rs index 5f336b9..19e373f 100644 --- a/crates/im-web/src/i18n/mod.rs +++ b/crates/im-web/src/i18n/mod.rs @@ -7,6 +7,7 @@ //! This module decides the language. It does not format sentences with values; those get small //! helper functions next to their keys. +pub mod account; pub mod shell; use topcoat::context::Cx; diff --git a/crates/im-web/src/i18n/shell.rs b/crates/im-web/src/i18n/shell.rs index dd9fcdb..b4ef15c 100644 --- a/crates/im-web/src/i18n/shell.rs +++ b/crates/im-web/src/i18n/shell.rs @@ -10,14 +10,10 @@ pub enum K { Admin, /// The link on the 404 page that returns to the start page. BackHome, - /// The title of the start page. - ImIsRunning, /// The sentence under the 404 title. NotFoundBody, /// The title of the 404 page. NotFoundTitle, - /// The sentence on the start page. - RunningBody, /// The bar shown while the server cannot be reached. ServerRestarting, /// The accessible name of the service switcher. @@ -33,18 +29,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::Admin, Lang::Tr) => "Yönetici", (K::BackHome, Lang::En) => "Back to the start", (K::BackHome, Lang::Tr) => "Başlangıca dön", - (K::ImIsRunning, Lang::En) => "im is running", - (K::ImIsRunning, Lang::Tr) => "im çalışıyor", (K::NotFoundBody, Lang::En) => "The page does not exist, or you do not have access to it.", (K::NotFoundBody, Lang::Tr) => "Sayfa yok ya da bu sayfayı görme izniniz yok.", (K::NotFoundTitle, Lang::En) => "Page not found", (K::NotFoundTitle, Lang::Tr) => "Sayfa bulunamadı", - (K::RunningBody, Lang::En) => { - "The server answers requests. Sign-in is not part of this build yet." - } - (K::RunningBody, Lang::Tr) => { - "Sunucu istekleri yanıtlıyor. Oturum açma bu sürümde henüz yok." - } (K::ServerRestarting, Lang::En) => "The server is restarting. Reconnecting…", (K::ServerRestarting, Lang::Tr) => "Sunucu yeniden başlatılıyor. Yeniden bağlanılıyor…", (K::Services, Lang::En) => "Services", diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index 2893ec3..9d59146 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -9,10 +9,10 @@ //! The hub is not a queue and not an authorisation check. Each route that opens a stream //! authenticates and authorises first, then calls [`stream_changes`]. //! -//! Nothing bumps a topic or opens [`stream_changes`] yet, so the items here are kept ahead of the -//! pages that use them. +//! The account stream (`/-/alive`) is the only user of the hub so far. [`stream_changes`] waits for +//! the admin pages that follow a list. -#![allow(dead_code)] // The hub and its topics wait for the pages that bump and follow them. +#![allow(dead_code)] // `stream_changes` and `Topic::AdminAudit` wait for the admin pages. use std::collections::HashMap; use std::future::Future; @@ -20,13 +20,17 @@ use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::Duration; use futures_util::{Stream, StreamExt, future::select_all, stream}; +use im_core::store::Store; use tokio::sync::watch; use topcoat::Result; -use topcoat::context::Cx; +use topcoat::context::{Cx, app_context}; use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{HeaderValue, route}; +use crate::auth::current_user; +use crate::state::AppState; + /// How long a client waits before it reconnects when a stream ends. Sent once, at the start. pub const STREAM_RETRY: Duration = Duration::from_millis(1000); @@ -166,12 +170,55 @@ pub fn events_response( Ok(response) } +/// The state of a viewer's `/-/alive` stream between two wakes. +struct AccountFollow { + /// Woken by every change of the viewer's account (sessions, security). + wake: watch::Receiver, + /// Checks that the session of this stream still exists. + store: Store, + /// The session the stream was opened with. + session_id: String, + /// Set after `signed_out` was sent, so the stream ends right after it. + done: bool, +} + /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and -/// starts again. Anonymous viewers may hold it, and it reveals nothing: for now it sends only the -/// `retry` hint and keep-alives. +/// starts again. +/// +/// An anonymous viewer gets keep-alives only. A signed-in viewer also gets an `account` event each +/// time their account changes (the page then refreshes), and a `signed_out` event when their session +/// is gone. After `signed_out` the browser goes to the sign-in page, and the stream ends. #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { - events_response(cx, stream::pending::>()) + let state = app_context::(cx); + let Some(viewer) = current_user(cx).await? else { + return events_response(cx, stream::pending::>()); + }; + let follow = AccountFollow { + wake: state + .live + .subscribe(&Topic::Account(viewer.user.id.clone())), + store: state.store.clone(), + session_id: viewer.session.id.clone(), + done: false, + }; + let events = stream::unfold(follow, |mut follow| async move { + if follow.done || follow.wake.changed().await.is_err() { + return None; + } + match follow.store.session_is_live(&follow.session_id).await { + Ok(true) => Some((Ok(Event::new().event("account").data("1")), follow)), + Ok(false) => { + follow.done = true; + Some((Ok(Event::new().event("signed_out").data("1")), follow)) + } + Err(error) => { + tracing::error!(error = %error, "alive: could not check the session"); + None + } + } + }); + events_response(cx, events) } #[cfg(test)] diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 6eb392c..4224ca5 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -5,13 +5,17 @@ //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. mod assets; +mod audit; +mod auth; mod boot; +mod client_ip; mod health; mod i18n; mod live; mod pages; mod security; mod state; +mod throttle; mod views; use std::path::{Path, PathBuf}; diff --git a/crates/im-web/src/pages/home.rs b/crates/im-web/src/pages/home.rs index 5577a3a..31e921e 100644 --- a/crates/im-web/src/pages/home.rs +++ b/crates/im-web/src/pages/home.rs @@ -1,25 +1,54 @@ -//! The start page. For now it only shows that the server runs; it becomes the account home once -//! sign-in exists. +//! The account home, the first page after sign-in. Without a session it goes to sign-in, and on an +//! instance with no users yet, to setup. use topcoat::Result; -use topcoat::context::Cx; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::see_other; use topcoat::router::page; use topcoat::view::{View, view}; -use crate::i18n::lang; -use crate::i18n::shell::{K, t}; -use crate::views::{notice, shell}; +use crate::auth::current_user; +use crate::i18n::account::{Txt, text}; +use crate::state::AppState; +use crate::views::{ViewerInfo, page_lang, shell}; /// `GET /`. #[page("/")] async fn home(cx: &Cx) -> Result { - let lang = lang(cx, None); - Ok(view! { - shell(title: t(lang, K::ImIsRunning), lang: lang, viewer: None, -
+ if app_context::(cx).store.user_count().await? == 0 { + return Err(see_other("/setup").into()); + } + let Some(viewer) = current_user(cx).await? else { + return Err(see_other("/login").into()); + }; + let lang = page_lang(cx, Some(&viewer)); + let two_factor = if viewer.user.totp_enabled() { + text(lang, Txt::On) + } else { + text(lang, Txt::Off) + }; + let name = viewer.user.name.clone(); + let email = viewer.user.email.clone(); + let is_admin = viewer.user.is_admin; + let info = ViewerInfo::of(&viewer); + Ok(view! { cx => + shell(title: text(lang, Txt::HomeTitle), lang: lang, viewer: Some(info), +

"im"

-

(t(lang, K::ImIsRunning))

- notice(message: t(lang, K::RunningBody)) +

(name)

+
+
(text(lang, Txt::Email))
+
(email)
+
(text(lang, Txt::TwoFactorStatus))
+
(two_factor)
+
+
) }) diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs new file mode 100644 index 0000000..6fd61ac --- /dev/null +++ b/crates/im-web/src/pages/login.rs @@ -0,0 +1,367 @@ +//! Sign-in: the password step, the second-factor step and sign-out. +//! +//! Order of a sign-in POST: the pre-session token first, then the throttle, then the lookup and the +//! password check (an unknown or disabled email still runs one hash, so timing does not reveal it), +//! then either a session or the pending cookie for the second factor. Every wrong answer gets the +//! same message. + +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use im_core::model::{AuditAction, User, amr}; +use im_core::names::normalize_email; +use im_core::password::{hash_password_async, verify_password_async}; +use serde::Deserialize; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, forbidden, see_other}; +use topcoat::router::response::response_headers; +use topcoat::router::{HeaderValue, StatusCode, header, page, route}; +use topcoat::view::{View, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{ + after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, clear_pre_csrf, + end_current_session, pending_login, pre_csrf_token, require_csrf, safe_next, set_pending_login, + start_session, +}; +use crate::client_ip::client_ip; +use crate::i18n::Lang; +use crate::i18n::account::{Txt, text}; +use crate::state::AppState; +use crate::throttle::{ + LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, two_factor_key, user_key, +}; +use crate::views::{alert, field, page_lang, shell}; + +/// The sign-in form. `next` is carried through a hidden field; it is checked again on use. +#[derive(Deserialize, Default)] +struct LoginForm { + #[serde(default)] + precsrf: String, + #[serde(default)] + email: String, + #[serde(default)] + password: String, + #[serde(default)] + next: String, +} + +/// The query of `GET /login`. +#[derive(Deserialize, Default)] +struct LoginQuery { + #[serde(default)] + next: String, +} + +/// The second-factor form. +#[derive(Deserialize, Default)] +struct TwoFactorForm { + #[serde(default)] + precsrf: String, + #[serde(default)] + code: String, +} + +/// A form with only the session's CSRF token. +#[derive(Deserialize, Default)] +pub struct CsrfForm { + #[serde(default)] + pub csrf: String, +} + +/// `GET /login`. With no users yet, the instance is not set up, so the visitor goes to setup. +#[page("/login")] +async fn login_form(cx: &Cx, Form(query): Form) -> Result { + if app_context::(cx).store.user_count().await? == 0 { + return Err(see_other("/setup").into()); + } + let csrf = pre_csrf_token(cx); + let next = safe_next(Some(&query.next)).to_owned(); + Ok(login_view( + cx, + page_lang(cx, None), + csrf, + String::new(), + next, + None, + false, + )) +} + +/// `POST /login`: the password step. +#[page(POST "/login")] +async fn login_submit(cx: &Cx, Form(form): Form) -> Result { + if !check_pre_csrf(cx, &form.precsrf) { + return Err(forbidden().into()); + } + let state = app_context::(cx); + let csrf = pre_csrf_token(cx); + let next = safe_next(Some(&form.next)).to_owned(); + let email = normalize_email(&form.email); + let user_limit = user_key(&email); + let ip_limit = ip_key("login-ip", client_ip(cx)); + let now = Instant::now(); + + // A key over its limit answers with the throttle message and a Retry-After, before any lookup. + let wait = [(&user_limit, LOGIN_USER_LIMIT), (&ip_limit, LOGIN_IP_LIMIT)] + .iter() + .filter_map(|(key, limit)| state.throttle.check(key, *limit, now)) + .max(); + if let Some(wait) = wait { + retry_after(cx, wait); + let lang = page_lang(cx, None); + return Ok(login_view( + cx, + lang, + csrf, + form.email, + next, + Some(Failure::Throttled), + true, + )); + } + + let found = state.store.user_by_email_folded(&email).await?; + let hash = match &found { + Some(user) => user.password_hash.clone(), + None => dummy_hash().await?, + }; + let password_ok = verify_password_async(form.password.clone(), hash).await?; + let target_id = found.as_ref().map(|user| user.id.clone()); + let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { + state.throttle.record_failure(&user_limit, now); + state.throttle.record_failure(&ip_limit, now); + let target = target_id.as_deref().map(|id| ("user", id)); + record( + cx, + Actor::Anonymous, + AuditAction::LoginFailed, + target, + json!({ "reason": "credentials" }), + ) + .await; + let lang = page_lang(cx, None); + return Ok(login_view( + cx, + lang, + csrf, + form.email, + next, + Some(Failure::Invalid), + false, + )); + }; + + state.throttle.clear(&user_limit); + if user.totp_enabled() { + set_pending_login(cx, &state.key, &user.id, &next)?; + return Err(see_other("/login/2fa").into()); + } + Err(finish_sign_in(cx, &user, amr::PASSWORD, &next).await?) +} + +/// `GET /login/2fa`. Needs a pending password step; without one, back to sign-in. +#[page("/login/2fa")] +async fn two_factor_form(cx: &Cx) -> Result { + let state = app_context::(cx); + if pending_login(cx, &state.key).is_none() { + return Err(see_other("/login").into()); + } + let csrf = pre_csrf_token(cx); + Ok(two_factor_view(cx, page_lang(cx, None), csrf, None, false)) +} + +/// `POST /login/2fa`: a six-digit code, or a recovery code. +#[page(POST "/login/2fa")] +async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result { + if !check_pre_csrf(cx, &form.precsrf) { + return Err(forbidden().into()); + } + let state = app_context::(cx); + let Some(pending) = pending_login(cx, &state.key) else { + return Err(see_other("/login").into()); + }; + let user = match state.store.user_by_id(&pending.user_id).await? { + Some(user) if !user.is_disabled() && user.totp_enabled() => user, + _ => { + clear_pending_login(cx); + return Err(see_other("/login").into()); + } + }; + let csrf = pre_csrf_token(cx); + let limit = two_factor_key(&user.id); + let now = Instant::now(); + if let Some(wait) = state.throttle.check(&limit, TWO_FACTOR_USER_LIMIT, now) { + retry_after(cx, wait); + return Ok(two_factor_view( + cx, + page_lang(cx, None), + csrf, + Some(Failure::Throttled), + true, + )); + } + + match check_second_factor(&state.store, &state.key, &user, &form.code).await? { + Some(method) => { + state.throttle.clear(&limit); + clear_pending_login(cx); + Err(finish_sign_in(cx, &user, method, &pending.next).await?) + } + None => { + state.throttle.record_failure(&limit, now); + record( + cx, + Actor::User(&user.id), + AuditAction::Login2faFailed, + Some(("user", &user.id)), + Value::Null, + ) + .await; + Ok(two_factor_view( + cx, + page_lang(cx, None), + csrf, + Some(Failure::Code), + false, + )) + } + } +} + +/// `POST /logout`. Ends the current session only; other sessions of the person stay. +#[route(POST "/logout")] +async fn logout(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + end_current_session(cx, &viewer).await?; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::Logout, + Some(("session", &viewer.session.id)), + Value::Null, + ) + .await; + Ok(see_other("/login")) +} + +/// Starts the session, clears the pre-session token, audits the sign-in and sends the person on. +async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Result { + let state = app_context::(cx); + start_session(cx, user, method).await?; + clear_pre_csrf(cx); + record( + cx, + Actor::User(&user.id), + AuditAction::LoginSuccess, + Some(("user", &user.id)), + json!({ "amr": method }), + ) + .await; + Ok(see_other(after_sign_in(state, user, next)).into()) +} + +/// The hash checked against when the email is unknown or the account disabled. Computed once, so +/// the timing of a miss matches the timing of a wrong password. +async fn dummy_hash() -> Result { + static DUMMY: OnceLock = OnceLock::new(); + if let Some(hash) = DUMMY.get() { + return Ok(hash.clone()); + } + let hash = hash_password_async("not-the-password-of-any-account".to_owned()).await?; + Ok(DUMMY.get_or_init(|| hash).clone()) +} + +/// What went wrong on a form, for the message shown above it. +#[derive(Clone, Copy)] +enum Failure { + /// Wrong email, password or account state. One message for all three. + Invalid, + /// The second-factor code was wrong or spent. + Code, + /// The throttle holds the account or the address. + Throttled, +} + +/// Sets `Retry-After` for a throttled answer, in whole seconds, at least one. +fn retry_after(cx: &Cx, wait: Duration) { + if let Ok(value) = HeaderValue::from_str(&wait.as_secs().max(1).to_string()) { + response_headers(cx).append(header::RETRY_AFTER, value); + } +} + +/// The sign-in page. The typed email comes back; the password never does. +fn login_view( + cx: &Cx, + lang: Lang, + csrf: String, + email: String, + next: String, + failure: Option, + throttled: bool, +) -> impl View { + let problem = failure.map(|failure| failure_text(lang, failure)); + view! { cx => + if throttled { + (StatusCode::TOO_MANY_REQUESTS) + } + shell(title: text(lang, Txt::SignIn), lang: lang, viewer: None, +
+

(text(lang, Txt::SignIn))

+ if let Some(problem) = problem { + alert(message: problem) + } +
+ + + field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: email) + field(label: text(lang, Txt::Password), name: "password", kind: "password", autocomplete: "current-password", value: String::new()) + +
+
+ ) + } +} + +/// The second-factor page. +fn two_factor_view( + cx: &Cx, + lang: Lang, + csrf: String, + failure: Option, + throttled: bool, +) -> impl View { + let problem = failure.map(|failure| failure_text(lang, failure)); + view! { cx => + if throttled { + (StatusCode::TOO_MANY_REQUESTS) + } + shell(title: text(lang, Txt::TwoFactorTitle), lang: lang, viewer: None, +
+

(text(lang, Txt::TwoFactorTitle))

+

(text(lang, Txt::TwoFactorIntro))

+ if let Some(problem) = problem { + alert(message: problem) + } +
+ + field(label: text(lang, Txt::Code), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new()) + +
+
+ ) + } +} + +/// The message for a failure on either sign-in form. +fn failure_text(lang: Lang, failure: Failure) -> String { + match failure { + Failure::Invalid => text(lang, Txt::ErrInvalidLogin), + Failure::Code => text(lang, Txt::ErrCodeInvalid), + Failure::Throttled => text(lang, Txt::ErrThrottled), + } + .to_owned() +} diff --git a/crates/im-web/src/pages/mod.rs b/crates/im-web/src/pages/mod.rs index 2f18c8a..1ca76fd 100644 --- a/crates/im-web/src/pages/mod.rs +++ b/crates/im-web/src/pages/mod.rs @@ -1,4 +1,11 @@ //! The pages and the page-level layers. One file per page. pub mod home; +pub mod login; pub mod not_found; +pub mod security; +pub mod sessions; +pub mod setup; + +#[cfg(test)] +mod tests; diff --git a/crates/im-web/src/pages/security.rs b/crates/im-web/src/pages/security.rs new file mode 100644 index 0000000..47f383d --- /dev/null +++ b/crates/im-web/src/pages/security.rs @@ -0,0 +1,637 @@ +//! The security page: the password, two-factor sign-in and the recovery codes of the signed-in +//! person. Each change is a POST that checks the CSRF token first and then redirects (PRG), except +//! where the codes are shown: those render on the POST response, once. + +use std::time::Instant; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; +use im_core::model::AuditAction; +use im_core::password::{check_policy, hash_password_async, verify_password_async}; +use im_core::secret; +use im_core::totp; +use serde::Deserialize; +use serde_json::json; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::see_other; +use topcoat::router::page; +use topcoat::view::{View, component, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{Viewer, check_second_factor, require_csrf, require_user, unix_now}; +use crate::i18n::Lang; +use crate::i18n::account::{Txt, policy_problem, recovery_left, text}; +use crate::live::Topic; +use crate::state::AppState; +use crate::throttle::{LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, two_factor_key, user_key}; +use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; + +/// How many recovery codes one issue gives. +const RECOVERY_CODES: usize = 10; + +/// The query of `GET /account/security`. +#[derive(Deserialize, Default)] +struct NoticeQuery { + #[serde(default)] + notice: String, +} + +/// The password change form. +#[derive(Deserialize, Default)] +struct PasswordForm { + #[serde(default)] + csrf: String, + #[serde(default)] + current_password: String, + #[serde(default)] + new_password: String, + #[serde(default)] + new_password_again: String, +} + +/// A form with a CSRF token and one six-digit code (or recovery code). +#[derive(Deserialize, Default)] +struct CodeForm { + #[serde(default)] + csrf: String, + #[serde(default)] + code: String, +} + +/// The turn-off form: the password and a second factor. +#[derive(Deserialize, Default)] +struct DisableForm { + #[serde(default)] + csrf: String, + #[serde(default)] + current_password: String, + #[serde(default)] + code: String, +} + +/// The recovery-code form: the password only. +#[derive(Deserialize, Default)] +struct RecoveryForm { + #[serde(default)] + csrf: String, + #[serde(default)] + current_password: String, +} + +/// What the page shows above its sections: a notice, an error, or freshly issued codes. +#[derive(Default)] +struct Flash { + notice: Option, + alert: Option, + codes: Vec, +} + +impl Flash { + fn alert(message: impl Into) -> Self { + Self { + alert: Some(message.into()), + ..Self::default() + } + } +} + +/// A pending enrolment, ready to show: the base32 secret, the otpauth link and the QR code. +struct Enrolment { + secret: String, + link: String, + qr: String, +} + +/// `GET /account/security`. +#[page("/account/security")] +async fn security_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_user(cx).await?; + let lang = page_lang(cx, Some(&viewer)); + let flash_notice = match query.notice.as_str() { + "enrol" => Some(text(lang, Txt::EnrolSecurityNotice)), + "saved-password" => Some(text(lang, Txt::SavedPassword)), + "saved-2fa-on" => Some(text(lang, Txt::Saved2faOn)), + "saved-2fa-off" => Some(text(lang, Txt::Saved2faOff)), + _ => None, + }; + let flash = Flash { + notice: flash_notice.map(str::to_owned), + ..Flash::default() + }; + render_security(cx, viewer.clone(), flash).await +} + +/// `POST /account/security/password`. +#[page(POST "/account/security/password")] +async fn change_password(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + if password_locked(state, &viewer) { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrThrottled)), + ) + .await; + } + if !password_matches(state, &viewer, &form.current_password).await? { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrWrongPassword)), + ) + .await; + } + if form.new_password != form.new_password_again { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrPasswordsDiffer)), + ) + .await; + } + if let Err(violation) = check_policy(&form.new_password, &viewer.user.email, &viewer.user.name) + { + let message = policy_problem(lang, violation); + return render_security(cx, viewer.clone(), Flash::alert(message)).await; + } + if verify_password_async(form.new_password.clone(), viewer.user.password_hash.clone()).await? { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrPasswordSame)), + ) + .await; + } + + let hash = hash_password_async(form.new_password.clone()).await?; + state + .store + .set_password_hash(&viewer.user.id, &hash) + .await?; + // Every other session of the person ends with the old password. This one stays signed in. + let ended = state + .store + .end_other_sessions(&viewer.user.id, &viewer.session.id) + .await?; + changed(state, &viewer); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::PasswordChanged, + Some(("user", &viewer.user.id)), + json!({ "sessions_ended": ended.len() }), + ) + .await; + Err(see_other("/account/security?notice=saved-password").into()) +} + +/// `POST /account/security/2fa/start`: starts an enrolment. Turning on needs no code; replacing an +/// authenticator of an account that already has two-factor sign-in needs its current code. +#[page(POST "/account/security/2fa/start")] +async fn start_enrolment(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + if viewer.user.totp_enabled() { + if form.code.trim().is_empty() { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrCodeMissing)), + ) + .await; + } + let limit = two_factor_key(&viewer.user.id); + let now = Instant::now(); + if state + .throttle + .check(&limit, TWO_FACTOR_USER_LIMIT, now) + .is_some() + { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrThrottled)), + ) + .await; + } + if check_second_factor(&state.store, &state.key, &viewer.user, &form.code) + .await? + .is_none() + { + state.throttle.record_failure(&limit, now); + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrCodeInvalid)), + ) + .await; + } + } + let secret = totp::new_secret(); + let sealed = secret::seal(&state.key, &secret)?; + state + .store + .set_totp_pending(&viewer.user.id, &sealed) + .await?; + Err(see_other("/account/security").into()) +} + +/// `POST /account/security/2fa/confirm`: the first code from the new authenticator turns +/// two-factor sign-in on, and issues the recovery codes, shown once. +#[page(POST "/account/security/2fa/confirm")] +async fn confirm_enrolment(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + let Some(sealed) = state.store.totp_pending(&viewer.user.id).await? else { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrNoPending)), + ) + .await; + }; + let shared = secret::open(&state.key, &sealed)?; + let last = viewer + .user + .totp_last_step + .and_then(|step| u64::try_from(step).ok()); + let Some(step) = totp::verify(&shared, form.code.trim(), totp::step_for(unix_now()), last) + else { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrCodeInvalid)), + ) + .await; + }; + + let codes = issue_codes(); + let hashes: Vec = codes + .iter() + .map(|code| totp::recovery_code_hash(code)) + .collect(); + state + .store + .enable_totp(&viewer.user.id, &sealed, step, &hashes) + .await?; + changed(state, &viewer); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::TotpEnabled, + Some(("user", &viewer.user.id)), + json!({ "recovery_codes": codes.len() }), + ) + .await; + // Reload the person, so the page shows two-factor sign-in as on. + let user = state + .store + .user_by_id(&viewer.user.id) + .await? + .ok_or(im_core::Error::NotFound)?; + let viewer = Viewer { user, ..viewer }; + let flash = Flash { + notice: Some(text(lang, Txt::Saved2faOn).to_owned()), + codes, + ..Flash::default() + }; + render_security(cx, viewer.clone(), flash).await +} + +/// `POST /account/security/2fa/disable`: needs the password and a second factor. +#[page(POST "/account/security/2fa/disable")] +async fn disable_two_factor(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + if !viewer.user.totp_enabled() { + return Err(see_other("/account/security").into()); + } + if password_locked(state, &viewer) { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrThrottled)), + ) + .await; + } + if !password_matches(state, &viewer, &form.current_password).await? { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrWrongPassword)), + ) + .await; + } + let limit = two_factor_key(&viewer.user.id); + let now = Instant::now(); + if state + .throttle + .check(&limit, TWO_FACTOR_USER_LIMIT, now) + .is_some() + { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrThrottled)), + ) + .await; + } + if form.code.trim().is_empty() { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrCodeMissing)), + ) + .await; + } + if check_second_factor(&state.store, &state.key, &viewer.user, &form.code) + .await? + .is_none() + { + state.throttle.record_failure(&limit, now); + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrCodeInvalid)), + ) + .await; + } + + state.store.disable_totp(&viewer.user.id).await?; + state.throttle.clear(&limit); + changed(state, &viewer); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::TotpDisabled, + Some(("user", &viewer.user.id)), + json!({}), + ) + .await; + Err(see_other("/account/security?notice=saved-2fa-off").into()) +} + +/// `POST /account/security/recovery`: replaces the recovery codes. The old codes stop working. +#[page(POST "/account/security/recovery")] +async fn regenerate_recovery(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + if !viewer.user.totp_enabled() { + return Err(see_other("/account/security").into()); + } + if password_locked(state, &viewer) { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrThrottled)), + ) + .await; + } + if !password_matches(state, &viewer, &form.current_password).await? { + return render_security( + cx, + viewer.clone(), + Flash::alert(text(lang, Txt::ErrWrongPassword)), + ) + .await; + } + + let codes = issue_codes(); + let hashes: Vec = codes + .iter() + .map(|code| totp::recovery_code_hash(code)) + .collect(); + state + .store + .replace_recovery_codes(&viewer.user.id, &hashes) + .await?; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::RecoveryCodesIssued, + Some(("user", &viewer.user.id)), + json!({ "count": codes.len() }), + ) + .await; + let flash = Flash { + codes, + ..Flash::default() + }; + render_security(cx, viewer.clone(), flash).await +} + +/// Fresh recovery codes, in the form people type them (`xxxx-xxxx`). +fn issue_codes() -> Vec { + (0..RECOVERY_CODES) + .map(|_| totp::new_recovery_code()) + .collect() +} + +/// True while the password counters hold the account. Wrong passwords on this page count toward +/// the same limit as sign-in. +fn password_locked(state: &AppState, viewer: &Viewer) -> bool { + state + .throttle + .check( + &user_key(&viewer.user.email), + LOGIN_USER_LIMIT, + Instant::now(), + ) + .is_some() +} + +/// Checks the password of the signed-in person and records the outcome in the throttle. +async fn password_matches(state: &AppState, viewer: &Viewer, given: &str) -> Result { + let ok = verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await?; + let limit = user_key(&viewer.user.email); + if ok { + state.throttle.clear(&limit); + } else { + state.throttle.record_failure(&limit, Instant::now()); + } + Ok(ok) +} + +/// Tells the open account pages that the person's security changed. +fn changed(state: &AppState, viewer: &Viewer) { + state.live.bump(&Topic::Account(viewer.user.id.clone())); +} + +/// Builds the QR code of a secret as a `data:` image, so no request leaves the page for it. +fn enrolment_of(state: &AppState, viewer: &Viewer, sealed: &str) -> Result { + let shared = secret::open(&state.key, sealed)?; + let link = totp::otpauth_uri(&viewer.user.email, &shared); + let code = qrcode::QrCode::new(link.as_bytes()) + .map_err(|error| topcoat::Error::msg(error.to_string()))?; + let svg = code + .render::() + .min_dimensions(240, 240) + .build(); + Ok(Enrolment { + secret: totp::base32_encode(&shared), + link, + qr: format!("data:image/svg+xml;base64,{}", BASE64.encode(svg)), + }) +} + +/// The security page: reads what the sections show, then renders them. +async fn render_security(cx: &Cx, viewer: Viewer, flash: Flash) -> Result { + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + let pending = match state.store.totp_pending(&viewer.user.id).await? { + Some(sealed) => Some(enrolment_of(state, &viewer, &sealed)?), + None => None, + }; + let enabled = viewer.user.totp_enabled(); + let unused = if enabled { + state.store.unused_recovery_codes(&viewer.user.id).await? + } else { + 0 + }; + let info = ViewerInfo::of(&viewer); + let csrf = viewer.session.csrf_token.clone(); + Ok(security_view( + cx, lang, info, csrf, enabled, unused, pending, flash, + )) +} + +/// The markup of the security page. It owns everything it shows, so it can outlive the handler. +#[allow(clippy::too_many_arguments)] +fn security_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + enabled: bool, + unused: u64, + pending: Option, + flash: Flash, +) -> impl View { + let has_pending = pending.is_some(); + let Flash { + notice: flash_notice, + alert: flash_alert, + codes, + } = flash; + view! { cx => + shell(title: text(lang, Txt::SecurityTitle), lang: lang, viewer: Some(info), +
+

(text(lang, Txt::SecurityTitle))

+ if let Some(message) = flash_notice { + notice(message: message) + } + if let Some(message) = flash_alert { + alert(message: message) + } + +
+

(text(lang, Txt::PasswordSection))

+

(text(lang, Txt::PasswordHelp))

+
+ + field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new()) + field(label: text(lang, Txt::NewPassword), name: "new_password", kind: "password", autocomplete: "new-password", value: String::new()) + field(label: text(lang, Txt::NewPasswordAgain), name: "new_password_again", kind: "password", autocomplete: "new-password", value: String::new()) +

(text(lang, Txt::PasswordHint))

+ +
+
+ +
+

(text(lang, Txt::TwoFactorSection))

+ if enabled { +

(text(lang, Txt::TwoFactorOnText))

+ } else { +

(text(lang, Txt::TwoFactorOffText))

+ } + if let Some(pending) = pending { + enrolment_block(lang: lang, csrf: csrf.clone(), secret: pending.secret, link: pending.link, qr: pending.qr) + } + if enabled { +
+

(text(lang, Txt::ReplaceTitle))

+

(text(lang, Txt::ReplaceHelp))

+
+ + field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new()) + +
+
+ +
+

(text(lang, Txt::RecoveryTitle))

+

(text(lang, Txt::RecoveryHelp))

+

(recovery_left(lang, unused))

+

(text(lang, Txt::RegenerateHelp))

+
+ + field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new()) + +
+
+ +
+

(text(lang, Txt::DisableTitle))

+

(text(lang, Txt::DisableHelp))

+
+ + field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new()) + field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new()) + +
+
+ } else if !has_pending { +
+ + +
+ } + if !codes.is_empty() { +
+

(text(lang, Txt::NewCodesTitle))

+

(text(lang, Txt::CodesShownOnce))

+
    + for code in codes { +
  • (code)
  • + } +
+
+ } +
+
+ ) + } +} + +/// A pending enrolment: the QR code, the secret to type, and the form that confirms the first code. +#[component] +async fn enrolment_block( + lang: Lang, + csrf: String, + secret: String, + link: String, + qr: String, +) -> Result { + Ok(view! { +
+

(text(lang, Txt::PendingTitle))

+

(text(lang, Txt::PendingHelp))

+ (text(lang, +

(text(lang, Txt::SecretKey)) (secret)

+

(text(lang, Txt::SetupLink))

+
+ + field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new()) + +
+
+ }) +} diff --git a/crates/im-web/src/pages/sessions.rs b/crates/im-web/src/pages/sessions.rs new file mode 100644 index 0000000..c901c5c --- /dev/null +++ b/crates/im-web/src/pages/sessions.rs @@ -0,0 +1,247 @@ +//! The session list of the signed-in person: where each session was made, and the buttons that end +//! one session or every other one. Ending the current session signs the browser out. + +use im_core::model::{AuditAction, Session}; +use serde::Deserialize; +use serde_json::json; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::{page, route}; +use topcoat::view::{View, component, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{Viewer, end_current_session, require_csrf, require_user}; +use crate::i18n::Lang; +use crate::i18n::account::{Txt, device_label, text}; +use crate::live::Topic; +use crate::state::AppState; +use crate::views::{ViewerInfo, notice, page_lang, shell}; + +/// The query of `GET /account/sessions`. +#[derive(Deserialize, Default)] +struct SessionsQuery { + #[serde(default)] + notice: String, +} + +/// The form that ends one session. +#[derive(Deserialize, Default)] +struct RevokeForm { + #[serde(default)] + csrf: String, + #[serde(default)] + session_id: String, +} + +/// A form with only the CSRF token. +#[derive(Deserialize, Default)] +struct CsrfOnly { + #[serde(default)] + csrf: String, +} + +/// `GET /account/sessions`. +#[page("/account/sessions")] +async fn sessions_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_user(cx).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + let sessions = state.store.list_sessions(&viewer.user.id).await?; + let flash = match query.notice.as_str() { + "saved-session" => Some(text(lang, Txt::SavedSession).to_owned()), + "saved-others" => Some(text(lang, Txt::SavedOthers).to_owned()), + _ => None, + }; + let rows: Vec = sessions + .iter() + .map(|session| SessionRow { + device: device_of(lang, session), + ip: session.ip.clone().unwrap_or_default(), + created: session.created_at.clone(), + last_seen: session.last_seen_at.clone(), + session_id: session.id.clone(), + current: session.id == viewer.session.id, + }) + .collect(); + let others = rows.iter().filter(|row| !row.current).count(); + Ok(sessions_view( + cx, + lang, + ViewerInfo::of(&viewer), + viewer.session.csrf_token.clone(), + rows, + others, + flash, + )) +} + +/// The markup of the sessions page. +fn sessions_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + rows: Vec, + others: usize, + flash: Option, +) -> impl View { + view! { cx => + shell(title: text(lang, Txt::SessionsTitle), lang: lang, viewer: Some(info), +
+

(text(lang, Txt::SessionsTitle))

+

(text(lang, Txt::SessionsIntro))

+ if let Some(message) = flash { + notice(message: message) + } +
    + for row in rows { + session_item(lang: lang, csrf: csrf.clone(), row: row) + } +
+ if others > 0 { +
+ + +
+ } else { +

(text(lang, Txt::NoOthers))

+ } +
+ ) + } +} + +/// One line of the session list, with the text already resolved. +struct SessionRow { + device: String, + ip: String, + created: String, + last_seen: String, + session_id: String, + current: bool, +} + +/// `POST /account/sessions/revoke`. Ends one session of the person. Ending the current one signs +/// this browser out. +#[route(POST "/account/sessions/revoke")] +async fn revoke_session(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + if form.session_id == viewer.session.id { + end_current_session(cx, &viewer).await?; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::Logout, + Some(("session", &viewer.session.id)), + json!({ "by": "sessions page" }), + ) + .await; + return Ok(see_other("/login")); + } + if state + .store + .end_session(&viewer.user.id, &form.session_id) + .await? + { + state.live.bump(&Topic::Account(viewer.user.id.clone())); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::SessionRevoked, + Some(("session", &form.session_id)), + json!({}), + ) + .await; + } + Ok(see_other("/account/sessions?notice=saved-session")) +} + +/// `POST /account/sessions/revoke-others`. Ends every session but the current one. +#[route(POST "/account/sessions/revoke-others")] +async fn revoke_others(cx: &Cx, Form(form): Form) -> Result { + let viewer: Viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let ended = state + .store + .end_other_sessions(&viewer.user.id, &viewer.session.id) + .await?; + if !ended.is_empty() { + state.live.bump(&Topic::Account(viewer.user.id.clone())); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::SessionsRevoked, + Some(("user", &viewer.user.id)), + json!({ "count": ended.len() }), + ) + .await; + } + Ok(see_other("/account/sessions?notice=saved-others")) +} + +/// The device name of a session, from its user agent. An unknown browser or system gets the +/// translated fallback. +fn device_of(lang: Lang, session: &Session) -> String { + let agent = session.user_agent.as_deref().unwrap_or(""); + let browser = if agent.contains("Edg/") { + Some("Edge") + } else if agent.contains("OPR/") { + Some("Opera") + } else if agent.contains("Firefox/") { + Some("Firefox") + } else if agent.contains("Chrome/") || agent.contains("Chromium/") { + Some("Chrome") + } else if agent.contains("Safari/") { + Some("Safari") + } else { + None + }; + let system = if agent.contains("Android") { + Some("Android") + } else if agent.contains("iPhone") || agent.contains("iPad") { + Some("iOS") + } else if agent.contains("Windows") { + Some("Windows") + } else if agent.contains("Mac OS X") { + Some("macOS") + } else if agent.contains("Linux") { + Some("Linux") + } else { + None + }; + device_label( + lang, + browser.unwrap_or(text(lang, Txt::UnknownBrowser)), + system.unwrap_or(text(lang, Txt::UnknownSystem)), + ) +} + +/// One session in the list: the device, where and when it was used, and the button that ends it. +#[component] +async fn session_item(lang: Lang, csrf: String, row: SessionRow) -> Result { + Ok(view! { +
  • +
    + (row.device.clone()) + if row.current { + (text(lang, Txt::ThisSession)) + } +
    + (text(lang, Txt::SignedInAt))": "(row.created.clone()) + " \u{b7} "(text(lang, Txt::LastSeen))": "(row.last_seen.clone()) + " \u{b7} "(text(lang, Txt::AddressLabel))": "(row.ip.clone()) +
    +
    + if !row.current { +
    + + + +
    + } +
  • + }) +} diff --git a/crates/im-web/src/pages/setup.rs b/crates/im-web/src/pages/setup.rs new file mode 100644 index 0000000..86f11d3 --- /dev/null +++ b/crates/im-web/src/pages/setup.rs @@ -0,0 +1,140 @@ +//! First-run setup. While no user exists, `GET /setup` shows the form that creates the first +//! administrator. Once a user exists, both the page and its POST are a 404, so the route does not +//! reveal that the instance was set up. + +use im_core::model::{AuditAction, amr}; +use im_core::names::{normalize_email, parse_email}; +use im_core::password::{check_policy, hash_password_async}; +use serde::Deserialize; +use serde_json::Value; +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; +use topcoat::view::{View, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session}; +use crate::i18n::Lang; +use crate::i18n::account::{Txt, policy_problem, text}; +use crate::state::AppState; +use crate::views::{alert, field, page_lang, shell}; + +/// The fields of the setup form. Every field defaults to empty, so a missing one is a failed check +/// (403 for the token, a message for the rest), not a 400. +#[derive(Deserialize, Default)] +struct SetupForm { + #[serde(default)] + precsrf: String, + #[serde(default)] + name: String, + #[serde(default)] + email: String, + #[serde(default)] + password: String, + #[serde(default)] + password_again: String, +} + +/// `GET /setup`. +#[page("/setup")] +async fn setup_form(cx: &Cx) -> Result { + if app_context::(cx).store.user_count().await? > 0 { + return Err(not_found().into()); + } + let csrf = pre_csrf_token(cx); + let lang = page_lang(cx, None); + Ok(setup_view( + cx, + lang, + csrf, + String::new(), + String::new(), + None, + )) +} + +/// `POST /setup`. Creates the first administrator, signs them in and sends them on. +#[page(POST "/setup")] +async fn setup_submit(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + if state.store.user_count().await? > 0 { + return Err(not_found().into()); + } + if !check_pre_csrf(cx, &form.precsrf) { + return Err(forbidden().into()); + } + let csrf = pre_csrf_token(cx); + let lang = page_lang(cx, None); + let name = form.name.trim().to_owned(); + let typed_email = form.email.clone(); + + let problem = + if name.is_empty() || name.chars().count() > 200 || name.chars().any(char::is_control) { + Some(text(lang, Txt::ErrNameInvalid).to_owned()) + } else { + match parse_email(&normalize_email(&form.email)) { + Err(_) => Some(text(lang, Txt::ErrEmailInvalid).to_owned()), + Ok(email) => match check_policy(&form.password, &email, &name) { + Err(violation) => Some(policy_problem(lang, violation)), + Ok(()) if form.password != form.password_again => { + Some(text(lang, Txt::ErrPasswordsDiffer).to_owned()) + } + Ok(()) => None, + }, + } + }; + if let Some(problem) = problem { + return Ok(setup_view(cx, lang, csrf, name, typed_email, Some(problem))); + } + + let email = parse_email(&normalize_email(&form.email))?; + let hash = hash_password_async(form.password.clone()).await?; + let user = match state.store.create_first_admin(&email, &name, &hash).await { + Ok(user) => user, + // Another setup finished first; the page no longer exists for this request either. + Err(im_core::Error::Conflict(_)) => return Err(not_found().into()), + Err(error) => return Err(error.into()), + }; + start_session(cx, &user, amr::PASSWORD).await?; + clear_pre_csrf(cx); + record( + cx, + Actor::User(&user.id), + AuditAction::SetupDone, + Some(("user", &user.id)), + Value::Null, + ) + .await; + Err(see_other(after_sign_in(state, &user, "/")).into()) +} + +/// The setup page. The typed name and email come back; passwords never do. +fn setup_view( + cx: &Cx, + lang: Lang, + csrf: String, + name: String, + email: String, + problem: Option, +) -> impl View { + view! { cx => shell(title: text(lang, Txt::SetupTitle), lang: lang, viewer: None, +
    +

    (text(lang, Txt::SetupTitle))

    +

    (text(lang, Txt::SetupIntro))

    + if let Some(problem) = problem { + alert(message: problem) + } +
    + + field(label: text(lang, Txt::Name), name: "name", kind: "text", autocomplete: "name", value: name) + field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: email) + field(label: text(lang, Txt::Password), name: "password", kind: "password", autocomplete: "new-password", value: String::new()) + field(label: text(lang, Txt::NewPasswordAgain), name: "password_again", kind: "password", autocomplete: "new-password", value: String::new()) +

    (text(lang, Txt::PasswordHint))

    + +
    +
    + ) } +} diff --git a/crates/im-web/src/pages/tests.rs b/crates/im-web/src/pages/tests.rs new file mode 100644 index 0000000..b313963 --- /dev/null +++ b/crates/im-web/src/pages/tests.rs @@ -0,0 +1,105 @@ +//! In-process tests of the forms: a request goes through the whole router, as a browser's would. +//! They cover the checks that must run before any side effect. + +use std::time::Duration; + +use http::header::{CONTENT_TYPE, COOKIE}; +use im_core::password::hash_password; +use im_core::store::sessions::NewSession; +use im_core::token::{generate_token, hash_token}; +use topcoat::router::{Body, to_bytes}; + +use crate::boot::{router, test_state}; +use crate::state::AppState; + +/// The cookie name the browser sends: the `__Host-` prefix is added by the jar. +const COOKIE_NAME: &str = "__Host-im_session"; + +/// Sends a form POST, with an optional session cookie, and returns the status and body. +async fn post_form(state: AppState, path: &str, cookie: Option<&str>, body: &str) -> (u16, String) { + let mut request = + http::Request::post(path).header(CONTENT_TYPE, "application/x-www-form-urlencoded"); + if let Some(cookie) = cookie { + request = request.header(COOKIE, format!("{COOKIE_NAME}={cookie}")); + } + let request = request.body(Body::from(body.to_owned())).expect("request"); + let response = router(state).handle(request).await; + let status = response.status().as_u16(); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("body"); + (status, String::from_utf8_lossy(&bytes).into_owned()) +} + +/// A signed-in session for a fresh account. Returns the cookie value. +async fn signed_in(state: &AppState) -> String { + let hash = hash_password("the current password").expect("hash"); + let user = state + .store + .create_user("ada@example.com", "Ada", &hash, true) + .await + .expect("user"); + let token = generate_token(); + state + .store + .create_session( + &NewSession { + user_id: &user.id, + token_hash: &hash_token(&token), + csrf_token: &generate_token(), + amr: "pwd", + ip: None, + user_agent: None, + ttl: Duration::from_secs(3600), + }, + 10, + ) + .await + .expect("session"); + token +} + +#[tokio::test] +async fn a_sign_in_post_without_the_pre_session_token_is_forbidden() { + let (_dir, state) = test_state().await; + let (status, _) = post_form(state, "/login", None, "email=ada%40example.com&password=x").await; + assert_eq!(status, 403); +} + +#[tokio::test] +async fn a_password_change_without_the_csrf_token_is_forbidden() { + let (_dir, state) = test_state().await; + let token = signed_in(&state).await; + let body = "current_password=the+current+password&new_password=a+brand+new+phrase&new_password_again=a+brand+new+phrase"; + let (status, _) = post_form( + state.clone(), + "/account/security/password", + Some(&token), + body, + ) + .await; + assert_eq!(status, 403); + // The password was not touched: the old one still signs in. + let user = state + .store + .user_by_email_folded("ada@example.com") + .await + .expect("query") + .expect("user"); + assert!(im_core::password::verify_password( + "the current password", + &user.password_hash + )); +} + +#[tokio::test] +async fn setup_is_not_found_once_a_user_exists() { + let (_dir, state) = test_state().await; + signed_in(&state).await; + let get = http::Request::get("/setup") + .body(Body::empty()) + .expect("request"); + assert_eq!(router(state.clone()).handle(get).await.status(), 404); + let (status, _) = post_form(state, "/setup", None, "precsrf=x").await; + assert_eq!(status, 404); +} diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index 5c4f8ca..7df15e9 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -6,9 +6,9 @@ use im_core::config::Config; use im_core::store::Store; use crate::live::LiveHub; +use crate::throttle::Throttle; /// Everything a request handler reaches through the app context. Every field is cheap to clone. -#[allow(dead_code)] // The key and the hub are read by the sign-in and live pages that come next. #[derive(Clone)] pub struct AppState { /// The configuration the process booted with. @@ -19,4 +19,6 @@ pub struct AppState { pub key: Arc<[u8; 32]>, /// The change counters of the live pages. pub live: Arc, + /// Failed sign-in and second-factor counters. + pub throttle: Arc, } diff --git a/crates/im-web/src/throttle.rs b/crates/im-web/src/throttle.rs new file mode 100644 index 0000000..bbc6749 --- /dev/null +++ b/crates/im-web/src/throttle.rs @@ -0,0 +1,185 @@ +//! In-memory sliding-window failure counters that slow down password guessing. +//! +//! Each key keeps the instants of its recent failures, and is limited while it has `limit` of them +//! inside [`WINDOW`]. Only rejected attempts are recorded, so a locked key stops growing. Memory is +//! bounded: expired instants and empty keys are pruned every few hundred failures, and at the key +//! cap the key whose latest failure is oldest is evicted. +//! +//! The counters live in one process. A restart clears them, and two processes would each count +//! their own. `im` runs as one process, so this is the whole picture. + +use std::collections::{HashMap, VecDeque}; +use std::net::IpAddr; +use std::sync::{Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +/// Length of the failure window. +pub const WINDOW: Duration = Duration::from_secs(15 * 60); + +/// Failed sign-ins allowed per normalised email address inside [`WINDOW`]. Also counts wrong +/// passwords on the security page, so guessing there locks sign-in too. +pub const LOGIN_USER_LIMIT: usize = 10; + +/// Failed sign-ins allowed per client address inside [`WINDOW`]. +pub const LOGIN_IP_LIMIT: usize = 30; + +/// Failed second-factor checks allowed per user inside [`WINDOW`]. +pub const TWO_FACTOR_USER_LIMIT: usize = 10; + +/// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past +/// this. +const MAX_KEYS: usize = 100_000; + +/// A full prune runs every this many recorded failures. +const PRUNE_EVERY: u32 = 256; + +/// The failure counters of the process. Shared by every request through the app state. +pub struct Throttle { + window: Duration, + max_keys: usize, + state: Mutex, +} + +#[derive(Default)] +struct State { + failures: HashMap>, + recorded: u32, +} + +impl Default for Throttle { + fn default() -> Self { + Self::with_limits(WINDOW, MAX_KEYS) + } +} + +impl Throttle { + /// Counters with a custom window and key cap. Tests use short windows. + pub fn with_limits(window: Duration, max_keys: usize) -> Self { + Self { + window, + max_keys: max_keys.max(1), + state: Mutex::new(State::default()), + } + } + + /// How long until `key` drops below `limit` failures, or `None` when it is not limited. + pub fn check(&self, key: &str, limit: usize, now: Instant) -> Option { + let mut state = self.lock(); + let timestamps = state.failures.get_mut(key)?; + drop_expired(timestamps, self.window, now); + if timestamps.len() < limit { + return None; + } + // The failure at this index leaves the window first, and that brings the count below limit. + let index = timestamps.len().checked_sub(limit)?; + let oldest = *timestamps.get(index)?; + Some((oldest + self.window).saturating_duration_since(now)) + } + + /// Records one rejected attempt for `key` at `now`. + pub fn record_failure(&self, key: &str, now: Instant) { + let mut state = self.lock(); + state.recorded = state.recorded.wrapping_add(1); + if state.recorded.is_multiple_of(PRUNE_EVERY) { + self.prune_locked(&mut state, now); + } + if !state.failures.contains_key(key) && state.failures.len() >= self.max_keys { + self.evict_oldest_locked(&mut state); + } + let timestamps = state.failures.entry(key.to_owned()).or_default(); + drop_expired(timestamps, self.window, now); + timestamps.push_back(now); + } + + /// Forgets the failures of `key`, after a success. + pub fn clear(&self, key: &str) { + self.lock().failures.remove(key); + } + + /// Drops expired failures and the keys left empty. + fn prune_locked(&self, state: &mut State, now: Instant) { + let window = self.window; + state.failures.retain(|_, timestamps| { + drop_expired(timestamps, window, now); + !timestamps.is_empty() + }); + } + + /// Removes the key whose latest failure is the oldest. Runs only when the cap is reached. + fn evict_oldest_locked(&self, state: &mut State) { + let victim = state + .failures + .iter() + .filter_map(|(key, timestamps)| timestamps.back().map(|last| (key, *last))) + .min_by_key(|(_, last)| *last) + .map(|(key, _)| key.clone()); + if let Some(key) = victim { + state.failures.remove(&key); + } + } + + fn lock(&self) -> MutexGuard<'_, State> { + // A poisoned lock still holds consistent counters, so the next caller uses it as it is. + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// Removes the failures that have left the window. +fn drop_expired(timestamps: &mut VecDeque, window: Duration, now: Instant) { + while let Some(front) = timestamps.front() { + if now.saturating_duration_since(*front) < window { + break; + } + timestamps.pop_front(); + } +} + +/// Throttle key for a normalised email address. +pub fn user_key(email: &str) -> String { + format!("user:{email}") +} + +/// Throttle key for the second factor of one user, by user id. +pub fn two_factor_key(user_id: &str) -> String { + format!("2fa:{user_id}") +} + +/// Throttle key for an address under a named scope, such as `login-ip`. +pub fn ip_key(scope: &str, ip: IpAddr) -> String { + format!("{scope}:{ip}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_key_is_limited_at_the_threshold_and_free_when_the_window_passes() { + let throttle = Throttle::with_limits(Duration::from_secs(60), 16); + let t0 = Instant::now(); + for i in 0..3 { + let at = t0 + Duration::from_secs(i); + assert!(throttle.check("k", 3, at).is_none()); + throttle.record_failure("k", at); + } + let retry = throttle + .check("k", 3, t0 + Duration::from_secs(10)) + .expect("limited"); + assert_eq!(retry, Duration::from_secs(50)); + assert!( + throttle + .check("k", 3, t0 + Duration::from_secs(60)) + .is_none() + ); + } + + #[test] + fn the_key_count_stays_at_the_cap() { + let throttle = Throttle::with_limits(Duration::from_secs(10), 8); + let t0 = Instant::now(); + for i in 0..1000u64 { + throttle.record_failure(&format!("key-{i}"), t0 + Duration::from_millis(i)); + assert!(throttle.lock().failures.len() <= 8); + } + } +} diff --git a/crates/im-web/src/views/mod.rs b/crates/im-web/src/views/mod.rs index 7eb0b78..5cc1fb2 100644 --- a/crates/im-web/src/views/mod.rs +++ b/crates/im-web/src/views/mod.rs @@ -4,20 +4,43 @@ //! emits an inline script, style or event handler; see `security.rs`. use topcoat::Result; +use topcoat::context::Cx; use topcoat::view::{Child, View, component, view}; use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; -use crate::i18n::Lang; +use crate::auth::Viewer; +use crate::i18n::account::{Txt, text}; use crate::i18n::shell::{K, t}; +use crate::i18n::{Lang, lang as request_lang}; -/// What the shell shows about the signed-in person. Nothing signs a person in yet, so every page -/// is built for an anonymous viewer. -#[allow(dead_code)] // Built by the sign-in code, which comes next. +/// What the shell shows about the signed-in person, and the token of their sign-out form. pub struct ViewerInfo { - /// The name shown in the topbar. + /// The name shown in the account menu. pub name: String, - /// Whether the topbar shows the administrator badge. + /// Whether the menu offers the administration section. pub is_admin: bool, + /// The session's CSRF token, for the sign-out form in the menu. + pub csrf: String, +} + +impl ViewerInfo { + /// What the shell shows for `viewer`, with the token of its sign-out form. + pub fn of(viewer: &Viewer) -> Self { + Self { + name: viewer.user.name.clone(), + is_admin: viewer.user.is_admin, + csrf: viewer.session.csrf_token.clone(), + } + } +} + +/// The language of a page: the signed-in person's stored choice when they have one, else the +/// request's `Accept-Language`. +pub fn page_lang(cx: &Cx, viewer: Option<&Viewer>) -> Lang { + let stored = viewer + .map(|viewer| viewer.user.locale.as_str()) + .filter(|locale| !locale.is_empty()); + request_lang(cx, stored) } /// The HTML document around a page. `title` is the page's own title; the document title adds the @@ -29,7 +52,7 @@ pub struct ViewerInfo { pub async fn shell( title: &str, lang: Lang, - viewer: Option<&ViewerInfo>, + viewer: Option, #[default] child: Child<'_>, ) -> Result { let document_title = format!("{title} \u{b7} im"); @@ -51,10 +74,7 @@ pub async fn shell(
    if let Some(viewer) = viewer { - (viewer.name.as_str()) - if viewer.is_admin { - (t(lang, K::Admin)) - } + user_menu(lang: lang, viewer: viewer) }
    @@ -64,16 +84,45 @@ pub async fn shell( }) } +/// The account menu of the topbar: the name, the account links and the sign-out button. It is a +/// disclosure element, so it opens without any script. The sign-out form is a full page load, so +/// the browser drops its live stream at once. +#[component] +pub async fn user_menu(lang: Lang, viewer: ViewerInfo) -> Result { + Ok(view! { +
    + + (viewer.name.clone()) + if viewer.is_admin { + (t(lang, K::Admin)) + } + +
    + +
    + + +
    +
    +
    + }) +} + /// An error message for a failed action. Forms show it above their fields. -#[allow(dead_code)] // The first form that can fail a check uses it. #[component] -pub async fn alert(message: &str) -> Result { +pub async fn alert(message: String) -> Result { Ok(view! { }) } /// A plain message that is not an error, such as a confirmation or a hint. #[component] -pub async fn notice(message: &str) -> Result { +pub async fn notice(message: String) -> Result { Ok(view! {
    (message)
    }) } @@ -87,3 +136,20 @@ pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result }) } + +/// A labelled text input. `value` refills the field after an error; password fields pass "". +#[component] +pub async fn field( + label: &str, + name: &'static str, + kind: &'static str, + autocomplete: &'static str, + value: String, +) -> Result { + Ok(view! { + + }) +} diff --git a/style/_components.scss b/style/_components.scss index 99cc0c5..f4f8f1a 100644 --- a/style/_components.scss +++ b/style/_components.scss @@ -313,3 +313,175 @@ textarea::placeholder { transition: none; } } + +// Account pages: the forms, the item lists of the sessions page, the security codes and the +// account menu of the topbar. The views only use these class names; nothing here is inline. + +.stack { + display: grid; + gap: 0.9rem; +} + +.narrow { + max-width: 28rem; + width: 100%; + margin-inline: auto; +} + +.hint { + color: var(--muted); + font-size: 0.875rem; + margin: 0; +} + +.warning { + color: var(--warn); + background: var(--warn-soft); + border-radius: var(--radius); + padding: 0.6rem 0.8rem; + margin: 0; +} + +.facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 0.4rem 1.2rem; + margin: 0; + + dt { + color: var(--muted); + } + + dd { + margin: 0; + } +} + +.links { + display: flex; + flex-wrap: wrap; + gap: 0.4rem 1rem; +} + +.qr { + width: 240px; + height: 240px; + max-width: 100%; + background: #fff; + border-radius: var(--radius); + padding: 0.5rem; +} + +.secret, +.codes-list code { + font-family: var(--font-mono); + overflow-wrap: anywhere; +} + +.codes-list { + list-style: none; + padding: 0; + margin: 0; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); + gap: 0.4rem; + + code { + display: block; + background: var(--surface-2); + border-radius: var(--radius); + padding: 0.4rem 0.6rem; + font-size: 1.05rem; + } +} + +.item-list { + list-style: none; + padding: 0; + margin: 0; + display: grid; + gap: 0.6rem; +} + +.item { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.6rem 1rem; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 0.8rem 1rem; +} + +.item-main { + display: grid; + gap: 0.2rem; + min-width: 0; +} + +.item-action { + margin: 0; +} + +.user-menu { + position: relative; + + summary { + cursor: pointer; + list-style: none; + display: inline-flex; + align-items: center; + gap: 0.4rem; + padding: 0.3rem 0.5rem; + border-radius: var(--radius); + } + + summary::-webkit-details-marker { + display: none; + } + + &[open] > summary { + background: var(--surface-2); + } +} + +.user-menu-name { + font-weight: 600; +} + +.user-menu-panel { + position: absolute; + right: 0; + top: 100%; + margin-top: 0.3rem; + min-width: 12rem; + z-index: 10; + display: grid; + gap: 0.3rem; + padding: 0.3rem; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: 0 8px 24px rgb(0 0 0 / 0.12); +} + +.user-menu-links { + display: grid; + + a { + padding: 0.4rem 0.6rem; + border-radius: 6px; + color: var(--text); + text-decoration: none; + } + + a:hover { + background: var(--surface-2); + } +} + +.user-menu-logout { + margin: 0; +}