forge
Explore
Log in

Don't you dare go Hollow

🛡️ ops: private db files from creation, https issuer, startup warnings, redacted Debug, URL-free request errors, daily 2FA bound

Browse files at this commit

08d6e476631bb7c940ba1ad0edec590124edca45Ahmet Kaan GümüşParent: 849ec00
crates/im-core/src/config.rsmodified+35 -6
@@ -373,17 +373,33 @@ impl Config {
373 }373 }
374 }374 }
375 375
376-/// Checks that `base_url` is an http(s) origin with a path of at most `/`.376+/// Checks that `base_url` is an origin with a path of at most `/`. It must be https, except for a localhost
377+/// or loopback host, where plain http never leaves the machine (the same rule as the SMTP `tls = "none"`).
377 fn validate_base_url(url: &str) -> Result<()> {378 fn validate_base_url(url: &str) -> Result<()> {
378- let rest = url379+ let (secure, rest) = match url.strip_prefix("https://") {
379- .strip_prefix("https://")380+ Some(rest) => (true, rest),
380- .or_else(|| url.strip_prefix("http://"))381+ None => (
381- .ok_or_else(|| Error::Config("base_url must start with http:// or https://".into()))?;382+ false,
383+ url.strip_prefix("http://").ok_or_else(|| {
384+ Error::Config("base_url must start with http:// or https://".into())
385+ })?,
386+ ),
387+ };
382 if rest.is_empty() || rest.ends_with('/') || url.chars().any(char::is_whitespace) {388 if rest.is_empty() || rest.ends_with('/') || url.chars().any(char::is_whitespace) {
383 return Err(Error::Config(389 return Err(Error::Config(
384 "base_url must be an origin with no trailing slash or spaces".into(),390 "base_url must be an origin with no trailing slash or spaces".into(),
385 ));391 ));
386 }392 }
393+ let authority = rest.split('/').next().unwrap_or(rest);
394+ let host = match authority.strip_prefix('[') {
395+ Some(bracketed) => bracketed.split(']').next().unwrap_or(bracketed),
396+ None => authority.split(':').next().unwrap_or(authority),
397+ };
398+ if !secure && !is_localhost(host) {
399+ return Err(Error::Config(
400+ "base_url must use https:// unless its host is localhost or a loopback address".into(),
401+ ));
402+ }
387 Ok(())403 Ok(())
388 }404 }
389 405
@@ -400,7 +416,7 @@ mod tests {
400 416
401 #[test]417 #[test]
402 fn plaintext_smtp_is_refused_unless_the_host_is_localhost() {418 fn plaintext_smtp_is_refused_unless_the_host_is_localhost() {
403- let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"http://a\"\n";419+ let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"https://a\"\n";
404 let remote = format!(420 let remote = format!(
405 "{base}[smtp]\nhost = \"mail.example.com\"\ntls = \"none\"\nfrom = \"im@example.com\"\n"421 "{base}[smtp]\nhost = \"mail.example.com\"\ntls = \"none\"\nfrom = \"im@example.com\"\n"
406 );422 );
@@ -412,4 +428,17 @@ mod tests {
412 let no_from = format!("{base}[smtp]\nhost = \"mail.example.com\"\n");428 let no_from = format!("{base}[smtp]\nhost = \"mail.example.com\"\n");
413 assert!(Config::parse(&no_from).is_err());429 assert!(Config::parse(&no_from).is_err());
414 }430 }
431+
432+ #[test]
433+ fn plain_http_base_url_is_refused_unless_the_host_is_loopback() {
434+ let base_url = |url: &str| {
435+ format!(
436+ "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"{url}\"\n"
437+ )
438+ };
439+ assert!(Config::parse(&base_url("http://id.example.com")).is_err());
440+ assert!(Config::parse(&base_url("http://127.0.0.1:7650")).is_ok());
441+ assert!(Config::parse(&base_url("http://[::1]:7650")).is_ok());
442+ assert!(Config::parse(&base_url("https://id.example.com")).is_ok());
443+ }
415 }444 }
crates/im-core/src/model.rsmodified+48 -2
@@ -5,7 +5,7 @@
5 //! Timestamps are the stored text form from `time.rs`.5 //! Timestamps are the stored text form from `time.rs`.
6 6
7 /// A person who can sign in. `id` is the OIDC `sub` once OIDC exists, and is never reused.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)]8+#[derive(Clone, PartialEq, Eq)]
9 pub struct User {9 pub struct User {
10 /// ULID.10 /// ULID.
11 pub id: String,11 pub id: String,
@@ -43,6 +43,32 @@ pub struct User {
43 pub updated_at: String,43 pub updated_at: String,
44 }44 }
45 45
46+/// Prints every field, except that the password hash and the sealed TOTP secret print as `<redacted>`, so a
47+/// debug log never holds them.
48+impl std::fmt::Debug for User {
49+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50+ f.debug_struct("User")
51+ .field("id", &self.id)
52+ .field("email", &self.email)
53+ .field("name", &self.name)
54+ .field("password_hash", &format_args!("<redacted>"))
55+ .field("is_admin", &self.is_admin)
56+ .field("disabled_at", &self.disabled_at)
57+ .field("totp_secret_sealed", &format_args!("<redacted>"))
58+ .field("totp_enabled_at", &self.totp_enabled_at)
59+ .field("totp_last_step", &self.totp_last_step)
60+ .field("locale", &self.locale)
61+ .field("locale_auto", &self.locale_auto)
62+ .field("zoneinfo", &self.zoneinfo)
63+ .field("theme", &self.theme)
64+ .field("photo_mime", &self.photo_mime)
65+ .field("picture_version", &self.picture_version)
66+ .field("created_at", &self.created_at)
67+ .field("updated_at", &self.updated_at)
68+ .finish()
69+ }
70+}
71+
46 impl User {72 impl User {
47 /// True when two-factor sign-in is on: the secret is stored and enrolment was confirmed.73 /// True when two-factor sign-in is on: the secret is stored and enrolment was confirmed.
48 pub fn totp_enabled(&self) -> bool {74 pub fn totp_enabled(&self) -> bool {
@@ -81,7 +107,7 @@ pub mod amr {
81 }107 }
82 108
83 /// A browser session. The cookie holds the token; the row holds only its hash.109 /// A browser session. The cookie holds the token; the row holds only its hash.
84-#[derive(Debug, Clone, PartialEq, Eq)]110+#[derive(Clone, PartialEq, Eq)]
85 pub struct Session {111 pub struct Session {
86 /// ULID. This is the OIDC `sid` once OIDC exists.112 /// ULID. This is the OIDC `sid` once OIDC exists.
87 pub id: String,113 pub id: String,
@@ -109,6 +135,26 @@ pub struct Session {
109 pub amr: String,135 pub amr: String,
110 }136 }
111 137
138+/// Prints every field, except that the token hash and the CSRF token print as `<redacted>`.
139+impl std::fmt::Debug for Session {
140+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141+ f.debug_struct("Session")
142+ .field("id", &self.id)
143+ .field("user_id", &self.user_id)
144+ .field("token_hash", &format_args!("<redacted>"))
145+ .field("csrf_token", &format_args!("<redacted>"))
146+ .field("created_at", &self.created_at)
147+ .field("expires_at", &self.expires_at)
148+ .field("hard_expires_at", &self.hard_expires_at)
149+ .field("last_seen_at", &self.last_seen_at)
150+ .field("ip", &self.ip)
151+ .field("user_agent", &self.user_agent)
152+ .field("auth_time", &self.auth_time)
153+ .field("amr", &self.amr)
154+ .finish()
155+ }
156+}
157+
112 /// What an audit entry is about. The variants are the values stored in `audit_log.action`.158 /// What an audit entry is about. The variants are the values stored in `audit_log.action`.
113 #[derive(Debug, Clone, Copy, PartialEq, Eq)]159 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
114 pub enum AuditAction {160 pub enum AuditAction {
crates/im-core/src/store/mod.rsmodified+23 -0
@@ -70,6 +70,7 @@ impl Store {
70 let path_str = path.to_str().ok_or_else(|| {70 let path_str = path.to_str().ok_or_else(|| {
71 Error::Config(format!("database path is not UTF-8: {}", path.display()))71 Error::Config(format!("database path is not UTF-8: {}", path.display()))
72 })?;72 })?;
73+ create_private_files(path)?;
73 let db = Builder::new_local(path_str).build().await.map_err(db_err)?;74 let db = Builder::new_local(path_str).build().await.map_err(db_err)?;
74 let conn = db.connect().map_err(db_err)?;75 let conn = db.connect().map_err(db_err)?;
75 apply_pragmas(&conn).await?;76 apply_pragmas(&conn).await?;
@@ -170,6 +171,28 @@ impl Store {
170 }171 }
171 }172 }
172 173
174+/// Creates the database file and its `-wal` and `-shm` sidecars as empty 0600 files when they do not exist,
175+/// so turso never creates them with the umask default. A file that exists is left alone here.
176+fn create_private_files(path: &Path) -> Result<()> {
177+ use std::os::unix::fs::OpenOptionsExt;
178+
179+ for suffix in ["", "-wal", "-shm"] {
180+ let mut name = path.as_os_str().to_owned();
181+ name.push(suffix);
182+ match std::fs::OpenOptions::new()
183+ .write(true)
184+ .create_new(true)
185+ .mode(0o600)
186+ .open(std::path::PathBuf::from(name))
187+ {
188+ Ok(_) => {}
189+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
190+ Err(e) => return Err(e.into()),
191+ }
192+ }
193+ Ok(())
194+}
195+
173 /// Makes the database file and its `-wal` and `-shm` sidecars private (mode 0600). They hold every row,196 /// Makes the database file and its `-wal` and `-shm` sidecars private (mode 0600). They hold every row,
174 /// including sealed secrets, so no other local user may read them whatever the process umask was. Runs197 /// including sealed secrets, so no other local user may read them whatever the process umask was. Runs
175 /// after the connections are open, when the sidecars exist.198 /// after the connections are open, when the sidecars exist.
crates/im-web/src/auth.rsmodified+13 -1
@@ -271,7 +271,7 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> {
271 }271 }
272 272
273 /// A password-verified sign-in that waits for its second factor.273 /// A password-verified sign-in that waits for its second factor.
274-#[derive(Debug, Clone, PartialEq, Eq)]274+#[derive(Clone, PartialEq, Eq)]
275 pub struct Pending {275 pub struct Pending {
276 /// Random id of this pending sign-in. The second factor spends it once (`Store::consume_pending_login`).276 /// Random id of this pending sign-in. The second factor spends it once (`Store::consume_pending_login`).
277 pub nonce: String,277 pub nonce: String,
@@ -283,6 +283,18 @@ pub struct Pending {
283 pub next: String,283 pub next: String,
284 }284 }
285 285
286+/// Prints every field, except that the nonce prints as `<redacted>`: spending it signs the person in.
287+impl std::fmt::Debug for Pending {
288+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289+ f.debug_struct("Pending")
290+ .field("nonce", &format_args!("<redacted>"))
291+ .field("user_id", &self.user_id)
292+ .field("amr", &self.amr)
293+ .field("next", &self.next)
294+ .finish()
295+ }
296+}
297+
286 /// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance298 /// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance
287 /// key, so the browser can neither change the person nor extend the expiry. It carries a random nonce,299 /// key, so the browser can neither change the person nor extend the expiry. It carries a random nonce,
288 /// which a successful second factor spends, so the same cookie cannot sign in twice.300 /// which a successful second factor spends, so the same cookie cannot sign in twice.
crates/im-web/src/backups.rsmodified+3 -2
@@ -169,14 +169,15 @@ async fn write_and_prune(
169 Ok(set)169 Ok(set)
170 }170 }
171 171
172-/// Sends one dead-man ping. Failures are logged; they never fail the backup.172+/// Sends one dead-man ping. Failures are logged; they never fail the backup. The URL holds the healthcheck
173+/// id, a secret, so a transport error is logged without it.
173 async fn ping(http: &reqwest::Client, url: &str) {174 async fn ping(http: &reqwest::Client, url: &str) {
174 match http.get(url).send().await {175 match http.get(url).send().await {
175 Ok(response) if response.status().is_success() => {}176 Ok(response) if response.status().is_success() => {}
176 Ok(response) => {177 Ok(response) => {
177 tracing::warn!(status = %response.status(), "dead-man ping answered with an error");178 tracing::warn!(status = %response.status(), "dead-man ping answered with an error");
178 }179 }
179- Err(error) => tracing::warn!(error = %error, "dead-man ping failed"),180+ Err(error) => tracing::warn!(error = %error.without_url(), "dead-man ping failed"),
180 }181 }
181 }182 }
182 183
crates/im-web/src/boot.rsmodified+27 -1
@@ -10,7 +10,7 @@ use std::os::unix::fs::PermissionsExt;
10 use std::path::Path;10 use std::path::Path;
11 use std::sync::{Arc, RwLock};11 use std::sync::{Arc, RwLock};
12 12
13-use im_core::config::{Config, PolicyConfig};13+use im_core::config::{Config, PolicyConfig, SmtpTls};
14 use im_core::photo::MAX_UPLOAD_BYTES;14 use im_core::photo::MAX_UPLOAD_BYTES;
15 use im_core::secret;15 use im_core::secret;
16 use im_core::store::Store;16 use im_core::store::Store;
@@ -69,6 +69,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> {
69 let listen = config.listen;69 let listen = config.listen;
70 let _lock = lock_data_dir(&config.data_dir)?;70 let _lock = lock_data_dir(&config.data_dir)?;
71 let state = open_state(config).await?;71 let state = open_state(config).await?;
72+ warn_weak_settings(&state);
72 73
73 let listener = TcpListener::bind(listen).await.map_err(|error| {74 let listener = TcpListener::bind(listen).await.map_err(|error| {
74 std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}"))75 std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}"))
@@ -126,6 +127,29 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> {
126 Ok(())127 Ok(())
127 }128 }
128 129
130+/// Logs one warning for each setting that weakens the instance or does not fit its deployment. The server
131+/// still starts: each is a choice an operator may have made on purpose. The policy is the one in effect,
132+/// so an administrator's saved setting counts too.
133+fn warn_weak_settings(state: &AppState) {
134+ let config = &state.config;
135+ if !state.policy().require_2fa_for_admins {
136+ tracing::warn!(
137+ "require_2fa_for_admins is off: administrators may sign in without two-factor sign-in"
138+ );
139+ }
140+ if config.smtp.tls == SmtpTls::None {
141+ tracing::warn!("smtp tls is none: mail is sent to the relay without encryption");
142+ }
143+ if !config.backup.enabled() {
144+ tracing::warn!("backups are not configured: no scheduled copy of the database is made");
145+ }
146+ if config.trusted_proxies.is_empty() && config.listen.ip().is_loopback() {
147+ tracing::warn!(
148+ "trusted_proxies is empty while listen is a loopback address: behind a proxy, every client shares one IP for throttling"
149+ );
150+ }
151+}
152+
129 /// Creates the data directory and opens the key and the database. Everything the router needs153 /// Creates the data directory and opens the key and the database. Everything the router needs
130 /// that touches the disk is ready when this returns. The signing keys are made ready too, so the154 /// that touches the disk is ready when this returns. The signing keys are made ready too, so the
131 /// first token can be signed. The operator commands use this as well.155 /// first token can be signed. The operator commands use this as well.
@@ -165,6 +189,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> {
165 live: Arc::new(LiveHub::default()),189 live: Arc::new(LiveHub::default()),
166 backup: Arc::new(BackupTrigger::default()),190 backup: Arc::new(BackupTrigger::default()),
167 throttle: Arc::new(Throttle::default()),191 throttle: Arc::new(Throttle::default()),
192+ two_factor_days: Arc::new(Throttle::two_factor_days()),
168 photo_uploads: Arc::new(Throttle::photo_uploads()),193 photo_uploads: Arc::new(Throttle::photo_uploads()),
169 email_changes: Arc::new(Throttle::email_changes()),194 email_changes: Arc::new(Throttle::email_changes()),
170 per_minute: Arc::new(Throttle::per_minute()),195 per_minute: Arc::new(Throttle::per_minute()),
@@ -291,6 +316,7 @@ mod tests {
291 live: Arc::new(LiveHub::default()),316 live: Arc::new(LiveHub::default()),
292 backup: Arc::new(BackupTrigger::default()),317 backup: Arc::new(BackupTrigger::default()),
293 throttle: Arc::new(Throttle::default()),318 throttle: Arc::new(Throttle::default()),
319+ two_factor_days: Arc::new(Throttle::two_factor_days()),
294 photo_uploads: Arc::new(Throttle::photo_uploads()),320 photo_uploads: Arc::new(Throttle::photo_uploads()),
295 email_changes: Arc::new(Throttle::email_changes()),321 email_changes: Arc::new(Throttle::email_changes()),
296 per_minute: Arc::new(Throttle::per_minute()),322 per_minute: Arc::new(Throttle::per_minute()),
crates/im-web/src/mail/mod.rsmodified+51 -1
@@ -40,7 +40,7 @@ pub enum Notice {
40 }40 }
41 41
42 /// One kind of mail, with the values its text needs. A link is already built by the caller.42 /// One kind of mail, with the values its text needs. A link is already built by the caller.
43-#[derive(Clone, Copy, Debug)]43+#[derive(Clone, Copy)]
44 pub enum Mail<'a> {44 pub enum Mail<'a> {
45 /// An administrator invited the recipient to create an account.45 /// An administrator invited the recipient to create an account.
46 Invite {46 Invite {
@@ -101,6 +101,56 @@ pub enum Mail<'a> {
101 },101 },
102 }102 }
103 103
104+/// Prints every value except the links, which print as `<redacted>`: each link carries a token.
105+impl std::fmt::Debug for Mail<'_> {
106+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107+ match self {
108+ Mail::Invite { days, .. } => f
109+ .debug_struct("Invite")
110+ .field("link", &format_args!("<redacted>"))
111+ .field("days", days)
112+ .finish(),
113+ Mail::Reset { minutes, .. } => f
114+ .debug_struct("Reset")
115+ .field("link", &format_args!("<redacted>"))
116+ .field("minutes", minutes)
117+ .finish(),
118+ Mail::EmailOld {
119+ new_email, hours, ..
120+ } => f
121+ .debug_struct("EmailOld")
122+ .field("link", &format_args!("<redacted>"))
123+ .field("new_email", new_email)
124+ .field("hours", hours)
125+ .finish(),
126+ Mail::EmailNew { hours, .. } => f
127+ .debug_struct("EmailNew")
128+ .field("link", &format_args!("<redacted>"))
129+ .field("hours", hours)
130+ .finish(),
131+ Mail::EmailDone { new_email } => f
132+ .debug_struct("EmailDone")
133+ .field("new_email", new_email)
134+ .finish(),
135+ Mail::EmailTaken { issuer } => f
136+ .debug_struct("EmailTaken")
137+ .field("issuer", issuer)
138+ .finish(),
139+ Mail::Security(notice) => f.debug_tuple("Security").field(notice).finish(),
140+ Mail::Notice { subject, body } => f
141+ .debug_struct("Notice")
142+ .field("subject", subject)
143+ .field("body", body)
144+ .finish(),
145+ Mail::Test { subject, body } => f
146+ .debug_struct("Test")
147+ .field("subject", subject)
148+ .field("body", body)
149+ .finish(),
150+ }
151+ }
152+}
153+
104 impl Mail<'_> {154 impl Mail<'_> {
105 /// The stored kind, one of the values `mail_outbox.kind` allows.155 /// The stored kind, one of the values `mail_outbox.kind` allows.
106 pub fn kind(&self) -> &'static str {156 pub fn kind(&self) -> &'static str {
crates/im-web/src/pages/login.rsmodified+3 -8
@@ -33,8 +33,7 @@ use crate::i18n::Lang;
33 use crate::i18n::account::{Txt, text};33 use crate::i18n::account::{Txt, text};
34 use crate::state::AppState;34 use crate::state::AppState;
35 use crate::throttle::{35 use crate::throttle::{
36- LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key,36+ LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, ip_key, login_audit_key, user_key,
37- login_audit_key, two_factor_key, user_key,
38 };37 };
39 use crate::views::{alert, field, page_lang, shell};38 use crate::views::{alert, field, page_lang, shell};
40 39
@@ -227,11 +226,7 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
227 }226 }
228 };227 };
229 let csrf = pre_csrf_token(cx);228 let csrf = pre_csrf_token(cx);
230- let limit = two_factor_key(&user.id);229+ if let Err(wait) = state.reserve_second_factor(&user.id) {
231- if let Err(wait) = state
232- .throttle
233- .reserve(&limit, TWO_FACTOR_USER_LIMIT, Instant::now())
234- {
235 retry_after(cx, wait);230 retry_after(cx, wait);
236 return Ok(two_factor_view(231 return Ok(two_factor_view(
237 cx,232 cx,
@@ -255,7 +250,7 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
255 }250 }
256 match check_second_factor(&state.store, &state.key, &user, &form.code).await {251 match check_second_factor(&state.store, &state.key, &user, &form.code).await {
257 Ok(Some(method)) => {252 Ok(Some(method)) => {
258- state.throttle.clear(&limit);253+ state.clear_second_factor(&user.id);
259 clear_pending_login(cx);254 clear_pending_login(cx);
260 match finish_sign_in(cx, &user, method, &pending.next).await? {255 match finish_sign_in(cx, &user, method, &pending.next).await? {
261 Some(redirect) => Err(redirect),256 Some(redirect) => Err(redirect),
crates/im-web/src/pages/security.rsmodified+5 -15
@@ -26,7 +26,7 @@ use crate::i18n::account::{Txt, policy_problem, recovery_left, text};
26 use crate::live::Topic;26 use crate::live::Topic;
27 use crate::mail::{self, Notice};27 use crate::mail::{self, Notice};
28 use crate::state::AppState;28 use crate::state::AppState;
29-use crate::throttle::{LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, two_factor_key, user_key};29+use crate::throttle::{LOGIN_USER_LIMIT, user_key};
30 use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};30 use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
31 31
32 /// How many recovery codes one issue gives.32 /// How many recovery codes one issue gives.
@@ -209,12 +209,7 @@ async fn start_enrolment(cx: &Cx, Form(form): Form<StartForm>) -> Result<impl Vi
209 )209 )
210 .await;210 .await;
211 }211 }
212- let limit = two_factor_key(&viewer.user.id);212+ if state.reserve_second_factor(&viewer.user.id).is_err() {
213- if state
214- .throttle
215- .reserve(&limit, TWO_FACTOR_USER_LIMIT, Instant::now())
216- .is_err()
217- {
218 return render_security(213 return render_security(
219 cx,214 cx,
220 viewer.clone(),215 viewer.clone(),
@@ -233,7 +228,7 @@ async fn start_enrolment(cx: &Cx, Form(form): Form<StartForm>) -> Result<impl Vi
233 )228 )
234 .await;229 .await;
235 }230 }
236- state.throttle.refund(&limit);231+ state.refund_second_factor(&viewer.user.id);
237 } else if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {232 } else if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
238 // Turning two-factor sign-in on is a change of the account, so the password is needed too.233 // Turning two-factor sign-in on is a change of the account, so the password is needed too.
239 return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;234 return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
@@ -354,12 +349,7 @@ async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
354 )349 )
355 .await;350 .await;
356 }351 }
357- let limit = two_factor_key(&viewer.user.id);352+ if state.reserve_second_factor(&viewer.user.id).is_err() {
358- if state
359- .throttle
360- .reserve(&limit, TWO_FACTOR_USER_LIMIT, Instant::now())
361- .is_err()
362- {
363 return render_security(353 return render_security(
364 cx,354 cx,
365 viewer.clone(),355 viewer.clone(),
@@ -384,7 +374,7 @@ async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
384 .store374 .store
385 .disable_totp(&viewer.user.id, Some(&viewer.session.id))375 .disable_totp(&viewer.user.id, Some(&viewer.session.id))
386 .await?;376 .await?;
387- state.throttle.clear(&limit);377+ state.clear_second_factor(&viewer.user.id);
388 changed(state, &viewer);378 changed(state, &viewer);
389 record(379 record(
390 cx,380 cx,
crates/im-web/src/service_probe.rsmodified+1 -1
@@ -114,7 +114,7 @@ async fn probe(http: &reqwest::Client, key: &str, origin: &str) -> bool {
114 let mut response = match http.get(&target).send().await {114 let mut response = match http.get(&target).send().await {
115 Ok(response) => response,115 Ok(response) => response,
116 Err(error) => {116 Err(error) => {
117- tracing::warn!(service = %key, error = %error, "service probe failed");117+ tracing::warn!(service = %key, error = %error.without_url(), "service probe failed");
118 return false;118 return false;
119 }119 }
120 };120 };
crates/im-web/src/state.rsmodified+32 -1
@@ -1,6 +1,7 @@
1 //! The state shared by every route. Topcoat hands it to each handler through the app context.1 //! The state shared by every route. Topcoat hands it to each handler through the app context.
2 2
3 use std::sync::{Arc, PoisonError, RwLock};3 use std::sync::{Arc, PoisonError, RwLock};
4+use std::time::{Duration, Instant};
4 5
5 use im_core::config::{Config, PolicyConfig};6 use im_core::config::{Config, PolicyConfig};
6 use im_core::store::Store;7 use im_core::store::Store;
@@ -9,7 +10,7 @@ use tokio::sync::{Semaphore, watch};
9 use crate::api::directory::StreamSlots;10 use crate::api::directory::StreamSlots;
10 use crate::backups::BackupTrigger;11 use crate::backups::BackupTrigger;
11 use crate::live::LiveHub;12 use crate::live::LiveHub;
12-use crate::throttle::Throttle;13+use crate::throttle::{TWO_FACTOR_DAY_LIMIT, TWO_FACTOR_USER_LIMIT, Throttle, two_factor_key};
13 14
14 /// Everything a request handler reaches through the app context. Every field is cheap to clone.15 /// Everything a request handler reaches through the app context. Every field is cheap to clone.
15 #[derive(Clone)]16 #[derive(Clone)]
@@ -30,6 +31,8 @@ pub struct AppState {
30 pub backup: Arc<BackupTrigger>,31 pub backup: Arc<BackupTrigger>,
31 /// Failed sign-in and second-factor counters.32 /// Failed sign-in and second-factor counters.
32 pub throttle: Arc<Throttle>,33 pub throttle: Arc<Throttle>,
34+ /// Failed second-factor checks per account, one day window (see `throttle::TWO_FACTOR_DAY_LIMIT`).
35+ pub two_factor_days: Arc<Throttle>,
33 /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`).36 /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`).
34 pub photo_uploads: Arc<Throttle>,37 pub photo_uploads: Arc<Throttle>,
35 /// Email-change requests per account, one hour window (see `throttle::EMAIL_CHANGE_LIMIT`).38 /// Email-change requests per account, one hour window (see `throttle::EMAIL_CHANGE_LIMIT`).
@@ -67,4 +70,32 @@ impl AppState {
67 .write()70 .write()
68 .unwrap_or_else(PoisonError::into_inner) = policy;71 .unwrap_or_else(PoisonError::into_inner) = policy;
69 }72 }
73+
74+ /// Counts one second-factor attempt of `user_id` against both the short and the day window. Nothing
75+ /// is counted when either refuses; the wait of the refusing window comes back.
76+ pub fn reserve_second_factor(&self, user_id: &str) -> Result<(), Duration> {
77+ let key = two_factor_key(user_id);
78+ let now = Instant::now();
79+ self.two_factor_days
80+ .reserve(&key, TWO_FACTOR_DAY_LIMIT, now)?;
81+ self.throttle
82+ .reserve(&key, TWO_FACTOR_USER_LIMIT, now)
83+ .inspect_err(|_| self.two_factor_days.refund(&key))
84+ }
85+
86+ /// Forgets the second-factor failures of `user_id` after a correct code: the short window is cleared,
87+ /// and the day window gives back the attempt just counted.
88+ pub fn clear_second_factor(&self, user_id: &str) {
89+ let key = two_factor_key(user_id);
90+ self.throttle.clear(&key);
91+ self.two_factor_days.refund(&key);
92+ }
93+
94+ /// Gives back the attempt just counted in both windows, for a correct code that keeps the short
95+ /// window as it was.
96+ pub fn refund_second_factor(&self, user_id: &str) {
97+ let key = two_factor_key(user_id);
98+ self.throttle.refund(&key);
99+ self.two_factor_days.refund(&key);
100+ }
70 }101 }
crates/im-web/src/throttle.rsmodified+13 -0
@@ -40,6 +40,14 @@ pub const LOGIN_IP_LIMIT: usize = 30;
40 /// Failed second-factor checks allowed per user inside [`WINDOW`].40 /// Failed second-factor checks allowed per user inside [`WINDOW`].
41 pub const TWO_FACTOR_USER_LIMIT: usize = 10;41 pub const TWO_FACTOR_USER_LIMIT: usize = 10;
42 42
43+/// Failed second-factor checks allowed per user inside [`TWO_FACTOR_DAY_WINDOW`]. It works beside
44+/// [`TWO_FACTOR_USER_LIMIT`], so a guesser who pauses between windows still runs out.
45+pub const TWO_FACTOR_DAY_LIMIT: usize = 30;
46+
47+/// Length of the second-factor day window: 24 hours. Kept on its own [`Throttle`] (see
48+/// [`Throttle::two_factor_days`]), because a throttle has one window for all its keys.
49+pub const TWO_FACTOR_DAY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60);
50+
43 /// Reset-link requests allowed per normalised email address inside [`WINDOW`]. Every request counts, known51 /// Reset-link requests allowed per normalised email address inside [`WINDOW`]. Every request counts, known
44 /// address or not, so the limit leaks nothing about the account.52 /// address or not, so the limit leaks nothing about the account.
45 pub const FORGOT_EMAIL_LIMIT: usize = 3;53 pub const FORGOT_EMAIL_LIMIT: usize = 3;
@@ -138,6 +146,11 @@ impl Throttle {
138 Self::with_limits(EMAIL_CHANGE_WINDOW, MAX_KEYS)146 Self::with_limits(EMAIL_CHANGE_WINDOW, MAX_KEYS)
139 }147 }
140 148
149+ /// The day-long counters of second-factor checks: 24 hour window, the same key cap.
150+ pub fn two_factor_days() -> Self {
151+ Self::with_limits(TWO_FACTOR_DAY_WINDOW, MAX_KEYS)
152+ }
153+
141 /// Counters with a custom window and key cap. Tests use short windows.154 /// Counters with a custom window and key cap. Tests use short windows.
142 pub fn with_limits(window: Duration, max_keys: usize) -> Self {155 pub fn with_limits(window: Duration, max_keys: usize) -> Self {
143 Self {156 Self {
docs/architecture.mdmodified+2 -2
@@ -148,7 +148,7 @@ way; the throttle still counts every failure.
148 148
149 **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password).149 **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password).
150 150
151-Files beside the DB in `data_dir`: `im.key`, `photos/<user_id>` (0600, written by temp file + fsync + rename). Photo upload and removal run under one151+The database file and its `-wal` and `-shm` sidecars are created 0600 before turso opens them, and chmod'd again after. Files beside the DB in `data_dir`: `im.key`, `photos/<user_id>` (0600, written by temp file + fsync + rename). Photo upload and removal run under one
152 process-wide lock (`photo_lock`), so a removal cannot delete a file a parallel upload has just put in place.152 process-wide lock (`photo_lock`), so a removal cannot delete a file a parallel upload has just put in place.
153 153
154 ---154 ---
@@ -206,7 +206,7 @@ redirects). Other errors redirect to the client with `error=` and `state`.
206 - Login order (forge): pre-CSRF → throttle (account key and IP key) → lookup (unknown → dummy verify) → password206 - Login order (forge): pre-CSRF → throttle (account key and IP key) → lookup (unknown → dummy verify) → password
207 → disabled check (revealed only after a correct password) → 2FA step or session.207 → disabled check (revealed only after a correct password) → 2FA step or session.
208 - Pending 2FA: sealed cookie `__Host-im_pending` (`user_id|expires|next|amr`), SameSite=Strict, 5 minutes.208 - Pending 2FA: sealed cookie `__Host-im_pending` (`user_id|expires|next|amr`), SameSite=Strict, 5 minutes.
209-- Second factor: 6 digits → TOTP with replay guard; `xxxx-xxxx` → recovery code (consumed). Throttled per user.209+- Second factor: 6 digits → TOTP with replay guard; `xxxx-xxxx` → recovery code (consumed). Throttled per user: 10 failures per 15 minutes and 30 per 24 hours.
210 - Session: 30 days idle-extended up to `session_max_days` (policy), cookie `__Host-im_session`. At most210 - Session: 30 days idle-extended up to `session_max_days` (policy), cookie `__Host-im_session`. At most
211 `max_sessions` per user: the oldest is ended (with back-channel) when exceeded.211 `max_sessions` per user: the oldest is ended (with back-channel) when exceeded.
212 - Limits beyond the failure counters (`throttle.rs`, in memory, refused with `429` or an OAuth error):212 - Limits beyond the failure counters (`throttle.rs`, in memory, refused with `429` or an OAuth error):