//! User accounts: creation, lookup, profile and password, and the two-factor state. //! //! Rules that must hold under concurrency are single conditional statements, so two requests cannot //! both win: //! //! - the first administrator exists only if no user does (`create_first_admin`); //! - a TOTP step is accepted once (`accept_totp_step`, `totp_last_step` is only ever raised); //! - a recovery code is spent once (`consume_recovery_code`, `used_at IS NULL`). //! //! A TOTP secret that is being enrolled is not written to the user row. It waits in the `settings` //! table under `totp_pending:`, sealed like any other secret, and moves to the row only //! when a code from it is confirmed. So re-enrolling while two-factor is on never switches the //! second factor off, and an abandoned enrolment changes nothing. use turso::{Connection, Row}; use crate::error::{Error, Result}; use crate::model::User; use crate::store::backchannel::{self, EndReason}; use crate::store::directory::{ChangeKind, record_change}; use crate::store::links::invalidate_links; use crate::store::sessions::{end_rows, live_session_ids}; use crate::store::{ Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, }; use crate::time::now_stamp; /// The columns of a user row, in the order [`map_user`] reads them. pub(crate) const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ photo_mime, picture_version, created_at, updated_at, locale_auto"; /// Maps a row selected with [`USER_COLS`]. pub(crate) fn map_user(row: &Row) -> Result { Ok(User { id: col_text(row, 0)?, email: col_text(row, 1)?, name: col_text(row, 2)?, password_hash: col_text(row, 3)?, is_admin: col_int(row, 4)? != 0, disabled_at: col_opt_text(row, 5)?, totp_secret_sealed: col_opt_text(row, 6)?, totp_enabled_at: col_opt_text(row, 7)?, totp_last_step: col_opt_int(row, 8)?, locale: col_text(row, 9)?, zoneinfo: col_text(row, 10)?, theme: col_text(row, 11)?, photo_mime: col_opt_text(row, 12)?, picture_version: col_int(row, 13)?, created_at: col_text(row, 14)?, updated_at: col_text(row, 15)?, locale_auto: col_int(row, 16)? != 0, }) } /// Maps an insert error. A UNIQUE violation is a conflict for the person; anything else is a /// database failure. pub(crate) fn insert_error(e: turso::Error) -> Error { let text = e.to_string(); if text.contains("UNIQUE") { Error::Conflict("that email address is already registered".into()) } else { db_err(e) } } /// The settings key that holds a TOTP secret waiting for its first confirmed code. fn pending_key(user_id: &str) -> String { format!("totp_pending:{user_id}") } /// Replaces the recovery codes of a user with `hashes`. Runs inside the caller's transaction. async fn replace_codes(conn: &Connection, user_id: &str, hashes: &[String]) -> Result<()> { conn.execute( "DELETE FROM recovery_codes WHERE user_id = ?1", (user_id.to_string(),), ) .await .map_err(db_err)?; for hash in hashes { conn.execute( "INSERT INTO recovery_codes (user_id, code_hash, used_at) VALUES (?1, ?2, NULL)", (user_id.to_string(), hash.clone()), ) .await .map_err(db_err)?; } Ok(()) } impl Store { /// Creates the first administrator, and only if there is no user at all. /// /// The check and the insert are one statement, so two parallel setups cannot both succeed. The /// second one gets [`Error::Conflict`]. `email` must already be normalised. pub async fn create_first_admin( &self, email: &str, name: &str, password_hash: &str, ) -> Result { let id = new_id(); let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let changed = tx .execute( "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ created_at, updated_at) \ SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \ WHERE NOT EXISTS (SELECT 1 FROM users)", ( id.clone(), email.to_string(), name.to_string(), password_hash.to_string(), now, ), ) .await .map_err(insert_error)?; if changed == 1 { record_change(&tx, &id, ChangeKind::Member).await?; } Ok(changed == 1) } .await; let created = finish(tx, outcome).await?; drop(conn); if !created { return Err(Error::Conflict("setup is already complete".into())); } self.announce_directory(); self.user_by_id(&id).await?.ok_or(Error::NotFound) } /// Creates an account. `email` must already be normalised. Fails with a conflict when the /// address is taken. pub async fn create_user( &self, email: &str, name: &str, password_hash: &str, is_admin: bool, ) -> Result { let id = new_id(); let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<()> = async { tx.execute( "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", ( id.clone(), email.to_string(), name.to_string(), password_hash.to_string(), i64::from(is_admin), now, ), ) .await .map_err(insert_error)?; record_change(&tx, &id, ChangeKind::Member).await } .await; finish(tx, outcome).await?; drop(conn); self.announce_directory(); self.user_by_id(&id).await?.ok_or(Error::NotFound) } /// The user with this id, or `None`. pub async fn user_by_id(&self, id: &str) -> Result> { let conn = self.read_conn().await; fetch_opt( &conn, &format!("SELECT {USER_COLS} FROM users WHERE id = ?1"), (id.to_string(),), map_user, ) .await } /// The user with this normalised address, or `None`. Callers normalise the input first. pub async fn user_by_email_folded(&self, folded: &str) -> Result> { let conn = self.read_conn().await; fetch_opt( &conn, &format!("SELECT {USER_COLS} FROM users WHERE email_folded = ?1"), (folded.to_string(),), map_user, ) .await } /// Changes the display name, and writes its directory row, in one transaction. The caller has /// checked the name with `names::parse_display_name`; the schema keeps it at 1 to 100 characters. pub async fn update_name(&self, id: &str, name: &str) -> Result<()> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<()> = async { let changed = tx .execute( "UPDATE users SET name = ?2, updated_at = ?3 WHERE id = ?1", (id.to_string(), name.to_string(), now_stamp()), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } record_change(&tx, id, ChangeKind::Member).await } .await; let result = finish(tx, outcome).await; if result.is_ok() { self.announce_directory(); } result } /// Changes the language, time zone and theme. `locale_auto` true means the language follows the /// browser and `locale` is kept only for when it is turned off again. The schema rejects unknown /// languages and themes. pub async fn update_preferences( &self, id: &str, locale: &str, locale_auto: bool, zoneinfo: &str, theme: &str, ) -> Result<()> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<()> = async { let changed = tx .execute( "UPDATE users SET locale = ?2, locale_auto = ?3, zoneinfo = ?4, theme = ?5, \ updated_at = ?6 WHERE id = ?1", ( id.to_string(), locale.to_string(), i64::from(locale_auto), zoneinfo.to_string(), theme.to_string(), now_stamp(), ), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } record_change(&tx, id, ChangeKind::Member).await } .await; let result = finish(tx, outcome).await; if result.is_ok() { self.announce_directory(); } result } /// Records that a photo was stored: sets its MIME type, bumps `picture_version` so caches see a /// new picture, and writes the directory row. One transaction. The file itself is written by the /// caller with [`crate::photo::write_photo`], before this call. pub async fn set_photo(&self, id: &str, mime: &str) -> Result<()> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<()> = async { let changed = tx .execute( "UPDATE users SET photo_mime = ?2, picture_version = picture_version + 1, \ updated_at = ?3 WHERE id = ?1", (id.to_string(), mime.to_string(), now_stamp()), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } record_change(&tx, id, ChangeKind::Member).await } .await; let result = finish(tx, outcome).await; if result.is_ok() { self.announce_directory(); } result } /// Records that the photo was removed. Returns false, and writes nothing, when there was no /// photo. Otherwise it clears the MIME type, bumps `picture_version` and writes the directory row. pub async fn clear_photo(&self, id: &str) -> Result { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let changed = tx .execute( "UPDATE users SET photo_mime = NULL, picture_version = picture_version + 1, \ updated_at = ?2 WHERE id = ?1 AND photo_mime IS NOT NULL", (id.to_string(), now_stamp()), ) .await .map_err(db_err)?; if changed == 0 { return Ok(false); } record_change(&tx, id, ChangeKind::Member).await?; Ok(true) } .await; let result = finish(tx, outcome).await; if matches!(result, Ok(true)) { self.announce_directory(); } result } /// Stores a new argon2id hash, ends every live session of the person except `keep_session_id`, /// with their back-channel logouts, and invalidates every pending account link (password reset and /// email change), so a link issued for the old password cannot set or change anything. One /// transaction: the old password never stays in force for a session that the new one has ended, and /// nothing changes unless all of it happens. The caller has checked the policy and the current /// password. Returns the ids of the sessions ended. pub async fn change_password( &self, id: &str, password_hash: &str, keep_session_id: &str, ) -> Result> { let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result> = async { let changed = tx .execute( "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1", (id.to_string(), password_hash.to_string(), now.clone()), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } invalidate_links(&tx, id, &now).await?; let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?; end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?; Ok(ids) } .await; finish(tx, outcome).await } /// Disables an account. The last enabled administrator cannot be disabled: that is part of the /// same conditional `UPDATE`, so two parallel requests cannot both disable the last two. In one transaction: the account is marked disabled, the directory feed /// records the change, one `sub`-only back-channel logout is queued for every client the person /// used (contracts.md 2.5), the refresh tokens are revoked, the pending reset and email-change links are /// used up, and every session is deleted. Returns /// false, with nothing changed, when the account is missing or already disabled. pub async fn disable_user(&self, user_id: &str) -> Result { let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let changed = tx .execute( "UPDATE users SET disabled_at = ?2, updated_at = ?2 \ WHERE id = ?1 AND disabled_at IS NULL \ AND (is_admin = 0 OR (SELECT COUNT(*) FROM users \ WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", (user_id.to_string(), now.clone()), ) .await .map_err(db_err)?; if changed != 1 { return Ok(false); } record_change(&tx, user_id, ChangeKind::Member).await?; // A reset or email-change link must not come back to life when the account is enabled again. invalidate_links(&tx, user_id, &now).await?; // Queued before the sessions go, because the client links are read from them. backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; tx.execute( "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", (user_id.to_string(), now.clone()), ) .await .map_err(db_err)?; // No per-session rows here: the sub-only row above covers every session of the person. tx.execute( "DELETE FROM sessions WHERE user_id = ?1", (user_id.to_string(),), ) .await .map_err(db_err)?; Ok(true) } .await; let result = finish(tx, outcome).await; if matches!(result, Ok(true)) { self.announce_directory(); } result } /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an /// earlier unconfirmed secret of the same user. The user row is not touched. pub async fn set_totp_pending(&self, user_id: &str, sealed_secret: &str) -> Result<()> { self.set_setting(&pending_key(user_id), sealed_secret).await } /// The sealed secret of an enrolment that is waiting for its confirming code, or `None`. pub async fn totp_pending(&self, user_id: &str) -> Result> { self.setting(&pending_key(user_id)).await } /// Turns two-factor sign-in on: stores the confirmed secret, records the step that confirmed /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. /// Sessions created before it are not second-factor sessions, so in the same transaction every live /// session except `keep_session_id` ends, with its back-channel logouts. `None` ends all of them. /// One transaction. Returns false, with nothing changed, when two-factor sign-in is already on (a /// parallel confirmation won) or the account is missing. pub async fn enable_totp( &self, user_id: &str, sealed_secret: &str, step: u64, recovery_hashes: &[String], keep_session_id: Option<&str>, ) -> Result { let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { // Conditional on the state read here: a second confirmation of the same enrolment finds // two-factor sign-in already on, and changes nothing (its recovery codes are not replaced). let changed = tx .execute( "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ totp_last_step = ?4, updated_at = ?3 \ WHERE id = ?1 AND totp_enabled_at IS NULL", ( user_id.to_string(), sealed_secret.to_string(), now.clone(), step, ), ) .await .map_err(db_err)?; if changed != 1 { return Ok(false); } replace_codes(&tx, user_id, recovery_hashes).await?; tx.execute( "DELETE FROM settings WHERE key = ?1", (pending_key(user_id),), ) .await .map_err(db_err)?; let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; Ok(true) } .await; finish(tx, outcome).await } /// Turns two-factor sign-in off: clears the secret, the step and the recovery codes, and drops /// any pending enrolment. Two-factor sign-in was the policy's guard for the session, so in the same /// transaction the person's refresh tokens are revoked and every live session except `keep_session_id` /// ends, with its back-channel logouts. `None` ends all of them. pub async fn disable_totp(&self, user_id: &str, keep_session_id: Option<&str>) -> Result<()> { let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<()> = async { let changed = tx .execute( "UPDATE users SET totp_secret_sealed = NULL, totp_enabled_at = NULL, \ totp_last_step = NULL, updated_at = ?2 WHERE id = ?1", (user_id.to_string(), now.clone()), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } tx.execute( "DELETE FROM recovery_codes WHERE user_id = ?1", (user_id.to_string(),), ) .await .map_err(db_err)?; tx.execute( "DELETE FROM settings WHERE key = ?1", (pending_key(user_id),), ) .await .map_err(db_err)?; tx.execute( "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", (user_id.to_string(), now.clone()), ) .await .map_err(db_err)?; let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; Ok(()) } .await; finish(tx, outcome).await } /// Spends the pending-login nonce of a password-verified sign-in that has just passed its second /// factor. Returns true only for the first spend. `keep_until` is when the nonce may be forgotten: /// after the pending cookie expired, it could not be used anyway. Expired nonces are removed here. pub async fn consume_pending_login(&self, nonce: &str, keep_until: &str) -> Result { let conn = self.inner.conn.lock().await; conn.execute( "DELETE FROM consumed_pending_logins WHERE expires_at <= ?1", (now_stamp(),), ) .await .map_err(db_err)?; let changed = conn .execute( "INSERT OR IGNORE INTO consumed_pending_logins (nonce, expires_at) VALUES (?1, ?2)", (nonce.to_string(), keep_until.to_string()), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Gives back a nonce that [`Store::consume_pending_login`] claimed, when the second factor was wrong, so /// the person can try again with the same pending login. Only a claim that did not lead to a sign-in is /// given back. pub async fn release_pending_login(&self, nonce: &str) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( "DELETE FROM consumed_pending_logins WHERE nonce = ?1", (nonce.to_string(),), ) .await .map_err(db_err)?; Ok(()) } /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard /// forward. A step that is not later than the recorded one, or any step while two-factor is off, /// returns false. This is the replay guard: a code is spent by this single statement. pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result { let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE users SET totp_last_step = ?2 \ WHERE id = ?1 AND totp_enabled_at IS NOT NULL \ AND (totp_last_step IS NULL OR totp_last_step < ?2)", (user_id.to_string(), step), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Replaces every recovery code of the user with `hashes`, all unused. One transaction. pub async fn replace_recovery_codes(&self, user_id: &str, hashes: &[String]) -> Result<()> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<()> = replace_codes(&tx, user_id, hashes).await; finish(tx, outcome).await } /// Spends a recovery code. Returns true only for the first use of an existing, unused code. pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE recovery_codes SET used_at = ?3 \ WHERE user_id = ?1 AND code_hash = ?2 AND used_at IS NULL", (user_id.to_string(), code_hash.to_string(), now_stamp()), ) .await .map_err(db_err)?; Ok(changed == 1) } /// How many recovery codes of the user are still unused. pub async fn unused_recovery_codes(&self, user_id: &str) -> Result { let conn = self.read_conn().await; let count = fetch_opt( &conn, "SELECT COUNT(*) FROM recovery_codes WHERE user_id = ?1 AND used_at IS NULL", (user_id.to_string(),), |row| col_int(row, 0), ) .await? .unwrap_or(0); u64::try_from(count).map_err(|_| Error::Database("negative count".into())) } } #[cfg(test)] mod tests { use super::*; use crate::password::hash_password; async fn store() -> (tempfile::TempDir, Store) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("im.db")).await.unwrap(); (dir, store) } #[tokio::test] async fn the_first_admin_can_be_created_once() { let (_dir, store) = store().await; let hash = hash_password("correct horse battery").unwrap(); let admin = store .create_first_admin("ada@example.com", "Ada", &hash) .await .unwrap(); assert!(admin.is_admin); assert_eq!(store.user_count().await.unwrap(), 1); let second = store .create_first_admin("bob@example.com", "Bob", &hash) .await; assert!(matches!(second, Err(Error::Conflict(_))), "{second:?}"); assert_eq!(store.user_count().await.unwrap(), 1); } #[tokio::test] async fn a_second_enrolment_confirmation_changes_nothing() { let (_dir, store) = store().await; let user = store .create_user("ada@example.com", "Ada", "hash", false) .await .unwrap(); assert!( store .enable_totp(&user.id, "v1:first", 100, &["h1".to_string()], None) .await .unwrap() ); // A parallel confirmation of the same enrolment: refused, and its recovery codes are not stored. assert!( !store .enable_totp(&user.id, "v1:second", 101, &["h2".to_string()], None) .await .unwrap() ); let after = store.user_by_id(&user.id).await.unwrap().unwrap(); assert_eq!(after.totp_last_step, Some(100)); } #[tokio::test] async fn a_totp_step_is_accepted_once_and_only_while_enabled() { let (_dir, store) = store().await; let user = store .create_user("ada@example.com", "Ada", "hash", false) .await .unwrap(); assert!(!store.accept_totp_step(&user.id, 100).await.unwrap()); store.set_totp_pending(&user.id, "v1:sealed").await.unwrap(); assert_eq!( store.totp_pending(&user.id).await.unwrap().as_deref(), Some("v1:sealed") ); store .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()], None) .await .unwrap(); assert!(store.totp_pending(&user.id).await.unwrap().is_none()); assert!(store.accept_totp_step(&user.id, 101).await.unwrap()); // The same step again, and an older one, are refused: the replay guard. assert!(!store.accept_totp_step(&user.id, 101).await.unwrap()); assert!(!store.accept_totp_step(&user.id, 100).await.unwrap()); assert!(store.accept_totp_step(&user.id, 102).await.unwrap()); } #[tokio::test] async fn a_recovery_code_works_once() { let (_dir, store) = store().await; let user = store .create_user("ada@example.com", "Ada", "hash", false) .await .unwrap(); store.set_totp_pending(&user.id, "v1:sealed").await.unwrap(); store .enable_totp( &user.id, "v1:sealed", 5, &["code-a".to_string(), "code-b".to_string()], None, ) .await .unwrap(); assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2); assert!( store .consume_recovery_code(&user.id, "code-a") .await .unwrap() ); assert!( !store .consume_recovery_code(&user.id, "code-a") .await .unwrap() ); assert!( !store .consume_recovery_code(&user.id, "unknown") .await .unwrap() ); assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 1); } #[tokio::test] async fn emails_are_unique_and_found_by_their_normalised_form() { let (_dir, store) = store().await; store .create_user("ada@example.com", "Ada", "hash", false) .await .unwrap(); let dup = store .create_user("ada@example.com", "Ada again", "hash", false) .await; assert!(matches!(dup, Err(Error::Conflict(_))), "{dup:?}"); assert!( store .user_by_email_folded("ada@example.com") .await .unwrap() .is_some() ); assert!( store .user_by_email_folded("ADA@example.com") .await .unwrap() .is_none() ); } }