forge
Explore
Log in

Don't you dare go Hollow

Accounts: setup, sign-in, 2FA with recovery codes, sessions, throttle, audit

Browse files at this commit

fb1f5245cd61e93961c8b25c6b9ca7c81b2de509Ahmet Kaan GümüşParent: 84d70dc
  • feat
    • accounts: setup, sign-in, 2FA with recovery codes, sessions, throttle, audit
Show full message
✨ feat: accounts: setup, sign-in, 2FA with recovery codes, sessions, throttle, audit
Cargo.lockmodified+34 -3
@@ -608,7 +608,7 @@ dependencies = [
608 "aes-gcm",608 "aes-gcm",
609 "base64 0.22.1",609 "base64 0.22.1",
610 "hkdf",610 "hkdf",
611- "hmac",611+ "hmac 0.12.1",
612 "percent-encoding",612 "percent-encoding",
613 "rand 0.8.8",613 "rand 0.8.8",
614 "sha2 0.10.9",614 "sha2 0.10.9",
@@ -1306,7 +1306,7 @@ version = "0.12.4"
1306 source = "registry+https://github.com/rust-lang/crates.io-index"1306 source = "registry+https://github.com/rust-lang/crates.io-index"
1307 checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"1307 checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
1308 dependencies = [1308 dependencies = [
1309- "hmac",1309+ "hmac 0.12.1",
1310 ]1310 ]
1311 1311
1312 [[package]]1312 [[package]]
@@ -1318,6 +1318,15 @@ dependencies = [
1318 "digest 0.10.7",1318 "digest 0.10.7",
1319 ]1319 ]
1320 1320
1321+[[package]]
1322+name = "hmac"
1323+version = "0.13.0"
1324+source = "registry+https://github.com/rust-lang/crates.io-index"
1325+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
1326+dependencies = [
1327+ "digest 0.11.3",
1328+]
1329+
1321 [[package]]1330 [[package]]
1322 name = "home"1331 name = "home"
1323 version = "0.5.12"1332 version = "0.5.12"
@@ -1648,10 +1657,12 @@ dependencies = [
1648 "chacha20poly1305",1657 "chacha20poly1305",
1649 "ed25519-dalek",1658 "ed25519-dalek",
1650 "hex",1659 "hex",
1660+ "hmac 0.13.0",
1651 "ipnet",1661 "ipnet",
1652 "rand 0.10.3",1662 "rand 0.10.3",
1653 "serde",1663 "serde",
1654 "serde_json",1664 "serde_json",
1665+ "sha1 0.11.0",
1655 "sha2 0.11.1",1666 "sha2 0.11.1",
1656 "subtle",1667 "subtle",
1657 "tempfile",1668 "tempfile",
@@ -1668,12 +1679,15 @@ dependencies = [
1668 name = "im-web"1679 name = "im-web"
1669 version = "0.1.0"1680 version = "0.1.0"
1670 dependencies = [1681 dependencies = [
1682+ "base64 0.23.1",
1671 "futures-util",1683 "futures-util",
1672 "grass",1684 "grass",
1673 "hex",1685 "hex",
1674 "http",1686 "http",
1675 "im-core",1687 "im-core",
1688+ "qrcode",
1676 "serde",1689 "serde",
1690+ "serde_json",
1677 "sha2 0.11.1",1691 "sha2 0.11.1",
1678 "tempfile",1692 "tempfile",
1679 "tokio",1693 "tokio",
@@ -2435,6 +2449,12 @@ dependencies = [
2435 "syn 2.0.119",2449 "syn 2.0.119",
2436 ]2450 ]
2437 2451
2452+[[package]]
2453+name = "qrcode"
2454+version = "0.14.1"
2455+source = "registry+https://github.com/rust-lang/crates.io-index"
2456+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
2457+
2438 [[package]]2458 [[package]]
2439 name = "quote"2459 name = "quote"
2440 version = "1.0.47"2460 version = "1.0.47"
@@ -2833,6 +2853,17 @@ dependencies = [
2833 "digest 0.10.7",2853 "digest 0.10.7",
2834 ]2854 ]
2835 2855
2856+[[package]]
2857+name = "sha1"
2858+version = "0.11.0"
2859+source = "registry+https://github.com/rust-lang/crates.io-index"
2860+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
2861+dependencies = [
2862+ "cfg-if",
2863+ "cpufeatures 0.3.1",
2864+ "digest 0.11.3",
2865+]
2866+
2836 [[package]]2867 [[package]]
2837 name = "sha1_smol"2868 name = "sha1_smol"
2838 version = "1.0.1"2869 version = "1.0.1"
@@ -3821,7 +3852,7 @@ dependencies = [
3821 "httparse",3852 "httparse",
3822 "log",3853 "log",
3823 "rand 0.9.5",3854 "rand 0.9.5",
3824- "sha1",3855+ "sha1 0.10.7",
3825 "thiserror",3856 "thiserror",
3826 ]3857 ]
3827 3858
Cargo.tomlmodified+3 -0
@@ -18,11 +18,14 @@ ed25519-dalek = { version = "3.0.0", features = ["rand_core"] }
18 futures-util = "0.3.34"18 futures-util = "0.3.34"
19 grass = "0.13.4"19 grass = "0.13.4"
20 hex = "0.4.3"20 hex = "0.4.3"
21+hmac = "0.13.0"
21 http = "1.5.0"22 http = "1.5.0"
22 ipnet = "2.12.2"23 ipnet = "2.12.2"
24+qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }
23 rand = "0.10.3"25 rand = "0.10.3"
24 serde = { version = "1.0.229", features = ["derive"] }26 serde = { version = "1.0.229", features = ["derive"] }
25 serde_json = "1.0.154"27 serde_json = "1.0.154"
28+sha1 = "0.11.0"
26 sha2 = "0.11.1"29 sha2 = "0.11.1"
27 subtle = "2.6.1"30 subtle = "2.6.1"
28 thiserror = "2.0.21"31 thiserror = "2.0.21"
config/im.example.tomlmodified+6 -0
@@ -31,3 +31,9 @@ interval_hours = 24
31 keep = 731 keep = 7
32 # Dead-man URL pinged after each run. Empty for none.32 # Dead-man URL pinged after each run. Empty for none.
33 healthcheck_url = ""33 healthcheck_url = ""
34+
35+[policy]
36+# An administrator without two-factor sign-in is sent to enrol it after signing in.
37+require_2fa_for_admins = true
38+# Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it.
39+max_sessions = 10
crates/im-core/Cargo.tomlmodified+2 -0
@@ -14,10 +14,12 @@ base64.workspace = true
14 chacha20poly1305.workspace = true14 chacha20poly1305.workspace = true
15 ed25519-dalek.workspace = true15 ed25519-dalek.workspace = true
16 hex.workspace = true16 hex.workspace = true
17+hmac.workspace = true
17 ipnet.workspace = true18 ipnet.workspace = true
18 rand.workspace = true19 rand.workspace = true
19 serde.workspace = true20 serde.workspace = true
20 serde_json.workspace = true21 serde_json.workspace = true
22+sha1.workspace = true
21 sha2.workspace = true23 sha2.workspace = true
22 subtle.workspace = true24 subtle.workspace = true
23 thiserror.workspace = true25 thiserror.workspace = true
crates/im-core/src/config.rsmodified+28 -0
@@ -73,6 +73,28 @@ impl BackupConfig {
73 }73 }
74 }74 }
75 75
76+/// Sign-in policy. These are the file values; a value saved in the admin UI wins over them once that
77+/// UI exists (`docs/architecture.md` section 7).
78+#[derive(Debug, Clone, Deserialize)]
79+#[serde(deny_unknown_fields, default)]
80+pub struct PolicyConfig {
81+ /// An administrator without two-factor sign-in is sent to enrol it after signing in, and cannot
82+ /// reach the admin pages until they do.
83+ pub require_2fa_for_admins: bool,
84+ /// Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it.
85+ /// At least 1.
86+ pub max_sessions: u32,
87+}
88+
89+impl Default for PolicyConfig {
90+ fn default() -> Self {
91+ Self {
92+ require_2fa_for_admins: true,
93+ max_sessions: 10,
94+ }
95+ }
96+}
97+
76 /// The whole file. Field names are the TOML keys.98 /// The whole file. Field names are the TOML keys.
77 #[derive(Debug, Clone, Deserialize)]99 #[derive(Debug, Clone, Deserialize)]
78 #[serde(deny_unknown_fields)]100 #[serde(deny_unknown_fields)]
@@ -96,6 +118,9 @@ pub struct Config {
96 /// Scheduled backups.118 /// Scheduled backups.
97 #[serde(default)]119 #[serde(default)]
98 pub backup: BackupConfig,120 pub backup: BackupConfig,
121+ /// Sign-in policy.
122+ #[serde(default)]
123+ pub policy: PolicyConfig,
99 }124 }
100 125
101 impl Config {126 impl Config {
@@ -144,6 +169,9 @@ impl Config {
144 return Err(Error::Config("[backup] keep must be at least 1".into()));169 return Err(Error::Config("[backup] keep must be at least 1".into()));
145 }170 }
146 }171 }
172+ if self.policy.max_sessions == 0 {
173+ return Err(Error::Config("[policy] max_sessions must be at least 1".into()));
174+ }
147 let hc = &self.backup.healthcheck_url;175 let hc = &self.backup.healthcheck_url;
148 if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) {176 if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) {
149 return Err(Error::Config(177 return Err(Error::Config(
crates/im-core/src/lib.rsmodified+3 -0
@@ -5,10 +5,13 @@
5 5
6 pub mod config;6 pub mod config;
7 pub mod error;7 pub mod error;
8+pub mod model;
9+pub mod names;
8 pub mod password;10 pub mod password;
9 pub mod secret;11 pub mod secret;
10 pub mod store;12 pub mod store;
11 pub mod time;13 pub mod time;
12 pub mod token;14 pub mod token;
15+pub mod totp;
13 16
14 pub use error::{Error, Result};17 pub use error::{Error, Result};
crates/im-core/src/model.rsadded+161 -0
@@ -0,0 +1,161 @@
1+//! Plain data types of the accounts and sessions, as the store returns them.
2+//!
3+//! These structs hold what is in the rows and nothing more. Rules that decide what a person may
4+//! do with them live in the store (as single conditional statements) or in the web layer.
5+//! Timestamps are the stored text form from `time.rs`.
6+
7+/// A person who can sign in. `id` is the OIDC `sub` once OIDC exists, and is never reused.
8+#[derive(Debug, Clone, PartialEq, Eq)]
9+pub struct User {
10+ /// ULID.
11+ pub id: String,
12+ /// The normalised address (trimmed, lowercased). Unique.
13+ pub email: String,
14+ /// Display name, 1 to 100 characters.
15+ pub name: String,
16+ /// Argon2id PHC string.
17+ pub password_hash: String,
18+ /// Instance administrator.
19+ pub is_admin: bool,
20+ /// Set when the account is disabled. A disabled account cannot sign in.
21+ pub disabled_at: Option<String>,
22+ /// The sealed TOTP secret, kept after two-factor sign-in is enabled.
23+ pub totp_secret_sealed: Option<String>,
24+ /// Set when two-factor sign-in is on.
25+ pub totp_enabled_at: Option<String>,
26+ /// The last TOTP step that was accepted. A code of this step or an earlier one is refused.
27+ pub totp_last_step: Option<i64>,
28+ /// `en` or `tr`.
29+ pub locale: String,
30+ /// IANA time zone name.
31+ pub zoneinfo: String,
32+ /// `system`, `light` or `dark`.
33+ pub theme: String,
34+ /// MIME type of the stored photo, when there is one.
35+ pub photo_mime: Option<String>,
36+ /// Bumps when the photo changes, so caches can tell two photos apart.
37+ pub picture_version: i64,
38+ /// Creation time.
39+ pub created_at: String,
40+ /// Last change of the row.
41+ pub updated_at: String,
42+}
43+
44+impl User {
45+ /// True when two-factor sign-in is on: the secret is stored and enrolment was confirmed.
46+ pub fn totp_enabled(&self) -> bool {
47+ self.totp_enabled_at.is_some() && self.totp_secret_sealed.is_some()
48+ }
49+
50+ /// True when the account is disabled.
51+ pub fn is_disabled(&self) -> bool {
52+ self.disabled_at.is_some()
53+ }
54+}
55+
56+/// How a session was authenticated. Stored in `sessions.amr`, and the CHECK constraint accepts
57+/// exactly these three values.
58+pub mod amr {
59+ /// Password only.
60+ pub const PASSWORD: &str = "pwd";
61+ /// Password and a TOTP code.
62+ pub const PASSWORD_TOTP: &str = "pwd otp";
63+ /// Password and a recovery code.
64+ pub const PASSWORD_RECOVERY: &str = "pwd rc";
65+}
66+
67+/// A browser session. The cookie holds the token; the row holds only its hash.
68+#[derive(Debug, Clone, PartialEq, Eq)]
69+pub struct Session {
70+ /// ULID. This is the OIDC `sid` once OIDC exists.
71+ pub id: String,
72+ /// The owner.
73+ pub user_id: String,
74+ /// Hex SHA-256 of the cookie token.
75+ pub token_hash: String,
76+ /// Per-session CSRF token. Every state-changing form carries it.
77+ pub csrf_token: String,
78+ /// Creation time (the sign-in time).
79+ pub created_at: String,
80+ /// Absolute expiry.
81+ pub expires_at: String,
82+ /// Last time the session was used. Written at most once every five minutes.
83+ pub last_seen_at: String,
84+ /// Address the session was created from.
85+ pub ip: Option<String>,
86+ /// The `User-Agent` at sign-in, truncated.
87+ pub user_agent: Option<String>,
88+ /// Time of the authentication that created the session.
89+ pub auth_time: String,
90+ /// One of the [`amr`] values.
91+ pub amr: String,
92+}
93+
94+/// What an audit entry is about. The variants are the values stored in `audit_log.action`.
95+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96+pub enum AuditAction {
97+ /// The first administrator was created.
98+ SetupDone,
99+ /// A sign-in succeeded (password, or password and a second factor).
100+ LoginSuccess,
101+ /// A sign-in was refused. The data says why.
102+ LoginFailed,
103+ /// A second-factor check was refused.
104+ Login2faFailed,
105+ /// The person signed out.
106+ Logout,
107+ /// The password was changed.
108+ PasswordChanged,
109+ /// Two-factor sign-in was turned on.
110+ TotpEnabled,
111+ /// Two-factor sign-in was turned off.
112+ TotpDisabled,
113+ /// A new set of recovery codes was issued.
114+ RecoveryCodesIssued,
115+ /// One session was ended by its owner.
116+ SessionRevoked,
117+ /// Every session except the current one was ended.
118+ SessionsRevoked,
119+}
120+
121+impl AuditAction {
122+ /// The stored text of the action.
123+ pub fn as_str(self) -> &'static str {
124+ match self {
125+ AuditAction::SetupDone => "setup.done",
126+ AuditAction::LoginSuccess => "login.success",
127+ AuditAction::LoginFailed => "login.failed",
128+ AuditAction::Login2faFailed => "login.2fa_failed",
129+ AuditAction::Logout => "logout",
130+ AuditAction::PasswordChanged => "password.changed",
131+ AuditAction::TotpEnabled => "totp.enabled",
132+ AuditAction::TotpDisabled => "totp.disabled",
133+ AuditAction::RecoveryCodesIssued => "recovery.issued",
134+ AuditAction::SessionRevoked => "session.revoked",
135+ AuditAction::SessionsRevoked => "sessions.revoked",
136+ }
137+ }
138+}
139+
140+/// One row of the audit log.
141+#[derive(Debug, Clone, PartialEq, Eq)]
142+pub struct AuditEntry {
143+ /// ULID. Ordered by `(at, id)` together.
144+ pub id: String,
145+ /// When the change was made.
146+ pub at: String,
147+ /// Who acted, when known. Not a foreign key, so the trail outlives the account.
148+ pub actor_id: Option<String>,
149+ /// `user`, `client`, `cli`, `system` or `anonymous`.
150+ pub actor_kind: String,
151+ /// The action, as [`AuditAction::as_str`] or a later kind.
152+ pub action: String,
153+ /// What the action is about, such as `user`.
154+ pub target_kind: Option<String>,
155+ /// The id of that thing.
156+ pub target_id: Option<String>,
157+ /// Client address, when known.
158+ pub ip: Option<String>,
159+ /// JSON with extra detail. Never holds a secret.
160+ pub data: Option<String>,
161+}
crates/im-core/src/names.rsadded+121 -0
@@ -0,0 +1,121 @@
1+//! Email addresses: normalisation and the shape check.
2+//!
3+//! An address has one stored form: trimmed and lowercased. The same string is the `email` and the
4+//! `email_folded` of a user, so lookups are case-insensitive by construction. The shape check
5+//! accepts ASCII only. Look-alike characters from other scripts would otherwise let a second
6+//! account look exactly like the first one.
7+//!
8+//! The check is a sanity check on the text, not proof that the address exists or receives mail.
9+
10+use crate::error::{Error, Result};
11+
12+/// Longest address accepted, in bytes (RFC 5321 path limit).
13+pub const MAX_EMAIL_LEN: usize = 254;
14+
15+/// Longest local part (the part before `@`), in bytes (RFC 5321).
16+pub const MAX_LOCAL_LEN: usize = 64;
17+
18+/// Longest domain label, in bytes (RFC 1035).
19+const MAX_LABEL_LEN: usize = 63;
20+
21+/// The stored form of an address: surrounding whitespace removed, then lowercased.
22+pub fn normalize_email(input: &str) -> String {
23+ input.trim().to_lowercase()
24+}
25+
26+/// Normalises `input` and checks its shape. Returns the stored form.
27+///
28+/// Rules: at most 254 bytes; exactly one `@`; a local part of 1 to 64 characters from the RFC 5322
29+/// `atext` set (no leading, trailing or doubled dot); a domain of dot-separated labels, at least
30+/// one dot, each label 1 to 63 letters, digits or hyphens without a leading or trailing hyphen.
31+/// Anything else, including whitespace and control characters, is refused.
32+pub fn parse_email(input: &str) -> Result<String> {
33+ let email = normalize_email(input);
34+ check_shape(&email)?;
35+ Ok(email)
36+}
37+
38+/// The shape rules of [`parse_email`], for text that is already normalised.
39+fn check_shape(email: &str) -> Result<()> {
40+ let invalid = || Error::Invalid("email address is not valid".into());
41+ if email.len() > MAX_EMAIL_LEN {
42+ return Err(invalid());
43+ }
44+ let (local, domain) = email.split_once('@').ok_or_else(invalid)?;
45+ if local.is_empty()
46+ || local.len() > MAX_LOCAL_LEN
47+ || local.starts_with('.')
48+ || local.ends_with('.')
49+ || local.contains("..")
50+ || !local.bytes().all(is_atext)
51+ {
52+ return Err(invalid());
53+ }
54+ if !domain.contains('.') {
55+ return Err(invalid());
56+ }
57+ for label in domain.split('.') {
58+ let well_formed = !label.is_empty()
59+ && label.len() <= MAX_LABEL_LEN
60+ && !label.starts_with('-')
61+ && !label.ends_with('-')
62+ && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-');
63+ if !well_formed {
64+ return Err(invalid());
65+ }
66+ }
67+ Ok(())
68+}
69+
70+/// RFC 5322 `atext` restricted to ASCII. The dot is handled by the caller.
71+fn is_atext(byte: u8) -> bool {
72+ byte.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~.".contains(&byte)
73+}
74+
75+#[cfg(test)]
76+mod tests {
77+ use super::*;
78+
79+ #[test]
80+ fn a_normal_address_is_trimmed_and_lowercased() {
81+ assert_eq!(
82+ parse_email(" Ada.Lovelace@Example.COM ").unwrap(),
83+ "ada.lovelace@example.com"
84+ );
85+ }
86+
87+ #[test]
88+ fn attack_strings_are_refused() {
89+ let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1));
90+ let long_total = format!("a@{}.com", "b".repeat(250));
91+ for bad in [
92+ "",
93+ "ada",
94+ "@example.com",
95+ "ada@",
96+ "ada@@example.com",
97+ "ada@example",
98+ "ada@.example.com",
99+ "ada@example..com",
100+ "ada@example.com.",
101+ "ada@-example.com",
102+ "ada@example-.com",
103+ "a da@example.com",
104+ "ada@exam\nple.com",
105+ "ada\u{0}@example.com",
106+ "ada\u{202e}@example.com",
107+ "\u{ff41}da@example.com",
108+ "ada@exam\u{430}le.com",
109+ ".ada@example.com",
110+ "ada.@example.com",
111+ "ada..x@example.com",
112+ "ada@example.c om",
113+ "ada@example.com/",
114+ "ada@ex\tample.com",
115+ &long_local,
116+ &long_total,
117+ ] {
118+ assert!(parse_email(bad).is_err(), "accepted {bad:?}");
119+ }
120+ }
121+}
crates/im-core/src/password.rsmodified+20 -12
@@ -55,25 +55,35 @@ pub async fn verify_password_async(pw: String, hash: String) -> Result<bool> {
55 .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))55 .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))
56 }56 }
57 57
58+/// Why a new password is refused by [`check_policy`]. The web layer maps each reason to a
59+/// translated message, so the reasons are kept apart from any text.
60+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61+pub enum PolicyViolation {
62+ /// Fewer than [`MIN_PASSWORD_CHARS`] characters.
63+ TooShort,
64+ /// More than [`MAX_PASSWORD_CHARS`] characters.
65+ TooLong,
66+ /// Contains the email local part or a word of the name.
67+ ContainsIdentity,
68+}
69+
58 /// Checks a new password against the policy.70 /// Checks a new password against the policy.
59 ///71 ///
60 /// Rules: 10 to 256 characters; it must not contain the email local part (when that is at least72 /// Rules: 10 to 256 characters; it must not contain the email local part (when that is at least
61 /// [`MIN_FORBIDDEN_WORD_CHARS`] long) or any word of the name that is at least that long, compared73 /// [`MIN_FORBIDDEN_WORD_CHARS`] long) or any word of the name that is at least that long, compared
62 /// case-insensitively. The rule that the password differs from the current one needs the stored74 /// case-insensitively. The rule that the password differs from the current one needs the stored
63 /// hash and is checked by the caller.75 /// hash and is checked by the caller.
64-///76+pub fn check_policy(
65-/// Returns `Error::Invalid` with a message that is safe to show the user.77+ password: &str,
66-pub fn check_policy(password: &str, email: &str, name: &str) -> Result<()> {78+ email: &str,
79+ name: &str,
80+) -> std::result::Result<(), PolicyViolation> {
67 let chars = password.chars().count();81 let chars = password.chars().count();
68 if chars < MIN_PASSWORD_CHARS {82 if chars < MIN_PASSWORD_CHARS {
69- return Err(Error::Invalid(format!(83+ return Err(PolicyViolation::TooShort);
70- "password must be at least {MIN_PASSWORD_CHARS} characters"
71- )));
72 }84 }
73 if chars > MAX_PASSWORD_CHARS {85 if chars > MAX_PASSWORD_CHARS {
74- return Err(Error::Invalid(format!(86+ return Err(PolicyViolation::TooLong);
75- "password must be at most {MAX_PASSWORD_CHARS} characters"
76- )));
77 }87 }
78 88
79 let lowered = password.to_lowercase();89 let lowered = password.to_lowercase();
@@ -84,9 +94,7 @@ pub fn check_policy(password: &str, email: &str, name: &str) -> Result<()> {
84 .filter(|word| word.chars().count() >= MIN_FORBIDDEN_WORD_CHARS);94 .filter(|word| word.chars().count() >= MIN_FORBIDDEN_WORD_CHARS);
85 for word in forbidden {95 for word in forbidden {
86 if lowered.contains(&word) {96 if lowered.contains(&word) {
87- return Err(Error::Invalid(97+ return Err(PolicyViolation::ContainsIdentity);
88- "password must not contain your email address or name".into(),
89- ));
90 }98 }
91 }99 }
92 Ok(())100 Ok(())
crates/im-core/src/store/audit.rsadded+182 -0
@@ -0,0 +1,182 @@
1+//! The audit log: append-only records of changes, and their listing with keyset paging.
2+//!
3+//! Entries are never updated or deleted here. The only removal is the operator's purge command
4+//! (`docs/architecture.md` section 10), which is not part of this module. Entries sort by
5+//! `(at, id)`; both parts are fixed-width text, so a cursor can name a position exactly.
6+
7+use crate::error::Result;
8+use crate::model::AuditEntry;
9+use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, new_id};
10+use crate::time::now_stamp;
11+
12+/// The columns of an audit row, in the order [`map_entry`] reads them.
13+const ENTRY_COLS: &str = "id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data";
14+
15+/// Maps a row selected with [`ENTRY_COLS`].
16+fn map_entry(row: &turso::Row) -> Result<AuditEntry> {
17+ Ok(AuditEntry {
18+ id: col_text(row, 0)?,
19+ at: col_text(row, 1)?,
20+ actor_id: col_opt_text(row, 2)?,
21+ actor_kind: col_text(row, 3)?,
22+ action: col_text(row, 4)?,
23+ target_kind: col_opt_text(row, 5)?,
24+ target_id: col_opt_text(row, 6)?,
25+ ip: col_opt_text(row, 7)?,
26+ data: col_opt_text(row, 8)?,
27+ })
28+}
29+
30+/// One entry to append. `data` is JSON text or `None`; it must never hold a secret.
31+#[derive(Debug, Clone, Copy)]
32+pub struct NewAudit<'a> {
33+ /// Who acted, when known.
34+ pub actor_id: Option<&'a str>,
35+ /// `user`, `client`, `cli`, `system` or `anonymous`.
36+ pub actor_kind: &'a str,
37+ /// The action text, as `model::AuditAction::as_str`.
38+ pub action: &'a str,
39+ /// What the action is about, such as `user`.
40+ pub target_kind: Option<&'a str>,
41+ /// The id of that thing.
42+ pub target_id: Option<&'a str>,
43+ /// Client address, when known.
44+ pub ip: Option<&'a str>,
45+ /// Extra detail as JSON text.
46+ pub data: Option<&'a str>,
47+}
48+
49+/// Filters of a listing. `None` leaves that field unrestricted. `from` is inclusive and `to` is
50+/// exclusive, both as stored stamps.
51+#[derive(Debug, Clone, Default)]
52+pub struct AuditFilter {
53+ /// Only this action.
54+ pub action: Option<String>,
55+ /// Only this actor.
56+ pub actor_id: Option<String>,
57+ /// Only this target id.
58+ pub target_id: Option<String>,
59+ /// Entries at or after this stamp.
60+ pub from: Option<String>,
61+ /// Entries before this stamp.
62+ pub to: Option<String>,
63+}
64+
65+/// The position after the last entry of a page: the next page starts strictly before it.
66+#[derive(Debug, Clone, PartialEq, Eq)]
67+pub struct AuditCursor {
68+ /// The `at` of the last entry of the page.
69+ pub at: String,
70+ /// The `id` of the last entry of the page.
71+ pub id: String,
72+}
73+
74+impl Store {
75+ /// Appends an entry, stamped with the current time.
76+ pub async fn record_audit(&self, entry: &NewAudit<'_>) -> Result<()> {
77+ let conn = self.inner.conn.lock().await;
78+ conn.execute(
79+ "INSERT INTO audit_log (id, at, actor_id, actor_kind, action, target_kind, target_id, \
80+ ip, data) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
81+ (
82+ new_id(),
83+ now_stamp(),
84+ entry.actor_id.map(str::to_owned),
85+ entry.actor_kind.to_owned(),
86+ entry.action.to_owned(),
87+ entry.target_kind.map(str::to_owned),
88+ entry.target_id.map(str::to_owned),
89+ entry.ip.map(str::to_owned),
90+ entry.data.map(str::to_owned),
91+ ),
92+ )
93+ .await
94+ .map_err(db_err)?;
95+ Ok(())
96+ }
97+
98+ /// One page of the log, newest first, after `after` when given. Returns at most `limit`
99+ /// entries. When the page is full, the cursor for the next page is the last entry's position.
100+ ///
101+ /// Keyset paging: a cursor names a position, so entries written while the reader pages do not
102+ /// shift the pages, and there is no offset to scan.
103+ pub async fn list_audit(
104+ &self,
105+ filter: &AuditFilter,
106+ after: Option<&AuditCursor>,
107+ limit: u32,
108+ ) -> Result<(Vec<AuditEntry>, Option<AuditCursor>)> {
109+ let limit = limit.clamp(1, 200);
110+ let conn = self.read_conn().await;
111+ let entries = fetch_all(
112+ &conn,
113+ &format!(
114+ "SELECT {ENTRY_COLS} FROM audit_log \
115+ WHERE (?1 IS NULL OR action = ?1) \
116+ AND (?2 IS NULL OR actor_id = ?2) \
117+ AND (?3 IS NULL OR target_id = ?3) \
118+ AND (?4 IS NULL OR at >= ?4) \
119+ AND (?5 IS NULL OR at < ?5) \
120+ AND (?6 IS NULL OR at < ?6 OR (at = ?6 AND id < ?7)) \
121+ ORDER BY at DESC, id DESC LIMIT ?8"
122+ ),
123+ (
124+ filter.action.clone(),
125+ filter.actor_id.clone(),
126+ filter.target_id.clone(),
127+ filter.from.clone(),
128+ filter.to.clone(),
129+ after.map(|c| c.at.clone()),
130+ after.map(|c| c.id.clone()),
131+ i64::from(limit),
132+ ),
133+ map_entry,
134+ )
135+ .await?;
136+ let next = if entries.len() == usize::try_from(limit).unwrap_or(usize::MAX) {
137+ entries.last().map(|last| AuditCursor {
138+ at: last.at.clone(),
139+ id: last.id.clone(),
140+ })
141+ } else {
142+ None
143+ };
144+ Ok((entries, next))
145+ }
146+}
147+
148+#[cfg(test)]
149+mod tests {
150+ use super::*;
151+
152+ #[tokio::test]
153+ async fn entries_page_newest_first_with_a_cursor() {
154+ let dir = tempfile::tempdir().unwrap();
155+ let store = Store::open(&dir.path().join("im.db")).await.unwrap();
156+ for _ in 0..5 {
157+ store
158+ .record_audit(&NewAudit {
159+ actor_id: Some("user-1"),
160+ actor_kind: "user",
161+ action: "logout",
162+ target_kind: None,
163+ target_id: None,
164+ ip: None,
165+ data: None,
166+ })
167+ .await
168+ .unwrap();
169+ }
170+ let filter = AuditFilter {
171+ actor_id: Some("user-1".into()),
172+ ..AuditFilter::default()
173+ };
174+ let (first, cursor) = store.list_audit(&filter, None, 3).await.unwrap();
175+ assert_eq!(first.len(), 3);
176+ let cursor = cursor.expect("a full page has a cursor");
177+ let (second, cursor) = store.list_audit(&filter, Some(&cursor), 3).await.unwrap();
178+ assert_eq!(second.len(), 2);
179+ assert!(cursor.is_none(), "a short page ends the listing");
180+ assert!(first[2].at >= second[0].at);
181+ }
182+}
crates/im-core/src/store/mod.rsmodified+27 -0
@@ -6,8 +6,11 @@
6 //! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values6 //! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values
7 //! in effect are logged at boot.7 //! in effect are logged at boot.
8 8
9+pub mod audit;
9 pub mod migrate;10 pub mod migrate;
11+pub mod sessions;
10 pub mod snapshot;12 pub mod snapshot;
13+pub mod users;
11 14
12 use std::path::Path;15 use std::path::Path;
13 use std::sync::Arc;16 use std::sync::Arc;
@@ -153,6 +156,12 @@ pub async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> {
153 }156 }
154 }157 }
155 158
159+/// A fresh ULID as text. Ids are ULIDs everywhere, so their text order is their creation order
160+/// within a millisecond.
161+pub(crate) fn new_id() -> String {
162+ ulid::Ulid::generate().to_string()
163+}
164+
156 /// Converts a Turso error to the crate error.165 /// Converts a Turso error to the crate error.
157 pub(crate) fn db_err(e: turso::Error) -> Error {166 pub(crate) fn db_err(e: turso::Error) -> Error {
158 Error::Database(e.to_string())167 Error::Database(e.to_string())
@@ -257,6 +266,24 @@ pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> {
257 }266 }
258 }267 }
259 268
269+/// Reads a nullable text column. SQL NULL is `None`.
270+pub(crate) fn col_opt_text(row: &Row, i: usize) -> Result<Option<String>> {
271+ match row.get_value(i).map_err(db_err)? {
272+ Value::Null => Ok(None),
273+ Value::Text(s) => Ok(Some(s)),
274+ _ => Err(Error::Database(format!("column {i} is not text"))),
275+ }
276+}
277+
278+/// Reads a nullable integer column. SQL NULL is `None`.
279+pub(crate) fn col_opt_int(row: &Row, i: usize) -> Result<Option<i64>> {
280+ match row.get_value(i).map_err(db_err)? {
281+ Value::Null => Ok(None),
282+ Value::Integer(n) => Ok(Some(n)),
283+ _ => Err(Error::Database(format!("column {i} is not an integer"))),
284+ }
285+}
286+
260 /// Reads a column as text, accepting integers too. Used for PRAGMA results, which are text for287 /// Reads a column as text, accepting integers too. Used for PRAGMA results, which are text for
261 /// some pragmas and integers for others.288 /// some pragmas and integers for others.
262 pub(crate) fn col_to_string(row: &Row, i: usize) -> Result<String> {289 pub(crate) fn col_to_string(row: &Row, i: usize) -> Result<String> {
crates/im-core/src/store/sessions.rsadded+331 -0
@@ -0,0 +1,331 @@
1+//! Browser sessions: creation with the per-user cap, lookup by token hash, touch, listing and
2+//! ending.
3+//!
4+//! A session row is the sign-in. Its cookie carries a random token; the row holds only the SHA-256
5+//! of it. Ended sessions are deleted, and their ids are returned to the caller, so that later
6+//! back-channel logout jobs can be queued for them before the rows are gone.
7+
8+use std::time::Duration;
9+
10+use turso::Connection;
11+
12+use crate::error::Result;
13+use crate::model::Session;
14+use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
15+use crate::time::{now_stamp, stamp_after, stamp_before};
16+
17+/// The least time between two writes of `last_seen_at` for one session, in seconds. Every request
18+/// reads the session; only one of them in this window writes it.
19+const TOUCH_INTERVAL: Duration = Duration::from_secs(5 * 60);
20+
21+/// The columns of a session row, in the order [`map_session`] reads them.
22+const SESSION_COLS: &str = "id, user_id, token_hash, csrf_token, created_at, expires_at, \
23+ last_seen_at, ip, user_agent, auth_time, amr";
24+
25+/// Maps a row selected with [`SESSION_COLS`].
26+fn map_session(row: &turso::Row) -> Result<Session> {
27+ Ok(Session {
28+ id: col_text(row, 0)?,
29+ user_id: col_text(row, 1)?,
30+ token_hash: col_text(row, 2)?,
31+ csrf_token: col_text(row, 3)?,
32+ created_at: col_text(row, 4)?,
33+ expires_at: col_text(row, 5)?,
34+ last_seen_at: col_text(row, 6)?,
35+ ip: col_opt_text(row, 7)?,
36+ user_agent: col_opt_text(row, 8)?,
37+ auth_time: col_text(row, 9)?,
38+ amr: col_text(row, 10)?,
39+ })
40+}
41+
42+/// What is needed to create a session. `token_hash` is the hash of the cookie token; the token
43+/// itself never reaches the store.
44+#[derive(Debug, Clone)]
45+pub struct NewSession<'a> {
46+ /// Owner of the session.
47+ pub user_id: &'a str,
48+ /// Hex SHA-256 of the token that goes in the cookie.
49+ pub token_hash: &'a str,
50+ /// The per-session CSRF token.
51+ pub csrf_token: &'a str,
52+ /// One of the `model::amr` values.
53+ pub amr: &'a str,
54+ /// Client address at sign-in.
55+ pub ip: Option<&'a str>,
56+ /// User agent at sign-in, already truncated by the caller.
57+ pub user_agent: Option<&'a str>,
58+ /// How long the session lives from now.
59+ pub ttl: Duration,
60+}
61+
62+/// The result of creating a session: the new row, and the ids of the sessions that were ended to
63+/// make room under the cap. The caller queues back-channel logout for `ended`.
64+#[derive(Debug, Clone)]
65+pub struct CreatedSession {
66+ /// The new session.
67+ pub session: Session,
68+ /// Ids of the sessions ended because the user was at the cap, oldest first.
69+ pub ended: Vec<String>,
70+}
71+
72+/// Deletes the sessions of `user_id` matching `keep` (none keeps nothing), and returns their ids.
73+/// Runs inside the caller's transaction.
74+async fn end_sessions(
75+ conn: &Connection,
76+ user_id: &str,
77+ keep: Option<&str>,
78+ now: &str,
79+) -> Result<Vec<String>> {
80+ // Only sessions that were still live count as ended. Expired rows are removed by the sweeper.
81+ let ids = fetch_all(
82+ conn,
83+ "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 AND id IS NOT ?3 \
84+ ORDER BY created_at ASC, id ASC",
85+ (user_id.to_string(), now.to_string(), keep.map(str::to_owned)),
86+ |row| col_text(row, 0),
87+ )
88+ .await?;
89+ for id in &ids {
90+ conn.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),))
91+ .await
92+ .map_err(db_err)?;
93+ }
94+ Ok(ids)
95+}
96+
97+impl Store {
98+ /// Creates a session for a user who has just proved who they are.
99+ ///
100+ /// In one transaction: if the user already has `max_sessions` live sessions, the oldest ones
101+ /// are ended until there is room for the new one, then the new row is inserted. The check and
102+ /// the insert are in the same transaction, so two parallel sign-ins cannot both exceed the cap.
103+ pub async fn create_session(
104+ &self,
105+ new: &NewSession<'_>,
106+ max_sessions: u32,
107+ ) -> Result<CreatedSession> {
108+ let now = now_stamp();
109+ let expires_at = stamp_after(new.ttl);
110+ let cap = usize::try_from(max_sessions.max(1)).unwrap_or(usize::MAX);
111+ let session = Session {
112+ id: new_id(),
113+ user_id: new.user_id.to_owned(),
114+ token_hash: new.token_hash.to_owned(),
115+ csrf_token: new.csrf_token.to_owned(),
116+ created_at: now.clone(),
117+ expires_at,
118+ last_seen_at: now.clone(),
119+ ip: new.ip.map(str::to_owned),
120+ user_agent: new.user_agent.map(str::to_owned),
121+ auth_time: now.clone(),
122+ amr: new.amr.to_owned(),
123+ };
124+
125+ let conn = self.inner.conn.lock().await;
126+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
127+ let outcome: Result<CreatedSession> = async {
128+ let live = fetch_all(
129+ &tx,
130+ "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 \
131+ ORDER BY created_at ASC, id ASC",
132+ (new.user_id.to_string(), now.clone()),
133+ |row| col_text(row, 0),
134+ )
135+ .await?;
136+ // Room for the new one: at most cap - 1 live sessions may remain.
137+ let overflow = live.len().saturating_sub(cap - 1);
138+ let mut ended = Vec::with_capacity(overflow);
139+ for id in live.into_iter().take(overflow) {
140+ tx.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),))
141+ .await
142+ .map_err(db_err)?;
143+ ended.push(id);
144+ }
145+ tx.execute(
146+ "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, \
147+ last_seen_at, ip, user_agent, auth_time, amr) \
148+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
149+ (
150+ session.id.clone(),
151+ session.user_id.clone(),
152+ session.token_hash.clone(),
153+ session.csrf_token.clone(),
154+ session.created_at.clone(),
155+ session.expires_at.clone(),
156+ session.last_seen_at.clone(),
157+ session.ip.clone(),
158+ session.user_agent.clone(),
159+ session.auth_time.clone(),
160+ session.amr.clone(),
161+ ),
162+ )
163+ .await
164+ .map_err(db_err)?;
165+ Ok(CreatedSession {
166+ session: session.clone(),
167+ ended,
168+ })
169+ }
170+ .await;
171+ finish(tx, outcome).await
172+ }
173+
174+ /// The live session of this token hash, or `None`. A session is live when it has not expired
175+ /// and its user is not disabled. A disabled user is signed out by the next request, with no
176+ /// extra step.
177+ pub async fn session_by_token_hash(&self, token_hash: &str) -> Result<Option<Session>> {
178+ let conn = self.read_conn().await;
179+ fetch_opt(
180+ &conn,
181+ &format!(
182+ "SELECT {SESSION_COLS} FROM sessions \
183+ WHERE token_hash = ?1 AND expires_at > ?2 \
184+ AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)"
185+ ),
186+ (token_hash.to_string(), now_stamp()),
187+ map_session,
188+ )
189+ .await
190+ }
191+
192+ /// True when the session with this id is still live (same rules as
193+ /// [`Store::session_by_token_hash`]). The live stream checks this after every change.
194+ pub async fn session_is_live(&self, session_id: &str) -> Result<bool> {
195+ let conn = self.read_conn().await;
196+ let found = fetch_opt(
197+ &conn,
198+ "SELECT 1 FROM sessions WHERE id = ?1 AND expires_at > ?2 \
199+ AND user_id IN (SELECT id FROM users WHERE disabled_at IS NULL)",
200+ (session_id.to_string(), now_stamp()),
201+ |_row| Ok(()),
202+ )
203+ .await?;
204+ Ok(found.is_some())
205+ }
206+
207+ /// Records that the session was used. Writes `last_seen_at` only when the stored value is more
208+ /// than five minutes old, so a busy page does not write on every request. Returns whether it
209+ /// wrote.
210+ pub async fn touch_session(&self, session_id: &str) -> Result<bool> {
211+ let conn = self.inner.conn.lock().await;
212+ let changed = conn
213+ .execute(
214+ "UPDATE sessions SET last_seen_at = ?2 WHERE id = ?1 AND last_seen_at < ?3",
215+ (
216+ session_id.to_string(),
217+ now_stamp(),
218+ stamp_before(TOUCH_INTERVAL),
219+ ),
220+ )
221+ .await
222+ .map_err(db_err)?;
223+ Ok(changed == 1)
224+ }
225+
226+ /// The live sessions of a user, most recently used first.
227+ pub async fn list_sessions(&self, user_id: &str) -> Result<Vec<Session>> {
228+ let conn = self.read_conn().await;
229+ fetch_all(
230+ &conn,
231+ &format!(
232+ "SELECT {SESSION_COLS} FROM sessions WHERE user_id = ?1 AND expires_at > ?2 \
233+ ORDER BY last_seen_at DESC, id DESC"
234+ ),
235+ (user_id.to_string(), now_stamp()),
236+ map_session,
237+ )
238+ .await
239+ }
240+
241+ /// Ends one session, only if it belongs to `user_id`. Returns false when there was nothing to
242+ /// end, which is also the answer for another user's session: the caller cannot tell them apart.
243+ pub async fn end_session(&self, user_id: &str, session_id: &str) -> Result<bool> {
244+ let conn = self.inner.conn.lock().await;
245+ let changed = conn
246+ .execute(
247+ "DELETE FROM sessions WHERE id = ?1 AND user_id = ?2",
248+ (session_id.to_string(), user_id.to_string()),
249+ )
250+ .await
251+ .map_err(db_err)?;
252+ Ok(changed == 1)
253+ }
254+
255+ /// Ends every live session of `user_id` except `keep_session_id`. Returns the ids ended.
256+ pub async fn end_other_sessions(
257+ &self,
258+ user_id: &str,
259+ keep_session_id: &str,
260+ ) -> Result<Vec<String>> {
261+ self.end_matching(user_id, Some(keep_session_id)).await
262+ }
263+
264+ /// Ends every live session of `user_id`. Returns the ids ended.
265+ pub async fn end_all_sessions(&self, user_id: &str) -> Result<Vec<String>> {
266+ self.end_matching(user_id, None).await
267+ }
268+
269+ async fn end_matching(&self, user_id: &str, keep: Option<&str>) -> Result<Vec<String>> {
270+ let conn = self.inner.conn.lock().await;
271+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
272+ let now = now_stamp();
273+ let outcome: Result<Vec<String>> = end_sessions(&tx, user_id, keep, &now).await;
274+ finish(tx, outcome).await
275+ }
276+
277+ /// Deletes the sessions that have expired. Returns how many were removed. Run by the sweeper.
278+ pub async fn sweep_expired_sessions(&self) -> Result<u64> {
279+ let conn = self.inner.conn.lock().await;
280+ conn.execute(
281+ "DELETE FROM sessions WHERE expires_at <= ?1",
282+ (now_stamp(),),
283+ )
284+ .await
285+ .map_err(db_err)
286+ }
287+}
288+
289+#[cfg(test)]
290+mod tests {
291+ use super::*;
292+
293+ #[tokio::test]
294+ async fn the_cap_ends_the_oldest_sessions_in_the_same_write() {
295+ let dir = tempfile::tempdir().unwrap();
296+ let store = Store::open(&dir.path().join("im.db")).await.unwrap();
297+ let user = store
298+ .create_user("ada@example.com", "Ada", "hash", false)
299+ .await
300+ .unwrap();
301+ let mut ids: Vec<String> = Vec::new();
302+ for n in 0..3 {
303+ let token = format!("hash-{n}");
304+ let created = store
305+ .create_session(
306+ &NewSession {
307+ user_id: &user.id,
308+ token_hash: &token,
309+ csrf_token: "csrf",
310+ amr: "pwd",
311+ ip: None,
312+ user_agent: None,
313+ ttl: Duration::from_secs(3600),
314+ },
315+ 2,
316+ )
317+ .await
318+ .unwrap();
319+ if n < 2 {
320+ assert!(created.ended.is_empty());
321+ } else {
322+ assert_eq!(created.ended, vec![ids[0].clone()]);
323+ }
324+ ids.push(created.session.id);
325+ }
326+ let live = store.list_sessions(&user.id).await.unwrap();
327+ assert_eq!(live.len(), 2);
328+ assert!(store.session_by_token_hash("hash-0").await.unwrap().is_none());
329+ assert!(store.session_by_token_hash("hash-2").await.unwrap().is_some());
330+ }
331+}
crates/im-core/src/store/users.rsadded+468 -0
@@ -0,0 +1,468 @@
1+//! User accounts: creation, lookup, profile and password, and the two-factor state.
2+//!
3+//! Rules that must hold under concurrency are single conditional statements, so two requests cannot
4+//! both win:
5+//!
6+//! - the first administrator exists only if no user does (`create_first_admin`);
7+//! - a TOTP step is accepted once (`accept_totp_step`, `totp_last_step` is only ever raised);
8+//! - a recovery code is spent once (`consume_recovery_code`, `used_at IS NULL`).
9+//!
10+//! A TOTP secret that is being enrolled is not written to the user row. It waits in the `settings`
11+//! table under `totp_pending:<user id>`, sealed like any other secret, and moves to the row only
12+//! when a code from it is confirmed. So re-enrolling while two-factor is on never switches the
13+//! second factor off, and an abandoned enrolment changes nothing.
14+
15+use turso::{Connection, Row};
16+
17+use crate::error::{Error, Result};
18+use crate::model::User;
19+use crate::store::{Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id};
20+use crate::time::now_stamp;
21+
22+/// The columns of a user row, in the order [`map_user`] reads them.
23+const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \
24+ totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \
25+ photo_mime, picture_version, created_at, updated_at";
26+
27+/// Maps a row selected with [`USER_COLS`].
28+fn map_user(row: &Row) -> Result<User> {
29+ Ok(User {
30+ id: col_text(row, 0)?,
31+ email: col_text(row, 1)?,
32+ name: col_text(row, 2)?,
33+ password_hash: col_text(row, 3)?,
34+ is_admin: col_int(row, 4)? != 0,
35+ disabled_at: col_opt_text(row, 5)?,
36+ totp_secret_sealed: col_opt_text(row, 6)?,
37+ totp_enabled_at: col_opt_text(row, 7)?,
38+ totp_last_step: col_opt_int(row, 8)?,
39+ locale: col_text(row, 9)?,
40+ zoneinfo: col_text(row, 10)?,
41+ theme: col_text(row, 11)?,
42+ photo_mime: col_opt_text(row, 12)?,
43+ picture_version: col_int(row, 13)?,
44+ created_at: col_text(row, 14)?,
45+ updated_at: col_text(row, 15)?,
46+ })
47+}
48+
49+/// Maps an insert error. A UNIQUE violation is a conflict for the person; anything else is a
50+/// database failure.
51+fn insert_error(e: turso::Error) -> Error {
52+ let text = e.to_string();
53+ if text.contains("UNIQUE") {
54+ Error::Conflict("that email address is already registered".into())
55+ } else {
56+ db_err(e)
57+ }
58+}
59+
60+/// The settings key that holds a TOTP secret waiting for its first confirmed code.
61+fn pending_key(user_id: &str) -> String {
62+ format!("totp_pending:{user_id}")
63+}
64+
65+/// Replaces the recovery codes of a user with `hashes`. Runs inside the caller's transaction.
66+async fn replace_codes(conn: &Connection, user_id: &str, hashes: &[String]) -> Result<()> {
67+ conn.execute(
68+ "DELETE FROM recovery_codes WHERE user_id = ?1",
69+ (user_id.to_string(),),
70+ )
71+ .await
72+ .map_err(db_err)?;
73+ for hash in hashes {
74+ conn.execute(
75+ "INSERT INTO recovery_codes (user_id, code_hash, used_at) VALUES (?1, ?2, NULL)",
76+ (user_id.to_string(), hash.clone()),
77+ )
78+ .await
79+ .map_err(db_err)?;
80+ }
81+ Ok(())
82+}
83+
84+impl Store {
85+ /// Creates the first administrator, and only if there is no user at all.
86+ ///
87+ /// The check and the insert are one statement, so two parallel setups cannot both succeed. The
88+ /// second one gets [`Error::Conflict`]. `email` must already be normalised.
89+ pub async fn create_first_admin(
90+ &self,
91+ email: &str,
92+ name: &str,
93+ password_hash: &str,
94+ ) -> Result<User> {
95+ let id = new_id();
96+ let now = now_stamp();
97+ let conn = self.inner.conn.lock().await;
98+ let changed = conn
99+ .execute(
100+ "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \
101+ created_at, updated_at) \
102+ SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \
103+ WHERE NOT EXISTS (SELECT 1 FROM users)",
104+ (
105+ id.clone(),
106+ email.to_string(),
107+ name.to_string(),
108+ password_hash.to_string(),
109+ now,
110+ ),
111+ )
112+ .await
113+ .map_err(insert_error)?;
114+ drop(conn);
115+ if changed == 0 {
116+ return Err(Error::Conflict("setup is already complete".into()));
117+ }
118+ self.user_by_id(&id).await?.ok_or(Error::NotFound)
119+ }
120+
121+ /// Creates an account. `email` must already be normalised. Fails with a conflict when the
122+ /// address is taken.
123+ pub async fn create_user(
124+ &self,
125+ email: &str,
126+ name: &str,
127+ password_hash: &str,
128+ is_admin: bool,
129+ ) -> Result<User> {
130+ let id = new_id();
131+ let now = now_stamp();
132+ let conn = self.inner.conn.lock().await;
133+ conn.execute(
134+ "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \
135+ created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)",
136+ (
137+ id.clone(),
138+ email.to_string(),
139+ name.to_string(),
140+ password_hash.to_string(),
141+ i64::from(is_admin),
142+ now,
143+ ),
144+ )
145+ .await
146+ .map_err(insert_error)?;
147+ drop(conn);
148+ self.user_by_id(&id).await?.ok_or(Error::NotFound)
149+ }
150+
151+ /// The user with this id, or `None`.
152+ pub async fn user_by_id(&self, id: &str) -> Result<Option<User>> {
153+ let conn = self.read_conn().await;
154+ fetch_opt(
155+ &conn,
156+ &format!("SELECT {USER_COLS} FROM users WHERE id = ?1"),
157+ (id.to_string(),),
158+ map_user,
159+ )
160+ .await
161+ }
162+
163+ /// The user with this normalised address, or `None`. Callers normalise the input first.
164+ pub async fn user_by_email_folded(&self, folded: &str) -> Result<Option<User>> {
165+ let conn = self.read_conn().await;
166+ fetch_opt(
167+ &conn,
168+ &format!("SELECT {USER_COLS} FROM users WHERE email_folded = ?1"),
169+ (folded.to_string(),),
170+ map_user,
171+ )
172+ .await
173+ }
174+
175+ /// Changes the display name. The schema keeps it at 1 to 100 characters.
176+ pub async fn update_name(&self, id: &str, name: &str) -> Result<()> {
177+ let conn = self.inner.conn.lock().await;
178+ let changed = conn
179+ .execute(
180+ "UPDATE users SET name = ?2, updated_at = ?3 WHERE id = ?1",
181+ (id.to_string(), name.to_string(), now_stamp()),
182+ )
183+ .await
184+ .map_err(db_err)?;
185+ if changed == 0 {
186+ return Err(Error::NotFound);
187+ }
188+ Ok(())
189+ }
190+
191+ /// Changes the language, time zone and theme. The schema rejects unknown languages and themes.
192+ pub async fn update_preferences(
193+ &self,
194+ id: &str,
195+ locale: &str,
196+ zoneinfo: &str,
197+ theme: &str,
198+ ) -> Result<()> {
199+ let conn = self.inner.conn.lock().await;
200+ let changed = conn
201+ .execute(
202+ "UPDATE users SET locale = ?2, zoneinfo = ?3, theme = ?4, updated_at = ?5 \
203+ WHERE id = ?1",
204+ (
205+ id.to_string(),
206+ locale.to_string(),
207+ zoneinfo.to_string(),
208+ theme.to_string(),
209+ now_stamp(),
210+ ),
211+ )
212+ .await
213+ .map_err(db_err)?;
214+ if changed == 0 {
215+ return Err(Error::NotFound);
216+ }
217+ Ok(())
218+ }
219+
220+ /// Stores a new argon2id hash. The caller has checked the policy and the current password.
221+ pub async fn set_password_hash(&self, id: &str, password_hash: &str) -> Result<()> {
222+ let conn = self.inner.conn.lock().await;
223+ let changed = conn
224+ .execute(
225+ "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1",
226+ (id.to_string(), password_hash.to_string(), now_stamp()),
227+ )
228+ .await
229+ .map_err(db_err)?;
230+ if changed == 0 {
231+ return Err(Error::NotFound);
232+ }
233+ Ok(())
234+ }
235+
236+ /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an
237+ /// earlier unconfirmed secret of the same user. The user row is not touched.
238+ pub async fn set_totp_pending(&self, user_id: &str, sealed_secret: &str) -> Result<()> {
239+ self.set_setting(&pending_key(user_id), sealed_secret).await
240+ }
241+
242+ /// The sealed secret of an enrolment that is waiting for its confirming code, or `None`.
243+ pub async fn totp_pending(&self, user_id: &str) -> Result<Option<String>> {
244+ self.setting(&pending_key(user_id)).await
245+ }
246+
247+ /// Turns two-factor sign-in on: stores the confirmed secret, records the step that confirmed
248+ /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret.
249+ /// One transaction.
250+ pub async fn enable_totp(
251+ &self,
252+ user_id: &str,
253+ sealed_secret: &str,
254+ step: u64,
255+ recovery_hashes: &[String],
256+ ) -> Result<()> {
257+ let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?;
258+ let now = now_stamp();
259+ let conn = self.inner.conn.lock().await;
260+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
261+ let outcome: Result<()> = async {
262+ let changed = tx
263+ .execute(
264+ "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \
265+ totp_last_step = ?4, updated_at = ?3 WHERE id = ?1",
266+ (
267+ user_id.to_string(),
268+ sealed_secret.to_string(),
269+ now,
270+ step,
271+ ),
272+ )
273+ .await
274+ .map_err(db_err)?;
275+ if changed == 0 {
276+ return Err(Error::NotFound);
277+ }
278+ replace_codes(&tx, user_id, recovery_hashes).await?;
279+ tx.execute("DELETE FROM settings WHERE key = ?1", (pending_key(user_id),))
280+ .await
281+ .map_err(db_err)?;
282+ Ok(())
283+ }
284+ .await;
285+ finish(tx, outcome).await
286+ }
287+
288+ /// Turns two-factor sign-in off: clears the secret, the step and the recovery codes, and drops
289+ /// any pending enrolment. One transaction.
290+ pub async fn disable_totp(&self, user_id: &str) -> Result<()> {
291+ let conn = self.inner.conn.lock().await;
292+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
293+ let outcome: Result<()> = async {
294+ let changed = tx
295+ .execute(
296+ "UPDATE users SET totp_secret_sealed = NULL, totp_enabled_at = NULL, \
297+ totp_last_step = NULL, updated_at = ?2 WHERE id = ?1",
298+ (user_id.to_string(), now_stamp()),
299+ )
300+ .await
301+ .map_err(db_err)?;
302+ if changed == 0 {
303+ return Err(Error::NotFound);
304+ }
305+ tx.execute(
306+ "DELETE FROM recovery_codes WHERE user_id = ?1",
307+ (user_id.to_string(),),
308+ )
309+ .await
310+ .map_err(db_err)?;
311+ tx.execute("DELETE FROM settings WHERE key = ?1", (pending_key(user_id),))
312+ .await
313+ .map_err(db_err)?;
314+ Ok(())
315+ }
316+ .await;
317+ finish(tx, outcome).await
318+ }
319+
320+ /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard
321+ /// forward. A step that is not later than the recorded one, or any step while two-factor is off,
322+ /// returns false. This is the replay guard: a code is spent by this single statement.
323+ pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result<bool> {
324+ let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?;
325+ let conn = self.inner.conn.lock().await;
326+ let changed = conn
327+ .execute(
328+ "UPDATE users SET totp_last_step = ?2 \
329+ WHERE id = ?1 AND totp_enabled_at IS NOT NULL \
330+ AND (totp_last_step IS NULL OR totp_last_step < ?2)",
331+ (user_id.to_string(), step),
332+ )
333+ .await
334+ .map_err(db_err)?;
335+ Ok(changed == 1)
336+ }
337+
338+ /// Replaces every recovery code of the user with `hashes`, all unused. One transaction.
339+ pub async fn replace_recovery_codes(&self, user_id: &str, hashes: &[String]) -> Result<()> {
340+ let conn = self.inner.conn.lock().await;
341+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
342+ let outcome: Result<()> = replace_codes(&tx, user_id, hashes).await;
343+ finish(tx, outcome).await
344+ }
345+
346+ /// Spends a recovery code. Returns true only for the first use of an existing, unused code.
347+ pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result<bool> {
348+ let conn = self.inner.conn.lock().await;
349+ let changed = conn
350+ .execute(
351+ "UPDATE recovery_codes SET used_at = ?3 \
352+ WHERE user_id = ?1 AND code_hash = ?2 AND used_at IS NULL",
353+ (user_id.to_string(), code_hash.to_string(), now_stamp()),
354+ )
355+ .await
356+ .map_err(db_err)?;
357+ Ok(changed == 1)
358+ }
359+
360+ /// How many recovery codes of the user are still unused.
361+ pub async fn unused_recovery_codes(&self, user_id: &str) -> Result<u64> {
362+ let conn = self.read_conn().await;
363+ let count = fetch_opt(
364+ &conn,
365+ "SELECT COUNT(*) FROM recovery_codes WHERE user_id = ?1 AND used_at IS NULL",
366+ (user_id.to_string(),),
367+ |row| col_int(row, 0),
368+ )
369+ .await?
370+ .unwrap_or(0);
371+ u64::try_from(count).map_err(|_| Error::Database("negative count".into()))
372+ }
373+}
374+
375+#[cfg(test)]
376+mod tests {
377+ use super::*;
378+ use crate::password::hash_password;
379+
380+ async fn store() -> (tempfile::TempDir, Store) {
381+ let dir = tempfile::tempdir().unwrap();
382+ let store = Store::open(&dir.path().join("im.db")).await.unwrap();
383+ (dir, store)
384+ }
385+
386+ #[tokio::test]
387+ async fn the_first_admin_can_be_created_once() {
388+ let (_dir, store) = store().await;
389+ let hash = hash_password("correct horse battery").unwrap();
390+ let admin = store
391+ .create_first_admin("ada@example.com", "Ada", &hash)
392+ .await
393+ .unwrap();
394+ assert!(admin.is_admin);
395+ assert_eq!(store.user_count().await.unwrap(), 1);
396+
397+ let second = store
398+ .create_first_admin("bob@example.com", "Bob", &hash)
399+ .await;
400+ assert!(matches!(second, Err(Error::Conflict(_))), "{second:?}");
401+ assert_eq!(store.user_count().await.unwrap(), 1);
402+ }
403+
404+ #[tokio::test]
405+ async fn a_totp_step_is_accepted_once_and_only_while_enabled() {
406+ let (_dir, store) = store().await;
407+ let user = store
408+ .create_user("ada@example.com", "Ada", "hash", false)
409+ .await
410+ .unwrap();
411+ assert!(!store.accept_totp_step(&user.id, 100).await.unwrap());
412+
413+ store.set_totp_pending(&user.id, "v1:sealed").await.unwrap();
414+ assert_eq!(
415+ store.totp_pending(&user.id).await.unwrap().as_deref(),
416+ Some("v1:sealed")
417+ );
418+ store
419+ .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()])
420+ .await
421+ .unwrap();
422+ assert!(store.totp_pending(&user.id).await.unwrap().is_none());
423+
424+ assert!(store.accept_totp_step(&user.id, 101).await.unwrap());
425+ // The same step again, and an older one, are refused: the replay guard.
426+ assert!(!store.accept_totp_step(&user.id, 101).await.unwrap());
427+ assert!(!store.accept_totp_step(&user.id, 100).await.unwrap());
428+ assert!(store.accept_totp_step(&user.id, 102).await.unwrap());
429+ }
430+
431+ #[tokio::test]
432+ async fn a_recovery_code_works_once() {
433+ let (_dir, store) = store().await;
434+ let user = store
435+ .create_user("ada@example.com", "Ada", "hash", false)
436+ .await
437+ .unwrap();
438+ store
439+ .set_totp_pending(&user.id, "v1:sealed")
440+ .await
441+ .unwrap();
442+ store
443+ .enable_totp(&user.id, "v1:sealed", 5, &["code-a".to_string(), "code-b".to_string()])
444+ .await
445+ .unwrap();
446+ assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2);
447+
448+ assert!(store.consume_recovery_code(&user.id, "code-a").await.unwrap());
449+ assert!(!store.consume_recovery_code(&user.id, "code-a").await.unwrap());
450+ assert!(!store.consume_recovery_code(&user.id, "unknown").await.unwrap());
451+ assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 1);
452+ }
453+
454+ #[tokio::test]
455+ async fn emails_are_unique_and_found_by_their_normalised_form() {
456+ let (_dir, store) = store().await;
457+ store
458+ .create_user("ada@example.com", "Ada", "hash", false)
459+ .await
460+ .unwrap();
461+ let dup = store
462+ .create_user("ada@example.com", "Ada again", "hash", false)
463+ .await;
464+ assert!(matches!(dup, Err(Error::Conflict(_))), "{dup:?}");
465+ assert!(store.user_by_email_folded("ada@example.com").await.unwrap().is_some());
466+ assert!(store.user_by_email_folded("ADA@example.com").await.unwrap().is_none());
467+ }
468+}
crates/im-core/src/totp.rsadded+229 -0
@@ -0,0 +1,229 @@
1+//! Second-factor helpers: TOTP (RFC 6238 over HMAC-SHA1, 6 digits, 30-second steps), RFC 4648
2+//! base32 for the shared secret, the `otpauth://` link that authenticator apps import, and
3+//! recovery codes.
4+//!
5+//! This module keeps no state. A code is accepted at the current step and one step either side.
6+//! [`verify`] returns the step it matched; the caller stores that step as the replay guard with a
7+//! conditional update (`Store::accept_totp_step`), so two requests with the same code cannot both
8+//! succeed.
9+
10+use hmac::{Hmac, KeyInit, Mac};
11+use sha1::Sha1;
12+use sha2::{Digest, Sha256};
13+
14+use crate::token::{constant_time_eq, random_readable};
15+
16+/// Shared secret length in bytes: 160 bits, the RFC 4226 recommendation.
17+pub const SECRET_LEN: usize = 20;
18+
19+/// Seconds per time step. RFC 6238 default and what authenticator apps assume.
20+pub const STEP_SECS: u64 = 30;
21+
22+/// Digits in a code. Six is what every authenticator app defaults to.
23+pub const DIGITS: usize = 6;
24+
25+/// Steps accepted on each side of the current one, to allow for clock drift of up to 30 seconds.
26+pub const SKEW_STEPS: i64 = 1;
27+
28+/// Issuer name shown by authenticator apps next to the account.
29+pub const ISSUER: &str = "im";
30+
31+const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
32+
33+type HmacSha1 = Hmac<Sha1>;
34+
35+/// A fresh random secret of [`SECRET_LEN`] bytes.
36+pub fn new_secret() -> [u8; SECRET_LEN] {
37+ let mut secret = [0u8; SECRET_LEN];
38+ rand::fill(&mut secret);
39+ secret
40+}
41+
42+/// HOTP (RFC 4226) with HMAC-SHA1, reduced to [`DIGITS`] digits.
43+pub fn hotp(secret: &[u8], counter: u64) -> u32 {
44+ // HMAC accepts a key of any length, so construction cannot fail.
45+ let mut mac =
46+ <HmacSha1 as KeyInit>::new_from_slice(secret).expect("HMAC takes any key length");
47+ mac.update(&counter.to_be_bytes());
48+ let tag = mac.finalize().into_bytes();
49+ // Dynamic truncation (RFC 4226 section 5.3): the low nibble of the last byte picks a window.
50+ let offset = usize::from(tag[tag.len() - 1] & 0x0f);
51+ let binary = u32::from_be_bytes([
52+ tag[offset] & 0x7f,
53+ tag[offset + 1],
54+ tag[offset + 2],
55+ tag[offset + 3],
56+ ]);
57+ binary % 10u32.pow(DIGITS as u32)
58+}
59+
60+/// The time step that contains `unix_secs`.
61+pub fn step_for(unix_secs: u64) -> u64 {
62+ unix_secs / STEP_SECS
63+}
64+
65+/// The zero-padded code for one step.
66+pub fn code_at(secret: &[u8], step: u64) -> String {
67+ format!("{:0width$}", hotp(secret, step), width = DIGITS)
68+}
69+
70+/// Checks `code` against the steps around `now_step`.
71+///
72+/// Returns the matched step when it is later than `last_step` (the replay guard; `None` means no
73+/// code was ever used). Malformed input returns `None` without any HMAC work. Every candidate
74+/// step is compared, so timing does not reveal which one matched.
75+pub fn verify(secret: &[u8], code: &str, now_step: u64, last_step: Option<u64>) -> Option<u64> {
76+ if code.len() != DIGITS || !code.bytes().all(|b| b.is_ascii_digit()) {
77+ return None;
78+ }
79+ let now = i64::try_from(now_step).ok()?;
80+ let mut matched = None;
81+ for delta in -SKEW_STEPS..=SKEW_STEPS {
82+ let Some(step) = now.checked_add(delta).and_then(|s| u64::try_from(s).ok()) else {
83+ continue;
84+ };
85+ let expected = code_at(secret, step);
86+ if constant_time_eq(expected.as_bytes(), code.as_bytes()) && matched.is_none() {
87+ matched = Some(step);
88+ }
89+ }
90+ matched.filter(|&step| last_step.is_none_or(|last| step > last))
91+}
92+
93+/// RFC 4648 base32, uppercase, without padding. This is the form authenticator apps expect.
94+pub fn base32_encode(data: &[u8]) -> String {
95+ let mut out = String::with_capacity(data.len().div_ceil(5) * 8);
96+ let mut buffer: u64 = 0;
97+ let mut bits: u32 = 0;
98+ for &byte in data {
99+ buffer = (buffer << 8) | u64::from(byte);
100+ bits += 8;
101+ while bits >= 5 {
102+ bits -= 5;
103+ out.push(char::from(
104+ BASE32_ALPHABET[((buffer >> bits) & 31) as usize],
105+ ));
106+ }
107+ }
108+ if bits > 0 {
109+ out.push(char::from(
110+ BASE32_ALPHABET[((buffer << (5 - bits)) & 31) as usize],
111+ ));
112+ }
113+ out
114+}
115+
116+/// The `otpauth://` link that authenticator apps import, for the account `account` (the email
117+/// address). The label and the issuer are percent-encoded, so an address with `+` or `@` survives.
118+pub fn otpauth_uri(account: &str, secret: &[u8]) -> String {
119+ let label = format!("{ISSUER}:{account}");
120+ format!(
121+ "otpauth://totp/{}?secret={}&issuer={}&algorithm=SHA1&digits={DIGITS}&period={STEP_SECS}",
122+ encode_component(&label),
123+ base32_encode(secret),
124+ encode_component(ISSUER),
125+ )
126+}
127+
128+/// Percent-encodes everything except RFC 3986 unreserved characters.
129+fn encode_component(text: &str) -> String {
130+ let mut out = String::with_capacity(text.len());
131+ for byte in text.bytes() {
132+ match byte {
133+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
134+ out.push(char::from(byte));
135+ }
136+ _ => out.push_str(&format!("%{byte:02X}")),
137+ }
138+ }
139+ out
140+}
141+
142+/// A new recovery code, shown to the person as `xxxx-xxxx` from the readable alphabet.
143+pub fn new_recovery_code() -> String {
144+ let raw = random_readable(8);
145+ format!("{}-{}", &raw[..4], &raw[4..])
146+}
147+
148+/// Hex SHA-256 of a recovery code after normalisation: lowercase, without dashes and spaces. The
149+/// stored hash and the checked input go through the same normalisation, so how the person types
150+/// the code does not matter.
151+pub fn recovery_code_hash(code: &str) -> String {
152+ let normalized: String = code
153+ .chars()
154+ .filter(|c| !c.is_whitespace() && *c != '-')
155+ .map(|c| c.to_ascii_lowercase())
156+ .collect();
157+ hex::encode(Sha256::digest(normalized.as_bytes()))
158+}
159+
160+#[cfg(test)]
161+mod tests {
162+ use super::*;
163+
164+ /// RFC 6238 appendix B, SHA-1 row: the 8-digit reference values reduce to these 6-digit codes.
165+ const RFC_KEY: &[u8] = b"12345678901234567890";
166+
167+ #[test]
168+ fn rfc6238_sha1_test_vectors() {
169+ let vectors: [(u64, &str); 6] = [
170+ (59, "287082"),
171+ (1_111_111_109, "081804"),
172+ (1_111_111_111, "050471"),
173+ (1_234_567_890, "005924"),
174+ (2_000_000_000, "279037"),
175+ (20_000_000_000, "353130"),
176+ ];
177+ for (time, expected) in vectors {
178+ assert_eq!(code_at(RFC_KEY, time / STEP_SECS), expected, "time {time}");
179+ }
180+ }
181+
182+ #[test]
183+ fn a_code_is_accepted_once_within_the_skew_window() {
184+ let now = 1_000;
185+ let code = code_at(RFC_KEY, now + 1);
186+ assert_eq!(verify(RFC_KEY, &code, now, None), Some(now + 1));
187+ // The same step is refused after it was recorded as used (the replay guard).
188+ assert_eq!(verify(RFC_KEY, &code, now, Some(now + 1)), None);
189+ assert_eq!(verify(RFC_KEY, &code_at(RFC_KEY, now + 2), now, None), None);
190+ assert_eq!(verify(RFC_KEY, "12345", now, None), None);
191+ }
192+
193+ #[test]
194+ fn base32_matches_the_rfc4648_vectors() {
195+ let cases = [
196+ ("", ""),
197+ ("f", "MY"),
198+ ("fo", "MZXQ"),
199+ ("foo", "MZXW6"),
200+ ("foob", "MZXW6YQ"),
201+ ("fooba", "MZXW6YTB"),
202+ ("foobar", "MZXW6YTBOI"),
203+ ];
204+ for (plain, encoded) in cases {
205+ assert_eq!(base32_encode(plain.as_bytes()), encoded);
206+ }
207+ }
208+
209+ #[test]
210+ fn the_link_encodes_the_label_and_carries_the_secret() {
211+ let uri = otpauth_uri("ada+1@example.com", b"foobar");
212+ assert_eq!(
213+ uri,
214+ "otpauth://totp/im%3Aada%2B1%40example.com?secret=MZXW6YTBOI&issuer=im\
215+ &algorithm=SHA1&digits=6&period=30"
216+ );
217+ }
218+
219+ #[test]
220+ fn recovery_codes_ignore_case_dashes_and_spaces() {
221+ let code = new_recovery_code();
222+ assert_eq!(code.len(), 9);
223+ assert_eq!(code.as_bytes()[4], b'-');
224+ assert_eq!(
225+ recovery_code_hash(&code),
226+ recovery_code_hash(&code.to_uppercase().replace('-', " "))
227+ );
228+ }
229+}
crates/im-web/Cargo.tomlmodified+3 -0
@@ -10,10 +10,13 @@ name = "im"
10 path = "src/main.rs"10 path = "src/main.rs"
11 11
12 [dependencies]12 [dependencies]
13+base64.workspace = true
13 futures-util.workspace = true14 futures-util.workspace = true
14 http.workspace = true15 http.workspace = true
15 im-core.workspace = true16 im-core.workspace = true
17+qrcode.workspace = true
16 serde.workspace = true18 serde.workspace = true
19+serde_json.workspace = true
17 # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout.20 # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout.
18 tokio = { workspace = true, features = ["net", "signal", "time"] }21 tokio = { workspace = true, features = ["net", "signal", "time"] }
19 topcoat.workspace = true22 topcoat.workspace = true
crates/im-web/assets/nav.jsmodified+9 -1
@@ -169,9 +169,17 @@
169 };169 };
170 }170 }
171 171
172- /** Holds /-/alive. It only drives the restart bar; the server sends nothing else on it yet. */172+ /**
173+ * Holds /-/alive. It drives the restart bar, and it carries the account events of a signed-in
174+ * browser: `account` when the person's sessions or security changed, and `signed_out` when this
175+ * browser's session is gone, which sends the page to sign-in.
176+ */
173 function holdAlive() {177 function holdAlive() {
174 hold(ALIVE_PATH, {178 hold(ALIVE_PATH, {
179+ events: {
180+ account: () => scheduleRefresh(),
181+ signed_out: () => location.assign("/login"),
182+ },
175 lost: () => {183 lost: () => {
176 serverDown = true;184 serverDown = true;
177 updateRestartBar();185 updateRestartBar();
crates/im-web/src/audit.rsadded+57 -0
@@ -0,0 +1,57 @@
1+//! The audit writer of the web layer. Every change of an account, a session or a sign-in goes
2+//! through [`record`].
3+//!
4+//! The entry is written after the change has committed. A failed write is logged and never fails
5+//! the request: a person who has just signed in should not see an error because the log was busy.
6+//! Nothing secret goes in `data`; callers pass counts, reasons and ids only.
7+
8+use im_core::model::AuditAction;
9+use im_core::store::audit::NewAudit;
10+use serde_json::Value;
11+use topcoat::context::{Cx, app_context};
12+
13+use crate::client_ip::client_addr;
14+use crate::state::AppState;
15+
16+/// Who performed the action.
17+#[derive(Clone, Copy)]
18+pub enum Actor<'a> {
19+ /// A signed-in person, by their id.
20+ User(&'a str),
21+ /// Nobody is signed in: a failed sign-in, for example.
22+ Anonymous,
23+}
24+
25+/// Appends one entry. `target` is the kind and id of what the action was about; `data` is JSON
26+/// (`Value::Null` for none).
27+pub async fn record(
28+ cx: &Cx,
29+ actor: Actor<'_>,
30+ action: AuditAction,
31+ target: Option<(&str, &str)>,
32+ data: Value,
33+) {
34+ let state = app_context::<AppState>(cx);
35+ let ip = client_addr(cx).to_string();
36+ let (actor_id, actor_kind) = match actor {
37+ Actor::User(id) => (Some(id), "user"),
38+ Actor::Anonymous => (None, "anonymous"),
39+ };
40+ let data_text = (!data.is_null()).then(|| data.to_string());
41+ let entry = NewAudit {
42+ actor_id,
43+ actor_kind,
44+ action: action.as_str(),
45+ target_kind: target.map(|(kind, _)| kind),
46+ target_id: target.map(|(_, id)| id),
47+ ip: Some(ip.as_str()),
48+ data: data_text.as_deref(),
49+ };
50+ if let Err(error) = state.store.record_audit(&entry).await {
51+ tracing::error!(
52+ error = %error,
53+ action = action.as_str(),
54+ "audit entry was not written"
55+ );
56+ }
57+}
crates/im-web/src/auth.rsadded+470 -0
@@ -0,0 +1,470 @@
1+//! Sessions and the signed-in person: the session cookie, the guards every page calls, the CSRF
2+//! checks, the token that protects pre-session forms, the sealed pending-login cookie between the
3+//! password and the second factor, and the guard on every `next` redirect.
4+//!
5+//! The browser holds the session token in `__Host-im_session`. The database holds only its SHA-256,
6+//! so a leaked row cannot be replayed as a cookie. Every guard here answers before any side effect,
7+//! and a state-changing handler calls [`require_csrf`] or [`check_pre_csrf`] first.
8+
9+use std::time::{Duration, SystemTime, UNIX_EPOCH};
10+
11+use im_core::model::{Session, User, amr};
12+use im_core::secret;
13+use im_core::store::Store;
14+use im_core::store::sessions::NewSession;
15+use im_core::token::{constant_time_eq, generate_token, hash_token};
16+use im_core::totp;
17+use topcoat::Result;
18+use topcoat::context::{Cx, app_context};
19+use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
20+use topcoat::router::error::{forbidden, not_found, see_other};
21+use topcoat::router::request::{headers, uri};
22+
23+use crate::client_ip::client_addr;
24+use crate::live::Topic;
25+use crate::state::AppState;
26+
27+/// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-im_session`.
28+pub const SESSION_COOKIE: &str = "im_session";
29+
30+/// How long a session lives, from sign-in. Both the row and the cookie use it.
31+pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
32+
33+/// Logical name of the pre-session CSRF cookie, used by the pages that run before a session exists.
34+pub const PRE_CSRF_COOKIE: &str = "im_precsrf";
35+
36+/// How long the pre-session CSRF token stays valid in the browser.
37+const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60);
38+
39+/// Logical name of the pending-login cookie, set between the password and the second factor.
40+pub const PENDING_COOKIE: &str = "im_pending";
41+
42+/// How long a password-verified sign-in may wait for its second factor. Five minutes is long enough
43+/// to fetch a code from an app, and short enough that a stolen cookie is of little use.
44+pub const PENDING_TTL: Duration = Duration::from_secs(5 * 60);
45+
46+/// The longest `next` value accepted, in bytes.
47+const MAX_NEXT_LEN: usize = 2048;
48+
49+/// The signed-in person and the session they signed in with.
50+#[derive(Clone)]
51+pub struct Viewer {
52+ /// The account. Not disabled.
53+ pub user: User,
54+ /// The session the request presented. Its `csrf_token` checks forms.
55+ pub session: Session,
56+}
57+
58+/// The cookie jar that forces the `__Host-` prefix: `Secure`, `Path=/` and no `Domain`.
59+fn jar(cx: &Cx) -> impl Cookies + '_ {
60+ cookies(cx).override_prefix_host()
61+}
62+
63+/// The session the request presented, if it is still live.
64+async fn presented_session(cx: &Cx) -> Result<Option<Session>> {
65+ let Some(cookie) = jar(cx).get(SESSION_COOKIE) else {
66+ return Ok(None);
67+ };
68+ let store = &app_context::<AppState>(cx).store;
69+ Ok(store
70+ .session_by_token_hash(&hash_token(cookie.value()))
71+ .await?)
72+}
73+
74+/// The signed-in person, or `None` when there is no live session. Refreshes `last_seen` (at most
75+/// once in five minutes; the store decides).
76+pub async fn current_user(cx: &Cx) -> Result<Option<Viewer>> {
77+ let Some(session) = presented_session(cx).await? else {
78+ return Ok(None);
79+ };
80+ let store = &app_context::<AppState>(cx).store;
81+ let Some(user) = store
82+ .user_by_id(&session.user_id)
83+ .await?
84+ .filter(|user| !user.is_disabled())
85+ else {
86+ return Ok(None);
87+ };
88+ store.touch_session(&session.id).await?;
89+ Ok(Some(Viewer { user, session }))
90+}
91+
92+/// The signed-in person. Anyone else is sent to `/login`, with the page they asked for as `next`.
93+pub async fn require_user(cx: &Cx) -> Result<Viewer> {
94+ match current_user(cx).await? {
95+ Some(viewer) => Ok(viewer),
96+ None => {
97+ let path = uri(cx).path_and_query().map_or("/", |p| p.as_str());
98+ let target = format!("/login?next={}", percent_encode(path));
99+ Err(see_other(target).into())
100+ }
101+ }
102+}
103+
104+/// The signed-in administrator. A person who is not an administrator gets 404, the same answer as a
105+/// page that does not exist. An administrator without two-factor sign-in, while the policy requires
106+/// it, is sent to the security page instead.
107+///
108+/// Not every handler needs it yet; the admin pages that use it come after the account pages.
109+#[allow(dead_code)]
110+pub async fn require_admin(cx: &Cx) -> Result<Viewer> {
111+ let viewer = require_user(cx).await?;
112+ if !viewer.user.is_admin {
113+ return Err(not_found().into());
114+ }
115+ let state = app_context::<AppState>(cx);
116+ if state.config.policy.require_2fa_for_admins && !viewer.user.totp_enabled() {
117+ return Err(see_other("/account/security?notice=enrol").into());
118+ }
119+ Ok(viewer)
120+}
121+
122+/// The signed-in person, when the submitted `csrf` field matches their session. Returns 403 for a
123+/// wrong or missing token. Call it first in every state-changing handler.
124+pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> {
125+ let viewer = require_user(cx).await?;
126+ if check_csrf(&viewer.session, submitted) {
127+ Ok(viewer)
128+ } else {
129+ Err(forbidden().into())
130+ }
131+}
132+
133+/// True only when `submitted` is the session's CSRF token, compared in constant time. An empty
134+/// stored token never matches, not even an empty submission.
135+pub fn check_csrf(session: &Session, submitted: &str) -> bool {
136+ !session.csrf_token.is_empty()
137+ && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes())
138+}
139+
140+/// Creates a session for `user`, authenticated by `amr`, and sets the cookie.
141+///
142+/// A session the browser already presented for the same person is ended first, so a sign-in always
143+/// rotates the session id. The cap of the policy is applied inside the store, in the same write.
144+pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> {
145+ let state = app_context::<AppState>(cx);
146+ if let Some(old) = presented_session(cx)
147+ .await?
148+ .filter(|old| old.user_id == user.id)
149+ {
150+ state.store.end_session(&user.id, &old.id).await?;
151+ }
152+ let token = generate_token();
153+ let csrf = generate_token();
154+ let ip = client_addr(cx).to_string();
155+ let user_agent = user_agent(cx);
156+ let created = state
157+ .store
158+ .create_session(
159+ &NewSession {
160+ user_id: &user.id,
161+ token_hash: &hash_token(&token),
162+ csrf_token: &csrf,
163+ amr,
164+ ip: Some(ip.as_str()),
165+ user_agent: user_agent.as_deref(),
166+ ttl: SESSION_TTL,
167+ },
168+ state.config.policy.max_sessions,
169+ )
170+ .await?;
171+ // Sessions ended by the cap are not signed out elsewhere yet; their back-channel logout is queued
172+ // once the OpenID provider exists.
173+ state.live.bump(&Topic::Account(user.id.clone()));
174+ let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX));
175+ jar(cx).add(
176+ Cookie::build((SESSION_COOKIE, token))
177+ .path("/")
178+ .secure(true)
179+ .http_only(true)
180+ .same_site(SameSite::Lax)
181+ .max_age(max_age)
182+ .build(),
183+ );
184+ Ok(created.session)
185+}
186+
187+/// Ends the session of `viewer` and clears its cookie. Other sessions of the person are untouched.
188+pub async fn end_current_session(cx: &Cx, viewer: &Viewer) -> Result<()> {
189+ let state = app_context::<AppState>(cx);
190+ state
191+ .store
192+ .end_session(&viewer.user.id, &viewer.session.id)
193+ .await?;
194+ state.live.bump(&Topic::Account(viewer.user.id.clone()));
195+ jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
196+ Ok(())
197+}
198+
199+/// The pre-session CSRF token. Login, setup and the second-factor page use it, because no session
200+/// exists yet. An existing cookie is reused, so two open tabs both keep working.
201+pub fn pre_csrf_token(cx: &Cx) -> String {
202+ if let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) {
203+ let value = cookie.value();
204+ if !value.is_empty() {
205+ return value.to_owned();
206+ }
207+ }
208+ let token = generate_token();
209+ jar(cx).add(pre_csrf_cookie(token.clone()));
210+ token
211+}
212+
213+/// True only when the submitted `precsrf` equals the pre-session cookie. Call it before any other
214+/// work in a pre-session POST.
215+pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool {
216+ let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) else {
217+ return false;
218+ };
219+ !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes())
220+}
221+
222+/// Removes the pre-session CSRF cookie after a successful sign-in or setup.
223+pub fn clear_pre_csrf(cx: &Cx) {
224+ jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/"));
225+}
226+
227+fn pre_csrf_cookie(token: String) -> Cookie<'static> {
228+ Cookie::build((PRE_CSRF_COOKIE, token))
229+ .path("/")
230+ .secure(true)
231+ .http_only(true)
232+ .same_site(SameSite::Strict)
233+ .max_age(time::Duration::seconds(
234+ i64::try_from(PRE_CSRF_TTL.as_secs()).unwrap_or(i64::MAX),
235+ ))
236+ .build()
237+}
238+
239+/// A password-verified sign-in that waits for its second factor.
240+#[derive(Debug, Clone, PartialEq, Eq)]
241+pub struct Pending {
242+ /// The person who passed the password step.
243+ pub user_id: String,
244+ /// The authentication method so far. Always the password.
245+ pub amr: String,
246+ /// Where to go after the second factor. Checked again with [`safe_next`] before use.
247+ pub next: String,
248+}
249+
250+/// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance
251+/// key, so the browser can neither change the person nor extend the expiry.
252+pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> Result<()> {
253+ let expires = unix_now() + PENDING_TTL.as_secs();
254+ let payload = format!("{user_id}|{expires}|{}|{next}", amr::PASSWORD);
255+ let sealed = secret::seal(key, payload.as_bytes())?;
256+ let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0));
257+ jar(cx).add(
258+ Cookie::build((PENDING_COOKIE, sealed))
259+ .path("/")
260+ .secure(true)
261+ .http_only(true)
262+ .same_site(SameSite::Strict)
263+ .max_age(max_age)
264+ .build(),
265+ );
266+ Ok(())
267+}
268+
269+/// The pending sign-in, or `None` when the cookie is missing, tampered with, malformed or expired.
270+/// `next` is the field as it was set; the caller applies [`safe_next`].
271+pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<Pending> {
272+ let cookie = jar(cx).get(PENDING_COOKIE)?;
273+ let plain = secret::open(key, cookie.value()).ok()?;
274+ let text = String::from_utf8(plain).ok()?;
275+ // `next` comes last, so a `|` inside it cannot shift the other fields.
276+ let mut parts = text.splitn(4, '|');
277+ let user_id = parts.next()?;
278+ let expires: u64 = parts.next()?.parse().ok()?;
279+ let amr = parts.next()?;
280+ let next = parts.next()?;
281+ if unix_now() >= expires {
282+ return None;
283+ }
284+ Some(Pending {
285+ user_id: user_id.to_owned(),
286+ amr: amr.to_owned(),
287+ next: next.to_owned(),
288+ })
289+}
290+
291+/// Removes the pending-login cookie.
292+pub fn clear_pending_login(cx: &Cx) {
293+ jar(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/"));
294+}
295+
296+/// Checks one six-digit TOTP code for `user`, with the replay guard. True only when the code is
297+/// valid and its step was not used before. Returns false when two-factor sign-in is off.
298+pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) -> Result<bool> {
299+ let Some(sealed) = user.totp_secret_sealed.as_deref() else {
300+ return Ok(false);
301+ };
302+ if !user.totp_enabled() {
303+ return Ok(false);
304+ }
305+ let shared = secret::open(key, sealed)?;
306+ let last = user
307+ .totp_last_step
308+ .and_then(|step| u64::try_from(step).ok());
309+ match totp::verify(&shared, code, totp::step_for(unix_now()), last) {
310+ Some(step) => Ok(store.accept_totp_step(&user.id, step).await?),
311+ None => Ok(false),
312+ }
313+}
314+
315+/// Checks a second factor: six digits are a TOTP code, anything else is a recovery code, which is
316+/// spent on success. Returns the authentication method that was proved, or `None`.
317+pub async fn check_second_factor(
318+ store: &Store,
319+ key: &[u8; 32],
320+ user: &User,
321+ input: &str,
322+) -> Result<Option<&'static str>> {
323+ let input = input.trim();
324+ if input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()) {
325+ let ok = verify_totp(store, key, user, input).await?;
326+ return Ok(ok.then_some(amr::PASSWORD_TOTP));
327+ }
328+ if !user.totp_enabled() {
329+ return Ok(None);
330+ }
331+ let spent = store
332+ .consume_recovery_code(&user.id, &totp::recovery_code_hash(input))
333+ .await?;
334+ Ok(spent.then_some(amr::PASSWORD_RECOVERY))
335+}
336+
337+/// Where a person goes after signing in. An administrator without two-factor sign-in goes to the
338+/// security page to enrol it, while the policy requires that. Anyone else goes to `next`.
339+pub fn after_sign_in(state: &AppState, user: &User, next: &str) -> String {
340+ if user.is_admin && state.config.policy.require_2fa_for_admins && !user.totp_enabled() {
341+ "/account/security?notice=enrol".to_owned()
342+ } else {
343+ safe_next(Some(next)).to_owned()
344+ }
345+}
346+
347+/// Returns `next` only when it is a same-site path: one leading `/`, then no `/` or `\` that would
348+/// make a browser treat it as another host, no control characters, at most 2048 bytes. Anything else
349+/// is `/`.
350+pub fn safe_next(next: Option<&str>) -> &str {
351+ match next {
352+ Some(next) if is_local_path(next) => next,
353+ _ => "/",
354+ }
355+}
356+
357+fn is_local_path(path: &str) -> bool {
358+ path.len() <= MAX_NEXT_LEN
359+ && path.starts_with('/')
360+ && !path.starts_with("//")
361+ && !path.starts_with("/\\")
362+ && path.chars().all(|c| !c.is_control())
363+}
364+
365+/// Percent-encodes everything except RFC 3986 unreserved characters and `/`.
366+pub fn percent_encode(input: &str) -> String {
367+ let mut out = String::with_capacity(input.len());
368+ for byte in input.bytes() {
369+ match byte {
370+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
371+ out.push(char::from(byte));
372+ }
373+ _ => out.push_str(&format!("%{byte:02X}")),
374+ }
375+ }
376+ out
377+}
378+
379+/// The `User-Agent` of the request, truncated to 512 characters.
380+pub fn user_agent(cx: &Cx) -> Option<String> {
381+ headers(cx)
382+ .get(http::header::USER_AGENT)
383+ .and_then(|value| value.to_str().ok())
384+ .map(|text| text.chars().take(512).collect())
385+}
386+
387+/// Seconds since the Unix epoch. A clock before the epoch reads as 0, which only makes every
388+/// pending sign-in expire at once.
389+pub fn unix_now() -> u64 {
390+ SystemTime::now()
391+ .duration_since(UNIX_EPOCH)
392+ .map_or(0, |d| d.as_secs())
393+}
394+
395+#[cfg(test)]
396+mod tests {
397+ use super::*;
398+
399+ #[test]
400+ fn next_accepts_only_local_paths() {
401+ assert_eq!(safe_next(Some("/")), "/");
402+ assert_eq!(
403+ safe_next(Some("/account/security?x=1")),
404+ "/account/security?x=1"
405+ );
406+ assert_eq!(safe_next(None), "/");
407+ }
408+
409+ #[test]
410+ fn next_refuses_every_attack_string() {
411+ let overlong = format!("/{}", "a".repeat(MAX_NEXT_LEN));
412+ for bad in [
413+ "",
414+ "https://evil.example/",
415+ "http://evil.example",
416+ "//evil.example/",
417+ "/\\evil.example/",
418+ "\\\\evil.example",
419+ "\\/evil.example",
420+ "evil.example",
421+ "javascript:alert(1)",
422+ "/\n/evil.example",
423+ "/\r\nSet-Cookie: x=1",
424+ "/\t",
425+ "/\u{0}",
426+ " //evil.example",
427+ overlong.as_str(),
428+ ] {
429+ assert_eq!(safe_next(Some(bad)), "/", "accepted {bad:?}");
430+ }
431+ }
432+
433+ #[test]
434+ fn percent_encoding_keeps_slashes_and_encodes_the_rest() {
435+ assert_eq!(percent_encode("/a/b-c_d.e~f"), "/a/b-c_d.e~f");
436+ assert_eq!(percent_encode("/s?x=1&y=2"), "/s%3Fx%3D1%26y%3D2");
437+ }
438+
439+ #[tokio::test]
440+ async fn a_recovery_code_signs_in_once() {
441+ use crate::boot::test_state;
442+ let (_dir, state) = test_state().await;
443+ let user = state
444+ .store
445+ .create_user("ada@example.com", "Ada", "hash", false)
446+ .await
447+ .expect("user");
448+ let sealed = secret::seal(&state.key, &totp::new_secret()).expect("seal");
449+ let code = totp::new_recovery_code();
450+ state
451+ .store
452+ .enable_totp(&user.id, &sealed, 1, &[totp::recovery_code_hash(&code)])
453+ .await
454+ .expect("enable");
455+ let user = state
456+ .store
457+ .user_by_id(&user.id)
458+ .await
459+ .expect("query")
460+ .expect("user");
461+ let first = check_second_factor(&state.store, &state.key, &user, &code)
462+ .await
463+ .expect("check");
464+ assert_eq!(first, Some(amr::PASSWORD_RECOVERY));
465+ let second = check_second_factor(&state.store, &state.key, &user, &code)
466+ .await
467+ .expect("check");
468+ assert_eq!(second, None);
469+ }
470+}
crates/im-web/src/boot.rsmodified+5 -1
@@ -22,6 +22,7 @@ use crate::live::LiveHub;
22 use crate::pages::not_found::NotFoundLayer;22 use crate::pages::not_found::NotFoundLayer;
23 use crate::security::{self, SecurityHeaders};23 use crate::security::{self, SecurityHeaders};
24 use crate::state::AppState;24 use crate::state::AppState;
25+use crate::throttle::Throttle;
25 26
26 /// Name of the instance key file inside the data directory.27 /// Name of the instance key file inside the data directory.
27 const KEY_FILE: &str = "im.key";28 const KEY_FILE: &str = "im.key";
@@ -81,6 +82,7 @@ async fn open_state(config: Config) -> im_core::Result<AppState> {
81 store,82 store,
82 key: Arc::new(key),83 key: Arc::new(key),
83 live: Arc::new(LiveHub::default()),84 live: Arc::new(LiveHub::default()),
85+ throttle: Arc::new(Throttle::default()),
84 })86 })
85 }87 }
86 88
@@ -155,6 +157,7 @@ mod tests {
155 store,157 store,
156 key: Arc::new(key),158 key: Arc::new(key),
157 live: Arc::new(LiveHub::default()),159 live: Arc::new(LiveHub::default()),
160+ throttle: Arc::new(Throttle::default()),
158 };161 };
159 (dir, state)162 (dir, state)
160 }163 }
@@ -171,7 +174,8 @@ mod tests {
171 #[tokio::test]174 #[tokio::test]
172 async fn a_page_carries_the_content_security_policy_and_nosniff() {175 async fn a_page_carries_the_content_security_policy_and_nosniff() {
173 let (_dir, state) = test_state().await;176 let (_dir, state) = test_state().await;
174- let response = get(state, "/", Some("text/html")).await;177+ // No user yet, so the setup page answers.
178+ let response = get(state, "/setup", Some("text/html")).await;
175 assert_eq!(response.status(), 200);179 assert_eq!(response.status(), 200);
176 assert_eq!(180 assert_eq!(
177 response.headers()[CONTENT_SECURITY_POLICY]181 response.headers()[CONTENT_SECURITY_POLICY]
crates/im-web/src/client_ip.rsadded+124 -0
@@ -0,0 +1,124 @@
1+//! The client address of a request, for throttling and for the audit log.
2+//!
3+//! The TCP peer is the client, unless the peer is in `trusted_proxies`. Only then is
4+//! `X-Forwarded-For` read: from the right, skipping trusted hops, the first untrusted address is the
5+//! client. Any unusable header falls back to the peer, so a spoofed header from an untrusted peer is
6+//! never believed. IPv6 is bucketed by /64 for throttling, so one client holding a /64 cannot
7+//! multiply its attempt budget.
8+
9+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
10+
11+use topcoat::context::{Cx, app_context};
12+use topcoat::router::IpNet;
13+use topcoat::router::request::{headers, remote_addr};
14+
15+use crate::state::AppState;
16+
17+/// The header a trusted proxy appends the client address to.
18+const FORWARDED_FOR: &str = "x-forwarded-for";
19+
20+/// The client address for throttling: the exact address, with IPv6 bucketed by /64.
21+pub fn client_ip(cx: &Cx) -> IpAddr {
22+ bucket(client_addr(cx))
23+}
24+
25+/// The exact client address of this request, normalised but not bucketed. Used for the audit log
26+/// and the session list. A request without a peer address (not possible over TCP) maps to the
27+/// unspecified address.
28+pub fn client_addr(cx: &Cx) -> IpAddr {
29+ let trusted = &app_context::<AppState>(cx).config.trusted_proxies;
30+ let peer = remote_addr(cx).map(|addr| addr.ip());
31+ let forwarded = headers(cx)
32+ .get_all(FORWARDED_FOR)
33+ .iter()
34+ .filter_map(|value| value.to_str().ok())
35+ .collect::<Vec<_>>()
36+ .join(",");
37+ resolve_addr(peer, &forwarded, trusted)
38+}
39+
40+/// Pure form of [`client_addr`]. `forwarded` is the combined `X-Forwarded-For` value, or empty.
41+pub fn resolve_addr(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {
42+ let Some(peer) = peer.map(normalize) else {
43+ return IpAddr::V4(Ipv4Addr::UNSPECIFIED);
44+ };
45+ if !is_trusted(peer, trusted) {
46+ return peer;
47+ }
48+ for entry in forwarded.rsplit(',') {
49+ let Ok(ip) = entry.trim().parse::<IpAddr>() else {
50+ return peer;
51+ };
52+ let ip = normalize(ip);
53+ if !is_trusted(ip, trusted) {
54+ return ip;
55+ }
56+ }
57+ peer
58+}
59+
60+fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool {
61+ trusted.iter().any(|net| net.contains(&ip))
62+}
63+
64+/// IPv4-mapped IPv6 addresses are reported as the IPv4 address they carry.
65+fn normalize(ip: IpAddr) -> IpAddr {
66+ match ip {
67+ IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4),
68+ IpAddr::V4(_) => ip,
69+ }
70+}
71+
72+/// Clears the host half of an IPv6 address, so every address of a /64 shares one bucket.
73+fn bucket(ip: IpAddr) -> IpAddr {
74+ match ip {
75+ IpAddr::V4(_) => ip,
76+ IpAddr::V6(v6) => {
77+ let mut octets = v6.octets();
78+ octets[8..].fill(0);
79+ IpAddr::V6(Ipv6Addr::from(octets))
80+ }
81+ }
82+}
83+
84+#[cfg(test)]
85+mod tests {
86+ use super::*;
87+
88+ fn ip(text: &str) -> IpAddr {
89+ text.parse().unwrap()
90+ }
91+
92+ #[test]
93+ fn forwarded_for_counts_only_from_a_trusted_peer() {
94+ let trusted: [IpNet; 1] = ["127.0.0.0/8".parse().unwrap()];
95+ // An untrusted peer's header is ignored. 127.0.0.0/8 is the trusted proxy range.
96+ assert_eq!(
97+ resolve_addr(Some(ip("203.0.113.9")), "198.51.100.7", &trusted),
98+ ip("203.0.113.9")
99+ );
100+ // A trusted proxy's header names the client, skipping trusted hops from the right.
101+ assert_eq!(
102+ resolve_addr(
103+ Some(ip("127.0.0.1")),
104+ "1.2.3.4, 198.51.100.7, 127.0.0.2",
105+ &trusted
106+ ),
107+ ip("198.51.100.7")
108+ );
109+ // An unusable header falls back to the peer.
110+ assert_eq!(
111+ resolve_addr(Some(ip("127.0.0.1")), "garbage", &trusted),
112+ ip("127.0.0.1")
113+ );
114+ }
115+
116+ #[test]
117+ fn ipv6_is_bucketed_by_slash_64_and_mapped_addresses_are_ipv4() {
118+ let a = bucket(ip("2001:db8:1:2:aaaa::1"));
119+ assert_eq!(a, bucket(ip("2001:db8:1:2:bbbb::9")));
120+ assert_ne!(a, bucket(ip("2001:db8:1:3::1")));
121+ assert_eq!(a, ip("2001:db8:1:2::"));
122+ assert_eq!(normalize(ip("::ffff:192.0.2.5")), ip("192.0.2.5"));
123+ }
124+}
crates/im-web/src/i18n/account.rsadded+415 -0
@@ -0,0 +1,415 @@
1+//! Strings of the accounts area: setup, sign-in, the two-factor step, the account home, security
2+//! and sessions. Each key has an English and a Turkish text in [`text`]; the match is exhaustive,
3+//! so a key without a translation does not compile.
4+//!
5+//! Sentences with values go through the small helpers below, not through concatenation in views,
6+//! because word order differs between the two languages.
7+
8+use super::Lang;
9+
10+/// One variant per phrase of the accounts area.
11+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12+pub enum Txt {
13+ /// The field label of an email address.
14+ Email,
15+ /// The field label of a display name.
16+ Name,
17+ /// The field label of a password.
18+ Password,
19+ /// The field label of a one-time code.
20+ Code,
21+ /// The field label of the current password.
22+ CurrentPassword,
23+ /// The field label of a new password.
24+ NewPassword,
25+ /// The field label of the repeated new password.
26+ NewPasswordAgain,
27+ /// Hint under the password field of setup and password change.
28+ PasswordHint,
29+ /// Shown while the throttle holds an account or an address back.
30+ ErrThrottled,
31+ /// The password of the current account is wrong.
32+ ErrWrongPassword,
33+ /// The two new passwords do not match.
34+ ErrPasswordsDiffer,
35+ /// The new password is the current one.
36+ ErrPasswordSame,
37+ /// The new password contains the email address or a word of the name.
38+ ErrPasswordIdentity,
39+ /// The name is empty or too long.
40+ ErrNameInvalid,
41+ /// The email address does not have a valid shape.
42+ ErrEmailInvalid,
43+ /// A second-factor code is wrong or already used.
44+ ErrCodeInvalid,
45+ /// A second-factor code is required and was not given.
46+ ErrCodeMissing,
47+ /// The enrolment was not kept (it expired or was replaced); the person must start again.
48+ ErrNoPending,
49+ /// The sign-in failed. Used for unknown email, wrong password and disabled account alike.
50+ ErrInvalidLogin,
51+ /// The title of the first-run setup page.
52+ SetupTitle,
53+ /// The sentence under the setup title.
54+ SetupIntro,
55+ /// The button that creates the first administrator.
56+ CreateAdmin,
57+ /// The button that signs in.
58+ SignIn,
59+ /// The button and menu item that end the session.
60+ SignOut,
61+ /// The title of the second-factor page.
62+ TwoFactorTitle,
63+ /// The sentence under the second-factor title.
64+ TwoFactorIntro,
65+ /// The button that checks the code.
66+ Verify,
67+ /// The title of the account home.
68+ HomeTitle,
69+ /// The label of the two-factor status on the account home.
70+ TwoFactorStatus,
71+ /// The status word for two-factor on.
72+ On,
73+ /// The status word for two-factor off.
74+ Off,
75+ /// The title of the security page, and the menu item that opens it.
76+ SecurityTitle,
77+ /// The account home link text that opens the security page.
78+ SecurityLinkText,
79+ /// The title of the sessions page, and the menu item that opens it.
80+ SessionsTitle,
81+ /// The account home link text that opens the sessions page.
82+ SessionsLinkText,
83+ /// The title of the administration section on the account home.
84+ AdminArea,
85+ /// The account home link text that opens the administration section.
86+ AdminLinkText,
87+ /// The heading of the password section.
88+ PasswordSection,
89+ /// The button that changes the password.
90+ ChangePassword,
91+ /// Says that changing the password signs out the other sessions.
92+ PasswordHelp,
93+ /// The heading of the two-factor section.
94+ TwoFactorSection,
95+ /// The status text when two-factor sign-in is on.
96+ TwoFactorOnText,
97+ /// The status text when two-factor sign-in is off.
98+ TwoFactorOffText,
99+ /// The heading above a secret that waits for its first code.
100+ PendingTitle,
101+ /// The instructions above a secret that waits for its first code.
102+ PendingHelp,
103+ /// The label of the base32 secret.
104+ SecretKey,
105+ /// The label of the otpauth link.
106+ SetupLink,
107+ /// The alternative text of the QR code.
108+ QrAlt,
109+ /// The button that turns two-factor sign-in on.
110+ TurnOn,
111+ /// The heading of the section that replaces the authenticator of an active account.
112+ ReplaceTitle,
113+ /// The instructions of the replacement section.
114+ ReplaceHelp,
115+ /// The button that starts a replacement enrolment.
116+ ReplaceButton,
117+ /// The label of the code typed from the authenticator app.
118+ CodeFromApp,
119+ /// The heading of the turn-off section.
120+ DisableTitle,
121+ /// The instructions of the turn-off section.
122+ DisableHelp,
123+ /// The button that turns two-factor sign-in off.
124+ TurnOff,
125+ /// The heading of the recovery codes section.
126+ RecoveryTitle,
127+ /// Explains what the recovery codes are for.
128+ RecoveryHelp,
129+ /// The button that issues new recovery codes.
130+ RegenerateCodes,
131+ /// Says that issuing new codes ends the old ones.
132+ RegenerateHelp,
133+ /// The heading above a freshly issued set of codes.
134+ NewCodesTitle,
135+ /// The warning above a freshly issued set of codes.
136+ CodesShownOnce,
137+ /// Notice: the password was changed.
138+ SavedPassword,
139+ /// Notice: two-factor sign-in was turned on.
140+ Saved2faOn,
141+ /// Notice: two-factor sign-in was turned off.
142+ Saved2faOff,
143+ /// Notice: one session was signed out.
144+ SavedSession,
145+ /// Notice: the other sessions were signed out.
146+ SavedOthers,
147+ /// Notice on the security page: an administrator must enrol.
148+ EnrolSecurityNotice,
149+ /// The sentence at the top of the sessions page.
150+ SessionsIntro,
151+ /// The badge of the session in use.
152+ ThisSession,
153+ /// The label of the sign-in time.
154+ SignedInAt,
155+ /// The label of the last use.
156+ LastSeen,
157+ /// The label of the address a session was created from.
158+ AddressLabel,
159+ /// The button that ends one session.
160+ SignOutSession,
161+ /// The button that ends every other session.
162+ SignOutOthers,
163+ /// Shown when the person has no other session.
164+ NoOthers,
165+ /// The browser name when the user agent is missing or unknown.
166+ UnknownBrowser,
167+ /// The system name when the user agent is missing or unknown.
168+ UnknownSystem,
169+ /// The label of the account menu.
170+ AccountMenu,
171+}
172+
173+/// The text of `key` in `lang`.
174+pub fn text(lang: Lang, key: Txt) -> &'static str {
175+ match (key, lang) {
176+ (Txt::Email, Lang::En) => "Email address",
177+ (Txt::Email, Lang::Tr) => "E-posta adresi",
178+ (Txt::Name, Lang::En) => "Name",
179+ (Txt::Name, Lang::Tr) => "Ad soyad",
180+ (Txt::Password, Lang::En) => "Password",
181+ (Txt::Password, Lang::Tr) => "Parola",
182+ (Txt::Code, Lang::En) => "Code",
183+ (Txt::Code, Lang::Tr) => "Kod",
184+ (Txt::CurrentPassword, Lang::En) => "Current password",
185+ (Txt::CurrentPassword, Lang::Tr) => "Mevcut parola",
186+ (Txt::NewPassword, Lang::En) => "New password",
187+ (Txt::NewPassword, Lang::Tr) => "Yeni parola",
188+ (Txt::NewPasswordAgain, Lang::En) => "New password, again",
189+ (Txt::NewPasswordAgain, Lang::Tr) => "Yeni parola, tekrar",
190+ (Txt::PasswordHint, Lang::En) => {
191+ "At least 10 characters. Do not use your name or your email address."
192+ }
193+ (Txt::PasswordHint, Lang::Tr) => {
194+ "En az 10 karakter. Adınızı ya da e-posta adresinizi kullanmayın."
195+ }
196+ (Txt::ErrThrottled, Lang::En) => "Too many attempts. Wait a few minutes, then try again.",
197+ (Txt::ErrThrottled, Lang::Tr) => {
198+ "Çok fazla deneme yapıldı. Birkaç dakika bekleyip yeniden deneyin."
199+ }
200+ (Txt::ErrWrongPassword, Lang::En) => "The password is wrong.",
201+ (Txt::ErrWrongPassword, Lang::Tr) => "Parola yanlış.",
202+ (Txt::ErrPasswordsDiffer, Lang::En) => "The two new passwords do not match.",
203+ (Txt::ErrPasswordsDiffer, Lang::Tr) => "Yeni parolalar eşleşmiyor.",
204+ (Txt::ErrPasswordSame, Lang::En) => "The new password must differ from the current one.",
205+ (Txt::ErrPasswordSame, Lang::Tr) => "Yeni parola, mevcut parolanızdan farklı olmalıdır.",
206+ (Txt::ErrPasswordIdentity, Lang::En) => {
207+ "The password must not contain your email address or your name."
208+ }
209+ (Txt::ErrPasswordIdentity, Lang::Tr) => {
210+ "Parola e-posta adresinizi ya da adınızı içermemelidir."
211+ }
212+ (Txt::ErrNameInvalid, Lang::En) => "Enter your name, at most 100 characters.",
213+ (Txt::ErrNameInvalid, Lang::Tr) => "Adınızı girin, en fazla 100 karakter.",
214+ (Txt::ErrEmailInvalid, Lang::En) => "Enter a valid email address.",
215+ (Txt::ErrEmailInvalid, Lang::Tr) => "Geçerli bir e-posta adresi girin.",
216+ (Txt::ErrCodeInvalid, Lang::En) => "The code is wrong, or it was already used.",
217+ (Txt::ErrCodeInvalid, Lang::Tr) => "Kod yanlış ya da daha önce kullanılmış.",
218+ (Txt::ErrCodeMissing, Lang::En) => "Enter the code from your authenticator app.",
219+ (Txt::ErrCodeMissing, Lang::Tr) => "Kimlik doğrulama uygulamanızdaki kodu girin.",
220+ (Txt::ErrNoPending, Lang::En) => "The setup was not kept. Start the setup again.",
221+ (Txt::ErrNoPending, Lang::Tr) => "Kurulum saklanmadı. Kurulumu yeniden başlatın.",
222+ (Txt::ErrInvalidLogin, Lang::En) => "The email address or the password is wrong.",
223+ (Txt::ErrInvalidLogin, Lang::Tr) => "E-posta adresi ya da parola yanlış.",
224+ (Txt::SetupTitle, Lang::En) => "Set up im",
225+ (Txt::SetupTitle, Lang::Tr) => "im kurulumu",
226+ (Txt::SetupIntro, Lang::En) => {
227+ "Create the first administrator. This page closes as soon as an account exists."
228+ }
229+ (Txt::SetupIntro, Lang::Tr) => {
230+ "İlk yöneticiyi oluşturun. Bir hesap oluşturulduğunda bu sayfa kapanır."
231+ }
232+ (Txt::CreateAdmin, Lang::En) => "Create administrator",
233+ (Txt::CreateAdmin, Lang::Tr) => "Yöneticiyi oluştur",
234+ (Txt::SignIn, Lang::En) => "Sign in",
235+ (Txt::SignIn, Lang::Tr) => "Oturum aç",
236+ (Txt::SignOut, Lang::En) => "Sign out",
237+ (Txt::SignOut, Lang::Tr) => "Oturumu kapat",
238+ (Txt::TwoFactorTitle, Lang::En) => "Two-step sign-in",
239+ (Txt::TwoFactorTitle, Lang::Tr) => "İki adımlı giriş",
240+ (Txt::TwoFactorIntro, Lang::En) => {
241+ "Enter the 6-digit code from your authenticator app, or one of your recovery codes."
242+ }
243+ (Txt::TwoFactorIntro, Lang::Tr) => {
244+ "Kimlik doğrulama uygulamanızdaki 6 haneli kodu ya da kurtarma kodlarınızdan birini girin."
245+ }
246+ (Txt::Verify, Lang::En) => "Verify",
247+ (Txt::Verify, Lang::Tr) => "Doğrula",
248+ (Txt::HomeTitle, Lang::En) => "Your account",
249+ (Txt::HomeTitle, Lang::Tr) => "Hesabınız",
250+ (Txt::TwoFactorStatus, Lang::En) => "Two-step sign-in",
251+ (Txt::TwoFactorStatus, Lang::Tr) => "İki adımlı giriş",
252+ (Txt::On, Lang::En) => "On",
253+ (Txt::On, Lang::Tr) => "Açık",
254+ (Txt::Off, Lang::En) => "Off",
255+ (Txt::Off, Lang::Tr) => "Kapalı",
256+ (Txt::SecurityTitle, Lang::En) => "Security",
257+ (Txt::SecurityTitle, Lang::Tr) => "Güvenlik",
258+ (Txt::SecurityLinkText, Lang::En) => "Password and two-step sign-in",
259+ (Txt::SecurityLinkText, Lang::Tr) => "Parola ve iki adımlı giriş",
260+ (Txt::SessionsTitle, Lang::En) => "Sessions",
261+ (Txt::SessionsTitle, Lang::Tr) => "Oturumlar",
262+ (Txt::SessionsLinkText, Lang::En) => "Where you are signed in",
263+ (Txt::SessionsLinkText, Lang::Tr) => "Oturumunuzun açık olduğu yerler",
264+ (Txt::AdminArea, Lang::En) => "Administration",
265+ (Txt::AdminArea, Lang::Tr) => "Yönetim",
266+ (Txt::AdminLinkText, Lang::En) => "Users, settings and the audit log",
267+ (Txt::AdminLinkText, Lang::Tr) => "Kullanıcılar, ayarlar ve denetim günlüğü",
268+ (Txt::PasswordSection, Lang::En) => "Password",
269+ (Txt::PasswordSection, Lang::Tr) => "Parola",
270+ (Txt::ChangePassword, Lang::En) => "Change password",
271+ (Txt::ChangePassword, Lang::Tr) => "Parolayı değiştir",
272+ (Txt::PasswordHelp, Lang::En) => "Changing it signs out your other sessions.",
273+ (Txt::PasswordHelp, Lang::Tr) => "Parolayı değiştirmek diğer oturumlarınızı kapatır.",
274+ (Txt::TwoFactorSection, Lang::En) => "Two-step sign-in",
275+ (Txt::TwoFactorSection, Lang::Tr) => "İki adımlı giriş",
276+ (Txt::TwoFactorOnText, Lang::En) => {
277+ "On. Signing in asks for a code from your authenticator app."
278+ }
279+ (Txt::TwoFactorOnText, Lang::Tr) => {
280+ "Açık. Girişte kimlik doğrulama uygulamanızdan bir kod istenir."
281+ }
282+ (Txt::TwoFactorOffText, Lang::En) => "Off. Signing in needs only your password.",
283+ (Txt::TwoFactorOffText, Lang::Tr) => "Kapalı. Girişte yalnızca parolanız istenir.",
284+ (Txt::PendingTitle, Lang::En) => "Add this key to your authenticator app",
285+ (Txt::PendingTitle, Lang::Tr) => "Bu anahtarı kimlik doğrulama uygulamanıza ekleyin",
286+ (Txt::PendingHelp, Lang::En) => {
287+ "Scan the code, or type the key by hand. Then enter the 6-digit code the app shows, to turn two-step sign-in on."
288+ }
289+ (Txt::PendingHelp, Lang::Tr) => {
290+ "Kodu tarayın ya da anahtarı elle yazın. Ardından iki adımlı girişi açmak için uygulamanın gösterdiği 6 haneli kodu girin."
291+ }
292+ (Txt::SecretKey, Lang::En) => "Key",
293+ (Txt::SecretKey, Lang::Tr) => "Anahtar",
294+ (Txt::SetupLink, Lang::En) => "Setup link",
295+ (Txt::SetupLink, Lang::Tr) => "Kurulum bağlantısı",
296+ (Txt::QrAlt, Lang::En) => "QR code for your authenticator app",
297+ (Txt::QrAlt, Lang::Tr) => "Kimlik doğrulama uygulamanız için QR kodu",
298+ (Txt::TurnOn, Lang::En) => "Turn on",
299+ (Txt::TurnOn, Lang::Tr) => "Aç",
300+ (Txt::ReplaceTitle, Lang::En) => "Set up a new authenticator",
301+ (Txt::ReplaceTitle, Lang::Tr) => "Yeni kimlik doğrulama uygulaması kur",
302+ (Txt::ReplaceHelp, Lang::En) => {
303+ "Enter a current code. Your present setup keeps working until the new one is confirmed."
304+ }
305+ (Txt::ReplaceHelp, Lang::Tr) => {
306+ "Güncel bir kod girin. Yenisi onaylanana kadar mevcut kurulumunuz çalışmaya devam eder."
307+ }
308+ (Txt::ReplaceButton, Lang::En) => "Start a new setup",
309+ (Txt::ReplaceButton, Lang::Tr) => "Yeni kurulumu başlat",
310+ (Txt::CodeFromApp, Lang::En) => "Code from the app",
311+ (Txt::CodeFromApp, Lang::Tr) => "Uygulamadaki kod",
312+ (Txt::DisableTitle, Lang::En) => "Turn off two-step sign-in",
313+ (Txt::DisableTitle, Lang::Tr) => "İki adımlı girişi kapat",
314+ (Txt::DisableHelp, Lang::En) => "Enter your password and a current code.",
315+ (Txt::DisableHelp, Lang::Tr) => "Parolanızı ve güncel bir kodu girin.",
316+ (Txt::TurnOff, Lang::En) => "Turn off",
317+ (Txt::TurnOff, Lang::Tr) => "Kapat",
318+ (Txt::RecoveryTitle, Lang::En) => "Recovery codes",
319+ (Txt::RecoveryTitle, Lang::Tr) => "Kurtarma kodları",
320+ (Txt::RecoveryHelp, Lang::En) => {
321+ "When you cannot use your app, each code signs you in once. Keep them somewhere safe."
322+ }
323+ (Txt::RecoveryHelp, Lang::Tr) => {
324+ "Uygulamanızı kullanamadığınızda her kod sizi bir kez giriş yaptırır. Güvenli bir yerde saklayın."
325+ }
326+ (Txt::RegenerateCodes, Lang::En) => "Get new recovery codes",
327+ (Txt::RegenerateCodes, Lang::Tr) => "Yeni kurtarma kodları al",
328+ (Txt::RegenerateHelp, Lang::En) => "The codes you have now stop working.",
329+ (Txt::RegenerateHelp, Lang::Tr) => "Şu anki kodlarınız çalışmaz hâle gelir.",
330+ (Txt::NewCodesTitle, Lang::En) => "Your new recovery codes",
331+ (Txt::NewCodesTitle, Lang::Tr) => "Yeni kurtarma kodlarınız",
332+ (Txt::CodesShownOnce, Lang::En) => "Save these now. They are not shown again.",
333+ (Txt::CodesShownOnce, Lang::Tr) => "Bunları şimdi kaydedin. Bir daha gösterilmez.",
334+ (Txt::SavedPassword, Lang::En) => "Your password was changed.",
335+ (Txt::SavedPassword, Lang::Tr) => "Parolanız değiştirildi.",
336+ (Txt::Saved2faOn, Lang::En) => "Two-step sign-in is on.",
337+ (Txt::Saved2faOn, Lang::Tr) => "İki adımlı giriş açıldı.",
338+ (Txt::Saved2faOff, Lang::En) => "Two-step sign-in is off.",
339+ (Txt::Saved2faOff, Lang::Tr) => "İki adımlı giriş kapatıldı.",
340+ (Txt::SavedSession, Lang::En) => "The session was signed out.",
341+ (Txt::SavedSession, Lang::Tr) => "Oturum kapatıldı.",
342+ (Txt::SavedOthers, Lang::En) => "The other sessions were signed out.",
343+ (Txt::SavedOthers, Lang::Tr) => "Diğer oturumlar kapatıldı.",
344+ (Txt::EnrolSecurityNotice, Lang::En) => {
345+ "Administrators must turn on two-step sign-in before they can use the administration pages."
346+ }
347+ (Txt::EnrolSecurityNotice, Lang::Tr) => {
348+ "Yöneticiler yönetim sayfalarını kullanmadan önce iki adımlı girişi açmalıdır."
349+ }
350+ (Txt::SessionsIntro, Lang::En) => "Browsers and devices where you are signed in.",
351+ (Txt::SessionsIntro, Lang::Tr) => "Oturumunuzun açık olduğu tarayıcılar ve cihazlar.",
352+ (Txt::ThisSession, Lang::En) => "This session",
353+ (Txt::ThisSession, Lang::Tr) => "Bu oturum",
354+ (Txt::SignedInAt, Lang::En) => "Signed in",
355+ (Txt::SignedInAt, Lang::Tr) => "Oturum açıldı",
356+ (Txt::LastSeen, Lang::En) => "Last seen",
357+ (Txt::LastSeen, Lang::Tr) => "Son görülme",
358+ (Txt::AddressLabel, Lang::En) => "Address",
359+ (Txt::AddressLabel, Lang::Tr) => "Adres",
360+ (Txt::SignOutSession, Lang::En) => "Sign out",
361+ (Txt::SignOutSession, Lang::Tr) => "Kapat",
362+ (Txt::SignOutOthers, Lang::En) => "Sign out all other sessions",
363+ (Txt::SignOutOthers, Lang::Tr) => "Diğer tüm oturumları kapat",
364+ (Txt::NoOthers, Lang::En) => "You have no other sessions.",
365+ (Txt::NoOthers, Lang::Tr) => "Başka bir oturumunuz yok.",
366+ (Txt::UnknownBrowser, Lang::En) => "Unknown browser",
367+ (Txt::UnknownBrowser, Lang::Tr) => "Bilinmeyen tarayıcı",
368+ (Txt::UnknownSystem, Lang::En) => "unknown system",
369+ (Txt::UnknownSystem, Lang::Tr) => "bilinmeyen sistem",
370+ (Txt::AccountMenu, Lang::En) => "Account menu",
371+ (Txt::AccountMenu, Lang::Tr) => "Hesap menüsü",
372+ }
373+}
374+
375+/// "The password must be at least 10 characters."
376+pub fn password_too_short(lang: Lang, min: usize) -> String {
377+ match lang {
378+ Lang::En => format!("The password must be at least {min} characters."),
379+ Lang::Tr => format!("Parola en az {min} karakter olmalıdır."),
380+ }
381+}
382+
383+/// "The password must be at most 256 characters."
384+pub fn password_too_long(lang: Lang, max: usize) -> String {
385+ match lang {
386+ Lang::En => format!("The password must be at most {max} characters."),
387+ Lang::Tr => format!("Parola en fazla {max} karakter olmalıdır."),
388+ }
389+}
390+
391+/// "3 unused recovery codes are left."
392+pub fn recovery_left(lang: Lang, unused: u64) -> String {
393+ match lang {
394+ Lang::En => format!("{unused} unused recovery codes are left."),
395+ Lang::Tr => format!("{unused} kullanılmamış kurtarma kodu kaldı."),
396+ }
397+}
398+
399+/// The name of a device for a session list: "Chrome on Linux", or "Chrome (Linux)" in Turkish.
400+pub fn device_label(lang: Lang, browser: &str, system: &str) -> String {
401+ match lang {
402+ Lang::En => format!("{browser} on {system}"),
403+ Lang::Tr => format!("{browser} ({system})"),
404+ }
405+}
406+
407+/// The message for a password that the policy refuses.
408+pub fn policy_problem(lang: Lang, violation: im_core::password::PolicyViolation) -> String {
409+ use im_core::password::{MAX_PASSWORD_CHARS, MIN_PASSWORD_CHARS, PolicyViolation};
410+ match violation {
411+ PolicyViolation::TooShort => password_too_short(lang, MIN_PASSWORD_CHARS),
412+ PolicyViolation::TooLong => password_too_long(lang, MAX_PASSWORD_CHARS),
413+ PolicyViolation::ContainsIdentity => text(lang, Txt::ErrPasswordIdentity).to_owned(),
414+ }
415+}
crates/im-web/src/i18n/mod.rsmodified+1 -0
@@ -7,6 +7,7 @@
7 //! This module decides the language. It does not format sentences with values; those get small7 //! This module decides the language. It does not format sentences with values; those get small
8 //! helper functions next to their keys.8 //! helper functions next to their keys.
9 9
10+pub mod account;
10 pub mod shell;11 pub mod shell;
11 12
12 use topcoat::context::Cx;13 use topcoat::context::Cx;
crates/im-web/src/i18n/shell.rsmodified+0 -12
@@ -10,14 +10,10 @@ pub enum K {
10 Admin,10 Admin,
11 /// The link on the 404 page that returns to the start page.11 /// The link on the 404 page that returns to the start page.
12 BackHome,12 BackHome,
13- /// The title of the start page.
14- ImIsRunning,
15 /// The sentence under the 404 title.13 /// The sentence under the 404 title.
16 NotFoundBody,14 NotFoundBody,
17 /// The title of the 404 page.15 /// The title of the 404 page.
18 NotFoundTitle,16 NotFoundTitle,
19- /// The sentence on the start page.
20- RunningBody,
21 /// The bar shown while the server cannot be reached.17 /// The bar shown while the server cannot be reached.
22 ServerRestarting,18 ServerRestarting,
23 /// The accessible name of the service switcher.19 /// The accessible name of the service switcher.
@@ -33,18 +29,10 @@ pub fn t(lang: Lang, key: K) -> &'static str {
33 (K::Admin, Lang::Tr) => "Yönetici",29 (K::Admin, Lang::Tr) => "Yönetici",
34 (K::BackHome, Lang::En) => "Back to the start",30 (K::BackHome, Lang::En) => "Back to the start",
35 (K::BackHome, Lang::Tr) => "Başlangıca dön",31 (K::BackHome, Lang::Tr) => "Başlangıca dön",
36- (K::ImIsRunning, Lang::En) => "im is running",
37- (K::ImIsRunning, Lang::Tr) => "im çalışıyor",
38 (K::NotFoundBody, Lang::En) => "The page does not exist, or you do not have access to it.",32 (K::NotFoundBody, Lang::En) => "The page does not exist, or you do not have access to it.",
39 (K::NotFoundBody, Lang::Tr) => "Sayfa yok ya da bu sayfayı görme izniniz yok.",33 (K::NotFoundBody, Lang::Tr) => "Sayfa yok ya da bu sayfayı görme izniniz yok.",
40 (K::NotFoundTitle, Lang::En) => "Page not found",34 (K::NotFoundTitle, Lang::En) => "Page not found",
41 (K::NotFoundTitle, Lang::Tr) => "Sayfa bulunamadı",35 (K::NotFoundTitle, Lang::Tr) => "Sayfa bulunamadı",
42- (K::RunningBody, Lang::En) => {
43- "The server answers requests. Sign-in is not part of this build yet."
44- }
45- (K::RunningBody, Lang::Tr) => {
46- "Sunucu istekleri yanıtlıyor. Oturum açma bu sürümde henüz yok."
47- }
48 (K::ServerRestarting, Lang::En) => "The server is restarting. Reconnecting…",36 (K::ServerRestarting, Lang::En) => "The server is restarting. Reconnecting…",
49 (K::ServerRestarting, Lang::Tr) => "Sunucu yeniden başlatılıyor. Yeniden bağlanılıyor…",37 (K::ServerRestarting, Lang::Tr) => "Sunucu yeniden başlatılıyor. Yeniden bağlanılıyor…",
50 (K::Services, Lang::En) => "Services",38 (K::Services, Lang::En) => "Services",
crates/im-web/src/live.rsmodified+54 -7
@@ -9,10 +9,10 @@
9 //! The hub is not a queue and not an authorisation check. Each route that opens a stream9 //! The hub is not a queue and not an authorisation check. Each route that opens a stream
10 //! authenticates and authorises first, then calls [`stream_changes`].10 //! authenticates and authorises first, then calls [`stream_changes`].
11 //!11 //!
12-//! Nothing bumps a topic or opens [`stream_changes`] yet, so the items here are kept ahead of the12+//! The account stream (`/-/alive`) is the only user of the hub so far. [`stream_changes`] waits for
13-//! pages that use them.13+//! the admin pages that follow a list.
14 14
15-#![allow(dead_code)] // The hub and its topics wait for the pages that bump and follow them.15+#![allow(dead_code)] // `stream_changes` and `Topic::AdminAudit` wait for the admin pages.
16 16
17 use std::collections::HashMap;17 use std::collections::HashMap;
18 use std::future::Future;18 use std::future::Future;
@@ -20,13 +20,17 @@ use std::sync::{Mutex, MutexGuard, PoisonError};
20 use std::time::Duration;20 use std::time::Duration;
21 21
22 use futures_util::{Stream, StreamExt, future::select_all, stream};22 use futures_util::{Stream, StreamExt, future::select_all, stream};
23+use im_core::store::Store;
23 use tokio::sync::watch;24 use tokio::sync::watch;
24 use topcoat::Result;25 use topcoat::Result;
25-use topcoat::context::Cx;26+use topcoat::context::{Cx, app_context};
26 use topcoat::router::content::sse::{Event, KeepAlive, Sse};27 use topcoat::router::content::sse::{Event, KeepAlive, Sse};
27 use topcoat::router::response::{IntoResponse, Response};28 use topcoat::router::response::{IntoResponse, Response};
28 use topcoat::router::{HeaderValue, route};29 use topcoat::router::{HeaderValue, route};
29 30
31+use crate::auth::current_user;
32+use crate::state::AppState;
33+
30 /// How long a client waits before it reconnects when a stream ends. Sent once, at the start.34 /// How long a client waits before it reconnects when a stream ends. Sent once, at the start.
31 pub const STREAM_RETRY: Duration = Duration::from_millis(1000);35 pub const STREAM_RETRY: Duration = Duration::from_millis(1000);
32 36
@@ -166,12 +170,55 @@ pub fn events_response(
166 Ok(response)170 Ok(response)
167 }171 }
168 172
173+/// The state of a viewer's `/-/alive` stream between two wakes.
174+struct AccountFollow {
175+ /// Woken by every change of the viewer's account (sessions, security).
176+ wake: watch::Receiver<u64>,
177+ /// Checks that the session of this stream still exists.
178+ store: Store,
179+ /// The session the stream was opened with.
180+ session_id: String,
181+ /// Set after `signed_out` was sent, so the stream ends right after it.
182+ done: bool,
183+}
184+
169 /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and185 /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and
170-/// starts again. Anonymous viewers may hold it, and it reveals nothing: for now it sends only the186+/// starts again.
171-/// `retry` hint and keep-alives.187+///
188+/// An anonymous viewer gets keep-alives only. A signed-in viewer also gets an `account` event each
189+/// time their account changes (the page then refreshes), and a `signed_out` event when their session
190+/// is gone. After `signed_out` the browser goes to the sign-in page, and the stream ends.
172 #[route(GET "/-/alive")]191 #[route(GET "/-/alive")]
173 async fn alive(cx: &Cx) -> Result<Response> {192 async fn alive(cx: &Cx) -> Result<Response> {
174- events_response(cx, stream::pending::<Result<Event>>())193+ let state = app_context::<AppState>(cx);
194+ let Some(viewer) = current_user(cx).await? else {
195+ return events_response(cx, stream::pending::<Result<Event>>());
196+ };
197+ let follow = AccountFollow {
198+ wake: state
199+ .live
200+ .subscribe(&Topic::Account(viewer.user.id.clone())),
201+ store: state.store.clone(),
202+ session_id: viewer.session.id.clone(),
203+ done: false,
204+ };
205+ let events = stream::unfold(follow, |mut follow| async move {
206+ if follow.done || follow.wake.changed().await.is_err() {
207+ return None;
208+ }
209+ match follow.store.session_is_live(&follow.session_id).await {
210+ Ok(true) => Some((Ok(Event::new().event("account").data("1")), follow)),
211+ Ok(false) => {
212+ follow.done = true;
213+ Some((Ok(Event::new().event("signed_out").data("1")), follow))
214+ }
215+ Err(error) => {
216+ tracing::error!(error = %error, "alive: could not check the session");
217+ None
218+ }
219+ }
220+ });
221+ events_response(cx, events)
175 }222 }
176 223
177 #[cfg(test)]224 #[cfg(test)]
crates/im-web/src/main.rsmodified+4 -0
@@ -5,13 +5,17 @@
5 //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error.5 //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error.
6 6
7 mod assets;7 mod assets;
8+mod audit;
9+mod auth;
8 mod boot;10 mod boot;
11+mod client_ip;
9 mod health;12 mod health;
10 mod i18n;13 mod i18n;
11 mod live;14 mod live;
12 mod pages;15 mod pages;
13 mod security;16 mod security;
14 mod state;17 mod state;
18+mod throttle;
15 mod views;19 mod views;
16 20
17 use std::path::{Path, PathBuf};21 use std::path::{Path, PathBuf};
crates/im-web/src/pages/home.rsmodified+41 -12
@@ -1,25 +1,54 @@
1-//! The start page. For now it only shows that the server runs; it becomes the account home once1+//! The account home, the first page after sign-in. Without a session it goes to sign-in, and on an
2-//! sign-in exists.2+//! instance with no users yet, to setup.
3 3
4 use topcoat::Result;4 use topcoat::Result;
5-use topcoat::context::Cx;5+use topcoat::context::{Cx, app_context};
6+use topcoat::router::error::see_other;
6 use topcoat::router::page;7 use topcoat::router::page;
7 use topcoat::view::{View, view};8 use topcoat::view::{View, view};
8 9
9-use crate::i18n::lang;10+use crate::auth::current_user;
10-use crate::i18n::shell::{K, t};11+use crate::i18n::account::{Txt, text};
11-use crate::views::{notice, shell};12+use crate::state::AppState;
13+use crate::views::{ViewerInfo, page_lang, shell};
12 14
13 /// `GET /`.15 /// `GET /`.
14 #[page("/")]16 #[page("/")]
15 async fn home(cx: &Cx) -> Result<impl View> {17 async fn home(cx: &Cx) -> Result<impl View> {
16- let lang = lang(cx, None);18+ if app_context::<AppState>(cx).store.user_count().await? == 0 {
17- Ok(view! {19+ return Err(see_other("/setup").into());
18- shell(title: t(lang, K::ImIsRunning), lang: lang, viewer: None,20+ }
19- <section class="card">21+ let Some(viewer) = current_user(cx).await? else {
22+ return Err(see_other("/login").into());
23+ };
24+ let lang = page_lang(cx, Some(&viewer));
25+ let two_factor = if viewer.user.totp_enabled() {
26+ text(lang, Txt::On)
27+ } else {
28+ text(lang, Txt::Off)
29+ };
30+ let name = viewer.user.name.clone();
31+ let email = viewer.user.email.clone();
32+ let is_admin = viewer.user.is_admin;
33+ let info = ViewerInfo::of(&viewer);
34+ Ok(view! { cx =>
35+ shell(title: text(lang, Txt::HomeTitle), lang: lang, viewer: Some(info),
36+ <section class="card stack">
20 <p class="kicker">"im"</p>37 <p class="kicker">"im"</p>
21- <h1>(t(lang, K::ImIsRunning))</h1>38+ <h1>(name)</h1>
22- notice(message: t(lang, K::RunningBody))39+ <dl class="facts">
40+ <dt>(text(lang, Txt::Email))</dt>
41+ <dd>(email)</dd>
42+ <dt>(text(lang, Txt::TwoFactorStatus))</dt>
43+ <dd>(two_factor)</dd>
44+ </dl>
45+ <nav class="links">
46+ <a href="/account/security">(text(lang, Txt::SecurityLinkText))</a>
47+ <a href="/account/sessions">(text(lang, Txt::SessionsLinkText))</a>
48+ if is_admin {
49+ <a href="/admin">(text(lang, Txt::AdminLinkText))</a>
50+ }
51+ </nav>
23 </section>52 </section>
24 )53 )
25 })54 })
crates/im-web/src/pages/login.rsadded+367 -0
@@ -0,0 +1,367 @@
1+//! Sign-in: the password step, the second-factor step and sign-out.
2+//!
3+//! Order of a sign-in POST: the pre-session token first, then the throttle, then the lookup and the
4+//! password check (an unknown or disabled email still runs one hash, so timing does not reveal it),
5+//! then either a session or the pending cookie for the second factor. Every wrong answer gets the
6+//! same message.
7+
8+use std::sync::OnceLock;
9+use std::time::{Duration, Instant};
10+
11+use im_core::model::{AuditAction, User, amr};
12+use im_core::names::normalize_email;
13+use im_core::password::{hash_password_async, verify_password_async};
14+use serde::Deserialize;
15+use serde_json::{Value, json};
16+use topcoat::Result;
17+use topcoat::context::{Cx, app_context};
18+use topcoat::router::content::Form;
19+use topcoat::router::error::{SeeOther, forbidden, see_other};
20+use topcoat::router::response::response_headers;
21+use topcoat::router::{HeaderValue, StatusCode, header, page, route};
22+use topcoat::view::{View, view};
23+
24+use crate::audit::{Actor, record};
25+use crate::auth::{
26+ after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, clear_pre_csrf,
27+ end_current_session, pending_login, pre_csrf_token, require_csrf, safe_next, set_pending_login,
28+ start_session,
29+};
30+use crate::client_ip::client_ip;
31+use crate::i18n::Lang;
32+use crate::i18n::account::{Txt, text};
33+use crate::state::AppState;
34+use crate::throttle::{
35+ LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, two_factor_key, user_key,
36+};
37+use crate::views::{alert, field, page_lang, shell};
38+
39+/// The sign-in form. `next` is carried through a hidden field; it is checked again on use.
40+#[derive(Deserialize, Default)]
41+struct LoginForm {
42+ #[serde(default)]
43+ precsrf: String,
44+ #[serde(default)]
45+ email: String,
46+ #[serde(default)]
47+ password: String,
48+ #[serde(default)]
49+ next: String,
50+}
51+
52+/// The query of `GET /login`.
53+#[derive(Deserialize, Default)]
54+struct LoginQuery {
55+ #[serde(default)]
56+ next: String,
57+}
58+
59+/// The second-factor form.
60+#[derive(Deserialize, Default)]
61+struct TwoFactorForm {
62+ #[serde(default)]
63+ precsrf: String,
64+ #[serde(default)]
65+ code: String,
66+}
67+
68+/// A form with only the session's CSRF token.
69+#[derive(Deserialize, Default)]
70+pub struct CsrfForm {
71+ #[serde(default)]
72+ pub csrf: String,
73+}
74+
75+/// `GET /login`. With no users yet, the instance is not set up, so the visitor goes to setup.
76+#[page("/login")]
77+async fn login_form(cx: &Cx, Form(query): Form<LoginQuery>) -> Result<impl View> {
78+ if app_context::<AppState>(cx).store.user_count().await? == 0 {
79+ return Err(see_other("/setup").into());
80+ }
81+ let csrf = pre_csrf_token(cx);
82+ let next = safe_next(Some(&query.next)).to_owned();
83+ Ok(login_view(
84+ cx,
85+ page_lang(cx, None),
86+ csrf,
87+ String::new(),
88+ next,
89+ None,
90+ false,
91+ ))
92+}
93+
94+/// `POST /login`: the password step.
95+#[page(POST "/login")]
96+async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> {
97+ if !check_pre_csrf(cx, &form.precsrf) {
98+ return Err(forbidden().into());
99+ }
100+ let state = app_context::<AppState>(cx);
101+ let csrf = pre_csrf_token(cx);
102+ let next = safe_next(Some(&form.next)).to_owned();
103+ let email = normalize_email(&form.email);
104+ let user_limit = user_key(&email);
105+ let ip_limit = ip_key("login-ip", client_ip(cx));
106+ let now = Instant::now();
107+
108+ // A key over its limit answers with the throttle message and a Retry-After, before any lookup.
109+ let wait = [(&user_limit, LOGIN_USER_LIMIT), (&ip_limit, LOGIN_IP_LIMIT)]
110+ .iter()
111+ .filter_map(|(key, limit)| state.throttle.check(key, *limit, now))
112+ .max();
113+ if let Some(wait) = wait {
114+ retry_after(cx, wait);
115+ let lang = page_lang(cx, None);
116+ return Ok(login_view(
117+ cx,
118+ lang,
119+ csrf,
120+ form.email,
121+ next,
122+ Some(Failure::Throttled),
123+ true,
124+ ));
125+ }
126+
127+ let found = state.store.user_by_email_folded(&email).await?;
128+ let hash = match &found {
129+ Some(user) => user.password_hash.clone(),
130+ None => dummy_hash().await?,
131+ };
132+ let password_ok = verify_password_async(form.password.clone(), hash).await?;
133+ let target_id = found.as_ref().map(|user| user.id.clone());
134+ let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else {
135+ state.throttle.record_failure(&user_limit, now);
136+ state.throttle.record_failure(&ip_limit, now);
137+ let target = target_id.as_deref().map(|id| ("user", id));
138+ record(
139+ cx,
140+ Actor::Anonymous,
141+ AuditAction::LoginFailed,
142+ target,
143+ json!({ "reason": "credentials" }),
144+ )
145+ .await;
146+ let lang = page_lang(cx, None);
147+ return Ok(login_view(
148+ cx,
149+ lang,
150+ csrf,
151+ form.email,
152+ next,
153+ Some(Failure::Invalid),
154+ false,
155+ ));
156+ };
157+
158+ state.throttle.clear(&user_limit);
159+ if user.totp_enabled() {
160+ set_pending_login(cx, &state.key, &user.id, &next)?;
161+ return Err(see_other("/login/2fa").into());
162+ }
163+ Err(finish_sign_in(cx, &user, amr::PASSWORD, &next).await?)
164+}
165+
166+/// `GET /login/2fa`. Needs a pending password step; without one, back to sign-in.
167+#[page("/login/2fa")]
168+async fn two_factor_form(cx: &Cx) -> Result<impl View> {
169+ let state = app_context::<AppState>(cx);
170+ if pending_login(cx, &state.key).is_none() {
171+ return Err(see_other("/login").into());
172+ }
173+ let csrf = pre_csrf_token(cx);
174+ Ok(two_factor_view(cx, page_lang(cx, None), csrf, None, false))
175+}
176+
177+/// `POST /login/2fa`: a six-digit code, or a recovery code.
178+#[page(POST "/login/2fa")]
179+async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<impl View> {
180+ if !check_pre_csrf(cx, &form.precsrf) {
181+ return Err(forbidden().into());
182+ }
183+ let state = app_context::<AppState>(cx);
184+ let Some(pending) = pending_login(cx, &state.key) else {
185+ return Err(see_other("/login").into());
186+ };
187+ let user = match state.store.user_by_id(&pending.user_id).await? {
188+ Some(user) if !user.is_disabled() && user.totp_enabled() => user,
189+ _ => {
190+ clear_pending_login(cx);
191+ return Err(see_other("/login").into());
192+ }
193+ };
194+ let csrf = pre_csrf_token(cx);
195+ let limit = two_factor_key(&user.id);
196+ let now = Instant::now();
197+ if let Some(wait) = state.throttle.check(&limit, TWO_FACTOR_USER_LIMIT, now) {
198+ retry_after(cx, wait);
199+ return Ok(two_factor_view(
200+ cx,
201+ page_lang(cx, None),
202+ csrf,
203+ Some(Failure::Throttled),
204+ true,
205+ ));
206+ }
207+
208+ match check_second_factor(&state.store, &state.key, &user, &form.code).await? {
209+ Some(method) => {
210+ state.throttle.clear(&limit);
211+ clear_pending_login(cx);
212+ Err(finish_sign_in(cx, &user, method, &pending.next).await?)
213+ }
214+ None => {
215+ state.throttle.record_failure(&limit, now);
216+ record(
217+ cx,
218+ Actor::User(&user.id),
219+ AuditAction::Login2faFailed,
220+ Some(("user", &user.id)),
221+ Value::Null,
222+ )
223+ .await;
224+ Ok(two_factor_view(
225+ cx,
226+ page_lang(cx, None),
227+ csrf,
228+ Some(Failure::Code),
229+ false,
230+ ))
231+ }
232+ }
233+}
234+
235+/// `POST /logout`. Ends the current session only; other sessions of the person stay.
236+#[route(POST "/logout")]
237+async fn logout(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
238+ let viewer = require_csrf(cx, &form.csrf).await?;
239+ end_current_session(cx, &viewer).await?;
240+ record(
241+ cx,
242+ Actor::User(&viewer.user.id),
243+ AuditAction::Logout,
244+ Some(("session", &viewer.session.id)),
245+ Value::Null,
246+ )
247+ .await;
248+ Ok(see_other("/login"))
249+}
250+
251+/// Starts the session, clears the pre-session token, audits the sign-in and sends the person on.
252+async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Result<topcoat::Error> {
253+ let state = app_context::<AppState>(cx);
254+ start_session(cx, user, method).await?;
255+ clear_pre_csrf(cx);
256+ record(
257+ cx,
258+ Actor::User(&user.id),
259+ AuditAction::LoginSuccess,
260+ Some(("user", &user.id)),
261+ json!({ "amr": method }),
262+ )
263+ .await;
264+ Ok(see_other(after_sign_in(state, user, next)).into())
265+}
266+
267+/// The hash checked against when the email is unknown or the account disabled. Computed once, so
268+/// the timing of a miss matches the timing of a wrong password.
269+async fn dummy_hash() -> Result<String> {
270+ static DUMMY: OnceLock<String> = OnceLock::new();
271+ if let Some(hash) = DUMMY.get() {
272+ return Ok(hash.clone());
273+ }
274+ let hash = hash_password_async("not-the-password-of-any-account".to_owned()).await?;
275+ Ok(DUMMY.get_or_init(|| hash).clone())
276+}
277+
278+/// What went wrong on a form, for the message shown above it.
279+#[derive(Clone, Copy)]
280+enum Failure {
281+ /// Wrong email, password or account state. One message for all three.
282+ Invalid,
283+ /// The second-factor code was wrong or spent.
284+ Code,
285+ /// The throttle holds the account or the address.
286+ Throttled,
287+}
288+
289+/// Sets `Retry-After` for a throttled answer, in whole seconds, at least one.
290+fn retry_after(cx: &Cx, wait: Duration) {
291+ if let Ok(value) = HeaderValue::from_str(&wait.as_secs().max(1).to_string()) {
292+ response_headers(cx).append(header::RETRY_AFTER, value);
293+ }
294+}
295+
296+/// The sign-in page. The typed email comes back; the password never does.
297+fn login_view(
298+ cx: &Cx,
299+ lang: Lang,
300+ csrf: String,
301+ email: String,
302+ next: String,
303+ failure: Option<Failure>,
304+ throttled: bool,
305+) -> impl View {
306+ let problem = failure.map(|failure| failure_text(lang, failure));
307+ view! { cx =>
308+ if throttled {
309+ (StatusCode::TOO_MANY_REQUESTS)
310+ }
311+ shell(title: text(lang, Txt::SignIn), lang: lang, viewer: None,
312+ <section class="card narrow stack">
313+ <h1>(text(lang, Txt::SignIn))</h1>
314+ if let Some(problem) = problem {
315+ alert(message: problem)
316+ }
317+ <form method="post" action="/login" class="stack">
318+ <input type="hidden" name="precsrf" value=(csrf)>
319+ <input type="hidden" name="next" value=(next)>
320+ field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: email)
321+ field(label: text(lang, Txt::Password), name: "password", kind: "password", autocomplete: "current-password", value: String::new())
322+ <button type="submit" class="button primary">(text(lang, Txt::SignIn))</button>
323+ </form>
324+ </section>
325+ )
326+ }
327+}
328+
329+/// The second-factor page.
330+fn two_factor_view(
331+ cx: &Cx,
332+ lang: Lang,
333+ csrf: String,
334+ failure: Option<Failure>,
335+ throttled: bool,
336+) -> impl View {
337+ let problem = failure.map(|failure| failure_text(lang, failure));
338+ view! { cx =>
339+ if throttled {
340+ (StatusCode::TOO_MANY_REQUESTS)
341+ }
342+ shell(title: text(lang, Txt::TwoFactorTitle), lang: lang, viewer: None,
343+ <section class="card narrow stack">
344+ <h1>(text(lang, Txt::TwoFactorTitle))</h1>
345+ <p class="muted">(text(lang, Txt::TwoFactorIntro))</p>
346+ if let Some(problem) = problem {
347+ alert(message: problem)
348+ }
349+ <form method="post" action="/login/2fa" class="stack">
350+ <input type="hidden" name="precsrf" value=(csrf)>
351+ field(label: text(lang, Txt::Code), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
352+ <button type="submit" class="button primary">(text(lang, Txt::Verify))</button>
353+ </form>
354+ </section>
355+ )
356+ }
357+}
358+
359+/// The message for a failure on either sign-in form.
360+fn failure_text(lang: Lang, failure: Failure) -> String {
361+ match failure {
362+ Failure::Invalid => text(lang, Txt::ErrInvalidLogin),
363+ Failure::Code => text(lang, Txt::ErrCodeInvalid),
364+ Failure::Throttled => text(lang, Txt::ErrThrottled),
365+ }
366+ .to_owned()
367+}
crates/im-web/src/pages/mod.rsmodified+7 -0
@@ -1,4 +1,11 @@
1 //! The pages and the page-level layers. One file per page.1 //! The pages and the page-level layers. One file per page.
2 2
3 pub mod home;3 pub mod home;
4+pub mod login;
4 pub mod not_found;5 pub mod not_found;
6+pub mod security;
7+pub mod sessions;
8+pub mod setup;
9+
10+#[cfg(test)]
11+mod tests;
crates/im-web/src/pages/security.rsadded+637 -0
@@ -0,0 +1,637 @@
1+//! The security page: the password, two-factor sign-in and the recovery codes of the signed-in
2+//! person. Each change is a POST that checks the CSRF token first and then redirects (PRG), except
3+//! where the codes are shown: those render on the POST response, once.
4+
5+use std::time::Instant;
6+
7+use base64::Engine as _;
8+use base64::engine::general_purpose::STANDARD as BASE64;
9+use im_core::model::AuditAction;
10+use im_core::password::{check_policy, hash_password_async, verify_password_async};
11+use im_core::secret;
12+use im_core::totp;
13+use serde::Deserialize;
14+use serde_json::json;
15+use topcoat::Result;
16+use topcoat::context::{Cx, app_context};
17+use topcoat::router::content::Form;
18+use topcoat::router::error::see_other;
19+use topcoat::router::page;
20+use topcoat::view::{View, component, view};
21+
22+use crate::audit::{Actor, record};
23+use crate::auth::{Viewer, check_second_factor, require_csrf, require_user, unix_now};
24+use crate::i18n::Lang;
25+use crate::i18n::account::{Txt, policy_problem, recovery_left, text};
26+use crate::live::Topic;
27+use crate::state::AppState;
28+use crate::throttle::{LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, two_factor_key, user_key};
29+use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
30+
31+/// How many recovery codes one issue gives.
32+const RECOVERY_CODES: usize = 10;
33+
34+/// The query of `GET /account/security`.
35+#[derive(Deserialize, Default)]
36+struct NoticeQuery {
37+ #[serde(default)]
38+ notice: String,
39+}
40+
41+/// The password change form.
42+#[derive(Deserialize, Default)]
43+struct PasswordForm {
44+ #[serde(default)]
45+ csrf: String,
46+ #[serde(default)]
47+ current_password: String,
48+ #[serde(default)]
49+ new_password: String,
50+ #[serde(default)]
51+ new_password_again: String,
52+}
53+
54+/// A form with a CSRF token and one six-digit code (or recovery code).
55+#[derive(Deserialize, Default)]
56+struct CodeForm {
57+ #[serde(default)]
58+ csrf: String,
59+ #[serde(default)]
60+ code: String,
61+}
62+
63+/// The turn-off form: the password and a second factor.
64+#[derive(Deserialize, Default)]
65+struct DisableForm {
66+ #[serde(default)]
67+ csrf: String,
68+ #[serde(default)]
69+ current_password: String,
70+ #[serde(default)]
71+ code: String,
72+}
73+
74+/// The recovery-code form: the password only.
75+#[derive(Deserialize, Default)]
76+struct RecoveryForm {
77+ #[serde(default)]
78+ csrf: String,
79+ #[serde(default)]
80+ current_password: String,
81+}
82+
83+/// What the page shows above its sections: a notice, an error, or freshly issued codes.
84+#[derive(Default)]
85+struct Flash {
86+ notice: Option<String>,
87+ alert: Option<String>,
88+ codes: Vec<String>,
89+}
90+
91+impl Flash {
92+ fn alert(message: impl Into<String>) -> Self {
93+ Self {
94+ alert: Some(message.into()),
95+ ..Self::default()
96+ }
97+ }
98+}
99+
100+/// A pending enrolment, ready to show: the base32 secret, the otpauth link and the QR code.
101+struct Enrolment {
102+ secret: String,
103+ link: String,
104+ qr: String,
105+}
106+
107+/// `GET /account/security`.
108+#[page("/account/security")]
109+async fn security_page(cx: &Cx, Form(query): Form<NoticeQuery>) -> Result<impl View> {
110+ let viewer = require_user(cx).await?;
111+ let lang = page_lang(cx, Some(&viewer));
112+ let flash_notice = match query.notice.as_str() {
113+ "enrol" => Some(text(lang, Txt::EnrolSecurityNotice)),
114+ "saved-password" => Some(text(lang, Txt::SavedPassword)),
115+ "saved-2fa-on" => Some(text(lang, Txt::Saved2faOn)),
116+ "saved-2fa-off" => Some(text(lang, Txt::Saved2faOff)),
117+ _ => None,
118+ };
119+ let flash = Flash {
120+ notice: flash_notice.map(str::to_owned),
121+ ..Flash::default()
122+ };
123+ render_security(cx, viewer.clone(), flash).await
124+}
125+
126+/// `POST /account/security/password`.
127+#[page(POST "/account/security/password")]
128+async fn change_password(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl View> {
129+ let viewer = require_csrf(cx, &form.csrf).await?;
130+ let state = app_context::<AppState>(cx);
131+ let lang = page_lang(cx, Some(&viewer));
132+ if password_locked(state, &viewer) {
133+ return render_security(
134+ cx,
135+ viewer.clone(),
136+ Flash::alert(text(lang, Txt::ErrThrottled)),
137+ )
138+ .await;
139+ }
140+ if !password_matches(state, &viewer, &form.current_password).await? {
141+ return render_security(
142+ cx,
143+ viewer.clone(),
144+ Flash::alert(text(lang, Txt::ErrWrongPassword)),
145+ )
146+ .await;
147+ }
148+ if form.new_password != form.new_password_again {
149+ return render_security(
150+ cx,
151+ viewer.clone(),
152+ Flash::alert(text(lang, Txt::ErrPasswordsDiffer)),
153+ )
154+ .await;
155+ }
156+ if let Err(violation) = check_policy(&form.new_password, &viewer.user.email, &viewer.user.name)
157+ {
158+ let message = policy_problem(lang, violation);
159+ return render_security(cx, viewer.clone(), Flash::alert(message)).await;
160+ }
161+ if verify_password_async(form.new_password.clone(), viewer.user.password_hash.clone()).await? {
162+ return render_security(
163+ cx,
164+ viewer.clone(),
165+ Flash::alert(text(lang, Txt::ErrPasswordSame)),
166+ )
167+ .await;
168+ }
169+
170+ let hash = hash_password_async(form.new_password.clone()).await?;
171+ state
172+ .store
173+ .set_password_hash(&viewer.user.id, &hash)
174+ .await?;
175+ // Every other session of the person ends with the old password. This one stays signed in.
176+ let ended = state
177+ .store
178+ .end_other_sessions(&viewer.user.id, &viewer.session.id)
179+ .await?;
180+ changed(state, &viewer);
181+ record(
182+ cx,
183+ Actor::User(&viewer.user.id),
184+ AuditAction::PasswordChanged,
185+ Some(("user", &viewer.user.id)),
186+ json!({ "sessions_ended": ended.len() }),
187+ )
188+ .await;
189+ Err(see_other("/account/security?notice=saved-password").into())
190+}
191+
192+/// `POST /account/security/2fa/start`: starts an enrolment. Turning on needs no code; replacing an
193+/// authenticator of an account that already has two-factor sign-in needs its current code.
194+#[page(POST "/account/security/2fa/start")]
195+async fn start_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl View> {
196+ let viewer = require_csrf(cx, &form.csrf).await?;
197+ let state = app_context::<AppState>(cx);
198+ let lang = page_lang(cx, Some(&viewer));
199+ if viewer.user.totp_enabled() {
200+ if form.code.trim().is_empty() {
201+ return render_security(
202+ cx,
203+ viewer.clone(),
204+ Flash::alert(text(lang, Txt::ErrCodeMissing)),
205+ )
206+ .await;
207+ }
208+ let limit = two_factor_key(&viewer.user.id);
209+ let now = Instant::now();
210+ if state
211+ .throttle
212+ .check(&limit, TWO_FACTOR_USER_LIMIT, now)
213+ .is_some()
214+ {
215+ return render_security(
216+ cx,
217+ viewer.clone(),
218+ Flash::alert(text(lang, Txt::ErrThrottled)),
219+ )
220+ .await;
221+ }
222+ if check_second_factor(&state.store, &state.key, &viewer.user, &form.code)
223+ .await?
224+ .is_none()
225+ {
226+ state.throttle.record_failure(&limit, now);
227+ return render_security(
228+ cx,
229+ viewer.clone(),
230+ Flash::alert(text(lang, Txt::ErrCodeInvalid)),
231+ )
232+ .await;
233+ }
234+ }
235+ let secret = totp::new_secret();
236+ let sealed = secret::seal(&state.key, &secret)?;
237+ state
238+ .store
239+ .set_totp_pending(&viewer.user.id, &sealed)
240+ .await?;
241+ Err(see_other("/account/security").into())
242+}
243+
244+/// `POST /account/security/2fa/confirm`: the first code from the new authenticator turns
245+/// two-factor sign-in on, and issues the recovery codes, shown once.
246+#[page(POST "/account/security/2fa/confirm")]
247+async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl View> {
248+ let viewer = require_csrf(cx, &form.csrf).await?;
249+ let state = app_context::<AppState>(cx);
250+ let lang = page_lang(cx, Some(&viewer));
251+ let Some(sealed) = state.store.totp_pending(&viewer.user.id).await? else {
252+ return render_security(
253+ cx,
254+ viewer.clone(),
255+ Flash::alert(text(lang, Txt::ErrNoPending)),
256+ )
257+ .await;
258+ };
259+ let shared = secret::open(&state.key, &sealed)?;
260+ let last = viewer
261+ .user
262+ .totp_last_step
263+ .and_then(|step| u64::try_from(step).ok());
264+ let Some(step) = totp::verify(&shared, form.code.trim(), totp::step_for(unix_now()), last)
265+ else {
266+ return render_security(
267+ cx,
268+ viewer.clone(),
269+ Flash::alert(text(lang, Txt::ErrCodeInvalid)),
270+ )
271+ .await;
272+ };
273+
274+ let codes = issue_codes();
275+ let hashes: Vec<String> = codes
276+ .iter()
277+ .map(|code| totp::recovery_code_hash(code))
278+ .collect();
279+ state
280+ .store
281+ .enable_totp(&viewer.user.id, &sealed, step, &hashes)
282+ .await?;
283+ changed(state, &viewer);
284+ record(
285+ cx,
286+ Actor::User(&viewer.user.id),
287+ AuditAction::TotpEnabled,
288+ Some(("user", &viewer.user.id)),
289+ json!({ "recovery_codes": codes.len() }),
290+ )
291+ .await;
292+ // Reload the person, so the page shows two-factor sign-in as on.
293+ let user = state
294+ .store
295+ .user_by_id(&viewer.user.id)
296+ .await?
297+ .ok_or(im_core::Error::NotFound)?;
298+ let viewer = Viewer { user, ..viewer };
299+ let flash = Flash {
300+ notice: Some(text(lang, Txt::Saved2faOn).to_owned()),
301+ codes,
302+ ..Flash::default()
303+ };
304+ render_security(cx, viewer.clone(), flash).await
305+}
306+
307+/// `POST /account/security/2fa/disable`: needs the password and a second factor.
308+#[page(POST "/account/security/2fa/disable")]
309+async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<impl View> {
310+ let viewer = require_csrf(cx, &form.csrf).await?;
311+ let state = app_context::<AppState>(cx);
312+ let lang = page_lang(cx, Some(&viewer));
313+ if !viewer.user.totp_enabled() {
314+ return Err(see_other("/account/security").into());
315+ }
316+ if password_locked(state, &viewer) {
317+ return render_security(
318+ cx,
319+ viewer.clone(),
320+ Flash::alert(text(lang, Txt::ErrThrottled)),
321+ )
322+ .await;
323+ }
324+ if !password_matches(state, &viewer, &form.current_password).await? {
325+ return render_security(
326+ cx,
327+ viewer.clone(),
328+ Flash::alert(text(lang, Txt::ErrWrongPassword)),
329+ )
330+ .await;
331+ }
332+ let limit = two_factor_key(&viewer.user.id);
333+ let now = Instant::now();
334+ if state
335+ .throttle
336+ .check(&limit, TWO_FACTOR_USER_LIMIT, now)
337+ .is_some()
338+ {
339+ return render_security(
340+ cx,
341+ viewer.clone(),
342+ Flash::alert(text(lang, Txt::ErrThrottled)),
343+ )
344+ .await;
345+ }
346+ if form.code.trim().is_empty() {
347+ return render_security(
348+ cx,
349+ viewer.clone(),
350+ Flash::alert(text(lang, Txt::ErrCodeMissing)),
351+ )
352+ .await;
353+ }
354+ if check_second_factor(&state.store, &state.key, &viewer.user, &form.code)
355+ .await?
356+ .is_none()
357+ {
358+ state.throttle.record_failure(&limit, now);
359+ return render_security(
360+ cx,
361+ viewer.clone(),
362+ Flash::alert(text(lang, Txt::ErrCodeInvalid)),
363+ )
364+ .await;
365+ }
366+
367+ state.store.disable_totp(&viewer.user.id).await?;
368+ state.throttle.clear(&limit);
369+ changed(state, &viewer);
370+ record(
371+ cx,
372+ Actor::User(&viewer.user.id),
373+ AuditAction::TotpDisabled,
374+ Some(("user", &viewer.user.id)),
375+ json!({}),
376+ )
377+ .await;
378+ Err(see_other("/account/security?notice=saved-2fa-off").into())
379+}
380+
381+/// `POST /account/security/recovery`: replaces the recovery codes. The old codes stop working.
382+#[page(POST "/account/security/recovery")]
383+async fn regenerate_recovery(cx: &Cx, Form(form): Form<RecoveryForm>) -> Result<impl View> {
384+ let viewer = require_csrf(cx, &form.csrf).await?;
385+ let state = app_context::<AppState>(cx);
386+ let lang = page_lang(cx, Some(&viewer));
387+ if !viewer.user.totp_enabled() {
388+ return Err(see_other("/account/security").into());
389+ }
390+ if password_locked(state, &viewer) {
391+ return render_security(
392+ cx,
393+ viewer.clone(),
394+ Flash::alert(text(lang, Txt::ErrThrottled)),
395+ )
396+ .await;
397+ }
398+ if !password_matches(state, &viewer, &form.current_password).await? {
399+ return render_security(
400+ cx,
401+ viewer.clone(),
402+ Flash::alert(text(lang, Txt::ErrWrongPassword)),
403+ )
404+ .await;
405+ }
406+
407+ let codes = issue_codes();
408+ let hashes: Vec<String> = codes
409+ .iter()
410+ .map(|code| totp::recovery_code_hash(code))
411+ .collect();
412+ state
413+ .store
414+ .replace_recovery_codes(&viewer.user.id, &hashes)
415+ .await?;
416+ record(
417+ cx,
418+ Actor::User(&viewer.user.id),
419+ AuditAction::RecoveryCodesIssued,
420+ Some(("user", &viewer.user.id)),
421+ json!({ "count": codes.len() }),
422+ )
423+ .await;
424+ let flash = Flash {
425+ codes,
426+ ..Flash::default()
427+ };
428+ render_security(cx, viewer.clone(), flash).await
429+}
430+
431+/// Fresh recovery codes, in the form people type them (`xxxx-xxxx`).
432+fn issue_codes() -> Vec<String> {
433+ (0..RECOVERY_CODES)
434+ .map(|_| totp::new_recovery_code())
435+ .collect()
436+}
437+
438+/// True while the password counters hold the account. Wrong passwords on this page count toward
439+/// the same limit as sign-in.
440+fn password_locked(state: &AppState, viewer: &Viewer) -> bool {
441+ state
442+ .throttle
443+ .check(
444+ &user_key(&viewer.user.email),
445+ LOGIN_USER_LIMIT,
446+ Instant::now(),
447+ )
448+ .is_some()
449+}
450+
451+/// Checks the password of the signed-in person and records the outcome in the throttle.
452+async fn password_matches(state: &AppState, viewer: &Viewer, given: &str) -> Result<bool> {
453+ let ok = verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await?;
454+ let limit = user_key(&viewer.user.email);
455+ if ok {
456+ state.throttle.clear(&limit);
457+ } else {
458+ state.throttle.record_failure(&limit, Instant::now());
459+ }
460+ Ok(ok)
461+}
462+
463+/// Tells the open account pages that the person's security changed.
464+fn changed(state: &AppState, viewer: &Viewer) {
465+ state.live.bump(&Topic::Account(viewer.user.id.clone()));
466+}
467+
468+/// Builds the QR code of a secret as a `data:` image, so no request leaves the page for it.
469+fn enrolment_of(state: &AppState, viewer: &Viewer, sealed: &str) -> Result<Enrolment> {
470+ let shared = secret::open(&state.key, sealed)?;
471+ let link = totp::otpauth_uri(&viewer.user.email, &shared);
472+ let code = qrcode::QrCode::new(link.as_bytes())
473+ .map_err(|error| topcoat::Error::msg(error.to_string()))?;
474+ let svg = code
475+ .render::<qrcode::render::svg::Color>()
476+ .min_dimensions(240, 240)
477+ .build();
478+ Ok(Enrolment {
479+ secret: totp::base32_encode(&shared),
480+ link,
481+ qr: format!("data:image/svg+xml;base64,{}", BASE64.encode(svg)),
482+ })
483+}
484+
485+/// The security page: reads what the sections show, then renders them.
486+async fn render_security(cx: &Cx, viewer: Viewer, flash: Flash) -> Result<impl View> {
487+ let state = app_context::<AppState>(cx);
488+ let lang = page_lang(cx, Some(&viewer));
489+ let pending = match state.store.totp_pending(&viewer.user.id).await? {
490+ Some(sealed) => Some(enrolment_of(state, &viewer, &sealed)?),
491+ None => None,
492+ };
493+ let enabled = viewer.user.totp_enabled();
494+ let unused = if enabled {
495+ state.store.unused_recovery_codes(&viewer.user.id).await?
496+ } else {
497+ 0
498+ };
499+ let info = ViewerInfo::of(&viewer);
500+ let csrf = viewer.session.csrf_token.clone();
501+ Ok(security_view(
502+ cx, lang, info, csrf, enabled, unused, pending, flash,
503+ ))
504+}
505+
506+/// The markup of the security page. It owns everything it shows, so it can outlive the handler.
507+#[allow(clippy::too_many_arguments)]
508+fn security_view(
509+ cx: &Cx,
510+ lang: Lang,
511+ info: ViewerInfo,
512+ csrf: String,
513+ enabled: bool,
514+ unused: u64,
515+ pending: Option<Enrolment>,
516+ flash: Flash,
517+) -> impl View {
518+ let has_pending = pending.is_some();
519+ let Flash {
520+ notice: flash_notice,
521+ alert: flash_alert,
522+ codes,
523+ } = flash;
524+ view! { cx =>
525+ shell(title: text(lang, Txt::SecurityTitle), lang: lang, viewer: Some(info),
526+ <section class="stack">
527+ <h1>(text(lang, Txt::SecurityTitle))</h1>
528+ if let Some(message) = flash_notice {
529+ notice(message: message)
530+ }
531+ if let Some(message) = flash_alert {
532+ alert(message: message)
533+ }
534+
535+ <section class="card stack">
536+ <h2>(text(lang, Txt::PasswordSection))</h2>
537+ <p class="muted">(text(lang, Txt::PasswordHelp))</p>
538+ <form method="post" action="/account/security/password" class="stack">
539+ <input type="hidden" name="csrf" value=(csrf.clone())>
540+ field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
541+ field(label: text(lang, Txt::NewPassword), name: "new_password", kind: "password", autocomplete: "new-password", value: String::new())
542+ field(label: text(lang, Txt::NewPasswordAgain), name: "new_password_again", kind: "password", autocomplete: "new-password", value: String::new())
543+ <p class="hint">(text(lang, Txt::PasswordHint))</p>
544+ <button type="submit" class="button primary">(text(lang, Txt::ChangePassword))</button>
545+ </form>
546+ </section>
547+
548+ <section class="card stack">
549+ <h2>(text(lang, Txt::TwoFactorSection))</h2>
550+ if enabled {
551+ <p>(text(lang, Txt::TwoFactorOnText))</p>
552+ } else {
553+ <p>(text(lang, Txt::TwoFactorOffText))</p>
554+ }
555+ if let Some(pending) = pending {
556+ enrolment_block(lang: lang, csrf: csrf.clone(), secret: pending.secret, link: pending.link, qr: pending.qr)
557+ }
558+ if enabled {
559+ <section class="stack">
560+ <h3>(text(lang, Txt::ReplaceTitle))</h3>
561+ <p class="muted">(text(lang, Txt::ReplaceHelp))</p>
562+ <form method="post" action="/account/security/2fa/start" class="stack">
563+ <input type="hidden" name="csrf" value=(csrf.clone())>
564+ field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
565+ <button type="submit" class="button ghost">(text(lang, Txt::ReplaceButton))</button>
566+ </form>
567+ </section>
568+
569+ <section class="stack">
570+ <h3>(text(lang, Txt::RecoveryTitle))</h3>
571+ <p class="muted">(text(lang, Txt::RecoveryHelp))</p>
572+ <p>(recovery_left(lang, unused))</p>
573+ <p class="muted">(text(lang, Txt::RegenerateHelp))</p>
574+ <form method="post" action="/account/security/recovery" class="stack">
575+ <input type="hidden" name="csrf" value=(csrf.clone())>
576+ field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
577+ <button type="submit" class="button ghost">(text(lang, Txt::RegenerateCodes))</button>
578+ </form>
579+ </section>
580+
581+ <section class="stack">
582+ <h3>(text(lang, Txt::DisableTitle))</h3>
583+ <p class="muted">(text(lang, Txt::DisableHelp))</p>
584+ <form method="post" action="/account/security/2fa/disable" class="stack">
585+ <input type="hidden" name="csrf" value=(csrf.clone())>
586+ field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
587+ field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
588+ <button type="submit" class="button danger">(text(lang, Txt::TurnOff))</button>
589+ </form>
590+ </section>
591+ } else if !has_pending {
592+ <form method="post" action="/account/security/2fa/start" class="stack">
593+ <input type="hidden" name="csrf" value=(csrf.clone())>
594+ <button type="submit" class="button primary">(text(lang, Txt::TurnOn))</button>
595+ </form>
596+ }
597+ if !codes.is_empty() {
598+ <section class="stack codes">
599+ <h3>(text(lang, Txt::NewCodesTitle))</h3>
600+ <p class="warning">(text(lang, Txt::CodesShownOnce))</p>
601+ <ul class="codes-list">
602+ for code in codes {
603+ <li><code>(code)</code></li>
604+ }
605+ </ul>
606+ </section>
607+ }
608+ </section>
609+ </section>
610+ )
611+ }
612+}
613+
614+/// A pending enrolment: the QR code, the secret to type, and the form that confirms the first code.
615+#[component]
616+async fn enrolment_block(
617+ lang: Lang,
618+ csrf: String,
619+ secret: String,
620+ link: String,
621+ qr: String,
622+) -> Result<impl View> {
623+ Ok(view! {
624+ <section class="enrolment stack">
625+ <h3>(text(lang, Txt::PendingTitle))</h3>
626+ <p class="muted">(text(lang, Txt::PendingHelp))</p>
627+ <img class="qr" src=(qr) alt=(text(lang, Txt::QrAlt)) width="240" height="240">
628+ <p><span class="field-label">(text(lang, Txt::SecretKey))</span> <code class="secret">(secret)</code></p>
629+ <p><a href=(link)>(text(lang, Txt::SetupLink))</a></p>
630+ <form method="post" action="/account/security/2fa/confirm" class="stack">
631+ <input type="hidden" name="csrf" value=(csrf)>
632+ field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
633+ <button type="submit" class="button primary">(text(lang, Txt::TurnOn))</button>
634+ </form>
635+ </section>
636+ })
637+}
crates/im-web/src/pages/sessions.rsadded+247 -0
@@ -0,0 +1,247 @@
1+//! The session list of the signed-in person: where each session was made, and the buttons that end
2+//! one session or every other one. Ending the current session signs the browser out.
3+
4+use im_core::model::{AuditAction, Session};
5+use serde::Deserialize;
6+use serde_json::json;
7+use topcoat::Result;
8+use topcoat::context::{Cx, app_context};
9+use topcoat::router::content::Form;
10+use topcoat::router::error::{SeeOther, see_other};
11+use topcoat::router::{page, route};
12+use topcoat::view::{View, component, view};
13+
14+use crate::audit::{Actor, record};
15+use crate::auth::{Viewer, end_current_session, require_csrf, require_user};
16+use crate::i18n::Lang;
17+use crate::i18n::account::{Txt, device_label, text};
18+use crate::live::Topic;
19+use crate::state::AppState;
20+use crate::views::{ViewerInfo, notice, page_lang, shell};
21+
22+/// The query of `GET /account/sessions`.
23+#[derive(Deserialize, Default)]
24+struct SessionsQuery {
25+ #[serde(default)]
26+ notice: String,
27+}
28+
29+/// The form that ends one session.
30+#[derive(Deserialize, Default)]
31+struct RevokeForm {
32+ #[serde(default)]
33+ csrf: String,
34+ #[serde(default)]
35+ session_id: String,
36+}
37+
38+/// A form with only the CSRF token.
39+#[derive(Deserialize, Default)]
40+struct CsrfOnly {
41+ #[serde(default)]
42+ csrf: String,
43+}
44+
45+/// `GET /account/sessions`.
46+#[page("/account/sessions")]
47+async fn sessions_page(cx: &Cx, Form(query): Form<SessionsQuery>) -> Result<impl View> {
48+ let viewer = require_user(cx).await?;
49+ let state = app_context::<AppState>(cx);
50+ let lang = page_lang(cx, Some(&viewer));
51+ let sessions = state.store.list_sessions(&viewer.user.id).await?;
52+ let flash = match query.notice.as_str() {
53+ "saved-session" => Some(text(lang, Txt::SavedSession).to_owned()),
54+ "saved-others" => Some(text(lang, Txt::SavedOthers).to_owned()),
55+ _ => None,
56+ };
57+ let rows: Vec<SessionRow> = sessions
58+ .iter()
59+ .map(|session| SessionRow {
60+ device: device_of(lang, session),
61+ ip: session.ip.clone().unwrap_or_default(),
62+ created: session.created_at.clone(),
63+ last_seen: session.last_seen_at.clone(),
64+ session_id: session.id.clone(),
65+ current: session.id == viewer.session.id,
66+ })
67+ .collect();
68+ let others = rows.iter().filter(|row| !row.current).count();
69+ Ok(sessions_view(
70+ cx,
71+ lang,
72+ ViewerInfo::of(&viewer),
73+ viewer.session.csrf_token.clone(),
74+ rows,
75+ others,
76+ flash,
77+ ))
78+}
79+
80+/// The markup of the sessions page.
81+fn sessions_view(
82+ cx: &Cx,
83+ lang: Lang,
84+ info: ViewerInfo,
85+ csrf: String,
86+ rows: Vec<SessionRow>,
87+ others: usize,
88+ flash: Option<String>,
89+) -> impl View {
90+ view! { cx =>
91+ shell(title: text(lang, Txt::SessionsTitle), lang: lang, viewer: Some(info),
92+ <section class="stack">
93+ <h1>(text(lang, Txt::SessionsTitle))</h1>
94+ <p class="muted">(text(lang, Txt::SessionsIntro))</p>
95+ if let Some(message) = flash {
96+ notice(message: message)
97+ }
98+ <ul class="item-list">
99+ for row in rows {
100+ session_item(lang: lang, csrf: csrf.clone(), row: row)
101+ }
102+ </ul>
103+ if others > 0 {
104+ <form method="post" action="/account/sessions/revoke-others">
105+ <input type="hidden" name="csrf" value=(csrf.clone())>
106+ <button type="submit" class="button danger">(text(lang, Txt::SignOutOthers))</button>
107+ </form>
108+ } else {
109+ <p class="muted">(text(lang, Txt::NoOthers))</p>
110+ }
111+ </section>
112+ )
113+ }
114+}
115+
116+/// One line of the session list, with the text already resolved.
117+struct SessionRow {
118+ device: String,
119+ ip: String,
120+ created: String,
121+ last_seen: String,
122+ session_id: String,
123+ current: bool,
124+}
125+
126+/// `POST /account/sessions/revoke`. Ends one session of the person. Ending the current one signs
127+/// this browser out.
128+#[route(POST "/account/sessions/revoke")]
129+async fn revoke_session(cx: &Cx, Form(form): Form<RevokeForm>) -> Result<SeeOther> {
130+ let viewer = require_csrf(cx, &form.csrf).await?;
131+ let state = app_context::<AppState>(cx);
132+ if form.session_id == viewer.session.id {
133+ end_current_session(cx, &viewer).await?;
134+ record(
135+ cx,
136+ Actor::User(&viewer.user.id),
137+ AuditAction::Logout,
138+ Some(("session", &viewer.session.id)),
139+ json!({ "by": "sessions page" }),
140+ )
141+ .await;
142+ return Ok(see_other("/login"));
143+ }
144+ if state
145+ .store
146+ .end_session(&viewer.user.id, &form.session_id)
147+ .await?
148+ {
149+ state.live.bump(&Topic::Account(viewer.user.id.clone()));
150+ record(
151+ cx,
152+ Actor::User(&viewer.user.id),
153+ AuditAction::SessionRevoked,
154+ Some(("session", &form.session_id)),
155+ json!({}),
156+ )
157+ .await;
158+ }
159+ Ok(see_other("/account/sessions?notice=saved-session"))
160+}
161+
162+/// `POST /account/sessions/revoke-others`. Ends every session but the current one.
163+#[route(POST "/account/sessions/revoke-others")]
164+async fn revoke_others(cx: &Cx, Form(form): Form<CsrfOnly>) -> Result<SeeOther> {
165+ let viewer: Viewer = require_csrf(cx, &form.csrf).await?;
166+ let state = app_context::<AppState>(cx);
167+ let ended = state
168+ .store
169+ .end_other_sessions(&viewer.user.id, &viewer.session.id)
170+ .await?;
171+ if !ended.is_empty() {
172+ state.live.bump(&Topic::Account(viewer.user.id.clone()));
173+ record(
174+ cx,
175+ Actor::User(&viewer.user.id),
176+ AuditAction::SessionsRevoked,
177+ Some(("user", &viewer.user.id)),
178+ json!({ "count": ended.len() }),
179+ )
180+ .await;
181+ }
182+ Ok(see_other("/account/sessions?notice=saved-others"))
183+}
184+
185+/// The device name of a session, from its user agent. An unknown browser or system gets the
186+/// translated fallback.
187+fn device_of(lang: Lang, session: &Session) -> String {
188+ let agent = session.user_agent.as_deref().unwrap_or("");
189+ let browser = if agent.contains("Edg/") {
190+ Some("Edge")
191+ } else if agent.contains("OPR/") {
192+ Some("Opera")
193+ } else if agent.contains("Firefox/") {
194+ Some("Firefox")
195+ } else if agent.contains("Chrome/") || agent.contains("Chromium/") {
196+ Some("Chrome")
197+ } else if agent.contains("Safari/") {
198+ Some("Safari")
199+ } else {
200+ None
201+ };
202+ let system = if agent.contains("Android") {
203+ Some("Android")
204+ } else if agent.contains("iPhone") || agent.contains("iPad") {
205+ Some("iOS")
206+ } else if agent.contains("Windows") {
207+ Some("Windows")
208+ } else if agent.contains("Mac OS X") {
209+ Some("macOS")
210+ } else if agent.contains("Linux") {
211+ Some("Linux")
212+ } else {
213+ None
214+ };
215+ device_label(
216+ lang,
217+ browser.unwrap_or(text(lang, Txt::UnknownBrowser)),
218+ system.unwrap_or(text(lang, Txt::UnknownSystem)),
219+ )
220+}
221+
222+/// One session in the list: the device, where and when it was used, and the button that ends it.
223+#[component]
224+async fn session_item(lang: Lang, csrf: String, row: SessionRow) -> Result<impl View> {
225+ Ok(view! {
226+ <li class="item">
227+ <div class="item-main">
228+ <strong>(row.device.clone())</strong>
229+ if row.current {
230+ <span class="badge accent">(text(lang, Txt::ThisSession))</span>
231+ }
232+ <div class="muted">
233+ <span>(text(lang, Txt::SignedInAt))": "(row.created.clone())</span>
234+ <span>" \u{b7} "(text(lang, Txt::LastSeen))": "(row.last_seen.clone())</span>
235+ <span>" \u{b7} "(text(lang, Txt::AddressLabel))": "(row.ip.clone())</span>
236+ </div>
237+ </div>
238+ if !row.current {
239+ <form method="post" action="/account/sessions/revoke" class="item-action">
240+ <input type="hidden" name="csrf" value=(csrf)>
241+ <input type="hidden" name="session_id" value=(row.session_id.clone())>
242+ <button type="submit" class="button ghost">(text(lang, Txt::SignOutSession))</button>
243+ </form>
244+ }
245+ </li>
246+ })
247+}
crates/im-web/src/pages/setup.rsadded+140 -0
@@ -0,0 +1,140 @@
1+//! First-run setup. While no user exists, `GET /setup` shows the form that creates the first
2+//! administrator. Once a user exists, both the page and its POST are a 404, so the route does not
3+//! reveal that the instance was set up.
4+
5+use im_core::model::{AuditAction, amr};
6+use im_core::names::{normalize_email, parse_email};
7+use im_core::password::{check_policy, hash_password_async};
8+use serde::Deserialize;
9+use serde_json::Value;
10+use topcoat::Result;
11+use topcoat::context::{Cx, app_context};
12+use topcoat::router::content::Form;
13+use topcoat::router::error::{forbidden, not_found, see_other};
14+use topcoat::router::page;
15+use topcoat::view::{View, view};
16+
17+use crate::audit::{Actor, record};
18+use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session};
19+use crate::i18n::Lang;
20+use crate::i18n::account::{Txt, policy_problem, text};
21+use crate::state::AppState;
22+use crate::views::{alert, field, page_lang, shell};
23+
24+/// The fields of the setup form. Every field defaults to empty, so a missing one is a failed check
25+/// (403 for the token, a message for the rest), not a 400.
26+#[derive(Deserialize, Default)]
27+struct SetupForm {
28+ #[serde(default)]
29+ precsrf: String,
30+ #[serde(default)]
31+ name: String,
32+ #[serde(default)]
33+ email: String,
34+ #[serde(default)]
35+ password: String,
36+ #[serde(default)]
37+ password_again: String,
38+}
39+
40+/// `GET /setup`.
41+#[page("/setup")]
42+async fn setup_form(cx: &Cx) -> Result<impl View> {
43+ if app_context::<AppState>(cx).store.user_count().await? > 0 {
44+ return Err(not_found().into());
45+ }
46+ let csrf = pre_csrf_token(cx);
47+ let lang = page_lang(cx, None);
48+ Ok(setup_view(
49+ cx,
50+ lang,
51+ csrf,
52+ String::new(),
53+ String::new(),
54+ None,
55+ ))
56+}
57+
58+/// `POST /setup`. Creates the first administrator, signs them in and sends them on.
59+#[page(POST "/setup")]
60+async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> {
61+ let state = app_context::<AppState>(cx);
62+ if state.store.user_count().await? > 0 {
63+ return Err(not_found().into());
64+ }
65+ if !check_pre_csrf(cx, &form.precsrf) {
66+ return Err(forbidden().into());
67+ }
68+ let csrf = pre_csrf_token(cx);
69+ let lang = page_lang(cx, None);
70+ let name = form.name.trim().to_owned();
71+ let typed_email = form.email.clone();
72+
73+ let problem =
74+ if name.is_empty() || name.chars().count() > 200 || name.chars().any(char::is_control) {
75+ Some(text(lang, Txt::ErrNameInvalid).to_owned())
76+ } else {
77+ match parse_email(&normalize_email(&form.email)) {
78+ Err(_) => Some(text(lang, Txt::ErrEmailInvalid).to_owned()),
79+ Ok(email) => match check_policy(&form.password, &email, &name) {
80+ Err(violation) => Some(policy_problem(lang, violation)),
81+ Ok(()) if form.password != form.password_again => {
82+ Some(text(lang, Txt::ErrPasswordsDiffer).to_owned())
83+ }
84+ Ok(()) => None,
85+ },
86+ }
87+ };
88+ if let Some(problem) = problem {
89+ return Ok(setup_view(cx, lang, csrf, name, typed_email, Some(problem)));
90+ }
91+
92+ let email = parse_email(&normalize_email(&form.email))?;
93+ let hash = hash_password_async(form.password.clone()).await?;
94+ let user = match state.store.create_first_admin(&email, &name, &hash).await {
95+ Ok(user) => user,
96+ // Another setup finished first; the page no longer exists for this request either.
97+ Err(im_core::Error::Conflict(_)) => return Err(not_found().into()),
98+ Err(error) => return Err(error.into()),
99+ };
100+ start_session(cx, &user, amr::PASSWORD).await?;
101+ clear_pre_csrf(cx);
102+ record(
103+ cx,
104+ Actor::User(&user.id),
105+ AuditAction::SetupDone,
106+ Some(("user", &user.id)),
107+ Value::Null,
108+ )
109+ .await;
110+ Err(see_other(after_sign_in(state, &user, "/")).into())
111+}
112+
113+/// The setup page. The typed name and email come back; passwords never do.
114+fn setup_view(
115+ cx: &Cx,
116+ lang: Lang,
117+ csrf: String,
118+ name: String,
119+ email: String,
120+ problem: Option<String>,
121+) -> impl View {
122+ view! { cx => shell(title: text(lang, Txt::SetupTitle), lang: lang, viewer: None,
123+ <section class="card narrow stack">
124+ <h1>(text(lang, Txt::SetupTitle))</h1>
125+ <p class="muted">(text(lang, Txt::SetupIntro))</p>
126+ if let Some(problem) = problem {
127+ alert(message: problem)
128+ }
129+ <form method="post" action="/setup" class="stack">
130+ <input type="hidden" name="precsrf" value=(csrf)>
131+ field(label: text(lang, Txt::Name), name: "name", kind: "text", autocomplete: "name", value: name)
132+ field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: email)
133+ field(label: text(lang, Txt::Password), name: "password", kind: "password", autocomplete: "new-password", value: String::new())
134+ field(label: text(lang, Txt::NewPasswordAgain), name: "password_again", kind: "password", autocomplete: "new-password", value: String::new())
135+ <p class="hint">(text(lang, Txt::PasswordHint))</p>
136+ <button type="submit" class="button primary">(text(lang, Txt::CreateAdmin))</button>
137+ </form>
138+ </section>
139+ ) }
140+}
crates/im-web/src/pages/tests.rsadded+105 -0
@@ -0,0 +1,105 @@
1+//! In-process tests of the forms: a request goes through the whole router, as a browser's would.
2+//! They cover the checks that must run before any side effect.
3+
4+use std::time::Duration;
5+
6+use http::header::{CONTENT_TYPE, COOKIE};
7+use im_core::password::hash_password;
8+use im_core::store::sessions::NewSession;
9+use im_core::token::{generate_token, hash_token};
10+use topcoat::router::{Body, to_bytes};
11+
12+use crate::boot::{router, test_state};
13+use crate::state::AppState;
14+
15+/// The cookie name the browser sends: the `__Host-` prefix is added by the jar.
16+const COOKIE_NAME: &str = "__Host-im_session";
17+
18+/// Sends a form POST, with an optional session cookie, and returns the status and body.
19+async fn post_form(state: AppState, path: &str, cookie: Option<&str>, body: &str) -> (u16, String) {
20+ let mut request =
21+ http::Request::post(path).header(CONTENT_TYPE, "application/x-www-form-urlencoded");
22+ if let Some(cookie) = cookie {
23+ request = request.header(COOKIE, format!("{COOKIE_NAME}={cookie}"));
24+ }
25+ let request = request.body(Body::from(body.to_owned())).expect("request");
26+ let response = router(state).handle(request).await;
27+ let status = response.status().as_u16();
28+ let bytes = to_bytes(response.into_body(), 1024 * 1024)
29+ .await
30+ .expect("body");
31+ (status, String::from_utf8_lossy(&bytes).into_owned())
32+}
33+
34+/// A signed-in session for a fresh account. Returns the cookie value.
35+async fn signed_in(state: &AppState) -> String {
36+ let hash = hash_password("the current password").expect("hash");
37+ let user = state
38+ .store
39+ .create_user("ada@example.com", "Ada", &hash, true)
40+ .await
41+ .expect("user");
42+ let token = generate_token();
43+ state
44+ .store
45+ .create_session(
46+ &NewSession {
47+ user_id: &user.id,
48+ token_hash: &hash_token(&token),
49+ csrf_token: &generate_token(),
50+ amr: "pwd",
51+ ip: None,
52+ user_agent: None,
53+ ttl: Duration::from_secs(3600),
54+ },
55+ 10,
56+ )
57+ .await
58+ .expect("session");
59+ token
60+}
61+
62+#[tokio::test]
63+async fn a_sign_in_post_without_the_pre_session_token_is_forbidden() {
64+ let (_dir, state) = test_state().await;
65+ let (status, _) = post_form(state, "/login", None, "email=ada%40example.com&password=x").await;
66+ assert_eq!(status, 403);
67+}
68+
69+#[tokio::test]
70+async fn a_password_change_without_the_csrf_token_is_forbidden() {
71+ let (_dir, state) = test_state().await;
72+ let token = signed_in(&state).await;
73+ let body = "current_password=the+current+password&new_password=a+brand+new+phrase&new_password_again=a+brand+new+phrase";
74+ let (status, _) = post_form(
75+ state.clone(),
76+ "/account/security/password",
77+ Some(&token),
78+ body,
79+ )
80+ .await;
81+ assert_eq!(status, 403);
82+ // The password was not touched: the old one still signs in.
83+ let user = state
84+ .store
85+ .user_by_email_folded("ada@example.com")
86+ .await
87+ .expect("query")
88+ .expect("user");
89+ assert!(im_core::password::verify_password(
90+ "the current password",
91+ &user.password_hash
92+ ));
93+}
94+
95+#[tokio::test]
96+async fn setup_is_not_found_once_a_user_exists() {
97+ let (_dir, state) = test_state().await;
98+ signed_in(&state).await;
99+ let get = http::Request::get("/setup")
100+ .body(Body::empty())
101+ .expect("request");
102+ assert_eq!(router(state.clone()).handle(get).await.status(), 404);
103+ let (status, _) = post_form(state, "/setup", None, "precsrf=x").await;
104+ assert_eq!(status, 404);
105+}
crates/im-web/src/state.rsmodified+3 -1
@@ -6,9 +6,9 @@ use im_core::config::Config;
6 use im_core::store::Store;6 use im_core::store::Store;
7 7
8 use crate::live::LiveHub;8 use crate::live::LiveHub;
9+use crate::throttle::Throttle;
9 10
10 /// Everything a request handler reaches through the app context. Every field is cheap to clone.11 /// Everything a request handler reaches through the app context. Every field is cheap to clone.
11-#[allow(dead_code)] // The key and the hub are read by the sign-in and live pages that come next.
12 #[derive(Clone)]12 #[derive(Clone)]
13 pub struct AppState {13 pub struct AppState {
14 /// The configuration the process booted with.14 /// The configuration the process booted with.
@@ -19,4 +19,6 @@ pub struct AppState {
19 pub key: Arc<[u8; 32]>,19 pub key: Arc<[u8; 32]>,
20 /// The change counters of the live pages.20 /// The change counters of the live pages.
21 pub live: Arc<LiveHub>,21 pub live: Arc<LiveHub>,
22+ /// Failed sign-in and second-factor counters.
23+ pub throttle: Arc<Throttle>,
22 }24 }
crates/im-web/src/throttle.rsadded+185 -0
@@ -0,0 +1,185 @@
1+//! In-memory sliding-window failure counters that slow down password guessing.
2+//!
3+//! Each key keeps the instants of its recent failures, and is limited while it has `limit` of them
4+//! inside [`WINDOW`]. Only rejected attempts are recorded, so a locked key stops growing. Memory is
5+//! bounded: expired instants and empty keys are pruned every few hundred failures, and at the key
6+//! cap the key whose latest failure is oldest is evicted.
7+//!
8+//! The counters live in one process. A restart clears them, and two processes would each count
9+//! their own. `im` runs as one process, so this is the whole picture.
10+
11+use std::collections::{HashMap, VecDeque};
12+use std::net::IpAddr;
13+use std::sync::{Mutex, MutexGuard};
14+use std::time::{Duration, Instant};
15+
16+/// Length of the failure window.
17+pub const WINDOW: Duration = Duration::from_secs(15 * 60);
18+
19+/// Failed sign-ins allowed per normalised email address inside [`WINDOW`]. Also counts wrong
20+/// passwords on the security page, so guessing there locks sign-in too.
21+pub const LOGIN_USER_LIMIT: usize = 10;
22+
23+/// Failed sign-ins allowed per client address inside [`WINDOW`].
24+pub const LOGIN_IP_LIMIT: usize = 30;
25+
26+/// Failed second-factor checks allowed per user inside [`WINDOW`].
27+pub const TWO_FACTOR_USER_LIMIT: usize = 10;
28+
29+/// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past
30+/// this.
31+const MAX_KEYS: usize = 100_000;
32+
33+/// A full prune runs every this many recorded failures.
34+const PRUNE_EVERY: u32 = 256;
35+
36+/// The failure counters of the process. Shared by every request through the app state.
37+pub struct Throttle {
38+ window: Duration,
39+ max_keys: usize,
40+ state: Mutex<State>,
41+}
42+
43+#[derive(Default)]
44+struct State {
45+ failures: HashMap<String, VecDeque<Instant>>,
46+ recorded: u32,
47+}
48+
49+impl Default for Throttle {
50+ fn default() -> Self {
51+ Self::with_limits(WINDOW, MAX_KEYS)
52+ }
53+}
54+
55+impl Throttle {
56+ /// Counters with a custom window and key cap. Tests use short windows.
57+ pub fn with_limits(window: Duration, max_keys: usize) -> Self {
58+ Self {
59+ window,
60+ max_keys: max_keys.max(1),
61+ state: Mutex::new(State::default()),
62+ }
63+ }
64+
65+ /// How long until `key` drops below `limit` failures, or `None` when it is not limited.
66+ pub fn check(&self, key: &str, limit: usize, now: Instant) -> Option<Duration> {
67+ let mut state = self.lock();
68+ let timestamps = state.failures.get_mut(key)?;
69+ drop_expired(timestamps, self.window, now);
70+ if timestamps.len() < limit {
71+ return None;
72+ }
73+ // The failure at this index leaves the window first, and that brings the count below limit.
74+ let index = timestamps.len().checked_sub(limit)?;
75+ let oldest = *timestamps.get(index)?;
76+ Some((oldest + self.window).saturating_duration_since(now))
77+ }
78+
79+ /// Records one rejected attempt for `key` at `now`.
80+ pub fn record_failure(&self, key: &str, now: Instant) {
81+ let mut state = self.lock();
82+ state.recorded = state.recorded.wrapping_add(1);
83+ if state.recorded.is_multiple_of(PRUNE_EVERY) {
84+ self.prune_locked(&mut state, now);
85+ }
86+ if !state.failures.contains_key(key) && state.failures.len() >= self.max_keys {
87+ self.evict_oldest_locked(&mut state);
88+ }
89+ let timestamps = state.failures.entry(key.to_owned()).or_default();
90+ drop_expired(timestamps, self.window, now);
91+ timestamps.push_back(now);
92+ }
93+
94+ /// Forgets the failures of `key`, after a success.
95+ pub fn clear(&self, key: &str) {
96+ self.lock().failures.remove(key);
97+ }
98+
99+ /// Drops expired failures and the keys left empty.
100+ fn prune_locked(&self, state: &mut State, now: Instant) {
101+ let window = self.window;
102+ state.failures.retain(|_, timestamps| {
103+ drop_expired(timestamps, window, now);
104+ !timestamps.is_empty()
105+ });
106+ }
107+
108+ /// Removes the key whose latest failure is the oldest. Runs only when the cap is reached.
109+ fn evict_oldest_locked(&self, state: &mut State) {
110+ let victim = state
111+ .failures
112+ .iter()
113+ .filter_map(|(key, timestamps)| timestamps.back().map(|last| (key, *last)))
114+ .min_by_key(|(_, last)| *last)
115+ .map(|(key, _)| key.clone());
116+ if let Some(key) = victim {
117+ state.failures.remove(&key);
118+ }
119+ }
120+
121+ fn lock(&self) -> MutexGuard<'_, State> {
122+ // A poisoned lock still holds consistent counters, so the next caller uses it as it is.
123+ self.state.lock().unwrap_or_else(|e| e.into_inner())
124+ }
125+}
126+
127+/// Removes the failures that have left the window.
128+fn drop_expired(timestamps: &mut VecDeque<Instant>, window: Duration, now: Instant) {
129+ while let Some(front) = timestamps.front() {
130+ if now.saturating_duration_since(*front) < window {
131+ break;
132+ }
133+ timestamps.pop_front();
134+ }
135+}
136+
137+/// Throttle key for a normalised email address.
138+pub fn user_key(email: &str) -> String {
139+ format!("user:{email}")
140+}
141+
142+/// Throttle key for the second factor of one user, by user id.
143+pub fn two_factor_key(user_id: &str) -> String {
144+ format!("2fa:{user_id}")
145+}
146+
147+/// Throttle key for an address under a named scope, such as `login-ip`.
148+pub fn ip_key(scope: &str, ip: IpAddr) -> String {
149+ format!("{scope}:{ip}")
150+}
151+
152+#[cfg(test)]
153+mod tests {
154+ use super::*;
155+
156+ #[test]
157+ fn a_key_is_limited_at_the_threshold_and_free_when_the_window_passes() {
158+ let throttle = Throttle::with_limits(Duration::from_secs(60), 16);
159+ let t0 = Instant::now();
160+ for i in 0..3 {
161+ let at = t0 + Duration::from_secs(i);
162+ assert!(throttle.check("k", 3, at).is_none());
163+ throttle.record_failure("k", at);
164+ }
165+ let retry = throttle
166+ .check("k", 3, t0 + Duration::from_secs(10))
167+ .expect("limited");
168+ assert_eq!(retry, Duration::from_secs(50));
169+ assert!(
170+ throttle
171+ .check("k", 3, t0 + Duration::from_secs(60))
172+ .is_none()
173+ );
174+ }
175+
176+ #[test]
177+ fn the_key_count_stays_at_the_cap() {
178+ let throttle = Throttle::with_limits(Duration::from_secs(10), 8);
179+ let t0 = Instant::now();
180+ for i in 0..1000u64 {
181+ throttle.record_failure(&format!("key-{i}"), t0 + Duration::from_millis(i));
182+ assert!(throttle.lock().failures.len() <= 8);
183+ }
184+ }
185+}
crates/im-web/src/views/mod.rsmodified+80 -14
@@ -4,20 +4,43 @@
4 //! emits an inline script, style or event handler; see `security.rs`.4 //! emits an inline script, style or event handler; see `security.rs`.
5 5
6 use topcoat::Result;6 use topcoat::Result;
7+use topcoat::context::Cx;
7 use topcoat::view::{Child, View, component, view};8 use topcoat::view::{Child, View, component, view};
8 9
9 use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF};10 use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF};
10-use crate::i18n::Lang;11+use crate::auth::Viewer;
12+use crate::i18n::account::{Txt, text};
11 use crate::i18n::shell::{K, t};13 use crate::i18n::shell::{K, t};
14+use crate::i18n::{Lang, lang as request_lang};
12 15
13-/// What the shell shows about the signed-in person. Nothing signs a person in yet, so every page16+/// What the shell shows about the signed-in person, and the token of their sign-out form.
14-/// is built for an anonymous viewer.
15-#[allow(dead_code)] // Built by the sign-in code, which comes next.
16 pub struct ViewerInfo {17 pub struct ViewerInfo {
17- /// The name shown in the topbar.18+ /// The name shown in the account menu.
18 pub name: String,19 pub name: String,
19- /// Whether the topbar shows the administrator badge.20+ /// Whether the menu offers the administration section.
20 pub is_admin: bool,21 pub is_admin: bool,
22+ /// The session's CSRF token, for the sign-out form in the menu.
23+ pub csrf: String,
24+}
25+
26+impl ViewerInfo {
27+ /// What the shell shows for `viewer`, with the token of its sign-out form.
28+ pub fn of(viewer: &Viewer) -> Self {
29+ Self {
30+ name: viewer.user.name.clone(),
31+ is_admin: viewer.user.is_admin,
32+ csrf: viewer.session.csrf_token.clone(),
33+ }
34+ }
35+}
36+
37+/// The language of a page: the signed-in person's stored choice when they have one, else the
38+/// request's `Accept-Language`.
39+pub fn page_lang(cx: &Cx, viewer: Option<&Viewer>) -> Lang {
40+ let stored = viewer
41+ .map(|viewer| viewer.user.locale.as_str())
42+ .filter(|locale| !locale.is_empty());
43+ request_lang(cx, stored)
21 }44 }
22 45
23 /// The HTML document around a page. `title` is the page's own title; the document title adds the46 /// The HTML document around a page. `title` is the page's own title; the document title adds the
@@ -29,7 +52,7 @@ pub struct ViewerInfo {
29 pub async fn shell(52 pub async fn shell(
30 title: &str,53 title: &str,
31 lang: Lang,54 lang: Lang,
32- viewer: Option<&ViewerInfo>,55+ viewer: Option<ViewerInfo>,
33 #[default] child: Child<'_>,56 #[default] child: Child<'_>,
34 ) -> Result<impl View> {57 ) -> Result<impl View> {
35 let document_title = format!("{title} \u{b7} im");58 let document_title = format!("{title} \u{b7} im");
@@ -51,10 +74,7 @@ pub async fn shell(
51 <nav class="switcher" aria-label=(t(lang, K::Services))></nav>74 <nav class="switcher" aria-label=(t(lang, K::Services))></nav>
52 <div class="topbar-end">75 <div class="topbar-end">
53 if let Some(viewer) = viewer {76 if let Some(viewer) = viewer {
54- <span>(viewer.name.as_str())</span>77+ user_menu(lang: lang, viewer: viewer)
55- if viewer.is_admin {
56- <span class="badge accent">(t(lang, K::Admin))</span>
57- }
58 }78 }
59 </div>79 </div>
60 </header>80 </header>
@@ -64,16 +84,45 @@ pub async fn shell(
64 })84 })
65 }85 }
66 86
87+/// The account menu of the topbar: the name, the account links and the sign-out button. It is a
88+/// disclosure element, so it opens without any script. The sign-out form is a full page load, so
89+/// the browser drops its live stream at once.
90+#[component]
91+pub async fn user_menu(lang: Lang, viewer: ViewerInfo) -> Result<impl View> {
92+ Ok(view! {
93+ <details class="user-menu">
94+ <summary>
95+ <span class="user-menu-name">(viewer.name.clone())</span>
96+ if viewer.is_admin {
97+ <span class="badge accent">(t(lang, K::Admin))</span>
98+ }
99+ </summary>
100+ <div class="user-menu-panel">
101+ <nav class="user-menu-links" aria-label=(text(lang, Txt::AccountMenu))>
102+ <a href="/account/security">(text(lang, Txt::SecurityTitle))</a>
103+ <a href="/account/sessions">(text(lang, Txt::SessionsTitle))</a>
104+ if viewer.is_admin {
105+ <a href="/admin">(text(lang, Txt::AdminArea))</a>
106+ }
107+ </nav>
108+ <form method="post" action="/logout" data-hard="true" class="user-menu-logout">
109+ <input type="hidden" name="csrf" value=(viewer.csrf.clone())>
110+ <button type="submit" class="button ghost">(text(lang, Txt::SignOut))</button>
111+ </form>
112+ </div>
113+ </details>
114+ })
115+}
116+
67 /// An error message for a failed action. Forms show it above their fields.117 /// An error message for a failed action. Forms show it above their fields.
68-#[allow(dead_code)] // The first form that can fail a check uses it.
69 #[component]118 #[component]
70-pub async fn alert(message: &str) -> Result<impl View> {119+pub async fn alert(message: String) -> Result<impl View> {
71 Ok(view! { <div class="alert" role="alert">(message)</div> })120 Ok(view! { <div class="alert" role="alert">(message)</div> })
72 }121 }
73 122
74 /// A plain message that is not an error, such as a confirmation or a hint.123 /// A plain message that is not an error, such as a confirmation or a hint.
75 #[component]124 #[component]
76-pub async fn notice(message: &str) -> Result<impl View> {125+pub async fn notice(message: String) -> Result<impl View> {
77 Ok(view! { <div class="notice" role="status">(message)</div> })126 Ok(view! { <div class="notice" role="status">(message)</div> })
78 }127 }
79 128
@@ -87,3 +136,20 @@ pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result<imp
87 </section>136 </section>
88 })137 })
89 }138 }
139+
140+/// A labelled text input. `value` refills the field after an error; password fields pass "".
141+#[component]
142+pub async fn field(
143+ label: &str,
144+ name: &'static str,
145+ kind: &'static str,
146+ autocomplete: &'static str,
147+ value: String,
148+) -> Result<impl View> {
149+ Ok(view! {
150+ <label class="field">
151+ <span class="field-label">(label)</span>
152+ <input name=(name) type=(kind) autocomplete=(autocomplete) value=(value) required="" spellcheck="false">
153+ </label>
154+ })
155+}
style/_components.scssmodified+172 -0
@@ -313,3 +313,175 @@ textarea::placeholder {
313 transition: none;313 transition: none;
314 }314 }
315 }315 }
316+
317+// Account pages: the forms, the item lists of the sessions page, the security codes and the
318+// account menu of the topbar. The views only use these class names; nothing here is inline.
319+
320+.stack {
321+ display: grid;
322+ gap: 0.9rem;
323+}
324+
325+.narrow {
326+ max-width: 28rem;
327+ width: 100%;
328+ margin-inline: auto;
329+}
330+
331+.hint {
332+ color: var(--muted);
333+ font-size: 0.875rem;
334+ margin: 0;
335+}
336+
337+.warning {
338+ color: var(--warn);
339+ background: var(--warn-soft);
340+ border-radius: var(--radius);
341+ padding: 0.6rem 0.8rem;
342+ margin: 0;
343+}
344+
345+.facts {
346+ display: grid;
347+ grid-template-columns: max-content 1fr;
348+ gap: 0.4rem 1.2rem;
349+ margin: 0;
350+
351+ dt {
352+ color: var(--muted);
353+ }
354+
355+ dd {
356+ margin: 0;
357+ }
358+}
359+
360+.links {
361+ display: flex;
362+ flex-wrap: wrap;
363+ gap: 0.4rem 1rem;
364+}
365+
366+.qr {
367+ width: 240px;
368+ height: 240px;
369+ max-width: 100%;
370+ background: #fff;
371+ border-radius: var(--radius);
372+ padding: 0.5rem;
373+}
374+
375+.secret,
376+.codes-list code {
377+ font-family: var(--font-mono);
378+ overflow-wrap: anywhere;
379+}
380+
381+.codes-list {
382+ list-style: none;
383+ padding: 0;
384+ margin: 0;
385+ display: grid;
386+ grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr));
387+ gap: 0.4rem;
388+
389+ code {
390+ display: block;
391+ background: var(--surface-2);
392+ border-radius: var(--radius);
393+ padding: 0.4rem 0.6rem;
394+ font-size: 1.05rem;
395+ }
396+}
397+
398+.item-list {
399+ list-style: none;
400+ padding: 0;
401+ margin: 0;
402+ display: grid;
403+ gap: 0.6rem;
404+}
405+
406+.item {
407+ display: flex;
408+ flex-wrap: wrap;
409+ align-items: center;
410+ justify-content: space-between;
411+ gap: 0.6rem 1rem;
412+ background: var(--surface);
413+ border: 1px solid var(--border);
414+ border-radius: var(--radius);
415+ padding: 0.8rem 1rem;
416+}
417+
418+.item-main {
419+ display: grid;
420+ gap: 0.2rem;
421+ min-width: 0;
422+}
423+
424+.item-action {
425+ margin: 0;
426+}
427+
428+.user-menu {
429+ position: relative;
430+
431+ summary {
432+ cursor: pointer;
433+ list-style: none;
434+ display: inline-flex;
435+ align-items: center;
436+ gap: 0.4rem;
437+ padding: 0.3rem 0.5rem;
438+ border-radius: var(--radius);
439+ }
440+
441+ summary::-webkit-details-marker {
442+ display: none;
443+ }
444+
445+ &[open] > summary {
446+ background: var(--surface-2);
447+ }
448+}
449+
450+.user-menu-name {
451+ font-weight: 600;
452+}
453+
454+.user-menu-panel {
455+ position: absolute;
456+ right: 0;
457+ top: 100%;
458+ margin-top: 0.3rem;
459+ min-width: 12rem;
460+ z-index: 10;
461+ display: grid;
462+ gap: 0.3rem;
463+ padding: 0.3rem;
464+ background: var(--surface);
465+ border: 1px solid var(--border);
466+ border-radius: var(--radius);
467+ box-shadow: 0 8px 24px rgb(0 0 0 / 0.12);
468+}
469+
470+.user-menu-links {
471+ display: grid;
472+
473+ a {
474+ padding: 0.4rem 0.6rem;
475+ border-radius: 6px;
476+ color: var(--text);
477+ text-decoration: none;
478+ }
479+
480+ a:hover {
481+ background: var(--surface-2);
482+ }
483+}
484+
485+.user-menu-logout {
486+ margin: 0;
487+}