forge
Explore
Log in

Don't you dare go Hollow

Passwords, tokens, sessions and the account flows

Browse files at this commit

defe2eb63d8b3ff47a3c24a9451cb699df1d7c86Ahmet Kaan GümüşParent: 9cf2cb5
  • feat
    • passwords, tokens, sessions and the account flows
Show full message
✨ feat(auth): passwords, tokens, sessions and the account flows

Two primitives, kept apart on purpose. Passwords are low-entropy and go
through Argon2id at the OWASP cheat sheet's recommended second config —
19 MiB, t=2, p=1 — which is also what the crate defaults to, set here
explicitly so a crate change cannot move it quietly. Tokens (sign-in
links, session cookies, and later read-only links and the calendar feed)
are 128 bits from a CSPRNG stored as a SHA-256 digest: full entropy has
nothing to brute-force, so Argon2 there would only cost a page load.
`Token` shows its plaintext once and renders as `Token(redacted)`, so a
stray `{:?}` cannot log a live secret.

Migration 0002 adds `workspace_owner`, `session` and `auth_attempt`.

The first account is claimed, not created: `claim_workspace` writes the
workspace, the admin and a `workspace_owner` row with a fixed primary key
in one IMMEDIATE transaction, so four racing claimants produce exactly
one admin, no half-written losers, and a clean AlreadyClaimed for the
rest. Redeeming a sign-in link is a conditional UPDATE plus rows-affected
inside a transaction, never a read-then-write, so a mail client's
prefetch and the person's click yield exactly one consumption.

The public surface answers uniformly in wording and in work: an unknown
address, an invited account with no password yet, and a wrong password
all pay for one Argon2 verify — against a real dummy hash on the miss
paths — and return the same rejection. Expiry is decided server-side
against stored timestamps. Sign-in attempts and link redemptions are rate
limited per address and per client over a 15-minute window, checked
before any hashing, and cleared on success. Changing a password revokes
every session for that account, which is the change-password pane's
promise made testable.
Cargo.lockmodified+131 -8
@@ -14,7 +14,7 @@ version = "0.5.2"
1414 source = "registry+https://github.com/rust-lang/crates.io-index"
1515 checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
1616 dependencies = [
17- "crypto-common",
17+ "crypto-common 0.1.7",
1818 "generic-array",
1919 ]
2020
@@ -126,6 +126,18 @@ dependencies = [
126126 "rustversion",
127127 ]
128128
129+[[package]]
130+name = "argon2"
131+version = "0.6.0-rc.8"
132+source = "registry+https://github.com/rust-lang/crates.io-index"
133+checksum = "7af50940b73bf4e16c15c448a2b121c63f2d68e3e54b6a8731673cb4aa0cdff5"
134+dependencies = [
135+ "base64ct",
136+ "blake2",
137+ "cpufeatures 0.3.0",
138+ "password-hash",
139+]
140+
129141 [[package]]
130142 name = "aristo"
131143 version = "0.4.1"
@@ -302,6 +314,12 @@ version = "0.22.1"
302314 source = "registry+https://github.com/rust-lang/crates.io-index"
303315 checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
304316
317+[[package]]
318+name = "base64ct"
319+version = "1.8.3"
320+source = "registry+https://github.com/rust-lang/crates.io-index"
321+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
322+
305323 [[package]]
306324 name = "bigdecimal"
307325 version = "0.4.10"
@@ -365,6 +383,15 @@ dependencies = [
365383 "wyz",
366384 ]
367385
386+[[package]]
387+name = "blake2"
388+version = "0.11.0-rc.6"
389+source = "registry+https://github.com/rust-lang/crates.io-index"
390+checksum = "061f1a09225e328e1ffbb378d2d49923c0ca5fee19fb5ac1cc9c1e9d52b93690"
391+dependencies = [
392+ "digest 0.11.3",
393+]
394+
368395 [[package]]
369396 name = "block-buffer"
370397 version = "0.10.4"
@@ -374,6 +401,15 @@ dependencies = [
374401 "generic-array",
375402 ]
376403
404+[[package]]
405+name = "block-buffer"
406+version = "0.12.1"
407+source = "registry+https://github.com/rust-lang/crates.io-index"
408+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
409+dependencies = [
410+ "hybrid-array",
411+]
412+
377413 [[package]]
378414 name = "bon"
379415 version = "3.10.0"
@@ -525,7 +561,7 @@ version = "0.4.4"
525561 source = "registry+https://github.com/rust-lang/crates.io-index"
526562 checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
527563 dependencies = [
528- "crypto-common",
564+ "crypto-common 0.1.7",
529565 "inout",
530566 ]
531567
@@ -540,6 +576,12 @@ dependencies = [
540576 "libloading",
541577 ]
542578
579+[[package]]
580+name = "cmov"
581+version = "0.5.4"
582+source = "registry+https://github.com/rust-lang/crates.io-index"
583+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
584+
543585 [[package]]
544586 name = "codee"
545587 version = "0.3.5"
@@ -606,6 +648,12 @@ dependencies = [
606648 "wasm-bindgen",
607649 ]
608650
651+[[package]]
652+name = "const-oid"
653+version = "0.10.2"
654+source = "registry+https://github.com/rust-lang/crates.io-index"
655+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
656+
609657 [[package]]
610658 name = "const-str"
611659 version = "1.1.0"
@@ -759,6 +807,15 @@ dependencies = [
759807 "typenum",
760808 ]
761809
810+[[package]]
811+name = "crypto-common"
812+version = "0.2.2"
813+source = "registry+https://github.com/rust-lang/crates.io-index"
814+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
815+dependencies = [
816+ "hybrid-array",
817+]
818+
762819 [[package]]
763820 name = "ctr"
764821 version = "0.9.2"
@@ -768,6 +825,15 @@ dependencies = [
768825 "cipher",
769826 ]
770827
828+[[package]]
829+name = "ctutils"
830+version = "0.4.2"
831+source = "registry+https://github.com/rust-lang/crates.io-index"
832+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
833+dependencies = [
834+ "cmov",
835+]
836+
771837 [[package]]
772838 name = "darling"
773839 version = "0.24.1"
@@ -840,8 +906,20 @@ version = "0.10.7"
840906 source = "registry+https://github.com/rust-lang/crates.io-index"
841907 checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
842908 dependencies = [
843- "block-buffer",
844- "crypto-common",
909+ "block-buffer 0.10.4",
910+ "crypto-common 0.1.7",
911+]
912+
913+[[package]]
914+name = "digest"
915+version = "0.11.3"
916+source = "registry+https://github.com/rust-lang/crates.io-index"
917+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
918+dependencies = [
919+ "block-buffer 0.12.1",
920+ "const-oid",
921+ "crypto-common 0.2.2",
922+ "ctutils",
845923 ]
846924
847925 [[package]]
@@ -859,9 +937,13 @@ dependencies = [
859937 name = "dizey-core"
860938 version = "0.1.0"
861939 dependencies = [
940+ "argon2",
862941 "async-trait",
942+ "rand 0.10.2",
863943 "serde",
864944 "serde_json",
945+ "sha2 0.11.0",
946+ "subtle",
865947 "thiserror",
866948 "time",
867949 "tokio",
@@ -1413,6 +1495,15 @@ version = "1.0.3"
14131495 source = "registry+https://github.com/rust-lang/crates.io-index"
14141496 checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
14151497
1498+[[package]]
1499+name = "hybrid-array"
1500+version = "0.4.14"
1501+source = "registry+https://github.com/rust-lang/crates.io-index"
1502+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
1503+dependencies = [
1504+ "typenum",
1505+]
1506+
14161507 [[package]]
14171508 name = "hydration_context"
14181509 version = "0.4.0-beta"
@@ -2466,6 +2557,16 @@ dependencies = [
24662557 "windows-link",
24672558 ]
24682559
2560+[[package]]
2561+name = "password-hash"
2562+version = "0.6.1"
2563+source = "registry+https://github.com/rust-lang/crates.io-index"
2564+checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"
2565+dependencies = [
2566+ "getrandom 0.4.3",
2567+ "phc",
2568+]
2569+
24692570 [[package]]
24702571 name = "paste"
24712572 version = "1.0.15"
@@ -2490,6 +2591,17 @@ version = "2.3.2"
24902591 source = "registry+https://github.com/rust-lang/crates.io-index"
24912592 checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
24922593
2594+[[package]]
2595+name = "phc"
2596+version = "0.6.1"
2597+source = "registry+https://github.com/rust-lang/crates.io-index"
2598+checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"
2599+dependencies = [
2600+ "base64ct",
2601+ "ctutils",
2602+ "getrandom 0.4.3",
2603+]
2604+
24932605 [[package]]
24942606 name = "pin-project"
24952607 version = "1.1.13"
@@ -3228,7 +3340,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
32283340 dependencies = [
32293341 "cfg-if",
32303342 "cpufeatures 0.2.17",
3231- "digest",
3343+ "digest 0.10.7",
32323344 ]
32333345
32343346 [[package]]
@@ -3245,7 +3357,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
32453357 dependencies = [
32463358 "cfg-if",
32473359 "cpufeatures 0.2.17",
3248- "digest",
3360+ "digest 0.10.7",
3361+]
3362+
3363+[[package]]
3364+name = "sha2"
3365+version = "0.11.0"
3366+source = "registry+https://github.com/rust-lang/crates.io-index"
3367+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
3368+dependencies = [
3369+ "cfg-if",
3370+ "cpufeatures 0.3.0",
3371+ "digest 0.11.3",
32493372 ]
32503373
32513374 [[package]]
@@ -4313,7 +4436,7 @@ version = "0.5.1"
43134436 source = "registry+https://github.com/rust-lang/crates.io-index"
43144437 checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
43154438 dependencies = [
4316- "crypto-common",
4439+ "crypto-common 0.1.7",
43174440 "subtle",
43184441 ]
43194442
@@ -4483,7 +4606,7 @@ checksum = "3e653af7ee4a9ef0fce481a9ec6f43cb78de20d0cdb4f4f5862e1dc6e407e6c8"
44834606 dependencies = [
44844607 "base16",
44854608 "quote",
4486- "sha2",
4609+ "sha2 0.10.9",
44874610 "syn 2.0.119",
44884611 ]
44894612
Cargo.tomlmodified+4 -0
@@ -17,6 +17,10 @@ uuid = { version = "1.25.0", features = ["v4", "serde"] }
1717 time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] }
1818 tokio = { version = "1.53.1", features = ["full"] }
1919 turso = "=0.8.0-pre.7"
20+argon2 = "0.6.0-rc.8"
21+rand = "0.10.2"
22+sha2 = "0.11.0"
23+subtle = "2.6.1"
2024
2125 [profile.release]
2226 codegen-units = 1
crates/dizey-core/Cargo.tomlmodified+4 -0
@@ -7,7 +7,11 @@ repository.workspace = true
77 description = "Domain model and storage for Dizey"
88
99 [dependencies]
10+argon2.workspace = true
1011 async-trait = "0.1.92"
12+rand.workspace = true
13+sha2.workspace = true
14+subtle.workspace = true
1115 serde.workspace = true
1216 serde_json.workspace = true
1317 thiserror.workspace = true
crates/dizey-core/migrations/0002_auth.sqladded+33 -0
@@ -0,0 +1,33 @@
1+-- Sessions, the single-owner claim, and the rate-limit ledger.
2+
3+-- Exactly one row, ever. The primary key is the whole point: two requests
4+-- racing to claim an empty workspace both try to insert singleton = 1 and the
5+-- database picks the winner, inside the same transaction that writes the
6+-- workspace and its admin.
7+CREATE TABLE workspace_owner (
8+ singleton INTEGER PRIMARY KEY,
9+ user_id TEXT NOT NULL REFERENCES user(id),
10+ claimed_at TEXT NOT NULL
11+);
12+
13+-- A signed-in browser. Only the hash of the cookie token is stored, exactly
14+-- like sign-in links and read-only links.
15+CREATE TABLE session (
16+ id TEXT PRIMARY KEY,
17+ user_id TEXT NOT NULL REFERENCES user(id),
18+ token_hash TEXT NOT NULL,
19+ created_at TEXT NOT NULL,
20+ expires_at TEXT NOT NULL,
21+ revoked_at TEXT
22+);
23+CREATE UNIQUE INDEX session_token ON session(token_hash);
24+CREATE INDEX session_by_user ON session(user_id);
25+
26+-- Sign-in attempts and link redemptions, one row per attempt, counted over a
27+-- window. The bucket is the address or the client address, never the password.
28+CREATE TABLE auth_attempt (
29+ id TEXT PRIMARY KEY,
30+ bucket TEXT NOT NULL,
31+ attempted_at TEXT NOT NULL
32+);
33+CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at);
crates/dizey-core/src/accounts.rsadded+379 -0
@@ -0,0 +1,379 @@
1+//! The account flows: claiming the workspace, inviting people, first sign-in,
2+//! signing in, changing a password, and turning a cookie back into a person.
3+//!
4+//! Two rules run through all of it.
5+//!
6+//! * **The public surface answers the same way whether or not an address has an
7+//! account.** That means the same wording *and* the same work: every path
8+//! that misses still pays for an Argon2 verify, or the response time becomes
9+//! the oracle the wording refuses to be. The honest, specific strings in the
10+//! mockups are admin-side copy and stay admin-side.
11+//! * **Capability checks live here, not in the UI.** A Viewer or a Member
12+//! calling an admin-only flow is rejected by this module.
13+
14+use std::sync::Arc;
15+
16+use time::{Duration, OffsetDateTime};
17+
18+use crate::auth::{
19+ self, AuthError, PasswordProblem, Token, hash_password, verify_password,
20+};
21+use crate::store::{NewUser, Session, Store, StoreError, User, Workspace};
22+use crate::Role;
23+
24+/// How long a first-sign-in link is good for. The mockups say seven days, and
25+/// an expired link is not a dead account: resending opens the same one.
26+pub const SIGNIN_LINK_LIFETIME: Duration = Duration::days(7);
27+
28+/// How long a signed-in browser stays signed in.
29+pub const SESSION_LIFETIME: Duration = Duration::days(14);
30+
31+/// The rate-limit window and its allowance. Deliberately modest: this exists so
32+/// an open form is not an unbounded Argon2 faucet, not to be clever.
33+pub const RATE_WINDOW: Duration = Duration::minutes(15);
34+pub const RATE_LIMIT: u64 = 10;
35+
36+/// What went wrong, in the vocabulary the caller is allowed to have.
37+#[derive(Debug, thiserror::Error)]
38+pub enum AccountError {
39+ /// The credentials did not work. Deliberately says nothing about which
40+ /// half, or whether the address exists at all.
41+ #[error("that did not work")]
42+ Rejected,
43+ /// Too many attempts from this address or this client, recently.
44+ #[error("too many attempts — wait a few minutes and try again")]
45+ RateLimited,
46+ /// A password the person chose broke a stated rule. Only ever returned on
47+ /// screens where we already know who they are.
48+ #[error("{0}")]
49+ Password(#[from] PasswordProblem),
50+ /// The caller's role does not permit this.
51+ #[error("not permitted")]
52+ Forbidden,
53+ /// This workspace already has an owner.
54+ #[error("this workspace already has an owner")]
55+ AlreadyClaimed,
56+ /// That address already has an account here. Admin-side wording: it is
57+ /// shown on the member list, never on a public form.
58+ #[error("that address already has an account")]
59+ AddressTaken,
60+ #[error("{0}")]
61+ Store(#[from] StoreError),
62+ #[error("{0}")]
63+ Auth(#[from] AuthError),
64+}
65+
66+pub type Result<T> = std::result::Result<T, AccountError>;
67+
68+/// A person plus the browser they are using.
69+#[derive(Debug)]
70+pub struct SignedIn {
71+ pub user: User,
72+ /// The cookie value. Exists exactly once, here.
73+ pub session_token: Token,
74+ pub session: Session,
75+}
76+
77+/// An invitation the admin can hand over. The link is shown once; after that
78+/// only its hash exists.
79+#[derive(Debug)]
80+pub struct Invitation {
81+ pub user: User,
82+ pub token: Token,
83+ pub expires_at: OffsetDateTime,
84+}
85+
86+#[derive(Clone)]
87+pub struct Accounts {
88+ store: Arc<dyn Store>,
89+}
90+
91+impl Accounts {
92+ pub fn new(store: Arc<dyn Store>) -> Self {
93+ Self { store }
94+ }
95+
96+ pub fn store(&self) -> &Arc<dyn Store> {
97+ &self.store
98+ }
99+
100+ // -- claiming ----------------------------------------------------------
101+
102+ /// The very first account. It becomes the admin and owns the workspace.
103+ ///
104+ /// The claim is atomic in the store, so two people racing an empty install
105+ /// cannot both end up admin and the loser does not quietly become a member.
106+ pub async fn claim_workspace(
107+ &self,
108+ workspace_name: &str,
109+ email: &str,
110+ display_name: &str,
111+ password: &str,
112+ ) -> Result<(Workspace, SignedIn)> {
113+ auth::check_password(password, email, display_name)?;
114+ let hash = hash_password(password)?;
115+ let (workspace, admin) = match self
116+ .store
117+ .claim_workspace(workspace_name, email, display_name, &hash)
118+ .await
119+ {
120+ Ok(pair) => pair,
121+ Err(StoreError::AlreadyClaimed) => return Err(AccountError::AlreadyClaimed),
122+ Err(e) => return Err(e.into()),
123+ };
124+ let signed_in = self.start_session(admin).await?;
125+ Ok((workspace, signed_in))
126+ }
127+
128+ // -- inviting ----------------------------------------------------------
129+
130+ /// Creates an account with a name and an address and no password, and mints
131+ /// the link that lets that person choose one.
132+ ///
133+ /// The admin never learns the password: only the hash of this link is
134+ /// stored, and the password is set by the person on the other end.
135+ pub async fn invite(
136+ &self,
137+ actor: &User,
138+ email: &str,
139+ display_name: &str,
140+ role: Role,
141+ ) -> Result<Invitation> {
142+ self.require_admin(actor)?;
143+ let user = self
144+ .store
145+ .create_user(NewUser {
146+ workspace_id: actor.workspace_id.clone(),
147+ email: email.to_string(),
148+ display_name: display_name.to_string(),
149+ role,
150+ })
151+ .await
152+ .map_err(|e| match e {
153+ StoreError::Conflict("account") => AccountError::AddressTaken,
154+ other => other.into(),
155+ })?;
156+ self.mint_link(actor, &user).await
157+ }
158+
159+ /// Sends the same person a fresh link. An expired link is not a dead
160+ /// account: this opens the same one.
161+ pub async fn resend_invitation(&self, actor: &User, user_id: &str) -> Result<Invitation> {
162+ self.require_admin(actor)?;
163+ let user = self
164+ .store
165+ .user(user_id)
166+ .await?
167+ .ok_or(StoreError::NotFound)?;
168+ if user.workspace_id != actor.workspace_id {
169+ return Err(AccountError::Forbidden);
170+ }
171+ self.mint_link(actor, &user).await
172+ }
173+
174+ async fn mint_link(&self, _actor: &User, user: &User) -> Result<Invitation> {
175+ let token = Token::mint();
176+ let expires_at = OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME;
177+ self.store
178+ .create_signin_link(&user.id, &token.hash(), expires_at)
179+ .await?;
180+ Ok(Invitation {
181+ user: user.clone(),
182+ token,
183+ expires_at,
184+ })
185+ }
186+
187+ // -- first sign-in -----------------------------------------------------
188+
189+ /// Redeems a first-sign-in link and sets the password the person chose.
190+ ///
191+ /// Every failure — unknown link, expired link, already-used link — is the
192+ /// same [`AccountError::Rejected`], and the miss path pays for a hash so
193+ /// the timing says nothing either.
194+ pub async fn redeem_signin_link(&self, presented: &str, password: &str) -> Result<SignedIn> {
195+ let now = OffsetDateTime::now_utc();
196+ let digest = auth::hash_token(presented);
197+ self.check_rate(&format!("link:{digest}")).await?;
198+
199+ let link = match self.store.signin_link_by_hash(&digest).await? {
200+ Some(link) => link,
201+ None => {
202+ // Same work as the success path, minus the effect.
203+ let _ = hash_password(password);
204+ return Err(AccountError::Rejected);
205+ }
206+ };
207+ // Expiry is decided here, against the stored timestamp. Nothing the
208+ // client sends is consulted.
209+ if !link.is_usable(now) {
210+ let _ = hash_password(password);
211+ return Err(AccountError::Rejected);
212+ }
213+ let user = match self.store.user(&link.user_id).await? {
214+ Some(user) => user,
215+ None => {
216+ let _ = hash_password(password);
217+ return Err(AccountError::Rejected);
218+ }
219+ };
220+
221+ // The rules are checked before the link is spent, so a rejected
222+ // password does not burn the invitation.
223+ auth::check_password(password, &user.email, &user.display_name)?;
224+ let hash = hash_password(password)?;
225+
226+ // The atomic step. A prefetching mail client and the person clicking
227+ // arrive together; exactly one of them consumes the link.
228+ if !self.store.consume_signin_link(&link.id, now).await? {
229+ return Err(AccountError::Rejected);
230+ }
231+
232+ self.store.set_password_hash(&user.id, &hash).await?;
233+ self.store.clear_auth_attempts(&format!("link:{digest}")).await?;
234+ let user = self.store.user(&user.id).await?.ok_or(StoreError::NotFound)?;
235+ self.start_session(user).await
236+ }
237+
238+ // -- signing in --------------------------------------------------------
239+
240+ /// Signs a person in. `client` is whatever identifies the caller's machine
241+ /// — it only ever becomes a rate-limit bucket.
242+ pub async fn sign_in(&self, email: &str, password: &str, client: &str) -> Result<SignedIn> {
243+ let workspace = match self.store.workspace().await? {
244+ Some(workspace) => workspace,
245+ None => {
246+ auth::dummy_verify(password);
247+ return Err(AccountError::Rejected);
248+ }
249+ };
250+ let address_bucket = format!("address:{}", email.trim().to_lowercase());
251+ let client_bucket = format!("client:{client}");
252+ self.check_rate(&address_bucket).await?;
253+ self.check_rate(&client_bucket).await?;
254+
255+ let now = OffsetDateTime::now_utc();
256+ self.store.record_auth_attempt(&address_bucket, now).await?;
257+ self.store.record_auth_attempt(&client_bucket, now).await?;
258+
259+ let user = self.store.user_by_email(&workspace.id, email).await?;
260+ let hash = user.as_ref().and_then(|u| u.password_hash.clone());
261+ // Three misses share one path: no such address, an invited account that
262+ // has not set a password yet, and a wrong password. Each pays for one
263+ // Argon2 verify and gets the same answer.
264+ let ok = match hash.as_deref() {
265+ Some(stored) => verify_password(password, stored),
266+ None => {
267+ auth::dummy_verify(password);
268+ false
269+ }
270+ };
271+ if !ok {
272+ return Err(AccountError::Rejected);
273+ }
274+
275+ let user = user.expect("a hash implies a user");
276+ self.store.clear_auth_attempts(&address_bucket).await?;
277+ self.store.clear_auth_attempts(&client_bucket).await?;
278+ self.store.mark_signed_in(&user.id, now).await?;
279+ self.start_session(user).await
280+ }
281+
282+ /// Changes a password and signs every browser out, including the one that
283+ /// asked — the caller gets a fresh session token back.
284+ pub async fn change_password(
285+ &self,
286+ user_id: &str,
287+ current: &str,
288+ new: &str,
289+ ) -> Result<SignedIn> {
290+ let user = self.store.user(user_id).await?.ok_or(StoreError::NotFound)?;
291+ let ok = match user.password_hash.as_deref() {
292+ Some(stored) => verify_password(current, stored),
293+ None => {
294+ auth::dummy_verify(current);
295+ false
296+ }
297+ };
298+ if !ok {
299+ return Err(AccountError::Rejected);
300+ }
301+ auth::check_password(new, &user.email, &user.display_name)?;
302+ let hash = hash_password(new)?;
303+ self.store.set_password_hash(&user.id, &hash).await?;
304+ // "Signs out your other devices", as the pane promises.
305+ self.store
306+ .revoke_sessions_for_user(&user.id, OffsetDateTime::now_utc())
307+ .await?;
308+ let user = self.store.user(&user.id).await?.ok_or(StoreError::NotFound)?;
309+ self.start_session(user).await
310+ }
311+
312+ // -- sessions ----------------------------------------------------------
313+
314+ /// Turns a cookie value back into a person, or into nothing at all.
315+ pub async fn authenticate(&self, presented: &str) -> Result<Option<User>> {
316+ let digest = auth::hash_token(presented);
317+ let Some(session) = self.store.session_by_hash(&digest).await? else {
318+ return Ok(None);
319+ };
320+ // The index found it; compare the digests properly before trusting it.
321+ let Some(stored) = self.store.session_token_hash(&session.id).await? else {
322+ return Ok(None);
323+ };
324+ if !auth::digests_match(&stored, &digest) {
325+ return Ok(None);
326+ }
327+ if !session.is_live(OffsetDateTime::now_utc()) {
328+ return Ok(None);
329+ }
330+ Ok(self.store.user(&session.user_id).await?)
331+ }
332+
333+ /// Ends one browser's session.
334+ pub async fn sign_out(&self, presented: &str) -> Result<()> {
335+ let digest = auth::hash_token(presented);
336+ if let Some(session) = self.store.session_by_hash(&digest).await? {
337+ let _ = self
338+ .store
339+ .revoke_session(&session.id, OffsetDateTime::now_utc())
340+ .await;
341+ }
342+ Ok(())
343+ }
344+
345+ async fn start_session(&self, user: User) -> Result<SignedIn> {
346+ let token = Token::mint();
347+ let session = self
348+ .store
349+ .create_session(
350+ &user.id,
351+ &token.hash(),
352+ OffsetDateTime::now_utc() + SESSION_LIFETIME,
353+ )
354+ .await?;
355+ Ok(SignedIn {
356+ user,
357+ session_token: token,
358+ session,
359+ })
360+ }
361+
362+ // -- guards ------------------------------------------------------------
363+
364+ fn require_admin(&self, actor: &User) -> Result<()> {
365+ if actor.role.can_administer() {
366+ Ok(())
367+ } else {
368+ Err(AccountError::Forbidden)
369+ }
370+ }
371+
372+ async fn check_rate(&self, bucket: &str) -> Result<()> {
373+ let since = OffsetDateTime::now_utc() - RATE_WINDOW;
374+ if self.store.count_auth_attempts(bucket, since).await? >= RATE_LIMIT {
375+ return Err(AccountError::RateLimited);
376+ }
377+ Ok(())
378+ }
379+}
crates/dizey-core/src/auth.rsadded+285 -0
@@ -0,0 +1,285 @@
1+//! Passwords, tokens and the rules around them.
2+//!
3+//! Two different jobs, deliberately kept apart:
4+//!
5+//! * **Passwords** are low-entropy and chosen by a person, so they go through
6+//! Argon2id with deliberately expensive parameters.
7+//! * **Tokens** — sign-in links, session cookies, read-only links, the calendar
8+//! feed — are 128 bits from a CSPRNG. There is nothing to brute-force, so
9+//! they are stored as a plain SHA-256 digest. Running Argon2 over them would
10+//! buy nothing and cost a page load.
11+
12+use argon2::password_hash::phc::PasswordHash;
13+use argon2::password_hash::{PasswordHasher, PasswordVerifier};
14+use argon2::{Algorithm, Argon2, Params, Version};
15+use rand::Rng;
16+use sha2::{Digest, Sha256};
17+use subtle::ConstantTimeEq;
18+
19+/// Argon2id at the OWASP Password Storage Cheat Sheet's recommended second
20+/// configuration: 19 MiB of memory, two iterations, one lane.
21+pub const ARGON2_MEMORY_KIB: u32 = 19 * 1024;
22+pub const ARGON2_ITERATIONS: u32 = 2;
23+pub const ARGON2_PARALLELISM: u32 = 1;
24+
25+/// How many bytes of randomness every token carries.
26+pub const TOKEN_BYTES: usize = 16;
27+
28+/// A password rule the person's choice broke. The wording is the wording on the
29+/// first-sign-in screen.
30+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
31+pub enum PasswordProblem {
32+ #[error("at least 10 characters")]
33+ TooShort,
34+ #[error("not your address or your name")]
35+ LooksLikeYou,
36+}
37+
38+#[derive(Debug, thiserror::Error)]
39+pub enum AuthError {
40+ #[error("password hashing failed: {0}")]
41+ Hashing(String),
42+}
43+
44+fn argon2() -> Argon2<'static> {
45+ let params = Params::new(
46+ ARGON2_MEMORY_KIB,
47+ ARGON2_ITERATIONS,
48+ ARGON2_PARALLELISM,
49+ None,
50+ )
51+ .expect("argon2 parameters are constants and are in range");
52+ Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
53+}
54+
55+/// Hashes a password into a PHC string, salt included.
56+pub fn hash_password(password: &str) -> Result<String, AuthError> {
57+ argon2()
58+ .hash_password(password.as_bytes())
59+ .map(|h| h.to_string())
60+ .map_err(|e| AuthError::Hashing(e.to_string()))
61+}
62+
63+/// Checks a password against a stored PHC string.
64+///
65+/// The parameters come from the stored hash, not from [`argon2`], so raising
66+/// the cost later does not lock anyone out.
67+pub fn verify_password(password: &str, phc: &str) -> bool {
68+ match PasswordHash::new(phc) {
69+ Ok(parsed) => argon2().verify_password(password.as_bytes(), &parsed).is_ok(),
70+ Err(_) => false,
71+ }
72+}
73+
74+/// A PHC string for a password nobody knows, used to keep the miss path as
75+/// expensive as the hit path.
76+///
77+/// Without this, "no such address" answers before Argon2 would have finished
78+/// and the response time tells an attacker what the wording refuses to.
79+pub fn dummy_password_hash() -> &'static str {
80+ // Minted by the ignored `print_a_dummy_hash` test over 256 bits of
81+ // randomness that was never written down.
82+ "$argon2id$v=19$m=19456,t=2,p=1$0JjUMrLBpJG7lzg5bxZhMQ$iGpGXBNDAaHV9jqDxDcCyuIEIV33kJ1IAPt0XCh753Q"
83+}
84+
85+/// Burns the same work a real verify would, and always fails.
86+///
87+/// Call this on every path where a lookup missed, before answering.
88+pub fn dummy_verify(password: &str) {
89+ let _ = verify_password(password, dummy_password_hash());
90+}
91+
92+/// A freshly minted secret. The plaintext exists only here and in the one
93+/// place that shows it; the database gets [`Token::hash`].
94+#[derive(Clone)]
95+pub struct Token {
96+ plaintext: String,
97+}
98+
99+impl Token {
100+ /// 128 bits from the thread CSPRNG, hex encoded.
101+ pub fn mint() -> Self {
102+ let mut bytes = [0u8; TOKEN_BYTES];
103+ rand::rng().fill_bytes(&mut bytes);
104+ Self {
105+ plaintext: hex(&bytes),
106+ }
107+ }
108+
109+ /// The value that goes in the link or the cookie. Shown exactly once.
110+ pub fn expose(&self) -> &str {
111+ &self.plaintext
112+ }
113+
114+ /// The value that goes in the database.
115+ pub fn hash(&self) -> String {
116+ hash_token(&self.plaintext)
117+ }
118+}
119+
120+impl std::fmt::Debug for Token {
121+ /// A token must not reach a log through a stray `{:?}`.
122+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123+ f.write_str("Token(redacted)")
124+ }
125+}
126+
127+/// SHA-256 of a token, hex encoded. Tokens are full-entropy, so a fast digest
128+/// is the right primitive here.
129+pub fn hash_token(plaintext: &str) -> String {
130+ let mut hasher = Sha256::new();
131+ hasher.update(plaintext.as_bytes());
132+ hex(&hasher.finalize())
133+}
134+
135+/// Compares two token digests without leaking where they diverge.
136+pub fn digests_match(a: &str, b: &str) -> bool {
137+ a.as_bytes().ct_eq(b.as_bytes()).into()
138+}
139+
140+fn hex(bytes: &[u8]) -> String {
141+ let mut out = String::with_capacity(bytes.len() * 2);
142+ for byte in bytes {
143+ out.push_str(&format!("{byte:02x}"));
144+ }
145+ out
146+}
147+
148+/// The rules the first-sign-in screen states, checked server-side.
149+pub fn check_password(password: &str, email: &str, display_name: &str) -> Result<(), PasswordProblem> {
150+ // Counted in characters, not bytes: a ten-character password is ten
151+ // characters whatever alphabet it is in.
152+ if password.chars().count() < 10 {
153+ return Err(PasswordProblem::TooShort);
154+ }
155+
156+ let folded = password.to_lowercase();
157+ let local_part = email.split('@').next().unwrap_or(email);
158+ let mut forbidden = vec![email.to_lowercase(), local_part.to_lowercase()];
159+ forbidden.extend(
160+ display_name
161+ .split_whitespace()
162+ .map(|word| word.to_lowercase()),
163+ );
164+ for needle in forbidden {
165+ // Short words ("de", "van") would forbid too much to be useful.
166+ if needle.chars().count() >= 3 && folded.contains(&needle) {
167+ return Err(PasswordProblem::LooksLikeYou);
168+ }
169+ }
170+ Ok(())
171+}
172+
173+#[cfg(test)]
174+mod tests {
175+ use super::*;
176+
177+ #[test]
178+ fn a_password_round_trips_and_a_wrong_one_does_not() {
179+ let phc = hash_password("correct horse battery").unwrap();
180+ assert!(phc.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"), "{phc}");
181+ assert!(verify_password("correct horse battery", &phc));
182+ assert!(!verify_password("correct horse batter", &phc));
183+ }
184+
185+ #[test]
186+ fn the_same_password_hashes_differently_every_time() {
187+ let a = hash_password("correct horse battery").unwrap();
188+ let b = hash_password("correct horse battery").unwrap();
189+ assert_ne!(a, b, "salts must differ");
190+ }
191+
192+ #[test]
193+ fn a_malformed_stored_hash_is_a_failed_verify_not_a_panic() {
194+ assert!(!verify_password("anything", ""));
195+ assert!(!verify_password("anything", "not-a-phc-string"));
196+ }
197+
198+ #[test]
199+ fn the_dummy_hash_is_usable_and_never_matches() {
200+ // If this ever stops parsing, the miss path silently gets cheap again.
201+ assert!(PasswordHash::new(dummy_password_hash()).is_ok());
202+ assert!(!verify_password("", dummy_password_hash()));
203+ assert!(!verify_password("password", dummy_password_hash()));
204+ dummy_verify("password");
205+ }
206+
207+ #[test]
208+ fn tokens_are_full_length_and_never_repeat() {
209+ let a = Token::mint();
210+ let b = Token::mint();
211+ assert_eq!(a.expose().len(), TOKEN_BYTES * 2);
212+ assert!(a.expose().chars().all(|c| c.is_ascii_hexdigit()));
213+ assert_ne!(a.expose(), b.expose());
214+ assert_ne!(a.hash(), b.hash());
215+ }
216+
217+ #[test]
218+ fn a_token_hashes_to_sha256_and_hides_itself_in_debug() {
219+ let token = Token::mint();
220+ assert_eq!(token.hash(), hash_token(token.expose()));
221+ assert_eq!(token.hash().len(), 64);
222+ assert_ne!(token.hash(), token.expose());
223+ assert_eq!(format!("{token:?}"), "Token(redacted)");
224+ }
225+
226+ #[test]
227+ fn known_answer_for_the_token_digest() {
228+ // SHA-256("dizey"), so a refactor cannot quietly change the algorithm
229+ // under stored hashes.
230+ assert_eq!(
231+ hash_token("dizey"),
232+ "ecef066ddcba712d09eca07be6a8625343e795c97b73a7f2f03417cce1fa58d7"
233+ );
234+ }
235+
236+ #[test]
237+ fn digest_comparison_is_by_value() {
238+ let token = Token::mint();
239+ assert!(digests_match(&token.hash(), &hash_token(token.expose())));
240+ assert!(!digests_match(&token.hash(), &hash_token("something else")));
241+ assert!(!digests_match("short", "longer"));
242+ }
243+
244+ #[test]
245+ fn password_rules_are_the_ones_on_the_screen() {
246+ let email = "grace@dizey.sh";
247+ let name = "Grace Hopper";
248+ assert_eq!(
249+ check_password("short", email, name),
250+ Err(PasswordProblem::TooShort)
251+ );
252+ assert_eq!(
253+ check_password("grace-and-more", email, name),
254+ Err(PasswordProblem::LooksLikeYou)
255+ );
256+ assert_eq!(
257+ check_password("HOPPERhopper", email, name),
258+ Err(PasswordProblem::LooksLikeYou),
259+ "case must not be an escape hatch"
260+ );
261+ assert_eq!(
262+ check_password("grace@dizey.sh!!", email, name),
263+ Err(PasswordProblem::LooksLikeYou)
264+ );
265+ assert!(check_password("tide-tables-1892", email, name).is_ok());
266+ // Ten characters exactly is allowed; nine is not.
267+ assert!(check_password("abcdefghij", email, name).is_ok());
268+ assert_eq!(
269+ check_password("abcdefghi", email, name),
270+ Err(PasswordProblem::TooShort)
271+ );
272+ }
273+}
274+
275+#[cfg(test)]
276+mod dummy_hash_generator {
277+ //! Run with `cargo test -p dizey-core --lib print_a_dummy_hash -- --ignored
278+ //! --nocapture` to mint a replacement for [`super::dummy_password_hash`].
279+ #[test]
280+ #[ignore = "generator, not a check"]
281+ fn print_a_dummy_hash() {
282+ let token = format!("{}{}", super::Token::mint().expose(), super::Token::mint().expose());
283+ println!("{}", super::hash_password(&token).unwrap());
284+ }
285+}
crates/dizey-core/src/lib.rsmodified+3 -0
@@ -3,8 +3,11 @@
33 //! Everything in here is server-side only: the web crate pulls it in behind its
44 //! `ssr` feature so none of it is compiled into the wasm bundle.
55
6+pub mod accounts;
7+pub mod auth;
68 pub mod role;
79 pub mod store;
810
911 pub use role::Role;
12+pub use accounts::{AccountError, Accounts};
1013 pub use store::{Store, StoreError, TursoStore};
crates/dizey-core/src/store/mod.rsmodified+80 -4
@@ -16,6 +16,8 @@ pub use turso_store::TursoStore;
1616
1717 #[derive(Debug, thiserror::Error)]
1818 pub enum StoreError {
19+ #[error("this workspace already has an owner")]
20+ AlreadyClaimed,
1921 #[error("database: {0}")]
2022 Backend(String),
2123 #[error("not found")]
@@ -120,14 +122,44 @@ impl SigninLink {
120122 }
121123 }
122124
125+/// A signed-in browser. As with every other token, only the hash of the cookie
126+/// value is stored.
127+#[derive(Debug, Clone, PartialEq)]
128+pub struct Session {
129+ pub id: String,
130+ pub user_id: String,
131+ pub created_at: OffsetDateTime,
132+ pub expires_at: OffsetDateTime,
133+ pub revoked_at: Option<OffsetDateTime>,
134+}
135+
136+impl Session {
137+ pub fn is_live(&self, now: OffsetDateTime) -> bool {
138+ self.revoked_at.is_none() && now < self.expires_at
139+ }
140+}
141+
123142 /// The storage boundary. Dyn-safe on purpose: handlers hold `Arc<dyn Store>`.
124143 #[async_trait]
125144 pub trait Store: Send + Sync + 'static {
126145 // -- workspace ---------------------------------------------------------
127146
128- /// Creates the workspace. Fails with [`StoreError::Conflict`] if one
129- /// already exists: Dizey hosts a single workspace per database.
130- async fn create_workspace(&self, name: &str) -> Result<Workspace>;
147+ /// Claims an empty database: writes the workspace, its first account and
148+ /// the single owner row in one transaction.
149+ ///
150+ /// The owner row has a fixed primary key, so two requests racing to claim
151+ /// the same empty workspace cannot both win, and the loser gets
152+ /// [`StoreError::AlreadyClaimed`] rather than quietly joining as a member.
153+ async fn claim_workspace(
154+ &self,
155+ workspace_name: &str,
156+ email: &str,
157+ display_name: &str,
158+ password_hash: &str,
159+ ) -> Result<(Workspace, User)>;
160+
161+ /// The account that claimed the workspace, if it has been claimed.
162+ async fn owner(&self) -> Result<Option<User>>;
131163
132164 async fn workspace(&self) -> Result<Option<Workspace>>;
133165
@@ -198,5 +230,49 @@ pub trait Store: Send + Sync + 'static {
198230 /// link apart from a wrong one — an expired link is not a dead account.
199231 async fn signin_link_by_hash(&self, token_hash: &str) -> Result<Option<SigninLink>>;
200232
201- async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()>;
233+ /// Marks the link used, in a transaction, conditional on it still being
234+ /// unused, and reports whether this call is the one that consumed it.
235+ ///
236+ /// Mail clients prefetch links, so two redemptions of the same link is
237+ /// ordinary traffic rather than an attack: exactly one of them must win.
238+ async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<bool>;
239+
240+ // -- sessions ----------------------------------------------------------
241+
242+ async fn create_session(
243+ &self,
244+ user_id: &str,
245+ token_hash: &str,
246+ expires_at: OffsetDateTime,
247+ ) -> Result<Session>;
248+
249+ /// Looks a session up by the hash of the cookie value. Returns it whether
250+ /// or not it is still live; the caller decides.
251+ async fn session_by_hash(&self, token_hash: &str) -> Result<Option<Session>>;
252+
253+ /// The stored digest for a session, so the caller can compare it in
254+ /// constant time rather than trusting the index lookup alone.
255+ async fn session_token_hash(&self, id: &str) -> Result<Option<String>>;
256+
257+ async fn revoke_session(&self, id: &str, at: OffsetDateTime) -> Result<()>;
258+
259+ /// Signs out every browser this account has. This is what the change-
260+ /// password pane promises.
261+ async fn revoke_sessions_for_user(&self, user_id: &str, at: OffsetDateTime) -> Result<u64>;
262+
263+ // -- rate limiting -----------------------------------------------------
264+
265+ /// Records one attempt against a bucket — an address, or a client address.
266+ async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()>;
267+
268+ /// How many attempts that bucket has made since `since`.
269+ async fn count_auth_attempts(&self, bucket: &str, since: OffsetDateTime) -> Result<u64>;
270+
271+ /// Forgets a bucket's attempts. Called on a success, so a person who
272+ /// mistypes twice and then gets it right is not left near the limit.
273+ async fn clear_auth_attempts(&self, bucket: &str) -> Result<()>;
274+
275+ /// Drops attempt rows older than `before`, so the ledger does not grow
276+ /// without bound.
277+ async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result<u64>;
202278 }
crates/dizey-core/src/store/turso_store.rsmodified+243 -18
@@ -8,21 +8,27 @@
88 use async_trait::async_trait;
99 use time::OffsetDateTime;
1010 use time::format_description::well_known::Rfc3339;
11+use turso::transaction::TransactionBehavior;
1112 use turso::{Builder, Connection, Row, Value, params};
1213 use uuid::Uuid;
1314
1415 use super::{
15- DeletePolicy, NewUser, Result, SigninLink, Store, StoreError, User, Workspace,
16+ DeletePolicy, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace,
1617 };
1718 use crate::Role;
1819
1920 /// Every migration, in order. Adding one means appending a file and a line.
20-const MIGRATIONS: &[(i64, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))];
21+const MIGRATIONS: &[(i64, &str)] = &[
22+ (1, include_str!("../../migrations/0001_init.sql")),
23+ (2, include_str!("../../migrations/0002_auth.sql")),
24+];
2125
2226 pub struct TursoStore {
27+ /// Shared by every single-statement call. Turso serialises statements on a
28+ /// connection, so this is safe; transactions are the exception and take a
29+ /// connection of their own.
2330 conn: Connection,
24- // Held so the database outlives its connection.
25- _db: turso::Database,
31+ db: turso::Database,
2632 }
2733
2834 impl TursoStore {
@@ -42,7 +48,7 @@ impl TursoStore {
4248 ] {
4349 conn.execute(pragma, ()).await.map_err(backend)?;
4450 }
45- let store = Self { conn, _db: db };
51+ let store = Self { conn, db };
4652 store.migrate().await?;
4753 Ok(store)
4854 }
@@ -94,6 +100,17 @@ impl TursoStore {
94100 Ok(self.applied_versions().await?.into_iter().max().unwrap_or(0))
95101 }
96102
103+ /// A connection of its own, for work that opens a transaction.
104+ /// `Connection::transaction` takes `&mut self`, and a transaction on the
105+ /// shared connection would swallow everyone else's statements.
106+ async fn tx_conn(&self) -> Result<Connection> {
107+ let conn = self.db.connect().map_err(backend)?;
108+ for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] {
109+ conn.execute(pragma, ()).await.map_err(backend)?;
110+ }
111+ Ok(conn)
112+ }
113+
97114 async fn one_row(&self, sql: &str, args: impl turso::IntoParams) -> Result<Option<Row>> {
98115 let mut rows = self.conn.query(sql, args).await.map_err(backend)?;
99116 rows.next().await.map_err(backend)
@@ -104,6 +121,13 @@ fn backend<E: std::fmt::Display>(e: E) -> StoreError {
104121 StoreError::Backend(e.to_string())
105122 }
106123
124+/// Turso reports constraint failures as text; there is no typed error to match
125+/// on in 0.8.0-pre.7.
126+fn is_constraint_violation(e: &turso::Error) -> bool {
127+ let text = e.to_string().to_lowercase();
128+ text.contains("constraint") || text.contains("unique")
129+}
130+
107131 fn now_text() -> Result<String> {
108132 stamp(OffsetDateTime::now_utc())
109133 }
@@ -195,6 +219,18 @@ fn signin_link_from(row: &Row) -> Result<SigninLink> {
195219 })
196220 }
197221
222+fn session_from(row: &Row) -> Result<Session> {
223+ Ok(Session {
224+ id: text(row, 0)?,
225+ user_id: text(row, 1)?,
226+ created_at: parse_stamp(&text(row, 2)?)?,
227+ expires_at: parse_stamp(&text(row, 3)?)?,
228+ revoked_at: opt_stamp(row, 4)?,
229+ })
230+}
231+
232+const SESSION_COLUMNS: &str = "id, user_id, created_at, expires_at, revoked_at";
233+
198234 /// Addresses are matched case-insensitively; the display form is kept as typed.
199235 fn fold_email(email: &str) -> String {
200236 email.trim().to_lowercase()
@@ -202,19 +238,89 @@ fn fold_email(email: &str) -> String {
202238
203239 #[async_trait]
204240 impl Store for TursoStore {
205- async fn create_workspace(&self, name: &str) -> Result<Workspace> {
206- if self.workspace().await?.is_some() {
207- return Err(StoreError::Conflict("workspace"));
208- }
209- let id = Uuid::new_v4().to_string();
210- self.conn
211- .execute(
212- "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)",
213- params![id.clone(), name, now_text()?],
214- )
241+ async fn claim_workspace(
242+ &self,
243+ workspace_name: &str,
244+ email: &str,
245+ display_name: &str,
246+ password_hash: &str,
247+ ) -> Result<(Workspace, User)> {
248+ let workspace_id = Uuid::new_v4().to_string();
249+ let admin_id = Uuid::new_v4().to_string();
250+ let now = now_text()?;
251+ let email = fold_email(email);
252+
253+ let mut conn = self.tx_conn().await?;
254+ // IMMEDIATE: take the write lock at BEGIN, so a second claimant waits
255+ // out the busy timeout here instead of doing the whole insert and
256+ // discovering the conflict at the end.
257+ let tx = conn
258+ .transaction_with_behavior(TransactionBehavior::Immediate)
215259 .await
216260 .map_err(backend)?;
217- self.workspace().await?.ok_or(StoreError::NotFound)
261+
262+ let claimed = async {
263+ tx.execute(
264+ "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)",
265+ params![workspace_id.clone(), workspace_name, now.clone()],
266+ )
267+ .await?;
268+ tx.execute(
269+ "INSERT INTO user (id, workspace_id, email, display_name, role, password_hash, \
270+ created_at) VALUES (?1, ?2, ?3, ?4, 'admin', ?5, ?6)",
271+ params![
272+ admin_id.clone(),
273+ workspace_id.clone(),
274+ email,
275+ display_name,
276+ password_hash,
277+ now.clone()
278+ ],
279+ )
280+ .await?;
281+ // The claim itself. Fixed primary key, so the second writer loses.
282+ tx.execute(
283+ "INSERT INTO workspace_owner (singleton, user_id, claimed_at) \
284+ VALUES (1, ?1, ?2)",
285+ params![admin_id.clone(), now],
286+ )
287+ .await?;
288+ Ok::<_, turso::Error>(())
289+ }
290+ .await;
291+
292+ match claimed {
293+ Ok(()) => tx.commit().await.map_err(|e| {
294+ if is_constraint_violation(&e) {
295+ StoreError::AlreadyClaimed
296+ } else {
297+ backend(e)
298+ }
299+ })?,
300+ Err(e) => {
301+ let _ = tx.rollback().await;
302+ return Err(if is_constraint_violation(&e) {
303+ StoreError::AlreadyClaimed
304+ } else {
305+ backend(e)
306+ });
307+ }
308+ }
309+
310+ let workspace = self.workspace().await?.ok_or(StoreError::NotFound)?;
311+ let admin = self.user(&admin_id).await?.ok_or(StoreError::NotFound)?;
312+ Ok((workspace, admin))
313+ }
314+
315+ async fn owner(&self) -> Result<Option<User>> {
316+ let sql = format!(
317+ "SELECT {USER_COLUMNS} FROM user \
318+ WHERE id = (SELECT user_id FROM workspace_owner WHERE singleton = 1)"
319+ );
320+ match self.one_row(&sql, ()).await? {
321+ Some(row) => Ok(Some(user_from(&row)?)),
322+ None => Ok(None),
323+ }
218324 }
219325
220326 async fn workspace(&self) -> Result<Option<Workspace>> {
@@ -467,17 +573,136 @@ impl Store for TursoStore {
467573 }
468574 }
469575
470- async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()> {
576+ async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<bool> {
577+ let mut conn = self.tx_conn().await?;
578+ let tx = conn
579+ .transaction_with_behavior(TransactionBehavior::Immediate)
580+ .await
581+ .map_err(backend)?;
582+ // Conditional update plus rows-affected, never read-then-write: the
583+ // second redemption of a prefetched link updates nothing.
584+ let n = tx
585+ .execute(
586+ "UPDATE signin_link SET used_at = ?1 WHERE id = ?2 AND used_at IS NULL",
587+ params![stamp(at)?, id],
588+ )
589+ .await
590+ .map_err(backend)?;
591+ tx.commit().await.map_err(backend)?;
592+ Ok(n == 1)
593+ }
594+
595+ async fn create_session(
596+ &self,
597+ user_id: &str,
598+ token_hash: &str,
599+ expires_at: OffsetDateTime,
600+ ) -> Result<Session> {
601+ let id = Uuid::new_v4().to_string();
602+ self.conn
603+ .execute(
604+ "INSERT INTO session (id, user_id, token_hash, created_at, expires_at) \
605+ VALUES (?1, ?2, ?3, ?4, ?5)",
606+ params![
607+ id.clone(),
608+ user_id,
609+ token_hash,
610+ now_text()?,
611+ stamp(expires_at)?
612+ ],
613+ )
614+ .await
615+ .map_err(backend)?;
616+ let sql = format!("SELECT {SESSION_COLUMNS} FROM session WHERE id = ?1");
617+ match self.one_row(&sql, params![id]).await? {
618+ Some(row) => session_from(&row),
619+ None => Err(StoreError::NotFound),
620+ }
621+ }
622+
623+ async fn session_by_hash(&self, token_hash: &str) -> Result<Option<Session>> {
624+ let sql = format!("SELECT {SESSION_COLUMNS} FROM session WHERE token_hash = ?1");
625+ match self.one_row(&sql, params![token_hash]).await? {
626+ Some(row) => Ok(Some(session_from(&row)?)),
627+ None => Ok(None),
628+ }
629+ }
630+
631+ async fn session_token_hash(&self, id: &str) -> Result<Option<String>> {
632+ match self
633+ .one_row("SELECT token_hash FROM session WHERE id = ?1", params![id])
634+ .await?
635+ {
636+ Some(row) => Ok(Some(text(&row, 0)?)),
637+ None => Ok(None),
638+ }
639+ }
640+
641+ async fn revoke_session(&self, id: &str, at: OffsetDateTime) -> Result<()> {
471642 let n = self
472643 .conn
473644 .execute(
474- "UPDATE signin_link SET used_at = ?1 WHERE id = ?2 AND used_at IS NULL",
645+ "UPDATE session SET revoked_at = ?1 WHERE id = ?2 AND revoked_at IS NULL",
475646 params![stamp(at)?, id],
476647 )
477648 .await
478649 .map_err(backend)?;
479650 if n == 0 { Err(StoreError::NotFound) } else { Ok(()) }
480651 }
652+
653+ async fn revoke_sessions_for_user(&self, user_id: &str, at: OffsetDateTime) -> Result<u64> {
654+ self.conn
655+ .execute(
656+ "UPDATE session SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL",
657+ params![stamp(at)?, user_id],
658+ )
659+ .await
660+ .map_err(backend)
661+ }
662+
663+ async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> {
664+ self.conn
665+ .execute(
666+ "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)",
667+ params![Uuid::new_v4().to_string(), bucket, stamp(at)?],
668+ )
669+ .await
670+ .map_err(backend)?;
671+ Ok(())
672+ }
673+
674+ async fn count_auth_attempts(&self, bucket: &str, since: OffsetDateTime) -> Result<u64> {
675+ // RFC 3339 in UTC sorts lexicographically, which is why the timestamps
676+ // are stored in that shape.
677+ match self
678+ .one_row(
679+ "SELECT COUNT(*) FROM auth_attempt WHERE bucket = ?1 AND attempted_at >= ?2",
680+ params![bucket, stamp(since)?],
681+ )
682+ .await?
683+ {
684+ Some(row) => count_of(&row),
685+ None => Ok(0),
686+ }
687+ }
688+
689+ async fn clear_auth_attempts(&self, bucket: &str) -> Result<()> {
690+ self.conn
691+ .execute("DELETE FROM auth_attempt WHERE bucket = ?1", params![bucket])
692+ .await
693+ .map_err(backend)?;
694+ Ok(())
695+ }
696+
697+ async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result<u64> {
698+ self.conn
699+ .execute(
700+ "DELETE FROM auth_attempt WHERE attempted_at < ?1",
701+ params![stamp(before)?],
702+ )
703+ .await
704+ .map_err(backend)
705+ }
481706 }
482707
483708 #[cfg(test)]
crates/dizey-core/tests/store.rsmodified+772 -26
@@ -1,11 +1,13 @@
1-//! Behaviour of the storage boundary, driven through the Turso implementation.
1+//! Integration tests for dizey-core: the storage boundary driven through the
2+//! Turso implementation, and the account flows on top of it.
23 //!
3-//! New storage tests belong in this file rather than a new `tests/*.rs`: one
4-//! test binary links and runs once.
4+//! New integration tests belong in this file rather than a new `tests/*.rs`:
5+//! one test binary links and runs once.
56
67 use std::path::PathBuf;
78
8-use dizey_core::store::{DeletePolicy, NewUser, Store, StoreError, TursoStore};
9+use dizey_core::auth::{Token, hash_password};
10+use dizey_core::store::{DeletePolicy, NewUser, Store, StoreError, TursoStore, User};
911 use dizey_core::Role;
1012 use time::{Duration, OffsetDateTime};
1113 use uuid::Uuid;
@@ -36,20 +38,47 @@ impl Drop for Scratch {
3638
3739 async fn workspace_with_admin() -> (Scratch, String, String) {
3840 let scratch = Scratch::open().await;
39- let ws = scratch.store.create_workspace("Dizey").await.unwrap();
40- let admin = scratch
41+ let (ws, admin) = scratch
4142 .store
42- .create_user(NewUser {
43- workspace_id: ws.id.clone(),
44- email: "ada@dizey.sh".into(),
45- display_name: "Ada".into(),
46- role: Role::Admin,
47- })
43+ .claim_workspace(
44+ "Dizey",
45+ "ada@dizey.sh",
46+ "Ada",
47+ &hash_password("tide-tables-1892").unwrap(),
48+ )
4849 .await
4950 .unwrap();
5051 (scratch, ws.id, admin.id)
5152 }
5253
54+/// Claims a workspace on an arbitrary store, for the tests that need one
55+/// without the `Scratch` wrapper.
56+async fn claim(store: &TursoStore) -> (String, String) {
57+ let (ws, admin) = store
58+ .claim_workspace(
59+ "Dizey",
60+ "ada@dizey.sh",
61+ "Ada",
62+ &hash_password("tide-tables-1892").unwrap(),
63+ )
64+ .await
65+ .unwrap();
66+ (ws.id, admin.id)
67+}
68+
69+async fn member(store: &TursoStore, workspace_id: &str, email: &str, name: &str) -> String {
70+ store
71+ .create_user(NewUser {
72+ workspace_id: workspace_id.to_string(),
73+ email: email.into(),
74+ display_name: name.into(),
75+ role: Role::Member,
76+ })
77+ .await
78+ .unwrap()
79+ .id
80+}
81+
5382 #[tokio::test]
5483 async fn migrations_apply_once_and_survive_reopen() {
5584 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() {
5786 let path = dir.join("dizey.db").to_string_lossy().into_owned();
5887
5988 let first = TursoStore::open(&path).await.unwrap();
60- assert_eq!(first.schema_version().await.unwrap(), 1);
61- first.create_workspace("Dizey").await.unwrap();
89+ assert_eq!(first.schema_version().await.unwrap(), 2);
90+ claim(&first).await;
6291 drop(first);
6392
6493 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
6594 // must not lose what the first open wrote.
6695 let second = TursoStore::open(&path).await.unwrap();
67- assert_eq!(second.schema_version().await.unwrap(), 1);
96+ assert_eq!(second.schema_version().await.unwrap(), 2);
6897 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey");
6998 drop(second);
7099 let _ = std::fs::remove_dir_all(&dir);
71100 }
72101
73102 #[tokio::test]
74-async fn a_database_holds_exactly_one_workspace() {
103+async fn the_first_account_owns_the_workspace() {
75104 let scratch = Scratch::open().await;
76105 assert!(scratch.store.workspace().await.unwrap().is_none());
77- scratch.store.create_workspace("Dizey").await.unwrap();
78- let again = scratch.store.create_workspace("Other").await;
79- assert!(matches!(again, Err(StoreError::Conflict("workspace"))));
106+ assert!(scratch.store.owner().await.unwrap().is_none());
107+
108+ let (_, admin_id) = claim(&scratch.store).await;
109+ let owner = scratch.store.owner().await.unwrap().unwrap();
110+ assert_eq!(owner.id, admin_id);
111+ assert_eq!(owner.role, Role::Admin);
112+ assert!(owner.has_signed_in(), "the admin sets their own password");
113+}
114+
115+#[tokio::test]
116+async fn a_second_claim_loses_and_changes_nothing() {
117+ let scratch = Scratch::open().await;
118+ claim(&scratch.store).await;
119+
120+ let second = scratch
121+ .store
122+ .claim_workspace(
123+ "Someone else's",
124+ "mallory@elsewhere.example",
125+ "Mallory",
126+ &hash_password("tide-tables-1892").unwrap(),
127+ )
128+ .await;
129+ assert!(matches!(second, Err(StoreError::AlreadyClaimed)));
130+
131+ // The loser must not have joined as anything at all.
132+ assert_eq!(scratch.store.workspace().await.unwrap().unwrap().name, "Dizey");
133+ assert_eq!(scratch.store.count_users("").await.unwrap(), 0);
134+ let ws_id = scratch.store.workspace().await.unwrap().unwrap().id;
135+ assert_eq!(scratch.store.count_users(&ws_id).await.unwrap(), 1);
136+ assert!(
137+ scratch
138+ .store
139+ .user_by_email(&ws_id, "mallory@elsewhere.example")
140+ .await
141+ .unwrap()
142+ .is_none()
143+ );
144+}
145+
146+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
147+async fn concurrent_claims_produce_exactly_one_admin() {
148+ let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4()));
149+ std::fs::create_dir_all(&dir).unwrap();
150+ let path = dir.join("dizey.db").to_string_lossy().into_owned();
151+ let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap());
152+
153+ let hash = hash_password("tide-tables-1892").unwrap();
154+ let mut claims = Vec::new();
155+ for i in 0..4 {
156+ let store = store.clone();
157+ let hash = hash.clone();
158+ claims.push(tokio::spawn(async move {
159+ store
160+ .claim_workspace(
161+ "Dizey",
162+ &format!("claimant{i}@dizey.sh"),
163+ &format!("Claimant {i}"),
164+ &hash,
165+ )
166+ .await
167+ .map(|(_, admin)| admin.email)
168+ }));
169+ }
170+
171+ let mut winners = Vec::new();
172+ for claim in claims {
173+ match claim.await.unwrap() {
174+ Ok(email) => winners.push(email),
175+ Err(StoreError::AlreadyClaimed) => {}
176+ Err(other) => panic!("unexpected claim failure: {other}"),
177+ }
178+ }
179+ assert_eq!(winners.len(), 1, "exactly one claim wins: {winners:?}");
180+
181+ let ws_id = store.workspace().await.unwrap().unwrap().id;
182+ assert_eq!(store.count_users(&ws_id).await.unwrap(), 1, "no half-written losers");
183+ let owner = store.owner().await.unwrap().unwrap();
184+ assert_eq!(owner.email, winners[0]);
185+
186+ drop(store);
187+ let _ = std::fs::remove_dir_all(&dir);
80188 }
81189
82190 #[tokio::test]
83191 async fn workspace_defaults_match_the_settings_screen() {
84192 let scratch = Scratch::open().await;
85- let ws = scratch.store.create_workspace("Dizey").await.unwrap();
193+ let (ws, _) = scratch
194+ .store
195+ .claim_workspace(
196+ "Dizey",
197+ "ada@dizey.sh",
198+ "Ada",
199+ &hash_password("tide-tables-1892").unwrap(),
200+ )
201+ .await
202+ .unwrap();
86203 assert_eq!(ws.attachment_limit_bytes, 25 * 1024 * 1024);
87204 assert_eq!(ws.photo_limit_bytes, 2 * 1024 * 1024);
88205 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() {
310427 .is_none()
311428 );
312429
313- scratch.store.consume_signin_link(&link.id, now).await.unwrap();
430+ assert!(scratch.store.consume_signin_link(&link.id, now).await.unwrap());
314431 let used = scratch
315432 .store
316433 .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() {
319436 .unwrap();
320437 assert!(!used.is_usable(now));
321438 // A second use finds nothing left to consume.
322- assert!(matches!(
323- scratch.store.consume_signin_link(&link.id, now).await,
324- Err(StoreError::NotFound)
325- ));
439+ assert!(!scratch.store.consume_signin_link(&link.id, now).await.unwrap());
326440 }
327441
328442 #[tokio::test]
@@ -362,6 +476,638 @@ async fn an_expired_link_is_still_a_live_account() {
362476 async fn the_store_is_usable_behind_a_trait_object() {
363477 let scratch = Scratch::open().await;
364478 let store: &dyn Store = &scratch.store;
365- store.create_workspace("Dizey").await.unwrap();
479+ store
480+ .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "$argon2id$fake")
481+ .await
482+ .unwrap();
366483 assert!(store.workspace().await.unwrap().is_some());
367484 }
485+
486+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
487+async fn a_prefetched_link_is_consumed_exactly_once() {
488+ let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4()));
489+ std::fs::create_dir_all(&dir).unwrap();
490+ let path = dir.join("dizey.db").to_string_lossy().into_owned();
491+ let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap());
492+ let (ws_id, _) = claim(&store).await;
493+ let user_id = member(&store, &ws_id, "grace@dizey.sh", "Grace").await;
494+
495+ let token = Token::mint();
496+ let now = OffsetDateTime::now_utc();
497+ let link = store
498+ .create_signin_link(&user_id, &token.hash(), now + Duration::days(7))
499+ .await
500+ .unwrap();
501+
502+ // The mail client prefetches while the person clicks.
503+ let mut redemptions = Vec::new();
504+ for _ in 0..4 {
505+ let store = store.clone();
506+ let id = link.id.clone();
507+ redemptions.push(tokio::spawn(async move {
508+ store.consume_signin_link(&id, now).await.unwrap()
509+ }));
510+ }
511+ let mut winners = 0;
512+ for redemption in redemptions {
513+ if redemption.await.unwrap() {
514+ winners += 1;
515+ }
516+ }
517+ assert_eq!(winners, 1, "exactly one redemption may win");
518+
519+ drop(store);
520+ let _ = std::fs::remove_dir_all(&dir);
521+}
522+
523+#[tokio::test]
524+async fn a_session_lives_until_it_expires_or_is_revoked() {
525+ let (scratch, ws_id, _) = workspace_with_admin().await;
526+ let user_id = member(&scratch.store, &ws_id, "grace@dizey.sh", "Grace").await;
527+
528+ let token = Token::mint();
529+ let now = OffsetDateTime::now_utc();
530+ let session = scratch
531+ .store
532+ .create_session(&user_id, &token.hash(), now + Duration::days(14))
533+ .await
534+ .unwrap();
535+ assert!(session.is_live(now));
536+
537+ // The cookie value is the only way in, and it is not what is stored.
538+ let found = scratch
539+ .store
540+ .session_by_hash(&token.hash())
541+ .await
542+ .unwrap()
543+ .unwrap();
544+ assert_eq!(found.id, session.id);
545+ assert!(
546+ scratch
547+ .store
548+ .session_by_hash(token.expose())
549+ .await
550+ .unwrap()
551+ .is_none(),
552+ "the plaintext must not be stored"
553+ );
554+ assert_eq!(
555+ scratch.store.session_token_hash(&session.id).await.unwrap(),
556+ Some(token.hash())
557+ );
558+
559+ scratch.store.revoke_session(&session.id, now).await.unwrap();
560+ let revoked = scratch
561+ .store
562+ .session_by_hash(&token.hash())
563+ .await
564+ .unwrap()
565+ .unwrap();
566+ assert!(!revoked.is_live(now), "a revoked session is dead at once");
567+ // Revoking twice is not an error the caller has to think about.
568+ assert!(matches!(
569+ scratch.store.revoke_session(&session.id, now).await,
570+ Err(StoreError::NotFound)
571+ ));
572+}
573+
574+#[tokio::test]
575+async fn an_expired_session_is_not_live() {
576+ let (scratch, ws_id, _) = workspace_with_admin().await;
577+ let user_id = member(&scratch.store, &ws_id, "grace@dizey.sh", "Grace").await;
578+ let now = OffsetDateTime::now_utc();
579+ let session = scratch
580+ .store
581+ .create_session(&user_id, &Token::mint().hash(), now - Duration::minutes(1))
582+ .await
583+ .unwrap();
584+ assert!(!session.is_live(now));
585+}
586+
587+#[tokio::test]
588+async fn changing_a_password_can_sign_out_every_other_device() {
589+ let (scratch, ws_id, _) = workspace_with_admin().await;
590+ let user_id = member(&scratch.store, &ws_id, "grace@dizey.sh", "Grace").await;
591+ let other_id = member(&scratch.store, &ws_id, "linus@dizey.sh", "Linus").await;
592+ let now = OffsetDateTime::now_utc();
593+
594+ let mut hashes = Vec::new();
595+ for _ in 0..3 {
596+ let token = Token::mint();
597+ scratch
598+ .store
599+ .create_session(&user_id, &token.hash(), now + Duration::days(14))
600+ .await
601+ .unwrap();
602+ hashes.push(token.hash());
603+ }
604+ let bystander = Token::mint();
605+ scratch
606+ .store
607+ .create_session(&other_id, &bystander.hash(), now + Duration::days(14))
608+ .await
609+ .unwrap();
610+
611+ let revoked = scratch
612+ .store
613+ .revoke_sessions_for_user(&user_id, now)
614+ .await
615+ .unwrap();
616+ assert_eq!(revoked, 3);
617+ for hash in &hashes {
618+ let session = scratch.store.session_by_hash(hash).await.unwrap().unwrap();
619+ assert!(!session.is_live(now));
620+ }
621+ // Someone else's browser is untouched.
622+ let bystander = scratch
623+ .store
624+ .session_by_hash(&bystander.hash())
625+ .await
626+ .unwrap()
627+ .unwrap();
628+ assert!(bystander.is_live(now));
629+}
630+
631+#[tokio::test]
632+async fn auth_attempts_are_counted_over_a_window() {
633+ let scratch = Scratch::open().await;
634+ let now = OffsetDateTime::now_utc();
635+ let window = now - Duration::minutes(15);
636+
637+ for minutes_ago in [30, 20, 10, 5, 1] {
638+ scratch
639+ .store
640+ .record_auth_attempt("grace@dizey.sh", now - Duration::minutes(minutes_ago))
641+ .await
642+ .unwrap();
643+ }
644+ scratch
645+ .store
646+ .record_auth_attempt("198.51.100.7", now)
647+ .await
648+ .unwrap();
649+
650+ // Only the three inside the window count, and buckets do not bleed.
651+ assert_eq!(
652+ scratch
653+ .store
654+ .count_auth_attempts("grace@dizey.sh", window)
655+ .await
656+ .unwrap(),
657+ 3
658+ );
659+ assert_eq!(
660+ scratch
661+ .store
662+ .count_auth_attempts("198.51.100.7", window)
663+ .await
664+ .unwrap(),
665+ 1
666+ );
667+ assert_eq!(
668+ scratch
669+ .store
670+ .count_auth_attempts("nobody@dizey.sh", window)
671+ .await
672+ .unwrap(),
673+ 0
674+ );
675+
676+ // A success clears the bucket that succeeded, and only that one.
677+ scratch
678+ .store
679+ .clear_auth_attempts("grace@dizey.sh")
680+ .await
681+ .unwrap();
682+ assert_eq!(
683+ scratch
684+ .store
685+ .count_auth_attempts("grace@dizey.sh", window)
686+ .await
687+ .unwrap(),
688+ 0
689+ );
690+ assert_eq!(
691+ scratch
692+ .store
693+ .count_auth_attempts("198.51.100.7", window)
694+ .await
695+ .unwrap(),
696+ 1
697+ );
698+
699+ // Pruning drops what is out of every window.
700+ scratch
701+ .store
702+ .record_auth_attempt("grace@dizey.sh", now - Duration::hours(2))
703+ .await
704+ .unwrap();
705+ let pruned = scratch
706+ .store
707+ .prune_auth_attempts(now - Duration::hours(1))
708+ .await
709+ .unwrap();
710+ assert_eq!(pruned, 1);
711+}
712+
713+// ---------------------------------------------------------------------------
714+// Account flows.
715+// ---------------------------------------------------------------------------
716+
717+use dizey_core::accounts::{AccountError, Accounts, RATE_LIMIT, SIGNIN_LINK_LIFETIME};
718+use dizey_core::auth::PasswordProblem;
719+use std::sync::Arc;
720+
721+/// An accounts service over a throwaway database. The directory is kept alive
722+/// by the returned guard.
723+async fn accounts() -> (Scratch, Accounts) {
724+ let scratch = Scratch::open().await;
725+ let store = TursoStore::open(scratch.dir.join("dizey.db").to_str().unwrap())
726+ .await
727+ .unwrap();
728+ let accounts = Accounts::new(Arc::new(store) as Arc<dyn Store>);
729+ (scratch, accounts)
730+}
731+
732+async fn claimed() -> (Scratch, Accounts, User) {
733+ let (scratch, accounts) = accounts().await;
734+ let (_, signed_in) = accounts
735+ .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "tide-tables-1892")
736+ .await
737+ .unwrap();
738+ (scratch, accounts, signed_in.user)
739+}
740+
741+#[tokio::test]
742+async fn claiming_makes_an_admin_and_signs_them_in() {
743+ let (_scratch, accounts) = accounts().await;
744+ let (workspace, signed_in) = accounts
745+ .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "tide-tables-1892")
746+ .await
747+ .unwrap();
748+ assert_eq!(workspace.name, "Dizey");
749+ assert_eq!(signed_in.user.role, Role::Admin);
750+
751+ // The cookie value works and is not what is stored.
752+ let who = accounts
753+ .authenticate(signed_in.session_token.expose())
754+ .await
755+ .unwrap()
756+ .unwrap();
757+ assert_eq!(who.id, signed_in.user.id);
758+ assert!(
759+ accounts
760+ .authenticate(&signed_in.session.id)
761+ .await
762+ .unwrap()
763+ .is_none()
764+ );
765+}
766+
767+#[tokio::test]
768+async fn the_claim_screen_enforces_its_own_password_rules() {
769+ let (_scratch, accounts) = accounts().await;
770+ let too_short = accounts
771+ .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "short")
772+ .await;
773+ assert!(matches!(
774+ too_short,
775+ Err(AccountError::Password(PasswordProblem::TooShort))
776+ ));
777+ // A rejected password must not have claimed anything.
778+ assert!(accounts.store().workspace().await.unwrap().is_none());
779+}
780+
781+#[tokio::test]
782+async fn a_second_claim_is_refused() {
783+ let (_scratch, accounts, _admin) = claimed().await;
784+ let second = accounts
785+ .claim_workspace("Theirs", "mallory@elsewhere.example", "Mallory", "tide-tables-1892")
786+ .await;
787+ assert!(matches!(second, Err(AccountError::AlreadyClaimed)));
788+}
789+
790+#[tokio::test]
791+async fn an_invited_member_chooses_their_own_password() {
792+ let (_scratch, accounts, admin) = claimed().await;
793+ let invitation = accounts
794+ .invite(&admin, "grace@dizey.sh", "Grace", Role::Member)
795+ .await
796+ .unwrap();
797+ assert!(!invitation.user.has_signed_in(), "no password yet");
798+ assert!(invitation.expires_at > OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME - Duration::minutes(1));
799+
800+ // The admin cannot sign in as them in the meantime.
801+ let as_them = accounts
802+ .sign_in("grace@dizey.sh", "tide-tables-1892", "198.51.100.7")
803+ .await;
804+ assert!(matches!(as_them, Err(AccountError::Rejected)));
805+
806+ let signed_in = accounts
807+ .redeem_signin_link(invitation.token.expose(), "sextant-and-chart")
808+ .await
809+ .unwrap();
810+ assert_eq!(signed_in.user.id, invitation.user.id);
811+ assert!(signed_in.user.has_signed_in());
812+
813+ // And now the password they chose works, and only that one.
814+ accounts
815+ .sign_in("grace@dizey.sh", "sextant-and-chart", "198.51.100.7")
816+ .await
817+ .unwrap();
818+}
819+
820+#[tokio::test]
821+async fn only_an_admin_may_invite() {
822+ let (_scratch, accounts, admin) = claimed().await;
823+ let invitation = accounts
824+ .invite(&admin, "grace@dizey.sh", "Grace", Role::Member)
825+ .await
826+ .unwrap();
827+ let member = accounts
828+ .redeem_signin_link(invitation.token.expose(), "sextant-and-chart")
829+ .await
830+ .unwrap()
831+ .user;
832+
833+ // Server-side, not merely hidden: a member calling the flow is refused.
834+ let attempt = accounts
835+ .invite(&member, "linus@dizey.sh", "Linus", Role::Member)
836+ .await;
837+ assert!(matches!(attempt, Err(AccountError::Forbidden)));
838+
839+ let mut viewer = member.clone();
840+ viewer.role = Role::Viewer;
841+ assert!(matches!(
842+ accounts.invite(&viewer, "linus@dizey.sh", "Linus", Role::Viewer).await,
843+ Err(AccountError::Forbidden)
844+ ));
845+}
846+
847+#[tokio::test]
848+async fn a_link_works_once_and_a_wrong_one_never_does() {
849+ let (_scratch, accounts, admin) = claimed().await;
850+ let invitation = accounts
851+ .invite(&admin, "grace@dizey.sh", "Grace", Role::Member)
852+ .await
853+ .unwrap();
854+
855+ accounts
856+ .redeem_signin_link(invitation.token.expose(), "sextant-and-chart")
857+ .await
858+ .unwrap();
859+ let again = accounts
860+ .redeem_signin_link(invitation.token.expose(), "another-password")
861+ .await;
862+ assert!(matches!(again, Err(AccountError::Rejected)));
863+
864+ let invented = accounts
865+ .redeem_signin_link(&"0".repeat(32), "another-password")
866+ .await;
867+ assert!(matches!(invented, Err(AccountError::Rejected)));
868+
869+ // The password they actually set is untouched by either failure.
870+ accounts
871+ .sign_in("grace@dizey.sh", "sextant-and-chart", "198.51.100.7")
872+ .await
873+ .unwrap();
874+}
875+
876+#[tokio::test]
877+async fn a_rejected_password_does_not_burn_the_invitation() {
878+ let (_scratch, accounts, admin) = claimed().await;
879+ let invitation = accounts
880+ .invite(&admin, "grace@dizey.sh", "Grace", Role::Member)
881+ .await
882+ .unwrap();
883+
884+ assert!(matches!(
885+ accounts.redeem_signin_link(invitation.token.expose(), "grace!!").await,
886+ Err(AccountError::Password(PasswordProblem::TooShort))
887+ ));
888+ assert!(matches!(
889+ accounts.redeem_signin_link(invitation.token.expose(), "grace-hopper-1906").await,
890+ Err(AccountError::Password(PasswordProblem::LooksLikeYou))
891+ ));
892+ // Still redeemable with a password that passes.
893+ accounts
894+ .redeem_signin_link(invitation.token.expose(), "sextant-and-chart")
895+ .await
896+ .unwrap();
897+}
898+
899+#[tokio::test]
900+async fn an_expired_link_is_refused_and_resending_opens_the_same_account() {
901+ let (_scratch, accounts, admin) = claimed().await;
902+ let invitation = accounts
903+ .invite(&admin, "grace@dizey.sh", "Grace", Role::Member)
904+ .await
905+ .unwrap();
906+
907+ // Age the link past its expiry by writing a fresh one with a past date.
908+ let stale = Token::mint();
909+ accounts
910+ .store()
911+ .create_signin_link(
912+ &invitation.user.id,
913+ &stale.hash(),
914+ OffsetDateTime::now_utc() - Duration::minutes(1),
915+ )
916+ .await
917+ .unwrap();
918+ assert!(matches!(
919+ accounts.redeem_signin_link(stale.expose(), "sextant-and-chart").await,
920+ Err(AccountError::Rejected)
921+ ));
922+
923+ let resent = accounts
924+ .resend_invitation(&admin, &invitation.user.id)
925+ .await
926+ .unwrap();
927+ assert_eq!(resent.user.id, invitation.user.id, "same account, new link");
928+ let signed_in = accounts
929+ .redeem_signin_link(resent.token.expose(), "sextant-and-chart")
930+ .await
931+ .unwrap();
932+ assert_eq!(signed_in.user.id, invitation.user.id);
933+}
934+
935+#[tokio::test]
936+async fn an_unknown_address_and_a_wrong_password_are_indistinguishable() {
937+ let (_scratch, accounts, _admin) = claimed().await;
938+ let unknown = accounts
939+ .sign_in("nobody@dizey.sh", "tide-tables-1892", "198.51.100.7")
940+ .await;
941+ let wrong = accounts
942+ .sign_in("ada@dizey.sh", "not-her-password", "198.51.100.8")
943+ .await;
944+ assert!(matches!(unknown, Err(AccountError::Rejected)));
945+ assert!(matches!(wrong, Err(AccountError::Rejected)));
946+ assert_eq!(
947+ unknown.unwrap_err().to_string(),
948+ wrong.unwrap_err().to_string(),
949+ "the wording must not distinguish them either"
950+ );
951+}
952+
953+#[tokio::test]
954+async fn the_miss_path_costs_what_the_hit_path_costs() {
955+ let (_scratch, accounts, _admin) = claimed().await;
956+ // Not a timing assertion — those are flaky. This asserts the work happens:
957+ // a miss takes at least as long as one Argon2 verify at our parameters,
958+ // which a skipped verify could not.
959+ let baseline = std::time::Instant::now();
960+ let _ = accounts
961+ .sign_in("ada@dizey.sh", "not-her-password", "198.51.100.7")
962+ .await;
963+ let hit_cost = baseline.elapsed();
964+
965+ let started = std::time::Instant::now();
966+ let _ = accounts
967+ .sign_in("nobody@dizey.sh", "not-a-password", "198.51.100.8")
968+ .await;
969+ let miss_cost = started.elapsed();
970+
971+ assert!(
972+ miss_cost * 4 > hit_cost,
973+ "miss {miss_cost:?} is suspiciously cheaper than hit {hit_cost:?}"
974+ );
975+}
976+
977+#[tokio::test]
978+async fn an_invited_account_that_has_no_password_cannot_be_signed_into() {
979+ let (_scratch, accounts, admin) = claimed().await;
980+ accounts
981+ .invite(&admin, "grace@dizey.sh", "Grace", Role::Member)
982+ .await
983+ .unwrap();
984+ // Not "set your password first" — that would confirm the address exists.
985+ assert!(matches!(
986+ accounts.sign_in("grace@dizey.sh", "", "198.51.100.7").await,
987+ Err(AccountError::Rejected)
988+ ));
989+}
990+
991+#[tokio::test]
992+async fn sign_in_attempts_are_rate_limited_per_address() {
993+ let (_scratch, accounts, _admin) = claimed().await;
994+ for _ in 0..RATE_LIMIT {
995+ let _ = accounts
996+ .sign_in("ada@dizey.sh", "wrong", "198.51.100.7")
997+ .await;
998+ }
999+ // The next attempt is refused before any Argon2 work happens.
1000+ assert!(matches!(
1001+ accounts.sign_in("ada@dizey.sh", "wrong", "203.0.113.9").await,
1002+ Err(AccountError::RateLimited)
1003+ ));
1004+ // A different address from a fresh client is unaffected.
1005+ assert!(matches!(
1006+ accounts.sign_in("someone@dizey.sh", "wrong", "203.0.113.9").await,
1007+ Err(AccountError::Rejected)
1008+ ));
1009+}
1010+
1011+#[tokio::test]
1012+async fn a_successful_sign_in_clears_the_bucket() {
1013+ let (_scratch, accounts, _admin) = claimed().await;
1014+ for _ in 0..(RATE_LIMIT - 1) {
1015+ let _ = accounts
1016+ .sign_in("ada@dizey.sh", "wrong", "198.51.100.7")
1017+ .await;
1018+ }
1019+ accounts
1020+ .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7")
1021+ .await
1022+ .unwrap();
1023+ // Someone who mistypes and then gets it right is not left at the edge.
1024+ assert!(matches!(
1025+ accounts.sign_in("ada@dizey.sh", "wrong", "198.51.100.7").await,
1026+ Err(AccountError::Rejected)
1027+ ));
1028+}
1029+
1030+#[tokio::test]
1031+async fn changing_a_password_signs_out_every_device() {
1032+ let (_scratch, accounts, admin) = claimed().await;
1033+ let first = accounts
1034+ .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7")
1035+ .await
1036+ .unwrap();
1037+ let second = accounts
1038+ .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.8")
1039+ .await
1040+ .unwrap();
1041+ assert!(accounts.authenticate(first.session_token.expose()).await.unwrap().is_some());
1042+
1043+ let fresh = accounts
1044+ .change_password(&admin.id, "tide-tables-1892", "chronometer-1761")
1045+ .await
1046+ .unwrap();
1047+
1048+ for old in [&first, &second] {
1049+ assert!(
1050+ accounts.authenticate(old.session_token.expose()).await.unwrap().is_none(),
1051+ "the pane promises this"
1052+ );
1053+ }
1054+ assert!(accounts.authenticate(fresh.session_token.expose()).await.unwrap().is_some());
1055+ accounts
1056+ .sign_in("ada@dizey.sh", "chronometer-1761", "198.51.100.7")
1057+ .await
1058+ .unwrap();
1059+}
1060+
1061+#[tokio::test]
1062+async fn changing_a_password_needs_the_current_one_and_obeys_the_rules() {
1063+ let (_scratch, accounts, admin) = claimed().await;
1064+ assert!(matches!(
1065+ accounts.change_password(&admin.id, "not-it", "chronometer-1761").await,
1066+ Err(AccountError::Rejected)
1067+ ));
1068+ assert!(matches!(
1069+ accounts.change_password(&admin.id, "tide-tables-1892", "short").await,
1070+ Err(AccountError::Password(PasswordProblem::TooShort))
1071+ ));
1072+ // The old password still works after both refusals.
1073+ accounts
1074+ .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7")
1075+ .await
1076+ .unwrap();
1077+}
1078+
1079+#[tokio::test]
1080+async fn signing_out_ends_that_browser_only() {
1081+ let (_scratch, accounts, _admin) = claimed().await;
1082+ let laptop = accounts
1083+ .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.7")
1084+ .await
1085+ .unwrap();
1086+ let phone = accounts
1087+ .sign_in("ada@dizey.sh", "tide-tables-1892", "198.51.100.8")
1088+ .await
1089+ .unwrap();
1090+
1091+ accounts.sign_out(laptop.session_token.expose()).await.unwrap();
1092+ assert!(accounts.authenticate(laptop.session_token.expose()).await.unwrap().is_none());
1093+ assert!(accounts.authenticate(phone.session_token.expose()).await.unwrap().is_some());
1094+ // Signing out an unknown token is not an error.
1095+ accounts.sign_out(&"0".repeat(32)).await.unwrap();
1096+}
1097+
1098+#[tokio::test]
1099+async fn an_address_can_only_be_invited_once() {
1100+ let (_scratch, accounts, admin) = claimed().await;
1101+ accounts
1102+ .invite(&admin, "grace@dizey.sh", "Grace", Role::Member)
1103+ .await
1104+ .unwrap();
1105+ assert!(matches!(
1106+ accounts.invite(&admin, "GRACE@dizey.sh", "Grace again", Role::Member).await,
1107+ Err(AccountError::AddressTaken)
1108+ ));
1109+ assert!(matches!(
1110+ accounts.invite(&admin, "ada@dizey.sh", "Ada again", Role::Member).await,
1111+ Err(AccountError::AddressTaken)
1112+ ));
1113+}