im
Clone
https://git.tahinli.com/Tahinli/im.git
0 watching·0 forks·Rust·AGPL-3.0·542.8 KiB·b9f0726·Tahinli·27 days ago·34 commits
| 1 | //! User accounts: creation, lookup, profile and password, and the two-factor state. |
| 2 | //! |
| 3 | //! Rules that must hold under concurrency are single conditional statements, so two requests cannot |
| 4 | //! both win: |
| 5 | //! |
| 6 | //! - the first administrator exists only if no user does (`create_first_admin`); |
| 7 | //! - a TOTP step is accepted once (`accept_totp_step`, `totp_last_step` is only ever raised); |
| 8 | //! - a recovery code is spent once (`consume_recovery_code`, `used_at IS NULL`). |
| 9 | //! |
| 10 | //! A TOTP secret that is being enrolled is not written to the user row. It waits in the `settings` |
| 11 | //! table under `totp_pending:<user id>`, sealed like any other secret, and moves to the row only |
| 12 | //! when a code from it is confirmed. So re-enrolling while two-factor is on never switches the |
| 13 | //! second factor off, and an abandoned enrolment changes nothing. |
| 14 | |
| 15 | use turso::{Connection, Row}; |
| 16 | |
| 17 | use crate::error::{Error, Result}; |
| 18 | use crate::model::User; |
| 19 | use crate::store::backchannel::{self, EndReason}; |
| 20 | use crate::store::directory::{ChangeKind, record_change}; |
| 21 | use crate::store::links::invalidate_links; |
| 22 | use crate::store::sessions::{end_rows, live_session_ids}; |
| 23 | use crate::store::{ |
| 24 | Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, |
| 25 | }; |
| 26 | use crate::time::now_stamp; |
| 27 | |
| 28 | /// The columns of a user row, in the order [`map_user`] reads them. |
| 29 | pub(crate) const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ |
| 30 | totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ |
| 31 | photo_mime, picture_version, created_at, updated_at, locale_auto"; |
| 32 | |
| 33 | /// Maps a row selected with [`USER_COLS`]. |
| 34 | pub(crate) fn map_user(row: &Row) -> Result<User> { |
| 35 | Ok(User { |
| 36 | id: col_text(row, 0)?, |
| 37 | email: col_text(row, 1)?, |
| 38 | name: col_text(row, 2)?, |
| 39 | password_hash: col_text(row, 3)?, |
| 40 | is_admin: col_int(row, 4)? != 0, |
| 41 | disabled_at: col_opt_text(row, 5)?, |
| 42 | totp_secret_sealed: col_opt_text(row, 6)?, |
| 43 | totp_enabled_at: col_opt_text(row, 7)?, |
| 44 | totp_last_step: col_opt_int(row, 8)?, |
| 45 | locale: col_text(row, 9)?, |
| 46 | zoneinfo: col_text(row, 10)?, |
| 47 | theme: col_text(row, 11)?, |
| 48 | photo_mime: col_opt_text(row, 12)?, |
| 49 | picture_version: col_int(row, 13)?, |
| 50 | created_at: col_text(row, 14)?, |
| 51 | updated_at: col_text(row, 15)?, |
| 52 | locale_auto: col_int(row, 16)? != 0, |
| 53 | }) |
| 54 | } |
| 55 | |
| 56 | /// Maps an insert error. A UNIQUE violation is a conflict for the person; anything else is a |
| 57 | /// database failure. |
| 58 | pub(crate) fn insert_error(e: turso::Error) -> Error { |
| 59 | let text = e.to_string(); |
| 60 | if text.contains("UNIQUE") { |
| 61 | Error::Conflict("that email address is already registered".into()) |
| 62 | } else { |
| 63 | db_err(e) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// The settings key that holds a TOTP secret waiting for its first confirmed code. |
| 68 | fn pending_key(user_id: &str) -> String { |
| 69 | format!("totp_pending:{user_id}") |
| 70 | } |
| 71 | |
| 72 | /// Replaces the recovery codes of a user with `hashes`. Runs inside the caller's transaction. |
| 73 | async fn replace_codes(conn: &Connection, user_id: &str, hashes: &[String]) -> Result<()> { |
| 74 | conn.execute( |
| 75 | "DELETE FROM recovery_codes WHERE user_id = ?1", |
| 76 | (user_id.to_string(),), |
| 77 | ) |
| 78 | .await |
| 79 | .map_err(db_err)?; |
| 80 | for hash in hashes { |
| 81 | conn.execute( |
| 82 | "INSERT INTO recovery_codes (user_id, code_hash, used_at) VALUES (?1, ?2, NULL)", |
| 83 | (user_id.to_string(), hash.clone()), |
| 84 | ) |
| 85 | .await |
| 86 | .map_err(db_err)?; |
| 87 | } |
| 88 | Ok(()) |
| 89 | } |
| 90 | |
| 91 | impl Store { |
| 92 | /// Creates the first administrator, and only if there is no user at all. |
| 93 | /// |
| 94 | /// The check and the insert are one statement, so two parallel setups cannot both succeed. The |
| 95 | /// second one gets [`Error::Conflict`]. `email` must already be normalised. |
| 96 | pub async fn create_first_admin( |
| 97 | &self, |
| 98 | email: &str, |
| 99 | name: &str, |
| 100 | password_hash: &str, |
| 101 | ) -> Result<User> { |
| 102 | let id = new_id(); |
| 103 | let now = now_stamp(); |
| 104 | let conn = self.inner.conn.lock().await; |
| 105 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 106 | let outcome: Result<bool> = async { |
| 107 | let changed = tx |
| 108 | .execute( |
| 109 | "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ |
| 110 | created_at, updated_at) \ |
| 111 | SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \ |
| 112 | WHERE NOT EXISTS (SELECT 1 FROM users)", |
| 113 | ( |
| 114 | id.clone(), |
| 115 | email.to_string(), |
| 116 | name.to_string(), |
| 117 | password_hash.to_string(), |
| 118 | now, |
| 119 | ), |
| 120 | ) |
| 121 | .await |
| 122 | .map_err(insert_error)?; |
| 123 | if changed == 1 { |
| 124 | record_change(&tx, &id, ChangeKind::Member).await?; |
| 125 | } |
| 126 | Ok(changed == 1) |
| 127 | } |
| 128 | .await; |
| 129 | let created = finish(tx, outcome).await?; |
| 130 | drop(conn); |
| 131 | if !created { |
| 132 | return Err(Error::Conflict("setup is already complete".into())); |
| 133 | } |
| 134 | self.announce_directory(); |
| 135 | self.user_by_id(&id).await?.ok_or(Error::NotFound) |
| 136 | } |
| 137 | |
| 138 | /// Creates an account. `email` must already be normalised. Fails with a conflict when the |
| 139 | /// address is taken. |
| 140 | pub async fn create_user( |
| 141 | &self, |
| 142 | email: &str, |
| 143 | name: &str, |
| 144 | password_hash: &str, |
| 145 | is_admin: bool, |
| 146 | ) -> Result<User> { |
| 147 | let id = new_id(); |
| 148 | let now = now_stamp(); |
| 149 | let conn = self.inner.conn.lock().await; |
| 150 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 151 | let outcome: Result<()> = async { |
| 152 | tx.execute( |
| 153 | "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ |
| 154 | created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", |
| 155 | ( |
| 156 | id.clone(), |
| 157 | email.to_string(), |
| 158 | name.to_string(), |
| 159 | password_hash.to_string(), |
| 160 | i64::from(is_admin), |
| 161 | now, |
| 162 | ), |
| 163 | ) |
| 164 | .await |
| 165 | .map_err(insert_error)?; |
| 166 | record_change(&tx, &id, ChangeKind::Member).await |
| 167 | } |
| 168 | .await; |
| 169 | finish(tx, outcome).await?; |
| 170 | drop(conn); |
| 171 | self.announce_directory(); |
| 172 | self.user_by_id(&id).await?.ok_or(Error::NotFound) |
| 173 | } |
| 174 | |
| 175 | /// The user with this id, or `None`. |
| 176 | pub async fn user_by_id(&self, id: &str) -> Result<Option<User>> { |
| 177 | let conn = self.read_conn().await; |
| 178 | fetch_opt( |
| 179 | &conn, |
| 180 | &format!("SELECT {USER_COLS} FROM users WHERE id = ?1"), |
| 181 | (id.to_string(),), |
| 182 | map_user, |
| 183 | ) |
| 184 | .await |
| 185 | } |
| 186 | |
| 187 | /// The user with this normalised address, or `None`. Callers normalise the input first. |
| 188 | pub async fn user_by_email_folded(&self, folded: &str) -> Result<Option<User>> { |
| 189 | let conn = self.read_conn().await; |
| 190 | fetch_opt( |
| 191 | &conn, |
| 192 | &format!("SELECT {USER_COLS} FROM users WHERE email_folded = ?1"), |
| 193 | (folded.to_string(),), |
| 194 | map_user, |
| 195 | ) |
| 196 | .await |
| 197 | } |
| 198 | |
| 199 | /// Changes the display name, and writes its directory row, in one transaction. The caller has |
| 200 | /// checked the name with `names::parse_display_name`; the schema keeps it at 1 to 100 characters. |
| 201 | pub async fn update_name(&self, id: &str, name: &str) -> Result<()> { |
| 202 | let conn = self.inner.conn.lock().await; |
| 203 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 204 | let outcome: Result<()> = async { |
| 205 | let changed = tx |
| 206 | .execute( |
| 207 | "UPDATE users SET name = ?2, updated_at = ?3 WHERE id = ?1", |
| 208 | (id.to_string(), name.to_string(), now_stamp()), |
| 209 | ) |
| 210 | .await |
| 211 | .map_err(db_err)?; |
| 212 | if changed == 0 { |
| 213 | return Err(Error::NotFound); |
| 214 | } |
| 215 | record_change(&tx, id, ChangeKind::Member).await |
| 216 | } |
| 217 | .await; |
| 218 | let result = finish(tx, outcome).await; |
| 219 | if result.is_ok() { |
| 220 | self.announce_directory(); |
| 221 | } |
| 222 | result |
| 223 | } |
| 224 | |
| 225 | /// Changes the language, time zone and theme. `locale_auto` true means the language follows the |
| 226 | /// browser and `locale` is kept only for when it is turned off again. The schema rejects unknown |
| 227 | /// languages and themes. |
| 228 | pub async fn update_preferences( |
| 229 | &self, |
| 230 | id: &str, |
| 231 | locale: &str, |
| 232 | locale_auto: bool, |
| 233 | zoneinfo: &str, |
| 234 | theme: &str, |
| 235 | ) -> Result<()> { |
| 236 | let conn = self.inner.conn.lock().await; |
| 237 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 238 | let outcome: Result<()> = async { |
| 239 | let changed = tx |
| 240 | .execute( |
| 241 | "UPDATE users SET locale = ?2, locale_auto = ?3, zoneinfo = ?4, theme = ?5, \ |
| 242 | updated_at = ?6 WHERE id = ?1", |
| 243 | ( |
| 244 | id.to_string(), |
| 245 | locale.to_string(), |
| 246 | i64::from(locale_auto), |
| 247 | zoneinfo.to_string(), |
| 248 | theme.to_string(), |
| 249 | now_stamp(), |
| 250 | ), |
| 251 | ) |
| 252 | .await |
| 253 | .map_err(db_err)?; |
| 254 | if changed == 0 { |
| 255 | return Err(Error::NotFound); |
| 256 | } |
| 257 | record_change(&tx, id, ChangeKind::Member).await |
| 258 | } |
| 259 | .await; |
| 260 | let result = finish(tx, outcome).await; |
| 261 | if result.is_ok() { |
| 262 | self.announce_directory(); |
| 263 | } |
| 264 | result |
| 265 | } |
| 266 | |
| 267 | /// Records that a photo was stored: sets its MIME type, bumps `picture_version` so caches see a |
| 268 | /// new picture, and writes the directory row. One transaction. The file itself is written by the |
| 269 | /// caller with [`crate::photo::write_photo`], before this call. |
| 270 | pub async fn set_photo(&self, id: &str, mime: &str) -> Result<()> { |
| 271 | let conn = self.inner.conn.lock().await; |
| 272 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 273 | let outcome: Result<()> = async { |
| 274 | let changed = tx |
| 275 | .execute( |
| 276 | "UPDATE users SET photo_mime = ?2, picture_version = picture_version + 1, \ |
| 277 | updated_at = ?3 WHERE id = ?1", |
| 278 | (id.to_string(), mime.to_string(), now_stamp()), |
| 279 | ) |
| 280 | .await |
| 281 | .map_err(db_err)?; |
| 282 | if changed == 0 { |
| 283 | return Err(Error::NotFound); |
| 284 | } |
| 285 | record_change(&tx, id, ChangeKind::Member).await |
| 286 | } |
| 287 | .await; |
| 288 | let result = finish(tx, outcome).await; |
| 289 | if result.is_ok() { |
| 290 | self.announce_directory(); |
| 291 | } |
| 292 | result |
| 293 | } |
| 294 | |
| 295 | /// Records that the photo was removed. Returns false, and writes nothing, when there was no |
| 296 | /// photo. Otherwise it clears the MIME type, bumps `picture_version` and writes the directory row. |
| 297 | pub async fn clear_photo(&self, id: &str) -> Result<bool> { |
| 298 | let conn = self.inner.conn.lock().await; |
| 299 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 300 | let outcome: Result<bool> = async { |
| 301 | let changed = tx |
| 302 | .execute( |
| 303 | "UPDATE users SET photo_mime = NULL, picture_version = picture_version + 1, \ |
| 304 | updated_at = ?2 WHERE id = ?1 AND photo_mime IS NOT NULL", |
| 305 | (id.to_string(), now_stamp()), |
| 306 | ) |
| 307 | .await |
| 308 | .map_err(db_err)?; |
| 309 | if changed == 0 { |
| 310 | return Ok(false); |
| 311 | } |
| 312 | record_change(&tx, id, ChangeKind::Member).await?; |
| 313 | Ok(true) |
| 314 | } |
| 315 | .await; |
| 316 | let result = finish(tx, outcome).await; |
| 317 | if matches!(result, Ok(true)) { |
| 318 | self.announce_directory(); |
| 319 | } |
| 320 | result |
| 321 | } |
| 322 | |
| 323 | /// Stores a new argon2id hash, ends every live session of the person except `keep_session_id`, |
| 324 | /// with their back-channel logouts, and invalidates every pending account link (password reset and |
| 325 | /// email change), so a link issued for the old password cannot set or change anything. One |
| 326 | /// transaction: the old password never stays in force for a session that the new one has ended, and |
| 327 | /// nothing changes unless all of it happens. The caller has checked the policy and the current |
| 328 | /// password. Returns the ids of the sessions ended. |
| 329 | pub async fn change_password( |
| 330 | &self, |
| 331 | id: &str, |
| 332 | password_hash: &str, |
| 333 | keep_session_id: &str, |
| 334 | ) -> Result<Vec<String>> { |
| 335 | let now = now_stamp(); |
| 336 | let conn = self.inner.conn.lock().await; |
| 337 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 338 | let outcome: Result<Vec<String>> = async { |
| 339 | let changed = tx |
| 340 | .execute( |
| 341 | "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1", |
| 342 | (id.to_string(), password_hash.to_string(), now.clone()), |
| 343 | ) |
| 344 | .await |
| 345 | .map_err(db_err)?; |
| 346 | if changed == 0 { |
| 347 | return Err(Error::NotFound); |
| 348 | } |
| 349 | invalidate_links(&tx, id, &now).await?; |
| 350 | let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?; |
| 351 | end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?; |
| 352 | Ok(ids) |
| 353 | } |
| 354 | .await; |
| 355 | finish(tx, outcome).await |
| 356 | } |
| 357 | |
| 358 | /// Disables an account. The last enabled administrator cannot be disabled: that is part of the |
| 359 | /// same conditional `UPDATE`, so two parallel requests cannot both disable the last two. In one transaction: the account is marked disabled, the directory feed |
| 360 | /// records the change, one `sub`-only back-channel logout is queued for every client the person |
| 361 | /// used (contracts.md 2.5), the refresh tokens are revoked, the pending reset and email-change links are |
| 362 | /// used up, and every session is deleted. Returns |
| 363 | /// false, with nothing changed, when the account is missing or already disabled. |
| 364 | pub async fn disable_user(&self, user_id: &str) -> Result<bool> { |
| 365 | let now = now_stamp(); |
| 366 | let conn = self.inner.conn.lock().await; |
| 367 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 368 | let outcome: Result<bool> = async { |
| 369 | let changed = tx |
| 370 | .execute( |
| 371 | "UPDATE users SET disabled_at = ?2, updated_at = ?2 \ |
| 372 | WHERE id = ?1 AND disabled_at IS NULL \ |
| 373 | AND (is_admin = 0 OR (SELECT COUNT(*) FROM users \ |
| 374 | WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", |
| 375 | (user_id.to_string(), now.clone()), |
| 376 | ) |
| 377 | .await |
| 378 | .map_err(db_err)?; |
| 379 | if changed != 1 { |
| 380 | return Ok(false); |
| 381 | } |
| 382 | record_change(&tx, user_id, ChangeKind::Member).await?; |
| 383 | // A reset or email-change link must not come back to life when the account is enabled again. |
| 384 | invalidate_links(&tx, user_id, &now).await?; |
| 385 | // Queued before the sessions go, because the client links are read from them. |
| 386 | backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; |
| 387 | tx.execute( |
| 388 | "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", |
| 389 | (user_id.to_string(), now.clone()), |
| 390 | ) |
| 391 | .await |
| 392 | .map_err(db_err)?; |
| 393 | // No per-session rows here: the sub-only row above covers every session of the person. |
| 394 | tx.execute( |
| 395 | "DELETE FROM sessions WHERE user_id = ?1", |
| 396 | (user_id.to_string(),), |
| 397 | ) |
| 398 | .await |
| 399 | .map_err(db_err)?; |
| 400 | Ok(true) |
| 401 | } |
| 402 | .await; |
| 403 | let result = finish(tx, outcome).await; |
| 404 | if matches!(result, Ok(true)) { |
| 405 | self.announce_directory(); |
| 406 | } |
| 407 | result |
| 408 | } |
| 409 | |
| 410 | /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an |
| 411 | /// earlier unconfirmed secret of the same user. The user row is not touched. |
| 412 | pub async fn set_totp_pending(&self, user_id: &str, sealed_secret: &str) -> Result<()> { |
| 413 | self.set_setting(&pending_key(user_id), sealed_secret).await |
| 414 | } |
| 415 | |
| 416 | /// The sealed secret of an enrolment that is waiting for its confirming code, or `None`. |
| 417 | pub async fn totp_pending(&self, user_id: &str) -> Result<Option<String>> { |
| 418 | self.setting(&pending_key(user_id)).await |
| 419 | } |
| 420 | |
| 421 | /// Turns two-factor sign-in on: stores the confirmed secret, records the step that confirmed |
| 422 | /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. |
| 423 | /// Sessions created before it are not second-factor sessions, so in the same transaction every live |
| 424 | /// session except `keep_session_id` ends, with its back-channel logouts. `None` ends all of them. |
| 425 | /// One transaction. Returns false, with nothing changed, when two-factor sign-in is already on (a |
| 426 | /// parallel confirmation won) or the account is missing. |
| 427 | pub async fn enable_totp( |
| 428 | &self, |
| 429 | user_id: &str, |
| 430 | sealed_secret: &str, |
| 431 | step: u64, |
| 432 | recovery_hashes: &[String], |
| 433 | keep_session_id: Option<&str>, |
| 434 | ) -> Result<bool> { |
| 435 | let step = |
| 436 | i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; |
| 437 | let now = now_stamp(); |
| 438 | let conn = self.inner.conn.lock().await; |
| 439 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 440 | let outcome: Result<bool> = async { |
| 441 | // Conditional on the state read here: a second confirmation of the same enrolment finds |
| 442 | // two-factor sign-in already on, and changes nothing (its recovery codes are not replaced). |
| 443 | let changed = tx |
| 444 | .execute( |
| 445 | "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ |
| 446 | totp_last_step = ?4, updated_at = ?3 \ |
| 447 | WHERE id = ?1 AND totp_enabled_at IS NULL", |
| 448 | ( |
| 449 | user_id.to_string(), |
| 450 | sealed_secret.to_string(), |
| 451 | now.clone(), |
| 452 | step, |
| 453 | ), |
| 454 | ) |
| 455 | .await |
| 456 | .map_err(db_err)?; |
| 457 | if changed != 1 { |
| 458 | return Ok(false); |
| 459 | } |
| 460 | replace_codes(&tx, user_id, recovery_hashes).await?; |
| 461 | tx.execute( |
| 462 | "DELETE FROM settings WHERE key = ?1", |
| 463 | (pending_key(user_id),), |
| 464 | ) |
| 465 | .await |
| 466 | .map_err(db_err)?; |
| 467 | let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; |
| 468 | end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; |
| 469 | Ok(true) |
| 470 | } |
| 471 | .await; |
| 472 | finish(tx, outcome).await |
| 473 | } |
| 474 | |
| 475 | /// Turns two-factor sign-in off: clears the secret, the step and the recovery codes, and drops |
| 476 | /// any pending enrolment. Two-factor sign-in was the policy's guard for the session, so in the same |
| 477 | /// transaction the person's refresh tokens are revoked and every live session except `keep_session_id` |
| 478 | /// ends, with its back-channel logouts. `None` ends all of them. |
| 479 | pub async fn disable_totp(&self, user_id: &str, keep_session_id: Option<&str>) -> Result<()> { |
| 480 | let now = now_stamp(); |
| 481 | let conn = self.inner.conn.lock().await; |
| 482 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 483 | let outcome: Result<()> = async { |
| 484 | let changed = tx |
| 485 | .execute( |
| 486 | "UPDATE users SET totp_secret_sealed = NULL, totp_enabled_at = NULL, \ |
| 487 | totp_last_step = NULL, updated_at = ?2 WHERE id = ?1", |
| 488 | (user_id.to_string(), now.clone()), |
| 489 | ) |
| 490 | .await |
| 491 | .map_err(db_err)?; |
| 492 | if changed == 0 { |
| 493 | return Err(Error::NotFound); |
| 494 | } |
| 495 | tx.execute( |
| 496 | "DELETE FROM recovery_codes WHERE user_id = ?1", |
| 497 | (user_id.to_string(),), |
| 498 | ) |
| 499 | .await |
| 500 | .map_err(db_err)?; |
| 501 | tx.execute( |
| 502 | "DELETE FROM settings WHERE key = ?1", |
| 503 | (pending_key(user_id),), |
| 504 | ) |
| 505 | .await |
| 506 | .map_err(db_err)?; |
| 507 | tx.execute( |
| 508 | "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", |
| 509 | (user_id.to_string(), now.clone()), |
| 510 | ) |
| 511 | .await |
| 512 | .map_err(db_err)?; |
| 513 | let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; |
| 514 | end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; |
| 515 | Ok(()) |
| 516 | } |
| 517 | .await; |
| 518 | finish(tx, outcome).await |
| 519 | } |
| 520 | |
| 521 | /// Spends the pending-login nonce of a password-verified sign-in that has just passed its second |
| 522 | /// factor. Returns true only for the first spend. `keep_until` is when the nonce may be forgotten: |
| 523 | /// after the pending cookie expired, it could not be used anyway. Expired nonces are removed here. |
| 524 | pub async fn consume_pending_login(&self, nonce: &str, keep_until: &str) -> Result<bool> { |
| 525 | let conn = self.inner.conn.lock().await; |
| 526 | conn.execute( |
| 527 | "DELETE FROM consumed_pending_logins WHERE expires_at <= ?1", |
| 528 | (now_stamp(),), |
| 529 | ) |
| 530 | .await |
| 531 | .map_err(db_err)?; |
| 532 | let changed = conn |
| 533 | .execute( |
| 534 | "INSERT OR IGNORE INTO consumed_pending_logins (nonce, expires_at) VALUES (?1, ?2)", |
| 535 | (nonce.to_string(), keep_until.to_string()), |
| 536 | ) |
| 537 | .await |
| 538 | .map_err(db_err)?; |
| 539 | Ok(changed == 1) |
| 540 | } |
| 541 | |
| 542 | /// Gives back a nonce that [`Store::consume_pending_login`] claimed, when the second factor was wrong, so |
| 543 | /// the person can try again with the same pending login. Only a claim that did not lead to a sign-in is |
| 544 | /// given back. |
| 545 | pub async fn release_pending_login(&self, nonce: &str) -> Result<()> { |
| 546 | let conn = self.inner.conn.lock().await; |
| 547 | conn.execute( |
| 548 | "DELETE FROM consumed_pending_logins WHERE nonce = ?1", |
| 549 | (nonce.to_string(),), |
| 550 | ) |
| 551 | .await |
| 552 | .map_err(db_err)?; |
| 553 | Ok(()) |
| 554 | } |
| 555 | |
| 556 | /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard |
| 557 | /// forward. A step that is not later than the recorded one, or any step while two-factor is off, |
| 558 | /// returns false. This is the replay guard: a code is spent by this single statement. |
| 559 | pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result<bool> { |
| 560 | let step = |
| 561 | i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; |
| 562 | let conn = self.inner.conn.lock().await; |
| 563 | let changed = conn |
| 564 | .execute( |
| 565 | "UPDATE users SET totp_last_step = ?2 \ |
| 566 | WHERE id = ?1 AND totp_enabled_at IS NOT NULL \ |
| 567 | AND (totp_last_step IS NULL OR totp_last_step < ?2)", |
| 568 | (user_id.to_string(), step), |
| 569 | ) |
| 570 | .await |
| 571 | .map_err(db_err)?; |
| 572 | Ok(changed == 1) |
| 573 | } |
| 574 | |
| 575 | /// Replaces every recovery code of the user with `hashes`, all unused. One transaction. |
| 576 | pub async fn replace_recovery_codes(&self, user_id: &str, hashes: &[String]) -> Result<()> { |
| 577 | let conn = self.inner.conn.lock().await; |
| 578 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 579 | let outcome: Result<()> = replace_codes(&tx, user_id, hashes).await; |
| 580 | finish(tx, outcome).await |
| 581 | } |
| 582 | |
| 583 | /// Spends a recovery code. Returns true only for the first use of an existing, unused code. |
| 584 | pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result<bool> { |
| 585 | let conn = self.inner.conn.lock().await; |
| 586 | let changed = conn |
| 587 | .execute( |
| 588 | "UPDATE recovery_codes SET used_at = ?3 \ |
| 589 | WHERE user_id = ?1 AND code_hash = ?2 AND used_at IS NULL", |
| 590 | (user_id.to_string(), code_hash.to_string(), now_stamp()), |
| 591 | ) |
| 592 | .await |
| 593 | .map_err(db_err)?; |
| 594 | Ok(changed == 1) |
| 595 | } |
| 596 | |
| 597 | /// How many recovery codes of the user are still unused. |
| 598 | pub async fn unused_recovery_codes(&self, user_id: &str) -> Result<u64> { |
| 599 | let conn = self.read_conn().await; |
| 600 | let count = fetch_opt( |
| 601 | &conn, |
| 602 | "SELECT COUNT(*) FROM recovery_codes WHERE user_id = ?1 AND used_at IS NULL", |
| 603 | (user_id.to_string(),), |
| 604 | |row| col_int(row, 0), |
| 605 | ) |
| 606 | .await? |
| 607 | .unwrap_or(0); |
| 608 | u64::try_from(count).map_err(|_| Error::Database("negative count".into())) |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | #[cfg(test)] |
| 613 | mod tests { |
| 614 | use super::*; |
| 615 | use crate::password::hash_password; |
| 616 | |
| 617 | async fn store() -> (tempfile::TempDir, Store) { |
| 618 | let dir = tempfile::tempdir().unwrap(); |
| 619 | let store = Store::open(&dir.path().join("im.db")).await.unwrap(); |
| 620 | (dir, store) |
| 621 | } |
| 622 | |
| 623 | #[tokio::test] |
| 624 | async fn the_first_admin_can_be_created_once() { |
| 625 | let (_dir, store) = store().await; |
| 626 | let hash = hash_password("correct horse battery").unwrap(); |
| 627 | let admin = store |
| 628 | .create_first_admin("ada@example.com", "Ada", &hash) |
| 629 | .await |
| 630 | .unwrap(); |
| 631 | assert!(admin.is_admin); |
| 632 | assert_eq!(store.user_count().await.unwrap(), 1); |
| 633 | |
| 634 | let second = store |
| 635 | .create_first_admin("bob@example.com", "Bob", &hash) |
| 636 | .await; |
| 637 | assert!(matches!(second, Err(Error::Conflict(_))), "{second:?}"); |
| 638 | assert_eq!(store.user_count().await.unwrap(), 1); |
| 639 | } |
| 640 | |
| 641 | #[tokio::test] |
| 642 | async fn a_second_enrolment_confirmation_changes_nothing() { |
| 643 | let (_dir, store) = store().await; |
| 644 | let user = store |
| 645 | .create_user("ada@example.com", "Ada", "hash", false) |
| 646 | .await |
| 647 | .unwrap(); |
| 648 | assert!( |
| 649 | store |
| 650 | .enable_totp(&user.id, "v1:first", 100, &["h1".to_string()], None) |
| 651 | .await |
| 652 | .unwrap() |
| 653 | ); |
| 654 | // A parallel confirmation of the same enrolment: refused, and its recovery codes are not stored. |
| 655 | assert!( |
| 656 | !store |
| 657 | .enable_totp(&user.id, "v1:second", 101, &["h2".to_string()], None) |
| 658 | .await |
| 659 | .unwrap() |
| 660 | ); |
| 661 | let after = store.user_by_id(&user.id).await.unwrap().unwrap(); |
| 662 | assert_eq!(after.totp_last_step, Some(100)); |
| 663 | } |
| 664 | |
| 665 | #[tokio::test] |
| 666 | async fn a_totp_step_is_accepted_once_and_only_while_enabled() { |
| 667 | let (_dir, store) = store().await; |
| 668 | let user = store |
| 669 | .create_user("ada@example.com", "Ada", "hash", false) |
| 670 | .await |
| 671 | .unwrap(); |
| 672 | assert!(!store.accept_totp_step(&user.id, 100).await.unwrap()); |
| 673 | |
| 674 | store.set_totp_pending(&user.id, "v1:sealed").await.unwrap(); |
| 675 | assert_eq!( |
| 676 | store.totp_pending(&user.id).await.unwrap().as_deref(), |
| 677 | Some("v1:sealed") |
| 678 | ); |
| 679 | store |
| 680 | .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()], None) |
| 681 | .await |
| 682 | .unwrap(); |
| 683 | assert!(store.totp_pending(&user.id).await.unwrap().is_none()); |
| 684 | |
| 685 | assert!(store.accept_totp_step(&user.id, 101).await.unwrap()); |
| 686 | // The same step again, and an older one, are refused: the replay guard. |
| 687 | assert!(!store.accept_totp_step(&user.id, 101).await.unwrap()); |
| 688 | assert!(!store.accept_totp_step(&user.id, 100).await.unwrap()); |
| 689 | assert!(store.accept_totp_step(&user.id, 102).await.unwrap()); |
| 690 | } |
| 691 | |
| 692 | #[tokio::test] |
| 693 | async fn a_recovery_code_works_once() { |
| 694 | let (_dir, store) = store().await; |
| 695 | let user = store |
| 696 | .create_user("ada@example.com", "Ada", "hash", false) |
| 697 | .await |
| 698 | .unwrap(); |
| 699 | store.set_totp_pending(&user.id, "v1:sealed").await.unwrap(); |
| 700 | store |
| 701 | .enable_totp( |
| 702 | &user.id, |
| 703 | "v1:sealed", |
| 704 | 5, |
| 705 | &["code-a".to_string(), "code-b".to_string()], |
| 706 | None, |
| 707 | ) |
| 708 | .await |
| 709 | .unwrap(); |
| 710 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2); |
| 711 | |
| 712 | assert!( |
| 713 | store |
| 714 | .consume_recovery_code(&user.id, "code-a") |
| 715 | .await |
| 716 | .unwrap() |
| 717 | ); |
| 718 | assert!( |
| 719 | !store |
| 720 | .consume_recovery_code(&user.id, "code-a") |
| 721 | .await |
| 722 | .unwrap() |
| 723 | ); |
| 724 | assert!( |
| 725 | !store |
| 726 | .consume_recovery_code(&user.id, "unknown") |
| 727 | .await |
| 728 | .unwrap() |
| 729 | ); |
| 730 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 1); |
| 731 | } |
| 732 | |
| 733 | #[tokio::test] |
| 734 | async fn emails_are_unique_and_found_by_their_normalised_form() { |
| 735 | let (_dir, store) = store().await; |
| 736 | store |
| 737 | .create_user("ada@example.com", "Ada", "hash", false) |
| 738 | .await |
| 739 | .unwrap(); |
| 740 | let dup = store |
| 741 | .create_user("ada@example.com", "Ada again", "hash", false) |
| 742 | .await; |
| 743 | assert!(matches!(dup, Err(Error::Conflict(_))), "{dup:?}"); |
| 744 | assert!( |
| 745 | store |
| 746 | .user_by_email_folded("ada@example.com") |
| 747 | .await |
| 748 | .unwrap() |
| 749 | .is_some() |
| 750 | ); |
| 751 | assert!( |
| 752 | store |
| 753 | .user_by_email_folded("ADA@example.com") |
| 754 | .await |
| 755 | .unwrap() |
| 756 | .is_none() |
| 757 | ); |
| 758 | } |
| 759 | } |