diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index b2a8482..193e1ce 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -67,10 +67,14 @@ pub enum AccountError { InvalidCredentials, #[error("this invite is not valid")] InviteInvalid, - #[error("this invite has expired")] - InviteExpired, + /// Unknown, spent or expired — one refusal for all three, so the page + /// never says which. + #[error("this reset link is not valid")] + ResetInvalid, #[error("this invite was already used")] InviteSpent, + #[error("this invite has expired")] + InviteExpired, #[error("an account with this address already exists")] EmailTaken, #[error("password: {0}")] @@ -240,31 +244,32 @@ pub async fn create_invite( } let token = Token::mint(); let now = store::now(); - let expires = now + time::Duration::days(INVITE_DAYS); - store - .conn - .execute( - "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \ + // The panel's Settings section owns this number now; the constant is the + // fresh-database default, not the value. + let expires = now + time::Duration::days(crate::settings::invite_days(store).await?); + let conn = store.conn.lock().await; + conn.execute( + "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - turso::params![ - token.hash(), - email, - invited_by.map(|id| id.to_string()), - admin as i64, - store::stamp(now)?, - store::stamp(expires)?, - ], - ) - .await - .map_err(backend)?; + turso::params![ + token.hash(), + email, + invited_by.map(|id| id.to_string()), + admin as i64, + store::stamp(now)?, + store::stamp(expires)?, + ], + ) + .await + .map_err(backend)?; Ok(token) } /// Looks an invite up by its raw token. Expiry and spent-ness are the /// caller's to rule on — this answers what the row says. pub async fn invite_by_token(store: &Store, token: &str) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT email, invited_by, admin, created_at, expires_at, accepted_at \ FROM invites WHERE token = ?1", @@ -303,8 +308,8 @@ pub struct PendingInvite { /// Invites not yet accepted and not yet expired, oldest first. pub async fn list_pending_invites(store: &Store) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT token, email, admin, created_at, expires_at FROM invites \ WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at", @@ -328,8 +333,8 @@ pub async fn list_pending_invites(store: &Store) -> Result> { /// Invalidates an invite: the row is gone, the link reads "not valid" from /// that moment on. Returns the address it was made out to, for the log line. pub async fn revoke_invite(store: &Store, token_hash: &str) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT email FROM invites WHERE token = ?1", turso::params![token_hash], @@ -340,14 +345,12 @@ pub async fn revoke_invite(store: &Store, token_hash: &str) -> Result(()) + } + .await; + match outcome { + Ok(()) => { + conn.execute("COMMIT", ()).await.map_err(backend)?; + Ok(user) + } + Err(e) => { + let _ = conn.execute("ROLLBACK", ()).await; + Err(e) + } + } +} + +// --------------------------------------------------------------------------- +// Password reset +// --------------------------------------------------------------------------- + +/// Mints a reset link for the account at `email`, retiring every previous +/// live one first: two reset mails means the first is already dead — the +/// newest link is the only door. `None` for an address with no account, so +/// the web layer can answer every address identically. +pub async fn create_reset( + store: &Store, + email: &str, +) -> std::result::Result, AccountError> { + let Some(user) = user_by_email(store, email).await? else { + return Ok(None); + }; + let token = Token::mint(); + let now = store::now(); + let expires = now + time::Duration::minutes(crate::settings::reset_minutes(store).await?); + let conn = store.conn.lock().await; + conn.execute( + "DELETE FROM reset_links WHERE user_id = ?1 AND used_at IS NULL", + turso::params![user.id.to_string()], + ) + .await + .map_err(backend)?; + conn.execute( + "INSERT INTO reset_links (token, user_id, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4)", + turso::params![ + token.hash(), + user.id.to_string(), + store::stamp(now)?, + store::stamp(expires)?, + ], + ) + .await + .map_err(backend)?; + Ok(Some(token)) +} + +/// Turns a valid reset link into a new password. The link is spent, the hash +/// replaced, and every session revoked in one transaction — the old +/// password's doors close the moment the new one exists. +pub async fn redeem_reset( + store: &Store, + token: &str, + password: &str, +) -> std::result::Result { + let hash = hash_token(token); + // Short-held read first: the row says whether the link may be redeemed. + let (user_id, expires_at, used) = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT user_id, expires_at, used_at FROM reset_links WHERE token = ?1", + turso::params![hash.clone()], ) .await - .map_err(|e| AccountError::Backend(e.to_string()))?; + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Err(AccountError::ResetInvalid); + }; + ( + UserId::from(store::text(&row, 0)?), + store::parse_stamp(&store::text(&row, 1)?)?, + store::opt_text(&row, 2)?.is_some(), + ) + }; + if used || expires_at < store::now() { + return Err(AccountError::ResetInvalid); + } + let user = user_by_id(store, &user_id) + .await? + .ok_or(AccountError::ResetInvalid)?; + check_password(password, &user.email, &user.name)?; + let password_hash = hash_password(password)?; + + // The write half holds the lock across its transaction; revocation comes + // after COMMIT because `revoke_user_sessions` locks for itself. + let conn = store.conn.lock().await; + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; + let outcome = async { + conn.execute( + "UPDATE reset_links SET used_at = ?1 WHERE token = ?2 AND used_at IS NULL", + turso::params![store::stamp(store::now())?, hash], + ) + .await + .map_err(|e| AccountError::Backend(e.to_string()))?; + conn.execute( + "UPDATE users SET password_hash = ?1 WHERE id = ?2", + turso::params![password_hash, user.id.to_string()], + ) + .await + .map_err(|e| AccountError::Backend(e.to_string()))?; Ok::<_, AccountError>(()) } .await; match outcome { Ok(()) => { - store.conn.execute("COMMIT", ()).await.map_err(backend)?; + conn.execute("COMMIT", ()).await.map_err(backend)?; + drop(conn); + crate::sessions::revoke_user_sessions(store, &user.id) + .await + .map_err(|e| AccountError::Backend(e.to_string()))?; + // Owning the mailbox is the proof; past failures stop counting. + clear_login_failures(store, &user.email).await?; Ok(user) } Err(e) => { - let _ = store.conn.execute("ROLLBACK", ()).await; + let _ = conn.execute("ROLLBACK", ()).await; Err(e) } } } +// --------------------------------------------------------------------------- +// Sign-in rate limiting +// --------------------------------------------------------------------------- + +/// The counter is a rolling hour of failures per key — the address for +/// passwords, `totp:{user}` for second factors. Reads and writes both sweep +/// their own key's stale rows, so the table never grows without bound. +async fn sweep_attempts(store: &Store, key: &str) -> Result<()> { + let conn = store.conn.lock().await; + let cutoff = store::stamp(store::now() - time::Duration::hours(1))?; + conn.execute( + "DELETE FROM login_attempts WHERE key = ?1 AND at < ?2", + turso::params![key, cutoff], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// True when the key has burned through the panel's per-hour allowance. +pub async fn login_blocked(store: &Store, key: &str) -> Result { + sweep_attempts(store, key).await?; + let cutoff = store::stamp(store::now() - time::Duration::hours(1))?; + let count = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT COUNT(*) FROM login_attempts WHERE key = ?1 AND at >= ?2", + turso::params![key, cutoff], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => store::int(&row, 0)?, + None => 0, + } + }; + // The limit reads settings, which locks for itself — the count's guard is + // already gone. + Ok(count >= crate::settings::login_attempts_per_hour(store).await?) +} + +/// Writes down a failure. Success is the caller's job to record too — by +/// clearing, with [`clear_login_failures`]. +pub async fn record_login_failure(store: &Store, key: &str) -> Result<()> { + sweep_attempts(store, key).await?; + let conn = store.conn.lock().await; + conn.execute( + "INSERT INTO login_attempts (key, at) VALUES (?1, ?2)", + turso::params![key, store::stamp(store::now())?], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// A success wipes the slate: the next failure starts from zero. +pub async fn clear_login_failures(store: &Store, key: &str) -> Result<()> { + let conn = store.conn.lock().await; + conn.execute( + "DELETE FROM login_attempts WHERE key = ?1", + turso::params![key], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// Whether the reset page may stand: the link exists, unspent, unexpired. +/// Redemption re-checks in its transaction — this is only the page's +/// early answer, so a dead link never shows a working form. +pub async fn reset_link_valid(store: &Store, token: &str) -> Result { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT expires_at, used_at FROM reset_links WHERE token = ?1", + turso::params![hash_token(token)], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(false); + }; + let expires_at = store::parse_stamp(&store::text(&row, 0)?)?; + Ok(store::opt_text(&row, 1)?.is_none() && expires_at >= store::now()) +} + /// Verifies an email+password pair, returning the user on success. Disabled /// accounts are refused with the same wording as a wrong password, and every /// miss path burns an Argon2 run so timing does not say which one it was. @@ -441,8 +641,8 @@ pub async fn verify_login( email: &str, password: &str, ) -> std::result::Result { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at \ FROM users WHERE email = ?1 COLLATE NOCASE", @@ -481,8 +681,8 @@ pub async fn change_password( current: &str, new: &str, ) -> std::result::Result<(), AccountError> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT password_hash FROM users WHERE id = ?1", turso::params![user.id.to_string()], @@ -500,37 +700,38 @@ pub async fn change_password( if verify_password(new, &phc) { return Err(PasswordProblem::IsCurrent.into()); } - store - .conn - .execute( - "UPDATE users SET password_hash = ?1 WHERE id = ?2", - turso::params![hash_password(new)?, user.id.to_string()], - ) - .await - .map_err(backend)?; + conn.execute( + "UPDATE users SET password_hash = ?1 WHERE id = ?2", + turso::params![hash_password(new)?, user.id.to_string()], + ) + .await + .map_err(backend)?; Ok(()) } /// Looks a user up by email — the CLI's revoke path resolves names this way. pub async fn user_by_email(store: &Store, email: &str) -> Result> { - let mut rows = store - .conn - .query( - "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE", - turso::params![email], - ) - .await - .map_err(backend)?; - let Some(row) = rows.next().await.map_err(backend)? else { - return Ok(None); + let id = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE", + turso::params![email], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => UserId::from(store::text(&row, 0)?), + None => return Ok(None), + } }; - let id = UserId::from(store::text(&row, 0)?); + // The id is in hand; the full row's lookup locks for itself. user_by_id(store, &id).await } pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ FROM users WHERE id = ?1", @@ -557,6 +758,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { /// account should not exist" — the OIDC subject dies with it, and if the /// person returns they get a fresh one. pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> { + let conn = store.conn.lock().await; let id = user.to_string(); for sql in [ "DELETE FROM app_sessions WHERE user_id = ?1", @@ -565,9 +767,7 @@ pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> { "UPDATE invites SET invited_by = NULL WHERE invited_by = ?1", "DELETE FROM users WHERE id = ?1", ] { - store - .conn - .execute(sql, turso::params![id.clone()]) + conn.execute(sql, turso::params![id.clone()]) .await .map_err(backend)?; } @@ -576,8 +776,8 @@ pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> { /// Every user, oldest first — the admin panel's roster. pub async fn list_users(store: &Store) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ FROM users ORDER BY created_at", @@ -604,28 +804,26 @@ pub async fn list_users(store: &Store) -> Result> { /// sessions resolve to nobody, and introspection says inactive — every door /// closes on the same flag. pub async fn set_disabled(store: &Store, user: &UserId, disabled: bool) -> Result<()> { - store - .conn - .execute( - "UPDATE users SET disabled = ?1 WHERE id = ?2", - turso::params![disabled as i64, user.to_string()], - ) - .await - .map_err(backend)?; + let conn = store.conn.lock().await; + conn.execute( + "UPDATE users SET disabled = ?1 WHERE id = ?2", + turso::params![disabled as i64, user.to_string()], + ) + .await + .map_err(backend)?; Ok(()) } /// Grants or revokes im's admin flag. Never crosses a token — this is im's /// own panel, not a claim apps ever see. pub async fn set_admin(store: &Store, user: &UserId, admin: bool) -> Result<()> { - store - .conn - .execute( - "UPDATE users SET admin = ?1 WHERE id = ?2", - turso::params![admin as i64, user.to_string()], - ) - .await - .map_err(backend)?; + let conn = store.conn.lock().await; + conn.execute( + "UPDATE users SET admin = ?1 WHERE id = ?2", + turso::params![admin as i64, user.to_string()], + ) + .await + .map_err(backend)?; Ok(()) } @@ -845,4 +1043,91 @@ mod tests { .is_ok() ); } + + #[tokio::test] + async fn a_second_reset_link_kills_the_first() { + let store = fixture().await; + let invite = create_invite(&store, "ann@example.com", None, false) + .await + .unwrap(); + let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") + .await + .unwrap(); + let session = crate::sessions::create_session(&store, &user.id) + .await + .unwrap(); + + // No account, no link — and nothing learned. + assert!( + create_reset(&store, "nobody@example.com") + .await + .unwrap() + .is_none() + ); + + let first = create_reset(&store, "ann@example.com") + .await + .unwrap() + .unwrap(); + let second = create_reset(&store, "ann@example.com") + .await + .unwrap() + .unwrap(); + // The first mail's link died the moment the second was minted. + assert!(matches!( + redeem_reset(&store, first.expose(), "Xk9#mQ2vLpR7").await, + Err(AccountError::ResetInvalid) + )); + + let changed = redeem_reset(&store, second.expose(), "Xk9#mQ2vLpR7") + .await + .unwrap(); + assert_eq!(changed.id, user.id); + // Spent links cannot be replayed, and the old password's sessions + // died with the change. + assert!(matches!( + redeem_reset(&store, second.expose(), "an0ther!Pass99").await, + Err(AccountError::ResetInvalid) + )); + assert!( + crate::sessions::resolve_session(&store, session.expose()) + .await + .unwrap() + .is_none() + ); + assert!( + verify_login(&store, "ann@example.com", "Xk9#mQ2vLpR7") + .await + .is_ok() + ); + } + + #[tokio::test] + async fn rate_limit_blocks_and_success_clears() { + let store = fixture().await; + crate::settings::set_policy( + &store, + &crate::settings::Policy { + login_attempts_per_hour: 3, + ..Default::default() + }, + ) + .await + .unwrap(); + + assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); + for _ in 0..3 { + record_login_failure(&store, "ann@example.com") + .await + .unwrap(); + } + assert!(login_blocked(&store, "ann@example.com").await.unwrap()); + // A different address is untouched. + assert!(!login_blocked(&store, "bob@example.com").await.unwrap()); + + clear_login_failures(&store, "ann@example.com") + .await + .unwrap(); + assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); + } } diff --git a/crates/im-core/src/events.rs b/crates/im-core/src/events.rs index 18ed7d5..f65b9fe 100644 --- a/crates/im-core/src/events.rs +++ b/crates/im-core/src/events.rs @@ -17,8 +17,8 @@ pub struct Event { /// Appends an event. Never fails the caller's operation: a log that cannot /// be written is printed, not propagated. pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option<&str>) { - let outcome = store - .conn + let conn = store.conn.lock().await; + let outcome = conn .execute( "INSERT INTO events (id, at, kind, actor, detail) VALUES (?1, ?2, ?3, ?4, ?5)", turso::params![ @@ -37,8 +37,8 @@ pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option< /// Newest-first page of the log for the admin panel. pub async fn list(store: &Store, limit: i64) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT id, at, kind, actor, detail FROM events ORDER BY at DESC, id DESC LIMIT ?1", turso::params![limit], diff --git a/crates/im-core/src/keys.rs b/crates/im-core/src/keys.rs index e64b0b6..12858b2 100644 --- a/crates/im-core/src/keys.rs +++ b/crates/im-core/src/keys.rs @@ -19,8 +19,8 @@ use crate::store::{self, Result, Store, StoreError, backend}; /// `kid` is a fingerprint of the public half, so a key's id is stable across /// restarts and a JWKS consumer can match header to key without guessing. pub async fn active_signing_key(store: &Store) -> Result<(String, RsaPrivateKey)> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT kid, private_der_enc FROM signing_keys WHERE active = 1 \ ORDER BY created_at DESC LIMIT 1", @@ -53,20 +53,18 @@ pub async fn active_signing_key(store: &Store) -> Result<(String, RsaPrivateKey) .as_bytes() .to_vec(); let kid = kid_of(&public_der); - store - .conn - .execute( - "INSERT INTO signing_keys (kid, private_der_enc, public_der, created_at) \ + conn.execute( + "INSERT INTO signing_keys (kid, private_der_enc, public_der, created_at) \ VALUES (?1, ?2, ?3, ?4)", - turso::params![ - kid.clone(), - secret::seal(store.key(), &private_der), - public_der, - store::stamp(store::now())?, - ], - ) - .await - .map_err(backend)?; + turso::params![ + kid.clone(), + secret::seal(store.key(), &private_der), + public_der, + store::stamp(store::now())?, + ], + ) + .await + .map_err(backend)?; Ok((kid, key)) } @@ -77,9 +75,9 @@ fn kid_of(public_der: &[u8]) -> String { /// Every active public key as a JWKS document. pub async fn jwks(store: &Store) -> Result { + let conn = store.conn.lock().await; use base64::Engine; - let mut rows = store - .conn + let mut rows = conn .query( "SELECT kid, public_der FROM signing_keys WHERE active = 1 ORDER BY created_at", (), @@ -107,8 +105,8 @@ pub async fn jwks(store: &Store) -> Result { /// The public half of an active key, by id — what JWT verification looks up. pub async fn public_key_by_kid(store: &Store, kid: &str) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT public_der FROM signing_keys WHERE kid = ?1 AND active = 1", turso::params![kid], diff --git a/crates/im-core/src/oidc.rs b/crates/im-core/src/oidc.rs index 9ae5732..4030c4e 100644 --- a/crates/im-core/src/oidc.rs +++ b/crates/im-core/src/oidc.rs @@ -61,31 +61,30 @@ pub async fn create_client( name: &str, redirect_uris: Vec, ) -> Result<(ClientId, Token)> { + let conn = store.conn.lock().await; let id = ClientId::mint(); let secret = Token::mint(); - store - .conn - .execute( - "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \ + conn.execute( + "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5)", - turso::params![ - id.to_string(), - name, - secret.hash(), - serde_json::to_string(&redirect_uris) - .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?, - store::stamp(store::now())?, - ], - ) - .await - .map_err(backend)?; + turso::params![ + id.to_string(), + name, + secret.hash(), + serde_json::to_string(&redirect_uris) + .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?, + store::stamp(store::now())?, + ], + ) + .await + .map_err(backend)?; Ok((id, secret)) } /// Looks a client up by its public id. pub async fn client_by_id(store: &Store, client_id: &str) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT client_id, name, secret_hash, redirect_uris, created_at \ FROM oidc_clients WHERE client_id = ?1", @@ -131,9 +130,9 @@ pub async fn create_auth_code( challenge: &str, session_hash: &str, ) -> Result { + let conn = store.conn.lock().await; let code = Token::mint(); - store - .conn + conn .execute( "INSERT INTO auth_codes \ (code_hash, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at) \ @@ -158,15 +157,11 @@ pub async fn create_auth_code( /// `consumed_at` stamp run inside one immediate transaction, so two parallel /// exchanges of the same code cannot both succeed. pub async fn consume_auth_code(store: &Store, code: &str) -> Result> { + let conn = store.conn.lock().await; let hash = hash_token(code); - store - .conn - .execute("BEGIN IMMEDIATE", ()) - .await - .map_err(backend)?; + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; let outcome = async { - let mut rows = store - .conn + let mut rows = conn .query( "SELECT client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, \ expires_at, consumed_at FROM auth_codes WHERE code_hash = ?1", @@ -183,14 +178,12 @@ pub async fn consume_auth_code(store: &Store, code: &str) -> Result Result { - store.conn.execute("COMMIT", ()).await.map_err(backend)?; + conn.execute("COMMIT", ()).await.map_err(backend)?; Ok(found) } Err(e) => { - let _ = store.conn.execute("ROLLBACK", ()).await; + let _ = conn.execute("ROLLBACK", ()).await; Err(e) } } @@ -226,23 +219,22 @@ pub async fn issue_refresh( client_id: &ClientId, session_hash: &str, ) -> Result { + let conn = store.conn.lock().await; let token = Token::mint(); - store - .conn - .execute( - "INSERT INTO refresh_tokens \ + conn.execute( + "INSERT INTO refresh_tokens \ (token_hash, user_id, client_id, session_hash, expires_at) \ VALUES (?1, ?2, ?3, ?4, ?5)", - turso::params![ - token.hash(), - user.to_string(), - client_id.to_string(), - session_hash, - store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?, - ], - ) - .await - .map_err(backend)?; + turso::params![ + token.hash(), + user.to_string(), + client_id.to_string(), + session_hash, + store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?, + ], + ) + .await + .map_err(backend)?; Ok(token) } @@ -251,15 +243,11 @@ pub async fn issue_refresh( /// come back. `None` for unknown, expired, or revoked tokens — and for tokens /// whose central session is gone, which is what makes SSO logout global. pub async fn rotate_refresh(store: &Store, token: &str) -> Result> { + let conn = store.conn.lock().await; let hash = hash_token(token); - store - .conn - .execute("BEGIN IMMEDIATE", ()) - .await - .map_err(backend)?; + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; let outcome = async { - let mut rows = store - .conn + let mut rows = conn .query( "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ FROM refresh_tokens WHERE token_hash = ?1", @@ -283,8 +271,7 @@ pub async fn rotate_refresh(store: &Store, token: &str) -> Result Result { - store.conn.execute("COMMIT", ()).await.map_err(backend)?; + conn.execute("COMMIT", ()).await.map_err(backend)?; Ok(found) } Err(e) => { - let _ = store.conn.execute("ROLLBACK", ()).await; + let _ = conn.execute("ROLLBACK", ()).await; Err(e) } } @@ -428,25 +423,24 @@ pub async fn issue_app_session( client_id: &ClientId, session_hash: &str, ) -> Result { + let conn = store.conn.lock().await; let token = Token::mint(); let now = store::now(); - store - .conn - .execute( - "INSERT INTO app_sessions \ + conn.execute( + "INSERT INTO app_sessions \ (token_hash, user_id, client_id, session_hash, created_at, expires_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - turso::params![ - token.hash(), - user.to_string(), - client_id.to_string(), - session_hash, - store::stamp(now)?, - store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?, - ], - ) - .await - .map_err(backend)?; + turso::params![ + token.hash(), + user.to_string(), + client_id.to_string(), + session_hash, + store::stamp(now)?, + store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?, + ], + ) + .await + .map_err(backend)?; Ok(token) } @@ -458,49 +452,52 @@ pub async fn introspect_app_session( token: &str, client_id: &str, ) -> Result> { - let mut rows = store - .conn - .query( - "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ - FROM app_sessions WHERE token_hash = ?1", - turso::params![hash_token(token)], - ) - .await - .map_err(backend)?; - let Some(row) = rows.next().await.map_err(backend)? else { - return Ok(None); - }; - if store::opt_text(&row, 4)?.is_some() { - return Ok(None); - } - let expires = store::parse_stamp(&store::text(&row, 3)?)?; - if expires < store::now() { - return Ok(None); - } - if store::text(&row, 1)? != client_id { - return Ok(None); - } - // The central session must still be alive — this is what makes admin - // revocation immediate. - let session_hash = store::text(&row, 2)?; - let mut sessions = store - .conn - .query( - "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1", - turso::params![session_hash], - ) - .await - .map_err(backend)?; - let Some(session) = sessions.next().await.map_err(backend)? else { - return Ok(None); + // Both rows are read under one short-held guard; the user lookup locks + // for itself after it drops. + let (user_id, expires) = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ + FROM app_sessions WHERE token_hash = ?1", + turso::params![hash_token(token)], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + if store::opt_text(&row, 4)?.is_some() { + return Ok(None); + } + let expires = store::parse_stamp(&store::text(&row, 3)?)?; + if expires < store::now() { + return Ok(None); + } + if store::text(&row, 1)? != client_id { + return Ok(None); + } + // The central session must still be alive — this is what makes admin + // revocation immediate. + let session_hash = store::text(&row, 2)?; + let mut sessions = conn + .query( + "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1", + turso::params![session_hash], + ) + .await + .map_err(backend)?; + let Some(session) = sessions.next().await.map_err(backend)? else { + return Ok(None); + }; + if store::opt_text(&session, 1)?.is_some() { + return Ok(None); + } + if store::parse_stamp(&store::text(&session, 0)?)? < store::now() { + return Ok(None); + } + (UserId::from(store::text(&row, 0)?), expires) }; - if store::opt_text(&session, 1)?.is_some() { - return Ok(None); - } - if store::parse_stamp(&store::text(&session, 0)?)? < store::now() { - return Ok(None); - } - let user_id = UserId::from(store::text(&row, 0)?); let Some(user) = crate::accounts::user_by_id(store, &user_id).await? else { return Ok(None); }; diff --git a/crates/im-core/src/sessions.rs b/crates/im-core/src/sessions.rs index 8bf69e1..719a130 100644 --- a/crates/im-core/src/sessions.rs +++ b/crates/im-core/src/sessions.rs @@ -9,7 +9,9 @@ use crate::accounts::{Token, hash_token}; use crate::model::{User, UserId}; use crate::store::{self, Result, Store, backend}; -/// How long a central session lives. +/// The default central-session lifetime. The panel's Settings section can +/// move it; the constant stays the fresh-database answer and the cookie's +/// Max-Age (which is set before the store is in hand). pub const SESSION_DAYS: i64 = 30; /// Creates a session for `user`, returning the raw cookie token. The row @@ -17,44 +19,50 @@ pub const SESSION_DAYS: i64 = 30; pub async fn create_session(store: &Store, user: &UserId) -> Result { let token = Token::mint(); let now = store::now(); - store - .conn - .execute( - "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \ + let days = crate::settings::policy(store).await?.session_days; + let conn = store.conn.lock().await; + conn.execute( + "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \ VALUES (?1, ?2, ?3, ?4)", - turso::params![ - token.hash(), - user.to_string(), - store::stamp(now)?, - store::stamp(now + time::Duration::days(SESSION_DAYS))?, - ], - ) - .await - .map_err(backend)?; + turso::params![ + token.hash(), + user.to_string(), + store::stamp(now)?, + store::stamp(now + time::Duration::days(days))?, + ], + ) + .await + .map_err(backend)?; Ok(token) } /// Resolves a raw cookie token to its user. `None` for unknown, expired, /// revoked, or disabled — every one of them is "please log in again". pub async fn resolve_session(store: &Store, token: &str) -> Result> { - let mut rows = store - .conn - .query( - "SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = ?1", - turso::params![hash_token(token)], - ) - .await - .map_err(backend)?; - let Some(row) = rows.next().await.map_err(backend)? else { - return Ok(None); + // The session row is read under a short-held guard; the user lookup locks + // for itself once the guard is dropped. + let found = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = ?1", + turso::params![hash_token(token)], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) + if store::opt_text(&row, 2)?.is_none() + && store::parse_stamp(&store::text(&row, 1)?)? >= store::now() => + { + Some(UserId::from(store::text(&row, 0)?)) + } + _ => None, + } }; - if store::opt_text(&row, 2)?.is_some() { - return Ok(None); - } - if store::parse_stamp(&store::text(&row, 1)?)? < store::now() { + let Some(user_id) = found else { return Ok(None); - } - let user_id = UserId::from(store::text(&row, 0)?); + }; match crate::accounts::user_by_id(store, &user_id).await? { Some(user) if !user.disabled => Ok(Some(user)), _ => Ok(None), @@ -71,31 +79,26 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { /// The hash-level half of [`revoke_session`], shared with the admin's /// revoke-everything below. pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> { + let conn = store.conn.lock().await; let now = store::stamp(store::now())?; - store - .conn - .execute( - "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", - turso::params![now.clone(), hash], - ) - .await - .map_err(backend)?; - store - .conn - .execute( - "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", - turso::params![now.clone(), hash], - ) - .await - .map_err(backend)?; - store - .conn - .execute( - "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", - turso::params![now, hash], - ) - .await - .map_err(backend)?; + conn.execute( + "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", + turso::params![now.clone(), hash], + ) + .await + .map_err(backend)?; + conn.execute( + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", + turso::params![now.clone(), hash], + ) + .await + .map_err(backend)?; + conn.execute( + "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", + turso::params![now, hash], + ) + .await + .map_err(backend)?; Ok(()) } @@ -104,18 +107,23 @@ pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> /// live app session down with them. Introspection is per-request, so the /// next call any app makes on their behalf comes back inactive — no ghost. pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result { - let mut rows = store - .conn - .query( - "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL", - turso::params![user.to_string()], - ) - .await - .map_err(backend)?; - let mut hashes = Vec::new(); - while let Some(row) = rows.next().await.map_err(backend)? { - hashes.push(store::text(&row, 0)?); - } + // Read under a short guard; the per-session revokes and the final sweep + // lock for themselves. + let hashes = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL", + turso::params![user.to_string()], + ) + .await + .map_err(backend)?; + let mut hashes = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + hashes.push(store::text(&row, 0)?); + } + hashes + }; let count = hashes.len() as u64; for hash in hashes { revoke_session_hash(store, &hash).await?; @@ -123,22 +131,19 @@ pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result { // Sessions already revoked earlier still own live app sessions; sweep // those too so nothing outlives the person being signed out. let now = store::stamp(store::now())?; - store - .conn - .execute( - "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", - turso::params![now.clone(), user.to_string()], - ) - .await - .map_err(backend)?; - store - .conn - .execute( - "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", - turso::params![now, user.to_string()], - ) - .await - .map_err(backend)?; + let conn = store.conn.lock().await; + conn.execute( + "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", + turso::params![now.clone(), user.to_string()], + ) + .await + .map_err(backend)?; + conn.execute( + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", + turso::params![now, user.to_string()], + ) + .await + .map_err(backend)?; Ok(count) } @@ -151,19 +156,22 @@ pub async fn revoke_user_sessions_except( keep_token: &str, ) -> Result { let keep = hash_token(keep_token); - let mut rows = store - .conn - .query( - "SELECT token_hash FROM sessions \ - WHERE user_id = ?1 AND revoked_at IS NULL AND token_hash != ?2", - turso::params![user.to_string(), keep.clone()], - ) - .await - .map_err(backend)?; - let mut hashes = Vec::new(); - while let Some(row) = rows.next().await.map_err(backend)? { - hashes.push(store::text(&row, 0)?); - } + let hashes = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT token_hash FROM sessions \ + WHERE user_id = ?1 AND revoked_at IS NULL AND token_hash != ?2", + turso::params![user.to_string(), keep.clone()], + ) + .await + .map_err(backend)?; + let mut hashes = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + hashes.push(store::text(&row, 0)?); + } + hashes + }; let count = hashes.len() as u64; for hash in &hashes { revoke_session_hash(store, hash).await?; @@ -171,24 +179,21 @@ pub async fn revoke_user_sessions_except( // The kept session is the only one allowed to keep its app sessions and // refresh tokens; everything else of this user's is swept. let now = store::stamp(store::now())?; - store - .conn - .execute( - "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ + let conn = store.conn.lock().await; + conn.execute( + "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ AND session_hash != ?3", - turso::params![now.clone(), user.to_string(), keep.clone()], - ) - .await - .map_err(backend)?; - store - .conn - .execute( - "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ + turso::params![now.clone(), user.to_string(), keep.clone()], + ) + .await + .map_err(backend)?; + conn.execute( + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ AND session_hash != ?3", - turso::params![now, user.to_string(), keep], - ) - .await - .map_err(backend)?; + turso::params![now, user.to_string(), keep], + ) + .await + .map_err(backend)?; Ok(count) } diff --git a/crates/im-core/src/settings.rs b/crates/im-core/src/settings.rs index d6af118..ca2fd83 100644 --- a/crates/im-core/src/settings.rs +++ b/crates/im-core/src/settings.rs @@ -38,8 +38,8 @@ impl Smtp { } async fn get(store: &Store, key: &str) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT value FROM settings WHERE key = ?1", turso::params![key], @@ -53,13 +53,20 @@ async fn get(store: &Store, key: &str) -> Result> { } async fn set(store: &Store, key: &str, value: &str) -> Result<()> { - store - .conn - .execute( - "INSERT INTO settings (key, value) VALUES (?1, ?2) \ + let conn = store.conn.lock().await; + conn.execute( + "INSERT INTO settings (key, value) VALUES (?1, ?2) \ ON CONFLICT(key) DO UPDATE SET value = excluded.value", - turso::params![key, value], - ) + turso::params![key, value], + ) + .await + .map_err(backend)?; + Ok(()) +} + +async fn remove(store: &Store, key: &str) -> Result<()> { + let conn = store.conn.lock().await; + conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) .await .map_err(backend)?; Ok(()) @@ -177,10 +184,9 @@ pub async fn last_check(store: &Store) -> Result> { /// A saved sender cannot borrow the last probe's verdict: the check is /// cleared on every settings write, like izlek's. async fn clear_check(store: &Store) -> Result<()> { + let conn = store.conn.lock().await; for key in ["smtp_check_at", "smtp_check_ms", "smtp_check_error"] { - store - .conn - .execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) + conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) .await .map_err(backend)?; } @@ -201,11 +207,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res "smtp_check_ms", "smtp_check_error", ] { - store - .conn - .execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) - .await - .map_err(backend)?; + remove(store, key).await?; } return Ok(()); } @@ -229,6 +231,122 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res Ok(()) } +/// The panel-tunable policy, with the defaults the code was born with. Every +/// reader falls back to the default when the key is absent, so a fresh +/// database behaves exactly like the pre-settings build. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Policy { + pub invite_days: i64, + pub session_days: i64, + pub pending_minutes: i64, + pub reset_minutes: i64, + pub login_attempts_per_hour: i64, +} + +impl Default for Policy { + fn default() -> Self { + Self { + invite_days: 7, + session_days: 30, + pending_minutes: 10, + reset_minutes: 60, + login_attempts_per_hour: 10, + } + } +} + +async fn number(store: &Store, key: &str, default: i64) -> Result { + Ok(get(store, key) + .await? + .and_then(|raw| raw.parse().ok()) + .unwrap_or(default)) +} + +/// The policy as stored, defaults filled in. +pub async fn policy(store: &Store) -> Result { + let defaults = Policy::default(); + Ok(Policy { + invite_days: number(store, "invite_days", defaults.invite_days).await?, + session_days: number(store, "session_days", defaults.session_days).await?, + pending_minutes: number(store, "pending_minutes", defaults.pending_minutes).await?, + reset_minutes: number(store, "reset_minutes", defaults.reset_minutes).await?, + login_attempts_per_hour: number( + store, + "login_attempts_per_hour", + defaults.login_attempts_per_hour, + ) + .await?, + }) +} + +/// Writes the policy. Values under one are refused by the panel before they +/// get here; zero or negative would be a door that never opens, so they are +/// clamped to the default rather than stored. +pub async fn set_policy(store: &Store, policy: &Policy) -> Result<()> { + let defaults = Policy::default(); + let clamp = |value: i64, default: i64| if value >= 1 { value } else { default }; + set( + store, + "invite_days", + &clamp(policy.invite_days, defaults.invite_days).to_string(), + ) + .await?; + set( + store, + "session_days", + &clamp(policy.session_days, defaults.session_days).to_string(), + ) + .await?; + set( + store, + "pending_minutes", + &clamp(policy.pending_minutes, defaults.pending_minutes).to_string(), + ) + .await?; + set( + store, + "reset_minutes", + &clamp(policy.reset_minutes, defaults.reset_minutes).to_string(), + ) + .await?; + set( + store, + "login_attempts_per_hour", + &clamp( + policy.login_attempts_per_hour, + defaults.login_attempts_per_hour, + ) + .to_string(), + ) + .await?; + Ok(()) +} + +/// Days an invite link stays valid. +pub async fn invite_days(store: &Store) -> Result { + number(store, "invite_days", Policy::default().invite_days).await +} + +/// Minutes between password and second factor before the pending marker dies. +pub async fn pending_minutes(store: &Store) -> Result { + number(store, "pending_minutes", Policy::default().pending_minutes).await +} + +/// Minutes a password-reset link stays valid. +pub async fn reset_minutes(store: &Store) -> Result { + number(store, "reset_minutes", Policy::default().reset_minutes).await +} + +/// Failed sign-ins per address per hour before the door refuses to listen. +pub async fn login_attempts_per_hour(store: &Store) -> Result { + number( + store, + "login_attempts_per_hour", + Policy::default().login_attempts_per_hour, + ) + .await +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index dc6fa66..c331eef 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -104,6 +104,18 @@ CREATE TABLE IF NOT EXISTS events ( actor TEXT, detail TEXT ); +CREATE TABLE IF NOT EXISTS reset_links ( + token TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id), + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_at TEXT +); +CREATE TABLE IF NOT EXISTS login_attempts ( + key TEXT NOT NULL, + at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS login_attempts_key ON login_attempts(key, at); CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL @@ -113,7 +125,7 @@ CREATE TABLE IF NOT EXISTS settings ( /// One database handle with the at-rest key beside it. Turso is a /// single-writer engine; one connection per store, like izlek-core. pub struct Store { - pub(crate) conn: Connection, + pub(crate) conn: tokio::sync::Mutex, pub(crate) key: Key, } @@ -127,7 +139,7 @@ impl Store { let db = Builder::new_local(raw).build().await.map_err(backend)?; let conn = db.connect().map_err(backend)?; let store = Store { - conn, + conn: tokio::sync::Mutex::new(conn), key: load_key(path)?, }; store.migrate().await?; @@ -136,15 +148,15 @@ impl Store { /// Applies the schema inside one immediate transaction; safe to re-run. pub async fn migrate(&self) -> Result<()> { - self.conn - .execute("BEGIN IMMEDIATE", ()) - .await - .map_err(backend)?; - if let Err(e) = self.conn.execute_batch(SCHEMA).await { - let _ = self.conn.execute("ROLLBACK", ()).await; + // One guard for the whole transaction — nothing interleaves with a + // schema write. + let conn = self.conn.lock().await; + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; + if let Err(e) = conn.execute_batch(SCHEMA).await { + let _ = conn.execute("ROLLBACK", ()).await; return Err(backend(e)); } - self.conn.execute("COMMIT", ()).await.map_err(backend)?; + conn.execute("COMMIT", ()).await.map_err(backend)?; Ok(()) } @@ -217,8 +229,8 @@ mod tests { let store = Store::open(&path).await.unwrap(); store.migrate().await.unwrap(); store.migrate().await.unwrap(); - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query("SELECT name FROM sqlite_master WHERE type = 'table'", ()) .await .unwrap(); @@ -234,6 +246,8 @@ mod tests { "auth_codes", "refresh_tokens", "signing_keys", + "reset_links", + "login_attempts", ] { assert!(tables.contains(&expected.to_string()), "missing {expected}"); } diff --git a/crates/im-core/src/totp.rs b/crates/im-core/src/totp.rs index bd823e3..fd364fe 100644 --- a/crates/im-core/src/totp.rs +++ b/crates/im-core/src/totp.rs @@ -84,28 +84,26 @@ pub fn verify_totp(secret: &[u8; 20], code: &str, at: OffsetDateTime) -> bool { /// Stores a freshly generated secret, sealed, unconfirmed until the user /// proves their app agrees (`confirm_totp`). pub async fn set_totp(store: &Store, user: &UserId, secret_bytes: &[u8; 20]) -> Result<()> { + let conn = store.conn.lock().await; let sealed = secret::seal(store.key(), secret_bytes); - store - .conn - .execute( - "UPDATE users SET totp_secret = ?1, totp_confirmed = 0 WHERE id = ?2", - turso::params![sealed, user.to_string()], - ) - .await - .map_err(backend)?; + conn.execute( + "UPDATE users SET totp_secret = ?1, totp_confirmed = 0 WHERE id = ?2", + turso::params![sealed, user.to_string()], + ) + .await + .map_err(backend)?; Ok(()) } /// Marks the stored secret confirmed — called after one successful code. pub async fn confirm_totp(store: &Store, user: &UserId) -> Result<()> { - store - .conn - .execute( - "UPDATE users SET totp_confirmed = 1 WHERE id = ?1", - turso::params![user.to_string()], - ) - .await - .map_err(backend)?; + let conn = store.conn.lock().await; + conn.execute( + "UPDATE users SET totp_confirmed = 1 WHERE id = ?1", + turso::params![user.to_string()], + ) + .await + .map_err(backend)?; Ok(()) } @@ -113,8 +111,8 @@ pub async fn confirm_totp(store: &Store, user: &UserId) -> Result<()> { /// TOTP was never set up. A sealed value that no longer opens (wrong key, /// damaged ciphertext) reads as `None` — the user re-enrolls. pub async fn totp_secret(store: &Store, user: &UserId) -> Result> { - let mut rows = store - .conn + let conn = store.conn.lock().await; + let mut rows = conn .query( "SELECT totp_secret, totp_confirmed FROM users WHERE id = ?1", turso::params![user.to_string()], diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index 74bfec9..78fc3a3 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -548,9 +548,13 @@ body:has(.admin-shell) { .admin-confirm { position: relative; + display: inline-flex; } .admin-confirm summary { list-style: none; + display: inline-flex; + align-items: center; + box-sizing: border-box; } .admin-confirm summary::-webkit-details-marker { display: none; diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 7a7669a..7106ac8 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -135,6 +135,7 @@ async fn admin_page(cx: &Cx) -> Result { ("account", "Account"), ("users", "Users"), ("mail", "Mail"), + ("settings", "Settings"), ("logs", "Logs"), ] .into_iter() @@ -149,6 +150,7 @@ async fn admin_page(cx: &Cx) -> Result { let section_html = match section.as_str() { "mail" => mail_section(cx).await?, + "settings" => settings_section(cx).await?, "logs" => logs_section(cx).await?, "users" => users_section(cx, &me, invited.as_deref()).await?, _ => account_section(&me), @@ -167,6 +169,7 @@ async fn admin_page(cx: &Cx) -> Result { "password" => "Password changed — every other device is signed out.", "uninvited" => "Invite invalidated — the link is dead.", "deleted" => "Account deleted.", + "settings" => "Settings saved.", _ => "Done.", } )), @@ -344,6 +347,68 @@ async fn users_section( )) } +/// The knobs the code shipped with, now the panel's: invite and reset link +/// lifetimes, the sign-in session's days, the pending marker's minutes, and +/// the sign-in failure ceiling. Same form skin as Mail. +async fn settings_section(cx: &Cx) -> Result { + let policy = settings::policy(&app(cx).store).await?; + Ok(format!( + r#"
+
Settings
+
The rules identity lives by. They apply from the next invite, sign-in or link — nothing already minted is rewritten.
+
+ + + + + + +
+
"#, + policy.invite_days, + policy.session_days, + policy.pending_minutes, + policy.reset_minutes, + policy.login_attempts_per_hour, + )) +} + +#[derive(Deserialize)] +struct PolicyForm { + invite_days: i64, + session_days: i64, + pending_minutes: i64, + reset_minutes: i64, + login_attempts_per_hour: i64, +} + +#[route(POST "/admin/settings")] +async fn settings_save(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + settings::set_policy( + store, + &settings::Policy { + invite_days: input.invite_days, + session_days: input.session_days, + pending_minutes: input.pending_minutes, + reset_minutes: input.reset_minutes, + login_attempts_per_hour: input.login_attempts_per_hour, + }, + ) + .await?; + server::log_event(cx, "settings_updated", Some(&me.email), None).await; + back(cx, "settings", "&ok=settings") +} + async fn mail_section(cx: &Cx) -> Result { let store = &app(cx).store; let smtp = settings::smtp(store).await?; diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index fce9214..029f6d2 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -55,10 +55,21 @@ pub struct LoginForm { async fn login(cx: &Cx, Form(input): Form) -> Redirect { let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string(); let store = &server::app(cx).store; + // The door stops listening after the panel's per-hour allowance of + // failures. The refusal says nothing about which step refused, as always. + let key = input.email.trim().to_lowercase(); + if accounts::login_blocked(store, &key).await? { + server::log_event(cx, "login_limited", Some(&key), None).await; + return see(format!( + "/login?error=rate_limited&back={}", + urlencode(&back) + )); + } match accounts::verify_login(store, &input.email, &input.password).await { Ok(user) if user.totp_confirmed => { - let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back); - server::set_pending_cookie(cx, sealed); + let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back).await; + server::set_pending_cookie(cx, sealed).await; + let _ = accounts::clear_login_failures(store, &key).await; see("/login/totp".to_string()) } Ok(user) => { @@ -69,13 +80,15 @@ async fn login(cx: &Cx, Form(input): Form) -> Redirect { let secret = im_core::totp::generate_secret(); im_core::totp::set_totp(store, &user.id, &secret).await?; } - let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, back); - server::set_pending_cookie(cx, sealed); + let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, back).await; + server::set_pending_cookie(cx, sealed).await; + let _ = accounts::clear_login_failures(store, &key).await; see("/enroll".to_string()) } Err(_) => { // The failure is logged against the address tried, never the // password — and never whether the address exists. + let _ = accounts::record_login_failure(store, &key).await; server::log_event(cx, "login_fail", Some(&input.email), None).await; see(format!("/login?error=bad_login&back={}", urlencode(&back))) } @@ -111,10 +124,20 @@ async fn login_totp(cx: &Cx, Form(input): Form) -> Redirect { }, None => false, }; + // The second factor gets the same ceiling as the first, keyed on the + // account, so an attacker past the password cannot grind codes either. + let totp_key = format!("totp:{}", pending.user); + if accounts::login_blocked(store, &totp_key).await? { + server::log_event(cx, "login_limited", None, Some("2fa")).await; + server::clear_pending_cookie(cx); + return see("/login?error=rate_limited".to_string()); + } if !ok { + let _ = accounts::record_login_failure(store, &totp_key).await; server::log_event(cx, "totp_fail", None, Some("login")).await; return see("/login/totp?error=bad_code".to_string()); } + let _ = accounts::clear_login_failures(store, &totp_key).await; let token = im_core::sessions::create_session(store, &user_id).await?; let email = accounts::user_by_id(store, &user_id) .await? @@ -173,8 +196,8 @@ async fn invite(cx: &Cx, Form(input): Form) -> Redirect { // enrolment page is the only way forward. let secret = im_core::totp::generate_secret(); im_core::totp::set_totp(store, &user.id, &secret).await?; - let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()); - server::set_pending_cookie(cx, sealed); + let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()).await; + server::set_pending_cookie(cx, sealed).await; server::log_event(cx, "invite_accepted", Some(&user.email), None).await; see("/enroll".to_string()) } @@ -226,3 +249,61 @@ async fn logout(cx: &Cx) -> Redirect { server::clear_session_cookie(cx); see("/".to_string()) } + +#[derive(Deserialize)] +pub struct ForgotForm { + email: String, +} + +/// The self-serve reset ask. It answers every address the same — the mail +/// either exists or it doesn't, and the page never says which. Each ask +/// retires the address's previous live link: the newest mail is the only +/// door. +#[route(POST "/forgot")] +async fn forgot(cx: &Cx, Form(input): Form) -> Redirect { + let store = &server::app(cx).store; + let email = input.email.trim().to_string(); + if let Some(token) = accounts::create_reset(store, &email).await? { + let issuer = server::app(cx).config.issuer.clone(); + if crate::mailer::send_reset(store, &issuer, &email, token.expose()) + .await + .is_ok() + { + server::log_event(cx, "reset_sent", Some(&email), None).await; + } + } + see("/forgot?ok=sent".to_string()) +} + +#[derive(Deserialize)] +pub struct ResetForm { + token: String, + password: String, + password_confirm: String, +} + +/// Redeems a reset link: new password in, every session out. A dead link is +/// sent back to the ask — the form it came from is gone with it. +#[route(POST "/reset")] +async fn reset(cx: &Cx, Form(input): Form) -> Redirect { + if input.password != input.password_confirm { + return see(format!("/reset/{}?error=passwords_differ", input.token)); + } + let store = &server::app(cx).store; + match accounts::redeem_reset(store, &input.token, &input.password).await { + Ok(user) => { + server::log_event(cx, "password_reset", Some(&user.email), None).await; + see("/login?ok=reset".to_string()) + } + Err(AccountError::Password(problem)) => { + let code = match problem { + im_core::accounts::PasswordProblem::TooShort => "password_too_short", + im_core::accounts::PasswordProblem::LooksLikeYou => "password_personal", + _ => "passwords_differ", + }; + see(format!("/reset/{}?error={code}", input.token)) + } + Err(AccountError::ResetInvalid) => see("/forgot?error=reset_invalid".to_string()), + Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), + } +} diff --git a/crates/im-web/src/mailer.rs b/crates/im-web/src/mailer.rs index 53edd7f..8dc082a 100644 --- a/crates/im-web/src/mailer.rs +++ b/crates/im-web/src/mailer.rs @@ -87,6 +87,23 @@ pub async fn send_invite(store: &Store, issuer: &str, email: &str, token: &str) Ok(link) } +/// The reset mail: the link is the whole payload, and sending it retires +/// every previous link for the address (see `accounts::create_reset`). +pub async fn send_reset(store: &Store, issuer: &str, email: &str, token: &str) -> Result { + let link = format!("{issuer}/reset/{token}"); + let minutes = settings::reset_minutes(store).await?; + send( + store, + email, + "Reset your password", + format!( + "A password reset was asked for this address. The link is yours for {minutes} minutes:\n\n{link}\n\nIf that wasn't you, this mail changes nothing.\n" + ), + ) + .await?; + Ok(link) +} + /// Dials the mail server without sending anything: connect, TLS, hello, /// authenticate, NOOP, hang up. A pass proves the host, the port, the /// encryption and the password; it says nothing about whether the diff --git a/crates/im-web/src/oidc.rs b/crates/im-web/src/oidc.rs index e25f169..8253334 100644 --- a/crates/im-web/src/oidc.rs +++ b/crates/im-web/src/oidc.rs @@ -302,7 +302,8 @@ async fn exchange(cx: &Cx, Form(input): Form) -> Result { &consumed.session_hash, ) .await?; - server::log_event(cx, + server::log_event( + cx, "code_exchanged", Some(&user.email), Some(&format!("via {}", client.name)), diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index de7753f..761dd6d 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -33,10 +33,20 @@ pub fn error_text(code: &str) -> &'static str { "smtp_test" => "The test mail could not be sent.", "password_wrong" => "That's not your current password.", "password_same" => "That's already your password.", + "rate_limited" => "Too many tries — wait a while and try again.", + "reset_invalid" => "This reset link is not valid — ask for a fresh one.", _ => "Something went wrong. Try again.", } } +/// The good news, where a page carries an `ok` code in its URL. +pub fn ok_text(code: &str) -> &'static str { + match code { + "reset" => "Password changed — sign in with the new one.", + _ => "Done.", + } +} + /// The refusal this request carries back, if any. Values come percent- /// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI. pub fn query_value(query: &str, key: &str) -> Option { @@ -107,6 +117,7 @@ async fn login_card(cx: &Cx) -> Result { let query = current_query(cx); let back = query_value(&query, "back").unwrap_or_else(|| "/".to_string()); let error = query_value(&query, "error"); + let ok = query_value(&query, "ok"); let stage = view! { cx =>
@@ -117,6 +128,9 @@ async fn login_card(cx: &Cx) -> Result {
"Sign in"
"One account for everything Dizey."
+ if let Some(code) = ok { +
(ok_text(&code))
+ } if let Some(code) = error {
(error_text(&code))
} @@ -146,6 +160,7 @@ async fn login_card(cx: &Cx) -> Result { "Sign in" + "Forgot it?" @@ -421,3 +436,111 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { }; shell(cx, "im", stage).await } + +/// "Forgot it?" — the self-serve reset ask. It answers the same whether the +/// address has an account: one quiet note, the same one for every address. +#[page("/forgot")] +async fn forgot(cx: &Cx) -> Result { + let query = current_query(cx); + let error = query_value(&query, "error"); + let sent = query_value(&query, "ok").as_deref() == Some("sent"); + let stage = view! { + cx => +
+
+ (wordmark(cx).await?) +
+
+
"Forgot it?"
+
"Your address gets a reset link, good for one password change. A fresh ask retires the last link."
+
+ if sent { +
"If that address has an account, a link is on its way."
+ } + if let Some(code) = error { +
(error_text(&code))
+ } +
+ + +
+ "Back to sign-in" +
+ +
+
+ }; + shell(cx, "Forgot it? · im", stage).await +} + +/// The reset link's destination: a new password, twice. A dead link never +/// shows a working form — it goes back to the ask with the refusal named. +#[route(GET "/reset/{token}")] +async fn reset_page(cx: &Cx) -> Result { + let token: &str = path_param::(cx); + if !im_core::accounts::reset_link_valid(&server::app(cx).store, token).await? { + return see_other("/forgot?error=reset_invalid").into_response(cx); + } + let query = current_query(cx); + let error = query_value(&query, "error"); + let stage = view! { + cx => +
+
+ (wordmark(cx).await?) +
+
+
"A fresh password"
+
"The change signs every device out, this one included."
+
+ if let Some(code) = error { +
(error_text(&code))
+ } +
+ + + + +
+
+ +
+
+ }; + shell(cx, "A fresh password · im", stage) + .await? + .into_response(cx) +} diff --git a/crates/im-web/src/server.rs b/crates/im-web/src/server.rs index 5f8e0db..207c525 100644 --- a/crates/im-web/src/server.rs +++ b/crates/im-web/src/server.rs @@ -85,13 +85,16 @@ pub fn set_session_cookie(cx: &Cx, token: &str) { }); } -pub fn set_pending_cookie(cx: &Cx, sealed: String) { +pub async fn set_pending_cookie(cx: &Cx, sealed: String) { + let minutes = im_core::settings::pending_minutes(&app(cx).store) + .await + .unwrap_or(PENDING_MINUTES); app_cookies(cx).add(cookie! { PENDING_COOKIE = sealed; Path = "/"; HttpOnly; SameSite = Lax; - MaxAge = time::Duration::minutes(PENDING_MINUTES) + MaxAge = time::Duration::minutes(minutes) }); } @@ -137,17 +140,20 @@ pub struct Pending { pub exp: i64, } -pub fn mint_pending( +pub async fn mint_pending( cx: &Cx, user: &im_core::model::UserId, purpose: PendingPurpose, back: String, ) -> String { + let minutes = im_core::settings::pending_minutes(&app(cx).store) + .await + .unwrap_or(PENDING_MINUTES); let pending = Pending { user: user.to_string(), purpose, back, - exp: time::OffsetDateTime::now_utc().unix_timestamp() + PENDING_MINUTES * 60, + exp: time::OffsetDateTime::now_utc().unix_timestamp() + minutes * 60, }; let json = serde_json::to_string(&pending).expect("Pending is plain data"); app(cx).store.seal_value(json.as_bytes()) diff --git a/style/main.scss b/style/main.scss index af4da63..327e315 100644 --- a/style/main.scss +++ b/style/main.scss @@ -590,9 +590,16 @@ body:has(.admin-shell) { // button skin; the popover names the cost and holds the real button. .admin-confirm { position: relative; + display: inline-flex; + // The summary wears the button skin verbatim — a native summary is a + // list-item, and without inline-flex it stands a few pixels off the real + // buttons beside it. summary { list-style: none; + display: inline-flex; + align-items: center; + box-sizing: border-box; &::-webkit-details-marker { display: none; } }