diff --git a/crates/iz-core/migrations/0001_init.sql b/crates/iz-core/migrations/0001_init.sql index f52e8ff..8804ff5 100644 --- a/crates/iz-core/migrations/0001_init.sql +++ b/crates/iz-core/migrations/0001_init.sql @@ -7,10 +7,13 @@ -- creation, and Crockford-uppercase already, which is what lets a task key -- borrow its tail. -- --- This file is the whole schema, and it is edited in place: a change to a --- table is made here, in the table, never appended as an ALTER. An existing --- database is brought up to it by `iz reconcile`, not by the store, so a --- change to a table lands in two places — here, and in that tool's copy map. +-- This file is the first migration, not the whole schema any more. It is the +-- shape İz was deployed with before workspace settings could be versioned; +-- everything after it is a numbered `0002_*.sql` beside it, and an empty +-- database is built by applying them in order. A live database is brought up +-- by `iz reconcile`, not by re-running the files, so a change to a table +-- lands in three places — the newest migration, this file's table, and that +-- tool's copy map. CREATE TABLE workspace ( id TEXT PRIMARY KEY, diff --git a/crates/iz-core/migrations/0002_security_knobs.sql b/crates/iz-core/migrations/0002_security_knobs.sql new file mode 100644 index 0000000..e5b11f9 --- /dev/null +++ b/crates/iz-core/migrations/0002_security_knobs.sql @@ -0,0 +1,19 @@ +-- The four security knobs as workspace settings. +-- +-- Until this change the attempt allowance, the rate-limit window, the session +-- lifetime and the sign-in-link lifetime were named consts in `accounts.rs`; +-- they are policy, and policy belongs to the admin on the Settings screen, the +-- way the attachment limits already did. The `DEFAULT` on each column is the +-- backfill: SQLite fills every existing row with it as the column is added. +-- Databases already carrying the columns never see this file applied piecemeal +-- — they reach the declared shape through `iz reconcile`, whose copy map +-- backfills the same numbers. +-- +-- The numbers here mirror `store::DEFAULT_RATE_LIMIT_ATTEMPTS` and its three +-- siblings in `crates/iz-core/src/store/mod.rs` — SQL cannot read a Rust +-- const, so the two lists must be changed together. + +ALTER TABLE workspace ADD COLUMN rate_limit_attempts INTEGER NOT NULL DEFAULT 10; +ALTER TABLE workspace ADD COLUMN rate_window_minutes INTEGER NOT NULL DEFAULT 15; +ALTER TABLE workspace ADD COLUMN session_lifetime_days INTEGER NOT NULL DEFAULT 14; +ALTER TABLE workspace ADD COLUMN signin_link_lifetime_days INTEGER NOT NULL DEFAULT 7; diff --git a/crates/iz-core/src/accounts.rs b/crates/iz-core/src/accounts.rs index 4185104..51c6c6c 100644 --- a/crates/iz-core/src/accounts.rs +++ b/crates/iz-core/src/accounts.rs @@ -21,17 +21,47 @@ use crate::store::{ LinkKind, NewUser, Session, Store, StoreError, User, Workspace, }; -/// How long a first-sign-in link is good for. The mockups say seven days, and -/// an expired link is not a dead account: resending opens the same one. -pub const SIGNIN_LINK_LIFETIME: Duration = Duration::days(7); +/// The account policy as the workspace row states it, read at use: the admin's +/// Settings screen is what sets these, and a const here would be a second +/// opinion the store could not overrule. An unclaimed install has no row to +/// read and stands on the defaults — its sign-in forms are rate-limited all +/// the same. +#[derive(Clone, Copy)] +struct Policy { + rate_limit: u64, + rate_window: Duration, + session_lifetime: Duration, + link_lifetime: Duration, +} -/// How long a signed-in browser stays signed in. -pub const SESSION_LIFETIME: Duration = Duration::days(14); +impl Policy { + /// One indexed read of the workspace row. Callers pay it per use; the + /// sign-in path already reads the row for other reasons. + async fn read(store: &dyn Store) -> Result { + Ok(Self::of(store.workspace().await?.as_ref())) + } -/// The rate-limit window and its allowance. Deliberately modest: this exists so -/// an open form is not an unbounded Argon2 faucet, not to be clever. -pub const RATE_WINDOW: Duration = Duration::minutes(15); -pub const RATE_LIMIT: u64 = 10; + fn of(workspace: Option<&Workspace>) -> Self { + use crate::store::{ + DEFAULT_RATE_LIMIT_ATTEMPTS, DEFAULT_RATE_WINDOW_MINUTES, + DEFAULT_SESSION_LIFETIME_DAYS, DEFAULT_SIGNIN_LINK_LIFETIME_DAYS, + }; + let Some(workspace) = workspace else { + return Self { + rate_limit: DEFAULT_RATE_LIMIT_ATTEMPTS, + rate_window: Duration::minutes(i64::from(DEFAULT_RATE_WINDOW_MINUTES)), + session_lifetime: Duration::days(i64::from(DEFAULT_SESSION_LIFETIME_DAYS)), + link_lifetime: Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS)), + }; + }; + Self { + rate_limit: workspace.rate_limit_attempts, + rate_window: Duration::minutes(i64::from(workspace.rate_window_minutes)), + session_lifetime: Duration::days(i64::from(workspace.session_lifetime_days)), + link_lifetime: Duration::days(i64::from(workspace.signin_link_lifetime_days)), + } + } +} /// What went wrong, in the vocabulary the caller is allowed to have. #[derive(Debug, thiserror::Error)] @@ -228,16 +258,21 @@ impl Accounts { .unwrap_or_else(|| self.fallback_url.clone())) } + /// Mints the invitation link and queues its mail. Minting retires any + /// earlier unspent link for the account: the newest link is the only one + /// that works. async fn mint_link(&self, actor: &User, user: &User) -> Result { + let policy = Policy::read(self.store.as_ref()).await?; let token = Token::mint(); - let expires_at = OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME; + let expires_at = OffsetDateTime::now_utc() + policy.link_lifetime; self.store .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Join) .await?; let subject = "Your İz sign-in link"; let body = format!( - "{actor} added you to İz.\n\n{base}/join/{token}\n\nThe link works once and expires in 7 days.\n", + "{actor} added you to İz.\n\n{base}/join/{token}\n\nThe link works once and expires in {days} days.\n", actor = actor.display_name, + days = policy.link_lifetime.whole_days(), base = self.base().await?, token = token.expose(), ); @@ -334,7 +369,9 @@ impl Accounts { /// account. The answer is the same whether it does or not: the miss path /// pays for an Argon2 hash the way sign-in's pays for a verify, and only /// the queued mail knows the difference. The token travels in the mail - /// and nowhere else — this method hands it to nobody. + /// and nowhere else — this method hands it to nobody. A fresh reset + /// retires the previous unspent one, so the newest mail carries the only + /// working link. /// /// The client bucket refuses outright, like sign-in's. The address bucket /// counts but stays silent: refusing by name would hand anyone who knows @@ -365,12 +402,18 @@ impl Accounts { return Ok(()); } + let policy = Policy::read(self.store.as_ref()).await?; let token = Token::mint(); - let expires_at = now + SIGNIN_LINK_LIFETIME; + let expires_at = now + policy.link_lifetime; self.store .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Reset) .await?; - let (subject, body) = reset_mail(&user, self.base().await?, &token.expose()); + let (subject, body) = reset_mail( + &user, + self.base().await?, + &token.expose(), + policy.link_lifetime.whole_days(), + ); self.store .queue_notice(&user.email, &subject, &body, now) .await?; @@ -464,7 +507,7 @@ impl Accounts { let address_bucket = format!("address:{}", email.trim().to_lowercase()); // The address bucket counts, but it never refuses on its own: refusing // before the verify would let anyone who knows a colleague's address - // lock them out with ten wrong guesses every fifteen minutes. A correct + // lock them out with a few wrong guesses per window. A correct // password always gets in; a wrong one still pays for its Argon2 and // still counts. The client bucket is what caps the work. let address_over_limit = self.over_limit(&address_bucket).await?; @@ -589,13 +632,14 @@ impl Accounts { } async fn start_session(&self, user: User) -> Result { + let policy = Policy::read(self.store.as_ref()).await?; let token = Token::mint(); let session = self .store .create_session( &user.id, &token.hash(), - OffsetDateTime::now_utc() + SESSION_LIFETIME, + OffsetDateTime::now_utc() + policy.session_lifetime, ) .await?; Ok(SignedIn { @@ -625,21 +669,25 @@ impl Accounts { /// The same question without the refusal, for the bucket that counts but /// must not lock an account out. async fn over_limit(&self, bucket: &str) -> Result { - let since = OffsetDateTime::now_utc() - RATE_WINDOW; - Ok(self.store.count_auth_attempts(bucket, since).await? >= RATE_LIMIT) + let policy = Policy::read(self.store.as_ref()).await?; + let since = OffsetDateTime::now_utc() - policy.rate_window; + Ok(self + .store + .count_auth_attempts(bucket, since) + .await? >= policy.rate_limit) } } -/// The reset mail, in the account's own language. Terse like the invitation's: -/// what happened, the link, the once-only fact. -fn reset_mail(user: &User, base: String, token: &str) -> (String, String) { +/// what happened, the link, the once-only fact. The lifetime it names is the +/// workspace's own, so the number travels with the mail. +fn reset_mail(user: &User, base: String, token: &str, days: i64) -> (String, String) { if user.language == "tr" { ( "İz parolanı sıfırla".to_string(), format!( "Bu adres için bir İz parola sıfırlaması istendi.\n\n\ {base}/reset/{token}\n\n\ - Bağlantı bir kez çalışır ve 7 gün içinde geçersiz olur.\n" + Bağlantı bir kez çalışır ve {days} gün içinde geçersiz olur.\n" ), ) } else { @@ -648,7 +696,7 @@ fn reset_mail(user: &User, base: String, token: &str) -> (String, String) { format!( "A reset was asked for the İz password on this address.\n\n\ {base}/reset/{token}\n\n\ - The link works once and expires in 7 days.\n" + The link works once and expires in {days} days.\n" ), ) } diff --git a/crates/iz-core/src/detail.rs b/crates/iz-core/src/detail.rs index 4d7d21f..4ccae2e 100644 --- a/crates/iz-core/src/detail.rs +++ b/crates/iz-core/src/detail.rs @@ -181,6 +181,7 @@ pub enum ActivityKind { ProfileSaved, SenderSaved, LimitsSaved, + SecuritySaved, TestMailSent, RuleCreated, RuleEdited, @@ -213,6 +214,7 @@ impl ActivityKind { ActivityKind::ProfileSaved => "profile_saved", ActivityKind::SenderSaved => "sender_saved", ActivityKind::LimitsSaved => "limits_saved", + ActivityKind::SecuritySaved => "security_saved", ActivityKind::TestMailSent => "test_mail_sent", ActivityKind::RuleCreated => "rule_created", ActivityKind::RuleEdited => "rule_edited", @@ -270,6 +272,7 @@ impl ActivityKind { "profile_saved" => ActivityKind::ProfileSaved, "sender_saved" => ActivityKind::SenderSaved, "limits_saved" => ActivityKind::LimitsSaved, + "security_saved" => ActivityKind::SecuritySaved, "test_mail_sent" => ActivityKind::TestMailSent, "rule_created" => ActivityKind::RuleCreated, "rule_edited" => ActivityKind::RuleEdited, @@ -335,6 +338,7 @@ impl ActivityEntry { | ActivityKind::ProfileSaved | ActivityKind::SenderSaved | ActivityKind::LimitsSaved + | ActivityKind::SecuritySaved | ActivityKind::TestMailSent | ActivityKind::RuleCreated | ActivityKind::RuleEdited diff --git a/crates/iz-core/src/mail.rs b/crates/iz-core/src/mail.rs index b77e32d..4ac5f74 100644 --- a/crates/iz-core/src/mail.rs +++ b/crates/iz-core/src/mail.rs @@ -924,6 +924,7 @@ impl Engine { | ActivityKind::ProfileSaved | ActivityKind::SenderSaved | ActivityKind::LimitsSaved + | ActivityKind::SecuritySaved | ActivityKind::TestMailSent | ActivityKind::RuleCreated | ActivityKind::RuleEdited diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 3eacf8f..c565e6c 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -52,6 +52,16 @@ pub enum StoreError { pub type Result = std::result::Result; +/// The security knobs a fresh workspace starts on, and what a database older +/// than `migrations/0002_security_knobs.sql` is backfilled onto — by that +/// migration's own `DEFAULT` clauses for the rows it meets, and by +/// `reconcile`'s copy map for every database it carries across. The SQL +/// literals mirror these numbers; change the two together. +pub const DEFAULT_RATE_LIMIT_ATTEMPTS: u64 = 10; +pub const DEFAULT_RATE_WINDOW_MINUTES: u32 = 15; +pub const DEFAULT_SESSION_LIFETIME_DAYS: u32 = 14; +pub const DEFAULT_SIGNIN_LINK_LIFETIME_DAYS: u32 = 7; + /// A workspace and the settings that ride on it. /// /// The sender is here except for its password, which has no field on purpose: @@ -89,6 +99,14 @@ pub struct Workspace { /// How long before a task's clock its reminder mail is queued, in /// minutes. `0` turns reminders off. pub reminder_minutes: u32, + /// The sign-in attempts one client or address may spend per window. + pub rate_limit_attempts: u64, + /// How far back the attempt count reaches, in minutes. + pub rate_window_minutes: u32, + /// How long a signed-in browser stays signed in, in days. + pub session_lifetime_days: u32, + /// How long a first-sign-in or reset link is good for, in days. + pub signin_link_lifetime_days: u32, /// The origin mail links point at, when an admin has set one. `None` /// means the address the process listens on — a box behind a proxy /// answers on localhost and is reached on a public name, and only an @@ -800,6 +818,19 @@ pub trait Store: BoardReads + DetailReads + 'static { reminder_minutes: u32, ) -> Result<()>; + /// Writes the workspace's four security knobs — the sign-in attempt + /// allowance, the rate-limit window, the session lifetime and the + /// sign-in-link lifetime — in one write, because they are one save on + /// one form. + async fn set_security( + &self, + workspace_id: &str, + rate_limit_attempts: u64, + rate_window_minutes: u32, + session_lifetime_days: u32, + signin_link_lifetime_days: u32, + ) -> Result<()>; + // -- users ------------------------------------------------------------- async fn create_user(&self, new: NewUser) -> Result; @@ -857,6 +888,12 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Stores the hash of a freshly minted link. The caller keeps the plaintext /// and shows it once. The kind decides which redeeming flow may spend it. + /// + /// Minting retires: every earlier unspent link of the same kind for the + /// same account is marked spent in the same transaction, so the newest + /// link is the only live one. A retired link is refused exactly like a + /// spent or expired one — retired *is* spent, the same `used_at` a + /// redemption writes. async fn create_signin_link( &self, user_id: &str, diff --git a/crates/iz-core/src/store/reconcile.rs b/crates/iz-core/src/store/reconcile.rs index e282ddf..1282311 100644 --- a/crates/iz-core/src/store/reconcile.rs +++ b/crates/iz-core/src/store/reconcile.rs @@ -12,7 +12,7 @@ //! while the rebuild runs. An extraction failure fails the rebuild, so the //! swap never trades the tables' binary for a directory that is not there. -use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint}; +use super::schema::{declared_fingerprint, diff_report, fingerprint, schema_sql}; use super::{Result, StoreError}; use turso::{Builder, Connection, params}; use ulid::Ulid; @@ -186,7 +186,7 @@ async fn rebuild( .await .map_err(|e| StoreError::Backend(e.to_string()))?; new_conn - .execute_batch(SCHEMA) + .execute_batch(&schema_sql()) .await .map_err(|e| StoreError::Backend(e.to_string()))?; // The blobs leave the old database before any row is copied: the copy's @@ -271,6 +271,7 @@ fn build_maps( old_has_reminder: bool, old_has_feed_seen: bool, old_has_tag: bool, + old_has_security: bool, ) -> Vec { let mut maps = Vec::new(); @@ -343,6 +344,44 @@ fn build_maps( "NULL".into() }, ), + ( + // The security knobs are the newest workspace columns: a + // database old enough to be reconciled has never heard of + // them and starts on today's defaults, exactly the numbers + // the matching migration's `DEFAULT` clauses backfill. One + // probe stands for all four — a database that carries one + // carries them all, because they shipped together. + "rate_limit_attempts", + if old_has_security { + "old.rate_limit_attempts".into() + } else { + crate::store::DEFAULT_RATE_LIMIT_ATTEMPTS.to_string() + }, + ), + ( + "rate_window_minutes", + if old_has_security { + "old.rate_window_minutes".into() + } else { + crate::store::DEFAULT_RATE_WINDOW_MINUTES.to_string() + }, + ), + ( + "session_lifetime_days", + if old_has_security { + "old.session_lifetime_days".into() + } else { + crate::store::DEFAULT_SESSION_LIFETIME_DAYS.to_string() + }, + ), + ( + "signin_link_lifetime_days", + if old_has_security { + "old.signin_link_lifetime_days".into() + } else { + crate::store::DEFAULT_SIGNIN_LINK_LIFETIME_DAYS.to_string() + }, + ), ("public_url", "old.public_url".into()), ], }); @@ -792,6 +831,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> let has_reminder = old_has_column(old_conn, "workspace", "reminder_minutes").await?; let has_feed_seen = old_has_column(old_conn, "user", "feed_seen_at").await?; let has_tag = old_has_column(old_conn, "tag", "id").await?; + let has_security = old_has_column(old_conn, "workspace", "rate_limit_attempts").await?; let maps = build_maps( has_smtp_check, has_batch_window, @@ -799,6 +839,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> has_reminder, has_feed_seen, has_tag, + has_security, ); validate_maps(new_conn, &maps).await?; @@ -1073,7 +1114,7 @@ mod tests { }; use turso::{Builder, params}; use ulid::Ulid; - use crate::store::schema::SCHEMA; + use crate::store::schema::schema_sql; #[test] fn backup_name_has_no_colons_or_spaces() { @@ -1099,9 +1140,9 @@ mod tests { let path = dir.join("iz.db").to_str().unwrap().to_string(); let db = Builder::new_local(&path).build().await.unwrap(); let conn = db.connect().unwrap(); - conn.execute_batch(SCHEMA).await.unwrap(); + conn.execute_batch(&schema_sql()).await.unwrap(); - let maps = build_maps(false, false, false, false, false, false); + let maps = build_maps(false, false, false, false, false, false, false); validate_maps(&conn, &maps) .await .expect("the full map set was refused against the declared schema"); @@ -1131,7 +1172,7 @@ mod tests { let photo_bytes = b"face-bytes".to_vec(); let db = Builder::new_local(path).build().await.unwrap(); let conn = db.connect().unwrap(); - conn.execute_batch(SCHEMA).await.unwrap(); + conn.execute_batch(&schema_sql()).await.unwrap(); // ALTER keeps the tables' own constraints intact, so this is the // shape a live database of the previous generation has. conn.execute( diff --git a/crates/iz-core/src/store/schema.rs b/crates/iz-core/src/store/schema.rs index bbed767..9c99dc5 100644 --- a/crates/iz-core/src/store/schema.rs +++ b/crates/iz-core/src/store/schema.rs @@ -9,8 +9,25 @@ use super::{Result, StoreError}; use turso::Connection; -/// The declared whole schema, applied to an empty database. -pub(crate) const SCHEMA: &str = include_str!("../../migrations/0001_init.sql"); +/// The declared migrations, in order. An empty database is built by applying +/// them one after another; each one applies cleanly to what the ones before +/// it built (`0002` is `ALTER`s), so their concatenation is itself a valid +/// whole-schema script. +pub(crate) const MIGRATIONS: &[&str] = &[ + include_str!("../../migrations/0001_init.sql"), + include_str!("../../migrations/0002_security_knobs.sql"), +]; + +/// The whole declared schema — every migration applied in order — as one +/// batch of SQL. +pub(crate) fn schema_sql() -> String { + let mut sql = String::new(); + for migration in MIGRATIONS { + sql.push_str(migration); + sql.push('\n'); + } + sql +} /// Reads and normalises the schema of the connected database. /// @@ -54,7 +71,7 @@ pub async fn declared_fingerprint() -> Result { .await .map_err(|e| StoreError::Backend(e.to_string()))?; let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?; - conn.execute_batch(SCHEMA) + conn.execute_batch(&schema_sql()) .await .map_err(|e| StoreError::Backend(e.to_string()))?; fingerprint(&conn).await diff --git a/crates/iz-core/src/store/turso_store.rs b/crates/iz-core/src/store/turso_store.rs index 2c3e2a8..a42fee7 100644 --- a/crates/iz-core/src/store/turso_store.rs +++ b/crates/iz-core/src/store/turso_store.rs @@ -372,7 +372,7 @@ impl TursoStore { if empty { conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; - if let Err(e) = conn.execute_batch(super::schema::SCHEMA).await { + if let Err(e) = conn.execute_batch(&super::schema::schema_sql()).await { let _ = conn.execute("ROLLBACK", ()).await; return Err(backend(e)); } @@ -1110,6 +1110,10 @@ fn workspace_from(row: &Row) -> Result { }), None => None, }, + rate_limit_attempts: row.get::(21).map_err(backend)?.max(0) as u64, + rate_window_minutes: row.get::(22).map_err(backend)?.max(0) as u32, + session_lifetime_days: row.get::(23).map_err(backend)?.max(0) as u32, + signin_link_lifetime_days: row.get::(24).map_err(backend)?.max(0) as u32, public_url: opt_text(row, 15)?, }) } @@ -1122,7 +1126,8 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \ smtp_from_name, smtp_from_address, \ (smtp_password IS NOT NULL AND smtp_password <> ''), \ smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \ - smtp_check_at, smtp_check_ms, smtp_check_error, mail_batch_minutes, reminder_minutes"; + smtp_check_at, smtp_check_ms, smtp_check_error, mail_batch_minutes, reminder_minutes, \ + rate_limit_attempts, rate_window_minutes, session_lifetime_days, signin_link_lifetime_days"; fn user_from(row: &Row) -> Result { Ok(User { @@ -1205,8 +1210,18 @@ impl Store for TursoStore { let claimed = async { tx.execute( - "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)", - params![workspace_id.clone(), workspace_name, now.clone()], + "INSERT INTO workspace (id, name, created_at, rate_limit_attempts, \ + rate_window_minutes, session_lifetime_days, signin_link_lifetime_days) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + workspace_id.clone(), + workspace_name, + now.clone(), + crate::store::DEFAULT_RATE_LIMIT_ATTEMPTS as i64, + i64::from(crate::store::DEFAULT_RATE_WINDOW_MINUTES), + i64::from(crate::store::DEFAULT_SESSION_LIFETIME_DAYS), + i64::from(crate::store::DEFAULT_SIGNIN_LINK_LIFETIME_DAYS), + ], ) .await?; tx.execute( @@ -1458,6 +1473,36 @@ impl Store for TursoStore { Ok(()) } + /// Writes the workspace's four security knobs: the sign-in attempt + /// allowance, the rate-limit window and the two lifetimes. One write, + /// because they are one save — the same rule `set_limits` lives by. + async fn set_security( + &self, + workspace_id: &str, + rate_limit_attempts: u64, + rate_window_minutes: u32, + session_lifetime_days: u32, + signin_link_lifetime_days: u32, + ) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE workspace SET rate_limit_attempts = ?1, rate_window_minutes = ?2, \ + session_lifetime_days = ?3, signin_link_lifetime_days = ?4 WHERE id = ?5", + params![ + rate_limit_attempts as i64, + i64::from(rate_window_minutes), + i64::from(session_lifetime_days), + i64::from(signin_link_lifetime_days), + workspace_id + ], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Settings]); + Ok(()) + } + async fn create_user(&self, new: NewUser) -> Result { let email = fold_email(&new.email); if self @@ -1808,23 +1853,35 @@ impl Store for TursoStore { kind: LinkKind, ) -> Result { let id = Ulid::new().to_string(); - self.conn - .lock() - .await - .execute( - "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at, kind) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - params![ - id.clone(), - user_id, - token_hash, - now_text()?, - stamp(expires_at)?, - kind.as_str(), - ], - ) + let now = now_text()?; + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) .await .map_err(backend)?; + // The newest link of a kind is the only live one: minting retires + // every earlier unspent link of the same kind for the account, in the + // same transaction as the insert, so a second reset mail cannot leave + // the first link working behind it. Retired is spent — the same + // stamped `used_at` a redemption writes — so there is no third state + // for reconcile or a fixture to know about. The update runs before + // the insert: the new row is unspent by definition and must not + // retire itself. + tx.execute( + "UPDATE signin_link SET used_at = ?1 \ + WHERE user_id = ?2 AND kind = ?3 AND used_at IS NULL", + params![now.clone(), user_id, kind.as_str()], + ) + .await + .map_err(backend)?; + tx.execute( + "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at, kind) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![id.clone(), user_id, token_hash, now, stamp(expires_at)?, kind.as_str()], + ) + .await + .map_err(backend)?; + tx.commit().await.map_err(backend)?; self.announce([Topic::Members]); match self .one_row( diff --git a/crates/iz-core/tests/store.rs b/crates/iz-core/tests/store.rs index d431b92..69d65e8 100644 --- a/crates/iz-core/tests/store.rs +++ b/crates/iz-core/tests/store.rs @@ -9,8 +9,10 @@ use std::path::PathBuf; use iz_core::Role; use iz_core::auth::{Token, hash_password}; use iz_core::store::{ - Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState, - Store, StoreError, Trigger, TursoStore, User, + Audience, DEFAULT_RATE_LIMIT_ATTEMPTS, DEFAULT_RATE_WINDOW_MINUTES, + DEFAULT_SESSION_LIFETIME_DAYS, DEFAULT_SIGNIN_LINK_LIFETIME_DAYS, Event, MailOutcome, + MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState, Store, StoreError, Trigger, + TursoStore, User, }; use time::{Duration, OffsetDateTime}; use ulid::Ulid; @@ -1087,6 +1089,37 @@ async fn limits_round_trip_including_the_file_type_list() { ); } +/// The security knobs come off the workspace row, not off consts: a fresh +/// claim starts on the migration's defaults, one save changes all four, and +/// the save announces itself like every other settings write. +#[tokio::test] +async fn the_security_knobs_default_round_trip_and_announce() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let mut rx = scratch.store.subscribe(); + + let ws = scratch.store.workspace().await.unwrap().unwrap(); + assert_eq!(ws.rate_limit_attempts, DEFAULT_RATE_LIMIT_ATTEMPTS); + assert_eq!(ws.rate_window_minutes, DEFAULT_RATE_WINDOW_MINUTES); + assert_eq!(ws.session_lifetime_days, DEFAULT_SESSION_LIFETIME_DAYS); + assert_eq!( + ws.signin_link_lifetime_days, + DEFAULT_SIGNIN_LINK_LIFETIME_DAYS + ); + + scratch + .store + .set_security(&ws_id, 3, 60, 30, 2) + .await + .unwrap(); + let ws = scratch.store.workspace().await.unwrap().unwrap(); + assert_eq!(ws.rate_limit_attempts, 3); + assert_eq!(ws.rate_window_minutes, 60); + assert_eq!(ws.session_lifetime_days, 30); + assert_eq!(ws.signin_link_lifetime_days, 2); + + assert_eq!(announced(&mut rx), vec!["settings".to_string()]); +} + #[tokio::test] async fn an_invited_member_has_no_password_until_they_choose_one() { let (scratch, ws_id, _) = workspace_with_admin().await; @@ -1694,7 +1727,7 @@ async fn auth_attempts_are_counted_over_a_window() { // Account flows. // --------------------------------------------------------------------------- -use iz_core::accounts::{AccountError, Accounts, RATE_LIMIT, SIGNIN_LINK_LIFETIME}; +use iz_core::accounts::{AccountError, Accounts}; use iz_core::auth::PasswordProblem; use std::sync::Arc; @@ -1721,6 +1754,18 @@ async fn claimed() -> (Scratch, Accounts, User) { (scratch, accounts, signed_in.user) } +/// The workspace's configured sign-in attempt allowance, read the way +/// `Accounts` reads it — off the workspace row, never off a const. +async fn allowance(accounts: &Accounts) -> u64 { + accounts + .store() + .workspace() + .await + .unwrap() + .expect("the workspace is claimed") + .rate_limit_attempts +} + #[tokio::test] async fn claiming_makes_an_admin_and_signs_them_in() { let (_scratch, accounts) = accounts().await; @@ -1789,7 +1834,9 @@ async fn an_invited_member_chooses_their_own_password() { assert!(!invitation.user.has_signed_in(), "no password yet"); assert!( invitation.expires_at - > OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME - Duration::minutes(1) + > OffsetDateTime::now_utc() + + Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS)) + - Duration::minutes(1) ); // The admin cannot sign in as them in the meantime. @@ -2115,7 +2162,8 @@ async fn an_invited_account_that_has_no_password_cannot_be_signed_into() { #[tokio::test] async fn sign_in_attempts_are_rate_limited_per_address() { let (_scratch, accounts, _admin) = claimed().await; - for _ in 0..RATE_LIMIT { + let allowance = allowance(&accounts).await; + for _ in 0..allowance { let _ = accounts .sign_in("ada@iz.sh", "wrong", "198.51.100.7") .await; @@ -2137,14 +2185,15 @@ async fn sign_in_attempts_are_rate_limited_per_address() { } /// The lockout question, decided: an address bucket that refuses before the -/// verify lets anyone who knows a colleague's address keep them out with ten -/// wrong guesses every fifteen minutes, from anywhere, with no account of their -/// own. So the address bucket counts but never refuses a correct password. +/// verify lets anyone who knows a colleague's address keep them out with a +/// windowful of wrong guesses, from anywhere, with no account of their own. +/// So the address bucket counts but never refuses a correct password. #[tokio::test] async fn a_flooded_address_never_locks_the_owner_out() { let (_scratch, accounts, _admin) = claimed().await; + let allowance = allowance(&accounts).await; // Each guess from its own client, so only the address bucket fills. - for i in 0..(RATE_LIMIT + 5) { + for i in 0..(allowance + 5) { let _ = accounts .sign_in("ada@iz.sh", "wrong", &format!("203.0.113.{i}")) .await; @@ -2160,7 +2209,8 @@ async fn a_flooded_address_never_locks_the_owner_out() { #[tokio::test] async fn sign_in_attempts_are_rate_limited_per_client() { let (_scratch, accounts, _admin) = claimed().await; - for i in 0..RATE_LIMIT { + let allowance = allowance(&accounts).await; + for i in 0..allowance { let _ = accounts .sign_in(&format!("nobody{i}@iz.sh"), "wrong", "203.0.113.9") .await; @@ -2180,11 +2230,12 @@ async fn sign_in_attempts_are_rate_limited_per_client() { #[tokio::test] async fn link_redemption_is_rate_limited_per_client() { let (_scratch, accounts, admin) = claimed().await; + let allowance = allowance(&accounts).await; let invitation = accounts .invite(&admin, "grace@iz.sh", "Grace", Role::Member) .await .unwrap(); - for i in 0..RATE_LIMIT { + for i in 0..allowance { let bogus = format!("{i:032x}"); assert!(matches!( accounts @@ -2220,7 +2271,8 @@ async fn link_redemption_is_rate_limited_per_client() { #[tokio::test] async fn changing_a_password_is_rate_limited_per_client() { let (_scratch, accounts, admin) = claimed().await; - for _ in 0..RATE_LIMIT { + let allowance = allowance(&accounts).await; + for _ in 0..allowance { let _ = accounts .change_password(&admin.id, "not-it", "chronometer-1761", "203.0.113.9") .await; @@ -2241,7 +2293,8 @@ async fn changing_a_password_is_rate_limited_per_client() { #[tokio::test] async fn a_successful_sign_in_clears_the_bucket() { let (_scratch, accounts, _admin) = claimed().await; - for _ in 0..(RATE_LIMIT - 1) { + let allowance = allowance(&accounts).await; + for _ in 0..(allowance - 1) { let _ = accounts .sign_in("ada@iz.sh", "wrong", "198.51.100.7") .await; @@ -2259,6 +2312,125 @@ async fn a_successful_sign_in_clears_the_bucket() { )); } +/// The allowance is the workspace's number, not a const's: lowered to three, +/// the third miss still answers Rejected and the fourth is RateLimited — the +/// refusal lands exactly at the configured count. +#[tokio::test] +async fn the_rate_allowance_is_the_configured_one() { + let (scratch, accounts, admin) = claimed().await; + scratch + .store + .set_security( + &admin.workspace_id, + 3, + DEFAULT_RATE_WINDOW_MINUTES, + DEFAULT_SESSION_LIFETIME_DAYS, + DEFAULT_SIGNIN_LINK_LIFETIME_DAYS, + ) + .await + .unwrap(); + + for _ in 0..3 { + assert!(matches!( + accounts.sign_in("ada@iz.sh", "wrong", "198.51.100.7").await, + Err(AccountError::Rejected) + )); + } + assert!(matches!( + accounts + .sign_in("ada@iz.sh", "wrong", "198.51.100.7") + .await, + Err(AccountError::RateLimited) + )); + // And the stored knob is the one that decided: the save is readable back. + assert_eq!(allowance(&accounts).await, 3); +} + +/// The lifetimes are the workspace's too. Nothing here waits them out: what +/// an admin changes is what the next session row and the next reset link +/// are written with, read straight back off the store. +#[tokio::test] +async fn the_lifetimes_are_the_configured_ones() { + let (scratch, accounts, _admin) = claimed().await; + + let signed_in = accounts + .sign_in("ada@iz.sh", "tide-tables-1892", "198.51.100.7") + .await + .unwrap(); + let expected = OffsetDateTime::now_utc() + + Duration::days(i64::from(DEFAULT_SESSION_LIFETIME_DAYS)); + assert!( + (signed_in.session.expires_at - expected).abs() < Duration::minutes(1), + "the session was not written with the default lifetime" + ); + + accounts + .request_password_reset("ada@iz.sh", "203.0.113.9") + .await + .unwrap(); + let link_expiry = newest_link_expiry(&scratch).await; + let expected = OffsetDateTime::now_utc() + + Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS)); + assert!( + (link_expiry - expected).abs() < Duration::minutes(1), + "the link was not written with the default lifetime" + ); + + scratch + .store + .set_security( + &signed_in.user.workspace_id, + DEFAULT_RATE_LIMIT_ATTEMPTS, + DEFAULT_RATE_WINDOW_MINUTES, + 30, + 2, + ) + .await + .unwrap(); + + let signed_in = accounts + .sign_in("ada@iz.sh", "tide-tables-1892", "198.51.100.8") + .await + .unwrap(); + let expected = OffsetDateTime::now_utc() + Duration::days(30); + assert!( + (signed_in.session.expires_at - expected).abs() < Duration::minutes(1), + "the session ignored the workspace's session lifetime" + ); + + accounts + .request_password_reset("ada@iz.sh", "203.0.113.9") + .await + .unwrap(); + let link_expiry = newest_link_expiry(&scratch).await; + let expected = OffsetDateTime::now_utc() + Duration::days(2); + assert!( + (link_expiry - expected).abs() < Duration::minutes(1), + "the link ignored the workspace's link lifetime" + ); +} + +/// The `expires_at` of the newest stored sign-in link, read the way it sits +/// on disk. +async fn newest_link_expiry(scratch: &Scratch) -> OffsetDateTime { + let conn = raw_conn(scratch).await; + let mut rows = conn + .query( + "SELECT expires_at FROM signin_link ORDER BY created_at DESC LIMIT 1", + (), + ) + .await + .unwrap(); + let raw: String = rows + .next() + .await + .unwrap() + .expect("a reset was asked, so a link exists") + .get(0) + .unwrap(); + OffsetDateTime::parse(&raw, &time::format_description::well_known::Rfc3339).unwrap() +} + #[tokio::test] async fn changing_a_password_signs_out_every_device() { let (_scratch, accounts, admin) = claimed().await; @@ -7367,6 +7539,72 @@ async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() { let _ = std::fs::remove_dir_all(&dir); } +/// The migration the security knobs exist for: a database of the shape the +/// first migration builds — everything an install made before +/// `0002_security_knobs.sql` shipped — comes up through the store's own +/// repair path, and its workspace lands on the defaults the migration and +/// the copy map both backfill, accounts and tasks intact. +#[tokio::test] +async fn reconcile_backfills_the_security_knobs_on_a_first_migration_database() { + let dir = std::env::temp_dir().join(format!("iz-reconcile-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("iz.db").to_str().unwrap().to_string(); + + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap(); + conn.execute_batch(include_str!("../migrations/0001_init.sql")) + .await + .unwrap(); + let now = "2026-09-01T09:00:00Z"; + conn.execute_batch(&format!( + "INSERT INTO workspace (id, name, created_at) VALUES ('W1', 'Dizey', '{now}'); + INSERT INTO user (id, workspace_id, email, display_name, role, password_hash, created_at) \ + VALUES ('U1', 'W1', 'ada@iz.sh', 'Ada', 'admin', 'argon2$hash', '{now}'); + INSERT INTO workspace_owner (singleton, user_id, claimed_at) VALUES (1, 'U1', '{now}');" + )) + .await + .unwrap(); + drop(conn); + drop(db); + + // Opening the store is the boot the upgrade happens on: the stale shape + // is reconciled before any handle is kept. + let store = TursoStore::open(&path, &dir.join("storage")) + .await + .expect("the store refused a first-migration database"); + + let ws = store.workspace().await.unwrap().unwrap(); + assert_eq!(ws.rate_limit_attempts, DEFAULT_RATE_LIMIT_ATTEMPTS); + assert_eq!(ws.rate_window_minutes, DEFAULT_RATE_WINDOW_MINUTES); + assert_eq!(ws.session_lifetime_days, DEFAULT_SESSION_LIFETIME_DAYS); + assert_eq!( + ws.signin_link_lifetime_days, + DEFAULT_SIGNIN_LINK_LIFETIME_DAYS + ); + assert_eq!(ws.name, "Dizey", "the workspace row itself was lost"); + assert_eq!( + scalar(&path, "SELECT COUNT(*) FROM user").await, + 1, + "the admin account did not come across" + ); + + // A database already on the new shape is not reconciled again: opening + // twice in a row is ordinary, and the knobs keep what a save wrote. + store + .set_security("W1", 7, 30, 21, 3) + .await + .unwrap(); + drop(store); + let second = TursoStore::open(&path, &dir.join("storage")) + .await + .unwrap(); + let ws = second.workspace().await.unwrap().unwrap(); + assert_eq!(ws.rate_limit_attempts, 7, "a second boot reset the knobs"); + assert_eq!(ws.rate_window_minutes, 30); + let _ = std::fs::remove_dir_all(&dir); +} + /// The rebuild the tag map exists for: a database that already carries user /// tags hands every one of them across untouched — same id, same board, same /// name, same order, same default mark — and every task still points at the @@ -9013,21 +9251,31 @@ async fn board_search_matches_keys_and_titles_in_place() { // browser out. The address's existence stays the requester's guess. // --------------------------------------------------------------------------- -/// The reset token out of the newest notice queued for the address — the mail -/// is the token's only carrier, so the test reads it like a recipient would. -async fn queued_reset_token(store: &std::sync::Arc, email: &str) -> Option { +/// Every reset token queued for the address, oldest first. The newest ask +/// retires the earlier links, so a test that asks twice needs both. +async fn queued_reset_tokens(store: &std::sync::Arc, email: &str) -> Vec { let sends = store .mail_queue(50, iz_core::store::FeedPage::Newest) .await .unwrap(); - let body = sends - .into_iter() - .rev() - .find(|send| send.kind == iz_core::store::SendKind::Notice && send.recipient == email) - .and_then(|send| send.body)?; - body.rsplit_once("/reset/") - .and_then(|(_, rest)| rest.split_whitespace().next()) - .map(str::to_string) + let mut tokens = Vec::new(); + for send in sends { + if send.kind != SendKind::Notice || send.recipient != email { + continue; + } + let Some(body) = send.body else { continue }; + let Some((_, rest)) = body.rsplit_once("/reset/") else { continue }; + if let Some(token) = rest.split_whitespace().next() { + tokens.push(token.to_string()); + } + } + tokens +} + +/// The reset token out of the newest notice queued for the address — the mail +/// is the token's only carrier, so the test reads it like a recipient would. +async fn queued_reset_token(store: &std::sync::Arc, email: &str) -> Option { + queued_reset_tokens(store, email).await.pop() } #[tokio::test] @@ -9174,7 +9422,8 @@ async fn each_link_redeems_only_on_its_own_screen() { .create_signin_link( &admin.id, &join.hash(), - time::OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME, + time::OffsetDateTime::now_utc() + + time::Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS)), iz_core::store::LinkKind::Join, ) .await @@ -9201,16 +9450,186 @@ async fn each_link_redeems_only_on_its_own_screen() { )); } +#[tokio::test] +async fn a_second_reset_request_retires_the_first_link() { + let (_scratch, accounts, _admin) = claimed().await; + accounts + .request_password_reset("ada@iz.sh", "203.0.113.9") + .await + .unwrap(); + accounts + .request_password_reset("ada@iz.sh", "203.0.113.9") + .await + .unwrap(); + let tokens = queued_reset_tokens(accounts.store(), "ada@iz.sh").await; + assert_eq!(tokens.len(), 2, "each ask queued its own mail"); + + // The first link died when the second was minted — before the second was + // redeemed — and it is refused like any other dead link. + assert!(matches!( + accounts + .redeem_reset_link(&tokens[0], "chronometer-1761", "203.0.113.10") + .await, + Err(AccountError::Rejected) + )); + + // The newest link is the one that works, and it really changes the + // password. + accounts + .redeem_reset_link(&tokens[1], "chronometer-1761", "203.0.113.10") + .await + .unwrap(); + assert!(matches!( + accounts + .sign_in("ada@iz.sh", "tide-tables-1892", "198.51.100.11") + .await, + Err(AccountError::Rejected) + )); + accounts + .sign_in("ada@iz.sh", "chronometer-1761", "198.51.100.11") + .await + .unwrap(); +} + +#[tokio::test] +async fn a_second_invitation_retires_the_first_link() { + let (_scratch, accounts, admin) = claimed().await; + let first = accounts + .invite(&admin, "grace@iz.sh", "Grace", Role::Member) + .await + .unwrap(); + let second = accounts + .resend_invitation(&admin, &first.user.id) + .await + .unwrap(); + assert_ne!(first.token.expose(), second.token.expose()); + + // The first link died when the second was minted. + assert!(matches!( + accounts + .redeem_signin_link(first.token.expose(), "sextant-and-chart", "198.51.100.7") + .await, + Err(AccountError::Rejected) + )); + // The second sets the password it was always going to. + let signed_in = accounts + .redeem_signin_link(second.token.expose(), "sextant-and-chart", "198.51.100.7") + .await + .unwrap(); + assert_eq!(signed_in.user.id, first.user.id); + accounts + .sign_in("grace@iz.sh", "sextant-and-chart", "198.51.100.7") + .await + .unwrap(); +} + +#[tokio::test] +async fn a_retired_link_stays_retired_after_the_newer_one_redeems() { + let (_scratch, accounts, admin) = claimed().await; + + // Reset: redeeming the newest mail must not wake the retired one. + accounts + .request_password_reset("ada@iz.sh", "203.0.113.9") + .await + .unwrap(); + accounts + .request_password_reset("ada@iz.sh", "203.0.113.9") + .await + .unwrap(); + let resets = queued_reset_tokens(accounts.store(), "ada@iz.sh").await; + assert_eq!(resets.len(), 2); + accounts + .redeem_reset_link(&resets[1], "chronometer-1761", "203.0.113.10") + .await + .unwrap(); + assert!(matches!( + accounts + .redeem_reset_link(&resets[0], "harbor-and-pilot-1812", "203.0.113.10") + .await, + Err(AccountError::Rejected) + )); + + // Join: the same for a resent invitation. + let first = accounts + .invite(&admin, "grace@iz.sh", "Grace", Role::Member) + .await + .unwrap(); + let second = accounts + .resend_invitation(&admin, &first.user.id) + .await + .unwrap(); + accounts + .redeem_signin_link(second.token.expose(), "sextant-and-chart", "198.51.100.7") + .await + .unwrap(); + assert!(matches!( + accounts + .redeem_signin_link(first.token.expose(), "harbor-and-pilot-1812", "198.51.100.7") + .await, + Err(AccountError::Rejected) + )); +} + +#[tokio::test] +async fn a_fresh_link_of_one_kind_leaves_the_other_kinds_link_alone() { + let (scratch, accounts, admin) = claimed().await; + + // An invited member who has not signed in can still be mailed a reset: + // both links are live, and neither mint retires the other. + let invitation = accounts + .invite(&admin, "grace@iz.sh", "Grace", Role::Member) + .await + .unwrap(); + accounts + .request_password_reset("grace@iz.sh", "203.0.113.9") + .await + .unwrap(); + let join = scratch + .store + .signin_link_by_hash(&invitation.token.hash()) + .await + .unwrap() + .expect("the invitation link is stored"); + assert!( + join.is_usable(OffsetDateTime::now_utc()), + "the reset mint retired the invitation" + ); + + // And the other way round: the admin holds a live reset; minting her an + // invitation over it leaves the reset spendable, and both links open + // their own screens. + accounts + .request_password_reset("ada@iz.sh", "203.0.113.9") + .await + .unwrap(); + let resent = accounts + .resend_invitation(&admin, &admin.id) + .await + .unwrap(); + let reset = queued_reset_token(accounts.store(), "ada@iz.sh") + .await + .expect("no reset mail queued"); + accounts + .redeem_reset_link(&reset, "chronometer-1761", "203.0.113.10") + .await + .unwrap(); + accounts + .redeem_signin_link(resent.token.expose(), "sextant-and-chart", "198.51.100.7") + .await + .unwrap(); +} + #[tokio::test] async fn reset_asks_are_rate_limited_per_client_and_silenced_per_address() { let (dir, store, workspace, _admin) = shared().await; let _grace = member(&store, &workspace, "grace@iz.sh", "Grace").await; let store = store as std::sync::Arc; let accounts = Accounts::new(store.clone(), "https://iz.sh"); + let allowance = accounts.store().workspace().await.unwrap().unwrap().rate_limit_attempts; - // One machine asks RATE_LIMIT times: every ask answers the same, and the - // eleventh from that machine is refused by name. - for _ in 0..RATE_LIMIT { + // One machine asks allowance times: every ask answers the same, and the + // next from that machine is refused by name. + for _ in 0..allowance { accounts .request_password_reset("grace@iz.sh", "203.0.113.9") .await @@ -9234,8 +9653,7 @@ async fn reset_asks_are_rate_limited_per_client_and_silenced_per_address() { "SELECT COUNT(*) FROM mail_send WHERE kind = 'notice'", ) .await; - assert_eq!(queued, RATE_LIMIT as i64, "the flood minted no mail"); - let _ = std::fs::remove_dir_all(&dir); + assert_eq!(queued, allowance as i64, "the flood minted no mail"); } #[tokio::test] diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs index e910e79..82495ab 100644 --- a/crates/iz-web/src/auth.rs +++ b/crates/iz-web/src/auth.rs @@ -7,7 +7,7 @@ //! [`crate::server::carry_refusal_on_redirect`] can carry it onto that //! redirect's query. -use iz_core::accounts::SESSION_LIFETIME; +use iz_core::store::DEFAULT_SESSION_LIFETIME_DAYS; use iz_core::detail::ActivityKind; use serde::{Deserialize, Serialize}; use topcoat::Result; @@ -23,6 +23,19 @@ use crate::server::{ }; use crate::settings::encode_q; +/// The workspace's session lifetime, read the same way every other knob is — +/// off the workspace row through the account service's store — so an admin's +/// change in Settings reaches the next cookie without a restart. A workspace +/// row that is not there yet (nobody has claimed the install) stands on the +/// default. +async fn session_lifetime(cx: &Cx) -> time::Duration { + let days = match accounts(cx).store().workspace().await { + Ok(Some(workspace)) => workspace.session_lifetime_days, + _ => DEFAULT_SESSION_LIFETIME_DAYS, + }; + time::Duration::days(i64::from(days)) +} + /// The workspace has exactly one name and no screen that sets it, so it is a /// constant rather than a field nobody was shown. pub const WORKSPACE_NAME: &str = "İz"; @@ -100,7 +113,7 @@ async fn claim_workspace(cx: &Cx, Form(input): Form) -> Redi .await { Ok((_workspace, signed_in)) => { - set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME); + set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await); let _ = accounts(cx) .store() .record_event( @@ -131,7 +144,7 @@ async fn sign_in(cx: &Cx, Form(input): Form) -> Redirect { .await { Ok(signed_in) => { - set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME); + set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await); let _ = accounts(cx) .store() .record_event( @@ -198,7 +211,7 @@ async fn redeem_link(cx: &Cx, Form(input): Form) -> Redirect { .await { Ok(signed_in) => { - set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME); + set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await); let _ = accounts(cx) .store() .record_event( @@ -240,7 +253,7 @@ async fn change_password(cx: &Cx, Form(input): Form) -> Redi .await { Ok(signed_in) => { - set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME); + set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await); let _ = accounts(cx) .store() .record_event( @@ -422,7 +435,7 @@ async fn redeem_reset(cx: &Cx, Form(input): Form) -> Redirect { .await { Ok(signed_in) => { - set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME); + set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await); let _ = accounts(cx) .store() .record_event( diff --git a/crates/iz-web/src/detail.rs b/crates/iz-web/src/detail.rs index 303cd30..bb5e707 100644 --- a/crates/iz-web/src/detail.rs +++ b/crates/iz-web/src/detail.rs @@ -18,7 +18,8 @@ use iz_core::board::{DeadlineState, Person}; use iz_core::detail::{ - Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in, parse_zone, + Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in, + moment_label_with_seconds_in, parse_zone, }; use iz_core::store::{Store, StoreError, User}; use serde::{Deserialize, Serialize}; @@ -418,14 +419,14 @@ async fn load_snapshot( state_kind: state_kind.to_string(), attempts: send.attempts, last_error: may_administer.then(|| send.last_error.clone()).flatten(), - sent_at: send.sent_at.map(|at| moment_label_in(at, zone)), + sent_at: send.sent_at.map(|at| moment_label_with_seconds_in(at, zone)), } }) .collect(); let outcome = crate::logs::outcome_word(decision.outcome, lang).to_string(); notifications.push(NotificationLine { happened, - at: moment_label_in(decision.at, zone), + at: moment_label_with_seconds_in(decision.at, zone), rule_name, outcome: if outcome_detail.is_empty() { outcome diff --git a/crates/iz-web/src/i18n.rs b/crates/iz-web/src/i18n.rs index 0d700d0..7fc96fb 100644 --- a/crates/iz-web/src/i18n.rs +++ b/crates/iz-web/src/i18n.rs @@ -153,6 +153,11 @@ pub enum Key { AttachmentLimitLabel, PhotoLimitLabel, AllowedFileTypesLabel, + Security, + RateLimitAttemptsLabel, + RateWindowLabel, + SessionLifetimeLabel, + LinkLifetimeLabel, Members, Message, Everyone, @@ -298,6 +303,7 @@ pub enum Key { ActProfileSaved, ActSenderSaved, ActLimitsSaved, + ActSecuritySaved, ActTestMailSent, ActMessageSent, ActSendRetried, @@ -636,6 +642,16 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (PhotoLimitLabel, Tr) => "FOTOĞRAF LİMİTİ (MB)", (AllowedFileTypesLabel, En) => "ALLOWED FILE TYPES", (AllowedFileTypesLabel, Tr) => "İZİN VERİLEN DOSYA TÜRLERİ", + (Security, En) => "Security", + (Security, Tr) => "Güvenlik", + (RateLimitAttemptsLabel, En) => "Sign-in attempts", + (RateLimitAttemptsLabel, Tr) => "Giriş denemesi", + (RateWindowLabel, En) => "Attempt window (minutes)", + (RateWindowLabel, Tr) => "Deneme penceresi (dakika)", + (SessionLifetimeLabel, En) => "Session lifetime (days)", + (SessionLifetimeLabel, Tr) => "Oturum süresi (gün)", + (LinkLifetimeLabel, En) => "Link lifetime (days)", + (LinkLifetimeLabel, Tr) => "Bağlantı süresi (gün)", (Members, En) => "Members", (Members, Tr) => "Üyeler", (Message, En) => "Message", @@ -921,6 +937,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ActSenderSaved, Tr) => "gönderen ayarlarını kaydetti", (ActLimitsSaved, En) => "saved the limits", (ActLimitsSaved, Tr) => "sınırları kaydetti", + (ActSecuritySaved, En) => "saved the security settings", + (ActSecuritySaved, Tr) => "güvenlik ayarlarını kaydetti", (ActTestMailSent, En) => "sent a test mail", (ActTestMailSent, Tr) => "test postası gönderdi", (ActMessageSent, En) => "sent a message", diff --git a/crates/iz-web/src/logs.rs b/crates/iz-web/src/logs.rs index 1d15bb2..9820b23 100644 --- a/crates/iz-web/src/logs.rs +++ b/crates/iz-web/src/logs.rs @@ -186,6 +186,7 @@ pub(crate) fn activity_sentence(kind: &iz_core::detail::ActivityKind, detail: &s ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).to_string(), ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).to_string(), ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).to_string(), + ActivityKind::SecuritySaved => t(lang, Key::ActSecuritySaved).to_string(), ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).to_string(), ActivityKind::MessageSent => t(lang, Key::ActMessageSent).to_string(), ActivityKind::RoleChanged => crate::i18n::role_changed_label(lang, detail), @@ -663,7 +664,7 @@ async fn snapshot( event_id: decision.event_id, task, happened, - at: iz_core::detail::moment_label_in(decision.at, zone), + at: iz_core::detail::moment_label_with_seconds_in(decision.at, zone), verdicts: vec![verdict], }); } @@ -698,7 +699,7 @@ async fn snapshot( let activity = raw_activity .into_iter() .map(|line| ActivityRow { - at: iz_core::detail::moment_label_in(line.at, zone), + at: iz_core::detail::moment_label_with_seconds_in(line.at, zone), actor: line .actor_name .unwrap_or_else(|| t(lang, Key::TheSystem).to_string()), diff --git a/crates/iz-web/src/people.rs b/crates/iz-web/src/people.rs index 70e1500..3f2c2cf 100644 --- a/crates/iz-web/src/people.rs +++ b/crates/iz-web/src/people.rs @@ -46,6 +46,7 @@ fn kind_word(lang: Lang, kind: &ActivityKind) -> String { ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).into(), ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).into(), ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).into(), + ActivityKind::SecuritySaved => t(lang, Key::ActSecuritySaved).into(), ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).into(), ActivityKind::MessageSent => t(lang, Key::ActMessageSent).into(), ActivityKind::Other(raw) if raw == "password_reset_requested" => { diff --git a/crates/iz-web/src/server.rs b/crates/iz-web/src/server.rs index 29deaf5..561f188 100644 --- a/crates/iz-web/src/server.rs +++ b/crates/iz-web/src/server.rs @@ -384,6 +384,10 @@ pub enum Refusal { EmptyName, /// A limit of nothing, or a limit wider than the disk should promise. BadLimit, + /// A security number below its floor or past its ceiling. Not `BadLimit`: + /// that sentence is about megabytes, and these knobs are counts, minutes + /// and days. + BadPolicy, /// The timezone field was not one of the offsets the form offers. BadZone, /// The theme field was not one of the values the form offers. @@ -466,6 +470,7 @@ impl Refusal { "A limit has to be at least 1 MB, and no wider than 500 MB per file or 20 MB per photo." .to_string() } + Refusal::BadPolicy => "A security number is out of range.".to_string(), Refusal::BadZone => "That is not a timezone.".to_string(), Refusal::BadTheme => "That is not a theme.".to_string(), Refusal::BadUi => "That is not an interface.".to_string(), @@ -531,6 +536,7 @@ impl Refusal { "Limit en az 1 MB, dosya başına en çok 500 MB, fotoğraf başına en çok 20 MB olabilir." .to_string() } + Refusal::BadPolicy => "Güvenlik sayısı aralığın dışında.".to_string(), Refusal::BadZone => "Bu bir saat dilimi değil.".to_string(), Refusal::BadTheme => "Bu bir tema değil.".to_string(), Refusal::BadUi => "Bu bir arayüz değil.".to_string(), @@ -583,6 +589,7 @@ impl Refusal { "empty-title" => Refusal::EmptyTitle, "empty-name" => Refusal::EmptyName, "bad-limit" => Refusal::BadLimit, + "bad-policy" => Refusal::BadPolicy, "bad-zone" => Refusal::BadZone, "bad-theme" => Refusal::BadTheme, "bad-ui" => Refusal::BadUi, @@ -640,6 +647,7 @@ impl Refusal { Refusal::EmptyTitle => "empty-title", Refusal::EmptyName => "empty-name", Refusal::BadLimit => "bad-limit", + Refusal::BadPolicy => "bad-policy", Refusal::BadZone => "bad-zone", Refusal::BadTheme => "bad-theme", Refusal::BadUi => "bad-ui", @@ -1011,6 +1019,8 @@ mod refusal_message_tests { Refusal::NotFound, Refusal::NoSuchMember, Refusal::TagInUse, + Refusal::BadLimit, + Refusal::BadPolicy, Refusal::Unavailable, ]; for refusal in all { diff --git a/crates/iz-web/src/settings.rs b/crates/iz-web/src/settings.rs index ebd2e1d..ac7ec72 100644 --- a/crates/iz-web/src/settings.rs +++ b/crates/iz-web/src/settings.rs @@ -44,6 +44,19 @@ pub const WIDEST_PHOTO_MB: u64 = 20; /// workflow. Two hours is already far past the point where a mail is news. pub const LONGEST_BATCH_MINUTES: u32 = 120; +/// The security knobs' bounds, in the `WIDEST_*` spirit: a floor beneath +/// which the knob stops meaning anything and a ceiling past which it stops +/// being a policy and becomes a wish. +/// +/// A hundred guesses a window is already a flood for a board a few people +/// share; a window past a day is a ban wearing a rate limit's name; a cookie +/// that outlives a year is not a session any more; a link that waits three +/// months is stale news, and resending mints another. +pub const WIDEST_RATE_LIMIT_ATTEMPTS: u64 = 100; +pub const LONGEST_RATE_WINDOW_MINUTES: u32 = 24 * 60; +pub const LONGEST_SESSION_DAYS: u32 = 365; +pub const LONGEST_LINK_DAYS: u32 = 90; + const MB: u64 = 1024 * 1024; /// `1.2 s` for anything over a second, `840 ms` below it. A mail server that @@ -193,6 +206,7 @@ fn section_of_call(call: &str) -> &'static str { match call { "save_sender" | "send_test_mail" | "check_sender" => "outgoing", "save_limits" => "limits", + "save_security" => "security", "invite_member" | "set_role" | "resend_link" => "members", "send_message" => "message", _ => "profile", @@ -360,6 +374,70 @@ async fn save_limits( Ok(saved_or_refused("save_limits", refusal)) } +#[derive(serde::Deserialize)] +struct SaveSecurityForm { + rate_limit_attempts: u64, + rate_window_minutes: u32, + session_lifetime_days: u32, + signin_link_lifetime_days: u32, +} + +/// Writes the workspace's four security knobs. Admin-only, checked here. +/// +/// The bounds are the form's `min`/`max` backed by this check, because the +/// form is a courtesy and this is the guard: a posted 0 would turn the rate +/// limit off outright and a pasted 100000 would turn it into a decoration. +#[route(POST "/api/save_security")] +async fn save_security( + cx: &Cx, + Form(input): Form, +) -> Result<(StatusCode, HeaderMap, Vec)> { + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return Ok(saved_or_refused("save_security", Some(refusal))), + }; + if input.rate_limit_attempts == 0 + || input.rate_window_minutes == 0 + || input.session_lifetime_days == 0 + || input.signin_link_lifetime_days == 0 + || input.rate_limit_attempts > WIDEST_RATE_LIMIT_ATTEMPTS + || input.rate_window_minutes > LONGEST_RATE_WINDOW_MINUTES + || input.session_lifetime_days > LONGEST_SESSION_DAYS + || input.signin_link_lifetime_days > LONGEST_LINK_DAYS + { + return Ok(saved_or_refused("save_security", Some(Refusal::BadPolicy))); + } + let outcome = accounts(cx) + .store() + .set_security( + &admin.workspace_id, + input.rate_limit_attempts, + input.rate_window_minutes, + input.session_lifetime_days, + input.signin_link_lifetime_days, + ) + .await; + let refusal = match outcome { + Ok(()) => { + let _ = accounts(cx) + .store() + .record_event( + Some(&admin.id), + &ActivityKind::SecuritySaved, + "", + time::OffsetDateTime::now_utc(), + ) + .await; + None + } + Err(problem) => { + eprintln!("store error: {problem}"); + Some(Refusal::Unavailable) + } + }; + Ok(saved_or_refused("save_security", refusal)) +} + #[derive(serde::Deserialize)] struct SaveSenderForm { host: String, @@ -974,6 +1052,22 @@ async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec Result<(u64, u32, u32, u32)> { + let workspace = accounts(cx) + .store() + .workspace() + .await? + .filter(|workspace| workspace.id == workspace_id) + .ok_or_else(|| topcoat::Error::from(std::io::Error::other("no workspace")))?; + Ok(( + workspace.rate_limit_attempts, + workspace.rate_window_minutes, + workspace.session_lifetime_days, + workspace.signin_link_lifetime_days, + )) +} + /// What the row under the test button says, once the workspace holds a /// `sender_test` to read. struct TestResult { @@ -1169,6 +1263,7 @@ enum Section { Profile, Outgoing, Limits, + Security, Members, Message, } @@ -1205,6 +1300,7 @@ async fn settings_page(cx: &Cx) -> Result { let section = match query_value(query, "section") { Some("outgoing") if administers => Section::Outgoing, Some("limits") if administers => Section::Limits, + Some("security") if administers => Section::Security, Some("members") if administers => Section::Members, Some("message") if administers => Section::Message, _ => Section::Profile, @@ -1225,6 +1321,11 @@ async fn settings_page(cx: &Cx) -> Result { } else { (None, Vec::new()) }; + let security = if administers { + Some(security_now(cx, &user.workspace_id).await?) + } else { + None + }; let members = if administers { Some(members_now(cx, &user).await?) } else { @@ -1238,6 +1339,7 @@ async fn settings_page(cx: &Cx) -> Result { let (sender_refusal, sender_saved) = call_state(query, "save_sender"); let (test_refusal, _) = call_state(query, "send_test_mail"); let (limits_refusal, limits_saved) = call_state(query, "save_limits"); + let (security_refusal, security_saved) = call_state(query, "save_security"); let (resend_refusal, _) = call_state(query, "resend_link"); let (invite_refusal, _) = call_state(query, "invite_member"); let (role_refusal, _) = call_state(query, "set_role"); @@ -1261,7 +1363,7 @@ async fn settings_page(cx: &Cx) -> Result { if administers { (t(lang, Key::OutgoingMail)) (t(lang, Key::WorkspaceLimits)) - (t(lang, Key::Members)) + (t(lang, Key::Security)) (t(lang, Key::Message)) } @@ -1610,6 +1712,80 @@ async fn settings_page(cx: &Cx) -> Result { } + if section == Section::Security + && let Some((rate_limit_attempts, rate_window_minutes, session_lifetime_days, signin_link_lifetime_days)) = security + { +
+
+

(t(lang, Key::Security))

+ (t(lang, Key::AdminOnly)) +
+
+
+ + +
+
+ + +
+
+ if let Some(refusal) = &security_refusal { + (refusal.message_in(lang)) + } + if security_saved { + (t(lang, Key::Saved)) + } + +
+
+
+ } + if section == Section::Members && let Some(members) = &members {
diff --git a/crates/iz-web/tests/http.rs b/crates/iz-web/tests/http.rs index dae0948..1c7a2c5 100644 --- a/crates/iz-web/tests/http.rs +++ b/crates/iz-web/tests/http.rs @@ -2617,6 +2617,161 @@ async fn a_limit_outside_what_the_disk_should_promise_is_refused() { } } +/// The security section, end to end: an admin sees the rail link and the +/// panel, a member sees neither — including by asking for the section by URL +/// — a member's post to the save endpoint is refused by the handler, an +/// out-of-range number is refused by name and stores nothing, and a save in +/// range lands in the row and renders back into the fields. +#[tokio::test] +async fn the_security_section_is_admin_only_and_round_trips() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await; + + // The admin gets the rail link, the panel and the defaults in the fields. + let page = app + .get("/settings?section=security", Some(&admin_cookie)) + .await; + assert_eq!(page.status, StatusCode::OK); + let html = String::from_utf8_lossy(&page.bytes); + assert!( + html.contains(r#"href="/settings?section=security""#), + "{html}" + ); + assert!(html.contains(r#"id="security""#), "{html}"); + assert!( + html.contains(r#"name="rate_limit_attempts""#) + && html.contains(r#"name="rate_window_minutes""#) + && html.contains(r#"name="session_lifetime_days""#) + && html.contains(r#"name="signin_link_lifetime_days""#), + "{html}" + ); + + // The member gets neither the link nor the panel, by link or by URL. + let page = app.get("/settings", Some(&member)).await; + let html = String::from_utf8_lossy(&page.bytes); + assert!( + !html.contains(r#"href="/settings?section=security""#), + "{html}" + ); + assert!(!html.contains(r#"id="security""#), "{html}"); + let page = app + .get("/settings?section=security", Some(&member)) + .await; + let html = String::from_utf8_lossy(&page.bytes); + assert!(html.contains(r#"id="profile""#), "{html}"); + assert!(!html.contains(r#"id="security""#), "{html}"); + + // And the member's post is refused by the handler, not the markup. + let answer = app + .post( + "/api/save_security", + Some(&member), + &[ + ("rate_limit_attempts", "3"), + ("rate_window_minutes", "15"), + ("session_lifetime_days", "14"), + ("signin_link_lifetime_days", "7"), + ], + ) + .await; + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=forbidden&on=save_security"), + "{:?}", + answer.location + ); + + // An out-of-range knob is refused by name, each bound in turn. + for (attempts, window, session, link) in [ + ("0", "15", "14", "7"), + ("10", "0", "14", "7"), + ("10", "15", "0", "7"), + ("10", "15", "14", "0"), + ("101", "15", "14", "7"), + ("10", "1441", "14", "7"), + ("10", "15", "366", "7"), + ("10", "15", "14", "91"), + ] { + let answer = app + .post( + "/api/save_security", + Some(&admin_cookie), + &[ + ("rate_limit_attempts", attempts), + ("rate_window_minutes", window), + ("session_lifetime_days", session), + ("signin_link_lifetime_days", link), + ], + ) + .await; + let location = answer.location.as_deref().unwrap_or_default(); + assert!( + location.contains("refusal=bad-policy&on=save_security"), + "{attempts}/{window}/{session}/{link}: {location}" + ); + } + let workspace = app.store.workspace().await.unwrap().unwrap(); + assert_eq!( + workspace.rate_limit_attempts, 10, + "a refused save still changed the row" + ); + + // A save in range lands on the section with its saved note, the row + // agrees, and the fields render the saved values back. + let answer = app + .post( + "/api/save_security", + Some(&admin_cookie), + &[ + ("rate_limit_attempts", "3"), + ("rate_window_minutes", "60"), + ("session_lifetime_days", "30"), + ("signin_link_lifetime_days", "2"), + ], + ) + .await; + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("saved=save_security"), + "{:?}", + answer.location + ); + let workspace = app.store.workspace().await.unwrap().unwrap(); + assert_eq!(workspace.rate_limit_attempts, 3); + assert_eq!(workspace.rate_window_minutes, 60); + assert_eq!(workspace.session_lifetime_days, 30); + assert_eq!(workspace.signin_link_lifetime_days, 2); + + let page = app + .get("/settings?section=security", Some(&admin_cookie)) + .await; + let html = String::from_utf8_lossy(&page.bytes); + for field in [ + r#"name="rate_limit_attempts"#, + r#"name="rate_window_minutes"#, + r#"name="session_lifetime_days"#, + r#"name="signin_link_lifetime_days"#, + ] { + let at = html.find(field).expect("the field vanished"); + let value = &html[at..]; + assert!( + value.contains("value=\"3\"") + || value.contains("value=\"60\"") + || value.contains("value=\"30\"") + || value.contains("value=\"2\""), + "field {field} does not render its saved value: {}", + &value[..value.len().min(200)] + ); + } +} + #[tokio::test] async fn a_file_type_that_is_not_an_extension_is_refused() { let app = App::open().await; @@ -4637,7 +4792,7 @@ fn moment_for(body: &str, title: &str) -> String { .to_string() } -/// The hour out of a `moment_label`-shaped stamp like `"Aug 19 11:04"`. +/// The hour out of a `moment_label`-shaped stamp like `"Aug 19 11:04:07"`. fn hour_of(moment: &str) -> u32 { moment .rsplit(' ') @@ -9672,22 +9827,32 @@ async fn the_board_search_filters_and_composes_with_the_project_filter() { // and the redeem flow over the mailed link. // --------------------------------------------------------------------------- -/// The reset token out of the newest notice queued for the address — the mail -/// is the token's only carrier, so the test reads it like a recipient would. -async fn queued_reset_token(app: &App, email: &str) -> Option { +/// Every reset token queued for the address, oldest first. The newest ask +/// retires the earlier links, so a test that asks twice needs both. +async fn queued_reset_tokens(app: &App, email: &str) -> Vec { let sends = app .store .mail_queue(50, iz_core::store::FeedPage::Newest) .await .unwrap(); - let body = sends - .into_iter() - .rev() - .find(|send| send.kind == SendKind::Notice && send.recipient == email) - .and_then(|send| send.body)?; - body.rsplit_once("/reset/") - .and_then(|(_, rest)| rest.split_whitespace().next()) - .map(str::to_string) + let mut tokens = Vec::new(); + for send in sends { + if send.kind != SendKind::Notice || send.recipient != email { + continue; + } + let Some(body) = send.body else { continue }; + let Some((_, rest)) = body.rsplit_once("/reset/") else { continue }; + if let Some(token) = rest.split_whitespace().next() { + tokens.push(token.to_string()); + } + } + tokens +} + +/// The reset token out of the newest notice queued for the address — the mail +/// is the token's only carrier, so the test reads it like a recipient would. +async fn queued_reset_token(app: &App, email: &str) -> Option { + queued_reset_tokens(app, email).await.pop() } #[tokio::test] @@ -9733,9 +9898,19 @@ async fn a_reset_link_redeems_on_its_own_screen() { let _admin = admin(&app).await; app.post("/api/forgot_password", None, &[("email", "ada@iz.sh")]) .await; - let token = queued_reset_token(&app, "ada@iz.sh") - .await - .expect("no reset mail queued"); + // A second ask retires the first link: the newest mail carries the only + // working token, and the retired one is dead before the newer is + // redeemed. + app.post("/api/forgot_password", None, &[("email", "ada@iz.sh")]) + .await; + let mut resets = queued_reset_tokens(&app, "ada@iz.sh").await; + assert_eq!(resets.len(), 2, "each ask queued its own mail"); + let retired = resets.remove(0); + let token = resets.remove(0); + let page = app.get(&format!("/reset/{retired}"), None).await; + let html = String::from_utf8_lossy(&page.bytes); + assert!(html.contains("no longer works"), "{html}"); + assert!(!html.contains("Choose a new password"), "{html}"); // The mailed link opens the choose-password card, naming the address it // was mailed to.