Passwords, tokens, sessions and the account flows
Browse files at this commitdefe2eb63d8b3ff47a3c24a9451cb699df1d7c86Parent: 9cf2cb5- feat
- passwords, tokens, sessions and the account flows
10 changed files +1934 -56
- Cargo.lock +131 -8
- Cargo.toml +4 -0
- crates/dizey-core/Cargo.toml +4 -0
- crates/dizey-core/migrations/0002_auth.sql +33 -0
- crates/dizey-core/src/accounts.rs +379 -0
- crates/dizey-core/src/auth.rs +285 -0
- crates/dizey-core/src/lib.rs +3 -0
- crates/dizey-core/src/store/mod.rs +80 -4
- crates/dizey-core/src/store/turso_store.rs +243 -18
- crates/dizey-core/tests/store.rs +772 -26
Cargo.lockmodified+131 -8
| @@ -14,7 +14,7 @@ version = "0.5.2" | ||
| 14 | 14 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 15 | 15 | checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" |
| 16 | 16 | dependencies = [ |
| 17 | - "crypto-common", | |
| 17 | + "crypto-common 0.1.7", | |
| 18 | 18 | "generic-array", |
| 19 | 19 | ] |
| 20 | 20 | |
| @@ -126,6 +126,18 @@ dependencies = [ | ||
| 126 | 126 | "rustversion", |
| 127 | 127 | ] |
| 128 | 128 | |
| 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 | + | |
| 129 | 141 | [[package]] |
| 130 | 142 | name = "aristo" |
| 131 | 143 | version = "0.4.1" |
| @@ -302,6 +314,12 @@ version = "0.22.1" | ||
| 302 | 314 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 303 | 315 | checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" |
| 304 | 316 | |
| 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 | + | |
| 305 | 323 | [[package]] |
| 306 | 324 | name = "bigdecimal" |
| 307 | 325 | version = "0.4.10" |
| @@ -365,6 +383,15 @@ dependencies = [ | ||
| 365 | 383 | "wyz", |
| 366 | 384 | ] |
| 367 | 385 | |
| 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 | + | |
| 368 | 395 | [[package]] |
| 369 | 396 | name = "block-buffer" |
| 370 | 397 | version = "0.10.4" |
| @@ -374,6 +401,15 @@ dependencies = [ | ||
| 374 | 401 | "generic-array", |
| 375 | 402 | ] |
| 376 | 403 | |
| 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 | + | |
| 377 | 413 | [[package]] |
| 378 | 414 | name = "bon" |
| 379 | 415 | version = "3.10.0" |
| @@ -525,7 +561,7 @@ version = "0.4.4" | ||
| 525 | 561 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 526 | 562 | checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" |
| 527 | 563 | dependencies = [ |
| 528 | - "crypto-common", | |
| 564 | + "crypto-common 0.1.7", | |
| 529 | 565 | "inout", |
| 530 | 566 | ] |
| 531 | 567 | |
| @@ -540,6 +576,12 @@ dependencies = [ | ||
| 540 | 576 | "libloading", |
| 541 | 577 | ] |
| 542 | 578 | |
| 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 | + | |
| 543 | 585 | [[package]] |
| 544 | 586 | name = "codee" |
| 545 | 587 | version = "0.3.5" |
| @@ -606,6 +648,12 @@ dependencies = [ | ||
| 606 | 648 | "wasm-bindgen", |
| 607 | 649 | ] |
| 608 | 650 | |
| 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 | + | |
| 609 | 657 | [[package]] |
| 610 | 658 | name = "const-str" |
| 611 | 659 | version = "1.1.0" |
| @@ -759,6 +807,15 @@ dependencies = [ | ||
| 759 | 807 | "typenum", |
| 760 | 808 | ] |
| 761 | 809 | |
| 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 | + | |
| 762 | 819 | [[package]] |
| 763 | 820 | name = "ctr" |
| 764 | 821 | version = "0.9.2" |
| @@ -768,6 +825,15 @@ dependencies = [ | ||
| 768 | 825 | "cipher", |
| 769 | 826 | ] |
| 770 | 827 | |
| 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 | + | |
| 771 | 837 | [[package]] |
| 772 | 838 | name = "darling" |
| 773 | 839 | version = "0.24.1" |
| @@ -840,8 +906,20 @@ version = "0.10.7" | ||
| 840 | 906 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 841 | 907 | checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" |
| 842 | 908 | 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", | |
| 845 | 923 | ] |
| 846 | 924 | |
| 847 | 925 | [[package]] |
| @@ -859,9 +937,13 @@ dependencies = [ | ||
| 859 | 937 | name = "dizey-core" |
| 860 | 938 | version = "0.1.0" |
| 861 | 939 | dependencies = [ |
| 940 | + "argon2", | |
| 862 | 941 | "async-trait", |
| 942 | + "rand 0.10.2", | |
| 863 | 943 | "serde", |
| 864 | 944 | "serde_json", |
| 945 | + "sha2 0.11.0", | |
| 946 | + "subtle", | |
| 865 | 947 | "thiserror", |
| 866 | 948 | "time", |
| 867 | 949 | "tokio", |
| @@ -1413,6 +1495,15 @@ version = "1.0.3" | ||
| 1413 | 1495 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1414 | 1496 | checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" |
| 1415 | 1497 | |
| 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 | + | |
| 1416 | 1507 | [[package]] |
| 1417 | 1508 | name = "hydration_context" |
| 1418 | 1509 | version = "0.4.0-beta" |
| @@ -2466,6 +2557,16 @@ dependencies = [ | ||
| 2466 | 2557 | "windows-link", |
| 2467 | 2558 | ] |
| 2468 | 2559 | |
| 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 | + | |
| 2469 | 2570 | [[package]] |
| 2470 | 2571 | name = "paste" |
| 2471 | 2572 | version = "1.0.15" |
| @@ -2490,6 +2591,17 @@ version = "2.3.2" | ||
| 2490 | 2591 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2491 | 2592 | checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" |
| 2492 | 2593 | |
| 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 | + | |
| 2493 | 2605 | [[package]] |
| 2494 | 2606 | name = "pin-project" |
| 2495 | 2607 | version = "1.1.13" |
| @@ -3228,7 +3340,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" | ||
| 3228 | 3340 | dependencies = [ |
| 3229 | 3341 | "cfg-if", |
| 3230 | 3342 | "cpufeatures 0.2.17", |
| 3231 | - "digest", | |
| 3343 | + "digest 0.10.7", | |
| 3232 | 3344 | ] |
| 3233 | 3345 | |
| 3234 | 3346 | [[package]] |
| @@ -3245,7 +3357,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" | ||
| 3245 | 3357 | dependencies = [ |
| 3246 | 3358 | "cfg-if", |
| 3247 | 3359 | "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", | |
| 3249 | 3372 | ] |
| 3250 | 3373 | |
| 3251 | 3374 | [[package]] |
| @@ -4313,7 +4436,7 @@ version = "0.5.1" | ||
| 4313 | 4436 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4314 | 4437 | checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" |
| 4315 | 4438 | dependencies = [ |
| 4316 | - "crypto-common", | |
| 4439 | + "crypto-common 0.1.7", | |
| 4317 | 4440 | "subtle", |
| 4318 | 4441 | ] |
| 4319 | 4442 | |
| @@ -4483,7 +4606,7 @@ checksum = "3e653af7ee4a9ef0fce481a9ec6f43cb78de20d0cdb4f4f5862e1dc6e407e6c8" | ||
| 4483 | 4606 | dependencies = [ |
| 4484 | 4607 | "base16", |
| 4485 | 4608 | "quote", |
| 4486 | - "sha2", | |
| 4609 | + "sha2 0.10.9", | |
| 4487 | 4610 | "syn 2.0.119", |
| 4488 | 4611 | ] |
| 4489 | 4612 |
Cargo.tomlmodified+4 -0
| @@ -17,6 +17,10 @@ uuid = { version = "1.25.0", features = ["v4", "serde"] } | ||
| 17 | 17 | time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] } |
| 18 | 18 | tokio = { version = "1.53.1", features = ["full"] } |
| 19 | 19 | 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" | |
| 20 | 24 | |
| 21 | 25 | [profile.release] |
| 22 | 26 | codegen-units = 1 |
crates/dizey-core/Cargo.tomlmodified+4 -0
| @@ -7,7 +7,11 @@ repository.workspace = true | ||
| 7 | 7 | description = "Domain model and storage for Dizey" |
| 8 | 8 | |
| 9 | 9 | [dependencies] |
| 10 | +argon2.workspace = true | |
| 10 | 11 | async-trait = "0.1.92" |
| 12 | +rand.workspace = true | |
| 13 | +sha2.workspace = true | |
| 14 | +subtle.workspace = true | |
| 11 | 15 | serde.workspace = true |
| 12 | 16 | serde_json.workspace = true |
| 13 | 17 | 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 @@ | ||
| 3 | 3 | //! Everything in here is server-side only: the web crate pulls it in behind its |
| 4 | 4 | //! `ssr` feature so none of it is compiled into the wasm bundle. |
| 5 | 5 | |
| 6 | +pub mod accounts; | |
| 7 | +pub mod auth; | |
| 6 | 8 | pub mod role; |
| 7 | 9 | pub mod store; |
| 8 | 10 | |
| 9 | 11 | pub use role::Role; |
| 12 | +pub use accounts::{AccountError, Accounts}; | |
| 10 | 13 | pub use store::{Store, StoreError, TursoStore}; |
crates/dizey-core/src/store/mod.rsmodified+80 -4
| @@ -16,6 +16,8 @@ pub use turso_store::TursoStore; | ||
| 16 | 16 | |
| 17 | 17 | #[derive(Debug, thiserror::Error)] |
| 18 | 18 | pub enum StoreError { |
| 19 | + #[error("this workspace already has an owner")] | |
| 20 | + AlreadyClaimed, | |
| 19 | 21 | #[error("database: {0}")] |
| 20 | 22 | Backend(String), |
| 21 | 23 | #[error("not found")] |
| @@ -120,14 +122,44 @@ impl SigninLink { | ||
| 120 | 122 | } |
| 121 | 123 | } |
| 122 | 124 | |
| 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 | + | |
| 123 | 142 | /// The storage boundary. Dyn-safe on purpose: handlers hold `Arc<dyn Store>`. |
| 124 | 143 | #[async_trait] |
| 125 | 144 | pub trait Store: Send + Sync + 'static { |
| 126 | 145 | // -- workspace --------------------------------------------------------- |
| 127 | 146 | |
| 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>>; | |
| 131 | 163 | |
| 132 | 164 | async fn workspace(&self) -> Result<Option<Workspace>>; |
| 133 | 165 | |
| @@ -198,5 +230,49 @@ pub trait Store: Send + Sync + 'static { | ||
| 198 | 230 | /// link apart from a wrong one — an expired link is not a dead account. |
| 199 | 231 | async fn signin_link_by_hash(&self, token_hash: &str) -> Result<Option<SigninLink>>; |
| 200 | 232 | |
| 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>; | |
| 202 | 278 | } |
crates/dizey-core/src/store/turso_store.rsmodified+243 -18
| @@ -8,21 +8,27 @@ | ||
| 8 | 8 | use async_trait::async_trait; |
| 9 | 9 | use time::OffsetDateTime; |
| 10 | 10 | use time::format_description::well_known::Rfc3339; |
| 11 | +use turso::transaction::TransactionBehavior; | |
| 11 | 12 | use turso::{Builder, Connection, Row, Value, params}; |
| 12 | 13 | use uuid::Uuid; |
| 13 | 14 | |
| 14 | 15 | use super::{ |
| 15 | - DeletePolicy, NewUser, Result, SigninLink, Store, StoreError, User, Workspace, | |
| 16 | + DeletePolicy, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace, | |
| 16 | 17 | }; |
| 17 | 18 | use crate::Role; |
| 18 | 19 | |
| 19 | 20 | /// 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 | +]; | |
| 21 | 25 | |
| 22 | 26 | 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. | |
| 23 | 30 | conn: Connection, |
| 24 | - // Held so the database outlives its connection. | |
| 25 | - _db: turso::Database, | |
| 31 | + db: turso::Database, | |
| 26 | 32 | } |
| 27 | 33 | |
| 28 | 34 | impl TursoStore { |
| @@ -42,7 +48,7 @@ impl TursoStore { | ||
| 42 | 48 | ] { |
| 43 | 49 | conn.execute(pragma, ()).await.map_err(backend)?; |
| 44 | 50 | } |
| 45 | - let store = Self { conn, _db: db }; | |
| 51 | + let store = Self { conn, db }; | |
| 46 | 52 | store.migrate().await?; |
| 47 | 53 | Ok(store) |
| 48 | 54 | } |
| @@ -94,6 +100,17 @@ impl TursoStore { | ||
| 94 | 100 | Ok(self.applied_versions().await?.into_iter().max().unwrap_or(0)) |
| 95 | 101 | } |
| 96 | 102 | |
| 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 | + | |
| 97 | 114 | async fn one_row(&self, sql: &str, args: impl turso::IntoParams) -> Result<Option<Row>> { |
| 98 | 115 | let mut rows = self.conn.query(sql, args).await.map_err(backend)?; |
| 99 | 116 | rows.next().await.map_err(backend) |
| @@ -104,6 +121,13 @@ fn backend<E: std::fmt::Display>(e: E) -> StoreError { | ||
| 104 | 121 | StoreError::Backend(e.to_string()) |
| 105 | 122 | } |
| 106 | 123 | |
| 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 | + | |
| 107 | 131 | fn now_text() -> Result<String> { |
| 108 | 132 | stamp(OffsetDateTime::now_utc()) |
| 109 | 133 | } |
| @@ -195,6 +219,18 @@ fn signin_link_from(row: &Row) -> Result<SigninLink> { | ||
| 195 | 219 | }) |
| 196 | 220 | } |
| 197 | 221 | |
| 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 | + | |
| 198 | 234 | /// Addresses are matched case-insensitively; the display form is kept as typed. |
| 199 | 235 | fn fold_email(email: &str) -> String { |
| 200 | 236 | email.trim().to_lowercase() |
| @@ -202,19 +238,89 @@ fn fold_email(email: &str) -> String { | ||
| 202 | 238 | |
| 203 | 239 | #[async_trait] |
| 204 | 240 | 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) | |
| 215 | 259 | .await |
| 216 | 260 | .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 | + } | |
| 218 | 324 | } |
| 219 | 325 | |
| 220 | 326 | async fn workspace(&self) -> Result<Option<Workspace>> { |
| @@ -467,17 +573,136 @@ impl Store for TursoStore { | ||
| 467 | 573 | } |
| 468 | 574 | } |
| 469 | 575 | |
| 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<()> { | |
| 471 | 642 | let n = self |
| 472 | 643 | .conn |
| 473 | 644 | .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", | |
| 475 | 646 | params![stamp(at)?, id], |
| 476 | 647 | ) |
| 477 | 648 | .await |
| 478 | 649 | .map_err(backend)?; |
| 479 | 650 | if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } |
| 480 | 651 | } |
| 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 | + } | |
| 481 | 706 | } |
| 482 | 707 | |
| 483 | 708 | #[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. | |
| 2 | 3 | //! |
| 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. | |
| 5 | 6 | |
| 6 | 7 | use std::path::PathBuf; |
| 7 | 8 | |
| 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}; | |
| 9 | 11 | use dizey_core::Role; |
| 10 | 12 | use time::{Duration, OffsetDateTime}; |
| 11 | 13 | use uuid::Uuid; |
| @@ -36,20 +38,47 @@ impl Drop for Scratch { | ||
| 36 | 38 | |
| 37 | 39 | async fn workspace_with_admin() -> (Scratch, String, String) { |
| 38 | 40 | let scratch = Scratch::open().await; |
| 39 | - let ws = scratch.store.create_workspace("Dizey").await.unwrap(); | |
| 40 | - let admin = scratch | |
| 41 | + let (ws, admin) = scratch | |
| 41 | 42 | .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 | + ) | |
| 48 | 49 | .await |
| 49 | 50 | .unwrap(); |
| 50 | 51 | (scratch, ws.id, admin.id) |
| 51 | 52 | } |
| 52 | 53 | |
| 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 | + | |
| 53 | 82 | #[tokio::test] |
| 54 | 83 | async fn migrations_apply_once_and_survive_reopen() { |
| 55 | 84 | 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() { | ||
| 57 | 86 | let path = dir.join("dizey.db").to_string_lossy().into_owned(); |
| 58 | 87 | |
| 59 | 88 | 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; | |
| 62 | 91 | drop(first); |
| 63 | 92 | |
| 64 | 93 | // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and |
| 65 | 94 | // must not lose what the first open wrote. |
| 66 | 95 | 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); | |
| 68 | 97 | assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); |
| 69 | 98 | drop(second); |
| 70 | 99 | let _ = std::fs::remove_dir_all(&dir); |
| 71 | 100 | } |
| 72 | 101 | |
| 73 | 102 | #[tokio::test] |
| 74 | -async fn a_database_holds_exactly_one_workspace() { | |
| 103 | +async fn the_first_account_owns_the_workspace() { | |
| 75 | 104 | let scratch = Scratch::open().await; |
| 76 | 105 | 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); | |
| 80 | 188 | } |
| 81 | 189 | |
| 82 | 190 | #[tokio::test] |
| 83 | 191 | async fn workspace_defaults_match_the_settings_screen() { |
| 84 | 192 | 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(); | |
| 86 | 203 | assert_eq!(ws.attachment_limit_bytes, 25 * 1024 * 1024); |
| 87 | 204 | assert_eq!(ws.photo_limit_bytes, 2 * 1024 * 1024); |
| 88 | 205 | 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() { | ||
| 310 | 427 | .is_none() |
| 311 | 428 | ); |
| 312 | 429 | |
| 313 | - scratch.store.consume_signin_link(&link.id, now).await.unwrap(); | |
| 430 | + assert!(scratch.store.consume_signin_link(&link.id, now).await.unwrap()); | |
| 314 | 431 | let used = scratch |
| 315 | 432 | .store |
| 316 | 433 | .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() { | ||
| 319 | 436 | .unwrap(); |
| 320 | 437 | assert!(!used.is_usable(now)); |
| 321 | 438 | // 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()); | |
| 326 | 440 | } |
| 327 | 441 | |
| 328 | 442 | #[tokio::test] |
| @@ -362,6 +476,638 @@ async fn an_expired_link_is_still_a_live_account() { | ||
| 362 | 476 | async fn the_store_is_usable_behind_a_trait_object() { |
| 363 | 477 | let scratch = Scratch::open().await; |
| 364 | 478 | 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(); | |
| 366 | 483 | assert!(store.workspace().await.unwrap().is_some()); |
| 367 | 484 | } |
| 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 | +} |