diff --git a/Cargo.lock b/Cargo.lock index 86aa835..0918329 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14,7 +14,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "generic-array", ] @@ -126,6 +126,18 @@ dependencies = [ "rustversion", ] +[[package]] +name = "argon2" +version = "0.6.0-rc.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7af50940b73bf4e16c15c448a2b121c63f2d68e3e54b6a8731673cb4aa0cdff5" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.3.0", + "password-hash", +] + [[package]] name = "aristo" version = "0.4.1" @@ -302,6 +314,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bigdecimal" version = "0.4.10" @@ -365,6 +383,15 @@ dependencies = [ "wyz", ] +[[package]] +name = "blake2" +version = "0.11.0-rc.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f1a09225e328e1ffbb378d2d49923c0ca5fee19fb5ac1cc9c1e9d52b93690" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -374,6 +401,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bon" version = "3.10.0" @@ -525,7 +561,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "inout", ] @@ -540,6 +576,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "codee" version = "0.3.5" @@ -606,6 +648,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const-str" version = "1.1.0" @@ -759,6 +807,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "ctr" version = "0.9.2" @@ -768,6 +825,15 @@ dependencies = [ "cipher", ] +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + [[package]] name = "darling" version = "0.24.1" @@ -840,8 +906,20 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -859,9 +937,13 @@ dependencies = [ name = "dizey-core" version = "0.1.0" dependencies = [ + "argon2", "async-trait", + "rand 0.10.2", "serde", "serde_json", + "sha2 0.11.0", + "subtle", "thiserror", "time", "tokio", @@ -1413,6 +1495,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + [[package]] name = "hydration_context" version = "0.4.0-beta" @@ -2466,6 +2557,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b" +dependencies = [ + "getrandom 0.4.3", + "phc", +] + [[package]] name = "paste" version = "1.0.15" @@ -2490,6 +2591,17 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phc" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892" +dependencies = [ + "base64ct", + "ctutils", + "getrandom 0.4.3", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -3228,7 +3340,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -3245,7 +3357,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", ] [[package]] @@ -4313,7 +4436,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "subtle", ] @@ -4483,7 +4606,7 @@ checksum = "3e653af7ee4a9ef0fce481a9ec6f43cb78de20d0cdb4f4f5862e1dc6e407e6c8" dependencies = [ "base16", "quote", - "sha2", + "sha2 0.10.9", "syn 2.0.119", ] diff --git a/Cargo.toml b/Cargo.toml index ff08544..32b3e4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,10 @@ uuid = { version = "1.25.0", features = ["v4", "serde"] } time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] } tokio = { version = "1.53.1", features = ["full"] } turso = "=0.8.0-pre.7" +argon2 = "0.6.0-rc.8" +rand = "0.10.2" +sha2 = "0.11.0" +subtle = "2.6.1" [profile.release] codegen-units = 1 diff --git a/crates/dizey-core/Cargo.toml b/crates/dizey-core/Cargo.toml index 7378633..6c49788 100644 --- a/crates/dizey-core/Cargo.toml +++ b/crates/dizey-core/Cargo.toml @@ -7,7 +7,11 @@ repository.workspace = true description = "Domain model and storage for Dizey" [dependencies] +argon2.workspace = true async-trait = "0.1.92" +rand.workspace = true +sha2.workspace = true +subtle.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/crates/dizey-core/migrations/0002_auth.sql b/crates/dizey-core/migrations/0002_auth.sql new file mode 100644 index 0000000..ed87248 --- /dev/null +++ b/crates/dizey-core/migrations/0002_auth.sql @@ -0,0 +1,33 @@ +-- Sessions, the single-owner claim, and the rate-limit ledger. + +-- Exactly one row, ever. The primary key is the whole point: two requests +-- racing to claim an empty workspace both try to insert singleton = 1 and the +-- database picks the winner, inside the same transaction that writes the +-- workspace and its admin. +CREATE TABLE workspace_owner ( + singleton INTEGER PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + claimed_at TEXT NOT NULL +); + +-- A signed-in browser. Only the hash of the cookie token is stored, exactly +-- like sign-in links and read-only links. +CREATE TABLE session ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + token_hash TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + revoked_at TEXT +); +CREATE UNIQUE INDEX session_token ON session(token_hash); +CREATE INDEX session_by_user ON session(user_id); + +-- Sign-in attempts and link redemptions, one row per attempt, counted over a +-- window. The bucket is the address or the client address, never the password. +CREATE TABLE auth_attempt ( + id TEXT PRIMARY KEY, + bucket TEXT NOT NULL, + attempted_at TEXT NOT NULL +); +CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at); diff --git a/crates/dizey-core/src/accounts.rs b/crates/dizey-core/src/accounts.rs new file mode 100644 index 0000000..e6257bc --- /dev/null +++ b/crates/dizey-core/src/accounts.rs @@ -0,0 +1,379 @@ +//! The account flows: claiming the workspace, inviting people, first sign-in, +//! signing in, changing a password, and turning a cookie back into a person. +//! +//! Two rules run through all of it. +//! +//! * **The public surface answers the same way whether or not an address has an +//! account.** That means the same wording *and* the same work: every path +//! that misses still pays for an Argon2 verify, or the response time becomes +//! the oracle the wording refuses to be. The honest, specific strings in the +//! mockups are admin-side copy and stay admin-side. +//! * **Capability checks live here, not in the UI.** A Viewer or a Member +//! calling an admin-only flow is rejected by this module. + +use std::sync::Arc; + +use time::{Duration, OffsetDateTime}; + +use crate::auth::{ + self, AuthError, PasswordProblem, Token, hash_password, verify_password, +}; +use crate::store::{NewUser, Session, Store, StoreError, User, Workspace}; +use crate::Role; + +/// How long a first-sign-in link is good for. The mockups say seven days, and +/// an expired link is not a dead account: resending opens the same one. +pub const SIGNIN_LINK_LIFETIME: Duration = Duration::days(7); + +/// How long a signed-in browser stays signed in. +pub const SESSION_LIFETIME: Duration = Duration::days(14); + +/// The rate-limit window and its allowance. Deliberately modest: this exists so +/// an open form is not an unbounded Argon2 faucet, not to be clever. +pub const RATE_WINDOW: Duration = Duration::minutes(15); +pub const RATE_LIMIT: u64 = 10; + +/// What went wrong, in the vocabulary the caller is allowed to have. +#[derive(Debug, thiserror::Error)] +pub enum AccountError { + /// The credentials did not work. Deliberately says nothing about which + /// half, or whether the address exists at all. + #[error("that did not work")] + Rejected, + /// Too many attempts from this address or this client, recently. + #[error("too many attempts — wait a few minutes and try again")] + RateLimited, + /// A password the person chose broke a stated rule. Only ever returned on + /// screens where we already know who they are. + #[error("{0}")] + Password(#[from] PasswordProblem), + /// The caller's role does not permit this. + #[error("not permitted")] + Forbidden, + /// This workspace already has an owner. + #[error("this workspace already has an owner")] + AlreadyClaimed, + /// That address already has an account here. Admin-side wording: it is + /// shown on the member list, never on a public form. + #[error("that address already has an account")] + AddressTaken, + #[error("{0}")] + Store(#[from] StoreError), + #[error("{0}")] + Auth(#[from] AuthError), +} + +pub type Result = std::result::Result; + +/// A person plus the browser they are using. +#[derive(Debug)] +pub struct SignedIn { + pub user: User, + /// The cookie value. Exists exactly once, here. + pub session_token: Token, + pub session: Session, +} + +/// An invitation the admin can hand over. The link is shown once; after that +/// only its hash exists. +#[derive(Debug)] +pub struct Invitation { + pub user: User, + pub token: Token, + pub expires_at: OffsetDateTime, +} + +#[derive(Clone)] +pub struct Accounts { + store: Arc, +} + +impl Accounts { + pub fn new(store: Arc) -> Self { + Self { store } + } + + pub fn store(&self) -> &Arc { + &self.store + } + + // -- claiming ---------------------------------------------------------- + + /// The very first account. It becomes the admin and owns the workspace. + /// + /// The claim is atomic in the store, so two people racing an empty install + /// cannot both end up admin and the loser does not quietly become a member. + pub async fn claim_workspace( + &self, + workspace_name: &str, + email: &str, + display_name: &str, + password: &str, + ) -> Result<(Workspace, SignedIn)> { + auth::check_password(password, email, display_name)?; + let hash = hash_password(password)?; + let (workspace, admin) = match self + .store + .claim_workspace(workspace_name, email, display_name, &hash) + .await + { + Ok(pair) => pair, + Err(StoreError::AlreadyClaimed) => return Err(AccountError::AlreadyClaimed), + Err(e) => return Err(e.into()), + }; + let signed_in = self.start_session(admin).await?; + Ok((workspace, signed_in)) + } + + // -- inviting ---------------------------------------------------------- + + /// Creates an account with a name and an address and no password, and mints + /// the link that lets that person choose one. + /// + /// The admin never learns the password: only the hash of this link is + /// stored, and the password is set by the person on the other end. + pub async fn invite( + &self, + actor: &User, + email: &str, + display_name: &str, + role: Role, + ) -> Result { + self.require_admin(actor)?; + let user = self + .store + .create_user(NewUser { + workspace_id: actor.workspace_id.clone(), + email: email.to_string(), + display_name: display_name.to_string(), + role, + }) + .await + .map_err(|e| match e { + StoreError::Conflict("account") => AccountError::AddressTaken, + other => other.into(), + })?; + self.mint_link(actor, &user).await + } + + /// Sends the same person a fresh link. An expired link is not a dead + /// account: this opens the same one. + pub async fn resend_invitation(&self, actor: &User, user_id: &str) -> Result { + self.require_admin(actor)?; + let user = self + .store + .user(user_id) + .await? + .ok_or(StoreError::NotFound)?; + if user.workspace_id != actor.workspace_id { + return Err(AccountError::Forbidden); + } + self.mint_link(actor, &user).await + } + + async fn mint_link(&self, _actor: &User, user: &User) -> Result { + let token = Token::mint(); + let expires_at = OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME; + self.store + .create_signin_link(&user.id, &token.hash(), expires_at) + .await?; + Ok(Invitation { + user: user.clone(), + token, + expires_at, + }) + } + + // -- first sign-in ----------------------------------------------------- + + /// Redeems a first-sign-in link and sets the password the person chose. + /// + /// Every failure — unknown link, expired link, already-used link — is the + /// same [`AccountError::Rejected`], and the miss path pays for a hash so + /// the timing says nothing either. + pub async fn redeem_signin_link(&self, presented: &str, password: &str) -> Result { + let now = OffsetDateTime::now_utc(); + let digest = auth::hash_token(presented); + self.check_rate(&format!("link:{digest}")).await?; + + let link = match self.store.signin_link_by_hash(&digest).await? { + Some(link) => link, + None => { + // Same work as the success path, minus the effect. + let _ = hash_password(password); + return Err(AccountError::Rejected); + } + }; + // Expiry is decided here, against the stored timestamp. Nothing the + // client sends is consulted. + if !link.is_usable(now) { + let _ = hash_password(password); + return Err(AccountError::Rejected); + } + let user = match self.store.user(&link.user_id).await? { + Some(user) => user, + None => { + let _ = hash_password(password); + return Err(AccountError::Rejected); + } + }; + + // The rules are checked before the link is spent, so a rejected + // password does not burn the invitation. + auth::check_password(password, &user.email, &user.display_name)?; + let hash = hash_password(password)?; + + // The atomic step. A prefetching mail client and the person clicking + // arrive together; exactly one of them consumes the link. + if !self.store.consume_signin_link(&link.id, now).await? { + return Err(AccountError::Rejected); + } + + self.store.set_password_hash(&user.id, &hash).await?; + self.store.clear_auth_attempts(&format!("link:{digest}")).await?; + let user = self.store.user(&user.id).await?.ok_or(StoreError::NotFound)?; + self.start_session(user).await + } + + // -- signing in -------------------------------------------------------- + + /// Signs a person in. `client` is whatever identifies the caller's machine + /// — it only ever becomes a rate-limit bucket. + pub async fn sign_in(&self, email: &str, password: &str, client: &str) -> Result { + let workspace = match self.store.workspace().await? { + Some(workspace) => workspace, + None => { + auth::dummy_verify(password); + return Err(AccountError::Rejected); + } + }; + let address_bucket = format!("address:{}", email.trim().to_lowercase()); + let client_bucket = format!("client:{client}"); + self.check_rate(&address_bucket).await?; + self.check_rate(&client_bucket).await?; + + let now = OffsetDateTime::now_utc(); + self.store.record_auth_attempt(&address_bucket, now).await?; + self.store.record_auth_attempt(&client_bucket, now).await?; + + let user = self.store.user_by_email(&workspace.id, email).await?; + let hash = user.as_ref().and_then(|u| u.password_hash.clone()); + // Three misses share one path: no such address, an invited account that + // has not set a password yet, and a wrong password. Each pays for one + // Argon2 verify and gets the same answer. + let ok = match hash.as_deref() { + Some(stored) => verify_password(password, stored), + None => { + auth::dummy_verify(password); + false + } + }; + if !ok { + return Err(AccountError::Rejected); + } + + let user = user.expect("a hash implies a user"); + self.store.clear_auth_attempts(&address_bucket).await?; + self.store.clear_auth_attempts(&client_bucket).await?; + self.store.mark_signed_in(&user.id, now).await?; + self.start_session(user).await + } + + /// Changes a password and signs every browser out, including the one that + /// asked — the caller gets a fresh session token back. + pub async fn change_password( + &self, + user_id: &str, + current: &str, + new: &str, + ) -> Result { + let user = self.store.user(user_id).await?.ok_or(StoreError::NotFound)?; + let ok = match user.password_hash.as_deref() { + Some(stored) => verify_password(current, stored), + None => { + auth::dummy_verify(current); + false + } + }; + if !ok { + return Err(AccountError::Rejected); + } + auth::check_password(new, &user.email, &user.display_name)?; + let hash = hash_password(new)?; + self.store.set_password_hash(&user.id, &hash).await?; + // "Signs out your other devices", as the pane promises. + self.store + .revoke_sessions_for_user(&user.id, OffsetDateTime::now_utc()) + .await?; + let user = self.store.user(&user.id).await?.ok_or(StoreError::NotFound)?; + self.start_session(user).await + } + + // -- sessions ---------------------------------------------------------- + + /// Turns a cookie value back into a person, or into nothing at all. + pub async fn authenticate(&self, presented: &str) -> Result> { + let digest = auth::hash_token(presented); + let Some(session) = self.store.session_by_hash(&digest).await? else { + return Ok(None); + }; + // The index found it; compare the digests properly before trusting it. + let Some(stored) = self.store.session_token_hash(&session.id).await? else { + return Ok(None); + }; + if !auth::digests_match(&stored, &digest) { + return Ok(None); + } + if !session.is_live(OffsetDateTime::now_utc()) { + return Ok(None); + } + Ok(self.store.user(&session.user_id).await?) + } + + /// Ends one browser's session. + pub async fn sign_out(&self, presented: &str) -> Result<()> { + let digest = auth::hash_token(presented); + if let Some(session) = self.store.session_by_hash(&digest).await? { + let _ = self + .store + .revoke_session(&session.id, OffsetDateTime::now_utc()) + .await; + } + Ok(()) + } + + async fn start_session(&self, user: User) -> Result { + let token = Token::mint(); + let session = self + .store + .create_session( + &user.id, + &token.hash(), + OffsetDateTime::now_utc() + SESSION_LIFETIME, + ) + .await?; + Ok(SignedIn { + user, + session_token: token, + session, + }) + } + + // -- guards ------------------------------------------------------------ + + fn require_admin(&self, actor: &User) -> Result<()> { + if actor.role.can_administer() { + Ok(()) + } else { + Err(AccountError::Forbidden) + } + } + + async fn check_rate(&self, bucket: &str) -> Result<()> { + let since = OffsetDateTime::now_utc() - RATE_WINDOW; + if self.store.count_auth_attempts(bucket, since).await? >= RATE_LIMIT { + return Err(AccountError::RateLimited); + } + Ok(()) + } +} diff --git a/crates/dizey-core/src/auth.rs b/crates/dizey-core/src/auth.rs new file mode 100644 index 0000000..6413e69 --- /dev/null +++ b/crates/dizey-core/src/auth.rs @@ -0,0 +1,285 @@ +//! Passwords, tokens and the rules around them. +//! +//! Two different jobs, deliberately kept apart: +//! +//! * **Passwords** are low-entropy and chosen by a person, so they go through +//! Argon2id with deliberately expensive parameters. +//! * **Tokens** — sign-in links, session cookies, read-only links, the calendar +//! feed — are 128 bits from a CSPRNG. There is nothing to brute-force, so +//! they are stored as a plain SHA-256 digest. Running Argon2 over them would +//! buy nothing and cost a page load. + +use argon2::password_hash::phc::PasswordHash; +use argon2::password_hash::{PasswordHasher, PasswordVerifier}; +use argon2::{Algorithm, Argon2, Params, Version}; +use rand::Rng; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; + +/// Argon2id at the OWASP Password Storage Cheat Sheet's recommended second +/// configuration: 19 MiB of memory, two iterations, one lane. +pub const ARGON2_MEMORY_KIB: u32 = 19 * 1024; +pub const ARGON2_ITERATIONS: u32 = 2; +pub const ARGON2_PARALLELISM: u32 = 1; + +/// How many bytes of randomness every token carries. +pub const TOKEN_BYTES: usize = 16; + +/// A password rule the person's choice broke. The wording is the wording on the +/// first-sign-in screen. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum PasswordProblem { + #[error("at least 10 characters")] + TooShort, + #[error("not your address or your name")] + LooksLikeYou, +} + +#[derive(Debug, thiserror::Error)] +pub enum AuthError { + #[error("password hashing failed: {0}")] + Hashing(String), +} + +fn argon2() -> Argon2<'static> { + let params = Params::new( + ARGON2_MEMORY_KIB, + ARGON2_ITERATIONS, + ARGON2_PARALLELISM, + None, + ) + .expect("argon2 parameters are constants and are in range"); + Argon2::new(Algorithm::Argon2id, Version::V0x13, params) +} + +/// Hashes a password into a PHC string, salt included. +pub fn hash_password(password: &str) -> Result { + argon2() + .hash_password(password.as_bytes()) + .map(|h| h.to_string()) + .map_err(|e| AuthError::Hashing(e.to_string())) +} + +/// Checks a password against a stored PHC string. +/// +/// The parameters come from the stored hash, not from [`argon2`], so raising +/// the cost later does not lock anyone out. +pub fn verify_password(password: &str, phc: &str) -> bool { + match PasswordHash::new(phc) { + Ok(parsed) => argon2().verify_password(password.as_bytes(), &parsed).is_ok(), + Err(_) => false, + } +} + +/// A PHC string for a password nobody knows, used to keep the miss path as +/// expensive as the hit path. +/// +/// Without this, "no such address" answers before Argon2 would have finished +/// and the response time tells an attacker what the wording refuses to. +pub fn dummy_password_hash() -> &'static str { + // Minted by the ignored `print_a_dummy_hash` test over 256 bits of + // randomness that was never written down. + "$argon2id$v=19$m=19456,t=2,p=1$0JjUMrLBpJG7lzg5bxZhMQ$iGpGXBNDAaHV9jqDxDcCyuIEIV33kJ1IAPt0XCh753Q" +} + +/// Burns the same work a real verify would, and always fails. +/// +/// Call this on every path where a lookup missed, before answering. +pub fn dummy_verify(password: &str) { + let _ = verify_password(password, dummy_password_hash()); +} + +/// A freshly minted secret. The plaintext exists only here and in the one +/// place that shows it; the database gets [`Token::hash`]. +#[derive(Clone)] +pub struct Token { + plaintext: String, +} + +impl Token { + /// 128 bits from the thread CSPRNG, hex encoded. + pub fn mint() -> Self { + let mut bytes = [0u8; TOKEN_BYTES]; + rand::rng().fill_bytes(&mut bytes); + Self { + plaintext: hex(&bytes), + } + } + + /// The value that goes in the link or the cookie. Shown exactly once. + pub fn expose(&self) -> &str { + &self.plaintext + } + + /// The value that goes in the database. + pub fn hash(&self) -> String { + hash_token(&self.plaintext) + } +} + +impl std::fmt::Debug for Token { + /// A token must not reach a log through a stray `{:?}`. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Token(redacted)") + } +} + +/// SHA-256 of a token, hex encoded. Tokens are full-entropy, so a fast digest +/// is the right primitive here. +pub fn hash_token(plaintext: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(plaintext.as_bytes()); + hex(&hasher.finalize()) +} + +/// Compares two token digests without leaking where they diverge. +pub fn digests_match(a: &str, b: &str) -> bool { + a.as_bytes().ct_eq(b.as_bytes()).into() +} + +fn hex(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + out.push_str(&format!("{byte:02x}")); + } + out +} + +/// The rules the first-sign-in screen states, checked server-side. +pub fn check_password(password: &str, email: &str, display_name: &str) -> Result<(), PasswordProblem> { + // Counted in characters, not bytes: a ten-character password is ten + // characters whatever alphabet it is in. + if password.chars().count() < 10 { + return Err(PasswordProblem::TooShort); + } + + let folded = password.to_lowercase(); + let local_part = email.split('@').next().unwrap_or(email); + let mut forbidden = vec![email.to_lowercase(), local_part.to_lowercase()]; + forbidden.extend( + display_name + .split_whitespace() + .map(|word| word.to_lowercase()), + ); + for needle in forbidden { + // Short words ("de", "van") would forbid too much to be useful. + if needle.chars().count() >= 3 && folded.contains(&needle) { + return Err(PasswordProblem::LooksLikeYou); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_password_round_trips_and_a_wrong_one_does_not() { + let phc = hash_password("correct horse battery").unwrap(); + assert!(phc.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"), "{phc}"); + assert!(verify_password("correct horse battery", &phc)); + assert!(!verify_password("correct horse batter", &phc)); + } + + #[test] + fn the_same_password_hashes_differently_every_time() { + let a = hash_password("correct horse battery").unwrap(); + let b = hash_password("correct horse battery").unwrap(); + assert_ne!(a, b, "salts must differ"); + } + + #[test] + fn a_malformed_stored_hash_is_a_failed_verify_not_a_panic() { + assert!(!verify_password("anything", "")); + assert!(!verify_password("anything", "not-a-phc-string")); + } + + #[test] + fn the_dummy_hash_is_usable_and_never_matches() { + // If this ever stops parsing, the miss path silently gets cheap again. + assert!(PasswordHash::new(dummy_password_hash()).is_ok()); + assert!(!verify_password("", dummy_password_hash())); + assert!(!verify_password("password", dummy_password_hash())); + dummy_verify("password"); + } + + #[test] + fn tokens_are_full_length_and_never_repeat() { + let a = Token::mint(); + let b = Token::mint(); + assert_eq!(a.expose().len(), TOKEN_BYTES * 2); + assert!(a.expose().chars().all(|c| c.is_ascii_hexdigit())); + assert_ne!(a.expose(), b.expose()); + assert_ne!(a.hash(), b.hash()); + } + + #[test] + fn a_token_hashes_to_sha256_and_hides_itself_in_debug() { + let token = Token::mint(); + assert_eq!(token.hash(), hash_token(token.expose())); + assert_eq!(token.hash().len(), 64); + assert_ne!(token.hash(), token.expose()); + assert_eq!(format!("{token:?}"), "Token(redacted)"); + } + + #[test] + fn known_answer_for_the_token_digest() { + // SHA-256("dizey"), so a refactor cannot quietly change the algorithm + // under stored hashes. + assert_eq!( + hash_token("dizey"), + "ecef066ddcba712d09eca07be6a8625343e795c97b73a7f2f03417cce1fa58d7" + ); + } + + #[test] + fn digest_comparison_is_by_value() { + let token = Token::mint(); + assert!(digests_match(&token.hash(), &hash_token(token.expose()))); + assert!(!digests_match(&token.hash(), &hash_token("something else"))); + assert!(!digests_match("short", "longer")); + } + + #[test] + fn password_rules_are_the_ones_on_the_screen() { + let email = "grace@dizey.sh"; + let name = "Grace Hopper"; + assert_eq!( + check_password("short", email, name), + Err(PasswordProblem::TooShort) + ); + assert_eq!( + check_password("grace-and-more", email, name), + Err(PasswordProblem::LooksLikeYou) + ); + assert_eq!( + check_password("HOPPERhopper", email, name), + Err(PasswordProblem::LooksLikeYou), + "case must not be an escape hatch" + ); + assert_eq!( + check_password("grace@dizey.sh!!", email, name), + Err(PasswordProblem::LooksLikeYou) + ); + assert!(check_password("tide-tables-1892", email, name).is_ok()); + // Ten characters exactly is allowed; nine is not. + assert!(check_password("abcdefghij", email, name).is_ok()); + assert_eq!( + check_password("abcdefghi", email, name), + Err(PasswordProblem::TooShort) + ); + } +} + +#[cfg(test)] +mod dummy_hash_generator { + //! Run with `cargo test -p dizey-core --lib print_a_dummy_hash -- --ignored + //! --nocapture` to mint a replacement for [`super::dummy_password_hash`]. + #[test] + #[ignore = "generator, not a check"] + fn print_a_dummy_hash() { + let token = format!("{}{}", super::Token::mint().expose(), super::Token::mint().expose()); + println!("{}", super::hash_password(&token).unwrap()); + } +} diff --git a/crates/dizey-core/src/lib.rs b/crates/dizey-core/src/lib.rs index 069602a..699f8d8 100644 --- a/crates/dizey-core/src/lib.rs +++ b/crates/dizey-core/src/lib.rs @@ -3,8 +3,11 @@ //! Everything in here is server-side only: the web crate pulls it in behind its //! `ssr` feature so none of it is compiled into the wasm bundle. +pub mod accounts; +pub mod auth; pub mod role; pub mod store; pub use role::Role; +pub use accounts::{AccountError, Accounts}; pub use store::{Store, StoreError, TursoStore}; diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index 3298d24..b081fe8 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -16,6 +16,8 @@ pub use turso_store::TursoStore; #[derive(Debug, thiserror::Error)] pub enum StoreError { + #[error("this workspace already has an owner")] + AlreadyClaimed, #[error("database: {0}")] Backend(String), #[error("not found")] @@ -120,14 +122,44 @@ impl SigninLink { } } +/// A signed-in browser. As with every other token, only the hash of the cookie +/// value is stored. +#[derive(Debug, Clone, PartialEq)] +pub struct Session { + pub id: String, + pub user_id: String, + pub created_at: OffsetDateTime, + pub expires_at: OffsetDateTime, + pub revoked_at: Option, +} + +impl Session { + pub fn is_live(&self, now: OffsetDateTime) -> bool { + self.revoked_at.is_none() && now < self.expires_at + } +} + /// The storage boundary. Dyn-safe on purpose: handlers hold `Arc`. #[async_trait] pub trait Store: Send + Sync + 'static { // -- workspace --------------------------------------------------------- - /// Creates the workspace. Fails with [`StoreError::Conflict`] if one - /// already exists: Dizey hosts a single workspace per database. - async fn create_workspace(&self, name: &str) -> Result; + /// Claims an empty database: writes the workspace, its first account and + /// the single owner row in one transaction. + /// + /// The owner row has a fixed primary key, so two requests racing to claim + /// the same empty workspace cannot both win, and the loser gets + /// [`StoreError::AlreadyClaimed`] rather than quietly joining as a member. + async fn claim_workspace( + &self, + workspace_name: &str, + email: &str, + display_name: &str, + password_hash: &str, + ) -> Result<(Workspace, User)>; + + /// The account that claimed the workspace, if it has been claimed. + async fn owner(&self) -> Result>; async fn workspace(&self) -> Result>; @@ -198,5 +230,49 @@ pub trait Store: Send + Sync + 'static { /// link apart from a wrong one — an expired link is not a dead account. async fn signin_link_by_hash(&self, token_hash: &str) -> Result>; - async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()>; + /// Marks the link used, in a transaction, conditional on it still being + /// unused, and reports whether this call is the one that consumed it. + /// + /// Mail clients prefetch links, so two redemptions of the same link is + /// ordinary traffic rather than an attack: exactly one of them must win. + async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result; + + // -- sessions ---------------------------------------------------------- + + async fn create_session( + &self, + user_id: &str, + token_hash: &str, + expires_at: OffsetDateTime, + ) -> Result; + + /// Looks a session up by the hash of the cookie value. Returns it whether + /// or not it is still live; the caller decides. + async fn session_by_hash(&self, token_hash: &str) -> Result>; + + /// The stored digest for a session, so the caller can compare it in + /// constant time rather than trusting the index lookup alone. + async fn session_token_hash(&self, id: &str) -> Result>; + + async fn revoke_session(&self, id: &str, at: OffsetDateTime) -> Result<()>; + + /// Signs out every browser this account has. This is what the change- + /// password pane promises. + async fn revoke_sessions_for_user(&self, user_id: &str, at: OffsetDateTime) -> Result; + + // -- rate limiting ----------------------------------------------------- + + /// Records one attempt against a bucket — an address, or a client address. + async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()>; + + /// How many attempts that bucket has made since `since`. + async fn count_auth_attempts(&self, bucket: &str, since: OffsetDateTime) -> Result; + + /// Forgets a bucket's attempts. Called on a success, so a person who + /// mistypes twice and then gets it right is not left near the limit. + async fn clear_auth_attempts(&self, bucket: &str) -> Result<()>; + + /// Drops attempt rows older than `before`, so the ledger does not grow + /// without bound. + async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result; } diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index 631210b..8c729ae 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -8,21 +8,27 @@ use async_trait::async_trait; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; +use turso::transaction::TransactionBehavior; use turso::{Builder, Connection, Row, Value, params}; use uuid::Uuid; use super::{ - DeletePolicy, NewUser, Result, SigninLink, Store, StoreError, User, Workspace, + DeletePolicy, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace, }; use crate::Role; /// Every migration, in order. Adding one means appending a file and a line. -const MIGRATIONS: &[(i64, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; +const MIGRATIONS: &[(i64, &str)] = &[ + (1, include_str!("../../migrations/0001_init.sql")), + (2, include_str!("../../migrations/0002_auth.sql")), +]; pub struct TursoStore { + /// Shared by every single-statement call. Turso serialises statements on a + /// connection, so this is safe; transactions are the exception and take a + /// connection of their own. conn: Connection, - // Held so the database outlives its connection. - _db: turso::Database, + db: turso::Database, } impl TursoStore { @@ -42,7 +48,7 @@ impl TursoStore { ] { conn.execute(pragma, ()).await.map_err(backend)?; } - let store = Self { conn, _db: db }; + let store = Self { conn, db }; store.migrate().await?; Ok(store) } @@ -94,6 +100,17 @@ impl TursoStore { Ok(self.applied_versions().await?.into_iter().max().unwrap_or(0)) } + /// A connection of its own, for work that opens a transaction. + /// `Connection::transaction` takes `&mut self`, and a transaction on the + /// shared connection would swallow everyone else's statements. + async fn tx_conn(&self) -> Result { + let conn = self.db.connect().map_err(backend)?; + for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] { + conn.execute(pragma, ()).await.map_err(backend)?; + } + Ok(conn) + } + async fn one_row(&self, sql: &str, args: impl turso::IntoParams) -> Result> { let mut rows = self.conn.query(sql, args).await.map_err(backend)?; rows.next().await.map_err(backend) @@ -104,6 +121,13 @@ fn backend(e: E) -> StoreError { StoreError::Backend(e.to_string()) } +/// Turso reports constraint failures as text; there is no typed error to match +/// on in 0.8.0-pre.7. +fn is_constraint_violation(e: &turso::Error) -> bool { + let text = e.to_string().to_lowercase(); + text.contains("constraint") || text.contains("unique") +} + fn now_text() -> Result { stamp(OffsetDateTime::now_utc()) } @@ -195,6 +219,18 @@ fn signin_link_from(row: &Row) -> Result { }) } +fn session_from(row: &Row) -> Result { + Ok(Session { + id: text(row, 0)?, + user_id: text(row, 1)?, + created_at: parse_stamp(&text(row, 2)?)?, + expires_at: parse_stamp(&text(row, 3)?)?, + revoked_at: opt_stamp(row, 4)?, + }) +} + +const SESSION_COLUMNS: &str = "id, user_id, created_at, expires_at, revoked_at"; + /// Addresses are matched case-insensitively; the display form is kept as typed. fn fold_email(email: &str) -> String { email.trim().to_lowercase() @@ -202,19 +238,89 @@ fn fold_email(email: &str) -> String { #[async_trait] impl Store for TursoStore { - async fn create_workspace(&self, name: &str) -> Result { - if self.workspace().await?.is_some() { - return Err(StoreError::Conflict("workspace")); - } - let id = Uuid::new_v4().to_string(); - self.conn - .execute( - "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)", - params![id.clone(), name, now_text()?], - ) + async fn claim_workspace( + &self, + workspace_name: &str, + email: &str, + display_name: &str, + password_hash: &str, + ) -> Result<(Workspace, User)> { + let workspace_id = Uuid::new_v4().to_string(); + let admin_id = Uuid::new_v4().to_string(); + let now = now_text()?; + let email = fold_email(email); + + let mut conn = self.tx_conn().await?; + // IMMEDIATE: take the write lock at BEGIN, so a second claimant waits + // out the busy timeout here instead of doing the whole insert and + // discovering the conflict at the end. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) .await .map_err(backend)?; - self.workspace().await?.ok_or(StoreError::NotFound) + + let claimed = async { + tx.execute( + "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)", + params![workspace_id.clone(), workspace_name, now.clone()], + ) + .await?; + tx.execute( + "INSERT INTO user (id, workspace_id, email, display_name, role, password_hash, \ + created_at) VALUES (?1, ?2, ?3, ?4, 'admin', ?5, ?6)", + params![ + admin_id.clone(), + workspace_id.clone(), + email, + display_name, + password_hash, + now.clone() + ], + ) + .await?; + // The claim itself. Fixed primary key, so the second writer loses. + tx.execute( + "INSERT INTO workspace_owner (singleton, user_id, claimed_at) \ + VALUES (1, ?1, ?2)", + params![admin_id.clone(), now], + ) + .await?; + Ok::<_, turso::Error>(()) + } + .await; + + match claimed { + Ok(()) => tx.commit().await.map_err(|e| { + if is_constraint_violation(&e) { + StoreError::AlreadyClaimed + } else { + backend(e) + } + })?, + Err(e) => { + let _ = tx.rollback().await; + return Err(if is_constraint_violation(&e) { + StoreError::AlreadyClaimed + } else { + backend(e) + }); + } + } + + let workspace = self.workspace().await?.ok_or(StoreError::NotFound)?; + let admin = self.user(&admin_id).await?.ok_or(StoreError::NotFound)?; + Ok((workspace, admin)) + } + + async fn owner(&self) -> Result> { + let sql = format!( + "SELECT {USER_COLUMNS} FROM user \ + WHERE id = (SELECT user_id FROM workspace_owner WHERE singleton = 1)" + ); + match self.one_row(&sql, ()).await? { + Some(row) => Ok(Some(user_from(&row)?)), + None => Ok(None), + } } async fn workspace(&self) -> Result> { @@ -467,17 +573,136 @@ impl Store for TursoStore { } } - async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()> { + async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + // Conditional update plus rows-affected, never read-then-write: the + // second redemption of a prefetched link updates nothing. + let n = tx + .execute( + "UPDATE signin_link SET used_at = ?1 WHERE id = ?2 AND used_at IS NULL", + params![stamp(at)?, id], + ) + .await + .map_err(backend)?; + tx.commit().await.map_err(backend)?; + Ok(n == 1) + } + + async fn create_session( + &self, + user_id: &str, + token_hash: &str, + expires_at: OffsetDateTime, + ) -> Result { + let id = Uuid::new_v4().to_string(); + self.conn + .execute( + "INSERT INTO session (id, user_id, token_hash, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + id.clone(), + user_id, + token_hash, + now_text()?, + stamp(expires_at)? + ], + ) + .await + .map_err(backend)?; + let sql = format!("SELECT {SESSION_COLUMNS} FROM session WHERE id = ?1"); + match self.one_row(&sql, params![id]).await? { + Some(row) => session_from(&row), + None => Err(StoreError::NotFound), + } + } + + async fn session_by_hash(&self, token_hash: &str) -> Result> { + let sql = format!("SELECT {SESSION_COLUMNS} FROM session WHERE token_hash = ?1"); + match self.one_row(&sql, params![token_hash]).await? { + Some(row) => Ok(Some(session_from(&row)?)), + None => Ok(None), + } + } + + async fn session_token_hash(&self, id: &str) -> Result> { + match self + .one_row("SELECT token_hash FROM session WHERE id = ?1", params![id]) + .await? + { + Some(row) => Ok(Some(text(&row, 0)?)), + None => Ok(None), + } + } + + async fn revoke_session(&self, id: &str, at: OffsetDateTime) -> Result<()> { let n = self .conn .execute( - "UPDATE signin_link SET used_at = ?1 WHERE id = ?2 AND used_at IS NULL", + "UPDATE session SET revoked_at = ?1 WHERE id = ?2 AND revoked_at IS NULL", params![stamp(at)?, id], ) .await .map_err(backend)?; if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } } + + async fn revoke_sessions_for_user(&self, user_id: &str, at: OffsetDateTime) -> Result { + self.conn + .execute( + "UPDATE session SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", + params![stamp(at)?, user_id], + ) + .await + .map_err(backend) + } + + async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> { + self.conn + .execute( + "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)", + params![Uuid::new_v4().to_string(), bucket, stamp(at)?], + ) + .await + .map_err(backend)?; + Ok(()) + } + + async fn count_auth_attempts(&self, bucket: &str, since: OffsetDateTime) -> Result { + // RFC 3339 in UTC sorts lexicographically, which is why the timestamps + // are stored in that shape. + match self + .one_row( + "SELECT COUNT(*) FROM auth_attempt WHERE bucket = ?1 AND attempted_at >= ?2", + params![bucket, stamp(since)?], + ) + .await? + { + Some(row) => count_of(&row), + None => Ok(0), + } + } + + async fn clear_auth_attempts(&self, bucket: &str) -> Result<()> { + self.conn + .execute("DELETE FROM auth_attempt WHERE bucket = ?1", params![bucket]) + .await + .map_err(backend)?; + Ok(()) + } + + async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result { + self.conn + .execute( + "DELETE FROM auth_attempt WHERE attempted_at < ?1", + params![stamp(before)?], + ) + .await + .map_err(backend) + } } #[cfg(test)] diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 9a1726c..83a449e 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -1,11 +1,13 @@ -//! Behaviour of the storage boundary, driven through the Turso implementation. +//! Integration tests for dizey-core: the storage boundary driven through the +//! Turso implementation, and the account flows on top of it. //! -//! New storage tests belong in this file rather than a new `tests/*.rs`: one -//! test binary links and runs once. +//! New integration tests belong in this file rather than a new `tests/*.rs`: +//! one test binary links and runs once. use std::path::PathBuf; -use dizey_core::store::{DeletePolicy, NewUser, Store, StoreError, TursoStore}; +use dizey_core::auth::{Token, hash_password}; +use dizey_core::store::{DeletePolicy, NewUser, Store, StoreError, TursoStore, User}; use dizey_core::Role; use time::{Duration, OffsetDateTime}; use uuid::Uuid; @@ -36,20 +38,47 @@ impl Drop for Scratch { async fn workspace_with_admin() -> (Scratch, String, String) { let scratch = Scratch::open().await; - let ws = scratch.store.create_workspace("Dizey").await.unwrap(); - let admin = scratch + let (ws, admin) = scratch .store - .create_user(NewUser { - workspace_id: ws.id.clone(), - email: "ada@dizey.sh".into(), - display_name: "Ada".into(), - role: Role::Admin, - }) + .claim_workspace( + "Dizey", + "ada@dizey.sh", + "Ada", + &hash_password("tide-tables-1892").unwrap(), + ) .await .unwrap(); (scratch, ws.id, admin.id) } +/// Claims a workspace on an arbitrary store, for the tests that need one +/// without the `Scratch` wrapper. +async fn claim(store: &TursoStore) -> (String, String) { + let (ws, admin) = store + .claim_workspace( + "Dizey", + "ada@dizey.sh", + "Ada", + &hash_password("tide-tables-1892").unwrap(), + ) + .await + .unwrap(); + (ws.id, admin.id) +} + +async fn member(store: &TursoStore, workspace_id: &str, email: &str, name: &str) -> String { + store + .create_user(NewUser { + workspace_id: workspace_id.to_string(), + email: email.into(), + display_name: name.into(), + role: Role::Member, + }) + .await + .unwrap() + .id +} + #[tokio::test] async fn migrations_apply_once_and_survive_reopen() { let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4())); @@ -57,32 +86,120 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("dizey.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 1); - first.create_workspace("Dizey").await.unwrap(); + assert_eq!(first.schema_version().await.unwrap(), 2); + claim(&first).await; drop(first); // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and // must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 1); + assert_eq!(second.schema_version().await.unwrap(), 2); assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); drop(second); let _ = std::fs::remove_dir_all(&dir); } #[tokio::test] -async fn a_database_holds_exactly_one_workspace() { +async fn the_first_account_owns_the_workspace() { let scratch = Scratch::open().await; assert!(scratch.store.workspace().await.unwrap().is_none()); - scratch.store.create_workspace("Dizey").await.unwrap(); - let again = scratch.store.create_workspace("Other").await; - assert!(matches!(again, Err(StoreError::Conflict("workspace")))); + assert!(scratch.store.owner().await.unwrap().is_none()); + + let (_, admin_id) = claim(&scratch.store).await; + let owner = scratch.store.owner().await.unwrap().unwrap(); + assert_eq!(owner.id, admin_id); + assert_eq!(owner.role, Role::Admin); + assert!(owner.has_signed_in(), "the admin sets their own password"); +} + +#[tokio::test] +async fn a_second_claim_loses_and_changes_nothing() { + let scratch = Scratch::open().await; + claim(&scratch.store).await; + + let second = scratch + .store + .claim_workspace( + "Someone else's", + "mallory@elsewhere.example", + "Mallory", + &hash_password("tide-tables-1892").unwrap(), + ) + .await; + assert!(matches!(second, Err(StoreError::AlreadyClaimed))); + + // The loser must not have joined as anything at all. + assert_eq!(scratch.store.workspace().await.unwrap().unwrap().name, "Dizey"); + assert_eq!(scratch.store.count_users("").await.unwrap(), 0); + let ws_id = scratch.store.workspace().await.unwrap().unwrap().id; + assert_eq!(scratch.store.count_users(&ws_id).await.unwrap(), 1); + assert!( + scratch + .store + .user_by_email(&ws_id, "mallory@elsewhere.example") + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn concurrent_claims_produce_exactly_one_admin() { + let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("dizey.db").to_string_lossy().into_owned(); + let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap()); + + let hash = hash_password("tide-tables-1892").unwrap(); + let mut claims = Vec::new(); + for i in 0..4 { + let store = store.clone(); + let hash = hash.clone(); + claims.push(tokio::spawn(async move { + store + .claim_workspace( + "Dizey", + &format!("claimant{i}@dizey.sh"), + &format!("Claimant {i}"), + &hash, + ) + .await + .map(|(_, admin)| admin.email) + })); + } + + let mut winners = Vec::new(); + for claim in claims { + match claim.await.unwrap() { + Ok(email) => winners.push(email), + Err(StoreError::AlreadyClaimed) => {} + Err(other) => panic!("unexpected claim failure: {other}"), + } + } + assert_eq!(winners.len(), 1, "exactly one claim wins: {winners:?}"); + + let ws_id = store.workspace().await.unwrap().unwrap().id; + assert_eq!(store.count_users(&ws_id).await.unwrap(), 1, "no half-written losers"); + let owner = store.owner().await.unwrap().unwrap(); + assert_eq!(owner.email, winners[0]); + + drop(store); + let _ = std::fs::remove_dir_all(&dir); } #[tokio::test] async fn workspace_defaults_match_the_settings_screen() { let scratch = Scratch::open().await; - let ws = scratch.store.create_workspace("Dizey").await.unwrap(); + let (ws, _) = scratch + .store + .claim_workspace( + "Dizey", + "ada@dizey.sh", + "Ada", + &hash_password("tide-tables-1892").unwrap(), + ) + .await + .unwrap(); assert_eq!(ws.attachment_limit_bytes, 25 * 1024 * 1024); assert_eq!(ws.photo_limit_bytes, 2 * 1024 * 1024); assert!(ws.allowed_file_types.is_empty(), "every type until narrowed"); @@ -310,7 +427,7 @@ async fn a_signin_link_stores_only_the_hash_and_is_used_once() { .is_none() ); - scratch.store.consume_signin_link(&link.id, now).await.unwrap(); + assert!(scratch.store.consume_signin_link(&link.id, now).await.unwrap()); let used = scratch .store .signin_link_by_hash("hash-of-the-token") @@ -319,10 +436,7 @@ async fn a_signin_link_stores_only_the_hash_and_is_used_once() { .unwrap(); assert!(!used.is_usable(now)); // A second use finds nothing left to consume. - assert!(matches!( - scratch.store.consume_signin_link(&link.id, now).await, - Err(StoreError::NotFound) - )); + assert!(!scratch.store.consume_signin_link(&link.id, now).await.unwrap()); } #[tokio::test] @@ -362,6 +476,638 @@ async fn an_expired_link_is_still_a_live_account() { async fn the_store_is_usable_behind_a_trait_object() { let scratch = Scratch::open().await; let store: &dyn Store = &scratch.store; - store.create_workspace("Dizey").await.unwrap(); + store + .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "$argon2id$fake") + .await + .unwrap(); assert!(store.workspace().await.unwrap().is_some()); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_prefetched_link_is_consumed_exactly_once() { + let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("dizey.db").to_string_lossy().into_owned(); + let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap()); + let (ws_id, _) = claim(&store).await; + let user_id = member(&store, &ws_id, "grace@dizey.sh", "Grace").await; + + let token = Token::mint(); + let now = OffsetDateTime::now_utc(); + let link = store + .create_signin_link(&user_id, &token.hash(), now + Duration::days(7)) + .await + .unwrap(); + + // The mail client prefetches while the person clicks. + let mut redemptions = Vec::new(); + for _ in 0..4 { + let store = store.clone(); + let id = link.id.clone(); + redemptions.push(tokio::spawn(async move { + store.consume_signin_link(&id, now).await.unwrap() + })); + } + let mut winners = 0; + for redemption in redemptions { + if redemption.await.unwrap() { + winners += 1; + } + } + assert_eq!(winners, 1, "exactly one redemption may win"); + + drop(store); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_session_lives_until_it_expires_or_is_revoked() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let user_id = member(&scratch.store, &ws_id, "grace@dizey.sh", "Grace").await; + + let token = Token::mint(); + let now = OffsetDateTime::now_utc(); + let session = scratch + .store + .create_session(&user_id, &token.hash(), now + Duration::days(14)) + .await + .unwrap(); + assert!(session.is_live(now)); + + // The cookie value is the only way in, and it is not what is stored. + let found = scratch + .store + .session_by_hash(&token.hash()) + .await + .unwrap() + .unwrap(); + assert_eq!(found.id, session.id); + assert!( + scratch + .store + .session_by_hash(token.expose()) + .await + .unwrap() + .is_none(), + "the plaintext must not be stored" + ); + assert_eq!( + scratch.store.session_token_hash(&session.id).await.unwrap(), + Some(token.hash()) + ); + + scratch.store.revoke_session(&session.id, now).await.unwrap(); + let revoked = scratch + .store + .session_by_hash(&token.hash()) + .await + .unwrap() + .unwrap(); + assert!(!revoked.is_live(now), "a revoked session is dead at once"); + // Revoking twice is not an error the caller has to think about. + assert!(matches!( + scratch.store.revoke_session(&session.id, now).await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn an_expired_session_is_not_live() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let user_id = member(&scratch.store, &ws_id, "grace@dizey.sh", "Grace").await; + let now = OffsetDateTime::now_utc(); + let session = scratch + .store + .create_session(&user_id, &Token::mint().hash(), now - Duration::minutes(1)) + .await + .unwrap(); + assert!(!session.is_live(now)); +} + +#[tokio::test] +async fn changing_a_password_can_sign_out_every_other_device() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let user_id = member(&scratch.store, &ws_id, "grace@dizey.sh", "Grace").await; + let other_id = member(&scratch.store, &ws_id, "linus@dizey.sh", "Linus").await; + let now = OffsetDateTime::now_utc(); + + let mut hashes = Vec::new(); + for _ in 0..3 { + let token = Token::mint(); + scratch + .store + .create_session(&user_id, &token.hash(), now + Duration::days(14)) + .await + .unwrap(); + hashes.push(token.hash()); + } + let bystander = Token::mint(); + scratch + .store + .create_session(&other_id, &bystander.hash(), now + Duration::days(14)) + .await + .unwrap(); + + let revoked = scratch + .store + .revoke_sessions_for_user(&user_id, now) + .await + .unwrap(); + assert_eq!(revoked, 3); + for hash in &hashes { + let session = scratch.store.session_by_hash(hash).await.unwrap().unwrap(); + assert!(!session.is_live(now)); + } + // Someone else's browser is untouched. + let bystander = scratch + .store + .session_by_hash(&bystander.hash()) + .await + .unwrap() + .unwrap(); + assert!(bystander.is_live(now)); +} + +#[tokio::test] +async fn auth_attempts_are_counted_over_a_window() { + let scratch = Scratch::open().await; + let now = OffsetDateTime::now_utc(); + let window = now - Duration::minutes(15); + + for minutes_ago in [30, 20, 10, 5, 1] { + scratch + .store + .record_auth_attempt("grace@dizey.sh", now - Duration::minutes(minutes_ago)) + .await + .unwrap(); + } + scratch + .store + .record_auth_attempt("198.51.100.7", now) + .await + .unwrap(); + + // Only the three inside the window count, and buckets do not bleed. + assert_eq!( + scratch + .store + .count_auth_attempts("grace@dizey.sh", window) + .await + .unwrap(), + 3 + ); + assert_eq!( + scratch + .store + .count_auth_attempts("198.51.100.7", window) + .await + .unwrap(), + 1 + ); + assert_eq!( + scratch + .store + .count_auth_attempts("nobody@dizey.sh", window) + .await + .unwrap(), + 0 + ); + + // A success clears the bucket that succeeded, and only that one. + scratch + .store + .clear_auth_attempts("grace@dizey.sh") + .await + .unwrap(); + assert_eq!( + scratch + .store + .count_auth_attempts("grace@dizey.sh", window) + .await + .unwrap(), + 0 + ); + assert_eq!( + scratch + .store + .count_auth_attempts("198.51.100.7", window) + .await + .unwrap(), + 1 + ); + + // Pruning drops what is out of every window. + scratch + .store + .record_auth_attempt("grace@dizey.sh", now - Duration::hours(2)) + .await + .unwrap(); + let pruned = scratch + .store + .prune_auth_attempts(now - Duration::hours(1)) + .await + .unwrap(); + assert_eq!(pruned, 1); +} + +// --------------------------------------------------------------------------- +// Account flows. +// --------------------------------------------------------------------------- + +use dizey_core::accounts::{AccountError, Accounts, RATE_LIMIT, SIGNIN_LINK_LIFETIME}; +use dizey_core::auth::PasswordProblem; +use std::sync::Arc; + +/// An accounts service over a throwaway database. The directory is kept alive +/// by the returned guard. +async fn accounts() -> (Scratch, Accounts) { + let scratch = Scratch::open().await; + let store = TursoStore::open(scratch.dir.join("dizey.db").to_str().unwrap()) + .await + .unwrap(); + let accounts = Accounts::new(Arc::new(store) as Arc); + (scratch, accounts) +} + +async fn claimed() -> (Scratch, Accounts, User) { + let (scratch, accounts) = accounts().await; + let (_, signed_in) = accounts + .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "tide-tables-1892") + .await + .unwrap(); + (scratch, accounts, signed_in.user) +} + +#[tokio::test] +async fn claiming_makes_an_admin_and_signs_them_in() { + let (_scratch, accounts) = accounts().await; + let (workspace, signed_in) = accounts + .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "tide-tables-1892") + .await + .unwrap(); + assert_eq!(workspace.name, "Dizey"); + assert_eq!(signed_in.user.role, Role::Admin); + + // The cookie value works and is not what is stored. + let who = accounts + .authenticate(signed_in.session_token.expose()) + .await + .unwrap() + .unwrap(); + assert_eq!(who.id, signed_in.user.id); + assert!( + accounts + .authenticate(&signed_in.session.id) + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn the_claim_screen_enforces_its_own_password_rules() { + let (_scratch, accounts) = accounts().await; + let too_short = accounts + .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "short") + .await; + assert!(matches!( + too_short, + Err(AccountError::Password(PasswordProblem::TooShort)) + )); + // A rejected password must not have claimed anything. + assert!(accounts.store().workspace().await.unwrap().is_none()); +} + +#[tokio::test] +async fn a_second_claim_is_refused() { + let (_scratch, accounts, _admin) = claimed().await; + let second = accounts + .claim_workspace("Theirs", "mallory@elsewhere.example", "Mallory", "tide-tables-1892") + .await; + assert!(matches!(second, Err(AccountError::AlreadyClaimed))); +} + +#[tokio::test] +async fn an_invited_member_chooses_their_own_password() { + let (_scratch, accounts, admin) = claimed().await; + let invitation = accounts + .invite(&admin, "grace@dizey.sh", "Grace", Role::Member) + .await + .unwrap(); + assert!(!invitation.user.has_signed_in(), "no password yet"); + assert!(invitation.expires_at > OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME - Duration::minutes(1)); + + // The admin cannot sign in as them in the meantime. + let as_them = accounts + .sign_in("grace@dizey.sh", "tide-tables-1892", "198.51.100.7") + .await; + assert!(matches!(as_them, Err(AccountError::Rejected))); + + let signed_in = accounts + .redeem_signin_link(invitation.token.expose(), "sextant-and-chart") + .await + .unwrap(); + assert_eq!(signed_in.user.id, invitation.user.id); + assert!(signed_in.user.has_signed_in()); + + // And now the password they chose works, and only that one. + accounts + .sign_in("grace@dizey.sh", "sextant-and-chart", "198.51.100.7") + .await + .unwrap(); +} + +#[tokio::test] +async fn only_an_admin_may_invite() { + let (_scratch, accounts, admin) = claimed().await; + let invitation = accounts + .invite(&admin, "grace@dizey.sh", "Grace", Role::Member) + .await + .unwrap(); + let member = accounts + .redeem_signin_link(invitation.token.expose(), "sextant-and-chart") + .await + .unwrap() + .user; + + // Server-side, not merely hidden: a member calling the flow is refused. + let attempt = accounts + .invite(&member, "linus@dizey.sh", "Linus", Role::Member) + .await; + assert!(matches!(attempt, Err(AccountError::Forbidden))); + + let mut viewer = member.clone(); + viewer.role = Role::Viewer; + assert!(matches!( + accounts.invite(&viewer, "linus@dizey.sh", "Linus", Role::Viewer).await, + Err(AccountError::Forbidden) + )); +} + +#[tokio::test] +async fn a_link_works_once_and_a_wrong_one_never_does() { + let (_scratch, accounts, admin) = claimed().await; + let invitation = accounts + .invite(&admin, "grace@dizey.sh", "Grace", Role::Member) + .await + .unwrap(); + + accounts + .redeem_signin_link(invitation.token.expose(), "sextant-and-chart") + .await + .unwrap(); + let again = accounts + .redeem_signin_link(invitation.token.expose(), "another-password") + .await; + assert!(matches!(again, Err(AccountError::Rejected))); + + let invented = accounts + .redeem_signin_link(&"0".repeat(32), "another-password") + .await; + assert!(matches!(invented, Err(AccountError::Rejected))); + + // The password they actually set is untouched by either failure. + accounts + .sign_in("grace@dizey.sh", "sextant-and-chart", "198.51.100.7") + .await + .unwrap(); +} + +#[tokio::test] +async fn a_rejected_password_does_not_burn_the_invitation() { + let (_scratch, accounts, admin) = claimed().await; + let invitation = accounts + .invite(&admin, "grace@dizey.sh", "Grace", Role::Member) + .await + .unwrap(); + + assert!(matches!( + accounts.redeem_signin_link(invitation.token.expose(), "grace!!").await, + Err(AccountError::Password(PasswordProblem::TooShort)) + )); + assert!(matches!( + accounts.redeem_signin_link(invitation.token.expose(), "grace-hopper-1906").await, + Err(AccountError::Password(PasswordProblem::LooksLikeYou)) + )); + // Still redeemable with a password that passes. + accounts + .redeem_signin_link(invitation.token.expose(), "sextant-and-chart") + .await + .unwrap(); +} + +#[tokio::test] +async fn an_expired_link_is_refused_and_resending_opens_the_same_account() { + let (_scratch, accounts, admin) = claimed().await; + let invitation = accounts + .invite(&admin, "grace@dizey.sh", "Grace", Role::Member) + .await + .unwrap(); + + // Age the link past its expiry by writing a fresh one with a past date. + let stale = Token::mint(); + accounts + .store() + .create_signin_link( + &invitation.user.id, + &stale.hash(), + OffsetDateTime::now_utc() - Duration::minutes(1), + ) + .await + .unwrap(); + assert!(matches!( + accounts.redeem_signin_link(stale.expose(), "sextant-and-chart").await, + Err(AccountError::Rejected) + )); + + let resent = accounts + .resend_invitation(&admin, &invitation.user.id) + .await + .unwrap(); + assert_eq!(resent.user.id, invitation.user.id, "same account, new link"); + let signed_in = accounts + .redeem_signin_link(resent.token.expose(), "sextant-and-chart") + .await + .unwrap(); + assert_eq!(signed_in.user.id, invitation.user.id); +} + +#[tokio::test] +async fn an_unknown_address_and_a_wrong_password_are_indistinguishable() { + let (_scratch, accounts, _admin) = claimed().await; + let unknown = accounts + .sign_in("nobody@dizey.sh", "tide-tables-1892", "198.51.100.7") + .await; + let wrong = accounts + .sign_in("ada@dizey.sh", "not-her-password", "198.51.100.8") + .await; + assert!(matches!(unknown, Err(AccountError::Rejected))); + assert!(matches!(wrong, Err(AccountError::Rejected))); + assert_eq!( + unknown.unwrap_err().to_string(), + wrong.unwrap_err().to_string(), + "the wording must not distinguish them either" + ); +} + +#[tokio::test] +async fn the_miss_path_costs_what_the_hit_path_costs() { + let (_scratch, accounts, _admin) = claimed().await; + // Not a timing assertion — those are flaky. This asserts the work happens: + // a miss takes at least as long as one Argon2 verify at our parameters, + // which a skipped verify could not. + let baseline = std::time::Instant::now(); + let _ = accounts + .sign_in("ada@dizey.sh", "not-her-password", "198.51.100.7") + .await; + let hit_cost = baseline.elapsed(); + + let started = std::time::Instant::now(); + let _ = accounts + .sign_in("nobody@dizey.sh", "not-a-password", "198.51.100.8") + .await; + let miss_cost = started.elapsed(); + + assert!( + miss_cost * 4 > hit_cost, + "miss {miss_cost:?} is suspiciously cheaper than hit {hit_cost:?}" + ); +} + +#[tokio::test] +async fn an_invited_account_that_has_no_password_cannot_be_signed_into() { + let (_scratch, accounts, admin) = claimed().await; + accounts + .invite(&admin, "grace@dizey.sh", "Grace", Role::Member) + .await + .unwrap(); + // Not "set your password first" — that would confirm the address exists. + assert!(matches!( + accounts.sign_in("grace@dizey.sh", "", "198.51.100.7").await, + Err(AccountError::Rejected) + )); +} + +#[tokio::test] +async fn sign_in_attempts_are_rate_limited_per_address() { + let (_scratch, accounts, _admin) = claimed().await; + for _ in 0..RATE_LIMIT { + let _ = accounts + .sign_in("ada@dizey.sh", "wrong", "198.51.100.7") + .await; + } + // The next attempt is refused before any Argon2 work happens. + assert!(matches!( + accounts.sign_in("ada@dizey.sh", "wrong", "203.0.113.9").await, + Err(AccountError::RateLimited) + )); + // A different address from a fresh client is unaffected. + assert!(matches!( + accounts.sign_in("someone@dizey.sh", "wrong", "203.0.113.9").await, + Err(AccountError::Rejected) + )); +} + +#[tokio::test] +async fn a_successful_sign_in_clears_the_bucket() { + let (_scratch, accounts, _admin) = claimed().await; + for _ in 0..(RATE_LIMIT - 1) { + let _ = accounts + .sign_in("ada@dizey.sh", "wrong", "198.51.100.7") + .await; + } + accounts + .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7") + .await + .unwrap(); + // Someone who mistypes and then gets it right is not left at the edge. + assert!(matches!( + accounts.sign_in("ada@dizey.sh", "wrong", "198.51.100.7").await, + Err(AccountError::Rejected) + )); +} + +#[tokio::test] +async fn changing_a_password_signs_out_every_device() { + let (_scratch, accounts, admin) = claimed().await; + let first = accounts + .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7") + .await + .unwrap(); + let second = accounts + .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.8") + .await + .unwrap(); + assert!(accounts.authenticate(first.session_token.expose()).await.unwrap().is_some()); + + let fresh = accounts + .change_password(&admin.id, "tide-tables-1892", "chronometer-1761") + .await + .unwrap(); + + for old in [&first, &second] { + assert!( + accounts.authenticate(old.session_token.expose()).await.unwrap().is_none(), + "the pane promises this" + ); + } + assert!(accounts.authenticate(fresh.session_token.expose()).await.unwrap().is_some()); + accounts + .sign_in("ada@dizey.sh", "chronometer-1761", "198.51.100.7") + .await + .unwrap(); +} + +#[tokio::test] +async fn changing_a_password_needs_the_current_one_and_obeys_the_rules() { + let (_scratch, accounts, admin) = claimed().await; + assert!(matches!( + accounts.change_password(&admin.id, "not-it", "chronometer-1761").await, + Err(AccountError::Rejected) + )); + assert!(matches!( + accounts.change_password(&admin.id, "tide-tables-1892", "short").await, + Err(AccountError::Password(PasswordProblem::TooShort)) + )); + // The old password still works after both refusals. + accounts + .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7") + .await + .unwrap(); +} + +#[tokio::test] +async fn signing_out_ends_that_browser_only() { + let (_scratch, accounts, _admin) = claimed().await; + let laptop = accounts + .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7") + .await + .unwrap(); + let phone = accounts + .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.8") + .await + .unwrap(); + + accounts.sign_out(laptop.session_token.expose()).await.unwrap(); + assert!(accounts.authenticate(laptop.session_token.expose()).await.unwrap().is_none()); + assert!(accounts.authenticate(phone.session_token.expose()).await.unwrap().is_some()); + // Signing out an unknown token is not an error. + accounts.sign_out(&"0".repeat(32)).await.unwrap(); +} + +#[tokio::test] +async fn an_address_can_only_be_invited_once() { + let (_scratch, accounts, admin) = claimed().await; + accounts + .invite(&admin, "grace@dizey.sh", "Grace", Role::Member) + .await + .unwrap(); + assert!(matches!( + accounts.invite(&admin, "GRACE@dizey.sh", "Grace again", Role::Member).await, + Err(AccountError::AddressTaken) + )); + assert!(matches!( + accounts.invite(&admin, "ada@dizey.sh", "Ada again", Role::Member).await, + Err(AccountError::AddressTaken) + )); +}