forge
Explore
Log in

Don't you dare go Hollow

The security knobs are the admin's, a newer link retires the old, logs read to the second

Browse files at this commit

a8afcdd0862c86319af7b42a72a1582d17bb1bbfAhmet Kaan GümüşParent: 157ae0f
The attempt allowance, the rate window, the session lifetime and the
link lifetime were consts in accounts.rs; they are policy, so they join
the workspace row and a new admin-only Security section on Settings,
bounded like the other limits and refused as bad-policy outside them.
The schema grows its first numbered migration to carry them — 0001 is
frozen, 0002's ALTERs backfill the defaults, and reconcile's copy maps
hand an old database the same numbers.

Minting a sign-in link now retires every earlier unspent link of the
same kind for the account in the same transaction: a second reset mail
kills the first link, and a re-invite kills the earlier invitation.
Superseded links fail redeem exactly like spent ones.

Every stamp on the logs page reads to the second, through the formatter
the queue rows already used; the detail modal's notification lines ride
the same helper.

18 changed files +1152 -112

crates/iz-core/migrations/0001_init.sqlmodified+7 -4
@@ -7,10 +7,13 @@
7 -- creation, and Crockford-uppercase already, which is what lets a task key7 -- creation, and Crockford-uppercase already, which is what lets a task key
8 -- borrow its tail.8 -- borrow its tail.
9 --9 --
10--- This file is the whole schema, and it is edited in place: a change to a10+-- This file is the first migration, not the whole schema any more. It is the
11--- table is made here, in the table, never appended as an ALTER. An existing11+-- shape İz was deployed with before workspace settings could be versioned;
12--- database is brought up to it by `iz reconcile`, not by the store, so a12+-- everything after it is a numbered `0002_*.sql` beside it, and an empty
13--- change to a table lands in two places — here, and in that tool's copy map.13+-- database is built by applying them in order. A live database is brought up
14+-- by `iz reconcile`, not by re-running the files, so a change to a table
15+-- lands in three places — the newest migration, this file's table, and that
16+-- tool's copy map.
14 17
15 CREATE TABLE workspace (18 CREATE TABLE workspace (
16 id TEXT PRIMARY KEY,19 id TEXT PRIMARY KEY,
crates/iz-core/migrations/0002_security_knobs.sqladded+19 -0
@@ -0,0 +1,19 @@
1+-- The four security knobs as workspace settings.
2+--
3+-- Until this change the attempt allowance, the rate-limit window, the session
4+-- lifetime and the sign-in-link lifetime were named consts in `accounts.rs`;
5+-- they are policy, and policy belongs to the admin on the Settings screen, the
6+-- way the attachment limits already did. The `DEFAULT` on each column is the
7+-- backfill: SQLite fills every existing row with it as the column is added.
8+-- Databases already carrying the columns never see this file applied piecemeal
9+-- — they reach the declared shape through `iz reconcile`, whose copy map
10+-- backfills the same numbers.
11+--
12+-- The numbers here mirror `store::DEFAULT_RATE_LIMIT_ATTEMPTS` and its three
13+-- siblings in `crates/iz-core/src/store/mod.rs` — SQL cannot read a Rust
14+-- const, so the two lists must be changed together.
15+
16+ALTER TABLE workspace ADD COLUMN rate_limit_attempts INTEGER NOT NULL DEFAULT 10;
17+ALTER TABLE workspace ADD COLUMN rate_window_minutes INTEGER NOT NULL DEFAULT 15;
18+ALTER TABLE workspace ADD COLUMN session_lifetime_days INTEGER NOT NULL DEFAULT 14;
19+ALTER TABLE workspace ADD COLUMN signin_link_lifetime_days INTEGER NOT NULL DEFAULT 7;
crates/iz-core/src/accounts.rsmodified+71 -23
@@ -21,17 +21,47 @@ use crate::store::{
21 LinkKind, NewUser, Session, Store, StoreError, User, Workspace,21 LinkKind, NewUser, Session, Store, StoreError, User, Workspace,
22 };22 };
23 23
24-/// How long a first-sign-in link is good for. The mockups say seven days, and24+/// The account policy as the workspace row states it, read at use: the admin's
25-/// an expired link is not a dead account: resending opens the same one.25+/// Settings screen is what sets these, and a const here would be a second
26-pub const SIGNIN_LINK_LIFETIME: Duration = Duration::days(7);26+/// opinion the store could not overrule. An unclaimed install has no row to
27+/// read and stands on the defaults — its sign-in forms are rate-limited all
28+/// the same.
29+#[derive(Clone, Copy)]
30+struct Policy {
31+ rate_limit: u64,
32+ rate_window: Duration,
33+ session_lifetime: Duration,
34+ link_lifetime: Duration,
35+}
27 36
28-/// How long a signed-in browser stays signed in.37+impl Policy {
29-pub const SESSION_LIFETIME: Duration = Duration::days(14);38+ /// One indexed read of the workspace row. Callers pay it per use; the
39+ /// sign-in path already reads the row for other reasons.
40+ async fn read(store: &dyn Store) -> Result<Self> {
41+ Ok(Self::of(store.workspace().await?.as_ref()))
42+ }
30 43
31-/// The rate-limit window and its allowance. Deliberately modest: this exists so44+ fn of(workspace: Option<&Workspace>) -> Self {
32-/// an open form is not an unbounded Argon2 faucet, not to be clever.45+ use crate::store::{
33-pub const RATE_WINDOW: Duration = Duration::minutes(15);46+ DEFAULT_RATE_LIMIT_ATTEMPTS, DEFAULT_RATE_WINDOW_MINUTES,
34-pub const RATE_LIMIT: u64 = 10;47+ DEFAULT_SESSION_LIFETIME_DAYS, DEFAULT_SIGNIN_LINK_LIFETIME_DAYS,
48+ };
49+ let Some(workspace) = workspace else {
50+ return Self {
51+ rate_limit: DEFAULT_RATE_LIMIT_ATTEMPTS,
52+ rate_window: Duration::minutes(i64::from(DEFAULT_RATE_WINDOW_MINUTES)),
53+ session_lifetime: Duration::days(i64::from(DEFAULT_SESSION_LIFETIME_DAYS)),
54+ link_lifetime: Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS)),
55+ };
56+ };
57+ Self {
58+ rate_limit: workspace.rate_limit_attempts,
59+ rate_window: Duration::minutes(i64::from(workspace.rate_window_minutes)),
60+ session_lifetime: Duration::days(i64::from(workspace.session_lifetime_days)),
61+ link_lifetime: Duration::days(i64::from(workspace.signin_link_lifetime_days)),
62+ }
63+ }
64+}
35 65
36 /// What went wrong, in the vocabulary the caller is allowed to have.66 /// What went wrong, in the vocabulary the caller is allowed to have.
37 #[derive(Debug, thiserror::Error)]67 #[derive(Debug, thiserror::Error)]
@@ -228,16 +258,21 @@ impl Accounts {
228 .unwrap_or_else(|| self.fallback_url.clone()))258 .unwrap_or_else(|| self.fallback_url.clone()))
229 }259 }
230 260
261+ /// Mints the invitation link and queues its mail. Minting retires any
262+ /// earlier unspent link for the account: the newest link is the only one
263+ /// that works.
231 async fn mint_link(&self, actor: &User, user: &User) -> Result<Invitation> {264 async fn mint_link(&self, actor: &User, user: &User) -> Result<Invitation> {
265+ let policy = Policy::read(self.store.as_ref()).await?;
232 let token = Token::mint();266 let token = Token::mint();
233- let expires_at = OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME;267+ let expires_at = OffsetDateTime::now_utc() + policy.link_lifetime;
234 self.store268 self.store
235 .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Join)269 .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Join)
236 .await?;270 .await?;
237 let subject = "Your İz sign-in link";271 let subject = "Your İz sign-in link";
238 let body = format!(272 let body = format!(
239- "{actor} added you to İz.\n\n{base}/join/{token}\n\nThe link works once and expires in 7 days.\n",273+ "{actor} added you to İz.\n\n{base}/join/{token}\n\nThe link works once and expires in {days} days.\n",
240 actor = actor.display_name,274 actor = actor.display_name,
275+ days = policy.link_lifetime.whole_days(),
241 base = self.base().await?,276 base = self.base().await?,
242 token = token.expose(),277 token = token.expose(),
243 );278 );
@@ -334,7 +369,9 @@ impl Accounts {
334 /// account. The answer is the same whether it does or not: the miss path369 /// account. The answer is the same whether it does or not: the miss path
335 /// pays for an Argon2 hash the way sign-in's pays for a verify, and only370 /// pays for an Argon2 hash the way sign-in's pays for a verify, and only
336 /// the queued mail knows the difference. The token travels in the mail371 /// the queued mail knows the difference. The token travels in the mail
337- /// and nowhere else — this method hands it to nobody.372+ /// and nowhere else — this method hands it to nobody. A fresh reset
373+ /// retires the previous unspent one, so the newest mail carries the only
374+ /// working link.
338 ///375 ///
339 /// The client bucket refuses outright, like sign-in's. The address bucket376 /// The client bucket refuses outright, like sign-in's. The address bucket
340 /// counts but stays silent: refusing by name would hand anyone who knows377 /// counts but stays silent: refusing by name would hand anyone who knows
@@ -365,12 +402,18 @@ impl Accounts {
365 return Ok(());402 return Ok(());
366 }403 }
367 404
405+ let policy = Policy::read(self.store.as_ref()).await?;
368 let token = Token::mint();406 let token = Token::mint();
369- let expires_at = now + SIGNIN_LINK_LIFETIME;407+ let expires_at = now + policy.link_lifetime;
370 self.store408 self.store
371 .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Reset)409 .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Reset)
372 .await?;410 .await?;
373- let (subject, body) = reset_mail(&user, self.base().await?, &token.expose());411+ let (subject, body) = reset_mail(
412+ &user,
413+ self.base().await?,
414+ &token.expose(),
415+ policy.link_lifetime.whole_days(),
416+ );
374 self.store417 self.store
375 .queue_notice(&user.email, &subject, &body, now)418 .queue_notice(&user.email, &subject, &body, now)
376 .await?;419 .await?;
@@ -464,7 +507,7 @@ impl Accounts {
464 let address_bucket = format!("address:{}", email.trim().to_lowercase());507 let address_bucket = format!("address:{}", email.trim().to_lowercase());
465 // The address bucket counts, but it never refuses on its own: refusing508 // The address bucket counts, but it never refuses on its own: refusing
466 // before the verify would let anyone who knows a colleague's address509 // before the verify would let anyone who knows a colleague's address
467- // lock them out with ten wrong guesses every fifteen minutes. A correct510+ // lock them out with a few wrong guesses per window. A correct
468 // password always gets in; a wrong one still pays for its Argon2 and511 // password always gets in; a wrong one still pays for its Argon2 and
469 // still counts. The client bucket is what caps the work.512 // still counts. The client bucket is what caps the work.
470 let address_over_limit = self.over_limit(&address_bucket).await?;513 let address_over_limit = self.over_limit(&address_bucket).await?;
@@ -589,13 +632,14 @@ impl Accounts {
589 }632 }
590 633
591 async fn start_session(&self, user: User) -> Result<SignedIn> {634 async fn start_session(&self, user: User) -> Result<SignedIn> {
635+ let policy = Policy::read(self.store.as_ref()).await?;
592 let token = Token::mint();636 let token = Token::mint();
593 let session = self637 let session = self
594 .store638 .store
595 .create_session(639 .create_session(
596 &user.id,640 &user.id,
597 &token.hash(),641 &token.hash(),
598- OffsetDateTime::now_utc() + SESSION_LIFETIME,642+ OffsetDateTime::now_utc() + policy.session_lifetime,
599 )643 )
600 .await?;644 .await?;
601 Ok(SignedIn {645 Ok(SignedIn {
@@ -625,21 +669,25 @@ impl Accounts {
625 /// The same question without the refusal, for the bucket that counts but669 /// The same question without the refusal, for the bucket that counts but
626 /// must not lock an account out.670 /// must not lock an account out.
627 async fn over_limit(&self, bucket: &str) -> Result<bool> {671 async fn over_limit(&self, bucket: &str) -> Result<bool> {
628- let since = OffsetDateTime::now_utc() - RATE_WINDOW;672+ let policy = Policy::read(self.store.as_ref()).await?;
629- Ok(self.store.count_auth_attempts(bucket, since).await? >= RATE_LIMIT)673+ let since = OffsetDateTime::now_utc() - policy.rate_window;
674+ Ok(self
675+ .store
676+ .count_auth_attempts(bucket, since)
677+ .await? >= policy.rate_limit)
630 }678 }
631 }679 }
632 680
633-/// The reset mail, in the account's own language. Terse like the invitation's:681+/// what happened, the link, the once-only fact. The lifetime it names is the
634-/// what happened, the link, the once-only fact.682+/// workspace's own, so the number travels with the mail.
635-fn reset_mail(user: &User, base: String, token: &str) -> (String, String) {683+fn reset_mail(user: &User, base: String, token: &str, days: i64) -> (String, String) {
636 if user.language == "tr" {684 if user.language == "tr" {
637 (685 (
638 "İz parolanı sıfırla".to_string(),686 "İz parolanı sıfırla".to_string(),
639 format!(687 format!(
640 "Bu adres için bir İz parola sıfırlaması istendi.\n\n\688 "Bu adres için bir İz parola sıfırlaması istendi.\n\n\
641 {base}/reset/{token}\n\n\689 {base}/reset/{token}\n\n\
642- Bağlantı bir kez çalışır ve 7 gün içinde geçersiz olur.\n"690+ Bağlantı bir kez çalışır ve {days} gün içinde geçersiz olur.\n"
643 ),691 ),
644 )692 )
645 } else {693 } else {
@@ -648,7 +696,7 @@ fn reset_mail(user: &User, base: String, token: &str) -> (String, String) {
648 format!(696 format!(
649 "A reset was asked for the İz password on this address.\n\n\697 "A reset was asked for the İz password on this address.\n\n\
650 {base}/reset/{token}\n\n\698 {base}/reset/{token}\n\n\
651- The link works once and expires in 7 days.\n"699+ The link works once and expires in {days} days.\n"
652 ),700 ),
653 )701 )
654 }702 }
crates/iz-core/src/detail.rsmodified+4 -0
@@ -181,6 +181,7 @@ pub enum ActivityKind {
181 ProfileSaved,181 ProfileSaved,
182 SenderSaved,182 SenderSaved,
183 LimitsSaved,183 LimitsSaved,
184+ SecuritySaved,
184 TestMailSent,185 TestMailSent,
185 RuleCreated,186 RuleCreated,
186 RuleEdited,187 RuleEdited,
@@ -213,6 +214,7 @@ impl ActivityKind {
213 ActivityKind::ProfileSaved => "profile_saved",214 ActivityKind::ProfileSaved => "profile_saved",
214 ActivityKind::SenderSaved => "sender_saved",215 ActivityKind::SenderSaved => "sender_saved",
215 ActivityKind::LimitsSaved => "limits_saved",216 ActivityKind::LimitsSaved => "limits_saved",
217+ ActivityKind::SecuritySaved => "security_saved",
216 ActivityKind::TestMailSent => "test_mail_sent",218 ActivityKind::TestMailSent => "test_mail_sent",
217 ActivityKind::RuleCreated => "rule_created",219 ActivityKind::RuleCreated => "rule_created",
218 ActivityKind::RuleEdited => "rule_edited",220 ActivityKind::RuleEdited => "rule_edited",
@@ -270,6 +272,7 @@ impl ActivityKind {
270 "profile_saved" => ActivityKind::ProfileSaved,272 "profile_saved" => ActivityKind::ProfileSaved,
271 "sender_saved" => ActivityKind::SenderSaved,273 "sender_saved" => ActivityKind::SenderSaved,
272 "limits_saved" => ActivityKind::LimitsSaved,274 "limits_saved" => ActivityKind::LimitsSaved,
275+ "security_saved" => ActivityKind::SecuritySaved,
273 "test_mail_sent" => ActivityKind::TestMailSent,276 "test_mail_sent" => ActivityKind::TestMailSent,
274 "rule_created" => ActivityKind::RuleCreated,277 "rule_created" => ActivityKind::RuleCreated,
275 "rule_edited" => ActivityKind::RuleEdited,278 "rule_edited" => ActivityKind::RuleEdited,
@@ -335,6 +338,7 @@ impl ActivityEntry {
335 | ActivityKind::ProfileSaved338 | ActivityKind::ProfileSaved
336 | ActivityKind::SenderSaved339 | ActivityKind::SenderSaved
337 | ActivityKind::LimitsSaved340 | ActivityKind::LimitsSaved
341+ | ActivityKind::SecuritySaved
338 | ActivityKind::TestMailSent342 | ActivityKind::TestMailSent
339 | ActivityKind::RuleCreated343 | ActivityKind::RuleCreated
340 | ActivityKind::RuleEdited344 | ActivityKind::RuleEdited
crates/iz-core/src/mail.rsmodified+1 -0
@@ -924,6 +924,7 @@ impl Engine {
924 | ActivityKind::ProfileSaved924 | ActivityKind::ProfileSaved
925 | ActivityKind::SenderSaved925 | ActivityKind::SenderSaved
926 | ActivityKind::LimitsSaved926 | ActivityKind::LimitsSaved
927+ | ActivityKind::SecuritySaved
927 | ActivityKind::TestMailSent928 | ActivityKind::TestMailSent
928 | ActivityKind::RuleCreated929 | ActivityKind::RuleCreated
929 | ActivityKind::RuleEdited930 | ActivityKind::RuleEdited
crates/iz-core/src/store/mod.rsmodified+37 -0
@@ -52,6 +52,16 @@ pub enum StoreError {
52 52
53 pub type Result<T> = std::result::Result<T, StoreError>;53 pub type Result<T> = std::result::Result<T, StoreError>;
54 54
55+/// The security knobs a fresh workspace starts on, and what a database older
56+/// than `migrations/0002_security_knobs.sql` is backfilled onto — by that
57+/// migration's own `DEFAULT` clauses for the rows it meets, and by
58+/// `reconcile`'s copy map for every database it carries across. The SQL
59+/// literals mirror these numbers; change the two together.
60+pub const DEFAULT_RATE_LIMIT_ATTEMPTS: u64 = 10;
61+pub const DEFAULT_RATE_WINDOW_MINUTES: u32 = 15;
62+pub const DEFAULT_SESSION_LIFETIME_DAYS: u32 = 14;
63+pub const DEFAULT_SIGNIN_LINK_LIFETIME_DAYS: u32 = 7;
64+
55 /// A workspace and the settings that ride on it.65 /// A workspace and the settings that ride on it.
56 ///66 ///
57 /// The sender is here except for its password, which has no field on purpose:67 /// The sender is here except for its password, which has no field on purpose:
@@ -89,6 +99,14 @@ pub struct Workspace {
89 /// How long before a task's clock its reminder mail is queued, in99 /// How long before a task's clock its reminder mail is queued, in
90 /// minutes. `0` turns reminders off.100 /// minutes. `0` turns reminders off.
91 pub reminder_minutes: u32,101 pub reminder_minutes: u32,
102+ /// The sign-in attempts one client or address may spend per window.
103+ pub rate_limit_attempts: u64,
104+ /// How far back the attempt count reaches, in minutes.
105+ pub rate_window_minutes: u32,
106+ /// How long a signed-in browser stays signed in, in days.
107+ pub session_lifetime_days: u32,
108+ /// How long a first-sign-in or reset link is good for, in days.
109+ pub signin_link_lifetime_days: u32,
92 /// The origin mail links point at, when an admin has set one. `None`110 /// The origin mail links point at, when an admin has set one. `None`
93 /// means the address the process listens on — a box behind a proxy111 /// means the address the process listens on — a box behind a proxy
94 /// answers on localhost and is reached on a public name, and only an112 /// answers on localhost and is reached on a public name, and only an
@@ -800,6 +818,19 @@ pub trait Store: BoardReads + DetailReads + 'static {
800 reminder_minutes: u32,818 reminder_minutes: u32,
801 ) -> Result<()>;819 ) -> Result<()>;
802 820
821+ /// Writes the workspace's four security knobs — the sign-in attempt
822+ /// allowance, the rate-limit window, the session lifetime and the
823+ /// sign-in-link lifetime — in one write, because they are one save on
824+ /// one form.
825+ async fn set_security(
826+ &self,
827+ workspace_id: &str,
828+ rate_limit_attempts: u64,
829+ rate_window_minutes: u32,
830+ session_lifetime_days: u32,
831+ signin_link_lifetime_days: u32,
832+ ) -> Result<()>;
833+
803 // -- users -------------------------------------------------------------834 // -- users -------------------------------------------------------------
804 835
805 async fn create_user(&self, new: NewUser) -> Result<User>;836 async fn create_user(&self, new: NewUser) -> Result<User>;
@@ -857,6 +888,12 @@ pub trait Store: BoardReads + DetailReads + 'static {
857 888
858 /// Stores the hash of a freshly minted link. The caller keeps the plaintext889 /// Stores the hash of a freshly minted link. The caller keeps the plaintext
859 /// and shows it once. The kind decides which redeeming flow may spend it.890 /// and shows it once. The kind decides which redeeming flow may spend it.
891+ ///
892+ /// Minting retires: every earlier unspent link of the same kind for the
893+ /// same account is marked spent in the same transaction, so the newest
894+ /// link is the only live one. A retired link is refused exactly like a
895+ /// spent or expired one — retired *is* spent, the same `used_at` a
896+ /// redemption writes.
860 async fn create_signin_link(897 async fn create_signin_link(
861 &self,898 &self,
862 user_id: &str,899 user_id: &str,
crates/iz-core/src/store/reconcile.rsmodified+47 -6
@@ -12,7 +12,7 @@
12 //! while the rebuild runs. An extraction failure fails the rebuild, so the12 //! while the rebuild runs. An extraction failure fails the rebuild, so the
13 //! swap never trades the tables' binary for a directory that is not there.13 //! swap never trades the tables' binary for a directory that is not there.
14 14
15-use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint};15+use super::schema::{declared_fingerprint, diff_report, fingerprint, schema_sql};
16 use super::{Result, StoreError};16 use super::{Result, StoreError};
17 use turso::{Builder, Connection, params};17 use turso::{Builder, Connection, params};
18 use ulid::Ulid;18 use ulid::Ulid;
@@ -186,7 +186,7 @@ async fn rebuild(
186 .await186 .await
187 .map_err(|e| StoreError::Backend(e.to_string()))?;187 .map_err(|e| StoreError::Backend(e.to_string()))?;
188 new_conn188 new_conn
189- .execute_batch(SCHEMA)189+ .execute_batch(&schema_sql())
190 .await190 .await
191 .map_err(|e| StoreError::Backend(e.to_string()))?;191 .map_err(|e| StoreError::Backend(e.to_string()))?;
192 // The blobs leave the old database before any row is copied: the copy's192 // The blobs leave the old database before any row is copied: the copy's
@@ -271,6 +271,7 @@ fn build_maps(
271 old_has_reminder: bool,271 old_has_reminder: bool,
272 old_has_feed_seen: bool,272 old_has_feed_seen: bool,
273 old_has_tag: bool,273 old_has_tag: bool,
274+ old_has_security: bool,
274 ) -> Vec<TableMap> {275 ) -> Vec<TableMap> {
275 let mut maps = Vec::new();276 let mut maps = Vec::new();
276 277
@@ -343,6 +344,44 @@ fn build_maps(
343 "NULL".into()344 "NULL".into()
344 },345 },
345 ),346 ),
347+ (
348+ // The security knobs are the newest workspace columns: a
349+ // database old enough to be reconciled has never heard of
350+ // them and starts on today's defaults, exactly the numbers
351+ // the matching migration's `DEFAULT` clauses backfill. One
352+ // probe stands for all four — a database that carries one
353+ // carries them all, because they shipped together.
354+ "rate_limit_attempts",
355+ if old_has_security {
356+ "old.rate_limit_attempts".into()
357+ } else {
358+ crate::store::DEFAULT_RATE_LIMIT_ATTEMPTS.to_string()
359+ },
360+ ),
361+ (
362+ "rate_window_minutes",
363+ if old_has_security {
364+ "old.rate_window_minutes".into()
365+ } else {
366+ crate::store::DEFAULT_RATE_WINDOW_MINUTES.to_string()
367+ },
368+ ),
369+ (
370+ "session_lifetime_days",
371+ if old_has_security {
372+ "old.session_lifetime_days".into()
373+ } else {
374+ crate::store::DEFAULT_SESSION_LIFETIME_DAYS.to_string()
375+ },
376+ ),
377+ (
378+ "signin_link_lifetime_days",
379+ if old_has_security {
380+ "old.signin_link_lifetime_days".into()
381+ } else {
382+ crate::store::DEFAULT_SIGNIN_LINK_LIFETIME_DAYS.to_string()
383+ },
384+ ),
346 ("public_url", "old.public_url".into()),385 ("public_url", "old.public_url".into()),
347 ],386 ],
348 });387 });
@@ -792,6 +831,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) ->
792 let has_reminder = old_has_column(old_conn, "workspace", "reminder_minutes").await?;831 let has_reminder = old_has_column(old_conn, "workspace", "reminder_minutes").await?;
793 let has_feed_seen = old_has_column(old_conn, "user", "feed_seen_at").await?;832 let has_feed_seen = old_has_column(old_conn, "user", "feed_seen_at").await?;
794 let has_tag = old_has_column(old_conn, "tag", "id").await?;833 let has_tag = old_has_column(old_conn, "tag", "id").await?;
834+ let has_security = old_has_column(old_conn, "workspace", "rate_limit_attempts").await?;
795 let maps = build_maps(835 let maps = build_maps(
796 has_smtp_check,836 has_smtp_check,
797 has_batch_window,837 has_batch_window,
@@ -799,6 +839,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) ->
799 has_reminder,839 has_reminder,
800 has_feed_seen,840 has_feed_seen,
801 has_tag,841 has_tag,
842+ has_security,
802 );843 );
803 validate_maps(new_conn, &maps).await?;844 validate_maps(new_conn, &maps).await?;
804 845
@@ -1073,7 +1114,7 @@ mod tests {
1073 };1114 };
1074 use turso::{Builder, params};1115 use turso::{Builder, params};
1075 use ulid::Ulid;1116 use ulid::Ulid;
1076- use crate::store::schema::SCHEMA;1117+ use crate::store::schema::schema_sql;
1077 1118
1078 #[test]1119 #[test]
1079 fn backup_name_has_no_colons_or_spaces() {1120 fn backup_name_has_no_colons_or_spaces() {
@@ -1099,9 +1140,9 @@ mod tests {
1099 let path = dir.join("iz.db").to_str().unwrap().to_string();1140 let path = dir.join("iz.db").to_str().unwrap().to_string();
1100 let db = Builder::new_local(&path).build().await.unwrap();1141 let db = Builder::new_local(&path).build().await.unwrap();
1101 let conn = db.connect().unwrap();1142 let conn = db.connect().unwrap();
1102- conn.execute_batch(SCHEMA).await.unwrap();1143+ conn.execute_batch(&schema_sql()).await.unwrap();
1103 1144
1104- let maps = build_maps(false, false, false, false, false, false);1145+ let maps = build_maps(false, false, false, false, false, false, false);
1105 validate_maps(&conn, &maps)1146 validate_maps(&conn, &maps)
1106 .await1147 .await
1107 .expect("the full map set was refused against the declared schema");1148 .expect("the full map set was refused against the declared schema");
@@ -1131,7 +1172,7 @@ mod tests {
1131 let photo_bytes = b"face-bytes".to_vec();1172 let photo_bytes = b"face-bytes".to_vec();
1132 let db = Builder::new_local(path).build().await.unwrap();1173 let db = Builder::new_local(path).build().await.unwrap();
1133 let conn = db.connect().unwrap();1174 let conn = db.connect().unwrap();
1134- conn.execute_batch(SCHEMA).await.unwrap();1175+ conn.execute_batch(&schema_sql()).await.unwrap();
1135 // ALTER keeps the tables' own constraints intact, so this is the1176 // ALTER keeps the tables' own constraints intact, so this is the
1136 // shape a live database of the previous generation has.1177 // shape a live database of the previous generation has.
1137 conn.execute(1178 conn.execute(
crates/iz-core/src/store/schema.rsmodified+20 -3
@@ -9,8 +9,25 @@
9 use super::{Result, StoreError};9 use super::{Result, StoreError};
10 use turso::Connection;10 use turso::Connection;
11 11
12-/// The declared whole schema, applied to an empty database.12+/// The declared migrations, in order. An empty database is built by applying
13-pub(crate) const SCHEMA: &str = include_str!("../../migrations/0001_init.sql");13+/// them one after another; each one applies cleanly to what the ones before
14+/// it built (`0002` is `ALTER`s), so their concatenation is itself a valid
15+/// whole-schema script.
16+pub(crate) const MIGRATIONS: &[&str] = &[
17+ include_str!("../../migrations/0001_init.sql"),
18+ include_str!("../../migrations/0002_security_knobs.sql"),
19+];
20+
21+/// The whole declared schema — every migration applied in order — as one
22+/// batch of SQL.
23+pub(crate) fn schema_sql() -> String {
24+ let mut sql = String::new();
25+ for migration in MIGRATIONS {
26+ sql.push_str(migration);
27+ sql.push('\n');
28+ }
29+ sql
30+}
14 31
15 /// Reads and normalises the schema of the connected database.32 /// Reads and normalises the schema of the connected database.
16 ///33 ///
@@ -54,7 +71,7 @@ pub async fn declared_fingerprint() -> Result<String> {
54 .await71 .await
55 .map_err(|e| StoreError::Backend(e.to_string()))?;72 .map_err(|e| StoreError::Backend(e.to_string()))?;
56 let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;73 let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
57- conn.execute_batch(SCHEMA)74+ conn.execute_batch(&schema_sql())
58 .await75 .await
59 .map_err(|e| StoreError::Backend(e.to_string()))?;76 .map_err(|e| StoreError::Backend(e.to_string()))?;
60 fingerprint(&conn).await77 fingerprint(&conn).await
crates/iz-core/src/store/turso_store.rsmodified+76 -19
@@ -372,7 +372,7 @@ impl TursoStore {
372 372
373 if empty {373 if empty {
374 conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;374 conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
375- if let Err(e) = conn.execute_batch(super::schema::SCHEMA).await {375+ if let Err(e) = conn.execute_batch(&super::schema::schema_sql()).await {
376 let _ = conn.execute("ROLLBACK", ()).await;376 let _ = conn.execute("ROLLBACK", ()).await;
377 return Err(backend(e));377 return Err(backend(e));
378 }378 }
@@ -1110,6 +1110,10 @@ fn workspace_from(row: &Row) -> Result<Workspace> {
1110 }),1110 }),
1111 None => None,1111 None => None,
1112 },1112 },
1113+ rate_limit_attempts: row.get::<i64>(21).map_err(backend)?.max(0) as u64,
1114+ rate_window_minutes: row.get::<i64>(22).map_err(backend)?.max(0) as u32,
1115+ session_lifetime_days: row.get::<i64>(23).map_err(backend)?.max(0) as u32,
1116+ signin_link_lifetime_days: row.get::<i64>(24).map_err(backend)?.max(0) as u32,
1113 public_url: opt_text(row, 15)?,1117 public_url: opt_text(row, 15)?,
1114 })1118 })
1115 }1119 }
@@ -1122,7 +1126,8 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \
1122 smtp_from_name, smtp_from_address, \1126 smtp_from_name, smtp_from_address, \
1123 (smtp_password IS NOT NULL AND smtp_password <> ''), \1127 (smtp_password IS NOT NULL AND smtp_password <> ''), \
1124 smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \1128 smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \
1125- smtp_check_at, smtp_check_ms, smtp_check_error, mail_batch_minutes, reminder_minutes";1129+ smtp_check_at, smtp_check_ms, smtp_check_error, mail_batch_minutes, reminder_minutes, \
1130+ rate_limit_attempts, rate_window_minutes, session_lifetime_days, signin_link_lifetime_days";
1126 1131
1127 fn user_from(row: &Row) -> Result<User> {1132 fn user_from(row: &Row) -> Result<User> {
1128 Ok(User {1133 Ok(User {
@@ -1205,8 +1210,18 @@ impl Store for TursoStore {
1205 1210
1206 let claimed = async {1211 let claimed = async {
1207 tx.execute(1212 tx.execute(
1208- "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)",1213+ "INSERT INTO workspace (id, name, created_at, rate_limit_attempts, \
1209- params![workspace_id.clone(), workspace_name, now.clone()],1214+ rate_window_minutes, session_lifetime_days, signin_link_lifetime_days) \
1215+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1216+ params![
1217+ workspace_id.clone(),
1218+ workspace_name,
1219+ now.clone(),
1220+ crate::store::DEFAULT_RATE_LIMIT_ATTEMPTS as i64,
1221+ i64::from(crate::store::DEFAULT_RATE_WINDOW_MINUTES),
1222+ i64::from(crate::store::DEFAULT_SESSION_LIFETIME_DAYS),
1223+ i64::from(crate::store::DEFAULT_SIGNIN_LINK_LIFETIME_DAYS),
1224+ ],
1210 )1225 )
1211 .await?;1226 .await?;
1212 tx.execute(1227 tx.execute(
@@ -1458,6 +1473,36 @@ impl Store for TursoStore {
1458 Ok(())1473 Ok(())
1459 }1474 }
1460 1475
1476+ /// Writes the workspace's four security knobs: the sign-in attempt
1477+ /// allowance, the rate-limit window and the two lifetimes. One write,
1478+ /// because they are one save — the same rule `set_limits` lives by.
1479+ async fn set_security(
1480+ &self,
1481+ workspace_id: &str,
1482+ rate_limit_attempts: u64,
1483+ rate_window_minutes: u32,
1484+ session_lifetime_days: u32,
1485+ signin_link_lifetime_days: u32,
1486+ ) -> Result<()> {
1487+ let conn = self.conn.lock().await;
1488+ conn.execute(
1489+ "UPDATE workspace SET rate_limit_attempts = ?1, rate_window_minutes = ?2, \
1490+ session_lifetime_days = ?3, signin_link_lifetime_days = ?4 WHERE id = ?5",
1491+ params![
1492+ rate_limit_attempts as i64,
1493+ i64::from(rate_window_minutes),
1494+ i64::from(session_lifetime_days),
1495+ i64::from(signin_link_lifetime_days),
1496+ workspace_id
1497+ ],
1498+ )
1499+ .await
1500+ .map_err(backend)?;
1501+ drop(conn);
1502+ self.announce([Topic::Settings]);
1503+ Ok(())
1504+ }
1505+
1461 async fn create_user(&self, new: NewUser) -> Result<User> {1506 async fn create_user(&self, new: NewUser) -> Result<User> {
1462 let email = fold_email(&new.email);1507 let email = fold_email(&new.email);
1463 if self1508 if self
@@ -1808,23 +1853,35 @@ impl Store for TursoStore {
1808 kind: LinkKind,1853 kind: LinkKind,
1809 ) -> Result<SigninLink> {1854 ) -> Result<SigninLink> {
1810 let id = Ulid::new().to_string();1855 let id = Ulid::new().to_string();
1811- self.conn1856+ let now = now_text()?;
1812- .lock()1857+ let mut conn = self.tx_conn().await?;
1813- .await1858+ let tx = conn
1814- .execute(1859+ .transaction_with_behavior(TransactionBehavior::Immediate)
1815- "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at, kind) \
1816- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1817- params![
1818- id.clone(),
1819- user_id,
1820- token_hash,
1821- now_text()?,
1822- stamp(expires_at)?,
1823- kind.as_str(),
1824- ],
1825- )
1826 .await1860 .await
1827 .map_err(backend)?;1861 .map_err(backend)?;
1862+ // The newest link of a kind is the only live one: minting retires
1863+ // every earlier unspent link of the same kind for the account, in the
1864+ // same transaction as the insert, so a second reset mail cannot leave
1865+ // the first link working behind it. Retired is spent — the same
1866+ // stamped `used_at` a redemption writes — so there is no third state
1867+ // for reconcile or a fixture to know about. The update runs before
1868+ // the insert: the new row is unspent by definition and must not
1869+ // retire itself.
1870+ tx.execute(
1871+ "UPDATE signin_link SET used_at = ?1 \
1872+ WHERE user_id = ?2 AND kind = ?3 AND used_at IS NULL",
1873+ params![now.clone(), user_id, kind.as_str()],
1874+ )
1875+ .await
1876+ .map_err(backend)?;
1877+ tx.execute(
1878+ "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at, kind) \
1879+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1880+ params![id.clone(), user_id, token_hash, now, stamp(expires_at)?, kind.as_str()],
1881+ )
1882+ .await
1883+ .map_err(backend)?;
1884+ tx.commit().await.map_err(backend)?;
1828 self.announce([Topic::Members]);1885 self.announce([Topic::Members]);
1829 match self1886 match self
1830 .one_row(1887 .one_row(
crates/iz-core/tests/store.rsmodified+448 -30
@@ -9,8 +9,10 @@ use std::path::PathBuf;
9 use iz_core::Role;9 use iz_core::Role;
10 use iz_core::auth::{Token, hash_password};10 use iz_core::auth::{Token, hash_password};
11 use iz_core::store::{11 use iz_core::store::{
12- Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState,12+ Audience, DEFAULT_RATE_LIMIT_ATTEMPTS, DEFAULT_RATE_WINDOW_MINUTES,
13- Store, StoreError, Trigger, TursoStore, User,13+ DEFAULT_SESSION_LIFETIME_DAYS, DEFAULT_SIGNIN_LINK_LIFETIME_DAYS, Event, MailOutcome,
14+ MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState, Store, StoreError, Trigger,
15+ TursoStore, User,
14 };16 };
15 use time::{Duration, OffsetDateTime};17 use time::{Duration, OffsetDateTime};
16 use ulid::Ulid;18 use ulid::Ulid;
@@ -1087,6 +1089,37 @@ async fn limits_round_trip_including_the_file_type_list() {
1087 );1089 );
1088 }1090 }
1089 1091
1092+/// The security knobs come off the workspace row, not off consts: a fresh
1093+/// claim starts on the migration's defaults, one save changes all four, and
1094+/// the save announces itself like every other settings write.
1095+#[tokio::test]
1096+async fn the_security_knobs_default_round_trip_and_announce() {
1097+ let (scratch, ws_id, _) = workspace_with_admin().await;
1098+ let mut rx = scratch.store.subscribe();
1099+
1100+ let ws = scratch.store.workspace().await.unwrap().unwrap();
1101+ assert_eq!(ws.rate_limit_attempts, DEFAULT_RATE_LIMIT_ATTEMPTS);
1102+ assert_eq!(ws.rate_window_minutes, DEFAULT_RATE_WINDOW_MINUTES);
1103+ assert_eq!(ws.session_lifetime_days, DEFAULT_SESSION_LIFETIME_DAYS);
1104+ assert_eq!(
1105+ ws.signin_link_lifetime_days,
1106+ DEFAULT_SIGNIN_LINK_LIFETIME_DAYS
1107+ );
1108+
1109+ scratch
1110+ .store
1111+ .set_security(&ws_id, 3, 60, 30, 2)
1112+ .await
1113+ .unwrap();
1114+ let ws = scratch.store.workspace().await.unwrap().unwrap();
1115+ assert_eq!(ws.rate_limit_attempts, 3);
1116+ assert_eq!(ws.rate_window_minutes, 60);
1117+ assert_eq!(ws.session_lifetime_days, 30);
1118+ assert_eq!(ws.signin_link_lifetime_days, 2);
1119+
1120+ assert_eq!(announced(&mut rx), vec!["settings".to_string()]);
1121+}
1122+
1090 #[tokio::test]1123 #[tokio::test]
1091 async fn an_invited_member_has_no_password_until_they_choose_one() {1124 async fn an_invited_member_has_no_password_until_they_choose_one() {
1092 let (scratch, ws_id, _) = workspace_with_admin().await;1125 let (scratch, ws_id, _) = workspace_with_admin().await;
@@ -1694,7 +1727,7 @@ async fn auth_attempts_are_counted_over_a_window() {
1694 // Account flows.1727 // Account flows.
1695 // ---------------------------------------------------------------------------1728 // ---------------------------------------------------------------------------
1696 1729
1697-use iz_core::accounts::{AccountError, Accounts, RATE_LIMIT, SIGNIN_LINK_LIFETIME};1730+use iz_core::accounts::{AccountError, Accounts};
1698 use iz_core::auth::PasswordProblem;1731 use iz_core::auth::PasswordProblem;
1699 use std::sync::Arc;1732 use std::sync::Arc;
1700 1733
@@ -1721,6 +1754,18 @@ async fn claimed() -> (Scratch, Accounts, User) {
1721 (scratch, accounts, signed_in.user)1754 (scratch, accounts, signed_in.user)
1722 }1755 }
1723 1756
1757+/// The workspace's configured sign-in attempt allowance, read the way
1758+/// `Accounts` reads it — off the workspace row, never off a const.
1759+async fn allowance(accounts: &Accounts) -> u64 {
1760+ accounts
1761+ .store()
1762+ .workspace()
1763+ .await
1764+ .unwrap()
1765+ .expect("the workspace is claimed")
1766+ .rate_limit_attempts
1767+}
1768+
1724 #[tokio::test]1769 #[tokio::test]
1725 async fn claiming_makes_an_admin_and_signs_them_in() {1770 async fn claiming_makes_an_admin_and_signs_them_in() {
1726 let (_scratch, accounts) = accounts().await;1771 let (_scratch, accounts) = accounts().await;
@@ -1789,7 +1834,9 @@ async fn an_invited_member_chooses_their_own_password() {
1789 assert!(!invitation.user.has_signed_in(), "no password yet");1834 assert!(!invitation.user.has_signed_in(), "no password yet");
1790 assert!(1835 assert!(
1791 invitation.expires_at1836 invitation.expires_at
1792- > OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME - Duration::minutes(1)1837+ > OffsetDateTime::now_utc()
1838+ + Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS))
1839+ - Duration::minutes(1)
1793 );1840 );
1794 1841
1795 // The admin cannot sign in as them in the meantime.1842 // 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() {
2115 #[tokio::test]2162 #[tokio::test]
2116 async fn sign_in_attempts_are_rate_limited_per_address() {2163 async fn sign_in_attempts_are_rate_limited_per_address() {
2117 let (_scratch, accounts, _admin) = claimed().await;2164 let (_scratch, accounts, _admin) = claimed().await;
2118- for _ in 0..RATE_LIMIT {2165+ let allowance = allowance(&accounts).await;
2166+ for _ in 0..allowance {
2119 let _ = accounts2167 let _ = accounts
2120 .sign_in("ada@iz.sh", "wrong", "198.51.100.7")2168 .sign_in("ada@iz.sh", "wrong", "198.51.100.7")
2121 .await;2169 .await;
@@ -2137,14 +2185,15 @@ async fn sign_in_attempts_are_rate_limited_per_address() {
2137 }2185 }
2138 2186
2139 /// The lockout question, decided: an address bucket that refuses before the2187 /// The lockout question, decided: an address bucket that refuses before the
2140-/// verify lets anyone who knows a colleague's address keep them out with ten2188+/// verify lets anyone who knows a colleague's address keep them out with a
2141-/// wrong guesses every fifteen minutes, from anywhere, with no account of their2189+/// windowful of wrong guesses, from anywhere, with no account of their own.
2142-/// own. So the address bucket counts but never refuses a correct password.2190+/// So the address bucket counts but never refuses a correct password.
2143 #[tokio::test]2191 #[tokio::test]
2144 async fn a_flooded_address_never_locks_the_owner_out() {2192 async fn a_flooded_address_never_locks_the_owner_out() {
2145 let (_scratch, accounts, _admin) = claimed().await;2193 let (_scratch, accounts, _admin) = claimed().await;
2194+ let allowance = allowance(&accounts).await;
2146 // Each guess from its own client, so only the address bucket fills.2195 // Each guess from its own client, so only the address bucket fills.
2147- for i in 0..(RATE_LIMIT + 5) {2196+ for i in 0..(allowance + 5) {
2148 let _ = accounts2197 let _ = accounts
2149 .sign_in("ada@iz.sh", "wrong", &format!("203.0.113.{i}"))2198 .sign_in("ada@iz.sh", "wrong", &format!("203.0.113.{i}"))
2150 .await;2199 .await;
@@ -2160,7 +2209,8 @@ async fn a_flooded_address_never_locks_the_owner_out() {
2160 #[tokio::test]2209 #[tokio::test]
2161 async fn sign_in_attempts_are_rate_limited_per_client() {2210 async fn sign_in_attempts_are_rate_limited_per_client() {
2162 let (_scratch, accounts, _admin) = claimed().await;2211 let (_scratch, accounts, _admin) = claimed().await;
2163- for i in 0..RATE_LIMIT {2212+ let allowance = allowance(&accounts).await;
2213+ for i in 0..allowance {
2164 let _ = accounts2214 let _ = accounts
2165 .sign_in(&format!("nobody{i}@iz.sh"), "wrong", "203.0.113.9")2215 .sign_in(&format!("nobody{i}@iz.sh"), "wrong", "203.0.113.9")
2166 .await;2216 .await;
@@ -2180,11 +2230,12 @@ async fn sign_in_attempts_are_rate_limited_per_client() {
2180 #[tokio::test]2230 #[tokio::test]
2181 async fn link_redemption_is_rate_limited_per_client() {2231 async fn link_redemption_is_rate_limited_per_client() {
2182 let (_scratch, accounts, admin) = claimed().await;2232 let (_scratch, accounts, admin) = claimed().await;
2233+ let allowance = allowance(&accounts).await;
2183 let invitation = accounts2234 let invitation = accounts
2184 .invite(&admin, "grace@iz.sh", "Grace", Role::Member)2235 .invite(&admin, "grace@iz.sh", "Grace", Role::Member)
2185 .await2236 .await
2186 .unwrap();2237 .unwrap();
2187- for i in 0..RATE_LIMIT {2238+ for i in 0..allowance {
2188 let bogus = format!("{i:032x}");2239 let bogus = format!("{i:032x}");
2189 assert!(matches!(2240 assert!(matches!(
2190 accounts2241 accounts
@@ -2220,7 +2271,8 @@ async fn link_redemption_is_rate_limited_per_client() {
2220 #[tokio::test]2271 #[tokio::test]
2221 async fn changing_a_password_is_rate_limited_per_client() {2272 async fn changing_a_password_is_rate_limited_per_client() {
2222 let (_scratch, accounts, admin) = claimed().await;2273 let (_scratch, accounts, admin) = claimed().await;
2223- for _ in 0..RATE_LIMIT {2274+ let allowance = allowance(&accounts).await;
2275+ for _ in 0..allowance {
2224 let _ = accounts2276 let _ = accounts
2225 .change_password(&admin.id, "not-it", "chronometer-1761", "203.0.113.9")2277 .change_password(&admin.id, "not-it", "chronometer-1761", "203.0.113.9")
2226 .await;2278 .await;
@@ -2241,7 +2293,8 @@ async fn changing_a_password_is_rate_limited_per_client() {
2241 #[tokio::test]2293 #[tokio::test]
2242 async fn a_successful_sign_in_clears_the_bucket() {2294 async fn a_successful_sign_in_clears_the_bucket() {
2243 let (_scratch, accounts, _admin) = claimed().await;2295 let (_scratch, accounts, _admin) = claimed().await;
2244- for _ in 0..(RATE_LIMIT - 1) {2296+ let allowance = allowance(&accounts).await;
2297+ for _ in 0..(allowance - 1) {
2245 let _ = accounts2298 let _ = accounts
2246 .sign_in("ada@iz.sh", "wrong", "198.51.100.7")2299 .sign_in("ada@iz.sh", "wrong", "198.51.100.7")
2247 .await;2300 .await;
@@ -2259,6 +2312,125 @@ async fn a_successful_sign_in_clears_the_bucket() {
2259 ));2312 ));
2260 }2313 }
2261 2314
2315+/// The allowance is the workspace's number, not a const's: lowered to three,
2316+/// the third miss still answers Rejected and the fourth is RateLimited — the
2317+/// refusal lands exactly at the configured count.
2318+#[tokio::test]
2319+async fn the_rate_allowance_is_the_configured_one() {
2320+ let (scratch, accounts, admin) = claimed().await;
2321+ scratch
2322+ .store
2323+ .set_security(
2324+ &admin.workspace_id,
2325+ 3,
2326+ DEFAULT_RATE_WINDOW_MINUTES,
2327+ DEFAULT_SESSION_LIFETIME_DAYS,
2328+ DEFAULT_SIGNIN_LINK_LIFETIME_DAYS,
2329+ )
2330+ .await
2331+ .unwrap();
2332+
2333+ for _ in 0..3 {
2334+ assert!(matches!(
2335+ accounts.sign_in("ada@iz.sh", "wrong", "198.51.100.7").await,
2336+ Err(AccountError::Rejected)
2337+ ));
2338+ }
2339+ assert!(matches!(
2340+ accounts
2341+ .sign_in("ada@iz.sh", "wrong", "198.51.100.7")
2342+ .await,
2343+ Err(AccountError::RateLimited)
2344+ ));
2345+ // And the stored knob is the one that decided: the save is readable back.
2346+ assert_eq!(allowance(&accounts).await, 3);
2347+}
2348+
2349+/// The lifetimes are the workspace's too. Nothing here waits them out: what
2350+/// an admin changes is what the next session row and the next reset link
2351+/// are written with, read straight back off the store.
2352+#[tokio::test]
2353+async fn the_lifetimes_are_the_configured_ones() {
2354+ let (scratch, accounts, _admin) = claimed().await;
2355+
2356+ let signed_in = accounts
2357+ .sign_in("ada@iz.sh", "tide-tables-1892", "198.51.100.7")
2358+ .await
2359+ .unwrap();
2360+ let expected = OffsetDateTime::now_utc()
2361+ + Duration::days(i64::from(DEFAULT_SESSION_LIFETIME_DAYS));
2362+ assert!(
2363+ (signed_in.session.expires_at - expected).abs() < Duration::minutes(1),
2364+ "the session was not written with the default lifetime"
2365+ );
2366+
2367+ accounts
2368+ .request_password_reset("ada@iz.sh", "203.0.113.9")
2369+ .await
2370+ .unwrap();
2371+ let link_expiry = newest_link_expiry(&scratch).await;
2372+ let expected = OffsetDateTime::now_utc()
2373+ + Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS));
2374+ assert!(
2375+ (link_expiry - expected).abs() < Duration::minutes(1),
2376+ "the link was not written with the default lifetime"
2377+ );
2378+
2379+ scratch
2380+ .store
2381+ .set_security(
2382+ &signed_in.user.workspace_id,
2383+ DEFAULT_RATE_LIMIT_ATTEMPTS,
2384+ DEFAULT_RATE_WINDOW_MINUTES,
2385+ 30,
2386+ 2,
2387+ )
2388+ .await
2389+ .unwrap();
2390+
2391+ let signed_in = accounts
2392+ .sign_in("ada@iz.sh", "tide-tables-1892", "198.51.100.8")
2393+ .await
2394+ .unwrap();
2395+ let expected = OffsetDateTime::now_utc() + Duration::days(30);
2396+ assert!(
2397+ (signed_in.session.expires_at - expected).abs() < Duration::minutes(1),
2398+ "the session ignored the workspace's session lifetime"
2399+ );
2400+
2401+ accounts
2402+ .request_password_reset("ada@iz.sh", "203.0.113.9")
2403+ .await
2404+ .unwrap();
2405+ let link_expiry = newest_link_expiry(&scratch).await;
2406+ let expected = OffsetDateTime::now_utc() + Duration::days(2);
2407+ assert!(
2408+ (link_expiry - expected).abs() < Duration::minutes(1),
2409+ "the link ignored the workspace's link lifetime"
2410+ );
2411+}
2412+
2413+/// The `expires_at` of the newest stored sign-in link, read the way it sits
2414+/// on disk.
2415+async fn newest_link_expiry(scratch: &Scratch) -> OffsetDateTime {
2416+ let conn = raw_conn(scratch).await;
2417+ let mut rows = conn
2418+ .query(
2419+ "SELECT expires_at FROM signin_link ORDER BY created_at DESC LIMIT 1",
2420+ (),
2421+ )
2422+ .await
2423+ .unwrap();
2424+ let raw: String = rows
2425+ .next()
2426+ .await
2427+ .unwrap()
2428+ .expect("a reset was asked, so a link exists")
2429+ .get(0)
2430+ .unwrap();
2431+ OffsetDateTime::parse(&raw, &time::format_description::well_known::Rfc3339).unwrap()
2432+}
2433+
2262 #[tokio::test]2434 #[tokio::test]
2263 async fn changing_a_password_signs_out_every_device() {2435 async fn changing_a_password_signs_out_every_device() {
2264 let (_scratch, accounts, admin) = claimed().await;2436 let (_scratch, accounts, admin) = claimed().await;
@@ -7367,6 +7539,72 @@ async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() {
7367 let _ = std::fs::remove_dir_all(&dir);7539 let _ = std::fs::remove_dir_all(&dir);
7368 }7540 }
7369 7541
7542+/// The migration the security knobs exist for: a database of the shape the
7543+/// first migration builds — everything an install made before
7544+/// `0002_security_knobs.sql` shipped — comes up through the store's own
7545+/// repair path, and its workspace lands on the defaults the migration and
7546+/// the copy map both backfill, accounts and tasks intact.
7547+#[tokio::test]
7548+async fn reconcile_backfills_the_security_knobs_on_a_first_migration_database() {
7549+ let dir = std::env::temp_dir().join(format!("iz-reconcile-{}", Ulid::new()));
7550+ std::fs::create_dir_all(&dir).unwrap();
7551+ let path = dir.join("iz.db").to_str().unwrap().to_string();
7552+
7553+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7554+ let conn = db.connect().unwrap();
7555+ conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap();
7556+ conn.execute_batch(include_str!("../migrations/0001_init.sql"))
7557+ .await
7558+ .unwrap();
7559+ let now = "2026-09-01T09:00:00Z";
7560+ conn.execute_batch(&format!(
7561+ "INSERT INTO workspace (id, name, created_at) VALUES ('W1', 'Dizey', '{now}');
7562+ INSERT INTO user (id, workspace_id, email, display_name, role, password_hash, created_at) \
7563+ VALUES ('U1', 'W1', 'ada@iz.sh', 'Ada', 'admin', 'argon2$hash', '{now}');
7564+ INSERT INTO workspace_owner (singleton, user_id, claimed_at) VALUES (1, 'U1', '{now}');"
7565+ ))
7566+ .await
7567+ .unwrap();
7568+ drop(conn);
7569+ drop(db);
7570+
7571+ // Opening the store is the boot the upgrade happens on: the stale shape
7572+ // is reconciled before any handle is kept.
7573+ let store = TursoStore::open(&path, &dir.join("storage"))
7574+ .await
7575+ .expect("the store refused a first-migration database");
7576+
7577+ let ws = store.workspace().await.unwrap().unwrap();
7578+ assert_eq!(ws.rate_limit_attempts, DEFAULT_RATE_LIMIT_ATTEMPTS);
7579+ assert_eq!(ws.rate_window_minutes, DEFAULT_RATE_WINDOW_MINUTES);
7580+ assert_eq!(ws.session_lifetime_days, DEFAULT_SESSION_LIFETIME_DAYS);
7581+ assert_eq!(
7582+ ws.signin_link_lifetime_days,
7583+ DEFAULT_SIGNIN_LINK_LIFETIME_DAYS
7584+ );
7585+ assert_eq!(ws.name, "Dizey", "the workspace row itself was lost");
7586+ assert_eq!(
7587+ scalar(&path, "SELECT COUNT(*) FROM user").await,
7588+ 1,
7589+ "the admin account did not come across"
7590+ );
7591+
7592+ // A database already on the new shape is not reconciled again: opening
7593+ // twice in a row is ordinary, and the knobs keep what a save wrote.
7594+ store
7595+ .set_security("W1", 7, 30, 21, 3)
7596+ .await
7597+ .unwrap();
7598+ drop(store);
7599+ let second = TursoStore::open(&path, &dir.join("storage"))
7600+ .await
7601+ .unwrap();
7602+ let ws = second.workspace().await.unwrap().unwrap();
7603+ assert_eq!(ws.rate_limit_attempts, 7, "a second boot reset the knobs");
7604+ assert_eq!(ws.rate_window_minutes, 30);
7605+ let _ = std::fs::remove_dir_all(&dir);
7606+}
7607+
7370 /// The rebuild the tag map exists for: a database that already carries user7608 /// The rebuild the tag map exists for: a database that already carries user
7371 /// tags hands every one of them across untouched — same id, same board, same7609 /// tags hands every one of them across untouched — same id, same board, same
7372 /// name, same order, same default mark — and every task still points at the7610 /// 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() {
9013 // browser out. The address's existence stays the requester's guess.9251 // browser out. The address's existence stays the requester's guess.
9014 // ---------------------------------------------------------------------------9252 // ---------------------------------------------------------------------------
9015 9253
9016-/// The reset token out of the newest notice queued for the address — the mail9254+/// Every reset token queued for the address, oldest first. The newest ask
9017-/// is the token's only carrier, so the test reads it like a recipient would.9255+/// retires the earlier links, so a test that asks twice needs both.
9018-async fn queued_reset_token(store: &std::sync::Arc<dyn Store>, email: &str) -> Option<String> {9256+async fn queued_reset_tokens(store: &std::sync::Arc<dyn Store>, email: &str) -> Vec<String> {
9019 let sends = store9257 let sends = store
9020 .mail_queue(50, iz_core::store::FeedPage::Newest)9258 .mail_queue(50, iz_core::store::FeedPage::Newest)
9021 .await9259 .await
9022 .unwrap();9260 .unwrap();
9023- let body = sends9261+ let mut tokens = Vec::new();
9024- .into_iter()9262+ for send in sends {
9025- .rev()9263+ if send.kind != SendKind::Notice || send.recipient != email {
9026- .find(|send| send.kind == iz_core::store::SendKind::Notice && send.recipient == email)9264+ continue;
9027- .and_then(|send| send.body)?;9265+ }
9028- body.rsplit_once("/reset/")9266+ let Some(body) = send.body else { continue };
9029- .and_then(|(_, rest)| rest.split_whitespace().next())9267+ let Some((_, rest)) = body.rsplit_once("/reset/") else { continue };
9030- .map(str::to_string)9268+ if let Some(token) = rest.split_whitespace().next() {
9269+ tokens.push(token.to_string());
9270+ }
9271+ }
9272+ tokens
9273+}
9274+
9275+/// The reset token out of the newest notice queued for the address — the mail
9276+/// is the token's only carrier, so the test reads it like a recipient would.
9277+async fn queued_reset_token(store: &std::sync::Arc<dyn Store>, email: &str) -> Option<String> {
9278+ queued_reset_tokens(store, email).await.pop()
9031 }9279 }
9032 9280
9033 #[tokio::test]9281 #[tokio::test]
@@ -9174,7 +9422,8 @@ async fn each_link_redeems_only_on_its_own_screen() {
9174 .create_signin_link(9422 .create_signin_link(
9175 &admin.id,9423 &admin.id,
9176 &join.hash(),9424 &join.hash(),
9177- time::OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME,9425+ time::OffsetDateTime::now_utc()
9426+ + time::Duration::days(i64::from(DEFAULT_SIGNIN_LINK_LIFETIME_DAYS)),
9178 iz_core::store::LinkKind::Join,9427 iz_core::store::LinkKind::Join,
9179 )9428 )
9180 .await9429 .await
@@ -9201,16 +9450,186 @@ async fn each_link_redeems_only_on_its_own_screen() {
9201 ));9450 ));
9202 }9451 }
9203 9452
9453+#[tokio::test]
9454+async fn a_second_reset_request_retires_the_first_link() {
9455+ let (_scratch, accounts, _admin) = claimed().await;
9456+ accounts
9457+ .request_password_reset("ada@iz.sh", "203.0.113.9")
9458+ .await
9459+ .unwrap();
9460+ accounts
9461+ .request_password_reset("ada@iz.sh", "203.0.113.9")
9462+ .await
9463+ .unwrap();
9464+ let tokens = queued_reset_tokens(accounts.store(), "ada@iz.sh").await;
9465+ assert_eq!(tokens.len(), 2, "each ask queued its own mail");
9466+
9467+ // The first link died when the second was minted — before the second was
9468+ // redeemed — and it is refused like any other dead link.
9469+ assert!(matches!(
9470+ accounts
9471+ .redeem_reset_link(&tokens[0], "chronometer-1761", "203.0.113.10")
9472+ .await,
9473+ Err(AccountError::Rejected)
9474+ ));
9475+
9476+ // The newest link is the one that works, and it really changes the
9477+ // password.
9478+ accounts
9479+ .redeem_reset_link(&tokens[1], "chronometer-1761", "203.0.113.10")
9480+ .await
9481+ .unwrap();
9482+ assert!(matches!(
9483+ accounts
9484+ .sign_in("ada@iz.sh", "tide-tables-1892", "198.51.100.11")
9485+ .await,
9486+ Err(AccountError::Rejected)
9487+ ));
9488+ accounts
9489+ .sign_in("ada@iz.sh", "chronometer-1761", "198.51.100.11")
9490+ .await
9491+ .unwrap();
9492+}
9493+
9494+#[tokio::test]
9495+async fn a_second_invitation_retires_the_first_link() {
9496+ let (_scratch, accounts, admin) = claimed().await;
9497+ let first = accounts
9498+ .invite(&admin, "grace@iz.sh", "Grace", Role::Member)
9499+ .await
9500+ .unwrap();
9501+ let second = accounts
9502+ .resend_invitation(&admin, &first.user.id)
9503+ .await
9504+ .unwrap();
9505+ assert_ne!(first.token.expose(), second.token.expose());
9506+
9507+ // The first link died when the second was minted.
9508+ assert!(matches!(
9509+ accounts
9510+ .redeem_signin_link(first.token.expose(), "sextant-and-chart", "198.51.100.7")
9511+ .await,
9512+ Err(AccountError::Rejected)
9513+ ));
9514+ // The second sets the password it was always going to.
9515+ let signed_in = accounts
9516+ .redeem_signin_link(second.token.expose(), "sextant-and-chart", "198.51.100.7")
9517+ .await
9518+ .unwrap();
9519+ assert_eq!(signed_in.user.id, first.user.id);
9520+ accounts
9521+ .sign_in("grace@iz.sh", "sextant-and-chart", "198.51.100.7")
9522+ .await
9523+ .unwrap();
9524+}
9525+
9526+#[tokio::test]
9527+async fn a_retired_link_stays_retired_after_the_newer_one_redeems() {
9528+ let (_scratch, accounts, admin) = claimed().await;
9529+
9530+ // Reset: redeeming the newest mail must not wake the retired one.
9531+ accounts
9532+ .request_password_reset("ada@iz.sh", "203.0.113.9")
9533+ .await
9534+ .unwrap();
9535+ accounts
9536+ .request_password_reset("ada@iz.sh", "203.0.113.9")
9537+ .await
9538+ .unwrap();
9539+ let resets = queued_reset_tokens(accounts.store(), "ada@iz.sh").await;
9540+ assert_eq!(resets.len(), 2);
9541+ accounts
9542+ .redeem_reset_link(&resets[1], "chronometer-1761", "203.0.113.10")
9543+ .await
9544+ .unwrap();
9545+ assert!(matches!(
9546+ accounts
9547+ .redeem_reset_link(&resets[0], "harbor-and-pilot-1812", "203.0.113.10")
9548+ .await,
9549+ Err(AccountError::Rejected)
9550+ ));
9551+
9552+ // Join: the same for a resent invitation.
9553+ let first = accounts
9554+ .invite(&admin, "grace@iz.sh", "Grace", Role::Member)
9555+ .await
9556+ .unwrap();
9557+ let second = accounts
9558+ .resend_invitation(&admin, &first.user.id)
9559+ .await
9560+ .unwrap();
9561+ accounts
9562+ .redeem_signin_link(second.token.expose(), "sextant-and-chart", "198.51.100.7")
9563+ .await
9564+ .unwrap();
9565+ assert!(matches!(
9566+ accounts
9567+ .redeem_signin_link(first.token.expose(), "harbor-and-pilot-1812", "198.51.100.7")
9568+ .await,
9569+ Err(AccountError::Rejected)
9570+ ));
9571+}
9572+
9573+#[tokio::test]
9574+async fn a_fresh_link_of_one_kind_leaves_the_other_kinds_link_alone() {
9575+ let (scratch, accounts, admin) = claimed().await;
9576+
9577+ // An invited member who has not signed in can still be mailed a reset:
9578+ // both links are live, and neither mint retires the other.
9579+ let invitation = accounts
9580+ .invite(&admin, "grace@iz.sh", "Grace", Role::Member)
9581+ .await
9582+ .unwrap();
9583+ accounts
9584+ .request_password_reset("grace@iz.sh", "203.0.113.9")
9585+ .await
9586+ .unwrap();
9587+ let join = scratch
9588+ .store
9589+ .signin_link_by_hash(&invitation.token.hash())
9590+ .await
9591+ .unwrap()
9592+ .expect("the invitation link is stored");
9593+ assert!(
9594+ join.is_usable(OffsetDateTime::now_utc()),
9595+ "the reset mint retired the invitation"
9596+ );
9597+
9598+ // And the other way round: the admin holds a live reset; minting her an
9599+ // invitation over it leaves the reset spendable, and both links open
9600+ // their own screens.
9601+ accounts
9602+ .request_password_reset("ada@iz.sh", "203.0.113.9")
9603+ .await
9604+ .unwrap();
9605+ let resent = accounts
9606+ .resend_invitation(&admin, &admin.id)
9607+ .await
9608+ .unwrap();
9609+ let reset = queued_reset_token(accounts.store(), "ada@iz.sh")
9610+ .await
9611+ .expect("no reset mail queued");
9612+ accounts
9613+ .redeem_reset_link(&reset, "chronometer-1761", "203.0.113.10")
9614+ .await
9615+ .unwrap();
9616+ accounts
9617+ .redeem_signin_link(resent.token.expose(), "sextant-and-chart", "198.51.100.7")
9618+ .await
9619+ .unwrap();
9620+}
9621+
9204 #[tokio::test]9622 #[tokio::test]
9205 async fn reset_asks_are_rate_limited_per_client_and_silenced_per_address() {9623 async fn reset_asks_are_rate_limited_per_client_and_silenced_per_address() {
9206 let (dir, store, workspace, _admin) = shared().await;9624 let (dir, store, workspace, _admin) = shared().await;
9207 let _grace = member(&store, &workspace, "grace@iz.sh", "Grace").await;9625 let _grace = member(&store, &workspace, "grace@iz.sh", "Grace").await;
9208 let store = store as std::sync::Arc<dyn Store>;9626 let store = store as std::sync::Arc<dyn Store>;
9209 let accounts = Accounts::new(store.clone(), "https://iz.sh");9627 let accounts = Accounts::new(store.clone(), "https://iz.sh");
9628+ let allowance = accounts.store().workspace().await.unwrap().unwrap().rate_limit_attempts;
9210 9629
9211- // One machine asks RATE_LIMIT times: every ask answers the same, and the9630+ // One machine asks allowance times: every ask answers the same, and the
9212- // eleventh from that machine is refused by name.9631+ // next from that machine is refused by name.
9213- for _ in 0..RATE_LIMIT {9632+ for _ in 0..allowance {
9214 accounts9633 accounts
9215 .request_password_reset("grace@iz.sh", "203.0.113.9")9634 .request_password_reset("grace@iz.sh", "203.0.113.9")
9216 .await9635 .await
@@ -9234,8 +9653,7 @@ async fn reset_asks_are_rate_limited_per_client_and_silenced_per_address() {
9234 "SELECT COUNT(*) FROM mail_send WHERE kind = 'notice'",9653 "SELECT COUNT(*) FROM mail_send WHERE kind = 'notice'",
9235 )9654 )
9236 .await;9655 .await;
9237- assert_eq!(queued, RATE_LIMIT as i64, "the flood minted no mail");9656+ assert_eq!(queued, allowance as i64, "the flood minted no mail");
9238- let _ = std::fs::remove_dir_all(&dir);
9239 }9657 }
9240 9658
9241 #[tokio::test]9659 #[tokio::test]
crates/iz-web/src/auth.rsmodified+19 -6
@@ -7,7 +7,7 @@
7 //! [`crate::server::carry_refusal_on_redirect`] can carry it onto that7 //! [`crate::server::carry_refusal_on_redirect`] can carry it onto that
8 //! redirect's query.8 //! redirect's query.
9 9
10-use iz_core::accounts::SESSION_LIFETIME;10+use iz_core::store::DEFAULT_SESSION_LIFETIME_DAYS;
11 use iz_core::detail::ActivityKind;11 use iz_core::detail::ActivityKind;
12 use serde::{Deserialize, Serialize};12 use serde::{Deserialize, Serialize};
13 use topcoat::Result;13 use topcoat::Result;
@@ -23,6 +23,19 @@ use crate::server::{
23 };23 };
24 use crate::settings::encode_q;24 use crate::settings::encode_q;
25 25
26+/// The workspace's session lifetime, read the same way every other knob is —
27+/// off the workspace row through the account service's store — so an admin's
28+/// change in Settings reaches the next cookie without a restart. A workspace
29+/// row that is not there yet (nobody has claimed the install) stands on the
30+/// default.
31+async fn session_lifetime(cx: &Cx) -> time::Duration {
32+ let days = match accounts(cx).store().workspace().await {
33+ Ok(Some(workspace)) => workspace.session_lifetime_days,
34+ _ => DEFAULT_SESSION_LIFETIME_DAYS,
35+ };
36+ time::Duration::days(i64::from(days))
37+}
38+
26 /// The workspace has exactly one name and no screen that sets it, so it is a39 /// The workspace has exactly one name and no screen that sets it, so it is a
27 /// constant rather than a field nobody was shown.40 /// constant rather than a field nobody was shown.
28 pub const WORKSPACE_NAME: &str = "İz";41 pub const WORKSPACE_NAME: &str = "İz";
@@ -100,7 +113,7 @@ async fn claim_workspace(cx: &Cx, Form(input): Form<ClaimWorkspaceForm>) -> Redi
100 .await113 .await
101 {114 {
102 Ok((_workspace, signed_in)) => {115 Ok((_workspace, signed_in)) => {
103- set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME);116+ set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await);
104 let _ = accounts(cx)117 let _ = accounts(cx)
105 .store()118 .store()
106 .record_event(119 .record_event(
@@ -131,7 +144,7 @@ async fn sign_in(cx: &Cx, Form(input): Form<SignInForm>) -> Redirect {
131 .await144 .await
132 {145 {
133 Ok(signed_in) => {146 Ok(signed_in) => {
134- set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME);147+ set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await);
135 let _ = accounts(cx)148 let _ = accounts(cx)
136 .store()149 .store()
137 .record_event(150 .record_event(
@@ -198,7 +211,7 @@ async fn redeem_link(cx: &Cx, Form(input): Form<RedeemLinkForm>) -> Redirect {
198 .await211 .await
199 {212 {
200 Ok(signed_in) => {213 Ok(signed_in) => {
201- set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME);214+ set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await);
202 let _ = accounts(cx)215 let _ = accounts(cx)
203 .store()216 .store()
204 .record_event(217 .record_event(
@@ -240,7 +253,7 @@ async fn change_password(cx: &Cx, Form(input): Form<ChangePasswordForm>) -> Redi
240 .await253 .await
241 {254 {
242 Ok(signed_in) => {255 Ok(signed_in) => {
243- set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME);256+ set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await);
244 let _ = accounts(cx)257 let _ = accounts(cx)
245 .store()258 .store()
246 .record_event(259 .record_event(
@@ -422,7 +435,7 @@ async fn redeem_reset(cx: &Cx, Form(input): Form<RedeemResetForm>) -> Redirect {
422 .await435 .await
423 {436 {
424 Ok(signed_in) => {437 Ok(signed_in) => {
425- set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME);438+ set_session_cookie(cx, signed_in.session_token.expose(), session_lifetime(cx).await);
426 let _ = accounts(cx)439 let _ = accounts(cx)
427 .store()440 .store()
428 .record_event(441 .record_event(
crates/iz-web/src/detail.rsmodified+4 -3
@@ -18,7 +18,8 @@
18 18
19 use iz_core::board::{DeadlineState, Person};19 use iz_core::board::{DeadlineState, Person};
20 use iz_core::detail::{20 use iz_core::detail::{
21- Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in, parse_zone,21+ Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in,
22+ moment_label_with_seconds_in, parse_zone,
22 };23 };
23 use iz_core::store::{Store, StoreError, User};24 use iz_core::store::{Store, StoreError, User};
24 use serde::{Deserialize, Serialize};25 use serde::{Deserialize, Serialize};
@@ -418,14 +419,14 @@ async fn load_snapshot(
418 state_kind: state_kind.to_string(),419 state_kind: state_kind.to_string(),
419 attempts: send.attempts,420 attempts: send.attempts,
420 last_error: may_administer.then(|| send.last_error.clone()).flatten(),421 last_error: may_administer.then(|| send.last_error.clone()).flatten(),
421- sent_at: send.sent_at.map(|at| moment_label_in(at, zone)),422+ sent_at: send.sent_at.map(|at| moment_label_with_seconds_in(at, zone)),
422 }423 }
423 })424 })
424 .collect();425 .collect();
425 let outcome = crate::logs::outcome_word(decision.outcome, lang).to_string();426 let outcome = crate::logs::outcome_word(decision.outcome, lang).to_string();
426 notifications.push(NotificationLine {427 notifications.push(NotificationLine {
427 happened,428 happened,
428- at: moment_label_in(decision.at, zone),429+ at: moment_label_with_seconds_in(decision.at, zone),
429 rule_name,430 rule_name,
430 outcome: if outcome_detail.is_empty() {431 outcome: if outcome_detail.is_empty() {
431 outcome432 outcome
crates/iz-web/src/i18n.rsmodified+18 -0
@@ -153,6 +153,11 @@ pub enum Key {
153 AttachmentLimitLabel,153 AttachmentLimitLabel,
154 PhotoLimitLabel,154 PhotoLimitLabel,
155 AllowedFileTypesLabel,155 AllowedFileTypesLabel,
156+ Security,
157+ RateLimitAttemptsLabel,
158+ RateWindowLabel,
159+ SessionLifetimeLabel,
160+ LinkLifetimeLabel,
156 Members,161 Members,
157 Message,162 Message,
158 Everyone,163 Everyone,
@@ -298,6 +303,7 @@ pub enum Key {
298 ActProfileSaved,303 ActProfileSaved,
299 ActSenderSaved,304 ActSenderSaved,
300 ActLimitsSaved,305 ActLimitsSaved,
306+ ActSecuritySaved,
301 ActTestMailSent,307 ActTestMailSent,
302 ActMessageSent,308 ActMessageSent,
303 ActSendRetried,309 ActSendRetried,
@@ -636,6 +642,16 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
636 (PhotoLimitLabel, Tr) => "FOTOĞRAF LİMİTİ (MB)",642 (PhotoLimitLabel, Tr) => "FOTOĞRAF LİMİTİ (MB)",
637 (AllowedFileTypesLabel, En) => "ALLOWED FILE TYPES",643 (AllowedFileTypesLabel, En) => "ALLOWED FILE TYPES",
638 (AllowedFileTypesLabel, Tr) => "İZİN VERİLEN DOSYA TÜRLERİ",644 (AllowedFileTypesLabel, Tr) => "İZİN VERİLEN DOSYA TÜRLERİ",
645+ (Security, En) => "Security",
646+ (Security, Tr) => "Güvenlik",
647+ (RateLimitAttemptsLabel, En) => "Sign-in attempts",
648+ (RateLimitAttemptsLabel, Tr) => "Giriş denemesi",
649+ (RateWindowLabel, En) => "Attempt window (minutes)",
650+ (RateWindowLabel, Tr) => "Deneme penceresi (dakika)",
651+ (SessionLifetimeLabel, En) => "Session lifetime (days)",
652+ (SessionLifetimeLabel, Tr) => "Oturum süresi (gün)",
653+ (LinkLifetimeLabel, En) => "Link lifetime (days)",
654+ (LinkLifetimeLabel, Tr) => "Bağlantı süresi (gün)",
639 (Members, En) => "Members",655 (Members, En) => "Members",
640 (Members, Tr) => "Üyeler",656 (Members, Tr) => "Üyeler",
641 (Message, En) => "Message",657 (Message, En) => "Message",
@@ -921,6 +937,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
921 (ActSenderSaved, Tr) => "gönderen ayarlarını kaydetti",937 (ActSenderSaved, Tr) => "gönderen ayarlarını kaydetti",
922 (ActLimitsSaved, En) => "saved the limits",938 (ActLimitsSaved, En) => "saved the limits",
923 (ActLimitsSaved, Tr) => "sınırları kaydetti",939 (ActLimitsSaved, Tr) => "sınırları kaydetti",
940+ (ActSecuritySaved, En) => "saved the security settings",
941+ (ActSecuritySaved, Tr) => "güvenlik ayarlarını kaydetti",
924 (ActTestMailSent, En) => "sent a test mail",942 (ActTestMailSent, En) => "sent a test mail",
925 (ActTestMailSent, Tr) => "test postası gönderdi",943 (ActTestMailSent, Tr) => "test postası gönderdi",
926 (ActMessageSent, En) => "sent a message",944 (ActMessageSent, En) => "sent a message",
crates/iz-web/src/logs.rsmodified+3 -2
@@ -186,6 +186,7 @@ pub(crate) fn activity_sentence(kind: &iz_core::detail::ActivityKind, detail: &s
186 ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).to_string(),186 ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).to_string(),
187 ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).to_string(),187 ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).to_string(),
188 ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).to_string(),188 ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).to_string(),
189+ ActivityKind::SecuritySaved => t(lang, Key::ActSecuritySaved).to_string(),
189 ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).to_string(),190 ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).to_string(),
190 ActivityKind::MessageSent => t(lang, Key::ActMessageSent).to_string(),191 ActivityKind::MessageSent => t(lang, Key::ActMessageSent).to_string(),
191 ActivityKind::RoleChanged => crate::i18n::role_changed_label(lang, detail),192 ActivityKind::RoleChanged => crate::i18n::role_changed_label(lang, detail),
@@ -663,7 +664,7 @@ async fn snapshot(
663 event_id: decision.event_id,664 event_id: decision.event_id,
664 task,665 task,
665 happened,666 happened,
666- at: iz_core::detail::moment_label_in(decision.at, zone),667+ at: iz_core::detail::moment_label_with_seconds_in(decision.at, zone),
667 verdicts: vec![verdict],668 verdicts: vec![verdict],
668 });669 });
669 }670 }
@@ -698,7 +699,7 @@ async fn snapshot(
698 let activity = raw_activity699 let activity = raw_activity
699 .into_iter()700 .into_iter()
700 .map(|line| ActivityRow {701 .map(|line| ActivityRow {
701- at: iz_core::detail::moment_label_in(line.at, zone),702+ at: iz_core::detail::moment_label_with_seconds_in(line.at, zone),
702 actor: line703 actor: line
703 .actor_name704 .actor_name
704 .unwrap_or_else(|| t(lang, Key::TheSystem).to_string()),705 .unwrap_or_else(|| t(lang, Key::TheSystem).to_string()),
crates/iz-web/src/people.rsmodified+1 -0
@@ -46,6 +46,7 @@ fn kind_word(lang: Lang, kind: &ActivityKind) -> String {
46 ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).into(),46 ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).into(),
47 ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).into(),47 ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).into(),
48 ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).into(),48 ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).into(),
49+ ActivityKind::SecuritySaved => t(lang, Key::ActSecuritySaved).into(),
49 ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).into(),50 ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).into(),
50 ActivityKind::MessageSent => t(lang, Key::ActMessageSent).into(),51 ActivityKind::MessageSent => t(lang, Key::ActMessageSent).into(),
51 ActivityKind::Other(raw) if raw == "password_reset_requested" => {52 ActivityKind::Other(raw) if raw == "password_reset_requested" => {
crates/iz-web/src/server.rsmodified+10 -0
@@ -384,6 +384,10 @@ pub enum Refusal {
384 EmptyName,384 EmptyName,
385 /// A limit of nothing, or a limit wider than the disk should promise.385 /// A limit of nothing, or a limit wider than the disk should promise.
386 BadLimit,386 BadLimit,
387+ /// A security number below its floor or past its ceiling. Not `BadLimit`:
388+ /// that sentence is about megabytes, and these knobs are counts, minutes
389+ /// and days.
390+ BadPolicy,
387 /// The timezone field was not one of the offsets the form offers.391 /// The timezone field was not one of the offsets the form offers.
388 BadZone,392 BadZone,
389 /// The theme field was not one of the values the form offers.393 /// The theme field was not one of the values the form offers.
@@ -466,6 +470,7 @@ impl Refusal {
466 "A limit has to be at least 1 MB, and no wider than 500 MB per file or 20 MB per photo."470 "A limit has to be at least 1 MB, and no wider than 500 MB per file or 20 MB per photo."
467 .to_string()471 .to_string()
468 }472 }
473+ Refusal::BadPolicy => "A security number is out of range.".to_string(),
469 Refusal::BadZone => "That is not a timezone.".to_string(),474 Refusal::BadZone => "That is not a timezone.".to_string(),
470 Refusal::BadTheme => "That is not a theme.".to_string(),475 Refusal::BadTheme => "That is not a theme.".to_string(),
471 Refusal::BadUi => "That is not an interface.".to_string(),476 Refusal::BadUi => "That is not an interface.".to_string(),
@@ -531,6 +536,7 @@ impl Refusal {
531 "Limit en az 1 MB, dosya başına en çok 500 MB, fotoğraf başına en çok 20 MB olabilir."536 "Limit en az 1 MB, dosya başına en çok 500 MB, fotoğraf başına en çok 20 MB olabilir."
532 .to_string()537 .to_string()
533 }538 }
539+ Refusal::BadPolicy => "Güvenlik sayısı aralığın dışında.".to_string(),
534 Refusal::BadZone => "Bu bir saat dilimi değil.".to_string(),540 Refusal::BadZone => "Bu bir saat dilimi değil.".to_string(),
535 Refusal::BadTheme => "Bu bir tema değil.".to_string(),541 Refusal::BadTheme => "Bu bir tema değil.".to_string(),
536 Refusal::BadUi => "Bu bir arayüz değil.".to_string(),542 Refusal::BadUi => "Bu bir arayüz değil.".to_string(),
@@ -583,6 +589,7 @@ impl Refusal {
583 "empty-title" => Refusal::EmptyTitle,589 "empty-title" => Refusal::EmptyTitle,
584 "empty-name" => Refusal::EmptyName,590 "empty-name" => Refusal::EmptyName,
585 "bad-limit" => Refusal::BadLimit,591 "bad-limit" => Refusal::BadLimit,
592+ "bad-policy" => Refusal::BadPolicy,
586 "bad-zone" => Refusal::BadZone,593 "bad-zone" => Refusal::BadZone,
587 "bad-theme" => Refusal::BadTheme,594 "bad-theme" => Refusal::BadTheme,
588 "bad-ui" => Refusal::BadUi,595 "bad-ui" => Refusal::BadUi,
@@ -640,6 +647,7 @@ impl Refusal {
640 Refusal::EmptyTitle => "empty-title",647 Refusal::EmptyTitle => "empty-title",
641 Refusal::EmptyName => "empty-name",648 Refusal::EmptyName => "empty-name",
642 Refusal::BadLimit => "bad-limit",649 Refusal::BadLimit => "bad-limit",
650+ Refusal::BadPolicy => "bad-policy",
643 Refusal::BadZone => "bad-zone",651 Refusal::BadZone => "bad-zone",
644 Refusal::BadTheme => "bad-theme",652 Refusal::BadTheme => "bad-theme",
645 Refusal::BadUi => "bad-ui",653 Refusal::BadUi => "bad-ui",
@@ -1011,6 +1019,8 @@ mod refusal_message_tests {
1011 Refusal::NotFound,1019 Refusal::NotFound,
1012 Refusal::NoSuchMember,1020 Refusal::NoSuchMember,
1013 Refusal::TagInUse,1021 Refusal::TagInUse,
1022+ Refusal::BadLimit,
1023+ Refusal::BadPolicy,
1014 Refusal::Unavailable,1024 Refusal::Unavailable,
1015 ];1025 ];
1016 for refusal in all {1026 for refusal in all {
crates/iz-web/src/settings.rsmodified+177 -1
@@ -44,6 +44,19 @@ pub const WIDEST_PHOTO_MB: u64 = 20;
44 /// workflow. Two hours is already far past the point where a mail is news.44 /// workflow. Two hours is already far past the point where a mail is news.
45 pub const LONGEST_BATCH_MINUTES: u32 = 120;45 pub const LONGEST_BATCH_MINUTES: u32 = 120;
46 46
47+/// The security knobs' bounds, in the `WIDEST_*` spirit: a floor beneath
48+/// which the knob stops meaning anything and a ceiling past which it stops
49+/// being a policy and becomes a wish.
50+///
51+/// A hundred guesses a window is already a flood for a board a few people
52+/// share; a window past a day is a ban wearing a rate limit's name; a cookie
53+/// that outlives a year is not a session any more; a link that waits three
54+/// months is stale news, and resending mints another.
55+pub const WIDEST_RATE_LIMIT_ATTEMPTS: u64 = 100;
56+pub const LONGEST_RATE_WINDOW_MINUTES: u32 = 24 * 60;
57+pub const LONGEST_SESSION_DAYS: u32 = 365;
58+pub const LONGEST_LINK_DAYS: u32 = 90;
59+
47 const MB: u64 = 1024 * 1024;60 const MB: u64 = 1024 * 1024;
48 61
49 /// `1.2 s` for anything over a second, `840 ms` below it. A mail server that62 /// `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 {
193 match call {206 match call {
194 "save_sender" | "send_test_mail" | "check_sender" => "outgoing",207 "save_sender" | "send_test_mail" | "check_sender" => "outgoing",
195 "save_limits" => "limits",208 "save_limits" => "limits",
209+ "save_security" => "security",
196 "invite_member" | "set_role" | "resend_link" => "members",210 "invite_member" | "set_role" | "resend_link" => "members",
197 "send_message" => "message",211 "send_message" => "message",
198 _ => "profile",212 _ => "profile",
@@ -360,6 +374,70 @@ async fn save_limits(
360 Ok(saved_or_refused("save_limits", refusal))374 Ok(saved_or_refused("save_limits", refusal))
361 }375 }
362 376
377+#[derive(serde::Deserialize)]
378+struct SaveSecurityForm {
379+ rate_limit_attempts: u64,
380+ rate_window_minutes: u32,
381+ session_lifetime_days: u32,
382+ signin_link_lifetime_days: u32,
383+}
384+
385+/// Writes the workspace's four security knobs. Admin-only, checked here.
386+///
387+/// The bounds are the form's `min`/`max` backed by this check, because the
388+/// form is a courtesy and this is the guard: a posted 0 would turn the rate
389+/// limit off outright and a pasted 100000 would turn it into a decoration.
390+#[route(POST "/api/save_security")]
391+async fn save_security(
392+ cx: &Cx,
393+ Form(input): Form<SaveSecurityForm>,
394+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
395+ let admin = match require_admin(cx).await {
396+ Ok(admin) => admin,
397+ Err(refusal) => return Ok(saved_or_refused("save_security", Some(refusal))),
398+ };
399+ if input.rate_limit_attempts == 0
400+ || input.rate_window_minutes == 0
401+ || input.session_lifetime_days == 0
402+ || input.signin_link_lifetime_days == 0
403+ || input.rate_limit_attempts > WIDEST_RATE_LIMIT_ATTEMPTS
404+ || input.rate_window_minutes > LONGEST_RATE_WINDOW_MINUTES
405+ || input.session_lifetime_days > LONGEST_SESSION_DAYS
406+ || input.signin_link_lifetime_days > LONGEST_LINK_DAYS
407+ {
408+ return Ok(saved_or_refused("save_security", Some(Refusal::BadPolicy)));
409+ }
410+ let outcome = accounts(cx)
411+ .store()
412+ .set_security(
413+ &admin.workspace_id,
414+ input.rate_limit_attempts,
415+ input.rate_window_minutes,
416+ input.session_lifetime_days,
417+ input.signin_link_lifetime_days,
418+ )
419+ .await;
420+ let refusal = match outcome {
421+ Ok(()) => {
422+ let _ = accounts(cx)
423+ .store()
424+ .record_event(
425+ Some(&admin.id),
426+ &ActivityKind::SecuritySaved,
427+ "",
428+ time::OffsetDateTime::now_utc(),
429+ )
430+ .await;
431+ None
432+ }
433+ Err(problem) => {
434+ eprintln!("store error: {problem}");
435+ Some(Refusal::Unavailable)
436+ }
437+ };
438+ Ok(saved_or_refused("save_security", refusal))
439+}
440+
363 #[derive(serde::Deserialize)]441 #[derive(serde::Deserialize)]
364 struct SaveSenderForm {442 struct SaveSenderForm {
365 host: String,443 host: String,
@@ -974,6 +1052,22 @@ async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String
974 ))1052 ))
975 }1053 }
976 1054
1055+/// The security knobs as the admin's screen shows them.
1056+async fn security_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u32, u32, u32)> {
1057+ let workspace = accounts(cx)
1058+ .store()
1059+ .workspace()
1060+ .await?
1061+ .filter(|workspace| workspace.id == workspace_id)
1062+ .ok_or_else(|| topcoat::Error::from(std::io::Error::other("no workspace")))?;
1063+ Ok((
1064+ workspace.rate_limit_attempts,
1065+ workspace.rate_window_minutes,
1066+ workspace.session_lifetime_days,
1067+ workspace.signin_link_lifetime_days,
1068+ ))
1069+}
1070+
977 /// What the row under the test button says, once the workspace holds a1071 /// What the row under the test button says, once the workspace holds a
978 /// `sender_test` to read.1072 /// `sender_test` to read.
979 struct TestResult {1073 struct TestResult {
@@ -1169,6 +1263,7 @@ enum Section {
1169 Profile,1263 Profile,
1170 Outgoing,1264 Outgoing,
1171 Limits,1265 Limits,
1266+ Security,
1172 Members,1267 Members,
1173 Message,1268 Message,
1174 }1269 }
@@ -1205,6 +1300,7 @@ async fn settings_page(cx: &Cx) -> Result {
1205 let section = match query_value(query, "section") {1300 let section = match query_value(query, "section") {
1206 Some("outgoing") if administers => Section::Outgoing,1301 Some("outgoing") if administers => Section::Outgoing,
1207 Some("limits") if administers => Section::Limits,1302 Some("limits") if administers => Section::Limits,
1303+ Some("security") if administers => Section::Security,
1208 Some("members") if administers => Section::Members,1304 Some("members") if administers => Section::Members,
1209 Some("message") if administers => Section::Message,1305 Some("message") if administers => Section::Message,
1210 _ => Section::Profile,1306 _ => Section::Profile,
@@ -1225,6 +1321,11 @@ async fn settings_page(cx: &Cx) -> Result {
1225 } else {1321 } else {
1226 (None, Vec::new())1322 (None, Vec::new())
1227 };1323 };
1324+ let security = if administers {
1325+ Some(security_now(cx, &user.workspace_id).await?)
1326+ } else {
1327+ None
1328+ };
1228 let members = if administers {1329 let members = if administers {
1229 Some(members_now(cx, &user).await?)1330 Some(members_now(cx, &user).await?)
1230 } else {1331 } else {
@@ -1238,6 +1339,7 @@ async fn settings_page(cx: &Cx) -> Result {
1238 let (sender_refusal, sender_saved) = call_state(query, "save_sender");1339 let (sender_refusal, sender_saved) = call_state(query, "save_sender");
1239 let (test_refusal, _) = call_state(query, "send_test_mail");1340 let (test_refusal, _) = call_state(query, "send_test_mail");
1240 let (limits_refusal, limits_saved) = call_state(query, "save_limits");1341 let (limits_refusal, limits_saved) = call_state(query, "save_limits");
1342+ let (security_refusal, security_saved) = call_state(query, "save_security");
1241 let (resend_refusal, _) = call_state(query, "resend_link");1343 let (resend_refusal, _) = call_state(query, "resend_link");
1242 let (invite_refusal, _) = call_state(query, "invite_member");1344 let (invite_refusal, _) = call_state(query, "invite_member");
1243 let (role_refusal, _) = call_state(query, "set_role");1345 let (role_refusal, _) = call_state(query, "set_role");
@@ -1261,7 +1363,7 @@ async fn settings_page(cx: &Cx) -> Result {
1261 if administers {1363 if administers {
1262 <a class=(rail_class(section, Section::Outgoing)) href="/settings?section=outgoing">(t(lang, Key::OutgoingMail))</a>1364 <a class=(rail_class(section, Section::Outgoing)) href="/settings?section=outgoing">(t(lang, Key::OutgoingMail))</a>
1263 <a class=(rail_class(section, Section::Limits)) href="/settings?section=limits">(t(lang, Key::WorkspaceLimits))</a>1365 <a class=(rail_class(section, Section::Limits)) href="/settings?section=limits">(t(lang, Key::WorkspaceLimits))</a>
1264- <a class=(rail_class(section, Section::Members)) href="/settings?section=members">(t(lang, Key::Members))</a>1366+ <a class=(rail_class(section, Section::Security)) href="/settings?section=security">(t(lang, Key::Security))</a>
1265 <a class=(rail_class(section, Section::Message)) href="/settings?section=message">(t(lang, Key::Message))</a>1367 <a class=(rail_class(section, Section::Message)) href="/settings?section=message">(t(lang, Key::Message))</a>
1266 }1368 }
1267 </nav>1369 </nav>
@@ -1610,6 +1712,80 @@ async fn settings_page(cx: &Cx) -> Result {
1610 </section>1712 </section>
1611 }1713 }
1612 1714
1715+ if section == Section::Security
1716+ && let Some((rate_limit_attempts, rate_window_minutes, session_lifetime_days, signin_link_lifetime_days)) = security
1717+ {
1718+ <section class="panel" id="security">
1719+ <div class="panel-head">
1720+ <h2 class="panel-title">(t(lang, Key::Security))</h2>
1721+ <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
1722+ </div>
1723+ <form method="post" action="/api/save_security" class="panel-body">
1724+ <div class="field-row">
1725+ <label class="field">
1726+ <span class="field-label">(t(lang, Key::RateLimitAttemptsLabel))</span>
1727+ <input
1728+ class="field-input"
1729+ type="number"
1730+ name="rate_limit_attempts"
1731+ min="1"
1732+ max=(WIDEST_RATE_LIMIT_ATTEMPTS.to_string())
1733+ value=(rate_limit_attempts.to_string())
1734+ required=""
1735+ >
1736+ </label>
1737+ <label class="field">
1738+ <span class="field-label">(t(lang, Key::RateWindowLabel))</span>
1739+ <input
1740+ class="field-input"
1741+ type="number"
1742+ name="rate_window_minutes"
1743+ min="1"
1744+ max=(LONGEST_RATE_WINDOW_MINUTES.to_string())
1745+ value=(rate_window_minutes.to_string())
1746+ required=""
1747+ >
1748+ </label>
1749+ </div>
1750+ <div class="field-row">
1751+ <label class="field">
1752+ <span class="field-label">(t(lang, Key::SessionLifetimeLabel))</span>
1753+ <input
1754+ class="field-input"
1755+ type="number"
1756+ name="session_lifetime_days"
1757+ min="1"
1758+ max=(LONGEST_SESSION_DAYS.to_string())
1759+ value=(session_lifetime_days.to_string())
1760+ required=""
1761+ >
1762+ </label>
1763+ <label class="field">
1764+ <span class="field-label">(t(lang, Key::LinkLifetimeLabel))</span>
1765+ <input
1766+ class="field-input"
1767+ type="number"
1768+ name="signin_link_lifetime_days"
1769+ min="1"
1770+ max=(LONGEST_LINK_DAYS.to_string())
1771+ value=(signin_link_lifetime_days.to_string())
1772+ required=""
1773+ >
1774+ </label>
1775+ </div>
1776+ <div class="panel-foot">
1777+ if let Some(refusal) = &security_refusal {
1778+ <span class="field-error">(refusal.message_in(lang))</span>
1779+ }
1780+ if security_saved {
1781+ <span class="field-note">(t(lang, Key::Saved))</span>
1782+ }
1783+ <button class="primary" type="submit">(t(lang, Key::Save))</button>
1784+ </div>
1785+ </form>
1786+ </section>
1787+ }
1788+
1613 if section == Section::Members && let Some(members) = &members {1789 if section == Section::Members && let Some(members) = &members {
1614 <section class="panel" id="members">1790 <section class="panel" id="members">
1615 <div class="panel-head">1791 <div class="panel-head">
crates/iz-web/tests/http.rsmodified+190 -15
@@ -2617,6 +2617,161 @@ async fn a_limit_outside_what_the_disk_should_promise_is_refused() {
2617 }2617 }
2618 }2618 }
2619 2619
2620+/// The security section, end to end: an admin sees the rail link and the
2621+/// panel, a member sees neither — including by asking for the section by URL
2622+/// — a member's post to the save endpoint is refused by the handler, an
2623+/// out-of-range number is refused by name and stores nothing, and a save in
2624+/// range lands in the row and renders back into the fields.
2625+#[tokio::test]
2626+async fn the_security_section_is_admin_only_and_round_trips() {
2627+ let app = App::open().await;
2628+ let admin_cookie = admin(&app).await;
2629+ let member = invited(&app, &admin_cookie, "deniz@iz.sh", "Deniz", Role::Member).await;
2630+
2631+ // The admin gets the rail link, the panel and the defaults in the fields.
2632+ let page = app
2633+ .get("/settings?section=security", Some(&admin_cookie))
2634+ .await;
2635+ assert_eq!(page.status, StatusCode::OK);
2636+ let html = String::from_utf8_lossy(&page.bytes);
2637+ assert!(
2638+ html.contains(r#"href="/settings?section=security""#),
2639+ "{html}"
2640+ );
2641+ assert!(html.contains(r#"id="security""#), "{html}");
2642+ assert!(
2643+ html.contains(r#"name="rate_limit_attempts""#)
2644+ && html.contains(r#"name="rate_window_minutes""#)
2645+ && html.contains(r#"name="session_lifetime_days""#)
2646+ && html.contains(r#"name="signin_link_lifetime_days""#),
2647+ "{html}"
2648+ );
2649+
2650+ // The member gets neither the link nor the panel, by link or by URL.
2651+ let page = app.get("/settings", Some(&member)).await;
2652+ let html = String::from_utf8_lossy(&page.bytes);
2653+ assert!(
2654+ !html.contains(r#"href="/settings?section=security""#),
2655+ "{html}"
2656+ );
2657+ assert!(!html.contains(r#"id="security""#), "{html}");
2658+ let page = app
2659+ .get("/settings?section=security", Some(&member))
2660+ .await;
2661+ let html = String::from_utf8_lossy(&page.bytes);
2662+ assert!(html.contains(r#"id="profile""#), "{html}");
2663+ assert!(!html.contains(r#"id="security""#), "{html}");
2664+
2665+ // And the member's post is refused by the handler, not the markup.
2666+ let answer = app
2667+ .post(
2668+ "/api/save_security",
2669+ Some(&member),
2670+ &[
2671+ ("rate_limit_attempts", "3"),
2672+ ("rate_window_minutes", "15"),
2673+ ("session_lifetime_days", "14"),
2674+ ("signin_link_lifetime_days", "7"),
2675+ ],
2676+ )
2677+ .await;
2678+ assert!(
2679+ answer
2680+ .location
2681+ .as_deref()
2682+ .unwrap_or_default()
2683+ .contains("refusal=forbidden&on=save_security"),
2684+ "{:?}",
2685+ answer.location
2686+ );
2687+
2688+ // An out-of-range knob is refused by name, each bound in turn.
2689+ for (attempts, window, session, link) in [
2690+ ("0", "15", "14", "7"),
2691+ ("10", "0", "14", "7"),
2692+ ("10", "15", "0", "7"),
2693+ ("10", "15", "14", "0"),
2694+ ("101", "15", "14", "7"),
2695+ ("10", "1441", "14", "7"),
2696+ ("10", "15", "366", "7"),
2697+ ("10", "15", "14", "91"),
2698+ ] {
2699+ let answer = app
2700+ .post(
2701+ "/api/save_security",
2702+ Some(&admin_cookie),
2703+ &[
2704+ ("rate_limit_attempts", attempts),
2705+ ("rate_window_minutes", window),
2706+ ("session_lifetime_days", session),
2707+ ("signin_link_lifetime_days", link),
2708+ ],
2709+ )
2710+ .await;
2711+ let location = answer.location.as_deref().unwrap_or_default();
2712+ assert!(
2713+ location.contains("refusal=bad-policy&on=save_security"),
2714+ "{attempts}/{window}/{session}/{link}: {location}"
2715+ );
2716+ }
2717+ let workspace = app.store.workspace().await.unwrap().unwrap();
2718+ assert_eq!(
2719+ workspace.rate_limit_attempts, 10,
2720+ "a refused save still changed the row"
2721+ );
2722+
2723+ // A save in range lands on the section with its saved note, the row
2724+ // agrees, and the fields render the saved values back.
2725+ let answer = app
2726+ .post(
2727+ "/api/save_security",
2728+ Some(&admin_cookie),
2729+ &[
2730+ ("rate_limit_attempts", "3"),
2731+ ("rate_window_minutes", "60"),
2732+ ("session_lifetime_days", "30"),
2733+ ("signin_link_lifetime_days", "2"),
2734+ ],
2735+ )
2736+ .await;
2737+ assert!(
2738+ answer
2739+ .location
2740+ .as_deref()
2741+ .unwrap_or_default()
2742+ .contains("saved=save_security"),
2743+ "{:?}",
2744+ answer.location
2745+ );
2746+ let workspace = app.store.workspace().await.unwrap().unwrap();
2747+ assert_eq!(workspace.rate_limit_attempts, 3);
2748+ assert_eq!(workspace.rate_window_minutes, 60);
2749+ assert_eq!(workspace.session_lifetime_days, 30);
2750+ assert_eq!(workspace.signin_link_lifetime_days, 2);
2751+
2752+ let page = app
2753+ .get("/settings?section=security", Some(&admin_cookie))
2754+ .await;
2755+ let html = String::from_utf8_lossy(&page.bytes);
2756+ for field in [
2757+ r#"name="rate_limit_attempts"#,
2758+ r#"name="rate_window_minutes"#,
2759+ r#"name="session_lifetime_days"#,
2760+ r#"name="signin_link_lifetime_days"#,
2761+ ] {
2762+ let at = html.find(field).expect("the field vanished");
2763+ let value = &html[at..];
2764+ assert!(
2765+ value.contains("value=\"3\"")
2766+ || value.contains("value=\"60\"")
2767+ || value.contains("value=\"30\"")
2768+ || value.contains("value=\"2\""),
2769+ "field {field} does not render its saved value: {}",
2770+ &value[..value.len().min(200)]
2771+ );
2772+ }
2773+}
2774+
2620 #[tokio::test]2775 #[tokio::test]
2621 async fn a_file_type_that_is_not_an_extension_is_refused() {2776 async fn a_file_type_that_is_not_an_extension_is_refused() {
2622 let app = App::open().await;2777 let app = App::open().await;
@@ -4637,7 +4792,7 @@ fn moment_for(body: &str, title: &str) -> String {
4637 .to_string()4792 .to_string()
4638 }4793 }
4639 4794
4640-/// The hour out of a `moment_label`-shaped stamp like `"Aug 19 11:04"`.4795+/// The hour out of a `moment_label`-shaped stamp like `"Aug 19 11:04:07"`.
4641 fn hour_of(moment: &str) -> u32 {4796 fn hour_of(moment: &str) -> u32 {
4642 moment4797 moment
4643 .rsplit(' ')4798 .rsplit(' ')
@@ -9672,22 +9827,32 @@ async fn the_board_search_filters_and_composes_with_the_project_filter() {
9672 // and the redeem flow over the mailed link.9827 // and the redeem flow over the mailed link.
9673 // ---------------------------------------------------------------------------9828 // ---------------------------------------------------------------------------
9674 9829
9675-/// The reset token out of the newest notice queued for the address — the mail9830+/// Every reset token queued for the address, oldest first. The newest ask
9676-/// is the token's only carrier, so the test reads it like a recipient would.9831+/// retires the earlier links, so a test that asks twice needs both.
9677-async fn queued_reset_token(app: &App, email: &str) -> Option<String> {9832+async fn queued_reset_tokens(app: &App, email: &str) -> Vec<String> {
9678 let sends = app9833 let sends = app
9679 .store9834 .store
9680 .mail_queue(50, iz_core::store::FeedPage::Newest)9835 .mail_queue(50, iz_core::store::FeedPage::Newest)
9681 .await9836 .await
9682 .unwrap();9837 .unwrap();
9683- let body = sends9838+ let mut tokens = Vec::new();
9684- .into_iter()9839+ for send in sends {
9685- .rev()9840+ if send.kind != SendKind::Notice || send.recipient != email {
9686- .find(|send| send.kind == SendKind::Notice && send.recipient == email)9841+ continue;
9687- .and_then(|send| send.body)?;9842+ }
9688- body.rsplit_once("/reset/")9843+ let Some(body) = send.body else { continue };
9689- .and_then(|(_, rest)| rest.split_whitespace().next())9844+ let Some((_, rest)) = body.rsplit_once("/reset/") else { continue };
9690- .map(str::to_string)9845+ if let Some(token) = rest.split_whitespace().next() {
9846+ tokens.push(token.to_string());
9847+ }
9848+ }
9849+ tokens
9850+}
9851+
9852+/// The reset token out of the newest notice queued for the address — the mail
9853+/// is the token's only carrier, so the test reads it like a recipient would.
9854+async fn queued_reset_token(app: &App, email: &str) -> Option<String> {
9855+ queued_reset_tokens(app, email).await.pop()
9691 }9856 }
9692 9857
9693 #[tokio::test]9858 #[tokio::test]
@@ -9733,9 +9898,19 @@ async fn a_reset_link_redeems_on_its_own_screen() {
9733 let _admin = admin(&app).await;9898 let _admin = admin(&app).await;
9734 app.post("/api/forgot_password", None, &[("email", "ada@iz.sh")])9899 app.post("/api/forgot_password", None, &[("email", "ada@iz.sh")])
9735 .await;9900 .await;
9736- let token = queued_reset_token(&app, "ada@iz.sh")9901+ // A second ask retires the first link: the newest mail carries the only
9737- .await9902+ // working token, and the retired one is dead before the newer is
9738- .expect("no reset mail queued");9903+ // redeemed.
9904+ app.post("/api/forgot_password", None, &[("email", "ada@iz.sh")])
9905+ .await;
9906+ let mut resets = queued_reset_tokens(&app, "ada@iz.sh").await;
9907+ assert_eq!(resets.len(), 2, "each ask queued its own mail");
9908+ let retired = resets.remove(0);
9909+ let token = resets.remove(0);
9910+ let page = app.get(&format!("/reset/{retired}"), None).await;
9911+ let html = String::from_utf8_lossy(&page.bytes);
9912+ assert!(html.contains("no longer works"), "{html}");
9913+ assert!(!html.contains("Choose a new password"), "{html}");
9739 9914
9740 // The mailed link opens the choose-password card, naming the address it9915 // The mailed link opens the choose-password card, naming the address it
9741 // was mailed to.9916 // was mailed to.