diff --git a/.gitignore b/.gitignore index 6da1e4743..a48ed433d 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,6 @@ node_modules # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ + +/test-results/ +/playwright-report/ diff --git a/Cargo.lock b/Cargo.lock index d75a472eb..39799a649 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -128,24 +128,27 @@ dependencies = [ "axum", "base64 0.22.1", "chrono", + "jsonwebtoken", "openssl", - "p256", "piquel-auth-protocol", "piquel-configuration", "piquel-repository", "piquel-telemetry", "rand 0.8.7", + "reqwest", "serde", "serde_json", "sha2", "thiserror 2.0.18", "tokio", "tower", + "tower-http", "tracing", "unicode-normalization", "url", "webauthn-authenticator-rs", "webauthn-rs", + "webauthn-rs-proto", ] [[package]] @@ -206,12 +209,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "base16ct" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" - [[package]] name = "base64" version = "0.21.7" @@ -299,6 +296,23 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -341,6 +355,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc" version = "3.4.0" @@ -377,18 +400,6 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" -[[package]] -name = "crypto-bigint" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "subtle", - "zeroize", -] - [[package]] name = "crypto-common" version = "0.1.7" @@ -465,20 +476,6 @@ version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" -[[package]] -name = "ecdsa" -version = "0.16.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" -dependencies = [ - "der", - "digest", - "elliptic-curve", - "rfc6979", - "signature", - "spki", -] - [[package]] name = "either" version = "1.16.0" @@ -488,26 +485,6 @@ dependencies = [ "serde", ] -[[package]] -name = "elliptic-curve" -version = "0.13.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" -dependencies = [ - "base16ct", - "crypto-bigint", - "digest", - "ff", - "generic-array", - "group", - "pem-rfc7468", - "pkcs8", - "rand_core 0.6.4", - "sec1", - "subtle", - "zeroize", -] - [[package]] name = "equivalent" version = "1.0.2" @@ -546,16 +523,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "ff" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -710,7 +677,6 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", - "zeroize", ] [[package]] @@ -720,8 +686,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -743,19 +711,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", -] - -[[package]] -name = "group" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" -dependencies = [ - "ff", - "rand_core 0.6.4", - "subtle", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -897,6 +857,23 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.8", ] [[package]] @@ -905,13 +882,21 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ + "base64 0.22.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", "tower-service", + "tracing", ] [[package]] @@ -1051,6 +1036,12 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itoa" version = "1.0.18" @@ -1068,6 +1059,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1132,6 +1138,12 @@ version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "matchers" version = "0.2.0" @@ -1339,18 +1351,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "p256" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2", -] - [[package]] name = "parking" version = "2.2.1" @@ -1386,6 +1386,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -1507,21 +1517,68 @@ dependencies = [ ] [[package]] -name = "primeorder" -version = "0.13.6" +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" dependencies = [ - "elliptic-curve", + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", ] [[package]] -name = "proc-macro2" -version = "1.0.106" +name = "quinn-proto" +version = "0.11.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" dependencies = [ - "unicode-ident", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", ] [[package]] @@ -1566,6 +1623,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -1604,6 +1672,21 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1640,13 +1723,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] -name = "rfc6979" -version = "0.4.0" +name = "reqwest" +version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "hmac", - "subtle", + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots 1.0.8", ] [[package]] @@ -1683,6 +1794,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rusticata-macros" version = "4.1.0" @@ -1712,6 +1829,7 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" dependencies = [ + "web-time", "zeroize", ] @@ -1744,20 +1862,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "sec1" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" -dependencies = [ - "base16ct", - "der", - "generic-array", - "pkcs8", - "subtle", - "zeroize", -] - [[package]] name = "serde" version = "1.0.228" @@ -1851,7 +1955,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -1862,7 +1966,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -1901,6 +2005,18 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.18", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -2182,6 +2298,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -2325,6 +2444,16 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.18" @@ -2366,6 +2495,25 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.0", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "tracing", + "url", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -2440,6 +2588,12 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -2528,6 +2682,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2562,6 +2725,16 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.126" @@ -2594,6 +2767,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webauthn-attestation-ca" version = "0.5.5" diff --git a/Cargo.toml b/Cargo.toml index ecc1cb404..e5b63fb28 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,6 @@ base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } http = "1.3" openssl = { version = "0.10", features = ["vendored"] } -p256 = { version = "0.13", features = ["ecdsa", "pem", "pkcs8"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.10" @@ -53,4 +52,8 @@ tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } url = { version = "2.5", features = ["serde"] } unicode-normalization = "0.1" uuid = { version = "1.19", features = ["v7", "serde"] } -webauthn-rs = { version = "0.5.5", features = ["danger-allow-state-serialisation"] } +webauthn-rs = { version = "0.5.5", features = ["danger-allow-state-serialisation", "conditional-ui", "workaround-google-passkey-specific-issues"] } + +jsonwebtoken = "9.3" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +webauthn-rs-proto = "0.5.5" diff --git a/README.md b/README.md index e4293d02f..14c26dbd8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,157 @@ -# piquel-fr -Monorepo for all of `piquel.fr` +# piquel.fr + +A monorepo for piquel.fr and its services. The first release is a passkey-first +OIDC/SSO authority at `auth.piquel.fr`, with account settings on `piquel.fr`. + +The authentication service is **one Rust executable** containing its login, +onboarding, consent and passkey pages. PostgreSQL is its only external data +service. GitHub and Google are optional login providers. The separate settings +frontend calls the public authentication API. Infrastructure is outside this repo's +current scope. + +## Build + +Requires Rust 1.97+, Node 24+, and pnpm (the workspace pins its version). + +```sh +pnpm install --frozen-lockfile +pnpm build +cargo build --release -p auth-service +``` + +The executable is `target/release/auth-service`. Auth assets are embedded at compile +time; rebuild Rust after changing `apps/auth-web`. The standalone settings build +is `apps/piquel-web/build`. Node is needed to build the frontends, not to run auth. + +## Configuration + +| Variable | Meaning | +| --- | --- | +| `AUTH_DATABASE_URL` | PostgreSQL URL; production requires `sslmode=verify-full` | +| `AUTH_PUBLIC_BASE_URL` | Exact auth origin, normally `https://auth.piquel.fr` | +| `AUTH_SETTINGS_URL` | Exact settings destination; defaults to `https://piquel.fr/settings` | +| `AUTH_PUBLIC_LISTENER` | Listener address; defaults to `127.0.0.1:8080` | +| `AUTH_KEY_PROVIDER` | RSA private-key reference, `file:///absolute/path/key.pem` or `env://VARIABLE_NAME` | +| `AUTH_SIGNING_KEY_ID` | Stable ID for that signing key; defaults to `primary` | +| `AUTH_CLIENTS_FILE` | JSON client configuration; omitted means no OIDC clients | +| `AUTH_INVITE_REQUIRED` | `true` by default; set `false` to allow public registration | +| `AUTH_GITHUB_CLIENT_ID`, `AUTH_GITHUB_CLIENT_SECRET` | Both required to enable GitHub; secret is an env/file reference | +| `AUTH_GOOGLE_CLIENT_ID`, `AUTH_GOOGLE_CLIENT_SECRET` | Both required to enable Google; secret is an env/file reference | +| `AUTH_DEVELOPMENT_MODE` | Explicit `true` permits HTTP and unencrypted PostgreSQL on loopback only, plus ephemeral signing keys | + +Generate a persistent RSA key with OpenSSL, for example +`openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out /absolute/path/key.pem`. +Keep the same key and ID across restarts. Replacing the only configured key +invalidates issued tokens; overlapping signing-key rotation is not implemented. + +Provider callback URLs are `/login/github/callback` and `/login/google/callback` +on the auth origin. GitHub uses `read:user user:email`; Google uses `openid email profile`. +Never put provider secrets or confidential-client secrets in frontend configuration. + +Apply migrations explicitly, then run the same executable: + +```sh +auth-service migrate +auth-service serve +``` + +The schema intentionally replaces the throwaway prototype. Use a fresh database; +there is no migration path for prototype account data. + +### Invitations + +```sh +auth-service invite create --expires-in 7d +``` + +This prints one signup link. The database stores a digest, expiry and redemption +time. Tokens expire after seven days by default; `h` and `d` are supported. A token +is redeemed atomically with account creation, so a failed signup does not spend it. +Disabling invitation enforcement affects signup only; existing users keep access. + +### OIDC clients + +`AUTH_CLIENTS_FILE` is authoritative: startup disables clients omitted from it. +Client IDs must be unique. A minimal public web client looks like: + +```json +[ + { + "id": "piquel-web", + "display_name": "Piquel", + "redirect_uris": ["https://piquel.fr/callback"], + "post_logout_uris": ["https://piquel.fr/"], + "allowed_scopes": ["openid", "profile", "email"], + "trusted": true, + "allow_refresh": false + } +] +``` + +For a confidential backend client, add `"client_secret": "env://MY_CLIENT_SECRET"`. +Generate its random secret with `auth-service secret`. Clients use +`client_secret_basic` when confidential and `none` when public; both require S256 +PKCE. Redirect URLs must match exactly. HTTP loopback callbacks are permitted for +local testing. Non-loopback callbacks require HTTPS. + +Discovery is `/.well-known/openid-configuration`; JWKS is `/.well-known/jwks.json`. +The endpoints implement code exchange, RS256 ID/access tokens, userinfo, opt-in +rotating refresh tokens, revocation and RP-initiated logout. Access tokens are +intended for the configured client audience. Only requested claims are released; +passkey-only accounts have no email claim. Browser clients should keep tokens in +memory and use SSO again after reload. Refresh permission is off unless explicitly +enabled and `offline_access` is allowed/requested. Consent is remembered per user, +client and scope; explicitly trusted clients bypass consent. + +## Security behavior + +- Passkeys require user verification and prefer resident credentials. Synced + passkeys and security keys are accepted. Android enrollment offers an explicit + Google Password Manager option for devices with Google services. Authentication supports the browser + account picker and a username fallback. +- Social-first signup remains pending until its first passkey is committed. A + social login can never replace an established account's passkeys. +- A passkey confirmation opens a fixed two-minute management window for the + current account and browser session. It permits repeated sensitive changes and + does not slide or renew through social login. Reads need only ordinary login. +- Matching verified email suggests linking; it never grants account access. + Linking requires possession of the provider account and the target account's + passkey authorization. Explicit linking permits different/missing provider email. +- One Google and one GitHub identity may be linked. Unlinking releases the provider + identity so another account can link it; account data and credentials never move. +- The last passkey cannot be removed. Removing a passkey/provider revokes other + central sessions. There is no recovery if every passkey is lost. +- Sessions last at most 30 days. Access tokens last five minutes. Refresh rotation + detects reuse and stops when its central session expires or is revoked. Logout + does not destroy application-owned sessions or already issued access tokens. +- Browser state and opaque secrets are random, hashed where lookup is needed, and + bound to the initiating browser. Auth cookies are host-only, Secure and HttpOnly. + Mutations require an exact allowed origin and CSRF header; OIDC back-channel + endpoints instead validate their protocol credentials. +- Request throttling and expiring-state cleanup use PostgreSQL. Throttling uses the + direct peer IP; forwarded IP headers are not trusted. Security audit records are + retained. Readiness checks PostgreSQL; startup validates configured signing/provider + secrets. Request and provider calls have bounded timeouts. + +## Validation + +```sh +pnpm check +cargo fmt --all --check +cargo clippy --workspace --all-targets +cargo nextest run --workspace +TEST_DATABASE_URL=postgres://... cargo nextest run -p auth-service -p piquel-repository --run-ignored all +cargo deny check advisories licenses +pnpm audit +``` + +Database integration tests are explicitly marked ignored for the ordinary test +command. The database command above runs them against a **disposable loopback test +database** and applies migrations. It must not target a real account database. +For browser validation against the actual binary, see [tests/browser/README.md](tests/browser/README.md). + +Backend tests use signed software-authenticator responses and local GitHub/Google +HTTP fixtures, including real signed Google ID tokens. Browser tests use Chromium's +synced virtual authenticator and real Rust/PostgreSQL endpoints. Actual Apple/Google +device synchronization and live provider credentials require separate validation; +virtual authenticators and provider fixtures do not establish that evidence. diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index b63bf7130..dac7510b0 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -18,7 +18,9 @@ axum.workspace = true base64.workspace = true chrono.workspace = true openssl.workspace = true -p256.workspace = true +jsonwebtoken.workspace = true +reqwest.workspace = true +tower-http.workspace = true rand.workspace = true serde.workspace = true serde_json.workspace = true @@ -29,6 +31,7 @@ tracing.workspace = true unicode-normalization.workspace = true url.workspace = true webauthn-rs.workspace = true +webauthn-rs-proto.workspace = true [dev-dependencies] tower.workspace = true diff --git a/apps/auth-service/build.rs b/apps/auth-service/build.rs new file mode 100644 index 000000000..1092ddc7c --- /dev/null +++ b/apps/auth-service/build.rs @@ -0,0 +1,61 @@ +//! Snapshots the completed static auth frontend into Cargo's build output. +use std::fmt::Write; +use std::{ + env, fs, + path::{Path, PathBuf}, +}; +struct Assets { + source: PathBuf, + snapshot: PathBuf, + entries: Vec<(String, PathBuf)>, +} +impl Assets { + fn collect(&mut self, dir: &Path) -> std::io::Result<()> { + for entry in fs::read_dir(dir)? { + let path = entry?.path(); + if path.is_dir() { + self.collect(&path)?; + } else { + let relative = path.strip_prefix(&self.source).expect("asset under source"); + let snapshot = self.snapshot.join(relative); + fs::create_dir_all(snapshot.parent().expect("asset parent"))?; + fs::copy(&path, &snapshot)?; + self.entries + .push((format!("/{}", relative.display()), snapshot)); + } + } + Ok(()) + } +} +fn main() { + let source = + PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("manifest")).join("../auth-web/build"); + let output = PathBuf::from(env::var("OUT_DIR").expect("output directory")); + println!("cargo:rerun-if-changed={}", source.display()); + let mut assets = Assets { + source: source.clone(), + snapshot: output.join("auth-assets"), + entries: Vec::new(), + }; + if source.exists() { + assets + .collect(&source) + .expect("build the auth frontend completely before compiling Rust"); + } + assets.entries.sort(); + let mut entries = String::new(); + for (name, path) in &assets.entries { + let path = path.to_str().expect("UTF-8 asset path"); + // Debug-format strings to emit escaped Rust string literals, including quotes. + writeln!( + &mut entries, + "({name:?},include_bytes!({path:?}) as &'static [u8])," + ) + .expect("write generated Rust"); + } + fs::write( + output.join("assets.rs"), + format!("pub(crate) static FILES: &[(&str,&[u8])] = &[{entries}];"), + ) + .expect("write embedded assets"); +} diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs deleted file mode 100644 index c4ad55b8c..000000000 --- a/apps/auth-service/src/account.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Account policy boundaries; persistence is delegated to the repository crate. - -use crate::email::normalize; -use chrono::Utc; -use piquel_auth_protocol::{AccountStatus, TokenId, UserId}; -use piquel_repository::{ - AppendAuditEvent, AppendInternalEvent, Database, DatabaseError, InsertUser, - InsertVerifiedEmail, StoredUser, UpdateUserProfile, -}; -use thiserror::Error; - -/// Validated account profile snapshot used by the identity service. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) struct AccountProfile { - pub id: UserId, - pub username: String, - pub display_name: String, - pub version: u64, - pub status: AccountStatus, -} - -pub(super) struct CreateAccount { - pub username: String, - pub display_name: String, - pub verified_email: Option, -} - -pub(super) struct UpdateAccountProfile { - pub id: UserId, - pub expected_version: u64, - pub username: String, - pub display_name: String, -} - -#[derive(Debug, Error)] -pub(super) enum AccountError { - #[error("invalid account profile")] - InvalidProfile, - #[error("account operation failed")] - Database(#[from] DatabaseError), -} - -impl From for AccountProfile { - fn from(user: StoredUser) -> Self { - Self { - id: user.id, - username: user.username, - display_name: user.display_name, - version: user.profile_version, - status: user.status, - } - } -} - -/// Creates account state, optional verified email, audit, and internal event in one transaction. -pub(super) async fn create( - database: &Database, - input: CreateAccount, -) -> Result { - validate_username(&input.username).map_err(|()| AccountError::InvalidProfile)?; - validate_display_name(&input.display_name).map_err(|()| AccountError::InvalidProfile)?; - let email = input - .verified_email - .as_deref() - .map(normalize) - .transpose() - .map_err(|()| AccountError::InvalidProfile)?; - let user_id = UserId::new(); - let mut transaction = database.begin().await?; - let user = transaction - .users() - .insert(&InsertUser { - id: user_id, - username: input.username, - display_name: input.display_name, - }) - .await?; - if let Some(email) = email { - transaction - .emails() - .insert_verified(&InsertVerifiedEmail { - id: TokenId::new(), - user_id, - normalized_email: email.as_str().to_owned(), - is_primary: true, - verified_at: Utc::now(), - }) - .await?; - } - transaction - .audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(user_id), - action: "account.create".into(), - outcome: "success".into(), - request_metadata: serde_json::json!({}), - }) - .await?; - transaction - .internal_events() - .append(&AppendInternalEvent { - id: TokenId::new(), - aggregate_type: "user".into(), - aggregate_id: user_id, - event_type: "account.created".into(), - schema_version: 1, - payload: serde_json::json!({"profile_version": 1}), - }) - .await?; - transaction.commit().await?; - Ok(user) -} - -/// Disables an account and invalidates every central session atomically. -/// -/// Later token plans extend this same transaction with refresh-family -/// revocation; callers must not update account status directly. -pub(super) async fn disable(database: &Database, user_id: UserId) -> Result { - let mut transaction = database.begin().await?; - let changed = transaction - .users() - .set_status(user_id, AccountStatus::Disabled) - .await?; - if !changed { - transaction.rollback().await?; - return Ok(false); - } - transaction.sessions().revoke_all_for_user(user_id).await?; - transaction - .audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(user_id), - action: "account.disable".into(), - outcome: "success".into(), - request_metadata: serde_json::json!({}), - }) - .await?; - transaction - .internal_events() - .append(&AppendInternalEvent { - id: TokenId::new(), - aggregate_type: "user".into(), - aggregate_id: user_id, - event_type: "account.disabled".into(), - schema_version: 1, - payload: serde_json::json!({}), - }) - .await?; - transaction.commit().await?; - Ok(true) -} - -/// Reads the current account profile snapshot. -pub(super) async fn find( - database: &Database, - user_id: UserId, -) -> Result, AccountError> { - Ok(database - .users() - .find_by_id(user_id) - .await? - .map(AccountProfile::from)) -} - -/// Updates presentation fields and emits the matching event atomically. -pub(super) async fn update_profile( - database: &Database, - input: UpdateAccountProfile, -) -> Result { - validate_username(&input.username).map_err(|()| AccountError::InvalidProfile)?; - validate_display_name(&input.display_name).map_err(|()| AccountError::InvalidProfile)?; - - let mut transaction = database.begin().await?; - let user = transaction - .users() - .update_profile(&UpdateUserProfile { - id: input.id, - expected_version: input.expected_version, - username: input.username, - display_name: input.display_name, - }) - .await?; - transaction - .internal_events() - .append(&AppendInternalEvent { - id: TokenId::new(), - aggregate_type: "user".into(), - aggregate_id: user.id, - event_type: "profile.updated".into(), - schema_version: 1, - payload: serde_json::json!({"profile_version": user.profile_version}), - }) - .await?; - transaction.commit().await?; - Ok(user.into()) -} - -/// Checks the deliberately narrow username policy used for initial accounts. -pub(super) fn validate_username(value: &str) -> Result<(), ()> { - if !(3..=32).contains(&value.len()) - || !value - .bytes() - .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_') - { - return Err(()); - } - Ok(()) -} -/// Checks a presentation name without treating it as an identity key. -pub(super) fn validate_display_name(value: &str) -> Result<(), ()> { - if value.trim().is_empty() || value.chars().count() > 80 || value.chars().any(char::is_control) - { - return Err(()); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use piquel_repository::DatabaseConfig; - use std::{env, time::Duration}; - - #[test] - fn profile_validation_is_deliberate() { - assert!(validate_username("ada_lovelace").is_ok()); - assert!(validate_username("Ada").is_err()); - assert!(validate_display_name("Ada Lovelace").is_ok()); - } - - #[tokio::test] - #[ignore = "requires TEST_DATABASE_URL"] - async fn profile_update_and_event_commit_together() { - let url = env::var("TEST_DATABASE_URL") - .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - let config = DatabaseConfig::new_development(url, 5, Duration::from_secs(5)) - .expect("test database configuration"); - let database = Database::connect(config).await.expect("connect database"); - database.run_migrations().await.expect("run migrations"); - - let unique = UserId::new().to_string(); - let suffix = &unique[unique.len() - 12..]; - let created = create( - &database, - CreateAccount { - username: format!("profile_{suffix}"), - display_name: "Before".into(), - verified_email: None, - }, - ) - .await - .expect("create account"); - let updated = update_profile( - &database, - UpdateAccountProfile { - id: created.id, - expected_version: created.profile_version, - username: created.username, - display_name: "After".into(), - }, - ) - .await - .expect("update profile"); - assert_eq!(updated.version, 2); - - let next_sequence = database - .internal_events() - .append(&AppendInternalEvent { - id: TokenId::new(), - aggregate_type: "user".into(), - aggregate_id: created.id, - event_type: "test.probe".into(), - schema_version: 1, - payload: serde_json::json!({}), - }) - .await - .expect("append probe event"); - assert_eq!(next_sequence, 3); - } -} diff --git a/apps/auth-service/src/assets.rs b/apps/auth-service/src/assets.rs new file mode 100644 index 000000000..4cca35661 --- /dev/null +++ b/apps/auth-service/src/assets.rs @@ -0,0 +1,48 @@ +use axum::{ + body::Body, + http::{StatusCode, Uri, header}, + response::{IntoResponse, Response}, +}; +include!(concat!(env!("OUT_DIR"), "/assets.rs")); +pub(crate) async fn serve(uri: Uri) -> Response { + let path = uri.path(); + let html = if path == "/" { + "/index.html".into() + } else { + format!("{}.html", path.trim_end_matches('/')) + }; + let Some((name, bytes)) = FILES + .iter() + .find(|(name, _)| *name == path || *name == html) + else { + return ( + StatusCode::NOT_FOUND, + axum::Json(serde_json::json!({"error":"Not found."})), + ) + .into_response(); + }; + let content_type = match name.rsplit('.').next() { + Some("html") => "text/html; charset=utf-8", + Some("js") => "text/javascript; charset=utf-8", + Some("css") => "text/css; charset=utf-8", + Some("svg") => "image/svg+xml", + Some("json") => "application/json", + Some("png") => "image/png", + Some("ico") => "image/x-icon", + Some("woff2") => "font/woff2", + _ => "application/octet-stream", + }; + let mut response = Response::new(Body::from(*bytes)); + response.headers_mut().insert( + header::CONTENT_TYPE, + content_type.parse().expect("static content type"), + ); + // SvelteKit emits per-page script hashes in a CSP meta tag; frame-ancestors requires a header. + response.headers_mut().insert( + header::CONTENT_SECURITY_POLICY, + "frame-ancestors 'none'; object-src 'none'; base-uri 'self'" + .parse() + .expect("static CSP"), + ); + response +} diff --git a/apps/auth-service/src/audit.rs b/apps/auth-service/src/audit.rs deleted file mode 100644 index c632886d7..000000000 --- a/apps/auth-service/src/audit.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Sanitized security-audit policy. - -/// Produces a bounded audit action name. Inputs such as tokens and emails are -/// never part of audit metadata or metric labels. -pub(super) fn action(value: &str) -> Result<&str, ()> { - if value.is_empty() - || value.len() > 64 - || !value - .bytes() - .all(|byte| byte.is_ascii_lowercase() || byte == b'.' || byte == b'_') - { - return Err(()); - } - Ok(value) -} diff --git a/apps/auth-service/src/event_log.rs b/apps/auth-service/src/event_log.rs deleted file mode 100644 index d6e5a7a94..000000000 --- a/apps/auth-service/src/event_log.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! Transactional internal-event validation. - -/// Validates a versioned, credential-free internal-event kind. -pub(super) fn event_kind(value: &str) -> Result<&str, ()> { - if !value.contains('.') - || value.len() > 100 - || !value - .bytes() - .all(|byte| byte.is_ascii_lowercase() || byte == b'.' || byte == b'_') - { - return Err(()); - } - Ok(value) -} diff --git a/apps/auth-service/src/federation.rs b/apps/auth-service/src/federation.rs new file mode 100644 index 000000000..cc46408d5 --- /dev/null +++ b/apps/auth-service/src/federation.rs @@ -0,0 +1,1060 @@ +//! Browser-bound social authentication. Email suggests linking; it never authorizes it. + +use crate::{ + email::normalize, + security::{self, ApiError}, +}; +use axum::{ + Json, Router, + extract::{Path, Query, State}, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{IntoResponse, Redirect, Response}, + routing::{delete, get, post}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{Duration, Utc}; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; +use piquel_auth_protocol::{AuthenticationMethod, SessionId, TokenId, UserId}; +use piquel_configuration::SecretReference; +use piquel_repository::{ + AppendAuditEvent, Database, DatabaseTransaction, InsertExternalIdentity, + InsertFederationTransaction, PendingFederation, +}; +use rand::{RngCore, rngs::OsRng}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use sha2::{Digest, Sha256}; +use std::{collections::HashMap, sync::Arc, time::Duration as StdDuration}; +use thiserror::Error; +use url::Url; + +const PENDING_COOKIE: &str = "__Host-piquel_federation_pending"; +const FLOW_COOKIE: &str = "__Host-piquel_federation"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Provider { + GitHub, + Google, +} +impl Provider { + fn parse(value: &str) -> Result { + match value { + "github" => Ok(Self::GitHub), + "google" => Ok(Self::Google), + _ => Err(ApiError::bad_request( + "This sign-in provider is not supported.", + )), + } + } + const fn name(self) -> &'static str { + match self { + Self::GitHub => "github", + Self::Google => "google", + } + } + const fn issuer(self) -> &'static str { + match self { + Self::GitHub => "https://github.com", + Self::Google => "https://accounts.google.com", + } + } + const fn authorization_endpoint(self) -> &'static str { + match self { + Self::GitHub => "https://github.com/login/oauth/authorize", + Self::Google => "https://accounts.google.com/o/oauth2/v2/auth", + } + } +} + +/// OAuth application credentials; each provider may be omitted independently. +#[derive(Clone, Debug)] +pub struct ProviderConfiguration { + /// Client identifier assigned by GitHub or Google. + pub client_id: String, + /// Secret reference resolved only for the provider token exchange. + pub client_secret: SecretReference, +} + +#[derive(Clone)] +struct Endpoints { + github_token: String, + github_user: String, + github_emails: String, + google_token: String, + google_keys: String, +} +impl Default for Endpoints { + fn default() -> Self { + Self { + github_token: "https://github.com/login/oauth/access_token".into(), + github_user: "https://api.github.com/user".into(), + github_emails: "https://api.github.com/user/emails?per_page=100".into(), + google_token: "https://oauth2.googleapis.com/token".into(), + google_keys: "https://www.googleapis.com/oauth2/v3/certs".into(), + } + } +} + +/// Social login and explicit linking, backed exclusively by PostgreSQL. +#[derive(Clone)] +pub struct FederationApplication { + database: Database, + base_url: Url, + providers: Arc>, + client: reqwest::Client, + endpoints: Endpoints, + settings_url: Option, +} +impl FederationApplication { + /// Build independently optional providers with bounded, non-redirecting HTTP. + /// + /// # Errors + /// Rejects invalid origins, client identifiers, or HTTP client configuration. + pub fn new( + database: Database, + base_url: &Url, + github: Option, + google: Option, + ) -> Result { + if !Self::secure_or_loopback(base_url) + || base_url.host_str().is_none() + || base_url.path() != "/" + || base_url.query().is_some() + || base_url.fragment().is_some() + || !base_url.username().is_empty() + || base_url.password().is_some() + { + return Err(FederationConfigurationError); + } + let providers: HashMap<_, _> = [("github", github), ("google", google)] + .into_iter() + .filter_map(|(name, config)| config.map(|config| (name, config))) + .collect(); + if providers + .values() + .any(|config| config.client_id.is_empty() || config.client_id.len() > 512) + { + return Err(FederationConfigurationError); + } + Ok(Self { + database, + base_url: base_url.clone(), + providers: Arc::new(providers), + endpoints: Endpoints::default(), + settings_url: None, + client: reqwest::Client::builder() + .timeout(StdDuration::from_secs(8)) + .connect_timeout(StdDuration::from_secs(3)) + .redirect(reqwest::redirect::Policy::none()) + .user_agent("piquel-auth") + .build() + .map_err(|_| FederationConfigurationError)?, + }) + } + fn secure_or_loopback(url: &Url) -> bool { + url.scheme() == "https" + || (url.scheme() == "http" + && url.host_str().is_some_and(|host| { + host == "localhost" + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + })) + } + /// Allow only the configured settings page as an external continuation. + /// + /// # Errors + /// Rejects insecure non-loopback URLs, user information, and fragments. + pub fn with_settings_url( + mut self, + settings_url: &Url, + ) -> Result { + if !Self::secure_or_loopback(settings_url) + || settings_url.host_str().is_none() + || !settings_url.username().is_empty() + || settings_url.password().is_some() + || settings_url.fragment().is_some() + { + return Err(FederationConfigurationError); + } + self.settings_url = Some(settings_url.clone()); + Ok(self) + } + fn return_to(&self, value: Option<&str>) -> Result { + if let Some(value) = value + && self + .settings_url + .as_ref() + .is_some_and(|url| url.as_str() == value) + { + return Ok(value.into()); + } + validate_return_to(value) + } + fn callback_url(&self, provider: Provider) -> String { + format!("{}login/{}/callback", self.base_url, provider.name()) + } +} +/// A configured callback origin or provider is invalid. +#[derive(Debug, Error)] +#[error("invalid federation configuration")] +pub struct FederationConfigurationError; + +pub(super) fn routes(app: FederationApplication) -> Router { + Router::new() + .route("/login/providers", get(providers)) + .route("/login/{provider}/start", post(start)) + .route("/login/{provider}/callback", get(callback)) + .route("/login/social/pending", get(pending_view)) + .route("/login/social/link", post(confirm_link)) + .route("/login/social/cancel", post(cancel)) + .route("/account/social-identities", get(list_identities)) + .route("/account/social-identities/{provider}", delete(unlink)) + .with_state(app) +} +async fn providers(State(app): State) -> Json> { + Json( + ["github", "google"] + .into_iter() + .filter(|name| app.providers.contains_key(name)) + .collect(), + ) +} +#[derive(Default, Deserialize)] +#[serde(rename_all = "snake_case")] +enum StartMode { + #[default] + Login, + Link, +} +#[derive(Default, Deserialize)] +struct StartInput { + return_to: Option, + #[serde(default)] + mode: StartMode, +} +async fn start( + State(app): State, + Path(provider): Path, + headers: HeaderMap, + Json(input): Json, +) -> Result { + let provider = Provider::parse(&provider)?; + let config = app + .providers + .get(provider.name()) + .ok_or_else(|| ApiError::bad_request("This sign-in provider is not configured."))?; + let session = match input.mode { + StartMode::Login => None, + StartMode::Link => Some(security::management(&app.database, &headers).await?), + }; + let state = BrowserSecret::random(); + let nonce = BrowserSecret::random(); + let verifier = BrowserSecret::random(); + let browser = BrowserSecret::random(); + let return_to = app.return_to(input.return_to.as_deref())?; + app.database + .federation() + .insert_transaction(&InsertFederationTransaction { + id: TokenId::new(), + provider: provider.name().into(), + state_digest: state.digest(), + browser_digest: browser.digest(), + nonce: nonce.0.clone(), + pkce_verifier: verifier.0.clone(), + return_to, + link_user_id: session.as_ref().map(|s| s.user_id), + link_session_id: session.as_ref().map(|s| s.id), + expires_at: Utc::now() + Duration::minutes(10), + }) + .await?; + let mut url = Url::parse(provider.authorization_endpoint()).map_err(ApiError::internal)?; + url.query_pairs_mut() + .append_pair("client_id", &config.client_id) + .append_pair("redirect_uri", &app.callback_url(provider)) + .append_pair("response_type", "code") + .append_pair( + "scope", + match provider { + Provider::GitHub => "read:user user:email", + Provider::Google => "openid email profile", + }, + ) + .append_pair("state", &state.0) + .append_pair( + "code_challenge", + &URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.0.as_bytes())), + ) + .append_pair("code_challenge_method", "S256"); + if provider == Provider::Google { + url.query_pairs_mut() + .append_pair("nonce", &nonce.0) + .append_pair("prompt", "select_account"); + } + let mut response = Json(serde_json::json!({"redirect_url":url.as_str()})).into_response(); + FederationFlow::append(&mut response, &browser.cookie(FLOW_COOKIE, 600))?; + Ok(response) +} +#[derive(Deserialize)] +struct CallbackQuery { + code: Option, + state: Option, + error: Option, +} +async fn callback( + State(app): State, + Path(provider): Path, + headers: HeaderMap, + Query(query): Query, +) -> Result { + let provider = Provider::parse(&provider)?; + let browser = + BrowserSecret::from_headers(&headers, FLOW_COOKIE)?.ok_or_else(ApiError::unauthorized)?; + let state = query + .state + .filter(|state| state.len() == 43) + .ok_or_else(|| { + ApiError::bad_request( + "This sign-in attempt is invalid or has expired. Please start again.", + ) + })?; + // Consume state even on provider cancellation; it cannot be replayed later. + let flow = app + .database + .federation() + .consume_transaction( + provider.name(), + &Sha256::digest(state.as_bytes()), + &browser.digest(), + ) + .await?; + if query.error.is_some() { + let mut response = Redirect::to("/login?error=social_cancelled").into_response(); + FederationFlow::append(&mut response, FederationFlow::clear_flow())?; + return Ok(response); + } + let code = query + .code + .filter(|code| !code.is_empty() && code.len() <= 2048) + .ok_or_else(|| { + ApiError::bad_request("The provider did not return a valid sign-in response.") + })?; + let identity = app + .exchange(provider, &code, &flow.pkce_verifier, &flow.nonce) + .await?; + if let Some(user_id) = flow.link_user_id { + let session = security::session(&app.database, &headers).await?; + if session.user_id != user_id || Some(session.id) != flow.link_session_id { + return Err(ApiError::forbidden( + "Your session changed. Please start linking this provider again.", + )); + } + if let Some(existing) = app + .database + .federation() + .find_active(provider.issuer(), &identity.subject) + .await? + && existing.user_id != user_id + { + return Err(ApiError::forbidden( + "This provider account is already linked to another Piquel account.", + )); + } + return app + .pending_response( + provider, + identity, + flow.return_to, + Some(user_id), + flow.link_session_id, + ) + .await; + } + app.finish_login(provider, identity, flow.return_to).await +} +impl FederationApplication { + /// Complete an existing subject's login, or retain evidence for explicit onboarding/linking. + async fn finish_login( + &self, + provider: Provider, + identity: VerifiedIdentity, + return_to: String, + ) -> Result { + let mut tx = self.database.begin().await?; + if let Some(existing) = tx + .federation() + .find_active(provider.issuer(), &identity.subject) + .await? + { + tx.users() + .find_active_by_id_for_update(existing.user_id) + .await? + .ok_or_else(ApiError::unauthorized)?; + // Recheck the subject after locking the account: unlink takes the same lock. + let current = tx + .federation() + .find_active(provider.issuer(), &identity.subject) + .await? + .ok_or_else(ApiError::unauthorized)?; + if current.id != existing.id + || tx + .passkeys() + .list_active(existing.user_id) + .await? + .is_empty() + { + return Err(ApiError::unauthorized()); + } + let cookie = security::create_session( + &mut tx, + existing.user_id, + AuthenticationMethod::Federation, + ) + .await?; + tx.federation().record_login(existing.id).await?; + FederationFlow::audit( + &mut tx, + existing.user_id, + "federation.login", + provider.name(), + ) + .await?; + tx.commit().await?; + let mut response = Redirect::to(&return_to).into_response(); + FederationFlow::append(&mut response, &cookie)?; + FederationFlow::append(&mut response, FederationFlow::clear_flow())?; + return Ok(response); + } + let owner = match &identity.email { + Some(email) => tx + .emails() + .find_active_verified(email) + .await? + .map(|email| email.user_id), + None => None, + }; + tx.rollback().await?; + self.pending_response(provider, identity, return_to, owner, None) + .await + } + async fn pending_response( + &self, + provider: Provider, + identity: VerifiedIdentity, + return_to: String, + link_user_id: Option, + link_session_id: Option, + ) -> Result { + let browser = BrowserSecret::random(); + self.database + .federation() + .insert_pending(&PendingFederation { + id: TokenId::new(), + browser_digest: browser.digest(), + provider: provider.name().into(), + issuer: provider.issuer().into(), + subject: identity.subject, + email: identity.email, + display_name: identity.display_name, + return_to, + link_user_id, + link_session_id, + expires_at: Utc::now() + Duration::minutes(10), + }) + .await?; + let mut response = Redirect::to(if link_user_id.is_some() { + "/login?social=link" + } else { + "/login?social=signup" + }) + .into_response(); + FederationFlow::append(&mut response, &browser.cookie(PENDING_COOKIE, 600))?; + FederationFlow::append(&mut response, FederationFlow::clear_flow())?; + Ok(response) + } +} +fn validate_return_to(value: Option<&str>) -> Result { + let value = value.unwrap_or("/"); + let base = Url::parse("https://auth.piquel.fr/").map_err(ApiError::internal)?; + let joined = base + .join(value) + .map_err(|_| ApiError::bad_request("This return address is not allowed."))?; + if value.len() > 2048 + || !value.starts_with('/') + || value.starts_with("//") + || value.contains('\\') + || value.chars().any(char::is_control) + || joined.origin() != base.origin() + || joined.fragment().is_some() + { + return Err(ApiError::bad_request("This return address is not allowed.")); + } + Ok(value.into()) +} + +pub(crate) async fn pending_signup( + database: &Database, + headers: &HeaderMap, +) -> Result, ApiError> { + let Some(browser) = BrowserSecret::from_headers(headers, PENDING_COOKIE)? else { + return Ok(None); + }; + let pending = database + .federation() + .pending(&browser.digest()) + .await? + .ok_or_else(|| ApiError::bad_request("This signup has expired. Please start again."))?; + if pending.link_user_id.is_some() { + return Err(ApiError::forbidden( + "Use a passkey for your existing account to link this provider.", + )); + } + Ok(Some(pending)) +} +/// Called only inside the transaction that creates the account and first key. +pub(crate) async fn attach_signup( + tx: &mut DatabaseTransaction<'_>, + pending_id: TokenId, + headers: &HeaderMap, + user_id: UserId, +) -> Result<(), ApiError> { + let browser = + BrowserSecret::from_headers(headers, PENDING_COOKIE)?.ok_or_else(ApiError::unauthorized)?; + let pending = tx + .federation() + .consume_pending(pending_id, &browser.digest()) + .await?; + if pending.link_user_id.is_some() || tx.passkeys().list_active(user_id).await?.is_empty() { + return Err(ApiError::forbidden( + "Create your first passkey before continuing.", + )); + } + if let Some(email) = &pending.email { + if tx.emails().find_active_verified(email).await?.is_some() { + return Err(ApiError::forbidden( + "This email belongs to an existing account. Sign in with its passkey to link this provider.", + )); + } + tx.federation().set_first_email(user_id, email).await?; + } + tx.federation() + .insert_identity(&pending.identity(user_id)) + .await?; + FederationFlow::audit(tx, user_id, "federation.link", &pending.provider).await +} +// Identity policy stays in this application, rather than the persistence model. +trait PendingIdentity { + fn identity(&self, user_id: UserId) -> InsertExternalIdentity; +} +impl PendingIdentity for PendingFederation { + fn identity(&self, user_id: UserId) -> InsertExternalIdentity { + InsertExternalIdentity { + id: TokenId::new(), + user_id, + provider: self.provider.clone(), + issuer: self.issuer.clone(), + subject: self.subject.clone(), + linked_email: self.email.clone(), + } + } +} +pub(crate) const fn pending_cookie_clear() -> &'static str { + "__Host-piquel_federation_pending=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0" +} +async fn pending_view( + State(app): State, + headers: HeaderMap, +) -> Result, ApiError> { + let browser = BrowserSecret::from_headers(&headers, PENDING_COOKIE)? + .ok_or_else(ApiError::unauthorized)?; + let pending = app + .database + .federation() + .pending(&browser.digest()) + .await? + .ok_or_else(|| { + ApiError::bad_request("This sign-in attempt has expired. Please start again.") + })?; + Ok(Json( + serde_json::json!({"kind":if pending.link_user_id.is_some(){"link"}else{"signup"},"provider":pending.provider,"email":pending.email,"display_name":pending.display_name,"return_to":pending.return_to}), + )) +} +async fn confirm_link( + State(app): State, + headers: HeaderMap, +) -> Result { + let session = security::management(&app.database, &headers).await?; + let browser = BrowserSecret::from_headers(&headers, PENDING_COOKIE)? + .ok_or_else(ApiError::unauthorized)?; + let mut tx = app.database.begin().await?; + tx.users() + .find_active_by_id_for_update(session.user_id) + .await? + .ok_or_else(ApiError::unauthorized)?; + if !tx.sessions().management_active(session.id).await? { + return Err(ApiError::forbidden( + "Confirm with a passkey to change authentication settings.", + )); + } + let pending = tx + .federation() + .pending(&browser.digest()) + .await? + .ok_or_else(|| { + ApiError::bad_request("This sign-in attempt has expired. Please start again.") + })?; + if pending.link_user_id != Some(session.user_id) + || pending.link_session_id.is_some_and(|id| id != session.id) + { + return Err(ApiError::forbidden( + "Sign in with a passkey for the account this provider should be linked to.", + )); + } + let pending = tx + .federation() + .consume_pending(pending.id, &browser.digest()) + .await?; + if tx.passkeys().list_active(session.user_id).await?.is_empty() { + return Err(ApiError::forbidden("A passkey is required to continue.")); + } + // A duplicate callback can only confirm the identical subject for this account. + match tx + .federation() + .find_active(&pending.issuer, &pending.subject) + .await? + { + Some(identity) if identity.user_id == session.user_id => {} + Some(_) => { + return Err(ApiError::forbidden( + "This provider account is already linked to another Piquel account.", + )); + } + None => { + tx.federation() + .insert_identity(&pending.identity(session.user_id)) + .await?; + } + } + if let Some(email) = &pending.email { + tx.federation() + .set_first_email(session.user_id, email) + .await?; + } + FederationFlow::audit( + &mut tx, + session.user_id, + "federation.link", + &pending.provider, + ) + .await?; + tx.commit().await?; + let mut response = Json(serde_json::json!({"return_to":pending.return_to})).into_response(); + FederationFlow::append(&mut response, pending_cookie_clear())?; + Ok(response) +} +async fn cancel( + State(app): State, + headers: HeaderMap, +) -> Result { + if let Some(browser) = BrowserSecret::from_headers(&headers, PENDING_COOKIE)? { + app.database + .federation() + .cancel_pending(&browser.digest()) + .await?; + } + let mut response = StatusCode::NO_CONTENT.into_response(); + FederationFlow::append(&mut response, pending_cookie_clear())?; + Ok(response) +} +#[derive(Serialize)] +struct SocialIdentityView { + provider: String, + linked_email: Option, +} +async fn list_identities( + State(app): State, + headers: HeaderMap, +) -> Result>, ApiError> { + let session = security::session(&app.database, &headers).await?; + Ok(Json( + app.database + .federation() + .list_active(session.user_id) + .await? + .into_iter() + .map(|identity| SocialIdentityView { + provider: identity.provider, + linked_email: identity.linked_email, + }) + .collect(), + )) +} +async fn unlink( + State(app): State, + Path(provider): Path, + headers: HeaderMap, +) -> Result { + let provider = Provider::parse(&provider)?; + let session = security::management(&app.database, &headers).await?; + let mut tx = app.database.begin().await?; + tx.users() + .find_active_by_id_for_update(session.user_id) + .await? + .ok_or_else(ApiError::unauthorized)?; + if !tx.sessions().management_active(session.id).await? { + return Err(ApiError::forbidden( + "Confirm with a passkey to change authentication settings.", + )); + } + if !tx + .federation() + .unlink(session.user_id, provider.name()) + .await? + { + return Err(ApiError::bad_request( + "This provider is not linked to your account.", + )); + } + tx.sessions() + .revoke_other(session.user_id, session.id) + .await?; + FederationFlow::audit( + &mut tx, + session.user_id, + "federation.unlink", + provider.name(), + ) + .await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) +} + +struct VerifiedIdentity { + subject: String, + email: Option, + display_name: String, +} +impl FederationApplication { + async fn exchange( + &self, + provider: Provider, + code: &str, + verifier: &str, + nonce: &str, + ) -> Result { + let config = self + .providers + .get(provider.name()) + .ok_or_else(|| ApiError::bad_request("This sign-in provider is not configured."))?; + let secret = config.client_secret.resolve().map_err(ApiError::internal)?; + let secret = std::str::from_utf8(secret.expose_secret()).map_err(ApiError::internal)?; + let callback = self.callback_url(provider); + let endpoint = match provider { + Provider::GitHub => &self.endpoints.github_token, + Provider::Google => &self.endpoints.google_token, + }; + let response = self + .client + .post(endpoint) + .header(header::ACCEPT, "application/json") + .form(&[ + ("client_id", config.client_id.as_str()), + ("client_secret", secret), + ("code", code), + ("redirect_uri", &callback), + ("code_verifier", verifier), + ("grant_type", "authorization_code"), + ]) + .send() + .await + .map_err(ApiError::internal)?; + let identity = match provider { + Provider::GitHub => self.github_identity(response).await?, + Provider::Google => { + self.google_identity(response, &config.client_id, nonce) + .await? + } + }; + if identity.subject.is_empty() || identity.subject.len() > 255 { + return Err(ApiError::bad_request( + "The provider returned an invalid account identifier.", + )); + } + Ok(identity) + } + async fn github_identity( + &self, + response: reqwest::Response, + ) -> Result { + let token: GithubToken = Self::json(response).await?; + if token.access_token.is_empty() || token.access_token.len() > 8192 { + return Err(ApiError::bad_request( + "The provider sign-in could not be verified. Please try again.", + )); + } + let user: GithubUser = Self::json( + self.client + .get(&self.endpoints.github_user) + .bearer_auth(&token.access_token) + .send() + .await + .map_err(ApiError::internal)?, + ) + .await?; + let response = self + .client + .get(&self.endpoints.github_emails) + .bearer_auth(&token.access_token) + .send() + .await + .map_err(ApiError::internal)?; + let emails: Vec = if response.status() == StatusCode::FORBIDDEN { + Vec::new() + } else { + Self::json(response).await? + }; + let email = emails + .iter() + .find(|email| email.verified && email.primary) + .and_then(|email| normalize(&email.email).ok()) + .map(|email| email.as_str().to_owned()); + if user.id == 0 { + return Err(ApiError::bad_request( + "The provider returned an invalid account identifier.", + )); + } + Ok(VerifiedIdentity { + subject: user.id.to_string(), + email, + display_name: user + .name + .filter(|name| !name.trim().is_empty()) + .unwrap_or(user.login) + .chars() + .take(80) + .collect(), + }) + } + async fn google_identity( + &self, + response: reqwest::Response, + client_id: &str, + nonce: &str, + ) -> Result { + let token: GoogleToken = Self::json(response).await?; + if token.id_token.len() > 8192 { + return Err(ApiError::bad_request( + "The provider sign-in could not be verified. Please try again.", + )); + } + let header = decode_header(&token.id_token).map_err(|_| { + ApiError::bad_request("The provider sign-in could not be verified. Please try again.") + })?; + if header.alg != Algorithm::RS256 { + return Err(ApiError::bad_request( + "The provider sign-in could not be verified. Please try again.", + )); + } + let kid = header.kid.ok_or_else(|| { + ApiError::bad_request("The provider sign-in could not be verified. Please try again.") + })?; + let jwks: GoogleJwks = Self::json( + self.client + .get(&self.endpoints.google_keys) + .send() + .await + .map_err(ApiError::internal)?, + ) + .await?; + let jwk = jwks + .keys + .into_iter() + .find(|key| { + key.kid == kid + && key.kty == "RSA" + && key.alg.as_deref().is_none_or(|alg| alg == "RS256") + && key.key_use.as_deref().is_none_or(|usage| usage == "sig") + }) + .ok_or_else(|| { + ApiError::bad_request( + "The provider sign-in could not be verified. Please try again.", + ) + })?; + let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(|_| { + ApiError::bad_request("The provider sign-in could not be verified. Please try again.") + })?; + let mut validation = Validation::new(Algorithm::RS256); + validation.set_audience(&[client_id]); + validation.set_issuer(&[Provider::Google.issuer(), "accounts.google.com"]); + validation.leeway = 30; + let claims = decode::(&token.id_token, &key, &validation) + .map_err(|_| { + ApiError::bad_request( + "The provider sign-in could not be verified. Please try again.", + ) + })? + .claims; + if claims.nonce != nonce + || claims.sub.is_empty() + || claims.exp <= Utc::now().timestamp() + || claims.iat > Utc::now().timestamp() + 30 + || claims.azp.as_deref().is_some_and(|azp| azp != client_id) + { + return Err(ApiError::bad_request( + "The provider sign-in could not be verified. Please try again.", + )); + } + let email = claims + .email + .filter(|_| claims.email_verified) + .and_then(|email| normalize(&email).ok()) + .map(|email| email.as_str().to_owned()); + Ok(VerifiedIdentity { + subject: claims.sub, + email, + display_name: claims + .name + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| "Google user".into()) + .chars() + .take(80) + .collect(), + }) + } + /// Bound even chunked provider responses before parsing them. + async fn json(response: reqwest::Response) -> Result { + let mut response = response.error_for_status().map_err(ApiError::internal)?; + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(ApiError::internal)? { + if body.len() + chunk.len() > 65536 { + return Err(ApiError::bad_request( + "The provider returned an unexpected response. Please try again.", + )); + } + body.extend_from_slice(&chunk); + } + serde_json::from_slice(&body).map_err(|_| { + ApiError::bad_request("The provider returned an unexpected response. Please try again.") + }) + } +} +#[derive(Deserialize)] +struct GithubToken { + access_token: String, +} +#[derive(Deserialize)] +struct GithubUser { + id: u64, + name: Option, + login: String, +} +#[derive(Deserialize)] +struct GithubEmail { + email: String, + verified: bool, + primary: bool, +} +#[derive(Deserialize)] +struct GoogleToken { + id_token: String, +} +#[derive(Clone, Deserialize)] +struct GoogleClaims { + sub: String, + exp: i64, + iat: i64, + nonce: String, + azp: Option, + email: Option, + #[serde(default)] + email_verified: bool, + name: Option, +} +#[derive(Deserialize)] +struct GoogleJwks { + keys: Vec, +} +#[derive(Deserialize)] +struct GoogleJwk { + kid: String, + kty: String, + alg: Option, + #[serde(rename = "use")] + key_use: Option, + n: String, + e: String, +} + +struct BrowserSecret(String); +impl BrowserSecret { + fn random() -> Self { + let mut bytes = [0_u8; 32]; + OsRng.fill_bytes(&mut bytes); + Self(URL_SAFE_NO_PAD.encode(bytes)) + } + fn digest(&self) -> Vec { + Sha256::digest(self.0.as_bytes()).to_vec() + } + fn from_headers(headers: &HeaderMap, name: &str) -> Result, ApiError> { + let prefix = format!("{name}="); + let mut found = None; + for header in headers.get_all(header::COOKIE) { + let header = header.to_str().map_err(|_| { + ApiError::bad_request("This browser session is invalid. Please start again.") + })?; + for part in header.split(';').map(str::trim) { + if let Some(value) = part.strip_prefix(&prefix) { + if found.is_some() + || value.len() != 43 + || URL_SAFE_NO_PAD.decode(value).is_err() + { + return Err(ApiError::bad_request( + "This browser session is invalid. Please start again.", + )); + } + found = Some(Self(value.into())); + } + } + } + Ok(found) + } + fn cookie(&self, name: &str, max_age: u32) -> String { + format!( + "{name}={}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={max_age}", + self.0 + ) + } +} +struct FederationFlow; +impl FederationFlow { + fn append(response: &mut Response, cookie: &str) -> Result<(), ApiError> { + response.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_str(cookie).map_err(ApiError::internal)?, + ); + Ok(()) + } + const fn clear_flow() -> &'static str { + "__Host-piquel_federation=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0" + } + async fn audit( + tx: &mut DatabaseTransaction<'_>, + user_id: UserId, + action: &str, + provider: &str, + ) -> Result<(), ApiError> { + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: action.into(), + outcome: "success".into(), + request_metadata: serde_json::json!({"provider":provider}), + }) + .await?; + Ok(()) + } +} + +#[cfg(test)] +#[path = "federation_tests.rs"] +mod tests; diff --git a/apps/auth-service/src/federation_tests.rs b/apps/auth-service/src/federation_tests.rs new file mode 100644 index 000000000..98b4b8f44 --- /dev/null +++ b/apps/auth-service/src/federation_tests.rs @@ -0,0 +1,685 @@ +use super::*; +use axum::{ + body::{Body, to_bytes}, + http::{Method, Request}, + routing::post, +}; +use piquel_repository::{DatabaseConfig, InsertPasskey, InsertUser, InsertVerifiedEmail}; +use tower::ServiceExt; + +struct TestApp { + app: FederationApplication, + task: tokio::task::JoinHandle<()>, + secret_file: std::path::PathBuf, + subject: String, +} +impl Drop for TestApp { + fn drop(&mut self) { + self.task.abort(); + let _ = std::fs::remove_file(&self.secret_file); + } +} +impl TestApp { + async fn new() -> Self { + Self::with_email(None).await + } + async fn with_email(email: Option<&str>) -> Self { + let url = std::env::var("TEST_DATABASE_URL") + .expect("TEST_DATABASE_URL must name an isolated migrated PostgreSQL database"); + let database = Database::connect( + DatabaseConfig::new_development(&url, 5, StdDuration::from_secs(5)) + .expect("database configuration"), + ) + .await + .expect("database"); + database.run_migrations().await.expect("migrations"); + let subject = OsRng.next_u64().max(1); + let emails = email.map_or_else( + || serde_json::json!([]), + |email| serde_json::json!([{"email":email,"primary":true,"verified":true}]), + ); + let mock = Router::new() + .route( + "/token", + post(|| async { Json(serde_json::json!({"access_token":"mock-token"})) }), + ) + .route( + "/user", + get(move || async move { + Json(serde_json::json!({"id":subject,"name":"Social User","login":"social"})) + }), + ) + .route( + "/emails", + get(move || { + let emails = emails.clone(); + async move { Json(emails) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("mock listener"); + let base = format!("http://{}", listener.local_addr().expect("mock address")); + let task = tokio::spawn(async move { + axum::serve(listener, mock).await.expect("mock server"); + }); + let secret_file = + std::env::temp_dir().join(format!("piquel-federation-test-{}", TokenId::new())); + std::fs::write(&secret_file, "test-secret").expect("mock provider secret"); + let config = ProviderConfiguration { + client_id: "test-client".into(), + client_secret: SecretReference::parse(&format!("file://{}", secret_file.display())) + .expect("secret reference"), + }; + let mut app = FederationApplication::new( + database, + &Url::parse("https://auth.piquel.fr/").expect("origin"), + Some(config), + None, + ) + .expect("federation"); + app.endpoints.github_token = format!("{base}/token"); + app.endpoints.github_user = format!("{base}/user"); + app.endpoints.github_emails = format!("{base}/emails"); + Self { + app, + task, + secret_file, + subject: subject.to_string(), + } + } + async fn callback(&self) -> Response { + let router = routes(self.app.clone()); + let response = router + .clone() + .oneshot(request( + Method::POST, + "/login/github/start", + None, + &serde_json::json!({}), + )) + .await + .expect("start"); + let cookie = response.headers()[header::SET_COOKIE] + .to_str() + .expect("cookie") + .split(';') + .next() + .expect("pair") + .to_owned(); + let body = json(response).await; + let url = Url::parse(body["redirect_url"].as_str().expect("redirect")).expect("url"); + let state = url + .query_pairs() + .find(|(name, _)| name == "state") + .expect("state") + .1 + .into_owned(); + router + .oneshot(request( + Method::GET, + &format!("/login/github/callback?state={state}&code=mock-code"), + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("callback") + } + async fn user(&self, email: Option<&str>, with_key: bool) -> UserId { + let id = UserId::new(); + let mut tx = self.app.database.begin().await.expect("transaction"); + tx.users() + .insert(&InsertUser { + id, + username: format!("fed_{}", TokenId::new()).replace('-', ""), + display_name: "Federation Test".into(), + }) + .await + .expect("user"); + if let Some(email) = email { + tx.emails() + .insert_verified(&InsertVerifiedEmail { + id: TokenId::new(), + user_id: id, + normalized_email: email.into(), + is_primary: true, + verified_at: Utc::now(), + }) + .await + .expect("email"); + } + if with_key { + self.key(&mut tx, id).await; + } + tx.commit().await.expect("commit"); + id + } + async fn key(&self, tx: &mut DatabaseTransaction<'_>, user_id: UserId) { + // Federation only checks key presence; cryptographic ceremony coverage lives in passkey tests. + tx.passkeys() + .insert(&InsertPasskey { + id: TokenId::new(), + credential_id: TokenId::new().to_string().into_bytes(), + user_id, + credential: serde_json::json!({}), + friendly_name: "Existing key".into(), + }) + .await + .expect("key"); + } + async fn pending( + &self, + owner: Option, + email: Option<&str>, + ) -> (PendingFederation, HeaderMap) { + let secret = BrowserSecret::random(); + let pending = PendingFederation { + id: TokenId::new(), + browser_digest: secret.digest(), + provider: "github".into(), + issuer: Provider::GitHub.issuer().into(), + subject: TokenId::new().to_string(), + email: email.map(str::to_owned), + display_name: "New social account".into(), + return_to: "/".into(), + link_user_id: owner, + link_session_id: None, + expires_at: Utc::now() + Duration::minutes(5), + }; + self.app + .database + .federation() + .insert_pending(&pending) + .await + .expect("pending identity"); + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(&format!("{PENDING_COOKIE}={}", secret.0)).expect("cookie"), + ); + (pending, headers) + } + async fn session(&self, user_id: UserId, grant: bool) -> (SessionId, String) { + let mut tx = self.app.database.begin().await.expect("transaction"); + let cookie = security::create_session(&mut tx, user_id, AuthenticationMethod::Federation) + .await + .expect("session"); + let raw = cookie.split(';').next().expect("cookie pair").to_owned(); + tx.commit().await.expect("commit"); + let mut headers = HeaderMap::new(); + headers.insert(header::COOKIE, HeaderValue::from_str(&raw).expect("cookie")); + let session = security::session(&self.app.database, &headers) + .await + .expect("active session"); + if grant { + self.app + .database + .sessions() + .grant_management(session.id) + .await + .expect("grant"); + } + (session.id, raw) + } +} +fn request( + method: Method, + path: &str, + cookie: Option<&str>, + body: &serde_json::Value, +) -> Request { + let mut request = Request::builder() + .method(method) + .uri(path) + .header(header::CONTENT_TYPE, "application/json"); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, cookie); + } + request.body(Body::from(body.to_string())).expect("request") +} +async fn json(response: Response) -> serde_json::Value { + serde_json::from_slice(&to_bytes(response.into_body(), 65536).await.expect("body")) + .expect("JSON") +} + +#[test] +fn return_destinations_and_browser_bindings_are_strict() { + for path in [ + "//evil.test", + "/\\evil.test", + "https://evil.test", + "/login#x", + "/\n/evil", + ] { + assert!(validate_return_to(Some(path)).is_err(), "{path}"); + } + assert_eq!( + validate_return_to(Some("/oauth/authorize?request=abc")).expect("local return"), + "/oauth/authorize?request=abc" + ); + let secret = BrowserSecret::random(); + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(&format!( + "{PENDING_COOKIE}={0}; {PENDING_COOKIE}={0}", + secret.0 + )) + .expect("cookie"), + ); + assert!(BrowserSecret::from_headers(&headers, PENDING_COOKIE).is_err()); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn provider_mock_callback_requires_browser_state_and_stays_pending() { + let test = TestApp::new().await; + let router = routes(test.app.clone()); + let response = router + .clone() + .oneshot(request( + Method::POST, + "/login/github/start", + None, + &serde_json::json!({}), + )) + .await + .expect("start"); + assert_eq!(response.status(), StatusCode::OK); + let cookie = response.headers()[header::SET_COOKIE] + .to_str() + .expect("cookie") + .split(';') + .next() + .expect("pair") + .to_owned(); + let body = json(response).await; + let url = Url::parse(body["redirect_url"].as_str().expect("redirect")).expect("url"); + let state = url + .query_pairs() + .find(|(key, _)| key == "state") + .expect("state") + .1 + .into_owned(); + let path = format!("/login/github/callback?code=mock-code&state={state}"); + let response = router + .clone() + .oneshot(request(Method::GET, &path, None, &serde_json::Value::Null)) + .await + .expect("unbound callback"); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + let response = router + .clone() + .oneshot(request( + Method::GET, + &path, + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("callback"); + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert_eq!(response.headers()[header::LOCATION], "/login?social=signup"); + assert!( + !response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .any(|value| value + .to_str() + .expect("cookie") + .starts_with("__Host-piquel_session=")) + ); + let response = router + .oneshot(request( + Method::GET, + &path, + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("replay"); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn onboarding_commits_only_with_first_key_and_browser_and_never_claims_existing_email() { + let test = TestApp::new().await; + let (pending, headers) = test.pending(None, None).await; + assert!( + pending_signup(&test.app.database, &headers) + .await + .expect("pending signup") + .is_some() + ); + let user = test.user(None, false).await; + let mut tx = test.app.database.begin().await.expect("tx"); + assert!( + attach_signup(&mut tx, pending.id, &headers, user) + .await + .is_err() + ); + tx.rollback().await.expect("rollback"); + let mut tx = test.app.database.begin().await.expect("tx"); + test.key(&mut tx, user).await; + assert!( + attach_signup(&mut tx, pending.id, &HeaderMap::new(), user) + .await + .is_err() + ); + attach_signup(&mut tx, pending.id, &headers, user) + .await + .expect("first key authorizes signup"); + tx.commit().await.expect("commit"); + assert_eq!( + test.app + .database + .federation() + .find_active(&pending.issuer, &pending.subject) + .await + .expect("identity") + .expect("linked") + .user_id, + user + ); + let email = format!("{}@example.com", TokenId::new()); + test.user(Some(&email), true).await; + let (pending, headers) = test.pending(None, Some(&email)).await; + let mut tx = test.app.database.begin().await.expect("tx"); + assert!( + attach_signup(&mut tx, pending.id, &headers, user) + .await + .is_err() + ); + tx.rollback().await.expect("rollback"); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn linking_requires_target_grant_and_unlink_releases_subject_without_changing_email() { + let test = TestApp::new().await; + let email = format!("{}@example.com", TokenId::new()); + let target = test.user(Some(&email), true).await; + let other = test.user(None, true).await; + let observed = format!("{}@example.com", TokenId::new()); + let (pending, pending_headers) = test.pending(Some(target), Some(&observed)).await; + let (_, other_cookie) = test.session(other, true).await; + let (target_session, target_cookie) = test.session(target, false).await; + let (other_session, _) = test.session(target, false).await; + let pending_cookie = pending_headers[header::COOKIE] + .to_str() + .expect("pending cookie"); + let router = routes(test.app.clone()); + for cookie in [&other_cookie, &target_cookie] { + let response = router + .clone() + .oneshot(request( + Method::POST, + "/login/social/link", + Some(&format!("{cookie}; {pending_cookie}")), + &serde_json::json!({}), + )) + .await + .expect("link rejection"); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + } + test.app + .database + .sessions() + .grant_management(target_session) + .await + .expect("grant"); + let response = router + .clone() + .oneshot(request( + Method::POST, + "/login/social/link", + Some(&format!("{target_cookie}; {pending_cookie}")), + &serde_json::json!({}), + )) + .await + .expect("link"); + assert_eq!(response.status(), StatusCode::OK); + assert!( + test.app + .database + .sessions() + .find_active_by_id(other_session) + .await + .expect("other session") + .is_some() + ); + assert_eq!( + test.app + .database + .emails() + .find_active_verified(&email) + .await + .expect("email") + .expect("owner") + .user_id, + target + ); + assert!( + test.app + .database + .emails() + .find_active_verified(&observed) + .await + .expect("observation") + .is_none() + ); + let response = router + .oneshot(request( + Method::DELETE, + "/account/social-identities/github", + Some(&target_cookie), + &serde_json::json!({}), + )) + .await + .expect("unlink"); + assert_eq!(response.status(), StatusCode::NO_CONTENT); + assert!( + test.app + .database + .sessions() + .find_active_by_id(other_session) + .await + .expect("revoked other session") + .is_none() + ); + test.app + .database + .federation() + .insert_identity(&pending.identity(other)) + .await + .expect("unlinked subject reusable"); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn google_mock_validates_signature_audience_nonce_and_expiry_without_requiring_email() { + use jsonwebtoken::{EncodingKey, Header, encode}; + let mut test = TestApp::new().await; + let rsa = openssl::rsa::Rsa::generate(2048).expect("RSA test key"); + let encoding = + EncodingKey::from_rsa_pem(&rsa.private_key_to_pem().expect("PEM")).expect("JWT key"); + let mut header = Header::new(Algorithm::RS256); + header.kid = Some("google-test".into()); + let mut claims = serde_json::json!({"iss":"https://accounts.google.com","sub":"12345","aud":"test-client","iat":Utc::now().timestamp(),"exp":Utc::now().timestamp()+300,"nonce":"test-nonce"}); + let valid = encode(&header, &claims, &encoding).expect("signed token"); + claims["aud"] = serde_json::json!("another-client"); + let wrong_audience = encode(&header, &claims, &encoding).expect("signed token"); + claims["aud"] = serde_json::json!("test-client"); + claims["exp"] = serde_json::json!(Utc::now().timestamp() - 120); + let expired = encode(&header, &claims, &encoding).expect("signed token"); + let other_rsa = openssl::rsa::Rsa::generate(2048).expect("untrusted key"); + let other_encoding = + EncodingKey::from_rsa_pem(&other_rsa.private_key_to_pem().expect("PEM")).expect("JWT key"); + claims["exp"] = serde_json::json!(Utc::now().timestamp() + 300); + let wrong_signature = + encode(&header, &claims, &other_encoding).expect("untrusted signed token"); + let keys = serde_json::json!({"keys":[{"kid":"google-test","kty":"RSA","alg":"RS256","use":"sig","n":URL_SAFE_NO_PAD.encode(rsa.n().to_vec()),"e":URL_SAFE_NO_PAD.encode(rsa.e().to_vec())}]}); + let tokens = Arc::new(HashMap::from([ + ("valid".to_owned(), valid), + ("wrong-audience".to_owned(), wrong_audience), + ("expired".to_owned(), expired), + ("wrong-signature".to_owned(), wrong_signature), + ])); + let mock = Router::new() + .route( + "/keys", + get(move || { + let keys = keys.clone(); + async move { Json(keys) } + }), + ) + .route( + "/token/{kind}", + get(move |Path(kind): Path| { + let tokens = tokens.clone(); + async move { Json(serde_json::json!({"id_token":tokens[&kind]})) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("mock listener"); + let base = format!("http://{}", listener.local_addr().expect("address")); + let task = tokio::spawn(async move { + axum::serve(listener, mock).await.expect("mock server"); + }); + test.app.endpoints.google_keys = format!("{base}/keys"); + let response = test + .app + .client + .get(format!("{base}/token/valid")) + .send() + .await + .expect("valid response"); + let identity = test + .app + .google_identity(response, "test-client", "test-nonce") + .await + .expect("valid Google identity without email"); + assert_eq!(identity.subject, "12345"); + assert!(identity.email.is_none()); + for (kind, nonce) in [ + ("valid", "wrong-nonce"), + ("wrong-audience", "test-nonce"), + ("expired", "test-nonce"), + ("wrong-signature", "test-nonce"), + ] { + let response = test + .app + .client + .get(format!("{base}/token/{kind}")) + .send() + .await + .expect("mock response"); + assert!( + test.app + .google_identity(response, "test-client", nonce) + .await + .is_err(), + "{kind} {nonce}" + ); + } + task.abort(); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn callback_email_collision_never_links_and_known_subject_never_bootstraps_a_missing_key() { + let observed = format!("{}@example.com", TokenId::new()); + let original = format!("{}@example.com", TokenId::new()); + let test = TestApp::with_email(Some(&observed)).await; + let email_owner = test.user(Some(&observed), true).await; + let response = test.callback().await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert_eq!(response.headers()[header::LOCATION], "/login?social=link"); + assert!( + test.app + .database + .federation() + .find_active(Provider::GitHub.issuer(), &test.subject) + .await + .expect("identity") + .is_none() + ); + let subject_owner = test.user(Some(&original), false).await; + test.app + .database + .federation() + .insert_identity(&InsertExternalIdentity { + id: TokenId::new(), + user_id: subject_owner, + provider: "github".into(), + issuer: Provider::GitHub.issuer().into(), + subject: test.subject.clone(), + linked_email: Some(original.clone()), + }) + .await + .expect("known identity"); + let response = test.callback().await; + assert_eq!( + response.status(), + StatusCode::UNAUTHORIZED, + "known accounts cannot bootstrap from social login" + ); + let mut tx = test.app.database.begin().await.expect("tx"); + test.key(&mut tx, subject_owner).await; + tx.commit().await.expect("commit"); + let response = test.callback().await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert_eq!(response.headers()[header::LOCATION], "/"); + let session_cookie = response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|value| value.to_str().expect("cookie")) + .find(|cookie| cookie.starts_with("__Host-piquel_session=")) + .expect("session cookie") + .split(';') + .next() + .expect("cookie pair"); + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(session_cookie).expect("cookie"), + ); + let session = security::session(&test.app.database, &headers) + .await + .expect("social session"); + assert_eq!( + session.user_id, subject_owner, + "stable subject takes priority over email observation" + ); + assert!( + security::management(&test.app.database, &headers) + .await + .is_err() + ); + assert_eq!( + test.app + .database + .emails() + .find_active_verified(&original) + .await + .expect("original email") + .expect("owner") + .user_id, + subject_owner + ); + assert_eq!( + test.app + .database + .emails() + .find_active_verified(&observed) + .await + .expect("observed email") + .expect("owner") + .user_id, + email_owner + ); +} diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 3a107dfcd..f4ce9ce18 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -1,192 +1,325 @@ -//! The deployable Piquel authentication authority. -// Future policy modules remain private to this application. - -use async_trait::async_trait; -use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::get}; -use piquel_configuration::{ConfigurationError, PublicUrl, SecretReference, socket_addr}; -use piquel_repository::{Database, DatabaseConfig}; -use std::{env, net::SocketAddr, sync::Arc, time::Duration}; - -#[allow(dead_code)] -mod account; -#[allow(dead_code)] -mod audit; -#[allow(dead_code)] +//! One authentication authority: browser flows, settings API, and OIDC. +mod assets; mod email; -#[allow(dead_code)] -mod event_log; +mod federation; +mod oidc; mod passkey; -pub use passkey::PasskeyApplication; -#[allow(dead_code)] -mod session; -mod signing; -pub use signing::Es256KeyProvider; +mod security; + +use federation::{FederationApplication, ProviderConfiguration}; +use oidc::{OidcApplication, Rs256KeyProvider}; +use passkey::PasskeyApplication; -/// Typed auth-service configuration. -#[derive(Clone, Debug)] +use anyhow::{Context, Result}; +use axum::{Json, Router, extract::DefaultBodyLimit, middleware, routing::get}; +use piquel_configuration::{PublicUrl, SecretReference}; +use piquel_repository::{BootstrapOidcClient, Database, DatabaseConfig}; +use serde::Deserialize; +use std::{env, net::SocketAddr, sync::Arc, time::Duration}; +use url::Url; + +/// Runtime configuration; secret values are never logged. pub struct AuthConfig { - /// Public issuer/base URL. - pub public_base_url: PublicUrl, - /// Public HTTP listener address. + public_base_url: Url, + settings_url: Url, + /// Address bound by the single public HTTP listener. pub public_listener: SocketAddr, - /// Reserved private RPC listener address; no RPC is exposed yet. - pub internal_listener: SocketAddr, - /// Database connection settings. - pub database: DatabaseConfig, - /// Key-provider locator, never a literal key. - pub key_provider: SecretReference, - /// `WebAuthn` relying-party identifier. - pub webauthn_rp_id: String, - /// Stable identifier embedded in signed-token headers. - pub signing_key_id: String, + key_provider: Option, + signing_key_id: String, + development: bool, + invite_required: bool, + github: Option, + google: Option, + clients: Vec, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ClientConfig { + id: String, + display_name: String, + redirect_uris: Vec, + #[serde(default)] + post_logout_uris: Vec, + #[serde(default = "ClientConfig::scopes")] + allowed_scopes: Vec, + #[serde(default)] + allow_refresh: bool, + #[serde(default)] + trusted: bool, + #[serde(default = "ClientConfig::enabled")] + enabled: bool, + client_secret: Option, +} +impl ClientConfig { + fn scopes() -> Vec { + vec!["openid".into(), "profile".into(), "email".into()] + } + fn enabled() -> bool { + true + } + fn into_client(self) -> Result { + let secret = self + .client_secret + .map(|reference| -> Result> { + let secret = SecretReference::parse(&reference)?.resolve()?; + OidcApplication::client_secret_hash(std::str::from_utf8(secret.expose_secret())?) + }) + .transpose()?; + Ok(BootstrapOidcClient { + allowed_audiences: vec![self.id.clone()], + id: self.id, + display_name: self.display_name, + redirect_uris: self.redirect_uris, + post_logout_uris: self.post_logout_uris, + allowed_scopes: self.allowed_scopes, + allow_refresh: self.allow_refresh, + trusted: self.trusted, + enabled: self.enabled, + client_secret_hash: secret, + }) + } } impl AuthConfig { - /// Loads the minimum service configuration from the environment. + fn required(name: &'static str) -> Result { + env::var(name).with_context(|| format!("{name} is required")) + } + fn flag(name: &str, default: bool) -> Result { + match env::var(name).as_deref() { + Ok("true") => Ok(true), + Ok("false") => Ok(false), + Err(env::VarError::NotPresent) => Ok(default), + _ => anyhow::bail!("{name} must be true or false"), + } + } + fn provider(name: &str) -> Result> { + let id = env::var(format!("AUTH_{name}_CLIENT_ID")).ok(); + let secret = env::var(format!("AUTH_{name}_CLIENT_SECRET")).ok(); + match (id, secret) { + (None, None) => Ok(None), + (Some(client_id), Some(secret)) => Ok(Some(ProviderConfiguration { + client_id, + client_secret: SecretReference::parse(&secret)?, + })), + _ => { + anyhow::bail!("Configure both AUTH_{name}_CLIENT_ID and AUTH_{name}_CLIENT_SECRET") + } + } + } + /// Loads database settings independently for migration/invitation commands. /// /// # Errors - /// - /// Returns an error when a required setting is absent or malformed. - pub fn from_environment() -> Result { - let required = |name| env::var(name).map_err(|_| ConfigurationError::Missing(name)); - let database_url = required("AUTH_DATABASE_URL")?; - let development = env::var("AUTH_DEVELOPMENT_MODE").is_ok_and(|value| value == "true"); - let public_base_url = if development { - PublicUrl::parse_development(&required("AUTH_PUBLIC_BASE_URL")?)? + /// Returns missing configuration or invalid database/TLS settings. + pub fn database_from_environment() -> Result { + let url = Self::required("AUTH_DATABASE_URL")?; + Ok(if Self::flag("AUTH_DEVELOPMENT_MODE", false)? { + DatabaseConfig::new_development(&url, 10, Duration::from_secs(5))? } else { - PublicUrl::parse(&required("AUTH_PUBLIC_BASE_URL")?)? + DatabaseConfig::new(&url, 10, Duration::from_secs(5))? + }) + } + /// Validates service, provider, and client settings before startup. + /// + /// # Errors + /// Returns invalid settings, unreadable client configuration, or unresolved secrets. + pub fn from_environment() -> Result { + let development = Self::flag("AUTH_DEVELOPMENT_MODE", false)?; + let parse = |value: &str| -> Result { + Ok(if development { + PublicUrl::parse_development(value)? + } else { + PublicUrl::parse(value)? + } + .as_url() + .clone()) }; - let database = if development { - DatabaseConfig::new_development(database_url, 10, Duration::from_secs(5)) - } else { - DatabaseConfig::new(database_url, 10, Duration::from_secs(5)) - } - .map_err(|_| ConfigurationError::Invalid { - name: "AUTH_DATABASE_URL", - })?; + let public_base_url = parse(&Self::required("AUTH_PUBLIC_BASE_URL")?)?; + anyhow::ensure!( + public_base_url.path() == "/" + && public_base_url.username().is_empty() + && public_base_url.password().is_none(), + "AUTH_PUBLIC_BASE_URL must be an origin" + ); + let settings_url = parse( + &env::var("AUTH_SETTINGS_URL").unwrap_or_else(|_| "https://piquel.fr/settings".into()), + )?; + anyhow::ensure!( + settings_url.username().is_empty() && settings_url.password().is_none(), + "AUTH_SETTINGS_URL must not contain credentials" + ); + let clients = env::var("AUTH_CLIENTS_FILE") + .ok() + .map(|path| -> Result> { + let inputs: Vec = + serde_json::from_slice(&std::fs::read(path).context("read OIDC clients file")?) + .context("parse OIDC clients file")?; + inputs.into_iter().map(ClientConfig::into_client).collect() + }) + .transpose()? + .unwrap_or_default(); + let unique: std::collections::HashSet<_> = + clients.iter().map(|client| &client.id).collect(); + anyhow::ensure!( + unique.len() == clients.len(), + "AUTH_CLIENTS_FILE contains duplicate client IDs" + ); + let key_provider = env::var("AUTH_KEY_PROVIDER") + .ok() + .map(|v| SecretReference::parse(&v)) + .transpose()?; + anyhow::ensure!( + development || key_provider.is_some(), + "AUTH_KEY_PROVIDER is required outside development" + ); Ok(Self { public_base_url, - public_listener: socket_addr( - "AUTH_PUBLIC_LISTENER", - &required("AUTH_PUBLIC_LISTENER")?, - )?, - internal_listener: socket_addr( - "AUTH_INTERNAL_LISTENER", - &required("AUTH_INTERNAL_LISTENER")?, - )?, - database, - key_provider: SecretReference::parse(&required("AUTH_KEY_PROVIDER")?)?, - webauthn_rp_id: required("AUTH_WEBAUTHN_RP_ID")?, - signing_key_id: required("AUTH_SIGNING_KEY_ID")?, - }) - } -} - -/// Dependency check used by readiness without minting credentials. -#[async_trait] -pub trait Readiness: Send + Sync { - /// Returns only when every required dependency is usable. - async fn check(&self) -> Result<(), ()>; -} - -/// Production readiness checks `PostgreSQL` and resolves the configured key. -pub struct ProductionReadiness { - database: Database, - key_provider: SecretReference, -} -impl ProductionReadiness { - /// Builds the production readiness dependency set. - #[must_use] - pub const fn new(database: Database, key_provider: SecretReference) -> Self { - Self { - database, + settings_url, + public_listener: env::var("AUTH_PUBLIC_LISTENER") + .unwrap_or_else(|_| "127.0.0.1:8080".into()) + .parse()?, key_provider, - } - } -} -#[async_trait] -impl Readiness for ProductionReadiness { - async fn check(&self) -> Result<(), ()> { - self.database.health_check().await.map_err(|_| ())?; - tokio::time::timeout(Duration::from_secs(2), async { - self.key_provider.resolve().map(|_| ()).map_err(|_| ()) + signing_key_id: env::var("AUTH_SIGNING_KEY_ID").unwrap_or_else(|_| "primary".into()), + development, + invite_required: Self::flag("AUTH_INVITE_REQUIRED", true)?, + github: Self::provider("GITHUB")?, + google: Self::provider("GOOGLE")?, + clients, }) - .await - .map_err(|_| ())? } -} - -#[derive(Clone)] -struct AppState { - readiness: Arc, -} + fn oidc(&self, database: &Database) -> Result { + let (keys, refresh_secret) = if let Some(reference) = &self.key_provider { + let secret = reference.resolve()?; + let pem = std::str::from_utf8(secret.expose_secret()) + .context("signing key is not UTF-8 PEM")?; + ( + Rs256KeyProvider::from_pem(&self.signing_key_id, pem)?, + secret.expose_secret().to_vec(), + ) + } else { + ( + Rs256KeyProvider::generate_for_development(&self.signing_key_id)?, + security::BrowserSecret::new().encoded().into_bytes(), + ) + }; + let keys = Arc::new(keys); + let oidc = if self.development { + OidcApplication::new_development( + database.clone(), + &self.public_base_url, + &refresh_secret, + keys, + ) + } else { + OidcApplication::new( + database.clone(), + &self.public_base_url, + &refresh_secret, + keys, + ) + } + .map_err(|()| anyhow::anyhow!("invalid OIDC configuration"))?; -/// Builds the public health-only router. Liveness has no dependencies; readiness fails closed. -pub fn router(readiness: Arc, passkeys: Option) -> Router { - let health = Router::new() - .route("/health/live", get(|| async { StatusCode::NO_CONTENT })) - .route("/health/ready", get(ready)) - .with_state(AppState { readiness }); - if let Some(passkeys) = passkeys { - health.merge(passkey::routes(passkeys)) - } else { - health + Ok(oidc) } } -async fn ready(State(state): State) -> impl IntoResponse { - match state.readiness.check().await { - Ok(()) => StatusCode::NO_CONTENT, - Err(()) => StatusCode::SERVICE_UNAVAILABLE, +/// Builds the service with browser-origin protection around every public endpoint. +/// +/// # Errors +/// Returns signing, provider, or database errors before accepting requests. +pub async fn router(config: &AuthConfig, database: Database) -> Result { + let oidc = config.oidc(&database)?; + let passkeys = PasskeyApplication::new( + database.clone(), + config + .public_base_url + .host_str() + .context("auth host missing")?, + &config.public_base_url, + config.invite_required, + )?; + let federation = FederationApplication::new( + database.clone(), + &config.public_base_url, + config.github.clone(), + config.google.clone(), + )? + .with_settings_url(&config.settings_url)?; + let mut tx = database.begin().await?; + tx.oidc().disable_all_clients().await?; + for client in &config.clients { + tx.oidc().bootstrap_client(client).await?; } + tx.commit().await?; + let provider_names = [ + ("github", config.github.is_some()), + ("google", config.google.is_some()), + ] + .into_iter() + .filter_map(|(name, enabled)| enabled.then_some(name)) + .collect::>(); + let public_config = serde_json::json!({"settings_url":config.settings_url,"providers":provider_names,"invite_required":config.invite_required}); + let health = database.clone(); + let policy = security::HttpSecurity { + database, + auth_origin: config.public_base_url.origin().ascii_serialization(), + settings_origin: config.settings_url.origin().ascii_serialization(), + client_origins: Arc::new( + config + .clients + .iter() + .filter(|c| c.client_secret_hash.is_none()) + .flat_map(|c| &c.redirect_uris) + .filter_map(|uri| { + Url::parse(uri) + .ok() + .map(|url| url.origin().ascii_serialization()) + }) + .collect(), + ), + }; + Ok(Router::new() + .route( + "/health/live", + get(|| async { axum::http::StatusCode::NO_CONTENT }), + ) + .route( + "/health/ready", + get(move || { + let db = health.clone(); + async move { + db.health_check() + .await + .map(|()| axum::http::StatusCode::NO_CONTENT) + .map_err(security::ApiError::from) + } + }), + ) + .route( + "/config", + get(move || { + let value = public_config.clone(); + async { Json(value) } + }), + ) + .merge(passkeys.routes()) + .merge(oidc::routes(oidc)) + .merge(federation::routes(federation)) + .fallback(assets::serve) + .layer(DefaultBodyLimit::max(64 * 1024)) + .layer(middleware::from_fn_with_state( + policy, + security::HttpSecurity::protect, + ))) } -#[cfg(test)] -mod tests { - use super::*; - use tower::ServiceExt; - - struct FixedReadiness(bool); - #[async_trait] - impl Readiness for FixedReadiness { - async fn check(&self) -> Result<(), ()> { - if self.0 { Ok(()) } else { Err(()) } - } - } - - #[tokio::test] - async fn liveness_has_no_dependencies_and_readiness_fails_closed() { - let app = router(Arc::new(FixedReadiness(false)), None); - let live = app - .clone() - .oneshot( - axum::http::Request::get("/health/live") - .body(axum::body::Body::empty()) - .expect("request"), - ) - .await - .expect("response"); - let ready = app - .oneshot( - axum::http::Request::get("/health/ready") - .body(axum::body::Body::empty()) - .expect("request"), - ) - .await - .expect("response"); - assert_eq!(live.status(), StatusCode::NO_CONTENT); - assert_eq!(ready.status(), StatusCode::SERVICE_UNAVAILABLE); - } - - #[tokio::test] - async fn readiness_succeeds_with_test_substitutes() { - let response = router(Arc::new(FixedReadiness(true)), None) - .oneshot( - axum::http::Request::get("/health/ready") - .body(axum::body::Body::empty()) - .expect("request"), - ) - .await - .expect("response"); - assert_eq!(response.status(), StatusCode::NO_CONTENT); - } +/// Fails explicitly if frontend assets have not been built into this executable. +/// +/// # Errors +/// Returns an actionable build error when embedded assets are missing. +pub fn require_embedded_assets() -> Result<()> { + anyhow::ensure!( + !assets::FILES.is_empty(), + "Build the auth frontend with pnpm --filter @piquel/auth-web build before compiling auth-service" + ); + Ok(()) } diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index bb5950aac..d15cd0319 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -1,40 +1,111 @@ -#![allow(missing_docs)] - -use auth_service::{AuthConfig, Es256KeyProvider, PasskeyApplication, ProductionReadiness, router}; +//! Authentication service and its small administrative CLI. +use anyhow::{Context, Result}; +use auth_service::AuthConfig; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{Duration, Utc}; use piquel_repository::Database; -use std::{net::SocketAddr, sync::Arc}; +use rand::{RngCore, rngs::OsRng}; +use sha2::{Digest, Sha256}; +use std::{env, net::SocketAddr}; #[tokio::main] -async fn main() -> anyhow::Result<()> { +async fn main() -> Result<()> { piquel_telemetry::init("auth_service=info"); - let config = AuthConfig::from_environment()?; - let listener_address: SocketAddr = config.public_listener; - let database = Database::connect(config.database).await?; - let key_secret = config.key_provider.resolve()?; - let pem = std::str::from_utf8(key_secret.expose_secret()) - .map_err(|_| anyhow::anyhow!("signing key provider returned invalid data"))?; - let purpose_keys = Es256KeyProvider::from_pkcs8_pem(config.signing_key_id.clone(), pem) - .map_err(|()| anyhow::anyhow!("signing key provider returned an invalid ES256 key"))?; - let passkeys = PasskeyApplication::new( - database.clone(), - &config.webauthn_rp_id, - config.public_base_url.as_url(), - Arc::new(purpose_keys), - )?; - let listener = tokio::net::TcpListener::bind(listener_address).await?; - tracing::info!(%listener_address, "auth service listening"); - axum::serve( - listener, - router( - Arc::new(ProductionReadiness::new(database, config.key_provider)), - Some(passkeys), - ), - ) - .with_graceful_shutdown(shutdown_signal()) - .await?; + let args: Vec = env::args().skip(1).collect(); + if args + .first() + .is_some_and(|v| matches!(v.as_str(), "--help" | "-h" | "help")) + { + println!( + "auth-service [serve | migrate | invite create [--expires-in 7d] | secret]\n\nDatabase commands use AUTH_DATABASE_URL. See README.md for configuration." + ); + return Ok(()); + } + if args.first().is_some_and(|v| v == "secret") { + let mut secret = [0; 32]; + OsRng.fill_bytes(&mut secret); + println!("{}", URL_SAFE_NO_PAD.encode(secret)); + return Ok(()); + } + let database = Database::connect(AuthConfig::database_from_environment()?) + .await + .context("connect to authentication database")?; + match args.first().map_or("serve", String::as_str) { + "migrate" => database + .run_migrations() + .await + .context("apply authentication schema")?, + "invite" => { + anyhow::ensure!( + args.get(1).is_some_and(|v| v == "create"), + "Usage: auth-service invite create [--expires-in 7d]" + ); + let duration = match &args[2..] { + [] => Duration::days(7), + [flag, value] if flag == "--expires-in" => { + let (number, unit) = value.split_at( + value + .len() + .checked_sub(1) + .filter(|n| value.is_char_boundary(*n)) + .context("invalid expiry")?, + ); + let number: i64 = number.parse().context("expiry must be e.g. 7d or 24h")?; + anyhow::ensure!( + number > 0 && number <= 365, + "expiry must be between 1 and 365 units" + ); + match unit { + "d" => Duration::days(number), + "h" => Duration::hours(number), + _ => anyhow::bail!("expiry must end in d or h"), + } + } + _ => anyhow::bail!("Usage: auth-service invite create [--expires-in 7d]"), + }; + let mut secret = [0; 32]; + OsRng.fill_bytes(&mut secret); + database + .security() + .create_invitation(&Sha256::digest(secret), Utc::now() + duration) + .await?; + let mut url = url::Url::parse( + &env::var("AUTH_PUBLIC_BASE_URL").context("AUTH_PUBLIC_BASE_URL is required")?, + )? + .join("register")?; + url.query_pairs_mut() + .append_pair("invitation", &URL_SAFE_NO_PAD.encode(secret)); + println!("{url}"); + } + "serve" => { + auth_service::require_embedded_assets()?; + let config = AuthConfig::from_environment()?; + let listener = tokio::net::TcpListener::bind(config.public_listener).await?; + let router = auth_service::router(&config, database.clone()).await?; + let cleanup = tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(300)); + loop { + interval.tick().await; + if let Err(error) = database.purge_expired_auth_state(1000).await { + tracing::error!(?error, "expired authentication state cleanup failed"); + } + } + }); + tracing::info!(address=%config.public_listener,"authentication service listening"); + let result = axum::serve( + listener, + router.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(async { + if let Err(error) = tokio::signal::ctrl_c().await { + tracing::error!(?error, "shutdown signal unavailable"); + } + }) + .await; + cleanup.abort(); + result?; + } + _ => anyhow::bail!("Unknown command. Run auth-service --help"), + } Ok(()) } - -async fn shutdown_signal() { - let _ = tokio::signal::ctrl_c().await; -} diff --git a/apps/auth-service/src/oidc.rs b/apps/auth-service/src/oidc.rs new file mode 100644 index 000000000..d07868aab --- /dev/null +++ b/apps/auth-service/src/oidc.rs @@ -0,0 +1,1269 @@ +//! Authorization Code + PKCE, signed tokens, and rotating opaque refresh tokens. + +mod signing; +pub use signing::Rs256KeyProvider; + +use axum::{ + Form, Json, Router, + extract::{Path, Query, State}, + http::{HeaderMap, StatusCode, header}, + response::{IntoResponse, Redirect, Response}, + routing::{get, post}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{Duration, Utc}; +use piquel_auth_protocol::{SessionId, TokenId, UserId}; +use piquel_repository::{ + AppendAuditEvent, Database, InsertAuthorizationCode, InsertAuthorizationRequest, + InsertRefreshFamily, InsertRefreshToken, RefreshRotationError, StoredAuthorizationRequest, + StoredOidcClient, StoredSession, +}; +use rand::{RngCore, rngs::OsRng}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{collections::BTreeSet, str::FromStr, sync::Arc}; +use thiserror::Error; +use url::Url; + +const OPAQUE_SECRET_BYTES: usize = 32; +const ACCESS_TOKEN_SECONDS: i64 = 300; + +/// Runnable OIDC application state. +#[derive(Clone)] +pub struct OidcApplication { + database: Database, + issuer: String, + refresh_key: Arc<[u8; 32]>, + keys: Arc, +} + +impl OidcApplication { + fn hmac(key: &[u8], value: &[u8]) -> Result<[u8; 32], ()> { + let key = openssl::pkey::PKey::hmac(key).map_err(|_| ())?; + let mut signer = openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &key) + .map_err(|_| ())?; + signer.update(value).map_err(|_| ())?; + signer + .sign_to_vec() + .map_err(|_| ())? + .try_into() + .map_err(|_| ()) + } + + /// Hashes a high-entropy static client secret. Generate at least 32 random bytes. + /// + /// # Errors + /// Returns an error when the encoded secret is too short or too large. + pub fn client_secret_hash(secret: &str) -> anyhow::Result> { + anyhow::ensure!( + (43..=512).contains(&secret.len()), + "OIDC client secrets must encode at least 32 random bytes" + ); + Ok(Sha256::digest(secret.as_bytes()).to_vec()) + } + + async fn authenticate_client( + &self, + headers: &HeaderMap, + supplied_id: Option<&str>, + ) -> Result { + let basic = headers + .get(header::AUTHORIZATION) + .map(|header| { + let value = header.to_str().map_err(|_| ApiError::client())?; + let encoded = value.strip_prefix("Basic ").ok_or_else(ApiError::client)?; + if encoded.len() > 1024 { + return Err(ApiError::client()); + } + let bytes = base64::engine::general_purpose::STANDARD + .decode(encoded) + .map_err(|_| ApiError::client())?; + let decoded = String::from_utf8(bytes).map_err(|_| ApiError::client())?; + let (id, secret) = decoded.split_once(':').ok_or_else(ApiError::client)?; + let decode = |value: &str| { + url::form_urlencoded::parse(format!("v={value}").as_bytes()) + .next() + .map(|(_, v)| v.into_owned()) + .ok_or_else(ApiError::client) + }; + Ok::<_, ApiError>((decode(id)?, decode(secret)?)) + }) + .transpose()?; + let id = basic + .as_ref() + .map(|(id, _)| id.as_str()) + .or(supplied_id) + .ok_or_else(ApiError::client)?; + if supplied_id.is_some_and(|supplied| supplied != id) { + return Err(ApiError::client()); + } + let client = self + .database + .oidc() + .find_client(id) + .await + .map_err(ApiError::internal)? + .filter(|c| c.enabled) + .ok_or_else(ApiError::client)?; + match (&client.client_secret_hash, basic) { + (None, None) => {} + (Some(expected), Some((_, secret))) + if openssl::memcmp::eq(expected, &Sha256::digest(secret.as_bytes())) => {} + _ => return Err(ApiError::client()), + } + Ok(client) + } + + /// Constructs an OIDC endpoint set with an exact HTTPS issuer. + /// + /// # Errors + /// + /// Returns an error for an insecure issuer or insufficient key material. + pub(crate) fn new( + database: Database, + issuer: &Url, + secret: &[u8], + keys: Arc, + ) -> Result { + if issuer.scheme() != "https" + || issuer.query().is_some() + || issuer.fragment().is_some() + || secret.len() < 32 + { + return Err(()); + } + Self::build(database, issuer, secret, keys) + } + + /// Constructs an HTTP issuer only for an explicit loopback development configuration. + /// + /// # Errors + /// + /// Returns an error unless the issuer is loopback-only and key material is sufficient. + pub(crate) fn new_development( + database: Database, + issuer: &Url, + secret: &[u8], + keys: Arc, + ) -> Result { + let loopback = issuer.host_str().is_some_and(|host| { + host == "localhost" + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + }); + if !loopback + || !matches!(issuer.scheme(), "http" | "https") + || issuer.query().is_some() + || issuer.fragment().is_some() + || secret.len() < 32 + { + return Err(()); + } + Self::build(database, issuer, secret, keys) + } + + fn build( + database: Database, + issuer: &Url, + secret: &[u8], + keys: Arc, + ) -> Result { + let refresh_key = Self::hmac(secret, b"piquel-refresh-token-digest-v1")?; + Ok(Self { + database, + issuer: issuer.as_str().trim_end_matches('/').into(), + refresh_key: Arc::new(refresh_key), + keys, + }) + } +} + +pub(super) fn routes(application: OidcApplication) -> Router { + Router::new() + .route("/.well-known/openid-configuration", get(discovery)) + .route("/.well-known/jwks.json", get(jwks)) + .route("/oauth/authorize", get(authorize)) + .route("/oauth/authorize/resume", get(resume)) + .route( + "/oauth/authorize/transaction/{transaction}", + get(authorization_transaction), + ) + .route("/oauth/authorize/decision", post(authorization_decision)) + .route("/oauth/token", post(token)) + .route("/oauth/revoke", post(revoke)) + .route("/oidc/userinfo", get(userinfo)) + .route("/oidc/logout", get(logout_start).post(logout)) + .with_state(application) +} + +async fn discovery(State(app): State) -> Json { + let base = &app.issuer; + Json(json!({ + "issuer":base, "authorization_endpoint":format!("{base}/oauth/authorize"), + "token_endpoint":format!("{base}/oauth/token"), "revocation_endpoint":format!("{base}/oauth/revoke"), + "userinfo_endpoint":format!("{base}/oidc/userinfo"), "jwks_uri":format!("{base}/.well-known/jwks.json"), + "end_session_endpoint":format!("{base}/oidc/logout"), "response_types_supported":["code"], + "grant_types_supported":["authorization_code","refresh_token"], "code_challenge_methods_supported":["S256"], + "token_endpoint_auth_methods_supported":["none","client_secret_basic"], "subject_types_supported":["public"], "response_modes_supported":["query"], "claims_supported":["sub","name","preferred_username","email","email_verified","auth_time","amr","sid"], "id_token_signing_alg_values_supported":["RS256"], + "scopes_supported":["openid","profile","email","offline_access"] + })) +} +async fn jwks(State(app): State) -> Json { + Json(app.keys.jwks()) +} + +#[derive(Deserialize)] +struct AuthorizeQuery { + response_type: String, + client_id: String, + redirect_uri: String, + scope: String, + #[serde(default)] + state: String, + nonce: Option, + code_challenge: String, + code_challenge_method: String, + audience: Option, + prompt: Option, + max_age: Option, +} + +async fn authorize( + State(app): State, + headers: HeaderMap, + Query(q): Query, +) -> Result { + let client = app + .database + .oidc() + .find_client(&q.client_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(ApiError::request)?; + if !client.enabled || !client.redirect_uris.contains(&q.redirect_uri) { + return Err(ApiError::request()); + } + let redirect = Url::parse(&q.redirect_uri).map_err(|_| ApiError::request())?; + let fail = |error: &str| redirect_error(&redirect, error, &q.state); + let challenge_valid = URL_SAFE_NO_PAD + .decode(&q.code_challenge) + .is_ok_and(|value| value.len() == 32); + if q.response_type != "code" + || q.state.len() > 512 + || q.code_challenge_method != "S256" + || !challenge_valid + { + return Err(fail("invalid_request")); + } + let scopes = parse_scopes(&q.scope).ok_or_else(|| fail("invalid_scope"))?; + if !scopes + .iter() + .all(|scope| client.allowed_scopes.contains(scope)) + { + return Err(fail("invalid_scope")); + } + let audience = q + .audience + .clone() + .or_else(|| client.allowed_audiences.first().cloned()) + .ok_or_else(ApiError::server)?; + if !client.allowed_audiences.contains(&audience) { + return Err(fail("invalid_target")); + } + if q.nonce + .as_ref() + .is_some_and(|nonce| nonce.is_empty() || nonce.len() > 512) + || q.max_age.is_some_and(|age| age < 0) + { + return Err(fail("invalid_request")); + } + let prompts: BTreeSet<_> = q + .prompt + .as_deref() + .unwrap_or_default() + .split_ascii_whitespace() + .collect(); + if prompts + .iter() + .any(|value| !matches!(*value, "none" | "login" | "consent" | "select_account")) + || (prompts.contains("none") && prompts.len() > 1) + { + return Err(fail("invalid_request")); + } + let session = browser_session(&app.database, &headers).await?; + let requires_login = (prompts.contains("login") || prompts.contains("select_account")) + || session.is_none() + || q.max_age.is_some_and(|age| { + age == 0 + || session.as_ref().is_none_or(|session| { + Utc::now() + .signed_duration_since(session.authenticated_at) + .num_seconds() + > age + }) + }); + if prompts.contains("none") && requires_login { + return Err(fail("login_required")); + } + let (transaction, id, secret) = new_opaque("par_v1"); + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + app.database + .oidc() + .insert_authorization_request(&InsertAuthorizationRequest { + id, + secret_digest: digest.to_vec(), + client_id: q.client_id, + redirect_uri: q.redirect_uri, + client_state: q.state.clone(), + pkce_challenge: q.code_challenge, + nonce: q.nonce, + scopes: scopes.into_iter().collect(), + audience, + force_consent: prompts.contains("consent"), + force_login: (prompts.contains("login") || prompts.contains("select_account")), + max_age: q.max_age, + expires_at: Utc::now() + Duration::minutes(10), + }) + .await + .map_err(ApiError::internal)?; + if requires_login { + return Ok(app.continuation_page("login", &transaction)); + } + app.continue_authorization(&headers, transaction, prompts.contains("none")) + .await +} + +#[derive(Serialize)] +struct AuthorizationTransactionView { + client_name: String, + scopes: Vec, + audience: String, +} + +async fn authorization_transaction( + State(app): State, + headers: HeaderMap, + Path(transaction): Path, +) -> Result, ApiError> { + let session = browser_session(&app.database, &headers) + .await? + .ok_or_else(ApiError::unauthorized)?; + let request = find_authorization_request(&app, &transaction).await?; + require_authorization_session(&request, &session)?; + Ok(Json(AuthorizationTransactionView { + client_name: request.client_display_name, + scopes: request.scopes, + audience: request.audience, + })) +} + +#[derive(Deserialize)] +struct AuthorizationDecision { + transaction: String, + decision: String, +} + +async fn authorization_decision( + State(app): State, + headers: HeaderMap, + Form(input): Form, +) -> Result, ApiError> { + require_same_origin(&app, &headers)?; + let redirect = decide(&app, &headers, input, true).await?; + let response = redirect.into_response(); + Ok(Json( + json!({"redirect_url":response.headers().get(header::LOCATION).and_then(|v|v.to_str().ok()).ok_or_else(ApiError::server)?}), + )) +} + +async fn decide( + app: &OidcApplication, + headers: &HeaderMap, + input: AuthorizationDecision, + explicit: bool, +) -> Result { + let session = browser_session(&app.database, headers) + .await? + .ok_or_else(ApiError::unauthorized)?; + let pending = find_authorization_request(app, &input.transaction).await?; + if !explicit && !can_authorize(app, &pending, &session).await? { + return Err(ApiError::request()); + } + let (id, secret) = parse_opaque("par_v1", &input.transaction)?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut transaction = app.database.begin().await.map_err(ApiError::internal)?; + let request = transaction + .oidc() + .consume_authorization_request(id, &digest) + .await + .map_err(|error| ApiError::database(error, "invalid_request"))?; + require_authorization_session(&request, &session)?; + let mut redirect = Url::parse(&request.redirect_uri).map_err(ApiError::internal)?; + match input.decision.as_str() { + "deny" => { + redirect + .query_pairs_mut() + .append_pair("error", "access_denied") + .append_pair("state", &request.client_state); + } + "approve" => { + if explicit { + transaction + .oidc() + .save_consent( + session.user_id, + &request.client_id, + &request.audience, + &request.scopes, + ) + .await + .map_err(ApiError::internal)?; + } + let user = transaction + .users() + .find_active_by_id_for_update(session.user_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(ApiError::unauthorized)?; + if user.id != session.user_id { + return Err(ApiError::unauthorized()); + } + let (code, code_id, code_secret) = new_opaque("pac_v1"); + let code_digest = keyed_digest(app.refresh_key.as_ref(), &code_secret)?; + transaction + .oidc() + .insert_code(&InsertAuthorizationCode { + id: code_id, + secret_digest: code_digest.to_vec(), + client_id: request.client_id, + user_id: session.user_id, + session_id: session.id, + redirect_uri: request.redirect_uri, + pkce_challenge: request.pkce_challenge, + nonce: request.nonce, + scopes: request.scopes, + audience: request.audience, + expires_at: Utc::now() + Duration::minutes(2), + }) + .await + .map_err(ApiError::internal)?; + redirect + .query_pairs_mut() + .append_pair("code", &code) + .append_pair("state", &request.client_state); + } + _ => return Err(ApiError::request()), + } + transaction.commit().await.map_err(ApiError::internal)?; + Ok(Redirect::to(redirect.as_str())) +} + +async fn find_authorization_request( + app: &OidcApplication, + value: &str, +) -> Result { + let (id, secret) = parse_opaque("par_v1", value)?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + app.database + .oidc() + .find_authorization_request(id, &digest) + .await + .map_err(ApiError::internal)? + .ok_or_else(ApiError::request) +} + +fn require_authorization_session( + request: &StoredAuthorizationRequest, + session: &StoredSession, +) -> Result<(), ApiError> { + let newer_than_request = session.authenticated_at >= request.created_at; + let within_max_age = request.max_age.is_none_or(|age| { + if age == 0 { + return newer_than_request; + } + age >= 0 + && Utc::now() + .signed_duration_since(session.authenticated_at) + .num_seconds() + <= age + }); + (!request.force_login || newer_than_request) + .then_some(()) + .filter(|()| within_max_age) + .ok_or_else(ApiError::unauthorized) +} + +#[derive(Deserialize)] +struct TokenForm { + grant_type: String, + client_id: Option, + code: Option, + redirect_uri: Option, + code_verifier: Option, + refresh_token: Option, + scope: Option, +} +impl TokenForm { + fn refresh_scopes(&self, granted: &[String]) -> Result, ApiError> { + let Some(requested) = self.scope.as_deref() else { + return Ok(granted.to_vec()); + }; + let scopes = parse_scopes(requested).ok_or_else(|| ApiError::oauth("invalid_scope"))?; + if !scopes.iter().all(|scope| granted.contains(scope)) { + return Err(ApiError::oauth("invalid_scope")); + } + Ok(scopes.into_iter().collect()) + } +} + +#[derive(Serialize)] +struct TokenResponse { + access_token: String, + token_type: &'static str, + expires_in: i64, + scope: String, + #[serde(skip_serializing_if = "Option::is_none")] + id_token: Option, + #[serde(skip_serializing_if = "Option::is_none")] + refresh_token: Option, +} + +async fn token( + State(app): State, + headers: HeaderMap, + Form(mut form): Form, +) -> Result, ApiError> { + let client = app + .authenticate_client(&headers, form.client_id.as_deref()) + .await?; + form.client_id = Some(client.id); + match form.grant_type.as_str() { + "authorization_code" => exchange_code(&app, form).await.map(Json), + "refresh_token" => rotate_refresh(&app, form).await.map(Json), + _ => Err(ApiError::oauth("unsupported_grant_type")), + } +} + +async fn exchange_code(app: &OidcApplication, form: TokenForm) -> Result { + let (id, secret) = parse_opaque( + "pac_v1", + form.code + .as_deref() + .ok_or_else(|| ApiError::oauth("invalid_grant"))?, + )?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut tx = app.database.begin().await.map_err(ApiError::internal)?; + let code = tx + .oidc() + .consume_code(id, &digest) + .await + .map_err(|error| ApiError::database(error, "invalid_grant"))?; + if Some(code.client_id.as_str()) != form.client_id.as_deref() + || form.redirect_uri.as_deref() != Some(&code.redirect_uri) + || validate_pkce_s256( + form.code_verifier.as_deref().unwrap_or_default(), + &code.pkce_challenge, + ) + .is_err() + { + return Err(ApiError::oauth("invalid_grant")); + } + let user = tx + .users() + .find_active_by_id_for_update(code.user_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let session = tx + .sessions() + .find_by_id(code.session_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let client = tx + .oidc() + .find_client(form.client_id.as_deref().ok_or_else(ApiError::client)?) + .await + .map_err(ApiError::internal)? + .ok_or_else(|| ApiError::oauth("invalid_client"))?; + let email = tx + .oidc() + .primary_email(user.id) + .await + .map_err(ApiError::internal)?; + let tokens = TokenGrant { + client: &client.id, + audience: &code.audience, + scopes: &code.scopes, + nonce: code.nonce.as_deref(), + } + .issue(app, &user, &session, email.as_deref())?; + let refresh = + if client.allow_refresh && code.scopes.iter().any(|scope| scope == "offline_access") { + Some( + create_refresh( + &mut tx, + app, + code.user_id, + code.session_id, + client.id, + code.audience, + code.scopes, + ) + .await?, + ) + } else { + None + }; + tx.commit().await.map_err(ApiError::internal)?; + Ok(TokenResponse { + refresh_token: refresh, + ..tokens + }) +} + +async fn rotate_refresh(app: &OidcApplication, form: TokenForm) -> Result { + let (id, secret) = parse_opaque( + "prt_v1", + form.refresh_token + .as_deref() + .ok_or_else(|| ApiError::oauth("invalid_grant"))?, + )?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut tx = app.database.begin().await.map_err(ApiError::internal)?; + let rotated = match tx + .tokens() + .consume_for_rotation( + id, + &digest, + form.client_id.as_deref().ok_or_else(ApiError::client)?, + ) + .await + { + Ok(value) => value, + Err(RefreshRotationError::Replay { user_id }) => { + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: "refresh.replay".into(), + outcome: "rejected".into(), + request_metadata: json!({}), + }) + .await + .map_err(ApiError::internal)?; + tx.commit().await.map_err(ApiError::internal)?; + tracing::warn!( + event = "auth.refresh_replay", + "refresh token replay rejected" + ); + return Err(ApiError::oauth("invalid_grant")); + } + Err(RefreshRotationError::Policy { user_id }) => { + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: "refresh.policy_rejected".into(), + outcome: "rejected".into(), + request_metadata: json!({}), + }) + .await + .map_err(ApiError::internal)?; + tx.commit().await.map_err(ApiError::internal)?; + return Err(ApiError::oauth("invalid_grant")); + } + Err(RefreshRotationError::Invalid) => return Err(ApiError::oauth("invalid_grant")), + Err(RefreshRotationError::Database(error)) => return Err(ApiError::internal(error)), + }; + if Some(rotated.client_id.as_str()) != form.client_id.as_deref() { + return Err(ApiError::oauth("invalid_grant")); + } + let scopes = form.refresh_scopes(&rotated.scopes)?; + let user = tx + .users() + .find_by_id(rotated.user_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let session = tx + .sessions() + .find_by_id(rotated.session_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let (raw, new_id, new_secret) = new_opaque("prt_v1"); + let new_digest = keyed_digest(app.refresh_key.as_ref(), &new_secret)?; + tx.tokens() + .insert_token(&InsertRefreshToken { + id: new_id, + family_id: rotated.family_id, + secret_digest: new_digest.to_vec(), + expires_at: session.expires_at, + }) + .await + .map_err(ApiError::internal)?; + let email = tx + .oidc() + .primary_email(user.id) + .await + .map_err(ApiError::internal)?; + let mut tokens = TokenGrant { + client: &rotated.client_id, + audience: &rotated.audience, + scopes: &scopes, + nonce: None, + } + .issue(app, &user, &session, email.as_deref())?; + tokens.refresh_token = Some(raw); + tx.commit().await.map_err(ApiError::internal)?; + Ok(tokens) +} + +async fn create_refresh( + tx: &mut piquel_repository::DatabaseTransaction<'_>, + app: &OidcApplication, + user_id: UserId, + session_id: SessionId, + client_id: String, + audience: String, + scopes: Vec, +) -> Result { + let session = tx + .sessions() + .find_active_by_id(session_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let family_id = TokenId::new(); + let (raw, id, secret) = new_opaque("prt_v1"); + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + tx.tokens() + .insert_family( + &InsertRefreshFamily { + id: family_id, + user_id, + client_id, + session_id, + audience, + scopes, + }, + &InsertRefreshToken { + id, + family_id, + secret_digest: digest.to_vec(), + expires_at: session.expires_at, + }, + ) + .await + .map_err(ApiError::internal)?; + Ok(raw) +} + +struct TokenGrant<'a> { + client: &'a str, + audience: &'a str, + scopes: &'a [String], + nonce: Option<&'a str>, +} +impl TokenGrant<'_> { + fn issue( + &self, + app: &OidcApplication, + user: &piquel_repository::StoredUser, + session: &StoredSession, + email: Option<&str>, + ) -> Result { + let Self { + client, + audience, + scopes, + nonce, + } = self; + let now = Utc::now().timestamp(); + let mut claims = json!({"iss":app.issuer,"sub":user.id,"sid":session.id,"auth_time":session.authenticated_at.timestamp(),"amr":session.authentication_methods,"iat":now,"exp":now+ACCESS_TOKEN_SECONDS}); + if scopes.iter().any(|s| s == "profile") { + claims["preferred_username"] = json!(user.username); + claims["name"] = json!(user.display_name); + } + if scopes.iter().any(|s| s == "email") + && let Some(email) = email + { + claims["email"] = json!(email); + claims["email_verified"] = json!(true); + } + let mut access = claims.clone(); + access["aud"] = json!(audience); + access["client_id"] = json!(client); + access["jti"] = json!(TokenId::new()); + access["scope"] = json!(scopes.join(" ")); + let access_token = app + .keys + .sign("at+jwt", &access) + .map_err(|()| ApiError::server())?; + let id_token = if scopes.iter().any(|s| s == "openid") { + claims["aud"] = json!(client); + if let Some(nonce) = nonce { + claims["nonce"] = json!(nonce); + } + Some( + app.keys + .sign("JWT", &claims) + .map_err(|()| ApiError::server())?, + ) + } else { + None + }; + Ok(TokenResponse { + access_token, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_SECONDS, + scope: scopes.join(" "), + id_token, + refresh_token: None, + }) + } +} + +#[derive(Deserialize)] +struct RevokeForm { + token: String, + client_id: Option, +} +async fn revoke( + State(app): State, + headers: HeaderMap, + Form(form): Form, +) -> Result { + let client = app + .authenticate_client(&headers, form.client_id.as_deref()) + .await?; + if let Ok((id, secret)) = parse_opaque("prt_v1", &form.token) { + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut tx = app.database.begin().await.map_err(ApiError::internal)?; + tx.tokens() + .revoke_family_for_client_token(id, &digest, &client.id) + .await + .map_err(ApiError::internal)?; + tx.commit().await.map_err(ApiError::internal)?; + } + Ok(StatusCode::OK) +} + +async fn userinfo( + State(app): State, + headers: HeaderMap, +) -> Result, ApiError> { + let token = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .ok_or_else(ApiError::unauthorized)?; + let claims = app + .keys + .verify(token, "at+jwt", &app.issuer) + .map_err(|()| ApiError::unauthorized())?; + let scopes: BTreeSet<_> = claims + .get("scope") + .and_then(Value::as_str) + .unwrap_or_default() + .split_ascii_whitespace() + .collect(); + if !scopes.contains("openid") { + return Err(ApiError::unauthorized()); + } + let mut response = json!({"sub":claims.get("sub")}); + if scopes.contains("profile") { + response["preferred_username"] = claims + .get("preferred_username") + .cloned() + .unwrap_or(Value::Null); + response["name"] = claims.get("name").cloned().unwrap_or(Value::Null); + response["profile_version"] = claims + .get("profile_version") + .cloned() + .unwrap_or(Value::Null); + } + if scopes.contains("email") { + for name in ["email", "email_verified"] { + if let Some(value) = claims.get(name) { + response[name] = value.clone(); + } + } + } + Ok(Json(response)) +} + +#[derive(Deserialize, Serialize)] +struct LogoutQuery { + client_id: Option, + id_token_hint: Option, + post_logout_redirect_uri: Option, + state: Option, +} + +impl OidcApplication { + async fn logout_destination(&self, q: &LogoutQuery) -> Result { + if q.state.as_ref().is_some_and(|s| s.len() > 512) { + return Err(ApiError::request()); + } + let hint = q + .id_token_hint + .as_ref() + .map(|token| { + self.keys + .verify_logout(token, &self.issuer) + .map_err(|()| ApiError::request()) + }) + .transpose()?; + let hinted_client = hint + .as_ref() + .and_then(|c| c.get("aud")) + .and_then(Value::as_str); + if q.client_id + .as_deref() + .zip(hinted_client) + .is_some_and(|(a, b)| a != b) + { + return Err(ApiError::request()); + } + let Some(uri) = q.post_logout_redirect_uri.as_ref() else { + return Ok(format!("{}/login", self.issuer)); + }; + let id = q + .client_id + .as_deref() + .or(hinted_client) + .ok_or_else(ApiError::request)?; + let client = self + .database + .oidc() + .find_client(id) + .await + .map_err(ApiError::internal)? + .filter(|c| c.enabled) + .ok_or_else(ApiError::request)?; + if !client.post_logout_uris.contains(uri) { + return Err(ApiError::request()); + } + let mut url = Url::parse(uri).map_err(|_| ApiError::request())?; + if let Some(state) = &q.state { + url.query_pairs_mut().append_pair("state", state); + } + Ok(url.into()) + } +} + +async fn logout_start( + State(app): State, + Query(q): Query, +) -> Result { + app.logout_destination(&q).await?; + let mut url = Url::parse(&format!("{}/logout", app.issuer)).map_err(ApiError::internal)?; + for (name, value) in [ + ("client_id", &q.client_id), + ("id_token_hint", &q.id_token_hint), + ("post_logout_redirect_uri", &q.post_logout_redirect_uri), + ("state", &q.state), + ] { + if let Some(value) = value { + url.query_pairs_mut().append_pair(name, value); + } + } + Ok(Redirect::to(url.as_str())) +} + +async fn logout( + State(app): State, + headers: HeaderMap, + Form(q): Form, +) -> Result { + if require_same_origin(&app, &headers).is_err() { + return logout_start(State(app), Query(q)) + .await + .map(IntoResponse::into_response); + } + let destination = app.logout_destination(&q).await?; + if let Some(session) = browser_session(&app.database, &headers).await? { + let mut tx = app.database.begin().await.map_err(ApiError::internal)?; + tx.oidc() + .revoke_session(session.id) + .await + .map_err(ApiError::internal)?; + tx.commit().await.map_err(ApiError::internal)?; + } + let mut response = Json(json!({"redirect_url":destination})).into_response(); + response.headers_mut().insert( + header::SET_COOKIE, + "__Host-piquel_session=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0" + .parse() + .map_err(ApiError::internal)?, + ); + Ok(response) +} + +fn require_same_origin(app: &OidcApplication, headers: &HeaderMap) -> Result<(), ApiError> { + let origin_matches = headers + .get(header::ORIGIN) + .and_then(|value| value.to_str().ok()) + .is_some_and(|origin| origin == app.issuer); + let csrf_header = headers + .get("x-piquel-csrf") + .and_then(|value| value.to_str().ok()) + == Some("1"); + let same_origin_fetch = headers + .get("sec-fetch-site") + .and_then(|value| value.to_str().ok()) + == Some("same-origin"); + (origin_matches && (csrf_header || same_origin_fetch)) + .then_some(()) + .ok_or_else(ApiError::request) +} + +async fn browser_session( + database: &Database, + headers: &HeaderMap, +) -> Result, ApiError> { + let Some(secret) = + crate::security::BrowserSecret::from_cookie(headers, "__Host-piquel_session") + else { + return Ok(None); + }; + database + .sessions() + .find_active_by_browser_secret(&secret.digest()) + .await + .map_err(|error| { + tracing::error!(?error, "OIDC session lookup failed"); + ApiError::server() + }) +} + +fn parse_scopes(value: &str) -> Option> { + let scopes: BTreeSet<_> = value.split_ascii_whitespace().map(str::to_owned).collect(); + (!scopes.is_empty() && scopes.len() <= 16).then_some(scopes) +} +fn new_opaque(prefix: &str) -> (String, TokenId, [u8; OPAQUE_SECRET_BYTES]) { + let id = TokenId::new(); + let mut secret = [0; OPAQUE_SECRET_BYTES]; + OsRng.fill_bytes(&mut secret); + ( + format!("{prefix}_{id}.{}", URL_SAFE_NO_PAD.encode(secret)), + id, + secret, + ) +} +fn parse_opaque( + prefix: &str, + value: &str, +) -> Result<(TokenId, [u8; OPAQUE_SECRET_BYTES]), ApiError> { + if value.len() > 160 { + return Err(ApiError::oauth("invalid_grant")); + } + let rest = value + .strip_prefix(&format!("{prefix}_")) + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let (id, secret) = rest + .split_once('.') + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let id = TokenId::from_str(id).map_err(|_| ApiError::oauth("invalid_grant"))?; + let decoded = URL_SAFE_NO_PAD + .decode(secret) + .map_err(|_| ApiError::oauth("invalid_grant"))?; + let secret: [u8; OPAQUE_SECRET_BYTES] = decoded + .try_into() + .map_err(|_| ApiError::oauth("invalid_grant"))?; + Ok((id, secret)) +} +fn keyed_digest(key: &[u8], secret: &[u8]) -> Result<[u8; 32], ApiError> { + OidcApplication::hmac(key, secret).map_err(|()| ApiError::server()) +} + +fn validate_pkce_s256(verifier: &str, challenge: &str) -> Result<(), ()> { + if !(43..=128).contains(&verifier.len()) + || !verifier + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')) + { + return Err(()); + } + (URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) == challenge) + .then_some(()) + .ok_or(()) +} +fn redirect_error(base: &Url, error: &str, state: &str) -> ApiError { + let mut url = base.clone(); + url.query_pairs_mut() + .append_pair("error", error) + .append_pair("state", state); + ApiError( + StatusCode::FOUND, + json!({"error":error}), + Some(url.to_string()), + ) +} + +#[derive(Debug, Error)] +#[error("OIDC request failed")] +struct ApiError(StatusCode, Value, Option); +impl ApiError { + fn internal(error: impl std::fmt::Debug) -> Self { + tracing::error!(error=?error,"OIDC operation failed"); + Self::server() + } + fn database(error: piquel_repository::DatabaseError, expected: &str) -> Self { + match error { + piquel_repository::DatabaseError::NotFound => Self::oauth(expected), + error => Self::internal(error), + } + } + + fn client() -> Self { + Self( + StatusCode::UNAUTHORIZED, + json!({"error":"invalid_client"}), + None, + ) + } + fn request() -> Self { + Self( + StatusCode::BAD_REQUEST, + json!({"error":"invalid_request"}), + None, + ) + } + fn oauth(code: &str) -> Self { + Self(StatusCode::BAD_REQUEST, json!({"error":code}), None) + } + fn unauthorized() -> Self { + Self( + StatusCode::UNAUTHORIZED, + json!({"error":"invalid_token"}), + None, + ) + } + fn server() -> Self { + Self( + StatusCode::INTERNAL_SERVER_ERROR, + json!({"error":"server_error"}), + None, + ) + } +} +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + if let Some(location) = self.2 { + return Redirect::to(&location).into_response(); + } + let client_error = self.1.get("error") == Some(&json!("invalid_client")); + let mut response = (self.0, Json(self.1)).into_response(); + if client_error { + response.headers_mut().insert( + header::WWW_AUTHENTICATE, + axum::http::HeaderValue::from_static("Basic realm=\"token\""), + ); + } + response + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exact_redirect_and_pkce_and_refresh_bounds() { + let registered = ["https://a.example/cb".to_owned()]; + assert!(!registered.contains(&"https://a.example/cb.evil".to_owned())); + assert!(validate_pkce_s256("short", "x").is_err()); + let huge = format!("prt_v1_{}.{:0200}", TokenId::new(), "x"); + assert!(parse_opaque("prt_v1", &huge).is_err()); + } +} + +#[derive(Deserialize)] +struct ResumeQuery { + transaction: String, +} +async fn resume( + State(app): State, + headers: HeaderMap, + Query(q): Query, +) -> Result { + app.continue_authorization(&headers, q.transaction, false) + .await +} +impl OidcApplication { + fn continuation_page(&self, page: &str, transaction: &str) -> Redirect { + Redirect::to(&format!("{}/{page}?transaction={transaction}", self.issuer)) + } + async fn continue_authorization( + &self, + headers: &HeaderMap, + transaction: String, + silent: bool, + ) -> Result { + let request = find_authorization_request(self, &transaction).await?; + let redirect = Url::parse(&request.redirect_uri).map_err(ApiError::internal)?; + let fail = |code| redirect_error(&redirect, code, &request.client_state); + let session = browser_session(&self.database, headers).await?; + let Some(session) = + session.filter(|session| require_authorization_session(&request, session).is_ok()) + else { + if silent { + return Err(fail("login_required")); + } + return Ok(self.continuation_page("login", &transaction)); + }; + if can_authorize(self, &request, &session).await? { + return decide( + self, + headers, + AuthorizationDecision { + transaction, + decision: "approve".into(), + }, + false, + ) + .await; + } + if silent { + return Err(fail("consent_required")); + } + Ok(self.continuation_page("authorize", &transaction)) + } +} + +async fn can_authorize( + app: &OidcApplication, + request: &StoredAuthorizationRequest, + session: &StoredSession, +) -> Result { + if request.force_consent { + return Ok(false); + } + let client = app + .database + .oidc() + .find_client(&request.client_id) + .await + .map_err(ApiError::internal)? + .ok_or_else(ApiError::request)?; + Ok(client.trusted + || app + .database + .oidc() + .consented( + session.user_id, + &request.client_id, + &request.audience, + &request.scopes, + ) + .await + .map_err(ApiError::internal)?) +} + +#[cfg(test)] +#[path = "oidc/tests.rs"] +mod flow_tests; diff --git a/apps/auth-service/src/oidc/signing.rs b/apps/auth-service/src/oidc/signing.rs new file mode 100644 index 000000000..c7106815d --- /dev/null +++ b/apps/auth-service/src/oidc/signing.rs @@ -0,0 +1,154 @@ +//! RSA signing for interoperable `OpenID` Connect ID and access tokens. +use super::Value; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::Utc; +use openssl::{ + hash::MessageDigest, + pkey::{PKey, Private}, + rsa::Rsa, + sign::{Signer, Verifier}, +}; +use serde_json::json; + +/// A configured RSA private key. Keep its stable key identifier with the PEM. +pub struct Rs256KeyProvider { + kid: String, + key: PKey, +} +impl Rs256KeyProvider { + /// Loads a PEM RSA private key and stable public key identifier. + /// + /// # Errors + /// Returns an error for invalid PEM, a non-RSA or undersized key, or an invalid identifier. + pub fn from_pem(kid: impl Into, pem: &str) -> anyhow::Result { + let key = PKey::private_key_from_pem(pem.as_bytes())?; + anyhow::ensure!( + key.rsa()?.size() >= 256, + "OIDC RSA keys must be at least 2048 bits" + ); + let kid = kid.into(); + anyhow::ensure!( + !kid.is_empty() && kid.len() <= 128 && !kid.chars().any(char::is_whitespace), + "Invalid signing key identifier" + ); + Ok(Self { kid, key }) + } + /// Generates an ephemeral key for explicit local development and tests. + /// + /// # Errors + /// Returns an error when the cryptographic provider cannot generate or encode the key. + pub fn generate_for_development(kid: impl Into) -> anyhow::Result { + let key = Rsa::generate(3072)?; + let pem = String::from_utf8(key.private_key_to_pem()?)?; + Self::from_pem(kid, &pem) + } + fn verified(&self, token: &str, typ: &str, issuer: &str) -> Result { + if token.len() > 16384 { + return Err(()); + } + let parts: Vec<_> = token.split('.').collect(); + if parts.len() != 3 { + return Err(()); + } + let header: Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[0]).map_err(|_| ())?) + .map_err(|_| ())?; + if header["alg"] != "RS256" + || header["typ"] != typ + || header["kid"] != self.kid + || header.get("crit").is_some() + { + return Err(()); + } + let signature = URL_SAFE_NO_PAD.decode(parts[2]).map_err(|_| ())?; + let mut verifier = Verifier::new(MessageDigest::sha256(), &self.key).map_err(|_| ())?; + verifier + .update(format!("{}.{}", parts[0], parts[1]).as_bytes()) + .map_err(|_| ())?; + if !verifier.verify(&signature).map_err(|_| ())? { + return Err(()); + } + let claims: Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[1]).map_err(|_| ())?) + .map_err(|_| ())?; + if claims["iss"] != issuer + || claims + .get("iat") + .and_then(Value::as_i64) + .is_none_or(|iat| iat > Utc::now().timestamp() + 30) + { + return Err(()); + } + Ok(claims) + } +} +impl Rs256KeyProvider { + pub(super) fn sign(&self, token_type: &str, claims: &Value) -> Result { + let header = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({"alg":"RS256","kid":self.kid,"typ":token_type})) + .map_err(|_| ())?, + ); + let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).map_err(|_| ())?); + let input = format!("{header}.{payload}"); + let mut signer = Signer::new(MessageDigest::sha256(), &self.key).map_err(|_| ())?; + signer.update(input.as_bytes()).map_err(|_| ())?; + Ok(format!( + "{input}.{}", + URL_SAFE_NO_PAD.encode(signer.sign_to_vec().map_err(|_| ())?) + )) + } + pub(super) fn jwks(&self) -> Value { + // Constructors verify that the private key is RSA. + let rsa = self.key.rsa().expect("validated RSA key"); + json!({"keys":[{"kty":"RSA","use":"sig","alg":"RS256","kid":self.kid,"n":URL_SAFE_NO_PAD.encode(rsa.n().to_vec()),"e":URL_SAFE_NO_PAD.encode(rsa.e().to_vec())}]}) + } + pub(super) fn verify(&self, token: &str, token_type: &str, issuer: &str) -> Result { + let claims = self.verified(token, token_type, issuer)?; + if claims + .get("exp") + .and_then(Value::as_i64) + .is_none_or(|exp| exp <= Utc::now().timestamp()) + { + return Err(()); + } + Ok(claims) + } + pub(super) fn verify_logout(&self, token: &str, issuer: &str) -> Result { + self.verified(token, "JWT", issuer) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rsa_verifies_signatures_types_expiry_and_logout_hints() { + let key = + Rs256KeyProvider::generate_for_development("test").expect("generate RSA test key"); + let now = Utc::now().timestamp(); + let claims = json!({"iss":"https://auth.example","sub":"user","aud":"client","iat":now-60,"exp":now-1}); + let expired = key + .sign("JWT", &claims) + .expect("sign expired ID token hint"); + assert!(key.verify(&expired, "JWT", "https://auth.example").is_err()); + assert!(key.verify_logout(&expired, "https://auth.example").is_ok()); + assert!(key.verify_logout(&expired, "https://evil.example").is_err()); + let mut valid = claims; + valid["exp"] = json!(now + 300); + let token = key.sign("at+jwt", &valid).expect("sign access token"); + assert!(key.verify(&token, "at+jwt", "https://auth.example").is_ok()); + assert!(key.verify(&token, "JWT", "https://auth.example").is_err()); + let mut bytes = token.into_bytes(); + let n = bytes.len(); + bytes[n - 10] = if bytes[n - 10] == b'A' { b'B' } else { b'A' }; + assert!( + key.verify( + std::str::from_utf8(&bytes).expect("modified compact token remains ASCII"), + "at+jwt", + "https://auth.example" + ) + .is_err() + ); + assert_eq!(key.jwks()["keys"][0]["kty"], "RSA"); + } +} diff --git a/apps/auth-service/src/oidc/tests.rs b/apps/auth-service/src/oidc/tests.rs new file mode 100644 index 000000000..84453a44b --- /dev/null +++ b/apps/auth-service/src/oidc/tests.rs @@ -0,0 +1,471 @@ +use super::*; +use axum::{ + body::{Body, to_bytes}, + http::{Method, Request}, +}; +use piquel_auth_protocol::AuthenticationMethod; +use piquel_repository::{BootstrapOidcClient, DatabaseConfig, InsertUser, InsertVerifiedEmail}; +use tower::ServiceExt; + +struct Flow { + app: OidcApplication, + client: BootstrapOidcClient, + cookie: String, + user_id: UserId, + basic: Option, +} +impl Flow { + async fn new(confidential: bool, trusted: bool) -> Self { + let url = std::env::var("TEST_DATABASE_URL") + .expect("TEST_DATABASE_URL must name a disposable PostgreSQL database"); + let db = Database::connect( + DatabaseConfig::new_development(&url, 5, std::time::Duration::from_secs(5)) + .expect("valid local test database configuration"), + ) + .await + .expect("connect to the disposable PostgreSQL database"); + db.run_migrations() + .await + .expect("apply test database migrations"); + let user_id = UserId::new(); + let mut tx = db.begin().await.expect("begin test account transaction"); + tx.users() + .insert(&InsertUser { + id: user_id, + username: format!("oidc_{}", &user_id.to_string()[24..]), + display_name: "OIDC Test".into(), + }) + .await + .expect("insert test account"); + tx.emails() + .insert_verified(&InsertVerifiedEmail { + id: TokenId::new(), + user_id, + normalized_email: format!("{user_id}@example.com"), + is_primary: true, + verified_at: Utc::now(), + }) + .await + .expect("insert verified test email"); + let cookie = + crate::security::create_session(&mut tx, user_id, AuthenticationMethod::Passkey) + .await + .expect("create test browser session") + .split(';') + .next() + .expect("extract session cookie pair") + .to_owned(); + tx.commit().await.expect("commit test account transaction"); + let secret = "randomly-generated-example-secret-for-testing-0123456789"; + let client = BootstrapOidcClient { + id: format!("test-{user_id}"), + display_name: "Test app".into(), + redirect_uris: vec!["https://client.example/callback".into()], + post_logout_uris: vec!["https://client.example/logout".into()], + allowed_scopes: vec![ + "openid".into(), + "profile".into(), + "email".into(), + "offline_access".into(), + ], + allowed_audiences: vec!["test-api".into()], + allow_refresh: true, + enabled: true, + trusted, + client_secret_hash: confidential.then(|| { + OidcApplication::client_secret_hash(secret).expect("hash test client secret") + }), + }; + db.oidc() + .bootstrap_client(&client) + .await + .expect("register test OIDC client"); + let basic = confidential.then(|| { + format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode(format!("{}:{secret}", client.id)) + ) + }); + let app = OidcApplication::new( + db, + &Url::parse("https://auth.example.com").expect("parse test issuer URL"), + &[7; 32], + Arc::new( + Rs256KeyProvider::generate_for_development("oidc-tests") + .expect("generate test RSA signing key"), + ), + ) + .expect("construct test OIDC application"); + Self { + app, + client, + cookie, + user_id, + basic, + } + } + async fn request( + &self, + method: Method, + uri: &str, + form: &[(&str, &str)], + basic: Option<&str>, + ) -> Response { + let mut builder = Request::builder() + .method(method) + .uri(uri) + .header(header::COOKIE, &self.cookie) + .header(header::ORIGIN, "https://auth.example.com") + .header("x-piquel-csrf", "1"); + if let Some(basic) = basic { + builder = builder.header(header::AUTHORIZATION, basic); + } + let body = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs(form.iter().copied()) + .finish(); + let request = builder + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from(body)) + .expect("build test HTTP request"); + routes(self.app.clone()) + .oneshot(request) + .await + .expect("dispatch OIDC HTTP request") + } + async fn authorize(&self, scope: &str, prompt: Option<&str>) -> Response { + let mut url = Url::parse("https://auth.example.com/oauth/authorize") + .expect("parse authorization endpoint URL"); + url.query_pairs_mut().extend_pairs([ + ("response_type", "code"), + ("client_id", &self.client.id), + ("redirect_uri", &self.client.redirect_uris[0]), + ("scope", scope), + ("state", "test-state"), + ("nonce", "test-nonce"), + ("code_challenge_method", "S256"), + ( + "code_challenge", + &URL_SAFE_NO_PAD.encode(Sha256::digest(Self::verifier().as_bytes())), + ), + ]); + if let Some(prompt) = prompt { + url.query_pairs_mut().append_pair("prompt", prompt); + } + self.request( + Method::GET, + &format!( + "{}?{}", + url.path(), + url.query() + .expect("authorization URL contains query parameters") + ), + &[], + None, + ) + .await + } + fn verifier() -> &'static str { + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + } + fn location(response: &Response) -> Url { + Url::parse( + response + .headers() + .get(header::LOCATION) + .expect("authorization response has a Location header") + .to_str() + .expect("Location header is valid text"), + ) + .expect("Location header contains an absolute URL") + } + fn parameter(url: &Url, name: &str) -> String { + url.query_pairs() + .find(|(key, _)| key == name) + .expect("redirect contains expected query parameter") + .1 + .into_owned() + } + async fn json(response: Response) -> Value { + serde_json::from_slice( + &to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("read complete HTTP response body"), + ) + .expect("decode HTTP JSON response") + } + async fn code(&self, scopes: &str) -> String { + let response = self.authorize(scopes, None).await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + let mut location = Self::location(&response); + if location.path() == "/authorize" { + let transaction = Self::parameter(&location, "transaction"); + let response = self + .request( + Method::POST, + "/oauth/authorize/decision", + &[("transaction", &transaction), ("decision", "approve")], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + location = Url::parse( + Self::json(response).await["redirect_url"] + .as_str() + .expect("decision response includes redirect_url"), + ) + .expect("decision redirect is a valid URL"); + } + Self::parameter(&location, "code") + } + async fn exchange(&self, code: &str, verifier: &str, basic: Option<&str>) -> Response { + self.request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", "authorization_code"), + ("client_id", &self.client.id), + ("redirect_uri", &self.client.redirect_uris[0]), + ("code", code), + ("code_verifier", verifier), + ], + basic, + ) + .await + } + async fn refresh(&self, token: &str) -> Response { + self.request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", "refresh_token"), + ("client_id", &self.client.id), + ("refresh_token", token), + ], + self.basic.as_deref(), + ) + .await + } +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn public_consent_pkce_claim_scoping_and_replay() { + let flow = Flow::new(false, false).await; + let response = flow.authorize("openid", Some("none")).await; + assert_eq!( + Flow::parameter(&Flow::location(&response), "error"), + "consent_required" + ); + let code = flow.code("openid").await; + assert_eq!( + flow.exchange(&code, "wrong", None).await.status(), + StatusCode::BAD_REQUEST + ); + let response = flow.exchange(&code, Flow::verifier(), None).await; + assert_eq!(response.status(), StatusCode::OK); + let tokens = Flow::json(response).await; + let claims = flow + .app + .keys + .verify( + tokens["id_token"] + .as_str() + .expect("token response contains an ID token"), + "JWT", + &flow.app.issuer, + ) + .expect("verify scoped ID token"); + assert_eq!(claims["nonce"], "test-nonce"); + assert!(claims.get("name").is_none()); + assert!(claims.get("email").is_none()); + assert_eq!( + flow.exchange(&code, Flow::verifier(), None).await.status(), + StatusCode::BAD_REQUEST + ); + let response = flow.authorize("openid", Some("none")).await; + assert!( + Flow::location(&response) + .query_pairs() + .any(|(name, _)| name == "code") + ); + let response = flow.authorize("openid email", Some("none")).await; + assert_eq!( + Flow::parameter(&Flow::location(&response), "error"), + "consent_required" + ); + let response = flow.authorize("openid", Some("login")).await; + assert_eq!(Flow::location(&response).path(), "/login"); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +#[expect( + clippy::too_many_lines, + reason = "The scenario follows one refresh family through narrowing, replay and logout." +)] +async fn confidential_refresh_rotation_logout_and_client_binding() { + let flow = Flow::new(true, true).await; + let code = flow.code("openid email offline_access").await; + assert_eq!( + flow.exchange(&code, Flow::verifier(), None).await.status(), + StatusCode::UNAUTHORIZED + ); + let response = flow + .exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await; + assert_eq!(response.status(), StatusCode::OK); + let tokens = Flow::json(response).await; + let claims = flow + .app + .keys + .verify( + tokens["id_token"] + .as_str() + .expect("token response contains an ID token"), + "JWT", + &flow.app.issuer, + ) + .expect("verify confidential client ID token"); + assert_eq!(claims["email"], format!("{}@example.com", flow.user_id)); + assert_eq!(claims["email_verified"], true); + let old = tokens["refresh_token"] + .as_str() + .expect("token response contains a refresh token"); + let other = Flow::new(false, true).await; + assert_eq!(other.refresh(old).await.status(), StatusCode::BAD_REQUEST); + let invalid = flow + .request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", "refresh_token"), + ("client_id", &flow.client.id), + ("refresh_token", old), + ("scope", "openid admin"), + ], + flow.basic.as_deref(), + ) + .await; + assert_eq!(invalid.status(), StatusCode::BAD_REQUEST); + assert_eq!(Flow::json(invalid).await["error"], "invalid_scope"); + let response = flow + .request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", "refresh_token"), + ("client_id", &flow.client.id), + ("refresh_token", old), + ("scope", "openid"), + ], + flow.basic.as_deref(), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let narrowed = Flow::json(response).await; + assert_eq!(narrowed["scope"], "openid"); + let narrowed_claims = flow + .app + .keys + .verify( + narrowed["id_token"] + .as_str() + .expect("refresh response contains an ID token"), + "JWT", + &flow.app.issuer, + ) + .expect("verify narrowed ID token"); + assert!(narrowed_claims.get("email").is_none()); + let fresh = narrowed["refresh_token"] + .as_str() + .expect("refresh response contains the rotated token") + .to_owned(); + assert_eq!(flow.refresh(old).await.status(), StatusCode::BAD_REQUEST); + assert_eq!(flow.refresh(&fresh).await.status(), StatusCode::BAD_REQUEST); + let code = flow.code("openid offline_access").await; + let response = flow + .exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await; + let tokens = Flow::json(response).await; + let response = flow + .request( + Method::POST, + "/oidc/logout", + &[ + ("client_id", &flow.client.id), + ("post_logout_redirect_uri", &flow.client.post_logout_uris[0]), + ], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert!( + response.headers()[header::SET_COOKIE] + .to_str() + .expect("Set-Cookie header is valid text") + .contains("Max-Age=0") + ); + assert_eq!( + flow.refresh( + tokens["refresh_token"] + .as_str() + .expect("token response contains a refresh token") + ) + .await + .status(), + StatusCode::BAD_REQUEST + ); + assert_eq!( + Flow::parameter( + &Flow::location(&flow.authorize("openid", Some("none")).await), + "error" + ), + "login_required" + ); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn policy_reduction_blocks_outstanding_codes_and_refresh() { + let mut flow = Flow::new(false, true).await; + let code = flow.code("openid email").await; + flow.client.allowed_scopes = vec!["openid".into(), "offline_access".into()]; + flow.app + .database + .oidc() + .bootstrap_client(&flow.client) + .await + .expect("apply reduced client scope policy"); + assert_eq!( + flow.exchange(&code, Flow::verifier(), None).await.status(), + StatusCode::BAD_REQUEST + ); + let code = flow.code("openid offline_access").await; + let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; + flow.client.allow_refresh = false; + flow.app + .database + .oidc() + .bootstrap_client(&flow.client) + .await + .expect("disable client refresh permission"); + assert_eq!( + flow.refresh( + tokens["refresh_token"] + .as_str() + .expect("token response contains a refresh token") + ) + .await + .status(), + StatusCode::BAD_REQUEST + ); + let response = flow + .request( + Method::GET, + "/oidc/logout?client_id=unknown&post_logout_redirect_uri=https%3A%2F%2Fevil.example", + &[], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); +} diff --git a/apps/auth-service/src/passkey.rs b/apps/auth-service/src/passkey.rs index ee164fed7..4cb1ee03f 100644 --- a/apps/auth-service/src/passkey.rs +++ b/apps/auth-service/src/passkey.rs @@ -1,9 +1,5 @@ -//! `WebAuthn` registration/authentication with database-backed single-use state. - -use crate::{ - Es256KeyProvider, - account::{validate_display_name, validate_username}, -}; +//! Browser-bound `WebAuthn` ceremonies and passkey-only management authorization. +use crate::security::{self, ApiError, BrowserSecret}; use axum::{ Json, Router, extract::{Path, State}, @@ -11,1277 +7,830 @@ use axum::{ response::{IntoResponse, Response}, routing::{get, patch, post}, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use chrono::{Duration, Utc}; use piquel_auth_protocol::{AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ - AppendAuditEvent, AppendInternalEvent, Database, DatabaseError, InsertCeremony, InsertPasskey, - InsertPurposeAuthorization, InsertSession, InsertUser, StoredSession, + AppendAuditEvent, Database, DatabaseTransaction, InsertCeremony, InsertPasskey, InsertUser, }; -use rand::{RngCore, rngs::OsRng}; use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; +use serde_json::{Value, json}; use std::sync::Arc; -use thiserror::Error; use url::Url; -use webauthn_rs::{ - Webauthn, WebauthnBuilder, - prelude::{ - CreationChallengeResponse, Passkey, PasskeyAuthentication, PasskeyRegistration, - PublicKeyCredential, RegisterPublicKeyCredential, RequestChallengeResponse, - }, -}; +use webauthn_rs::{Webauthn, WebauthnBuilder, prelude::*}; +use webauthn_rs_proto::ResidentKeyRequirement; -/// Runnable passkey HTTP application state. #[derive(Clone)] pub struct PasskeyApplication { database: Database, webauthn: Arc, - issuer: Arc, - purpose_keys: Arc, -} - -const PURPOSE_TOKEN_TYPE: &str = "purpose+jwt"; -const PURPOSE_AUDIENCE: &str = "piquel-account-management"; -const MANAGE_PASSKEYS_PURPOSE: &str = "manage-passkeys"; -const PURPOSE_TOKEN_SECONDS: i64 = 120; - -#[derive(Debug, Error)] -pub enum PasskeyConfigurationError { - #[error("invalid WebAuthn relying-party configuration")] - Invalid, -} - -impl PasskeyApplication { - /// Builds exact origin/RP validation. Subdomains and alternate ports are not enabled. - /// - /// # Errors - /// - /// Returns an error when the origin and RP identifier are not an exact valid pair. - pub fn new( - database: Database, - rp_id: &str, - origin: &Url, - purpose_keys: Arc, - ) -> Result { - validate_rp_origin(rp_id, origin)?; - let webauthn = WebauthnBuilder::new(rp_id, origin) - .map_err(|_| PasskeyConfigurationError::Invalid)? - .rp_name("Piquel") - .build() - .map_err(|_| PasskeyConfigurationError::Invalid)?; - Ok(Self { - database, - webauthn: Arc::new(webauthn), - issuer: origin.as_str().trim_end_matches('/').into(), - purpose_keys, - }) - } + invite_required: bool, } -fn validate_rp_origin(rp_id: &str, origin: &Url) -> Result<(), PasskeyConfigurationError> { - if origin.scheme() != "https" - || origin.username() != "" - || origin.password().is_some() - || origin.path() != "/" - || origin.query().is_some() - || origin.fragment().is_some() - { - return Err(PasskeyConfigurationError::Invalid); - } - let host = origin - .host_str() - .ok_or(PasskeyConfigurationError::Invalid)?; - if host != rp_id - && !host - .strip_suffix(rp_id) - .is_some_and(|prefix| prefix.ends_with('.')) - { - return Err(PasskeyConfigurationError::Invalid); - } - Ok(()) +#[derive(Serialize, Deserialize)] +enum Ceremony { + Register { + user_id: UserId, + username: String, + display_name: String, + invitation: Option>, + pending: Option, + state: PasskeyRegistration, + }, + Login { + user_id: UserId, + state: PasskeyAuthentication, + }, + Discover { + state: DiscoverableAuthentication, + }, + Manage { + user_id: UserId, + session_id: SessionId, + state: PasskeyAuthentication, + }, + Enroll { + user_id: UserId, + session_id: SessionId, + state: PasskeyRegistration, + }, } - -pub(super) fn routes(application: PasskeyApplication) -> Router { - Router::new() - .route("/webauthn/register/start", post(start_registration)) - .route("/webauthn/register/finish", post(finish_registration)) - .route("/webauthn/authenticate/start", post(start_authentication)) - .route("/webauthn/authenticate/finish", post(finish_authentication)) - .route("/account/passkeys/enroll/start", post(start_enrollment)) - .route("/account/passkeys/enroll/finish", post(finish_enrollment)) - .route( - "/account/passkeys/authorize/start", - post(start_purpose_authorization), - ) - .route( - "/account/passkeys/authorize/finish", - post(finish_purpose_authorization), - ) - .route("/account/passkeys", get(list_passkeys)) - .route( - "/account/passkeys/{id}", - patch(rename_passkey).delete(revoke_passkey), - ) - .route("/session/logout", post(logout)) - .with_state(application) +#[derive(Serialize, Deserialize)] +struct BoundCeremony { + browser_digest: Vec, + ceremony: Ceremony, +} +#[derive(Clone, Copy, Default, Deserialize)] +#[serde(rename_all = "snake_case")] +enum PasskeyKind { + #[default] + Standard, + GooglePasswordManager, +} +#[derive(Default, Deserialize)] +struct EnrollmentStart { + #[serde(default)] + passkey_kind: PasskeyKind, } - #[derive(Deserialize)] struct RegistrationStart { + #[serde(default)] + passkey_kind: PasskeyKind, username: String, + #[serde(default)] display_name: String, -} -#[derive(Serialize)] -struct RegistrationStarted { - ceremony_id: TokenId, - public_key: CreationChallengeResponse, -} -#[derive(Serialize, Deserialize)] -struct RegistrationState { - user_id: UserId, - username: String, - display_name: String, - webauthn: PasskeyRegistration, + invitation: Option, } #[derive(Deserialize)] struct RegistrationFinish { ceremony_id: TokenId, credential: RegisterPublicKeyCredential, - #[serde(default = "default_passkey_name")] + #[serde(default = "RegistrationFinish::default_name")] friendly_name: String, } -fn default_passkey_name() -> String { - "Passkey".into() -} - -async fn start_registration( - State(app): State, - Json(input): Json, -) -> Result, ApiError> { - validate_username(&input.username).map_err(|()| ApiError)?; - validate_display_name(&input.display_name).map_err(|()| ApiError)?; - let user_id = UserId::new(); - let (challenge, webauthn) = app - .webauthn - .start_passkey_registration( - user_id.as_uuid(), - &input.username, - &input.display_name, - None, - ) - .map_err(|_| ApiError)?; - let state = RegistrationState { - user_id, - username: input.username, - display_name: input.display_name, - webauthn, - }; - let state = serde_json::to_value(state).map_err(|_| ApiError)?; - let serialized = serde_json::to_vec(&state).map_err(|_| ApiError)?; - let ceremony_id = TokenId::new(); - app.database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: ceremony_id, - // Bootstrap users do not exist until the registration response is - // verified and the account is created atomically at finish time. - user_id: None, - session_id: None, - kind: "registration".into(), - challenge_digest: Sha256::digest(serialized).to_vec(), - state, - expires_at: Utc::now() + Duration::minutes(5), - }) - .await - .map_err(|_| ApiError)?; - Ok(Json(RegistrationStarted { - ceremony_id, - public_key: challenge, - })) -} - -async fn finish_registration( - State(app): State, - Json(input): Json, -) -> Result { - if input.friendly_name.trim().is_empty() || input.friendly_name.chars().count() > 80 { - return Err(ApiError); +impl RegistrationFinish { + fn default_name() -> String { + "Passkey".into() } - // Consumption is intentionally committed before processing the response: - // invalid responses and downstream failures must not make a challenge - // reusable. - let ceremony = app - .database - .passkeys() - .consume_ceremony(input.ceremony_id, "registration") - .await - .map_err(|_| ApiError)?; - let state: RegistrationState = serde_json::from_value(ceremony.state).map_err(|_| ApiError)?; - let passkey = app - .webauthn - .finish_passkey_registration(&input.credential, &state.webauthn) - .map_err(|_| ApiError)?; - let credential_id = passkey.cred_id().as_ref().to_vec(); - let credential = serde_json::to_value(passkey).map_err(|_| ApiError)?; - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - transaction - .users() - .insert(&InsertUser { - id: state.user_id, - username: state.username, - display_name: state.display_name, - }) - .await - .map_err(|_| ApiError)?; - transaction - .passkeys() - .insert(&InsertPasskey { - id: TokenId::new(), - credential_id, - user_id: state.user_id, - credential, - friendly_name: input.friendly_name, - }) - .await - .map_err(|_| ApiError)?; - let cookie = create_session(&mut transaction, state.user_id).await?; - transaction - .audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(state.user_id), - action: "passkey.enroll".into(), - outcome: "success".into(), - request_metadata: serde_json::json!({}), - }) - .await - .map_err(|_| ApiError)?; - transaction - .internal_events() - .append(&AppendInternalEvent { - id: TokenId::new(), - aggregate_type: "user".into(), - aggregate_id: state.user_id, - event_type: "passkey.enrolled".into(), - schema_version: 1, - payload: serde_json::json!({}), - }) - .await - .map_err(|_| ApiError)?; - transaction.commit().await.map_err(|_| ApiError)?; - no_content_with_cookie(&cookie) } - #[derive(Deserialize)] -struct AuthenticationStart { - username: String, -} -#[derive(Serialize)] -struct AuthenticationStarted { - ceremony_id: TokenId, - public_key: RequestChallengeResponse, -} -#[derive(Serialize, Deserialize)] -struct AuthenticationState { - user_id: UserId, - webauthn: PasskeyAuthentication, +struct LoginStart { + username: Option, } #[derive(Deserialize)] struct AuthenticationFinish { ceremony_id: TokenId, credential: PublicKeyCredential, } - -async fn start_authentication( - State(app): State, - Json(input): Json, -) -> Result, ApiError> { - validate_username(&input.username).map_err(|()| ApiError)?; - let user = app - .database - .users() - .find_active_by_username(&input.username) - .await - .map_err(|_| ApiError)? - .ok_or(ApiError)?; - let passkeys = active_passkeys(&app.database, user.id).await?; - let (challenge, webauthn) = app - .webauthn - .start_passkey_authentication(&passkeys) - .map_err(|_| ApiError)?; - let state = serde_json::to_value(AuthenticationState { - user_id: user.id, - webauthn, - }) - .map_err(|_| ApiError)?; - let serialized = serde_json::to_vec(&state).map_err(|_| ApiError)?; - let ceremony_id = TokenId::new(); - app.database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: ceremony_id, - user_id: Some(user.id), - session_id: None, - kind: "authentication".into(), - challenge_digest: Sha256::digest(serialized).to_vec(), - state, - expires_at: Utc::now() + Duration::minutes(5), - }) - .await - .map_err(|_| ApiError)?; - Ok(Json(AuthenticationStarted { - ceremony_id, - public_key: challenge, - })) +#[derive(Deserialize)] +struct Rename { + friendly_name: String, } -async fn finish_authentication( - State(app): State, - Json(input): Json, -) -> Result { - let ceremony = app - .database - .passkeys() - .consume_ceremony(input.ceremony_id, "authentication") - .await - .map_err(|_| ApiError)?; - let state: AuthenticationState = - serde_json::from_value(ceremony.state).map_err(|_| ApiError)?; - let result = app - .webauthn - .finish_passkey_authentication(&input.credential, &state.webauthn) - .map_err(|_| ApiError)?; - if !result.user_verified() { - return Err(ApiError); - } - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - let stored = transaction - .passkeys() - .find_active_by_credential_id_for_update(result.cred_id().as_ref()) - .await - .map_err(|_| ApiError)? - .filter(|credential| credential.user_id == state.user_id) - .ok_or(ApiError)?; - let mut passkey: Passkey = serde_json::from_value(stored.credential).map_err(|_| ApiError)?; - passkey.update_credential(&result).ok_or(ApiError)?; - let credential = serde_json::to_value(passkey).map_err(|_| ApiError)?; - let updated = transaction - .passkeys() - .update_after_authentication(result.cred_id().as_ref(), &credential) - .await - .map_err(|_| ApiError)?; - if !updated { - return Err(ApiError); - } - let cookie = create_session(&mut transaction, state.user_id).await?; - transaction - .audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(state.user_id), - action: "passkey.authenticate".into(), - outcome: "success".into(), - request_metadata: serde_json::json!({}), +impl PasskeyApplication { + pub fn new( + database: Database, + rp_id: &str, + origin: &Url, + invite_required: bool, + ) -> anyhow::Result { + anyhow::ensure!( + origin.host_str() == Some(rp_id) + && origin.username().is_empty() + && origin.password().is_none() + && origin.path() == "/" + && origin.query().is_none() + && origin.fragment().is_none(), + "WebAuthn origin must exactly match its RP ID" + ); + anyhow::ensure!( + origin.scheme() == "https" + || (origin.scheme() == "http" && matches!(rp_id, "localhost" | "127.0.0.1")), + "WebAuthn requires HTTPS outside loopback development" + ); + Ok(Self { + database, + webauthn: Arc::new( + WebauthnBuilder::new(rp_id, origin)? + .rp_name("Piquel") + .build()?, + ), + invite_required, }) - .await - .map_err(|_| ApiError)?; - transaction.commit().await.map_err(|_| ApiError)?; - no_content_with_cookie(&cookie) -} - -async fn active_passkeys(database: &Database, user_id: UserId) -> Result, ApiError> { - let stored = database - .passkeys() - .list_active(user_id) - .await - .map_err(|_| ApiError)?; - if stored.is_empty() { - return Err(ApiError); } - stored - .into_iter() - .map(|stored| serde_json::from_value(stored.credential).map_err(|_| ApiError)) - .collect() -} - -#[derive(Serialize, Deserialize)] -struct PurposeAuthenticationState { - user_id: UserId, - session_id: SessionId, - webauthn: PasskeyAuthentication, -} -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct PurposeTokenClaims { - iss: String, - sub: UserId, - aud: String, - purpose: String, - sid: SessionId, - auth_time: i64, - iat: i64, - exp: i64, - jti: TokenId, -} - -impl PurposeTokenClaims { - fn is_valid_for(&self, issuer: &str, user_id: UserId, session_id: SessionId, now: i64) -> bool { - self.iss == issuer - && self.sub == user_id - && self.aud == PURPOSE_AUDIENCE - && self.purpose == MANAGE_PASSKEYS_PURPOSE - && self.sid == session_id - && self.exp > now - && self.exp > self.iat - && self.exp - self.iat <= PURPOSE_TOKEN_SECONDS - && self.iat <= now + 30 - && self.auth_time <= self.iat - && self.iat - self.auth_time <= 30 + pub(crate) fn routes(self) -> Router { + Router::new() + .route("/webauthn/register/start", post(Self::start_registration)) + .route("/webauthn/register/finish", post(Self::finish_registration)) + .route("/webauthn/authenticate/start", post(Self::start_login)) + .route("/webauthn/authenticate/finish", post(Self::finish_login)) + .route( + "/account/passkeys/authorize/start", + post(Self::start_management), + ) + .route( + "/account/passkeys/authorize/finish", + post(Self::finish_management), + ) + .route( + "/account/passkeys/enroll/start", + post(Self::start_enrollment), + ) + .route( + "/account/passkeys/enroll/finish", + post(Self::finish_enrollment), + ) + .route("/account/passkeys", get(Self::list)) + .route( + "/account/passkeys/{id}", + patch(Self::rename).delete(Self::revoke), + ) + .route("/session", get(Self::session_view)) + .route("/session/logout", post(Self::logout)) + .with_state(self) } -} -#[derive(Serialize)] -struct PurposeAuthorized { - purpose_token: String, - token_type: &'static str, - expires_in: i64, -} - -async fn start_purpose_authorization( - State(app): State, - headers: HeaderMap, -) -> Result, ApiError> { - let session = active_session(&app.database, &headers).await?; - let passkeys = active_passkeys(&app.database, session.user_id).await?; - let (challenge, webauthn) = app - .webauthn - .start_passkey_authentication(&passkeys) - .map_err(|_| ApiError)?; - let state = serde_json::to_value(PurposeAuthenticationState { - user_id: session.user_id, - session_id: session.id, - webauthn, - }) - .map_err(|_| ApiError)?; - let serialized = serde_json::to_vec(&state).map_err(|_| ApiError)?; - let ceremony_id = TokenId::new(); - app.database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: ceremony_id, - user_id: Some(session.user_id), - session_id: Some(session.id), - kind: "purpose_authentication".into(), - challenge_digest: Sha256::digest(serialized).to_vec(), - state, - expires_at: Utc::now() + Duration::minutes(5), - }) - .await - .map_err(|_| ApiError)?; - Ok(Json(AuthenticationStarted { - ceremony_id, - public_key: challenge, - })) -} - -async fn finish_purpose_authorization( - State(app): State, - headers: HeaderMap, - Json(input): Json, -) -> Result { - let session = active_session(&app.database, &headers).await?; - let ceremony = app - .database - .passkeys() - .consume_ceremony(input.ceremony_id, "purpose_authentication") - .await - .map_err(|_| ApiError)?; - let state: PurposeAuthenticationState = - serde_json::from_value(ceremony.state).map_err(|_| ApiError)?; - if state.user_id != session.user_id || state.session_id != session.id { - return Err(ApiError); + fn valid_name(name: &str) -> bool { + !name.trim().is_empty() && name.chars().count() <= 80 && !name.chars().any(char::is_control) } - let result = app - .webauthn - .finish_passkey_authentication(&input.credential, &state.webauthn) - .map_err(|_| ApiError)?; - if !result.user_verified() { - return Err(ApiError); + fn failed(error: impl std::fmt::Debug) -> ApiError { + // Authentication errors are intentionally generic; credential/challenge contents are never logged. + tracing::debug!(?error, "WebAuthn request rejected"); + ApiError::bad_request("Passkey verification failed. Please try again.") + } + fn response(value: impl Serialize, cookie: Option) -> Result { + let mut response = Json(value).into_response(); + if let Some(cookie) = cookie { + response.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_str(&cookie).map_err(ApiError::internal)?, + ); + } + Ok(response) + } + fn signed_in(cookie: &str) -> Result { + let mut response = StatusCode::NO_CONTENT.into_response(); + response.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_str(cookie).map_err(ApiError::internal)?, + ); + Ok(response) } - let now = Utc::now(); - let authorization_id = TokenId::new(); - let claims = PurposeTokenClaims { - iss: app.issuer.to_string(), - sub: session.user_id, - aud: PURPOSE_AUDIENCE.into(), - purpose: MANAGE_PASSKEYS_PURPOSE.into(), - sid: session.id, - auth_time: now.timestamp(), - iat: now.timestamp(), - exp: (now + Duration::seconds(PURPOSE_TOKEN_SECONDS)).timestamp(), - jti: authorization_id, - }; - let token = app - .purpose_keys - .sign(PURPOSE_TOKEN_TYPE, &claims) - .map_err(|()| ApiError)?; - - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - let stored = transaction - .passkeys() - .find_active_by_credential_id_for_update(result.cred_id().as_ref()) - .await - .map_err(|_| ApiError)? - .filter(|credential| credential.user_id == session.user_id) - .ok_or(ApiError)?; - let mut passkey: Passkey = serde_json::from_value(stored.credential).map_err(|_| ApiError)?; - passkey.update_credential(&result).ok_or(ApiError)?; - let updated = transaction - .passkeys() - .update_after_authentication( - result.cred_id().as_ref(), - &serde_json::to_value(passkey).map_err(|_| ApiError)?, + async fn start( + &self, + headers: &HeaderMap, + kind: &str, + user_id: Option, + session_id: Option, + ceremony: Ceremony, + challenge: impl Serialize, + ) -> Result { + let browser = BrowserSecret::from_cookie(headers, "__Host-piquel_ceremony") + .unwrap_or_else(BrowserSecret::new); + let id = TokenId::new(); + self.database + .passkeys() + .insert_ceremony(&InsertCeremony { + id, + user_id, + session_id, + kind: kind.into(), + challenge_digest: browser.digest(), + state: serde_json::to_value(BoundCeremony { + browser_digest: browser.digest(), + ceremony, + }) + .map_err(ApiError::internal)?, + expires_at: Utc::now() + Duration::minutes(5), + }) + .await?; + Self::response( + json!({"ceremony_id":id,"public_key":challenge}), + Some(browser.cookie("__Host-piquel_ceremony", 600)), ) - .await - .map_err(|_| ApiError)?; - if !updated { - return Err(ApiError); } - transaction - .passkeys() - .insert_purpose_authorization(&InsertPurposeAuthorization { - id: authorization_id, - user_id: session.user_id, - session_id: session.id, - purpose: MANAGE_PASSKEYS_PURPOSE.into(), - expires_at: now + Duration::seconds(PURPOSE_TOKEN_SECONDS), - }) - .await - .map_err(|_| ApiError)?; - transaction - .audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(session.user_id), - action: "passkey.authorize_management".into(), - outcome: "success".into(), - request_metadata: serde_json::json!({}), - }) - .await - .map_err(|_| ApiError)?; - transaction.commit().await.map_err(|_| ApiError)?; - - let mut response = Json(PurposeAuthorized { - purpose_token: token, - token_type: "Bearer", - expires_in: PURPOSE_TOKEN_SECONDS, - }) - .into_response(); - response - .headers_mut() - .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); - Ok(response) -} - -#[derive(Serialize, Deserialize)] -struct EnrollmentState { - user_id: UserId, - session_id: SessionId, - authorization_id: TokenId, - webauthn: PasskeyRegistration, -} - -async fn start_enrollment( - State(app): State, - headers: HeaderMap, -) -> Result, ApiError> { - let session = active_session(&app.database, &headers).await?; - let authorization = require_purpose_authorization(&app, &headers, &session).await?; - let user = app - .database - .users() - .find_by_id(session.user_id) - .await - .map_err(|_| ApiError)? - .ok_or(ApiError)?; - let (challenge, webauthn) = app - .webauthn - .start_passkey_registration(user.id.as_uuid(), &user.username, &user.display_name, None) - .map_err(|_| ApiError)?; - let state = serde_json::to_value(EnrollmentState { - user_id: user.id, - session_id: session.id, - authorization_id: authorization.jti, - webauthn, - }) - .map_err(|_| ApiError)?; - let serialized = serde_json::to_vec(&state).map_err(|_| ApiError)?; - let ceremony_id = TokenId::new(); - app.database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: ceremony_id, - user_id: Some(user.id), - session_id: Some(session.id), - kind: "enrollment".into(), - challenge_digest: Sha256::digest(serialized).to_vec(), - state, - expires_at: Utc::now() + Duration::minutes(5), - }) - .await - .map_err(|_| ApiError)?; - Ok(Json(RegistrationStarted { - ceremony_id, - public_key: challenge, - })) -} - -async fn finish_enrollment( - State(app): State, - headers: HeaderMap, - Json(input): Json, -) -> Result { - if input.friendly_name.trim().is_empty() || input.friendly_name.chars().count() > 80 { - return Err(ApiError); + async fn consume( + &self, + headers: &HeaderMap, + id: TokenId, + kind: &str, + ) -> Result { + let browser = + BrowserSecret::from_cookie(headers, "__Host-piquel_ceremony").ok_or_else(|| { + ApiError::bad_request("Please restart the passkey flow in this browser.") + })?; + let record = self.database.passkeys().consume_ceremony(id, kind).await?; + let bound: BoundCeremony = + serde_json::from_value(record.state).map_err(ApiError::internal)?; + if bound.browser_digest != browser.digest() { + return Err(Self::failed("browser mismatch")); + } + Ok(bound.ceremony) } - let session = active_session(&app.database, &headers).await?; - let authorization = require_purpose_authorization(&app, &headers, &session).await?; - let ceremony = app - .database - .passkeys() - .consume_ceremony(input.ceremony_id, "enrollment") - .await - .map_err(|_| ApiError)?; - let state: EnrollmentState = serde_json::from_value(ceremony.state).map_err(|_| ApiError)?; - if state.user_id != session.user_id - || state.session_id != session.id - || state.authorization_id != authorization.jti - { - return Err(ApiError); + async fn keys(&self, user_id: UserId) -> Result, ApiError> { + self.database + .passkeys() + .list_active(user_id) + .await? + .into_iter() + .map(|v| serde_json::from_value(v.credential).map_err(ApiError::internal)) + .collect() } - let passkey = app - .webauthn - .finish_passkey_registration(&input.credential, &state.webauthn) - .map_err(|_| ApiError)?; - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - let consumed = transaction - .passkeys() - .consume_purpose_authorization( - authorization.jti, - session.user_id, - session.id, - MANAGE_PASSKEYS_PURPOSE, - ) - .await - .map_err(|_| ApiError)?; - if !consumed { - return Err(ApiError); + fn registration( + &self, + user_id: UserId, + username: &str, + name: &str, + exclusions: Option>, + kind: PasskeyKind, + headers: &HeaderMap, + ) -> Result<(CreationChallengeResponse, PasskeyRegistration), ApiError> { + if matches!(kind, PasskeyKind::GooglePasswordManager) { + if !headers + .get(header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.contains("Android")) + { + return Err(ApiError::bad_request( + "Choose Google Password Manager only on an Android device with Google services.", + )); + } + return self + .webauthn + .start_google_passkey_in_google_password_manager_only_registration( + user_id.as_uuid(), + username, + name, + exclusions, + ) + .map_err(Self::failed); + } + let (mut challenge, state) = self + .webauthn + .start_passkey_registration(user_id.as_uuid(), username, name, exclusions) + .map_err(Self::failed)?; + // Prefer account-picker credentials while retaining security keys that need a username. + if let Some(selection) = challenge.public_key.authenticator_selection.as_mut() { + selection.resident_key = Some(ResidentKeyRequirement::Preferred); + selection.require_resident_key = false; + } + Ok((challenge, state)) } - transaction - .passkeys() - .insert(&InsertPasskey { - id: TokenId::new(), - credential_id: passkey.cred_id().as_ref().to_vec(), - user_id: session.user_id, - credential: serde_json::to_value(passkey).map_err(|_| ApiError)?, - friendly_name: input.friendly_name, - }) - .await - .map_err(|_| ApiError)?; - transaction - .audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(session.user_id), - action: "passkey.enroll".into(), - outcome: "success".into(), - request_metadata: serde_json::json!({}), - }) - .await - .map_err(|_| ApiError)?; - transaction.commit().await.map_err(|_| ApiError)?; - Ok(StatusCode::NO_CONTENT) -} - -#[derive(Serialize)] -struct PasskeyView { - id: TokenId, - friendly_name: String, -} - -async fn list_passkeys( - State(app): State, - headers: HeaderMap, -) -> Result>, ApiError> { - let session = active_session(&app.database, &headers).await?; - let keys = app - .database - .passkeys() - .list_active(session.user_id) - .await - .map_err(|_| ApiError)?; - Ok(Json( - keys.into_iter() - .map(|key| PasskeyView { - id: key.id, - friendly_name: key.friendly_name, + async fn audit( + tx: &mut DatabaseTransaction<'_>, + user_id: UserId, + action: &str, + ) -> Result<(), ApiError> { + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: action.into(), + outcome: "success".into(), + request_metadata: json!({}), }) - .collect(), - )) -} - -#[derive(Deserialize)] -struct RenamePasskey { - friendly_name: String, -} - -async fn rename_passkey( - State(app): State, - headers: HeaderMap, - Path(id): Path, - Json(input): Json, -) -> Result { - if input.friendly_name.trim().is_empty() || input.friendly_name.chars().count() > 80 { - return Err(ApiError); + .await?; + Ok(()) + } + async fn update_credential( + tx: &mut DatabaseTransaction<'_>, + user_id: UserId, + result: &AuthenticationResult, + ) -> Result<(), ApiError> { + if !result.user_verified() { + return Err(Self::failed("user verification required")); + } + tx.users() + .find_active_by_id_for_update(user_id) + .await? + .ok_or_else(ApiError::unauthorized)?; + let stored = tx + .passkeys() + .find_active_by_credential_id_for_update(result.cred_id().as_ref()) + .await? + .filter(|v| v.user_id == user_id) + .ok_or_else(ApiError::unauthorized)?; + // The ceremony contains a credential snapshot. Check the latest counter under + // the row lock as well, so overlapping ceremonies cannot accept a regression. + let counter = stored + .credential + .pointer("/cred/counter") + .and_then(Value::as_u64) + .ok_or_else(|| { + ApiError::internal(anyhow::anyhow!("stored passkey counter is missing")) + })?; + if (counter > 0 || result.counter() > 0) && u64::from(result.counter()) <= counter { + return Err(Self::failed("credential counter did not increase")); + } + let mut credential: Passkey = + serde_json::from_value(stored.credential).map_err(ApiError::internal)?; + credential + .update_credential(result) + .ok_or_else(|| Self::failed("credential mismatch"))?; + if !tx + .passkeys() + .update_after_authentication( + result.cred_id().as_ref(), + &serde_json::to_value(credential).map_err(ApiError::internal)?, + ) + .await? + { + return Err(Self::failed("revoked credential")); + } + Ok(()) + } + async fn lock_management( + tx: &mut DatabaseTransaction<'_>, + session: &piquel_repository::StoredSession, + ) -> Result<(), ApiError> { + tx.users() + .find_active_by_id_for_update(session.user_id) + .await? + .ok_or_else(ApiError::unauthorized)?; + if !tx.sessions().management_active(session.id).await? { + return Err(ApiError::forbidden( + "Your management window expired. Confirm with a passkey again.", + )); + } + Ok(()) } - let session = active_session(&app.database, &headers).await?; - app.database - .passkeys() - .rename(id, session.user_id, &input.friendly_name) - .await - .map_err(|_| ApiError)? - .then_some(StatusCode::NO_CONTENT) - .ok_or(ApiError) -} -async fn revoke_passkey( - State(app): State, - headers: HeaderMap, - Path(id): Path, -) -> Result { - let session = active_session(&app.database, &headers).await?; - let authorization = require_purpose_authorization(&app, &headers, &session).await?; - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - let consumed = transaction - .passkeys() - .consume_purpose_authorization( - authorization.jti, - session.user_id, - session.id, - MANAGE_PASSKEYS_PURPOSE, + async fn start_registration( + State(app): State, + headers: HeaderMap, + Json(mut input): Json, + ) -> Result { + if input.username.len() < 3 + || input.username.len() > 32 + || !input + .username + .bytes() + .all(|v| v.is_ascii_lowercase() || v.is_ascii_digit() || v == b'_' || v == b'-') + { + return Err(ApiError::bad_request( + "Use 3–32 lowercase letters, numbers, underscores or hyphens for your username.", + )); + } + if input.display_name.is_empty() { + input.display_name = input.username.clone(); + } + if !Self::valid_name(&input.display_name) { + return Err(ApiError::bad_request( + "Choose a display name of at most 80 characters.", + )); + } + let invitation = input + .invitation + .as_deref() + .and_then(BrowserSecret::parse) + .map(|v| v.digest()); + if app.invite_required { + let digest = invitation + .as_ref() + .ok_or_else(|| ApiError::forbidden("A valid invitation is required."))?; + if !app.database.security().invitation_active(digest).await? { + return Err(ApiError::forbidden( + "This invitation has expired or has already been used.", + )); + } + } + let pending = crate::federation::pending_signup(&app.database, &headers).await?; + let user_id = UserId::new(); + let (challenge, state) = app.registration( + user_id, + &input.username, + &input.display_name, + None, + input.passkey_kind, + &headers, + )?; + app.start( + &headers, + "registration", + None, + None, + Ceremony::Register { + user_id, + username: input.username, + display_name: input.display_name, + invitation, + pending: pending.map(|v| v.id), + state, + }, + challenge, ) .await - .map_err(|_| ApiError)?; - if !consumed { - return Err(ApiError); } - let revoked = transaction - .passkeys() - .revoke_if_not_last(id, session.user_id) - .await - .map_err(|_| ApiError)?; - if !revoked { - return Err(ApiError); + async fn finish_registration( + State(app): State, + headers: HeaderMap, + Json(input): Json, + ) -> Result { + if !Self::valid_name(&input.friendly_name) { + return Err(ApiError::bad_request( + "Choose a passkey name of at most 80 characters.", + )); + } + let Ceremony::Register { + user_id, + username, + display_name, + invitation, + pending, + state, + } = app + .consume(&headers, input.ceremony_id, "registration") + .await? + else { + return Err(Self::failed("wrong ceremony")); + }; + let key = app + .webauthn + .finish_passkey_registration(&input.credential, &state) + .map_err(Self::failed)?; + let mut tx = app.database.begin().await?; + if app.invite_required + && !tx + .security() + .redeem_invitation( + invitation + .as_deref() + .ok_or_else(|| ApiError::forbidden("Invitation required."))?, + ) + .await? + { + return Err(ApiError::forbidden( + "This invitation has expired or has already been used.", + )); + } + tx.users() + .insert(&InsertUser { + id: user_id, + username, + display_name, + }) + .await?; + tx.passkeys() + .insert(&InsertPasskey { + id: TokenId::new(), + credential_id: key.cred_id().as_ref().to_vec(), + user_id, + credential: serde_json::to_value(key).map_err(ApiError::internal)?, + friendly_name: input.friendly_name, + }) + .await?; + if let Some(pending) = pending { + crate::federation::attach_signup(&mut tx, pending, &headers, user_id).await?; + } + let cookie = + security::create_session(&mut tx, user_id, AuthenticationMethod::Passkey).await?; + Self::audit(&mut tx, user_id, "account.create").await?; + tx.commit().await?; + let mut response = Self::signed_in(&cookie)?; + response.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_static(crate::federation::pending_cookie_clear()), + ); + Ok(response) } - transaction - .audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(session.user_id), - action: "passkey.revoke".into(), - outcome: "success".into(), - request_metadata: serde_json::json!({}), - }) - .await - .map_err(|_| ApiError)?; - transaction.commit().await.map_err(|_| ApiError)?; - Ok(StatusCode::NO_CONTENT) -} - -async fn active_session( - database: &Database, - headers: &HeaderMap, -) -> Result { - let secret = session_secret(headers).ok_or(ApiError)?; - database - .sessions() - .find_active_by_browser_secret(&Sha256::digest(secret)) - .await - .map_err(|_| ApiError)? - .ok_or(ApiError) -} - -async fn require_purpose_authorization( - app: &PasskeyApplication, - headers: &HeaderMap, - session: &StoredSession, -) -> Result { - let token = bearer_token(headers).ok_or(ApiError)?; - let claims: PurposeTokenClaims = app - .purpose_keys - .verify(PURPOSE_TOKEN_TYPE, token) - .map_err(|()| ApiError)?; - if !claims.is_valid_for( - &app.issuer, - session.user_id, - session.id, - Utc::now().timestamp(), - ) { - return Err(ApiError); + async fn start_login( + State(app): State, + headers: HeaderMap, + Json(input): Json, + ) -> Result { + if let Some(username) = input.username.filter(|v| !v.is_empty()) { + let user = app + .database + .users() + .find_active_by_username(&username) + .await? + .ok_or_else(|| Self::failed("account unavailable"))?; + let (challenge, state) = app + .webauthn + .start_passkey_authentication(&app.keys(user.id).await?) + .map_err(Self::failed)?; + app.start( + &headers, + "authentication", + Some(user.id), + None, + Ceremony::Login { + user_id: user.id, + state, + }, + challenge, + ) + .await + } else { + let (mut challenge, state) = app + .webauthn + .start_discoverable_authentication() + .map_err(Self::failed)?; + challenge.mediation = None; + app.start( + &headers, + "authentication", + None, + None, + Ceremony::Discover { state }, + challenge, + ) + .await + } + } + async fn finish_login( + State(app): State, + headers: HeaderMap, + Json(input): Json, + ) -> Result { + let (user_id, result) = match app + .consume(&headers, input.ceremony_id, "authentication") + .await? + { + Ceremony::Login { user_id, state } => ( + user_id, + app.webauthn + .finish_passkey_authentication(&input.credential, &state) + .map_err(Self::failed)?, + ), + Ceremony::Discover { state } => { + let (uuid, _) = app + .webauthn + .identify_discoverable_authentication(&input.credential) + .map_err(Self::failed)?; + let user_id = UserId::from_uuid(uuid).map_err(Self::failed)?; + let keys: Vec = app + .keys(user_id) + .await? + .iter() + .map(DiscoverableKey::from) + .collect(); + ( + user_id, + app.webauthn + .finish_discoverable_authentication(&input.credential, state, &keys) + .map_err(Self::failed)?, + ) + } + _ => return Err(Self::failed("wrong ceremony")), + }; + let mut tx = app.database.begin().await?; + Self::update_credential(&mut tx, user_id, &result).await?; + let cookie = + security::create_session(&mut tx, user_id, AuthenticationMethod::Passkey).await?; + Self::audit(&mut tx, user_id, "passkey.login").await?; + tx.commit().await?; + Self::signed_in(&cookie) } - let active = app - .database - .passkeys() - .purpose_authorization_is_active( - claims.jti, - session.user_id, - session.id, - MANAGE_PASSKEYS_PURPOSE, + async fn start_management( + State(app): State, + headers: HeaderMap, + ) -> Result { + let session = security::session(&app.database, &headers).await?; + let (challenge, state) = app + .webauthn + .start_passkey_authentication(&app.keys(session.user_id).await?) + .map_err(Self::failed)?; + app.start( + &headers, + "purpose_authentication", + Some(session.user_id), + Some(session.id), + Ceremony::Manage { + user_id: session.user_id, + session_id: session.id, + state, + }, + challenge, ) .await - .map_err(|_| ApiError)?; - active.then_some(claims).ok_or(ApiError) -} - -fn bearer_token(headers: &HeaderMap) -> Option<&str> { - let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?; - let token = value.strip_prefix("Bearer ")?; - (!token.is_empty() && !token.bytes().any(|byte| byte.is_ascii_whitespace())).then_some(token) -} - -async fn create_session( - transaction: &mut piquel_repository::DatabaseTransaction<'_>, - user_id: UserId, -) -> Result { - let session_id = SessionId::new(); - let now = Utc::now(); - let mut secret = [0_u8; 32]; - OsRng.fill_bytes(&mut secret); - transaction - .sessions() - .insert(&InsertSession { - id: session_id, - user_id, - authentication_methods: vec![AuthenticationMethod::Passkey], - authenticated_at: now, - expires_at: now + Duration::days(30), - user_agent_family: None, - }) - .await - .map_err(|_| ApiError)?; - transaction - .sessions() - .insert_browser_secret(session_id, &Sha256::digest(secret)) - .await - .map_err(|_| ApiError)?; - Ok(format!( - "__Host-piquel_session={}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=2592000", - URL_SAFE_NO_PAD.encode(secret) - )) -} - -fn no_content_with_cookie(cookie: &str) -> Result { - let mut response = StatusCode::NO_CONTENT.into_response(); - response.headers_mut().insert( - header::SET_COOKIE, - HeaderValue::from_str(cookie).map_err(|_| ApiError)?, - ); - Ok(response) -} - -async fn logout( - State(app): State, - headers: HeaderMap, -) -> Result { - let secret = session_secret(&headers).ok_or(ApiError)?; - if let Some(session) = app - .database - .sessions() - .find_active_by_browser_secret(&Sha256::digest(secret)) - .await - .map_err(|_| ApiError)? - { - app.database - .sessions() - .revoke(session.id) - .await - .map_err(|_| ApiError)?; } - no_content_with_cookie( - "__Host-piquel_session=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0", - ) -} - -fn session_secret(headers: &HeaderMap) -> Option> { - headers - .get(header::COOKIE)? - .to_str() - .ok()? - .split(';') - .map(str::trim) - .find_map(|cookie| cookie.strip_prefix("__Host-piquel_session=")) - .and_then(|value| URL_SAFE_NO_PAD.decode(value).ok()) - .filter(|secret| secret.len() == 32) -} - -#[derive(Debug)] -struct ApiError; -impl IntoResponse for ApiError { - fn into_response(self) -> Response { - ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({"error":"authentication_failed"})), + async fn finish_management( + State(app): State, + headers: HeaderMap, + Json(input): Json, + ) -> Result { + let session = security::session(&app.database, &headers).await?; + let Ceremony::Manage { + user_id, + session_id, + state, + } = app + .consume(&headers, input.ceremony_id, "purpose_authentication") + .await? + else { + return Err(Self::failed("wrong ceremony")); + }; + if session.user_id != user_id || session.id != session_id { + return Err(Self::failed("session changed")); + } + let result = app + .webauthn + .finish_passkey_authentication(&input.credential, &state) + .map_err(Self::failed)?; + let mut tx = app.database.begin().await?; + Self::update_credential(&mut tx, user_id, &result).await?; + let expires = tx.sessions().grant_management(session_id).await?; + Self::audit(&mut tx, user_id, "settings.unlock").await?; + tx.commit().await?; + Self::response( + json!({"expires_in":120,"management_expires_at":expires}), + None, ) - .into_response() } -} -impl From for ApiError { - fn from(_: DatabaseError) -> Self { - Self + async fn start_enrollment( + State(app): State, + headers: HeaderMap, + input: Option>, + ) -> Result { + let session = security::management(&app.database, &headers).await?; + let user = app + .database + .users() + .find_by_id(session.user_id) + .await? + .ok_or_else(ApiError::unauthorized)?; + let exclusions = app + .keys(user.id) + .await? + .iter() + .map(|v| v.cred_id().clone()) + .collect(); + let (challenge, state) = app.registration( + user.id, + &user.username, + &user.display_name, + Some(exclusions), + input.map(|Json(v)| v.passkey_kind).unwrap_or_default(), + &headers, + )?; + app.start( + &headers, + "enrollment", + Some(user.id), + Some(session.id), + Ceremony::Enroll { + user_id: user.id, + session_id: session.id, + state, + }, + challenge, + ) + .await } -} - -#[cfg(test)] -mod tests { - use super::*; - use axum::{ - body::Body, - http::{Method, Request}, - }; - use piquel_repository::DatabaseConfig; - use std::{env, time::Duration as StdDuration}; - use tower::ServiceExt; - use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey}; - - fn http_request( - method: Method, - uri: &str, - cookie: Option<&str>, - purpose_token: Option<&str>, - body: Option, - ) -> Request { - let mut builder = Request::builder().method(method).uri(uri); - if let Some(cookie) = cookie { - builder = builder.header(header::COOKIE, cookie); - } - if let Some(token) = purpose_token { - builder = builder.header(header::AUTHORIZATION, format!("Bearer {token}")); + async fn finish_enrollment( + State(app): State, + headers: HeaderMap, + Json(input): Json, + ) -> Result { + if !Self::valid_name(&input.friendly_name) { + return Err(ApiError::bad_request( + "Choose a passkey name of at most 80 characters.", + )); } - let body = if let Some(body) = body { - builder = builder.header(header::CONTENT_TYPE, "application/json"); - Body::from(serde_json::to_vec(&body).expect("request JSON")) - } else { - Body::empty() + let session = security::management(&app.database, &headers).await?; + let Ceremony::Enroll { + user_id, + session_id, + state, + } = app + .consume(&headers, input.ceremony_id, "enrollment") + .await? + else { + return Err(Self::failed("wrong ceremony")); }; - builder.body(body).expect("request") + if user_id != session.user_id || session_id != session.id { + return Err(Self::failed("session changed")); + } + let key = app + .webauthn + .finish_passkey_registration(&input.credential, &state) + .map_err(Self::failed)?; + let mut tx = app.database.begin().await?; + Self::lock_management(&mut tx, &session).await?; + tx.passkeys() + .insert(&InsertPasskey { + id: TokenId::new(), + credential_id: key.cred_id().as_ref().to_vec(), + user_id, + credential: serde_json::to_value(key).map_err(ApiError::internal)?, + friendly_name: input.friendly_name, + }) + .await?; + Self::audit(&mut tx, user_id, "passkey.add").await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) } - - async fn response_json(response: Response) -> serde_json::Value { - let bytes = axum::body::to_bytes(response.into_body(), 1_048_576) - .await - .expect("response body"); - serde_json::from_slice(&bytes).expect("response JSON") + async fn list(State(app): State, headers: HeaderMap) -> Result, ApiError> { + let session = security::session(&app.database, &headers).await?; + Ok(Json(json!( + app.database + .passkeys() + .list_active(session.user_id) + .await? + .into_iter() + .map(|v| json!({"id":v.id,"friendly_name":v.friendly_name})) + .collect::>() + ))) } - - #[test] - fn rp_origin_rejects_attacker_controlled_urls() { - for origin in [ - "https://example.com.evil", - "https://evil.test/example.com", - "https://example.com@evil.test", - ] { - let url = Url::parse(origin).expect("URL fixture"); - assert!( - validate_rp_origin("example.com", &url).is_err(), - "accepted {origin}" - ); + async fn rename( + State(app): State, + headers: HeaderMap, + Path(id): Path, + Json(input): Json, + ) -> Result { + if !Self::valid_name(&input.friendly_name) { + return Err(ApiError::bad_request( + "Choose a passkey name of at most 80 characters.", + )); } - assert!( - validate_rp_origin( - "example.com", - &Url::parse("https://example.com").expect("valid URL") - ) - .is_ok() - ); - } - - #[test] - fn cookie_parser_requires_exact_secret_size() { - let secret = [7_u8; 32]; - let mut headers = HeaderMap::new(); - headers.insert( - header::COOKIE, - HeaderValue::from_str(&format!( - "__Host-piquel_session={}", - URL_SAFE_NO_PAD.encode(secret) - )) - .expect("cookie"), - ); - assert_eq!(session_secret(&headers), Some(secret.to_vec())); + let session = security::management(&app.database, &headers).await?; + let mut tx = app.database.begin().await?; + Self::lock_management(&mut tx, &session).await?; + if !tx + .passkeys() + .rename(id, session.user_id, &input.friendly_name) + .await? + { + return Err(ApiError::bad_request("Passkey not found.")); + } + Self::audit(&mut tx, session.user_id, "passkey.rename").await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) } - - #[test] - fn purpose_tokens_are_exactly_bound_and_short_lived() { - let keys = Es256KeyProvider::generate_for_tests("purpose-test"); - let user_id = UserId::new(); - let session_id = SessionId::new(); - let now = Utc::now().timestamp(); - let claims = PurposeTokenClaims { - iss: "https://auth.example.com".into(), - sub: user_id, - aud: PURPOSE_AUDIENCE.into(), - purpose: MANAGE_PASSKEYS_PURPOSE.into(), - sid: session_id, - auth_time: now, - iat: now, - exp: now + PURPOSE_TOKEN_SECONDS, - jti: TokenId::new(), - }; - let token = keys - .sign(PURPOSE_TOKEN_TYPE, &claims) - .expect("purpose token"); - let verified: PurposeTokenClaims = keys - .verify(PURPOSE_TOKEN_TYPE, &token) - .expect("verify purpose token"); - assert!(verified.is_valid_for("https://auth.example.com", user_id, session_id, now)); - assert!(!verified.is_valid_for("https://attacker.example", user_id, session_id, now)); - assert!(!verified.is_valid_for("https://auth.example.com", UserId::new(), session_id, now)); - assert!(!verified.is_valid_for("https://auth.example.com", user_id, SessionId::new(), now)); - let mut wrong_audience = verified.clone(); - wrong_audience.aud = "another-audience".into(); - assert!(!wrong_audience.is_valid_for("https://auth.example.com", user_id, session_id, now)); - let mut wrong_purpose = verified.clone(); - wrong_purpose.purpose = "delete-account".into(); - assert!(!wrong_purpose.is_valid_for("https://auth.example.com", user_id, session_id, now)); - assert!(!verified.is_valid_for( - "https://auth.example.com", - user_id, - session_id, - now + PURPOSE_TOKEN_SECONDS - )); - - let mut headers = HeaderMap::new(); - headers.insert( - header::AUTHORIZATION, - HeaderValue::from_str(&format!("Bearer {token}")).expect("authorization header"), - ); - assert_eq!(bearer_token(&headers), Some(token.as_str())); + async fn revoke( + State(app): State, + headers: HeaderMap, + Path(id): Path, + ) -> Result { + let session = security::management(&app.database, &headers).await?; + let mut tx = app.database.begin().await?; + Self::lock_management(&mut tx, &session).await?; + if !tx + .passkeys() + .revoke_if_not_last(id, session.user_id) + .await? + { + return Err(ApiError::bad_request( + "Keep at least one passkey on your account.", + )); + } + tx.sessions() + .revoke_other(session.user_id, session.id) + .await?; + Self::audit(&mut tx, session.user_id, "passkey.remove").await?; + tx.commit().await?; + Ok(StatusCode::NO_CONTENT) } - - #[test] - fn standards_conformant_authenticator_registers_and_authenticates() { - let origin = Url::parse("https://auth.example.com").expect("origin"); - let webauthn = WebauthnBuilder::new("example.com", &origin) - .expect("builder") - .rp_name("Piquel Test") - .build() - .expect("webauthn"); - let user_id = UserId::new(); - let (challenge, registration_state) = webauthn - .start_passkey_registration(user_id.as_uuid(), "test_user", "Test User", None) - .expect("registration start"); - // The software authenticator has no physical verification gesture. Enable its - // explicit test-only UV simulation so the ceremony exercises our required-UV - // policy instead of weakening production configuration for this test. - let mut authenticator = WebauthnAuthenticator::new(SoftPasskey::new(true)); - let registration = authenticator - .do_registration(origin.clone(), challenge) - .expect("authenticator registration"); - let passkey = webauthn - .finish_passkey_registration(®istration, ®istration_state) - .expect("registration finish"); - let (challenge, authentication_state) = webauthn - .start_passkey_authentication(&[passkey]) - .expect("authentication start"); - let assertion = authenticator - .do_authentication(origin, challenge) - .expect("authenticator assertion"); - let result = webauthn - .finish_passkey_authentication(&assertion, &authentication_state) - .expect("authentication finish"); - assert!(result.user_verified()); + async fn session_view( + State(app): State, + headers: HeaderMap, + ) -> Result, ApiError> { + let session = security::session(&app.database, &headers).await?; + let user = app + .database + .users() + .find_by_id(session.user_id) + .await? + .ok_or_else(ApiError::unauthorized)?; + let expires = app + .database + .sessions() + .management_expiry(session.id) + .await?; + Ok(Json( + json!({"user":{"id":user.id,"username":user.username,"display_name":user.display_name},"management_expires_at":expires}), + )) } - - #[tokio::test] - #[ignore = "requires TEST_DATABASE_URL"] - #[allow(clippy::too_many_lines)] - async fn purpose_authorization_is_required_and_single_use_over_http() { - let database_url = env::var("TEST_DATABASE_URL") - .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - let database = Database::connect( - DatabaseConfig::new_development(database_url, 5, StdDuration::from_secs(5)) - .expect("database configuration"), - ) - .await - .expect("database"); - database.run_migrations().await.expect("migrations"); - - let origin = Url::parse("https://auth.example.com").expect("origin"); - let application = PasskeyApplication::new( - database, - "example.com", - &origin, - Arc::new(Es256KeyProvider::generate_for_tests("purpose-http")), - ) - .expect("passkey application"); - let app = routes(application); - let mut authenticator = WebauthnAuthenticator::new(SoftPasskey::new(true)); - let suffix = UserId::new().to_string(); - let username = format!("purpose_{}", &suffix[suffix.len() - 12..]); - - let response = app - .clone() - .oneshot(http_request( - Method::POST, - "/webauthn/register/start", - None, - None, - Some(serde_json::json!({ - "username": username, - "display_name": "Purpose Test" - })), - )) - .await - .expect("registration start"); - assert_eq!(response.status(), StatusCode::OK); - let started = response_json(response).await; - let creation: CreationChallengeResponse = - serde_json::from_value(started["public_key"].clone()).expect("creation options"); - let registered = authenticator - .do_registration(origin.clone(), creation) - .expect("registration response"); - let response = app - .clone() - .oneshot(http_request( - Method::POST, - "/webauthn/register/finish", - None, - None, - Some(serde_json::json!({ - "ceremony_id": started["ceremony_id"], - "credential": registered, - "friendly_name": "Primary" - })), - )) - .await - .expect("registration finish"); - assert_eq!(response.status(), StatusCode::NO_CONTENT); - let cookie = response - .headers() - .get(header::SET_COOKIE) - .expect("session cookie") - .to_str() - .expect("cookie text") - .split(';') - .next() - .expect("cookie pair") - .to_owned(); - - let response = app - .clone() - .oneshot(http_request( - Method::POST, - "/account/passkeys/enroll/start", - Some(&cookie), - None, - None, - )) - .await - .expect("unauthorized enrollment"); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - - let response = app - .clone() - .oneshot(http_request( - Method::POST, - "/account/passkeys/authorize/start", - Some(&cookie), - None, - None, - )) - .await - .expect("purpose start"); - assert_eq!(response.status(), StatusCode::OK); - let purpose_started = response_json(response).await; - let request: RequestChallengeResponse = - serde_json::from_value(purpose_started["public_key"].clone()) - .expect("authentication options"); - let assertion = authenticator - .do_authentication(origin.clone(), request) - .expect("purpose assertion"); - let response = app - .clone() - .oneshot(http_request( - Method::POST, - "/account/passkeys/authorize/finish", - Some(&cookie), - None, - Some(serde_json::json!({ - "ceremony_id": purpose_started["ceremony_id"], - "credential": assertion - })), - )) - .await - .expect("purpose finish"); - assert_eq!(response.status(), StatusCode::OK); - assert_eq!( - response.headers().get(header::CACHE_CONTROL), - Some(&HeaderValue::from_static("no-store")) - ); - let authorized = response_json(response).await; - let purpose_token = authorized["purpose_token"] - .as_str() - .expect("purpose token") - .to_owned(); - - let response = app - .clone() - .oneshot(http_request( - Method::POST, - "/account/passkeys/enroll/start", - Some(&cookie), - Some(&purpose_token), - None, - )) - .await - .expect("enrollment start"); - assert_eq!(response.status(), StatusCode::OK); - let enrollment = response_json(response).await; - let creation: CreationChallengeResponse = - serde_json::from_value(enrollment["public_key"].clone()).expect("creation options"); - let registered = authenticator - .do_registration(origin, creation) - .expect("backup registration response"); - let response = app - .clone() - .oneshot(http_request( - Method::POST, - "/account/passkeys/enroll/finish", - Some(&cookie), - Some(&purpose_token), - Some(serde_json::json!({ - "ceremony_id": enrollment["ceremony_id"], - "credential": registered, - "friendly_name": "Backup" - })), - )) - .await - .expect("enrollment finish"); - assert_eq!(response.status(), StatusCode::NO_CONTENT); - - let response = app - .oneshot(http_request( - Method::POST, - "/account/passkeys/enroll/start", - Some(&cookie), - Some(&purpose_token), - None, - )) - .await - .expect("replayed purpose token"); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); + async fn logout(State(app): State, headers: HeaderMap) -> Result { + if let Some(session) = security::optional_session(&app.database, &headers).await? { + app.database.sessions().revoke(session.id).await?; + } + Self::signed_in("__Host-piquel_session=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0") } } + +#[cfg(test)] +#[path = "passkey_tests.rs"] +mod tests; diff --git a/apps/auth-service/src/passkey_tests.rs b/apps/auth-service/src/passkey_tests.rs new file mode 100644 index 000000000..cb2aafdca --- /dev/null +++ b/apps/auth-service/src/passkey_tests.rs @@ -0,0 +1,301 @@ +use super::*; +use axum::{ + body::{Body, to_bytes}, + http::{Method, Request}, +}; +use piquel_repository::DatabaseConfig; +use tower::ServiceExt; +use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey}; + +struct Fixture { + app: PasskeyApplication, + authenticator: WebauthnAuthenticator, + origin: Url, + user_id: UserId, + key_id: TokenId, + username: String, +} +impl Fixture { + async fn new() -> Self { + let url = std::env::var("TEST_DATABASE_URL").expect("isolated test database"); + let database = Database::connect( + DatabaseConfig::new_development(&url, 5, std::time::Duration::from_secs(5)) + .expect("configuration"), + ) + .await + .expect("database"); + database.run_migrations().await.expect("migrations"); + let origin = Url::parse("https://auth.piquel.fr/").expect("origin"); + let app = PasskeyApplication::new(database, "auth.piquel.fr", &origin, false) + .expect("passkey app"); + let user_id = UserId::new(); + let username = format!("key_{}", &TokenId::new().to_string()[24..]); + let key_id = TokenId::new(); + // This software authenticator supports UV and signed counters, but not + // resident credentials. Browser tests cover production resident signup; + // use the library's normal registration to seed this assertion fixture. + let (challenge, state) = app + .webauthn + .start_passkey_registration(user_id.as_uuid(), &username, "Test user", None) + .expect("registration"); + let mut authenticator = WebauthnAuthenticator::new(SoftPasskey::new(true)); + let registration = authenticator + .do_registration(origin.clone(), challenge) + .expect("software registration"); + let key = app + .webauthn + .finish_passkey_registration(®istration, &state) + .expect("verified registration"); + let mut tx = app.database.begin().await.expect("transaction"); + tx.users() + .insert(&InsertUser { + id: user_id, + username: username.clone(), + display_name: "Test user".into(), + }) + .await + .expect("user"); + tx.passkeys() + .insert(&InsertPasskey { + id: key_id, + credential_id: key.cred_id().as_ref().to_vec(), + user_id, + credential: serde_json::to_value(key).expect("credential"), + friendly_name: "Original key".into(), + }) + .await + .expect("stored key"); + tx.commit().await.expect("commit"); + Self { + app, + authenticator, + origin, + user_id, + key_id, + username, + } + } + async fn request(&self, path: &str, method: Method, cookies: &str, body: Value) -> Response { + self.app + .clone() + .routes() + .oneshot( + Request::builder() + .method(method) + .uri(path) + .header(header::CONTENT_TYPE, "application/json") + .header(header::COOKIE, cookies) + .body(Body::from(body.to_string())) + .expect("request"), + ) + .await + .expect("response") + } + async fn start(&self, path: &str, cookies: &str, body: Value) -> (Value, String) { + let response = self.request(path, Method::POST, cookies, body).await; + assert_eq!(response.status(), StatusCode::OK); + let cookie = Self::cookie(&response); + let value = + serde_json::from_slice(&to_bytes(response.into_body(), 65536).await.expect("body")) + .expect("JSON"); + (value, cookie) + } + fn cookie(response: &Response) -> String { + response.headers()[header::SET_COOKIE] + .to_str() + .expect("cookie") + .split(';') + .next() + .expect("cookie pair") + .to_owned() + } + fn assertion(&mut self, started: &Value) -> PublicKeyCredential { + let challenge = serde_json::from_value(started["public_key"].clone()) + .expect("authentication challenge"); + self.authenticator + .do_authentication(self.origin.clone(), challenge) + .expect("software assertion") + } + async fn login(&mut self) -> String { + let (started, browser) = self + .start( + "/webauthn/authenticate/start", + "", + json!({"username":self.username}), + ) + .await; + let assertion = self.assertion(&started); + let response = self + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + Self::cookie(&response) + } +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn overlapping_assertions_reject_old_counter_after_new_counter_commits() { + let mut fixture = Fixture::new().await; + let (older, browser) = fixture + .start( + "/webauthn/authenticate/start", + "", + json!({"username":fixture.username}), + ) + .await; + let (newer, _) = fixture + .start( + "/webauthn/authenticate/start", + &browser, + json!({"username":fixture.username}), + ) + .await; + let older_assertion = fixture.assertion(&older); + let newer_assertion = fixture.assertion(&newer); + let newer_body = json!({"ceremony_id":newer["ceremony_id"],"credential":newer_assertion}); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + newer_body.clone(), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id":older["ceremony_id"],"credential":older_assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(response.headers().get(header::SET_COOKIE).is_none()); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + newer_body, + ) + .await; + assert_eq!( + response.status(), + StatusCode::BAD_REQUEST, + "ceremony cannot replay" + ); + let keys = fixture + .app + .database + .passkeys() + .list_active(fixture.user_id) + .await + .expect("keys"); + assert_eq!(keys[0].credential.pointer("/cred/counter"), Some(&json!(2))); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn ceremonies_require_browser_binding_and_management_requires_the_same_session() { + let mut fixture = Fixture::new().await; + let (started, _) = fixture + .start( + "/webauthn/authenticate/start", + "", + json!({"username":fixture.username}), + ) + .await; + let assertion = fixture.assertion(&started); + let body = json!({"ceremony_id":started["ceremony_id"],"credential":assertion}); + for cookies in [ + String::new(), + format!("__Host-piquel_ceremony={}", BrowserSecret::new().encoded()), + ] { + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &cookies, + body.clone(), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(response.headers().get(header::SET_COOKIE).is_none()); + } + let first = fixture.login().await; + let second = fixture.login().await; + let (started, browser) = fixture + .start("/account/passkeys/authorize/start", &first, json!({})) + .await; + let assertion = fixture.assertion(&started); + let response = fixture + .request( + "/account/passkeys/authorize/finish", + Method::POST, + &format!("{second}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!( + response.status(), + StatusCode::BAD_REQUEST, + "management proof is bound to the initiating session" + ); + let path = format!("/account/passkeys/{}", fixture.key_id); + let response = fixture + .request( + &path, + Method::PATCH, + &second, + json!({"friendly_name":"Unauthorized"}), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let (started, browser) = fixture + .start("/account/passkeys/authorize/start", &first, json!({})) + .await; + let assertion = fixture.assertion(&started); + let response = fixture + .request( + "/account/passkeys/authorize/finish", + Method::POST, + &format!("{first}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + for name in ["Renamed once", "Renamed twice"] { + let response = fixture + .request(&path, Method::PATCH, &first, json!({"friendly_name":name})) + .await; + assert_eq!( + response.status(), + StatusCode::NO_CONTENT, + "management grant is reusable" + ); + } + let response = fixture + .request(&path, Method::DELETE, &first, json!({})) + .await; + assert_eq!( + response.status(), + StatusCode::BAD_REQUEST, + "last passkey cannot be removed" + ); + let keys = fixture + .app + .database + .passkeys() + .list_active(fixture.user_id) + .await + .expect("keys"); + assert_eq!(keys.len(), 1); + assert_eq!(keys[0].friendly_name, "Renamed twice"); +} diff --git a/apps/auth-service/src/security.rs b/apps/auth-service/src/security.rs new file mode 100644 index 000000000..c1fb7a407 --- /dev/null +++ b/apps/auth-service/src/security.rs @@ -0,0 +1,321 @@ +//! Shared browser-session, management authorization, and HTTP trust boundaries. + +use axum::{ + Json, + extract::{ConnectInfo, Request, State}, + http::{HeaderMap, HeaderValue, Method, StatusCode, header}, + middleware::Next, + response::{IntoResponse, Response}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{Duration, Utc}; +use piquel_auth_protocol::{AuthenticationMethod, SessionId, UserId}; +use piquel_repository::{ + Database, DatabaseError, DatabaseTransaction, InsertSession, StoredSession, +}; +use rand::{RngCore, rngs::OsRng}; +use sha2::{Digest, Sha256}; +use std::{net::SocketAddr, sync::Arc}; + +#[derive(Debug)] +pub(crate) struct ApiError { + status: StatusCode, + message: &'static str, +} +impl ApiError { + pub(crate) fn bad_request(message: &'static str) -> Self { + Self { + status: StatusCode::BAD_REQUEST, + message, + } + } + pub(crate) fn unauthorized() -> Self { + Self { + status: StatusCode::UNAUTHORIZED, + message: "Sign in to continue.", + } + } + pub(crate) fn forbidden(message: &'static str) -> Self { + Self { + status: StatusCode::FORBIDDEN, + message, + } + } + pub(crate) fn internal(error: impl Into) -> Self { + tracing::error!(error = ?error.into(), "authentication operation failed"); + Self { + status: StatusCode::INTERNAL_SERVER_ERROR, + message: "The request could not be completed. Please try again.", + } + } +} +impl From for ApiError { + fn from(error: DatabaseError) -> Self { + match error { + DatabaseError::NotFound => { + Self::bad_request("This request has expired or is no longer available.") + } + DatabaseError::Conflict => Self { + status: StatusCode::CONFLICT, + message: "This information is already in use.", + }, + error => Self::internal(error), + } + } +} +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + (self.status, Json(serde_json::json!({"error":self.message}))).into_response() + } +} + +/// Random browser secrets are encoded once, and only their digests reach the database. +pub(crate) struct BrowserSecret(Vec); +impl BrowserSecret { + pub(crate) fn new() -> Self { + let mut value = vec![0; 32]; + OsRng.fill_bytes(&mut value); + Self(value) + } + pub(crate) fn parse(value: &str) -> Option { + URL_SAFE_NO_PAD + .decode(value) + .ok() + .filter(|v| v.len() == 32) + .map(Self) + } + pub(crate) fn from_cookie(headers: &HeaderMap, name: &str) -> Option { + headers + .get(header::COOKIE)? + .to_str() + .ok()? + .split(';') + .map(str::trim) + .find_map(|v| { + v.split_once('=') + .filter(|(key, _)| *key == name) + .and_then(|(_, v)| Self::parse(v)) + }) + } + pub(crate) fn encoded(&self) -> String { + URL_SAFE_NO_PAD.encode(&self.0) + } + pub(crate) fn digest(&self) -> Vec { + Sha256::digest(&self.0).to_vec() + } + pub(crate) fn cookie(&self, name: &str, max_age: i64) -> String { + format!( + "{name}={}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={max_age}", + self.encoded() + ) + } +} + +pub(crate) async fn optional_session( + database: &Database, + headers: &HeaderMap, +) -> Result, ApiError> { + let Some(secret) = BrowserSecret::from_cookie(headers, "__Host-piquel_session") else { + return Ok(None); + }; + Ok(database + .sessions() + .find_active_by_browser_secret(&secret.digest()) + .await?) +} +pub(crate) async fn session( + database: &Database, + headers: &HeaderMap, +) -> Result { + optional_session(database, headers) + .await? + .ok_or_else(ApiError::unauthorized) +} +pub(crate) async fn management( + database: &Database, + headers: &HeaderMap, +) -> Result { + let session = session(database, headers).await?; + if !database.sessions().management_active(session.id).await? { + return Err(ApiError::forbidden( + "Confirm with a passkey to unlock settings for two minutes.", + )); + } + Ok(session) +} +pub(crate) async fn create_session( + tx: &mut DatabaseTransaction<'_>, + user_id: UserId, + method: AuthenticationMethod, +) -> Result { + let now = Utc::now(); + let id = SessionId::new(); + tx.sessions() + .insert(&InsertSession { + id, + user_id, + authentication_methods: vec![method], + authenticated_at: now, + expires_at: now + Duration::days(30), + user_agent_family: None, + }) + .await?; + let secret = BrowserSecret::new(); + tx.sessions() + .insert_browser_secret(id, &secret.digest()) + .await?; + Ok(secret.cookie("__Host-piquel_session", 30 * 24 * 60 * 60)) +} + +#[derive(Clone)] +pub(crate) struct HttpSecurity { + pub database: Database, + pub auth_origin: String, + pub settings_origin: String, + pub client_origins: Arc>, +} +impl HttpSecurity { + fn allowed_origin(&self, path: &str, origin: &str) -> bool { + origin == self.auth_origin + || (origin == self.settings_origin + && (path.starts_with("/account/") + || path.starts_with("/session") + || path == "/config" + || path.starts_with("/federation/") + || path.starts_with("/login/"))) + || (matches!( + path, + "/oauth/token" + | "/oauth/userinfo" + | "/oauth/revoke" + | "/oidc/token" + | "/oidc/userinfo" + | "/oidc/revoke" + | "/.well-known/openid-configuration" + | "/.well-known/jwks.json" + ) && self.client_origins.iter().any(|v| v == origin)) + } + + pub(crate) async fn protect( + State(policy): State, + request: Request, + next: Next, + ) -> Response { + let origin = request + .headers() + .get(header::ORIGIN) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + let path = request.uri().path(); + let allowed = origin + .as_deref() + .is_some_and(|v| policy.allowed_origin(path, v)); + let mut response = if request.method() == Method::OPTIONS { + if allowed { + StatusCode::NO_CONTENT.into_response() + } else { + ApiError::forbidden("Origin is not allowed.").into_response() + } + } else { + // OAuth back-channel endpoints authenticate the client/token and do not use browser cookies. + let logout = path == "/oidc/logout"; + let protocol = logout + || matches!( + path, + "/oauth/token" | "/oauth/revoke" | "/oidc/token" | "/oidc/revoke" + ); + let mutation = !matches!(*request.method(), Method::GET | Method::HEAD); + if (origin.is_some() && !allowed && !logout) + || (mutation + && !protocol + && (!allowed || request.headers().get("x-piquel-csrf").is_none())) + { + ApiError::forbidden("This request must originate from an approved Piquel page.") + .into_response() + } else { + let limited = mutation + || path.starts_with("/federation/") + || path.starts_with("/login/") + || path == "/oauth/authorize"; + let rate = if limited { + let ip = request + .extensions() + .get::>() + .map_or_else(|| "local-test".into(), |v| v.0.ip().to_string()); + policy + .database + .security() + .allow_request(&Sha256::digest(ip.as_bytes()), 120) + .await + } else { + Ok(true) + }; + match rate { + Ok(true) => match tokio::time::timeout( + std::time::Duration::from_secs(30), + next.run(request), + ) + .await + { + Ok(response) => response, + Err(_) => ( + StatusCode::GATEWAY_TIMEOUT, + Json(serde_json::json!({"error":"Request timed out."})), + ) + .into_response(), + }, + Ok(false) => ( + StatusCode::TOO_MANY_REQUESTS, + [(header::RETRY_AFTER, "60")], + Json( + serde_json::json!({"error":"Too many requests. Please wait a minute."}), + ), + ) + .into_response(), + Err(error) => ApiError::from(error).into_response(), + } + } + }; + Self::decorate(&mut response, origin, allowed); + response + } + fn decorate(response: &mut Response, origin: Option, allowed: bool) { + let headers = response.headers_mut(); + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + headers.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + headers.insert( + header::REFERRER_POLICY, + HeaderValue::from_static("no-referrer"), + ); + headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); + headers.insert( + header::STRICT_TRANSPORT_SECURITY, + HeaderValue::from_static("max-age=31536000"), + ); + if allowed { + if let Some(origin) = origin.and_then(|v| HeaderValue::from_str(&v).ok()) { + headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin); + } + headers.insert( + header::ACCESS_CONTROL_ALLOW_CREDENTIALS, + HeaderValue::from_static("true"), + ); + headers.insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("content-type, x-piquel-csrf, authorization"), + ); + headers.insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, POST, PATCH, DELETE, OPTIONS"), + ); + headers.insert(header::VARY, HeaderValue::from_static("Origin")); + } + } +} + +#[cfg(test)] +#[path = "security_tests.rs"] +mod tests; diff --git a/apps/auth-service/src/security_tests.rs b/apps/auth-service/src/security_tests.rs new file mode 100644 index 000000000..e44fdb354 --- /dev/null +++ b/apps/auth-service/src/security_tests.rs @@ -0,0 +1,275 @@ +use super::*; +use axum::{Router, body::Body, http::Request as HttpRequest, middleware, routing::any}; +use piquel_repository::DatabaseConfig; +use std::net::{IpAddr, Ipv6Addr}; +use tower::ServiceExt; + +struct SecurityFixture { + router: Router, + peer: SocketAddr, +} +impl SecurityFixture { + async fn database(max_connections: u32, timeout: std::time::Duration) -> Database { + let url = std::env::var("TEST_DATABASE_URL") + .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); + Database::connect( + DatabaseConfig::new_development(&url, max_connections, timeout) + .expect("database configuration"), + ) + .await + .expect("database") + } + async fn new() -> Self { + let database = Self::database(5, std::time::Duration::from_secs(5)).await; + database.run_migrations().await.expect("migrations"); + let policy = HttpSecurity { + database, + auth_origin: "https://auth.piquel.fr".into(), + settings_origin: "https://piquel.fr".into(), + client_origins: Arc::new(vec!["https://external.example".into()]), + }; + let mut router = Router::new(); + for path in [ + "/account/passkeys", + "/webauthn/authenticate/start", + "/.well-known/openid-configuration", + "/.well-known/jwks.json", + "/oauth/token", + "/oauth/userinfo", + "/oidc/token", + "/oidc/userinfo", + "/oidc/logout", + ] { + router = router.route(path, any(|| async { StatusCode::ACCEPTED })); + } + let peer = SocketAddr::new( + IpAddr::V6(Ipv6Addr::from(UserId::new().as_uuid().as_u128())), + 4321, + ); + Self { + router: router.layer(middleware::from_fn_with_state( + policy, + HttpSecurity::protect, + )), + peer, + } + } + async fn request( + &self, + method: Method, + path: &str, + origin: Option<&str>, + csrf: bool, + ) -> Response { + let mut request = HttpRequest::builder().method(method.clone()).uri(path); + if let Some(origin) = origin { + request = request.header(header::ORIGIN, origin); + } + if csrf { + request = request.header("x-piquel-csrf", "1"); + } + if method == Method::OPTIONS { + request = request + .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST") + .header( + header::ACCESS_CONTROL_REQUEST_HEADERS, + "content-type, x-piquel-csrf", + ); + } + let mut request = request.body(Body::empty()).expect("request"); + request.extensions_mut().insert(ConnectInfo(self.peer)); + self.router + .clone() + .oneshot(request) + .await + .expect("response") + } + fn exact_cors(response: &Response, origin: &str) { + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], + origin + ); + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_CREDENTIALS], + "true" + ); + assert_eq!(response.headers()[header::VARY], "Origin"); + assert_ne!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + } + fn denied(response: &Response) { + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .is_none() + ); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); + assert_eq!( + response.headers()[header::X_CONTENT_TYPE_OPTIONS], + "nosniff" + ); + } +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +#[expect( + clippy::too_many_lines, + reason = "Keep this complete browser-origin trust-boundary scenario together." +)] +async fn router_enforces_exact_browser_origins_csrf_and_public_client_cors_boundaries() { + let fixture = SecurityFixture::new().await; + for origin in ["https://auth.piquel.fr", "https://piquel.fr"] { + let response = fixture + .request(Method::POST, "/account/passkeys", Some(origin), true) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + SecurityFixture::exact_cors(&response, origin); + let response = fixture + .request(Method::POST, "/account/passkeys", Some(origin), false) + .await; + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "approved origin still needs CSRF header" + ); + } + for origin in [ + None, + Some("null"), + Some("https://evil.example"), + Some("https://piquel.fr.evil.example"), + Some("https://auth.piquel.fr:444"), + Some("http://auth.piquel.fr"), + ] { + let response = fixture + .request(Method::POST, "/account/passkeys", origin, true) + .await; + SecurityFixture::denied(&response); + } + let response = fixture + .request( + Method::POST, + "/webauthn/authenticate/start", + Some("https://piquel.fr"), + true, + ) + .await; + SecurityFixture::denied(&response); + let response = fixture + .request( + Method::POST, + "/webauthn/authenticate/start", + Some("https://auth.piquel.fr"), + true, + ) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + + // OIDC endpoints authenticate their own tokens/client credentials. Browser + // clients can read public metadata and call protocol APIs, never settings. + for (method, path) in [ + (Method::GET, "/.well-known/openid-configuration"), + (Method::GET, "/.well-known/jwks.json"), + (Method::POST, "/oauth/token"), + (Method::POST, "/oidc/token"), + (Method::GET, "/oauth/userinfo"), + (Method::GET, "/oidc/userinfo"), + ] { + let response = fixture + .request(method, path, Some("https://external.example"), false) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED, "{path}"); + SecurityFixture::exact_cors(&response, "https://external.example"); + } + for method in [Method::GET, Method::POST, Method::OPTIONS] { + let response = fixture + .request( + method, + "/account/passkeys", + Some("https://external.example"), + true, + ) + .await; + SecurityFixture::denied(&response); + } + for origin in ["https://auth.piquel.fr", "https://piquel.fr"] { + let response = fixture + .request(Method::OPTIONS, "/account/passkeys", Some(origin), false) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + SecurityFixture::exact_cors(&response, origin); + assert!( + response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS] + .to_str() + .expect("allowed headers") + .contains("x-piquel-csrf") + ); + } + let response = fixture + .request( + Method::OPTIONS, + "/oidc/token", + Some("https://external.example"), + false, + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + SecurityFixture::exact_cors(&response, "https://external.example"); + for origin in [None, Some("null"), Some("https://evil.example")] { + let response = fixture + .request(Method::OPTIONS, "/account/passkeys", origin, false) + .await; + SecurityFixture::denied(&response); + } + // External RP-initiated logout reaches its own validating handler. This + // dummy handler only proves delegation and cannot log out a real session. + let response = fixture + .request( + Method::GET, + "/oidc/logout", + Some("https://external.example"), + false, + ) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + assert!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .is_none() + ); +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn optional_session_preserves_database_failure_instead_of_reporting_signed_out() { + let database = SecurityFixture::database(1, std::time::Duration::from_millis(50)).await; + // Exhaust only this test's private pool; the database and all other tests + // remain usable. A well-formed session cookie must trigger a real lookup. + let transaction = database.begin().await.expect("hold sole connection"); + assert!( + optional_session(&database, &HeaderMap::new()) + .await + .expect("no cookie requires no lookup") + .is_none() + ); + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(&format!( + "__Host-piquel_session={}", + BrowserSecret::new().encoded() + )) + .expect("cookie"), + ); + let error = optional_session(&database, &headers) + .await + .expect_err("database timeout must propagate"); + assert_eq!( + error.into_response().status(), + StatusCode::INTERNAL_SERVER_ERROR + ); + transaction.rollback().await.expect("release connection"); +} diff --git a/apps/auth-service/src/session.rs b/apps/auth-service/src/session.rs deleted file mode 100644 index 24e59ae1c..000000000 --- a/apps/auth-service/src/session.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Central-session policy values. - -use chrono::{Duration as ChronoDuration, Utc}; -use piquel_auth_protocol::{AuthenticationMethod, SessionId, UserId}; -use piquel_repository::{Database, DatabaseError, InsertSession, StoredSession}; -use std::time::Duration; -use thiserror::Error; - -/// Session creation input with minimized client metadata. -#[derive(Clone, Debug)] -pub(super) struct NewSession { - pub id: SessionId, - pub user_id: UserId, - pub methods: Vec, - pub ttl: Duration, - pub user_agent_family: Option, -} - -#[derive(Debug, Error)] -pub(super) enum SessionError { - #[error("invalid session")] - InvalidSession, - #[error("session operation failed")] - Database(#[from] DatabaseError), -} - -/// Requires bounded expiry and at least one actual authentication method. -pub(super) fn validate_new_session(session: &NewSession) -> Result<(), ()> { - if session.methods.is_empty() - || session.ttl.is_zero() - || session.ttl > Duration::from_hours(720) - { - return Err(()); - } - if session - .user_agent_family - .as_deref() - .is_some_and(|value| value.len() > 100) - { - return Err(()); - } - Ok(()) -} - -/// Creates a bounded central session for an active account. -pub(super) async fn create( - database: &Database, - session: NewSession, -) -> Result { - validate_new_session(&session).map_err(|()| SessionError::InvalidSession)?; - let authenticated_at = Utc::now(); - let ttl = ChronoDuration::from_std(session.ttl).map_err(|_| SessionError::InvalidSession)?; - let expires_at = authenticated_at - .checked_add_signed(ttl) - .ok_or(SessionError::InvalidSession)?; - database - .sessions() - .insert(&InsertSession { - id: session.id, - user_id: session.user_id, - authentication_methods: session.methods, - authenticated_at, - expires_at, - user_agent_family: session.user_agent_family, - }) - .await - .map_err(Into::into) -} - -/// Resolves a session only while both it and its account remain active. -pub(super) async fn find_active( - database: &Database, - id: SessionId, -) -> Result, SessionError> { - database - .sessions() - .find_active_by_id(id) - .await - .map_err(Into::into) -} - -/// Advances activity tracking only for a currently usable session. -pub(super) async fn touch(database: &Database, id: SessionId) -> Result { - database.sessions().touch(id).await.map_err(Into::into) -} - -/// Idempotently revokes a central session. -pub(super) async fn revoke(database: &Database, id: SessionId) -> Result { - database.sessions().revoke(id).await.map_err(Into::into) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn valid_session() -> NewSession { - NewSession { - id: SessionId::new(), - user_id: UserId::new(), - methods: vec![AuthenticationMethod::Passkey], - ttl: Duration::from_hours(1), - user_agent_family: Some("Firefox".into()), - } - } - - #[test] - fn session_creation_policy_is_bounded() { - assert!(validate_new_session(&valid_session()).is_ok()); - - let mut no_method = valid_session(); - no_method.methods.clear(); - assert!(validate_new_session(&no_method).is_err()); - - let mut excessive_ttl = valid_session(); - excessive_ttl.ttl = Duration::from_hours(721); - assert!(validate_new_session(&excessive_ttl).is_err()); - - let mut excessive_metadata = valid_session(); - excessive_metadata.user_agent_family = Some("x".repeat(101)); - assert!(validate_new_session(&excessive_metadata).is_err()); - } -} diff --git a/apps/auth-service/src/signing.rs b/apps/auth-service/src/signing.rs deleted file mode 100644 index fda48d206..000000000 --- a/apps/auth-service/src/signing.rs +++ /dev/null @@ -1,149 +0,0 @@ -//! Exact ES256 compact-JWS signing used by authentication token categories. - -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use p256::{ - ecdsa::{ - Signature, SigningKey, - signature::{Signer, Verifier}, - }, - pkcs8::DecodePrivateKey, -}; -#[cfg(test)] -use rand::rngs::OsRng; -use serde::{Serialize, de::DeserializeOwned}; -use serde_json::json; - -/// Local PEM-backed ES256 signing provider. -pub struct Es256KeyProvider { - kid: String, - signing: SigningKey, -} - -impl Es256KeyProvider { - /// Loads a P-256 PKCS#8 PEM signing key. - /// - /// # Errors - /// - /// Returns an error when the PEM is not a P-256 PKCS#8 private key. - #[allow(clippy::result_unit_err)] - pub fn from_pkcs8_pem(kid: impl Into, pem: &str) -> Result { - let kid = kid.into(); - if kid.is_empty() || kid.len() > 128 || kid.chars().any(char::is_whitespace) { - return Err(()); - } - Ok(Self { - kid, - signing: SigningKey::from_pkcs8_pem(pem).map_err(|_| ())?, - }) - } - - /// Generates an ephemeral key for tests only. - #[cfg(test)] - #[must_use] - pub(crate) fn generate_for_tests(kid: impl Into) -> Self { - Self { - kid: kid.into(), - signing: SigningKey::random(&mut OsRng), - } - } - - pub(crate) fn sign(&self, token_type: &str, claims: &T) -> Result { - let header = URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&json!({ - "alg": "ES256", - "kid": self.kid, - "typ": token_type, - })) - .map_err(|_| ())?, - ); - let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).map_err(|_| ())?); - let signing_input = format!("{header}.{payload}"); - let signature: Signature = self.signing.sign(signing_input.as_bytes()); - Ok(format!( - "{signing_input}.{}", - URL_SAFE_NO_PAD.encode(signature.to_bytes()) - )) - } - - pub(crate) fn verify( - &self, - token_type: &str, - token: &str, - ) -> Result { - if token.len() > 8192 { - return Err(()); - } - let mut pieces = token.split('.'); - let header_part = pieces.next().ok_or(())?; - let claims_part = pieces.next().ok_or(())?; - let signature_part = pieces.next().ok_or(())?; - if pieces.next().is_some() { - return Err(()); - } - let header: serde_json::Value = - serde_json::from_slice(&URL_SAFE_NO_PAD.decode(header_part).map_err(|_| ())?) - .map_err(|_| ())?; - if header.get("alg") != Some(&json!("ES256")) - || header.get("kid") != Some(&json!(self.kid)) - || header.get("typ") != Some(&json!(token_type)) - { - return Err(()); - } - let signature = URL_SAFE_NO_PAD.decode(signature_part).map_err(|_| ())?; - let signature = Signature::from_slice(&signature).map_err(|_| ())?; - self.signing - .verifying_key() - .verify( - format!("{header_part}.{claims_part}").as_bytes(), - &signature, - ) - .map_err(|_| ())?; - serde_json::from_slice(&URL_SAFE_NO_PAD.decode(claims_part).map_err(|_| ())?) - .map_err(|_| ()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use p256::pkcs8::{EncodePrivateKey, LineEnding}; - - #[test] - fn token_type_and_signature_are_enforced() { - let keys = Es256KeyProvider::generate_for_tests("test-key"); - let token = keys - .sign("purpose+jwt", &json!({"subject":"user"})) - .expect("sign token"); - assert_eq!( - keys.verify::("purpose+jwt", &token), - Ok(json!({"subject":"user"})) - ); - assert!(keys.verify::("at+jwt", &token).is_err()); - - let mut tampered = token.into_bytes(); - let last = tampered.last_mut().expect("signature byte"); - *last = if *last == b'A' { b'B' } else { b'A' }; - assert!( - keys.verify::( - "purpose+jwt", - std::str::from_utf8(&tampered).expect("ASCII token") - ) - .is_err() - ); - } - - #[test] - fn pkcs8_pem_loading_uses_the_signing_path() { - let signing = SigningKey::random(&mut OsRng); - let pem = signing.to_pkcs8_pem(LineEnding::LF).expect("PKCS#8 PEM"); - let keys = Es256KeyProvider::from_pkcs8_pem("configured-key", pem.as_str()) - .expect("configured signing key"); - let token = keys - .sign("purpose+jwt", &json!({"configured":true})) - .expect("sign with configured key"); - assert_eq!( - keys.verify::("purpose+jwt", &token), - Ok(json!({"configured":true})) - ); - } -} diff --git a/apps/auth-web/.gitignore b/apps/auth-web/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/apps/auth-web/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/apps/auth-web/README.md b/apps/auth-web/README.md new file mode 100644 index 000000000..27905d2fe --- /dev/null +++ b/apps/auth-web/README.md @@ -0,0 +1,18 @@ +Static SvelteKit pages for the authentication origin. `pnpm --filter @piquel/auth-web build` +produces `build/`, which the Rust auth-service build embeds into its executable. +Node is needed only to build these assets. + +Passkey ceremonies, login, social linking and authorization confirmation run here. +All configuration comes from the public `/config` endpoint; no provider secrets or +session tokens are placed in the frontend bundle. The auth session uses an HttpOnly +cookie. A signup invitation can be retained in tab sessionStorage across the social +redirect and is removed after successful registration. + +On Android, registration and enrollment offer an explicit Google Password Manager +option. Ordinary passkey/security-key registration remains the default. The browser +cannot determine whether Google Password Manager is installed, so this choice is +never made automatically. + +SvelteKit emits per-page CSP hashes in HTML. The Rust service adds frame-ancestor +protection in its response header without imposing a conflicting script policy. +Account settings are built separately in `apps/piquel-web`. diff --git a/apps/auth-web/package.json b/apps/auth-web/package.json new file mode 100644 index 000000000..b66bd8db2 --- /dev/null +++ b/apps/auth-web/package.json @@ -0,0 +1,23 @@ +{ + "name": "@piquel/auth-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json" + }, + "dependencies": { + "@piquel/browser": "workspace:*" + }, + "devDependencies": { + "@sveltejs/adapter-static": "catalog:", + "@sveltejs/kit": "catalog:", + "@sveltejs/vite-plugin-svelte": "catalog:", + "svelte": "catalog:", + "svelte-check": "catalog:", + "typescript": "catalog:", + "vite": "catalog:" + } +} diff --git a/apps/auth-web/src/app.html b/apps/auth-web/src/app.html new file mode 100644 index 000000000..5adf2916b --- /dev/null +++ b/apps/auth-web/src/app.html @@ -0,0 +1,2 @@ + +%sveltekit.head%
%sveltekit.body%
diff --git a/apps/auth-web/src/lib/AuthPage.svelte b/apps/auth-web/src/lib/AuthPage.svelte new file mode 100644 index 000000000..3f7ede1f7 --- /dev/null +++ b/apps/auth-web/src/lib/AuthPage.svelte @@ -0,0 +1,150 @@ + + +{linking ? 'Link social sign-in' : registration ? 'Create your account' : management ? 'Verify your passkey' : 'Sign in'} · Piquel +
+

{management ? 'Account security' : linking ? 'Social sign-in' : registration ? 'One account. Your services.' : 'Your Piquel account'}

+

{title}

+ {#if linking} +

{providerName(pending!.provider)} uses an email associated with an existing account. Verify that account with its passkey to add this provider.

+ {#if pending?.email}

{pending.email}

{/if} + {#if session}

Signed in as @{session.user.username}.

{/if} + {:else if registration} +

Create a passkey with your device or password manager. You’ll use it to sign in and protect your account settings.

+ {#if pending}

Finish creating your account to add {providerName(pending.provider)} sign-in.

{/if} + {:else if mode === 'manage'} +

Use a passkey to unlock changes to your security settings for two minutes.

+ {:else if mode === 'enroll'} +

Verify an existing passkey, then save another with your device or password manager.

+ {:else}

Sign in with a passkey, or use a linked social account.

{/if} + {#if error}{/if} + {#if !ready && !error}

Loading your sign-in options…

{/if} + {#if ready} +
+ {#if available} +
{ event.preventDefault(); void submit(); }}> + {#if registration || fallback} + + {#if registration}3–32 lowercase letters, numbers, or underscores.{/if} + {/if} + {#if registration || mode === 'enroll'}{/if} + {#if android && (registration || mode === 'enroll')} + +

Choose Google Password Manager only if it is available on this Android device.

+ {/if} + {#if registration && config?.invite_required}{/if} + +
+ {#if !registration && !fallback && !session}{/if} + {:else}

Passkeys need a supported browser and a secure connection. Open this page in Safari, Chrome, or another browser with passkey support.

{/if} + {#if !registration && !management && !linking} + {#if config?.providers.length}
or continue with
{/if} + {#each config?.providers ?? [] as provider}{/each} + {/if} + {#if linking} + {#if session}{/if} + + {/if} +
+ + {/if} +
+ + diff --git a/apps/auth-web/src/routes/+layout.svelte b/apps/auth-web/src/routes/+layout.svelte new file mode 100644 index 000000000..59542fb13 --- /dev/null +++ b/apps/auth-web/src/routes/+layout.svelte @@ -0,0 +1,6 @@ + + +
piquel / sign in
{@render children()}
diff --git a/apps/auth-web/src/routes/+layout.ts b/apps/auth-web/src/routes/+layout.ts new file mode 100644 index 000000000..529e9eb36 --- /dev/null +++ b/apps/auth-web/src/routes/+layout.ts @@ -0,0 +1,2 @@ +export const prerender = true; +export const trailingSlash = 'never'; diff --git a/apps/auth-web/src/routes/+page.svelte b/apps/auth-web/src/routes/+page.svelte new file mode 100644 index 000000000..de2a91752 --- /dev/null +++ b/apps/auth-web/src/routes/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/auth-web/src/routes/authorize/+page.svelte b/apps/auth-web/src/routes/authorize/+page.svelte new file mode 100644 index 000000000..c481f8f73 --- /dev/null +++ b/apps/auth-web/src/routes/authorize/+page.svelte @@ -0,0 +1,27 @@ + +Authorize application · Piquel +
+

Application access

Continue to {details?.client_name ?? 'your application'}.

Review what this application will receive from your Piquel account.

+ {#if error}Sign in again + {:else if !details}

Loading application details…

+ {:else}

{details.client_name}

    {#each details.scopes as scope}
  • {scope === 'openid' ? 'Your account identifier' : scope === 'profile' ? 'Your username and display name' : scope === 'email' ? 'Your verified email address' : scope === 'offline_access' ? 'Stay signed in' : scope}
  • {/each}
{/if} +
diff --git a/apps/auth-web/src/routes/enroll/+page.svelte b/apps/auth-web/src/routes/enroll/+page.svelte new file mode 100644 index 000000000..afe12bf3e --- /dev/null +++ b/apps/auth-web/src/routes/enroll/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/auth-web/src/routes/link/+page.svelte b/apps/auth-web/src/routes/link/+page.svelte new file mode 100644 index 000000000..ac382781d --- /dev/null +++ b/apps/auth-web/src/routes/link/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/auth-web/src/routes/login/+page.svelte b/apps/auth-web/src/routes/login/+page.svelte new file mode 100644 index 000000000..de2a91752 --- /dev/null +++ b/apps/auth-web/src/routes/login/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/auth-web/src/routes/logout/+page.svelte b/apps/auth-web/src/routes/logout/+page.svelte new file mode 100644 index 000000000..163ab2acf --- /dev/null +++ b/apps/auth-web/src/routes/logout/+page.svelte @@ -0,0 +1,7 @@ + +Sign out · Piquel +

Your Piquel account

Ready to sign out?

This will end your Piquel sign-in session in this browser.

{#if error}{/if}Keep my session
diff --git a/apps/auth-web/src/routes/manage/+page.svelte b/apps/auth-web/src/routes/manage/+page.svelte new file mode 100644 index 000000000..687b3f24e --- /dev/null +++ b/apps/auth-web/src/routes/manage/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/auth-web/src/routes/register/+page.svelte b/apps/auth-web/src/routes/register/+page.svelte new file mode 100644 index 000000000..5f32bc9ad --- /dev/null +++ b/apps/auth-web/src/routes/register/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/auth-web/src/routes/social-onboarding/+page.svelte b/apps/auth-web/src/routes/social-onboarding/+page.svelte new file mode 100644 index 000000000..5f32bc9ad --- /dev/null +++ b/apps/auth-web/src/routes/social-onboarding/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/auth-web/svelte.config.js b/apps/auth-web/svelte.config.js new file mode 100644 index 000000000..9da856a95 --- /dev/null +++ b/apps/auth-web/svelte.config.js @@ -0,0 +1,2 @@ +import adapter from '@sveltejs/adapter-static'; +export default { kit: { adapter: adapter(), csp: { mode: 'hash', directives: { 'default-src': ['self'], 'script-src': ['self'], 'style-src': ['self', 'unsafe-inline'], 'connect-src': ['self'], 'object-src': ['none'], 'base-uri': ['none'], 'form-action': ['self'] } } } }; diff --git a/apps/auth-web/tsconfig.json b/apps/auth-web/tsconfig.json new file mode 100644 index 000000000..b8c5ae0eb --- /dev/null +++ b/apps/auth-web/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "./.svelte-kit/tsconfig.json", + "compilerOptions": { + "strict": true, + "allowJs": true, + "checkJs": true, + "moduleResolution": "bundler", + "resolveJsonModule": true, + "skipLibCheck": true + } +} diff --git a/apps/auth-web/vite.config.ts b/apps/auth-web/vite.config.ts new file mode 100644 index 000000000..63a65fd85 --- /dev/null +++ b/apps/auth-web/vite.config.ts @@ -0,0 +1,3 @@ +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; +export default defineConfig({ plugins: [sveltekit()] }); diff --git a/apps/piquel-web/.gitignore b/apps/piquel-web/.gitignore new file mode 100644 index 000000000..84c048a73 --- /dev/null +++ b/apps/piquel-web/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/apps/piquel-web/README.md b/apps/piquel-web/README.md new file mode 100644 index 000000000..10fe622ac --- /dev/null +++ b/apps/piquel-web/README.md @@ -0,0 +1,13 @@ +Static SvelteKit account settings, available at `/` and `/settings`. + +`VITE_AUTH_ORIGIN=https://auth.piquel.fr pnpm --filter @piquel/piquel-web build` +produces the standalone `build/` directory. The default auth origin is +`https://auth.piquel.fr`. This public build setting also configures the page's CSP. + +Settings call the public auth API with credentialed requests and a CSRF header. +The auth service must allow this exact settings origin and configure its complete +settings URL. All WebAuthn operations redirect to the auth origin; the two-minute +management authorization remains in PostgreSQL and is checked by the API. +This frontend never stores access or refresh tokens. + +For validation with the real Rust service, see `tests/browser/README.md`. diff --git a/apps/piquel-web/package.json b/apps/piquel-web/package.json new file mode 100644 index 000000000..0f7d16cf9 --- /dev/null +++ b/apps/piquel-web/package.json @@ -0,0 +1,23 @@ +{ + "name": "@piquel/piquel-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json" + }, + "dependencies": { + "@piquel/browser": "workspace:*" + }, + "devDependencies": { + "@sveltejs/adapter-static": "catalog:", + "@sveltejs/kit": "catalog:", + "@sveltejs/vite-plugin-svelte": "catalog:", + "svelte": "catalog:", + "svelte-check": "catalog:", + "typescript": "catalog:", + "vite": "catalog:" + } +} diff --git a/apps/piquel-web/src/app.html b/apps/piquel-web/src/app.html new file mode 100644 index 000000000..5adf2916b --- /dev/null +++ b/apps/piquel-web/src/app.html @@ -0,0 +1,2 @@ + +%sveltekit.head%
%sveltekit.body%
diff --git a/apps/piquel-web/src/lib/Settings.svelte b/apps/piquel-web/src/lib/Settings.svelte new file mode 100644 index 000000000..f47e9a6ae --- /dev/null +++ b/apps/piquel-web/src/lib/Settings.svelte @@ -0,0 +1,78 @@ + +Account security · Piquel +
+

Your account

Security, made personal.

Manage how you sign in to Piquel and keep your account in your hands.

+ {#if error}{/if} + {#if loading}

Loading account settings…

+ {:else if !session}

Sign in to see your settings

Use your Piquel account to manage your passkeys and linked providers.

Sign in
+ {:else} +
{session.user.display_name}

@{session.user.username}

+
{#if unlocked}Security settings unlocked

{Math.floor(remaining / 60)}:{String(remaining % 60).padStart(2, '0')} remaining. Your passkey verification expires automatically.

{:else}Your settings are protected

Verify a passkey to make changes for two minutes.

{/if}
{#if !unlocked}Unlock with a passkey{/if}
+

Passkeys

{passkeys.length} registered

Saved securely with your device or password manager. Keep a second passkey so you can always get back in.

+
    {#each passkeys as passkey}
  • + {#if editing === passkey.id}
    { event.preventDefault(); void rename(passkey); }}>
    + {:else if removing === passkey.id}
    Remove “{passkey.friendly_name}”?

    You won’t be able to use this passkey to sign in again.

    + {:else}
    {passkey.friendly_name}{#if passkey.created_at}

    Added {new Date(passkey.created_at).toLocaleDateString()}

    {/if}
    {/if} +
  • {/each}
+ {#if !passkeys.length}

Add your first passkey to protect your account and unlock security settings.

{/if} + Add a passkey

Your last passkey cannot be removed.

+
+

Social sign-in

Linked providers can sign you in. Only a passkey can authorize changes to these settings.

+
    {#each config?.providers ?? [] as provider}{@const identity = identities.find(value => value.provider === provider)}
  • {providerName(provider)}

    {identity ? identity.linked_email ?? 'Linked to your account' : 'Not linked'}

    {#if identity}{:else}{/if}
    {#if removing === provider}

    Remove {providerName(provider)} sign-in? Your passkeys will still work.

    {/if}
  • {/each}
+ {#if !config?.providers.length}

Social sign-in is not available yet.

{/if} +
+ {/if} +
diff --git a/apps/piquel-web/src/routes/+layout.svelte b/apps/piquel-web/src/routes/+layout.svelte new file mode 100644 index 000000000..356c3714f --- /dev/null +++ b/apps/piquel-web/src/routes/+layout.svelte @@ -0,0 +1,6 @@ + + +
piquel / account
{@render children()}
diff --git a/apps/piquel-web/src/routes/+layout.ts b/apps/piquel-web/src/routes/+layout.ts new file mode 100644 index 000000000..529e9eb36 --- /dev/null +++ b/apps/piquel-web/src/routes/+layout.ts @@ -0,0 +1,2 @@ +export const prerender = true; +export const trailingSlash = 'never'; diff --git a/apps/piquel-web/src/routes/+page.svelte b/apps/piquel-web/src/routes/+page.svelte new file mode 100644 index 000000000..148679b4b --- /dev/null +++ b/apps/piquel-web/src/routes/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/piquel-web/src/routes/settings/+page.svelte b/apps/piquel-web/src/routes/settings/+page.svelte new file mode 100644 index 000000000..148679b4b --- /dev/null +++ b/apps/piquel-web/src/routes/settings/+page.svelte @@ -0,0 +1,2 @@ + + diff --git a/apps/piquel-web/svelte.config.js b/apps/piquel-web/svelte.config.js new file mode 100644 index 000000000..8665cbd06 --- /dev/null +++ b/apps/piquel-web/svelte.config.js @@ -0,0 +1,2 @@ +import adapter from '@sveltejs/adapter-static'; +export default { kit: { adapter: adapter(), csp: { mode: 'hash', directives: { 'default-src': ['self'], 'script-src': ['self'], 'style-src': ['self', 'unsafe-inline'], 'connect-src': ['self', process.env.VITE_AUTH_ORIGIN ?? 'https://auth.piquel.fr'], 'object-src': ['none'], 'base-uri': ['none'], 'form-action': ['self'] } } } }; diff --git a/apps/piquel-web/tsconfig.json b/apps/piquel-web/tsconfig.json new file mode 100644 index 000000000..b8c5ae0eb --- /dev/null +++ b/apps/piquel-web/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "./.svelte-kit/tsconfig.json", + "compilerOptions": { + "strict": true, + "allowJs": true, + "checkJs": true, + "moduleResolution": "bundler", + "resolveJsonModule": true, + "skipLibCheck": true + } +} diff --git a/apps/piquel-web/vite.config.ts b/apps/piquel-web/vite.config.ts new file mode 100644 index 000000000..63a65fd85 --- /dev/null +++ b/apps/piquel-web/vite.config.ts @@ -0,0 +1,3 @@ +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; +export default defineConfig({ plugins: [sveltekit()] }); diff --git a/crates/auth-protocol/src/lib.rs b/crates/auth-protocol/src/lib.rs index e0e1379cf..2f1fe5d45 100644 --- a/crates/auth-protocol/src/lib.rs +++ b/crates/auth-protocol/src/lib.rs @@ -89,60 +89,6 @@ uuid_id!(UserId, "Immutable global Piquel account identifier."); uuid_id!(SessionId, "Opaque central-session identifier."); uuid_id!(TokenId, "Identifier for a token record or JWT."); -macro_rules! text_id { - ($name:ident, $doc:literal, $kind:literal) => { - #[doc = $doc] - #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] - #[serde(try_from = "String", into = "String")] - pub struct $name(String); - impl $name { - /// Returns the validated wire representation. - #[must_use] - pub fn as_str(&self) -> &str { - &self.0 - } - } - impl fmt::Display for $name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } - } - impl FromStr for $name { - type Err = InvalidValue; - fn from_str(value: &str) -> Result { - if value.is_empty() - || value.len() > 128 - || !value.bytes().all(|byte| { - byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':') - }) - { - return Err(InvalidValue::new($kind)); - } - Ok(Self(value.to_owned())) - } - } - impl TryFrom for $name { - type Error = InvalidValue; - fn try_from(value: String) -> Result { - value.parse() - } - } - impl From<$name> for String { - fn from(value: $name) -> Self { - value.0 - } - } - }; -} - -text_id!(ClientId, "Registered OAuth client identifier.", "client_id"); -text_id!(Audience, "Exact resource-server audience.", "audience"); -text_id!( - ServiceId, - "Registered internal service identifier.", - "service_id" -); - /// Account availability state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -161,27 +107,6 @@ pub enum AuthenticationMethod { Passkey, /// An approved external identity provider authenticated the user. Federation, - /// An existing central session continued the authentication. - Session, -} - -/// Shared fields in a resource-server access token. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct AccessTokenClaims { - /// Issuing authority URL. - pub iss: String, - /// Immutable account subject. - pub sub: UserId, - /// Exact intended resource audience. - pub aud: Audience, - /// Session that authenticated the subject. - pub sid: SessionId, - /// Unique token identifier. - pub jti: TokenId, - /// Expiry timestamp in Unix seconds. - pub exp: i64, - /// Issued-at timestamp in Unix seconds. - pub iat: i64, } #[cfg(test)] @@ -199,11 +124,4 @@ mod tests { ); assert!(id.to_string().to_uppercase().parse::().is_err()); } - - #[test] - fn text_identifiers_reject_wire_ambiguity() { - assert!("product-api".parse::().is_ok()); - assert!("product api".parse::().is_err()); - assert!("".parse::().is_err()); - } } diff --git a/crates/configuration/src/lib.rs b/crates/configuration/src/lib.rs index 5623c14b6..f030d69c9 100644 --- a/crates/configuration/src/lib.rs +++ b/crates/configuration/src/lib.rs @@ -1,11 +1,6 @@ //! Small validated configuration primitives. Secrets are references, never values. -use std::{ - env, fmt, fs, - net::{IpAddr, SocketAddr}, - str::FromStr, - time::Duration, -}; +use std::{env, fmt, fs, net::IpAddr}; use thiserror::Error; use url::Url; @@ -84,7 +79,7 @@ impl SecretReference { /// /// Returns an error for empty or whitespace-containing references. pub fn parse(value: &str) -> Result { - let allowed = ["env://", "file://", "kms://"]; + let allowed = ["env://", "file://"]; if value.trim().is_empty() || value.chars().any(char::is_whitespace) || !allowed.iter().any(|prefix| value.starts_with(prefix)) @@ -151,29 +146,6 @@ impl fmt::Display for SecretReference { } } -/// Parses a socket address from an environment value. -/// -/// # Errors -/// -/// Returns an error if the supplied value is not a socket address. -pub fn socket_addr(name: &'static str, value: &str) -> Result { - SocketAddr::from_str(value).map_err(|_| ConfigurationError::Invalid { name }) -} -/// Parses a non-zero duration expressed as seconds. -/// -/// # Errors -/// -/// Returns an error if the supplied value is zero or not an unsigned integer. -pub fn seconds(name: &'static str, value: &str) -> Result { - let seconds = value - .parse::() - .map_err(|_| ConfigurationError::Invalid { name })?; - if seconds == 0 { - return Err(ConfigurationError::Invalid { name }); - } - Ok(Duration::from_secs(seconds)) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/database/README.md b/crates/database/README.md index 6887f666d..0a4875f2d 100644 --- a/crates/database/README.md +++ b/crates/database/README.md @@ -1,14 +1,11 @@ -# Piquel repository +# piquel-repository -`piquel-repository` is the only SQLx consumer. Applications use `Database` and -typed repositories only; pool, transaction, row, and SQLx error types are not -public API. +Typed PostgreSQL persistence for the authentication service. SQLx pools and SQL +remain private; callers use repositories or a `DatabaseTransaction`. -Set `DATABASE_URL` in the process environment and run migrations explicitly with -`just migrate`. Applications do -not migrate on startup. Database integration tests use a disposable PostgreSQL -database named by `TEST_DATABASE_URL`; each test must create an isolated schema -and drop it afterwards, so ordering is never significant. +See [database architecture](../../docs/architecture/database-crate.md) for invariants. +Run migrations through the single service binary: `auth-service migrate`. -Database tests are not currently configured. `just test-database` prints a -message and skips the database suite. +Integration tests use a disposable `TEST_DATABASE_URL`, apply the schema, and insert +uniquely named fixtures into that database. They do not create per-test schemas. +Run them explicitly with the command in the root README; ordinary tests skip them. diff --git a/crates/database/migrations/0001_initial_extensions.sql b/crates/database/migrations/0001_initial_extensions.sql deleted file mode 100644 index ff7fb7593..000000000 --- a/crates/database/migrations/0001_initial_extensions.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Reserved initial migration. UUIDv7 values are generated by the application. --- Tables are introduced only by their owning feature migrations. diff --git a/crates/database/migrations/0002_identity_sessions.sql b/crates/database/migrations/0002_identity_sessions.sql index ab1e3e2b8..6c4907790 100644 --- a/crates/database/migrations/0002_identity_sessions.sql +++ b/crates/database/migrations/0002_identity_sessions.sql @@ -120,17 +120,3 @@ CREATE TABLE security_audit_log ( created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX security_audit_log_user_created_idx ON security_audit_log (user_id, created_at DESC); - -CREATE TABLE internal_events ( - id UUID PRIMARY KEY, - aggregate_type TEXT NOT NULL, - aggregate_id UUID NOT NULL, - aggregate_sequence BIGINT NOT NULL CHECK (aggregate_sequence > 0), - event_type TEXT NOT NULL, - schema_version INTEGER NOT NULL CHECK (schema_version > 0), - payload JSONB NOT NULL, - occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(), - published_at TIMESTAMPTZ, - UNIQUE (aggregate_type, aggregate_id, aggregate_sequence) -); -CREATE INDEX internal_events_unpublished_idx ON internal_events (occurred_at) WHERE published_at IS NULL; diff --git a/crates/database/migrations/0003_passkey_credentials.sql b/crates/database/migrations/0003_passkey_credentials.sql index 7969d3785..ec43b5e95 100644 --- a/crates/database/migrations/0003_passkey_credentials.sql +++ b/crates/database/migrations/0003_passkey_credentials.sql @@ -3,10 +3,6 @@ CREATE TABLE passkey_credentials ( credential_id BYTEA NOT NULL UNIQUE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, credential JSONB NOT NULL, - signature_counter BIGINT NOT NULL DEFAULT 0 CHECK (signature_counter >= 0), - transports JSONB NOT NULL DEFAULT '[]'::jsonb, - backup_eligible BOOLEAN NOT NULL, - backup_state BOOLEAN NOT NULL, friendly_name TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), last_used_at TIMESTAMPTZ, @@ -14,8 +10,8 @@ CREATE TABLE passkey_credentials ( ); CREATE INDEX passkey_credentials_active_user_idx ON passkey_credentials (user_id, created_at) WHERE revoked_at IS NULL; --- Ceremony records are deliberately server-side and short lived. Their digest --- prevents challenge material from appearing in persistent state or logs. +-- Ceremony state includes the challenge and is stored server-side until expiry. +-- It is never accepted twice and must never appear in logs. CREATE TABLE webauthn_ceremonies ( id UUID PRIMARY KEY, user_id UUID REFERENCES users(id) ON DELETE CASCADE, @@ -29,17 +25,6 @@ CREATE TABLE webauthn_ceremonies ( ); CREATE INDEX webauthn_ceremonies_expiry_idx ON webauthn_ceremonies (expires_at) WHERE consumed_at IS NULL; -CREATE TABLE purpose_authorizations ( - id UUID PRIMARY KEY, - user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, - session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - purpose TEXT NOT NULL CHECK (purpose IN ('manage-passkeys')), - expires_at TIMESTAMPTZ NOT NULL, - consumed_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); -CREATE INDEX purpose_authorizations_expiry_idx ON purpose_authorizations (expires_at) WHERE consumed_at IS NULL; - CREATE TABLE browser_session_secrets ( session_id UUID PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE, secret_digest BYTEA NOT NULL UNIQUE, diff --git a/crates/database/migrations/0004_oidc_tokens.sql b/crates/database/migrations/0004_oidc_tokens.sql new file mode 100644 index 000000000..082c3e3b3 --- /dev/null +++ b/crates/database/migrations/0004_oidc_tokens.sql @@ -0,0 +1,81 @@ +CREATE TABLE oidc_clients ( + id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + client_secret_hash BYTEA CHECK (client_secret_hash IS NULL OR octet_length(client_secret_hash)=32), + trusted BOOLEAN NOT NULL DEFAULT FALSE, + allowed_scopes JSONB NOT NULL, + allowed_audiences JSONB NOT NULL, + allow_refresh BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE TABLE oidc_redirect_uris ( + client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, + uri TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('authorization', 'post_logout')), + PRIMARY KEY (client_id, uri, kind) +); + +CREATE TABLE authorization_codes ( + id UUID PRIMARY KEY, + secret_digest BYTEA NOT NULL UNIQUE, + client_id TEXT NOT NULL REFERENCES oidc_clients(id), + user_id UUID NOT NULL REFERENCES users(id), + session_id UUID NOT NULL REFERENCES sessions(id), + redirect_uri TEXT NOT NULL, + pkce_challenge TEXT NOT NULL, + nonce TEXT, + scopes JSONB NOT NULL, + audience TEXT NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX authorization_codes_active_idx ON authorization_codes (expires_at) WHERE consumed_at IS NULL; + +CREATE TABLE authorization_requests ( + id UUID PRIMARY KEY, + secret_digest BYTEA NOT NULL UNIQUE, + client_id TEXT NOT NULL REFERENCES oidc_clients(id), + redirect_uri TEXT NOT NULL, + client_state TEXT NOT NULL, + nonce TEXT, + pkce_challenge TEXT NOT NULL, + scopes JSONB NOT NULL, + audience TEXT NOT NULL, + force_login BOOLEAN NOT NULL, + force_consent BOOLEAN NOT NULL, + max_age BIGINT, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX authorization_requests_active_idx ON authorization_requests (expires_at) WHERE consumed_at IS NULL; + +CREATE TABLE refresh_token_families ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id), + client_id TEXT NOT NULL REFERENCES oidc_clients(id), + session_id UUID NOT NULL REFERENCES sessions(id), + audience TEXT NOT NULL, + scopes JSONB NOT NULL, + revoked_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE TABLE refresh_tokens ( + id UUID PRIMARY KEY, + family_id UUID NOT NULL REFERENCES refresh_token_families(id) ON DELETE CASCADE, + secret_digest BYTEA NOT NULL UNIQUE, + expires_at TIMESTAMPTZ NOT NULL, + issued_at TIMESTAMPTZ NOT NULL DEFAULT now(), + consumed_at TIMESTAMPTZ +); +CREATE INDEX refresh_tokens_family_idx ON refresh_tokens (family_id); + +CREATE TABLE oidc_consents ( + user_id UUID NOT NULL REFERENCES users(id), + client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, + audience TEXT NOT NULL, + scopes JSONB NOT NULL, + PRIMARY KEY(user_id, client_id, audience) +); diff --git a/crates/database/migrations/0005_federation.sql b/crates/database/migrations/0005_federation.sql new file mode 100644 index 000000000..faf143955 --- /dev/null +++ b/crates/database/migrations/0005_federation.sql @@ -0,0 +1,51 @@ +CREATE TABLE external_login_identities ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + provider_name TEXT NOT NULL CHECK (provider_name IN ('github', 'google')), + issuer TEXT NOT NULL, + subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 255), + linked_email TEXT, + linked_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_login_at TIMESTAMPTZ NOT NULL DEFAULT now(), + revoked_at TIMESTAMPTZ +); +-- Unlinking releases a provider subject, but keeps its audit history. +CREATE UNIQUE INDEX external_identity_active_subject ON external_login_identities(issuer,subject) WHERE revoked_at IS NULL; +CREATE UNIQUE INDEX external_identity_active_provider ON external_login_identities(user_id,provider_name) WHERE revoked_at IS NULL; + +CREATE TABLE federation_transactions ( + id UUID PRIMARY KEY, + provider_name TEXT NOT NULL CHECK (provider_name IN ('github', 'google')), + state_digest BYTEA NOT NULL UNIQUE CHECK (octet_length(state_digest)=32), + browser_digest BYTEA NOT NULL CHECK (octet_length(browser_digest)=32), + nonce TEXT NOT NULL, + pkce_verifier TEXT NOT NULL, + return_to TEXT NOT NULL, + link_user_id UUID REFERENCES users(id) ON DELETE CASCADE, + link_session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK ((link_user_id IS NULL) = (link_session_id IS NULL)) +); +CREATE INDEX federation_transactions_expiry_idx ON federation_transactions(expires_at); + +-- No user or normal session exists while social signup is pending. The browser +-- must finish its first passkey before this identity can be committed. +CREATE TABLE pending_federation ( + id UUID PRIMARY KEY, + browser_digest BYTEA NOT NULL UNIQUE CHECK (octet_length(browser_digest)=32), + provider_name TEXT NOT NULL CHECK (provider_name IN ('github','google')), + issuer TEXT NOT NULL, + subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 255), + email TEXT, + display_name TEXT NOT NULL, + return_to TEXT NOT NULL, + link_user_id UUID REFERENCES users(id) ON DELETE CASCADE, + link_session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (link_session_id IS NULL OR link_user_id IS NOT NULL) +); +CREATE INDEX pending_federation_expiry_idx ON pending_federation(expires_at); diff --git a/crates/database/migrations/0008_security.sql b/crates/database/migrations/0008_security.sql new file mode 100644 index 000000000..f45b0e410 --- /dev/null +++ b/crates/database/migrations/0008_security.sql @@ -0,0 +1,14 @@ +ALTER TABLE sessions ADD COLUMN management_expires_at TIMESTAMPTZ; + +CREATE TABLE invitations ( + secret_digest BYTEA PRIMARY KEY CHECK (octet_length(secret_digest) = 32), + expires_at TIMESTAMPTZ NOT NULL, + redeemed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE request_limits ( + bucket BYTEA PRIMARY KEY, + requests INTEGER NOT NULL, + expires_at TIMESTAMPTZ NOT NULL +); diff --git a/crates/database/src/bin/migrate.rs b/crates/database/src/bin/migrate.rs deleted file mode 100644 index b29209f99..000000000 --- a/crates/database/src/bin/migrate.rs +++ /dev/null @@ -1,12 +0,0 @@ -#![allow(missing_docs)] - -use piquel_repository::{Database, DatabaseConfig}; -use std::{env, time::Duration}; - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - let url = env::var("DATABASE_URL")?; - let database = Database::connect(DatabaseConfig::new(url, 1, Duration::from_secs(10))?).await?; - database.run_migrations().await?; - Ok(()) -} diff --git a/crates/database/src/connection.rs b/crates/database/src/connection.rs index 482fbd00e..7d41f82fb 100644 --- a/crates/database/src/connection.rs +++ b/crates/database/src/connection.rs @@ -1,14 +1,17 @@ use crate::{ DatabaseConnectionError, DatabaseError, repositories::*, transaction::DatabaseTransaction, }; -use sqlx::{PgPool, postgres::PgPoolOptions}; -use std::{net::IpAddr, time::Duration}; +use sqlx::{ + PgPool, + postgres::{PgConnectOptions, PgPoolOptions, PgSslMode}, +}; +use std::{net::IpAddr, str::FromStr, time::Duration}; use url::Url; /// Validated database connection configuration. #[derive(Clone)] pub struct DatabaseConfig { - url: String, + options: PgConnectOptions, max_connections: u32, connect_timeout: Duration, } @@ -16,7 +19,7 @@ impl std::fmt::Debug for DatabaseConfig { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter .debug_struct("DatabaseConfig") - .field("url", &"[REDACTED]") + .field("options", &"[REDACTED]") .field("max_connections", &self.max_connections) .field("connect_timeout", &self.connect_timeout) .finish() @@ -25,13 +28,13 @@ impl std::fmt::Debug for DatabaseConfig { impl DatabaseConfig { /// Creates production configuration requiring verified `PostgreSQL` TLS. pub fn new( - url: String, + url: &str, max_connections: u32, connect_timeout: Duration, ) -> Result { - Self::validate(&url, max_connections, connect_timeout, false)?; + let options = Self::validate(url, max_connections, connect_timeout, false)?; Ok(Self { - url, + options, max_connections, connect_timeout, }) @@ -39,13 +42,13 @@ impl DatabaseConfig { /// Creates explicit local-development configuration for a loopback database. pub fn new_development( - url: String, + url: &str, max_connections: u32, connect_timeout: Duration, ) -> Result { - Self::validate(&url, max_connections, connect_timeout, true)?; + let options = Self::validate(url, max_connections, connect_timeout, true)?; Ok(Self { - url, + options, max_connections, connect_timeout, }) @@ -56,7 +59,7 @@ impl DatabaseConfig { max_connections: u32, connect_timeout: Duration, development: bool, - ) -> Result<(), DatabaseConnectionError> { + ) -> Result { let parsed = Url::parse(url).map_err(|_| DatabaseConnectionError::InvalidConfiguration)?; if !matches!(parsed.scheme(), "postgres" | "postgresql") || max_connections == 0 @@ -67,6 +70,18 @@ impl DatabaseConfig { let host = parsed .host_str() .ok_or(DatabaseConnectionError::InvalidConfiguration)?; + + let mut ssl_modes = parsed.query_pairs().filter_map(|(name, value)| { + matches!(name.as_ref(), "sslmode" | "ssl-mode").then_some(value) + }); + let ssl_mode = ssl_modes.next(); + if ssl_modes.next().is_some() + || parsed + .query_pairs() + .any(|(name, _)| matches!(name.as_ref(), "host" | "hostaddr")) + { + return Err(DatabaseConnectionError::InvalidConfiguration); + } if development { let loopback = host.eq_ignore_ascii_case("localhost") || host @@ -75,13 +90,19 @@ impl DatabaseConfig { if !loopback { return Err(DatabaseConnectionError::InvalidConfiguration); } - } else if !parsed - .query_pairs() - .any(|(name, value)| name == "sslmode" && value == "verify-full") - { + } else if ssl_mode.as_deref() != Some("verify-full") { return Err(DatabaseConnectionError::InvalidConfiguration); } - Ok(()) + + let options = PgConnectOptions::from_str(url) + .map_err(|_| DatabaseConnectionError::InvalidConfiguration)?; + Ok(if development { + options + } else { + // Keep the effective mode explicit even after validating the URL so + // future parser changes cannot silently weaken production TLS. + options.ssl_mode(PgSslMode::VerifyFull) + }) } } @@ -96,9 +117,9 @@ impl Database { let pool = PgPoolOptions::new() .max_connections(config.max_connections) .acquire_timeout(config.connect_timeout) - .connect(&config.url) + .connect_with(config.options) .await - .map_err(|_| DatabaseConnectionError::Unavailable)?; + .map_err(|error| DatabaseConnectionError::Connection(Box::new(error)))?; Ok(Self { pool }) } /// Checks availability with a bounded, non-sensitive query. @@ -120,12 +141,40 @@ impl Database { .map(DatabaseTransaction::new) .map_err(Into::into) } - /// Runs immutable migrations only when explicitly invoked by the migration binary. + /// Runs schema migrations when explicitly requested through the auth binary. pub async fn run_migrations(&self) -> Result<(), DatabaseError> { sqlx::migrate!("./migrations") .run(&self.pool) .await - .map_err(|_| DatabaseError::Internal) + .map_err(|error| DatabaseError::Operation(Box::new(error))) + } + /// Purges a bounded batch of expired ephemeral authentication state. + pub async fn purge_expired_auth_state(&self, batch_size: u32) -> Result { + let limit = i64::from(batch_size.clamp(1, 1_000)); + let mut transaction = self.pool.begin().await.map_err(DatabaseError::from)?; + let mut deleted = 0; + for statement in [ + "DELETE FROM request_limits WHERE ctid IN (SELECT ctid FROM request_limits WHERE expires_at UserRepository<'_> { UserRepository::from_pool(&self.pool) @@ -139,9 +188,6 @@ impl Database { pub fn audit_events(&self) -> AuditEventRepository<'_> { AuditEventRepository::from_pool(&self.pool) } - pub fn internal_events(&self) -> InternalEventRepository<'_> { - InternalEventRepository::from_pool(&self.pool) - } pub fn passkeys(&self) -> PasskeyRepository<'_> { PasskeyRepository::from_pool(&self.pool) } @@ -154,8 +200,8 @@ impl Database { pub fn federation(&self) -> FederationRepository<'_> { FederationRepository::from_pool(&self.pool) } - pub fn service_identities(&self) -> ServiceIdentityRepository<'_> { - ServiceIdentityRepository::from_pool(&self.pool) + pub fn security(&self) -> SecurityRepository<'_> { + SecurityRepository::from_pool(&self.pool) } } @@ -165,17 +211,20 @@ mod tests { #[test] fn production_requires_verified_tls() { + assert!( + DatabaseConfig::new("postgres://db.example/piquel", 1, Duration::from_secs(1)).is_err() + ); assert!( DatabaseConfig::new( - "postgres://db.example/piquel".into(), + "postgres://db.example/piquel?sslmode=verify-full", 1, Duration::from_secs(1) ) - .is_err() + .is_ok() ); assert!( DatabaseConfig::new( - "postgres://db.example/piquel?sslmode=verify-full".into(), + "postgres://db.example/piquel?ssl-mode=verify-full", 1, Duration::from_secs(1) ) @@ -183,11 +232,28 @@ mod tests { ); } + #[test] + fn production_rejects_ambiguous_tls_modes_and_host_overrides() { + for url in [ + "postgres://db.example/piquel?sslmode=verify-full&sslmode=disable", + "postgres://db.example/piquel?sslmode=disable&sslmode=verify-full", + "postgres://db.example/piquel?sslmode=verify-full&ssl-mode=disable", + "postgres://db.example/piquel?sslmode=verify-full&ssl-mode=verify-full", + "postgres://db.example/piquel?sslmode=verify-full&host=elsewhere.example", + "postgres://db.example/piquel?sslmode=verify-full&hostaddr=127.0.0.1", + ] { + assert!( + DatabaseConfig::new(url, 1, Duration::from_secs(1)).is_err(), + "accepted ambiguous database URL: {url}" + ); + } + } + #[test] fn development_is_loopback_only() { assert!( DatabaseConfig::new_development( - "postgres://localhost/piquel".into(), + "postgres://localhost/piquel", 1, Duration::from_secs(1) ) @@ -195,7 +261,15 @@ mod tests { ); assert!( DatabaseConfig::new_development( - "postgres://db.example/piquel".into(), + "postgres://db.example/piquel", + 1, + Duration::from_secs(1) + ) + .is_err() + ); + assert!( + DatabaseConfig::new_development( + "postgres://localhost/piquel?host=db.example", 1, Duration::from_secs(1) ) diff --git a/crates/database/src/error.rs b/crates/database/src/error.rs index c8eb48e45..5b64c9cb2 100644 --- a/crates/database/src/error.rs +++ b/crates/database/src/error.rs @@ -17,6 +17,8 @@ pub enum DatabaseError { TransactionFailed, #[error("an unexpected database error occurred")] Internal, + #[error("database operation failed")] + Operation(#[source] Box), } /// Errors that can occur while constructing the database boundary. @@ -26,18 +28,18 @@ pub enum DatabaseConnectionError { InvalidConfiguration, #[error("database connection is unavailable")] Unavailable, + #[error("database connection failed")] + Connection(#[source] Box), } impl From for DatabaseError { fn from(value: sqlx::Error) -> Self { match value { sqlx::Error::RowNotFound => Self::NotFound, - sqlx::Error::PoolTimedOut => Self::Timeout, - sqlx::Error::PoolClosed | sqlx::Error::Io(_) | sqlx::Error::Tls(_) => Self::Unavailable, sqlx::Error::Database(database_error) if database_error.is_unique_violation() => { Self::Conflict } - _ => Self::Internal, + error => Self::Operation(Box::new(error)), } } } diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs index 78351761e..f2b258c9d 100644 --- a/crates/database/src/lib.rs +++ b/crates/database/src/lib.rs @@ -1,8 +1,9 @@ //! The sole `SQLx` boundary for the Piquel workspace. //! //! Applications receive typed repositories and never a pool, executor, row, or -//! `SQLx` error. Feature repositories are intentionally scaffolded until their -//! owning auth plan supplies persistence operations. +//! `SQLx` error. Repositories expose only the operations used by the service. +// This unpublished persistence API mirrors the schema; field-by-field rustdoc +// and mechanical accessor annotations would duplicate the migration documentation. #![allow(missing_docs)] #![allow( clippy::missing_errors_doc, @@ -20,8 +21,7 @@ pub use connection::{Database, DatabaseConfig}; pub use error::{DatabaseConnectionError, DatabaseError}; pub use models::*; pub use repositories::{ - AuditEventRepository, EmailRepository, FederationRepository, InternalEventRepository, - OidcRepository, PasskeyRepository, ServiceIdentityRepository, SessionRepository, - TokenRepository, UserRepository, + AuditEventRepository, EmailRepository, FederationRepository, OidcRepository, PasskeyRepository, + SecurityRepository, SessionRepository, TokenRepository, UserRepository, }; pub use transaction::DatabaseTransaction; diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index c1645f99e..e57f02046 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -18,13 +18,6 @@ pub struct InsertUser { pub username: String, pub display_name: String, } -#[derive(Clone, Debug)] -pub struct UpdateUserProfile { - pub id: UserId, - pub expected_version: u64, - pub username: String, - pub display_name: String, -} #[derive(Clone, Debug, PartialEq, Eq)] pub struct StoredEmail { pub id: TokenId, @@ -68,16 +61,6 @@ pub struct AppendAuditEvent { pub outcome: String, pub request_metadata: Value, } -#[derive(Clone, Debug)] -pub struct AppendInternalEvent { - pub id: TokenId, - pub aggregate_type: String, - pub aggregate_id: UserId, - pub event_type: String, - pub schema_version: u32, - pub payload: Value, -} - #[derive(Clone, Debug)] pub struct InsertPasskey { pub id: TokenId, @@ -111,11 +94,8 @@ pub struct ConsumedCeremony { pub session_id: Option, pub state: Value, } -#[derive(Clone, Debug)] -pub struct InsertPurposeAuthorization { - pub id: TokenId, - pub user_id: UserId, - pub session_id: SessionId, - pub purpose: String, - pub expires_at: DateTime, -} + +mod federation; +mod oidc; +pub use federation::*; +pub use oidc::*; diff --git a/crates/database/src/models/federation.rs b/crates/database/src/models/federation.rs new file mode 100644 index 000000000..e003c9c71 --- /dev/null +++ b/crates/database/src/models/federation.rs @@ -0,0 +1,56 @@ +use super::*; + +#[derive(Clone, Debug)] +pub struct InsertFederationTransaction { + pub id: TokenId, + pub provider: String, + pub state_digest: Vec, + pub browser_digest: Vec, + pub nonce: String, + pub pkce_verifier: String, + pub return_to: String, + pub link_user_id: Option, + pub link_session_id: Option, + pub expires_at: DateTime, +} +#[derive(Clone, Debug)] +pub struct ConsumedFederationTransaction { + pub nonce: String, + pub pkce_verifier: String, + pub return_to: String, + pub link_user_id: Option, + pub link_session_id: Option, +} +#[derive(Clone, Debug)] +pub struct InsertExternalIdentity { + pub id: TokenId, + pub user_id: UserId, + pub provider: String, + pub issuer: String, + pub subject: String, + pub linked_email: Option, +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredExternalIdentity { + pub id: TokenId, + pub user_id: UserId, + pub provider: String, + pub issuer: String, + pub subject: String, + pub linked_email: Option, +} +/// Verified provider evidence, usable only by its initiating browser until expiry. +#[derive(Clone, Debug)] +pub struct PendingFederation { + pub id: TokenId, + pub browser_digest: Vec, + pub provider: String, + pub issuer: String, + pub subject: String, + pub email: Option, + pub display_name: String, + pub return_to: String, + pub link_user_id: Option, + pub link_session_id: Option, + pub expires_at: DateTime, +} diff --git a/crates/database/src/models/oidc.rs b/crates/database/src/models/oidc.rs new file mode 100644 index 000000000..f587708e8 --- /dev/null +++ b/crates/database/src/models/oidc.rs @@ -0,0 +1,132 @@ +use super::*; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredOidcClient { + pub id: String, + pub display_name: String, + pub redirect_uris: Vec, + pub post_logout_uris: Vec, + pub allowed_scopes: Vec, + pub allowed_audiences: Vec, + pub allow_refresh: bool, + pub enabled: bool, + pub trusted: bool, + pub client_secret_hash: Option>, +} + +#[derive(Clone, Debug)] +pub struct InsertAuthorizationRequest { + pub id: TokenId, + pub secret_digest: Vec, + pub client_id: String, + pub redirect_uri: String, + pub client_state: String, + pub nonce: Option, + pub pkce_challenge: String, + pub scopes: Vec, + pub audience: String, + pub force_login: bool, + pub force_consent: bool, + pub max_age: Option, + pub expires_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct StoredAuthorizationRequest { + pub id: TokenId, + pub client_id: String, + pub client_display_name: String, + pub redirect_uri: String, + pub client_state: String, + pub nonce: Option, + pub pkce_challenge: String, + pub scopes: Vec, + pub audience: String, + pub force_login: bool, + pub force_consent: bool, + pub max_age: Option, + pub created_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct BootstrapOidcClient { + pub id: String, + pub display_name: String, + pub redirect_uris: Vec, + pub post_logout_uris: Vec, + pub allowed_scopes: Vec, + pub allowed_audiences: Vec, + pub allow_refresh: bool, + pub enabled: bool, + pub trusted: bool, + pub client_secret_hash: Option>, +} + +#[derive(Clone, Debug)] +pub struct InsertAuthorizationCode { + pub id: TokenId, + pub secret_digest: Vec, + pub client_id: String, + pub user_id: UserId, + pub session_id: SessionId, + pub redirect_uri: String, + pub pkce_challenge: String, + pub nonce: Option, + pub scopes: Vec, + pub audience: String, + pub expires_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct ConsumedAuthorizationCode { + pub client_id: String, + pub user_id: UserId, + pub session_id: SessionId, + pub redirect_uri: String, + pub pkce_challenge: String, + pub nonce: Option, + pub scopes: Vec, + pub audience: String, +} + +#[derive(Clone, Debug)] +pub struct InsertRefreshFamily { + pub id: TokenId, + pub user_id: UserId, + pub client_id: String, + pub session_id: SessionId, + pub audience: String, + pub scopes: Vec, +} + +#[derive(Clone, Debug)] +pub struct InsertRefreshToken { + pub id: TokenId, + pub family_id: TokenId, + pub secret_digest: Vec, + pub expires_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct RotatedRefreshToken { + pub family_id: TokenId, + pub user_id: UserId, + pub client_id: String, + pub session_id: SessionId, + pub audience: String, + pub scopes: Vec, +} + +#[derive(Debug)] +pub enum RefreshRotationError { + Database(crate::DatabaseError), + Invalid, + Replay { user_id: UserId }, + Policy { user_id: UserId }, +} + +impl RefreshRotationError { + pub(crate) fn database(error: impl std::error::Error + Send + Sync + 'static) -> Self { + Self::Database(crate::DatabaseError::Operation(Box::new(error))) + } +} diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 4b1e9679a..1e33eed37 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,14 +1,9 @@ //! Domain repository handles backed by a private pool or transaction connection. -use crate::{ - AppendAuditEvent, AppendInternalEvent, ConsumedCeremony, DatabaseError, InsertCeremony, - InsertPasskey, InsertPurposeAuthorization, InsertSession, InsertUser, InsertVerifiedEmail, - StoredEmail, StoredPasskey, StoredSession, StoredUser, UpdateUserProfile, -}; +use crate::{DatabaseError, models::*}; use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; use sqlx::{PgConnection, PgPool, Row}; -#[allow(dead_code)] pub(crate) enum RepositoryExecutor<'a> { Pool(&'a PgPool), Connection(&'a mut PgConnection), @@ -18,7 +13,6 @@ macro_rules! repository { ($name:ident) => { /// Focused persistence handle; it has no policy and no public SQL escape hatch. pub struct $name<'a> { - #[allow(dead_code)] pub(crate) executor: RepositoryExecutor<'a>, } impl<'a> $name<'a> { @@ -39,12 +33,11 @@ repository!(UserRepository); repository!(EmailRepository); repository!(SessionRepository); repository!(AuditEventRepository); -repository!(InternalEventRepository); repository!(PasskeyRepository); repository!(OidcRepository); repository!(TokenRepository); repository!(FederationRepository); -repository!(ServiceIdentityRepository); +repository!(SecurityRepository); macro_rules! fetch_optional { ($self:expr, $query:expr) => {{ @@ -122,41 +115,18 @@ impl UserRepository<'_> { pub async fn find_by_id(&mut self, id: UserId) -> Result, DatabaseError> { fetch_optional!(self, sqlx::query("SELECT id, username, display_name, profile_version, status, created_at, updated_at FROM users WHERE id = $1").bind(id.as_uuid()))?.map(|row| stored_user(&row)).transpose() } + pub async fn find_active_by_id_for_update( + &mut self, + id: UserId, + ) -> Result, DatabaseError> { + fetch_optional!(self, sqlx::query("SELECT id, username, display_name, profile_version, status, created_at, updated_at FROM users WHERE id = $1 AND status='active' FOR UPDATE").bind(id.as_uuid()))?.map(|row| stored_user(&row)).transpose() + } pub async fn find_active_by_username( &mut self, username: &str, ) -> Result, DatabaseError> { fetch_optional!(self, sqlx::query("SELECT id, username, display_name, profile_version, status, created_at, updated_at FROM users WHERE username = $1 AND status = 'active'").bind(username))?.map(|row| stored_user(&row)).transpose() } - pub async fn update_profile( - &mut self, - input: &UpdateUserProfile, - ) -> Result { - let expected = - i64::try_from(input.expected_version).map_err(|_| DatabaseError::Conflict)?; - let row = fetch_optional!(self, sqlx::query("UPDATE users SET username = $1, display_name = $2, profile_version = profile_version + 1, updated_at = now() WHERE id = $3 AND profile_version = $4 RETURNING id, username, display_name, profile_version, status, created_at, updated_at").bind(&input.username).bind(&input.display_name).bind(input.id.as_uuid()).bind(expected))?.ok_or(DatabaseError::Conflict)?; - stored_user(&row) - } - pub async fn set_status( - &mut self, - id: UserId, - status: AccountStatus, - ) -> Result { - let status = match status { - AccountStatus::Active => "active", - AccountStatus::Disabled => "disabled", - }; - Ok(execute!( - self, - sqlx::query( - "UPDATE users SET status = $1, updated_at = now() WHERE id = $2 AND status <> $1" - ) - .bind(status) - .bind(id.as_uuid()) - )? - .rows_affected() - == 1) - } } impl EmailRepository<'_> { @@ -241,9 +211,7 @@ impl SessionRepository<'_> { ) -> Result, DatabaseError> { fetch_optional!(self, sqlx::query("SELECT s.id,s.user_id,s.authentication_methods,s.authenticated_at,s.expires_at,s.last_seen_at,s.revoked_at FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.id=$1 AND s.revoked_at IS NULL AND s.expires_at>now() AND u.status='active'").bind(id.as_uuid()))?.map(|row| stored_session(&row)).transpose() } - pub async fn touch(&mut self, id: SessionId) -> Result { - Ok(execute!(self, sqlx::query("UPDATE sessions s SET last_seen_at=now() FROM users u WHERE s.id=$1 AND s.user_id=u.id AND u.status='active' AND s.revoked_at IS NULL AND s.expires_at>now()").bind(id.as_uuid()))?.rows_affected()==1) - } + pub async fn revoke(&mut self, id: SessionId) -> Result { Ok(execute!( self, @@ -253,17 +221,8 @@ impl SessionRepository<'_> { .rows_affected() == 1) } - pub async fn revoke_all_for_user(&mut self, user_id: UserId) -> Result { - Ok(execute!( - self, - sqlx::query( - "UPDATE sessions SET revoked_at=now() WHERE user_id=$1 AND revoked_at IS NULL" - ) - .bind(user_id.as_uuid()) - )? - .rows_affected()) - } } + fn stored_session(row: &sqlx::postgres::PgRow) -> Result { let methods: serde_json::Value = row .try_get("authentication_methods") @@ -302,21 +261,9 @@ impl AuditEventRepository<'_> { Ok(()) } } -impl InternalEventRepository<'_> { - pub async fn append(&mut self, input: &AppendInternalEvent) -> Result { - let version = i32::try_from(input.schema_version).map_err(|_| DatabaseError::Internal)?; - let row = fetch_one!(self, sqlx::query("WITH locked AS (SELECT pg_advisory_xact_lock(hashtextextended($1 || ':' || $2::text, 0))), next AS (SELECT COALESCE(MAX(aggregate_sequence),0)+1 AS sequence FROM internal_events, locked WHERE aggregate_type=$1 AND aggregate_id=$2) INSERT INTO internal_events (id,aggregate_type,aggregate_id,aggregate_sequence,event_type,schema_version,payload) SELECT $3,$1,$2,sequence,$4,$5,$6 FROM next RETURNING aggregate_sequence").bind(&input.aggregate_type).bind(input.aggregate_id.as_uuid()).bind(input.id.as_uuid()).bind(&input.event_type).bind(version).bind(&input.payload))?; - u64::try_from( - row.try_get::("aggregate_sequence") - .map_err(|_| DatabaseError::InvalidStoredData)?, - ) - .map_err(|_| DatabaseError::InvalidStoredData) - } -} - impl PasskeyRepository<'_> { pub async fn insert(&mut self, input: &InsertPasskey) -> Result { - let row = fetch_one!(self, sqlx::query("INSERT INTO passkey_credentials (id,credential_id,user_id,credential,backup_eligible,backup_state,friendly_name) VALUES ($1,$2,$3,$4,false,false,$5) RETURNING id,credential_id,user_id,credential,friendly_name,revoked_at").bind(input.id.as_uuid()).bind(&input.credential_id).bind(input.user_id.as_uuid()).bind(&input.credential).bind(&input.friendly_name))?; + let row = fetch_one!(self, sqlx::query("INSERT INTO passkey_credentials (id,credential_id,user_id,credential,friendly_name) VALUES ($1,$2,$3,$4,$5) RETURNING id,credential_id,user_id,credential,friendly_name,revoked_at").bind(input.id.as_uuid()).bind(&input.credential_id).bind(input.user_id.as_uuid()).bind(&input.credential).bind(&input.friendly_name))?; stored_passkey(&row) } @@ -331,13 +278,6 @@ impl PasskeyRepository<'_> { rows.iter().map(stored_passkey).collect() } - pub async fn find_active_by_credential_id( - &mut self, - credential_id: &[u8], - ) -> Result, DatabaseError> { - fetch_optional!(self, sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE credential_id=$1 AND revoked_at IS NULL").bind(credential_id))?.map(|row| stored_passkey(&row)).transpose() - } - pub async fn find_active_by_credential_id_for_update( &mut self, credential_id: &[u8], @@ -406,34 +346,6 @@ impl PasskeyRepository<'_> { .map_err(|_| DatabaseError::InvalidStoredData)?, }) } - - pub async fn insert_purpose_authorization( - &mut self, - input: &InsertPurposeAuthorization, - ) -> Result<(), DatabaseError> { - execute!(self, sqlx::query("INSERT INTO purpose_authorizations(id,user_id,session_id,purpose,expires_at) VALUES($1,$2,$3,$4,$5)").bind(input.id.as_uuid()).bind(input.user_id.as_uuid()).bind(input.session_id.as_uuid()).bind(&input.purpose).bind(input.expires_at))?; - Ok(()) - } - - pub async fn purpose_authorization_is_active( - &mut self, - id: TokenId, - user_id: UserId, - session_id: SessionId, - purpose: &str, - ) -> Result { - Ok(fetch_optional!(self, sqlx::query("SELECT 1 FROM purpose_authorizations p JOIN sessions s ON s.id=p.session_id JOIN users u ON u.id=p.user_id WHERE p.id=$1 AND p.user_id=$2 AND p.session_id=$3 AND p.purpose=$4 AND p.consumed_at IS NULL AND p.expires_at>now() AND s.revoked_at IS NULL AND s.expires_at>now() AND u.status='active'").bind(id.as_uuid()).bind(user_id.as_uuid()).bind(session_id.as_uuid()).bind(purpose))?.is_some()) - } - - pub async fn consume_purpose_authorization( - &mut self, - id: TokenId, - user_id: UserId, - session_id: SessionId, - purpose: &str, - ) -> Result { - Ok(execute!(self, sqlx::query("WITH active_session AS MATERIALIZED (SELECT s.id FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.id=$3 AND s.user_id=$2 AND s.revoked_at IS NULL AND s.expires_at>now() AND u.status='active' FOR UPDATE OF s) UPDATE purpose_authorizations p SET consumed_at=now() FROM active_session s WHERE p.id=$1 AND p.user_id=$2 AND p.session_id=s.id AND p.purpose=$4 AND p.consumed_at IS NULL AND p.expires_at>now()").bind(id.as_uuid()).bind(user_id.as_uuid()).bind(session_id.as_uuid()).bind(purpose))?.rows_affected()==1) - } } fn stored_passkey(row: &sqlx::postgres::PgRow) -> Result { @@ -487,3 +399,8 @@ impl SessionRepository<'_> { fetch_optional!(self, sqlx::query("SELECT s.id,s.user_id,s.authentication_methods,s.authenticated_at,s.expires_at,s.last_seen_at,s.revoked_at FROM browser_session_secrets b JOIN sessions s ON s.id=b.session_id JOIN users u ON u.id=s.user_id WHERE b.secret_digest=$1 AND s.revoked_at IS NULL AND s.expires_at>now() AND u.status='active'").bind(digest))?.map(|row| stored_session(&row)).transpose() } } + +mod federation; +mod oidc; + +mod security; diff --git a/crates/database/src/repositories/federation.rs b/crates/database/src/repositories/federation.rs new file mode 100644 index 000000000..96a28dbb0 --- /dev/null +++ b/crates/database/src/repositories/federation.rs @@ -0,0 +1,181 @@ +use super::*; +use crate::PendingFederation; + +impl FederationRepository<'_> { + pub async fn insert_transaction( + &mut self, + input: &InsertFederationTransaction, + ) -> Result<(), DatabaseError> { + execute!(self,sqlx::query("INSERT INTO federation_transactions(id,provider_name,state_digest,browser_digest,nonce,pkce_verifier,return_to,expires_at,link_user_id,link_session_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)").bind(input.id.as_uuid()).bind(&input.provider).bind(&input.state_digest).bind(&input.browser_digest).bind(&input.nonce).bind(&input.pkce_verifier).bind(&input.return_to).bind(input.expires_at).bind(input.link_user_id.map(UserId::as_uuid)).bind(input.link_session_id.map(SessionId::as_uuid)))?; + Ok(()) + } + pub async fn consume_transaction( + &mut self, + provider: &str, + state_digest: &[u8], + browser_digest: &[u8], + ) -> Result { + let row=fetch_optional!(self,sqlx::query("UPDATE federation_transactions SET consumed_at=now() WHERE provider_name=$1 AND state_digest=$2 AND browser_digest=$3 AND consumed_at IS NULL AND expires_at>now() RETURNING nonce,pkce_verifier,return_to,link_user_id,link_session_id").bind(provider).bind(state_digest).bind(browser_digest))?.ok_or(DatabaseError::NotFound)?; + Ok(ConsumedFederationTransaction { + link_user_id: row + .try_get::, _>("link_user_id") + .map_err(|_| DatabaseError::InvalidStoredData)? + .map(UserId::from_uuid) + .transpose() + .map_err(|_| DatabaseError::InvalidStoredData)?, + link_session_id: row + .try_get::, _>("link_session_id") + .map_err(|_| DatabaseError::InvalidStoredData)? + .map(SessionId::from_uuid) + .transpose() + .map_err(|_| DatabaseError::InvalidStoredData)?, + nonce: row + .try_get("nonce") + .map_err(|_| DatabaseError::InvalidStoredData)?, + pkce_verifier: row + .try_get("pkce_verifier") + .map_err(|_| DatabaseError::InvalidStoredData)?, + return_to: row + .try_get("return_to") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + } + pub async fn find_active( + &mut self, + issuer: &str, + subject: &str, + ) -> Result, DatabaseError> { + fetch_optional!(self,sqlx::query("SELECT id,user_id,provider_name,issuer,subject,linked_email FROM external_login_identities WHERE issuer=$1 AND subject=$2 AND revoked_at IS NULL").bind(issuer).bind(subject))?.map(|row|stored_external_identity(&row)).transpose() + } + pub async fn insert_identity( + &mut self, + input: &InsertExternalIdentity, + ) -> Result { + let row=fetch_one!(self,sqlx::query("INSERT INTO external_login_identities(id,user_id,provider_name,issuer,subject,linked_email) VALUES($1,$2,$3,$4,$5,$6) RETURNING id,user_id,provider_name,issuer,subject,linked_email").bind(input.id.as_uuid()).bind(input.user_id.as_uuid()).bind(&input.provider).bind(&input.issuer).bind(&input.subject).bind(&input.linked_email))?; + stored_external_identity(&row) + } + pub async fn record_login(&mut self, id: TokenId) -> Result<(), DatabaseError> { + execute!(self,sqlx::query("UPDATE external_login_identities SET last_login_at=now() WHERE id=$1 AND revoked_at IS NULL").bind(id.as_uuid()))?; + Ok(()) + } + pub async fn list_active( + &mut self, + user_id: UserId, + ) -> Result, DatabaseError> { + let rows=match &mut self.executor{RepositoryExecutor::Pool(pool)=>sqlx::query("SELECT id,user_id,provider_name,issuer,subject,linked_email FROM external_login_identities WHERE user_id=$1 AND revoked_at IS NULL ORDER BY linked_at").bind(user_id.as_uuid()).fetch_all(*pool).await,RepositoryExecutor::Connection(connection)=>sqlx::query("SELECT id,user_id,provider_name,issuer,subject,linked_email FROM external_login_identities WHERE user_id=$1 AND revoked_at IS NULL ORDER BY linked_at").bind(user_id.as_uuid()).fetch_all(&mut **connection).await}.map_err(Into::::into)?; + rows.iter().map(stored_external_identity).collect() + } +} +fn stored_external_identity( + row: &sqlx::postgres::PgRow, +) -> Result { + Ok(StoredExternalIdentity { + id: TokenId::from_uuid( + row.try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + user_id: UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + provider: row + .try_get("provider_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + issuer: row + .try_get("issuer") + .map_err(|_| DatabaseError::InvalidStoredData)?, + subject: row + .try_get("subject") + .map_err(|_| DatabaseError::InvalidStoredData)?, + linked_email: row + .try_get("linked_email") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} + +impl FederationRepository<'_> { + pub async fn insert_pending(&mut self, input: &PendingFederation) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("INSERT INTO pending_federation(id,browser_digest,provider_name,issuer,subject,email,display_name,return_to,link_user_id,link_session_id,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)") + .bind(input.id.as_uuid()).bind(&input.browser_digest).bind(&input.provider).bind(&input.issuer).bind(&input.subject).bind(&input.email).bind(&input.display_name).bind(&input.return_to).bind(input.link_user_id.map(UserId::as_uuid)).bind(input.link_session_id.map(SessionId::as_uuid)).bind(input.expires_at))?; + Ok(()) + } + pub async fn pending( + &mut self, + digest: &[u8], + ) -> Result, DatabaseError> { + fetch_optional!(self, sqlx::query("SELECT * FROM pending_federation WHERE browser_digest=$1 AND consumed_at IS NULL AND expires_at>now()").bind(digest))?.map(|row| stored_pending(&row)).transpose() + } + /// Consumption participates in the caller's identity/account transaction. + pub async fn consume_pending( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result { + let row = fetch_optional!(self, sqlx::query("UPDATE pending_federation SET consumed_at=now() WHERE id=$1 AND browser_digest=$2 AND consumed_at IS NULL AND expires_at>now() RETURNING *").bind(id.as_uuid()).bind(digest))?.ok_or(DatabaseError::NotFound)?; + stored_pending(&row) + } + pub async fn cancel_pending(&mut self, digest: &[u8]) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("UPDATE pending_federation SET consumed_at=now() WHERE browser_digest=$1 AND consumed_at IS NULL").bind(digest))?; + Ok(()) + } + pub async fn unlink(&mut self, user_id: UserId, provider: &str) -> Result { + Ok(execute!(self, sqlx::query("UPDATE external_login_identities SET revoked_at=now() WHERE user_id=$1 AND provider_name=$2 AND revoked_at IS NULL").bind(user_id.as_uuid()).bind(provider))?.rows_affected()==1) + } + /// Preserve the first verified local email forever; never import conflicting + /// provider observations into another account's email ownership. + pub async fn set_first_email( + &mut self, + user_id: UserId, + email: &str, + ) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("INSERT INTO user_emails(id,user_id,normalized_email,verified_at,is_primary) SELECT $1,$2,$3,now(),true WHERE NOT EXISTS(SELECT 1 FROM user_emails WHERE user_id=$2 AND verified_at IS NOT NULL) AND NOT EXISTS(SELECT 1 FROM active_verified_email_ownership WHERE normalized_email=$3 AND user_id<>$2)").bind(TokenId::new().as_uuid()).bind(user_id.as_uuid()).bind(email))?; + Ok(()) + } +} +fn stored_pending(row: &sqlx::postgres::PgRow) -> Result { + Ok(PendingFederation { + id: TokenId::from_uuid( + row.try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + browser_digest: row + .try_get("browser_digest") + .map_err(|_| DatabaseError::InvalidStoredData)?, + provider: row + .try_get("provider_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + issuer: row + .try_get("issuer") + .map_err(|_| DatabaseError::InvalidStoredData)?, + subject: row + .try_get("subject") + .map_err(|_| DatabaseError::InvalidStoredData)?, + email: row + .try_get("email") + .map_err(|_| DatabaseError::InvalidStoredData)?, + display_name: row + .try_get("display_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + return_to: row + .try_get("return_to") + .map_err(|_| DatabaseError::InvalidStoredData)?, + link_user_id: row + .try_get::, _>("link_user_id") + .map_err(|_| DatabaseError::InvalidStoredData)? + .map(UserId::from_uuid) + .transpose() + .map_err(|_| DatabaseError::InvalidStoredData)?, + link_session_id: row + .try_get::, _>("link_session_id") + .map_err(|_| DatabaseError::InvalidStoredData)? + .map(SessionId::from_uuid) + .transpose() + .map_err(|_| DatabaseError::InvalidStoredData)?, + expires_at: row + .try_get("expires_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} diff --git a/crates/database/src/repositories/oidc.rs b/crates/database/src/repositories/oidc.rs new file mode 100644 index 000000000..530c641b3 --- /dev/null +++ b/crates/database/src/repositories/oidc.rs @@ -0,0 +1,401 @@ +use super::*; + +impl OidcRepository<'_> { + /// Used inside the startup provisioning transaction so removed clients fail closed. + pub async fn disable_all_clients(&mut self) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("UPDATE oidc_clients SET enabled=FALSE"))?; + Ok(()) + } + + /// Idempotently provisions a statically reviewed client and exact URI allowlists. + pub async fn bootstrap_client( + &mut self, + input: &BootstrapOidcClient, + ) -> Result<(), DatabaseError> { + validate_bootstrap_client(input)?; + let scopes = + serde_json::to_value(&input.allowed_scopes).map_err(|_| DatabaseError::Internal)?; + let audiences = + serde_json::to_value(&input.allowed_audiences).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("WITH upsert AS (INSERT INTO oidc_clients(id,display_name,allowed_scopes,allowed_audiences,allow_refresh,enabled,trusted,client_secret_hash) VALUES($1,$2,$3,$4,$5,$8,$9,$10) ON CONFLICT(id) DO UPDATE SET display_name=EXCLUDED.display_name,allowed_scopes=EXCLUDED.allowed_scopes,allowed_audiences=EXCLUDED.allowed_audiences,allow_refresh=EXCLUDED.allow_refresh,enabled=EXCLUDED.enabled,trusted=EXCLUDED.trusted,client_secret_hash=EXCLUDED.client_secret_hash RETURNING id), desired(uri,kind) AS (SELECT unnest($6::text[]),'authorization' UNION ALL SELECT unnest($7::text[]),'post_logout'), inserted AS (INSERT INTO oidc_redirect_uris(client_id,uri,kind) SELECT $1,d.uri,d.kind FROM desired d,upsert ON CONFLICT DO NOTHING RETURNING uri), removed AS (DELETE FROM oidc_redirect_uris r WHERE r.client_id=$1 AND NOT EXISTS (SELECT 1 FROM desired d WHERE d.uri=r.uri AND d.kind=r.kind) RETURNING uri) SELECT id FROM upsert") + .bind(&input.id).bind(&input.display_name).bind(scopes).bind(audiences).bind(input.allow_refresh).bind(&input.redirect_uris).bind(&input.post_logout_uris).bind(input.enabled).bind(input.trusted).bind(&input.client_secret_hash))?; + Ok(()) + } + + pub async fn find_client( + &mut self, + id: &str, + ) -> Result, DatabaseError> { + let row = fetch_optional!(self, sqlx::query("SELECT c.id,c.display_name,c.enabled,c.allowed_scopes,c.allowed_audiences,c.allow_refresh,c.trusted,c.client_secret_hash,COALESCE(jsonb_agg(r.uri) FILTER (WHERE r.kind='authorization'),'[]'::jsonb) AS redirect_uris,COALESCE(jsonb_agg(r.uri) FILTER (WHERE r.kind='post_logout'),'[]'::jsonb) AS post_logout_uris FROM oidc_clients c LEFT JOIN oidc_redirect_uris r ON r.client_id=c.id WHERE c.id=$1 GROUP BY c.id").bind(id))?; + row.map(|row| { + let strings = |column| -> Result, DatabaseError> { + serde_json::from_value( + row.try_get(column) + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData) + }; + Ok(StoredOidcClient { + id: row + .try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + display_name: row + .try_get("display_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + enabled: row + .try_get("enabled") + .map_err(|_| DatabaseError::InvalidStoredData)?, + trusted: row + .try_get("trusted") + .map_err(|_| DatabaseError::InvalidStoredData)?, + client_secret_hash: row + .try_get("client_secret_hash") + .map_err(|_| DatabaseError::InvalidStoredData)?, + redirect_uris: strings("redirect_uris")?, + post_logout_uris: strings("post_logout_uris")?, + allowed_scopes: strings("allowed_scopes")?, + allowed_audiences: strings("allowed_audiences")?, + allow_refresh: row + .try_get("allow_refresh") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + }) + .transpose() + } + + pub async fn insert_code( + &mut self, + input: &InsertAuthorizationCode, + ) -> Result<(), DatabaseError> { + let scopes = serde_json::to_value(&input.scopes).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("INSERT INTO authorization_codes(id,secret_digest,client_id,user_id,session_id,redirect_uri,pkce_challenge,nonce,scopes,audience,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)") + .bind(input.id.as_uuid()).bind(&input.secret_digest).bind(&input.client_id) + .bind(input.user_id.as_uuid()).bind(input.session_id.as_uuid()).bind(&input.redirect_uri) + .bind(&input.pkce_challenge).bind(&input.nonce).bind(scopes).bind(&input.audience).bind(input.expires_at))?; + Ok(()) + } + + pub async fn insert_authorization_request( + &mut self, + input: &InsertAuthorizationRequest, + ) -> Result<(), DatabaseError> { + let scopes = serde_json::to_value(&input.scopes).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("INSERT INTO authorization_requests(id,secret_digest,client_id,redirect_uri,client_state,nonce,pkce_challenge,scopes,audience,force_login,max_age,expires_at,force_consent) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)") + .bind(input.id.as_uuid()).bind(&input.secret_digest).bind(&input.client_id) + .bind(&input.redirect_uri).bind(&input.client_state).bind(&input.nonce) + .bind(&input.pkce_challenge).bind(scopes).bind(&input.audience) + .bind(input.force_login).bind(input.max_age).bind(input.expires_at).bind(input.force_consent))?; + Ok(()) + } + + pub async fn find_authorization_request( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result, DatabaseError> { + fetch_optional!(self, sqlx::query("SELECT r.id,r.client_id,c.display_name AS client_display_name,r.redirect_uri,r.client_state,r.nonce,r.pkce_challenge,r.scopes,r.audience,r.force_login,r.force_consent,r.max_age,r.created_at FROM authorization_requests r JOIN oidc_clients c ON c.id=r.client_id WHERE r.id=$1 AND r.secret_digest=$2 AND r.consumed_at IS NULL AND r.expires_at>now() AND c.enabled").bind(id.as_uuid()).bind(digest))?.map(|row| stored_authorization_request(&row)).transpose() + } + + pub async fn consume_authorization_request( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result { + let row = fetch_optional!(self, sqlx::query("UPDATE authorization_requests r SET consumed_at=now() FROM oidc_clients c WHERE r.id=$1 AND r.secret_digest=$2 AND r.consumed_at IS NULL AND r.expires_at>now() AND c.id=r.client_id AND c.enabled AND c.allowed_scopes @> r.scopes AND c.allowed_audiences ? r.audience AND EXISTS(SELECT 1 FROM oidc_redirect_uris d WHERE d.client_id=c.id AND d.kind='authorization' AND d.uri=r.redirect_uri) RETURNING r.id,r.client_id,c.display_name AS client_display_name,r.redirect_uri,r.client_state,r.nonce,r.pkce_challenge,r.scopes,r.audience,r.force_login,r.force_consent,r.max_age,r.created_at").bind(id.as_uuid()).bind(digest))?.ok_or(DatabaseError::NotFound)?; + stored_authorization_request(&row) + } + + pub async fn consume_code( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result { + let row = fetch_optional!(self, sqlx::query("UPDATE authorization_codes c SET consumed_at=now() FROM oidc_clients cl,sessions s,users u WHERE c.id=$1 AND c.secret_digest=$2 AND c.consumed_at IS NULL AND c.expires_at>now() AND cl.id=c.client_id AND cl.enabled AND cl.allowed_scopes @> c.scopes AND cl.allowed_audiences ? c.audience AND EXISTS(SELECT 1 FROM oidc_redirect_uris d WHERE d.client_id=cl.id AND d.kind='authorization' AND d.uri=c.redirect_uri) AND s.id=c.session_id AND s.revoked_at IS NULL AND s.expires_at>now() AND u.id=c.user_id AND u.status='active' RETURNING c.client_id,c.user_id,c.session_id,c.redirect_uri,c.pkce_challenge,c.nonce,c.scopes,c.audience").bind(id.as_uuid()).bind(digest))?.ok_or(DatabaseError::NotFound)?; + Ok(ConsumedAuthorizationCode { + client_id: row + .try_get("client_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + user_id: UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + session_id: SessionId::from_uuid( + row.try_get("session_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + redirect_uri: row + .try_get("redirect_uri") + .map_err(|_| DatabaseError::InvalidStoredData)?, + pkce_challenge: row + .try_get("pkce_challenge") + .map_err(|_| DatabaseError::InvalidStoredData)?, + nonce: row + .try_get("nonce") + .map_err(|_| DatabaseError::InvalidStoredData)?, + scopes: serde_json::from_value( + row.try_get("scopes") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + audience: row + .try_get("audience") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + } +} + +fn validate_bootstrap_client(input: &BootstrapOidcClient) -> Result<(), DatabaseError> { + let identifier = |value: &str| { + (1..=64).contains(&value.len()) + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }; + let redirect = |value: &str| { + url::Url::parse(value).is_ok_and(|url| { + (url.scheme() == "https" + || (url.scheme() == "http" + && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")))) + && url.host_str().is_some() + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() + }) + }; + let valid = input + .client_secret_hash + .as_ref() + .is_none_or(|hash| hash.len() == 32) + && identifier(&input.id) + && !input.display_name.trim().is_empty() + && input.display_name.chars().count() <= 80 + && !input.redirect_uris.is_empty() + && input.redirect_uris.len() <= 16 + && input.post_logout_uris.len() <= 16 + && input.redirect_uris.iter().all(|uri| redirect(uri)) + && input.post_logout_uris.iter().all(|uri| redirect(uri)) + && !input.allowed_scopes.is_empty() + && input.allowed_scopes.len() <= 32 + && input.allowed_scopes.iter().all(|scope| identifier(scope)) + && !input.allowed_audiences.is_empty() + && input.allowed_audiences.len() <= 16 + && input + .allowed_audiences + .iter() + .all(|audience| identifier(audience)); + valid.then_some(()).ok_or(DatabaseError::Conflict) +} + +fn stored_authorization_request( + row: &sqlx::postgres::PgRow, +) -> Result { + Ok(StoredAuthorizationRequest { + id: TokenId::from_uuid( + row.try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + client_id: row + .try_get("client_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + client_display_name: row + .try_get("client_display_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + redirect_uri: row + .try_get("redirect_uri") + .map_err(|_| DatabaseError::InvalidStoredData)?, + client_state: row + .try_get("client_state") + .map_err(|_| DatabaseError::InvalidStoredData)?, + nonce: row + .try_get("nonce") + .map_err(|_| DatabaseError::InvalidStoredData)?, + pkce_challenge: row + .try_get("pkce_challenge") + .map_err(|_| DatabaseError::InvalidStoredData)?, + scopes: serde_json::from_value( + row.try_get("scopes") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + audience: row + .try_get("audience") + .map_err(|_| DatabaseError::InvalidStoredData)?, + force_consent: row + .try_get("force_consent") + .map_err(|_| DatabaseError::InvalidStoredData)?, + force_login: row + .try_get("force_login") + .map_err(|_| DatabaseError::InvalidStoredData)?, + max_age: row + .try_get("max_age") + .map_err(|_| DatabaseError::InvalidStoredData)?, + created_at: row + .try_get("created_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} + +impl TokenRepository<'_> { + pub async fn insert_family( + &mut self, + family: &InsertRefreshFamily, + token: &InsertRefreshToken, + ) -> Result<(), DatabaseError> { + let scopes = serde_json::to_value(&family.scopes).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("INSERT INTO refresh_token_families(id,user_id,client_id,session_id,audience,scopes) VALUES($1,$2,$3,$4,$5,$6)") + .bind(family.id.as_uuid()).bind(family.user_id.as_uuid()).bind(&family.client_id) + .bind(family.session_id.as_uuid()).bind(&family.audience).bind(scopes))?; + self.insert_token(token).await + } + + pub async fn insert_token(&mut self, token: &InsertRefreshToken) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("INSERT INTO refresh_tokens(id,family_id,secret_digest,expires_at) VALUES($1,$2,$3,$4)") + .bind(token.id.as_uuid()).bind(token.family_id.as_uuid()).bind(&token.secret_digest).bind(token.expires_at))?; + Ok(()) + } + + pub async fn consume_for_rotation( + &mut self, + id: TokenId, + digest: &[u8], + client: &str, + ) -> Result { + let row = fetch_optional!(self, sqlx::query("SELECT t.family_id,t.consumed_at,f.user_id,f.client_id,f.session_id,f.audience,f.scopes,c.allow_refresh,c.allowed_scopes,c.allowed_audiences FROM refresh_tokens t JOIN refresh_token_families f ON f.id=t.family_id JOIN oidc_clients c ON c.id=f.client_id JOIN sessions s ON s.id=f.session_id JOIN users u ON u.id=f.user_id WHERE t.id=$1 AND t.secret_digest=$2 AND f.client_id=$3 AND t.expires_at>now() AND f.revoked_at IS NULL AND c.enabled AND s.revoked_at IS NULL AND s.expires_at>now() AND u.status='active' FOR UPDATE OF t,f,c,s,u").bind(id.as_uuid()).bind(digest).bind(client)).map_err(RefreshRotationError::database)?.ok_or(RefreshRotationError::Invalid)?; + let family_uuid: uuid::Uuid = row + .try_get("family_id") + .map_err(RefreshRotationError::database)?; + let user_id = UserId::from_uuid( + row.try_get("user_id") + .map_err(RefreshRotationError::database)?, + ) + .map_err(RefreshRotationError::database)?; + if row + .try_get::>, _>("consumed_at") + .map_err(RefreshRotationError::database)? + .is_some() + { + execute!(self, sqlx::query("UPDATE refresh_token_families SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL").bind(family_uuid)).map_err(RefreshRotationError::database)?; + return Err(RefreshRotationError::Replay { user_id }); + } + let family_scopes: Vec = serde_json::from_value( + row.try_get("scopes") + .map_err(RefreshRotationError::database)?, + ) + .map_err(RefreshRotationError::database)?; + let allowed_scopes: Vec = serde_json::from_value( + row.try_get("allowed_scopes") + .map_err(RefreshRotationError::database)?, + ) + .map_err(RefreshRotationError::database)?; + let allowed_audiences: Vec = serde_json::from_value( + row.try_get("allowed_audiences") + .map_err(RefreshRotationError::database)?, + ) + .map_err(RefreshRotationError::database)?; + let audience: String = row + .try_get("audience") + .map_err(RefreshRotationError::database)?; + let policy_valid = row + .try_get::("allow_refresh") + .map_err(RefreshRotationError::database)? + && allowed_audiences.contains(&audience) + && family_scopes + .iter() + .all(|scope| allowed_scopes.contains(scope)); + if !policy_valid { + execute!(self, sqlx::query("UPDATE refresh_token_families SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL").bind(family_uuid)).map_err(RefreshRotationError::database)?; + return Err(RefreshRotationError::Policy { user_id }); + } + if execute!( + self, + sqlx::query( + "UPDATE refresh_tokens SET consumed_at=now() WHERE id=$1 AND consumed_at IS NULL" + ) + .bind(id.as_uuid()) + ) + .map_err(RefreshRotationError::database)? + .rows_affected() + != 1 + { + return Err(RefreshRotationError::Invalid); + } + Ok(RotatedRefreshToken { + family_id: TokenId::from_uuid(family_uuid).map_err(RefreshRotationError::database)?, + user_id, + client_id: row + .try_get("client_id") + .map_err(RefreshRotationError::database)?, + session_id: SessionId::from_uuid( + row.try_get("session_id") + .map_err(RefreshRotationError::database)?, + ) + .map_err(RefreshRotationError::database)?, + audience, + scopes: family_scopes, + }) + } + + pub async fn revoke_family_for_token( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("UPDATE refresh_token_families f SET revoked_at=COALESCE(revoked_at,now()) FROM refresh_tokens t WHERE t.id=$1 AND t.secret_digest=$2 AND t.family_id=f.id").bind(id.as_uuid()).bind(digest))?; + Ok(()) + } + + pub async fn revoke_all_for_user(&mut self, user_id: UserId) -> Result { + Ok(execute!(self, sqlx::query("UPDATE refresh_token_families SET revoked_at=now() WHERE user_id=$1 AND revoked_at IS NULL").bind(user_id.as_uuid()))?.rows_affected()) + } +} + +impl OidcRepository<'_> { + pub async fn consented( + &mut self, + user: UserId, + client: &str, + audience: &str, + scopes: &[String], + ) -> Result { + let scopes = serde_json::to_value(scopes).map_err(|_| DatabaseError::Internal)?; + Ok(fetch_optional!(self, sqlx::query("SELECT 1 FROM oidc_consents WHERE user_id=$1 AND client_id=$2 AND audience=$3 AND scopes @> $4").bind(user.as_uuid()).bind(client).bind(audience).bind(scopes))?.is_some()) + } + pub async fn save_consent( + &mut self, + user: UserId, + client: &str, + audience: &str, + scopes: &[String], + ) -> Result<(), DatabaseError> { + let scopes = serde_json::to_value(scopes).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("INSERT INTO oidc_consents(user_id,client_id,audience,scopes) VALUES($1,$2,$3,$4) ON CONFLICT(user_id,client_id,audience) DO UPDATE SET scopes=(SELECT jsonb_agg(DISTINCT value) FROM jsonb_array_elements(oidc_consents.scopes || EXCLUDED.scopes))").bind(user.as_uuid()).bind(client).bind(audience).bind(scopes))?; + Ok(()) + } + pub async fn primary_email(&mut self, user: UserId) -> Result, DatabaseError> { + fetch_optional!(self,sqlx::query("SELECT normalized_email FROM user_emails WHERE user_id=$1 AND verified_at IS NOT NULL ORDER BY is_primary DESC,created_at LIMIT 1").bind(user.as_uuid()))?.map(|row| row.try_get("normalized_email").map_err(|_| DatabaseError::InvalidStoredData)).transpose() + } + pub async fn revoke_session(&mut self, session: SessionId) -> Result<(), DatabaseError> { + execute!( + self, + sqlx::query("UPDATE sessions SET revoked_at=COALESCE(revoked_at,now()) WHERE id=$1") + .bind(session.as_uuid()) + )?; + execute!(self,sqlx::query("UPDATE refresh_token_families SET revoked_at=COALESCE(revoked_at,now()) WHERE session_id=$1").bind(session.as_uuid()))?; + Ok(()) + } +} + +impl TokenRepository<'_> { + pub async fn revoke_family_for_client_token( + &mut self, + id: TokenId, + digest: &[u8], + client: &str, + ) -> Result<(), DatabaseError> { + execute!(self,sqlx::query("UPDATE refresh_token_families f SET revoked_at=COALESCE(revoked_at,now()) FROM refresh_tokens t WHERE t.id=$1 AND t.secret_digest=$2 AND t.family_id=f.id AND f.client_id=$3").bind(id.as_uuid()).bind(digest).bind(client))?; + Ok(()) + } +} diff --git a/crates/database/src/repositories/security.rs b/crates/database/src/repositories/security.rs new file mode 100644 index 000000000..7a5a049ee --- /dev/null +++ b/crates/database/src/repositories/security.rs @@ -0,0 +1,70 @@ +use super::*; +use chrono::{DateTime, Utc}; + +impl SessionRepository<'_> { + /// Locks the session during a transaction so logout cannot race a settings change. + pub async fn management_active(&mut self, id: SessionId) -> Result { + Ok(fetch_optional!(self, sqlx::query("SELECT s.id FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.id=$1 AND s.revoked_at IS NULL AND s.expires_at>clock_timestamp() AND s.management_expires_at>clock_timestamp() AND u.status='active' FOR UPDATE OF s").bind(id.as_uuid()))?.is_some()) + } + + pub async fn management_expiry( + &mut self, + id: SessionId, + ) -> Result>, DatabaseError> { + let row = fetch_optional!(self, sqlx::query("SELECT management_expires_at FROM sessions WHERE id=$1 AND revoked_at IS NULL AND expires_at>now() AND management_expires_at>now()").bind(id.as_uuid()))?; + row.map(|row| row.try_get("management_expires_at").map_err(Into::into)) + .transpose() + .map(Option::flatten) + } + + pub async fn grant_management( + &mut self, + id: SessionId, + ) -> Result, DatabaseError> { + let row = fetch_one!(self, sqlx::query("UPDATE sessions SET management_expires_at=LEAST(expires_at,clock_timestamp()+interval '2 minutes') WHERE id=$1 AND revoked_at IS NULL AND expires_at>clock_timestamp() RETURNING management_expires_at").bind(id.as_uuid()))?; + row.try_get("management_expires_at").map_err(Into::into) + } + + pub async fn revoke_other( + &mut self, + user_id: UserId, + except_session: SessionId, + ) -> Result { + Ok(execute!(self, sqlx::query("UPDATE sessions SET revoked_at=now(),management_expires_at=NULL WHERE user_id=$1 AND id<>$2 AND revoked_at IS NULL").bind(user_id.as_uuid()).bind(except_session.as_uuid()))?.rows_affected()) + } +} + +impl SecurityRepository<'_> { + pub async fn create_invitation( + &mut self, + digest: &[u8], + expires_at: DateTime, + ) -> Result<(), DatabaseError> { + execute!( + self, + sqlx::query("INSERT INTO invitations(secret_digest,expires_at) VALUES($1,$2)") + .bind(digest) + .bind(expires_at) + )?; + Ok(()) + } + + pub async fn invitation_active(&mut self, digest: &[u8]) -> Result { + Ok(fetch_optional!(self, sqlx::query("SELECT 1 FROM invitations WHERE secret_digest=$1 AND redeemed_at IS NULL AND expires_at>now()").bind(digest))?.is_some()) + } + + /// Redeems an invitation inside the account-creation transaction. + pub async fn redeem_invitation(&mut self, digest: &[u8]) -> Result { + Ok(execute!(self, sqlx::query("UPDATE invitations SET redeemed_at=clock_timestamp() WHERE secret_digest=$1 AND redeemed_at IS NULL AND expires_at>clock_timestamp()").bind(digest))?.rows_affected()==1) + } + + /// A database-backed fixed window shared by all service processes. + pub async fn allow_request( + &mut self, + bucket: &[u8], + limit: i32, + ) -> Result { + let row = fetch_one!(self, sqlx::query("INSERT INTO request_limits(bucket,requests,expires_at) VALUES($1,1,now()+interval '1 minute') ON CONFLICT(bucket) DO UPDATE SET requests=CASE WHEN request_limits.expires_at<=now() THEN 1 ELSE request_limits.requests+1 END, expires_at=CASE WHEN request_limits.expires_at<=now() THEN now()+interval '1 minute' ELSE request_limits.expires_at END RETURNING requests").bind(bucket))?; + Ok(row.try_get::("requests")? <= limit) + } +} diff --git a/crates/database/src/transaction.rs b/crates/database/src/transaction.rs index f23be5d28..036f33d41 100644 --- a/crates/database/src/transaction.rs +++ b/crates/database/src/transaction.rs @@ -21,9 +21,6 @@ impl<'a> DatabaseTransaction<'a> { pub fn audit_events(&mut self) -> AuditEventRepository<'_> { AuditEventRepository::from_connection(&mut self.inner) } - pub fn internal_events(&mut self) -> InternalEventRepository<'_> { - InternalEventRepository::from_connection(&mut self.inner) - } pub fn passkeys(&mut self) -> PasskeyRepository<'_> { PasskeyRepository::from_connection(&mut self.inner) } @@ -36,8 +33,8 @@ impl<'a> DatabaseTransaction<'a> { pub fn federation(&mut self) -> FederationRepository<'_> { FederationRepository::from_connection(&mut self.inner) } - pub fn service_identities(&mut self) -> ServiceIdentityRepository<'_> { - ServiceIdentityRepository::from_connection(&mut self.inner) + pub fn security(&mut self) -> SecurityRepository<'_> { + SecurityRepository::from_connection(&mut self.inner) } pub async fn commit(self) -> Result<(), DatabaseError> { self.inner.commit().await.map_err(Into::into) diff --git a/crates/database/tests/Dockerfile b/crates/database/tests/Dockerfile deleted file mode 100644 index 031f7b09b..000000000 --- a/crates/database/tests/Dockerfile +++ /dev/null @@ -1,4 +0,0 @@ -FROM rust:1.97 -WORKDIR /workspace -COPY . . -CMD ["cargo", "test", "-p", "piquel-repository", "--test", "identity", "--", "--ignored", "--test-threads=1", "--nocapture"] diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs deleted file mode 100644 index c5e4a76d7..000000000 --- a/crates/database/tests/identity.rs +++ /dev/null @@ -1,547 +0,0 @@ -#![allow(missing_docs)] - -use chrono::{Duration as ChronoDuration, Utc}; -use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; -use piquel_repository::{ - AppendInternalEvent, Database, DatabaseConfig, DatabaseError, InsertCeremony, InsertPasskey, - InsertPurposeAuthorization, InsertSession, InsertUser, InsertVerifiedEmail, UpdateUserProfile, -}; -use std::{env, time::Duration}; - -async fn database() -> Database { - let url = env::var("TEST_DATABASE_URL") - .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - let config = DatabaseConfig::new_development(url, 10, Duration::from_secs(5)) - .expect("test database configuration"); - let database = Database::connect(config) - .await - .expect("connect test database"); - database.run_migrations().await.expect("run migrations"); - database -} - -async fn insert_user(database: &Database, prefix: &str) -> UserId { - let id = UserId::new(); - let identifier = id.to_string(); - let username = format!("{prefix}_{}", &identifier[identifier.len() - 12..]); - database - .users() - .insert(&InsertUser { - id, - username: username.clone(), - display_name: username, - }) - .await - .expect("insert user"); - id -} - -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -#[allow(clippy::too_many_lines)] -async fn identity_transactions_and_concurrency_hold() { - let database = database().await; - - let rolled_back = UserId::new(); - let mut transaction = database.begin().await.expect("begin"); - transaction - .users() - .insert(&InsertUser { - id: rolled_back, - username: format!("rollback_{}", &rolled_back.to_string()[..8]), - display_name: "Rolled Back".into(), - }) - .await - .expect("insert"); - transaction - .internal_events() - .append(&AppendInternalEvent { - id: TokenId::new(), - aggregate_type: "user".into(), - aggregate_id: rolled_back, - event_type: "account.created".into(), - schema_version: 1, - payload: serde_json::json!({}), - }) - .await - .expect("event"); - transaction.rollback().await.expect("rollback"); - assert!( - database - .users() - .find_by_id(rolled_back) - .await - .expect("lookup") - .is_none() - ); - - let invalid_primary = UserId::new(); - let mut transaction = database.begin().await.expect("begin invalid account"); - transaction - .users() - .insert(&InsertUser { - id: invalid_primary, - username: format!("invalid_{}", &invalid_primary.to_string()[..8]), - display_name: "Invalid Primary".into(), - }) - .await - .expect("insert account"); - transaction - .emails() - .insert_verified(&InsertVerifiedEmail { - id: TokenId::new(), - user_id: invalid_primary, - normalized_email: format!("invalid-{invalid_primary}@example.com"), - is_primary: false, - verified_at: Utc::now(), - }) - .await - .expect("insert until deferred check"); - assert!(transaction.commit().await.is_err()); - assert!( - database - .users() - .find_by_id(invalid_primary) - .await - .expect("lookup invalid account") - .is_none() - ); - - let first = insert_user(&database, "first").await; - let second = insert_user(&database, "second").await; - - database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: TokenId::new(), - user_id: None, - session_id: None, - kind: "registration".into(), - challenge_digest: vec![2; 32], - state: serde_json::json!({"bootstrap":true}), - expires_at: Utc::now() + ChronoDuration::minutes(5), - }) - .await - .expect("bootstrap ceremony before user creation"); - database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: TokenId::new(), - user_id: Some(first), - session_id: None, - kind: "enrollment".into(), - challenge_digest: vec![3; 32], - state: serde_json::json!({"enrollment":true}), - expires_at: Utc::now() + ChronoDuration::minutes(5), - }) - .await - .expect("enrollment ceremony"); - database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: TokenId::new(), - user_id: Some(first), - session_id: None, - kind: "purpose_authentication".into(), - challenge_digest: vec![4; 32], - state: serde_json::json!({"purpose":true}), - expires_at: Utc::now() + ChronoDuration::minutes(5), - }) - .await - .expect("purpose authentication ceremony"); - - let ceremony_id = TokenId::new(); - database - .passkeys() - .insert_ceremony(&InsertCeremony { - id: ceremony_id, - user_id: Some(first), - session_id: None, - kind: "authentication".into(), - challenge_digest: vec![1; 32], - state: serde_json::json!({"test":true}), - expires_at: Utc::now() + ChronoDuration::minutes(5), - }) - .await - .expect("ceremony"); - let one = database.clone(); - let two = database.clone(); - let (left, right) = tokio::join!( - async move { - one.passkeys() - .consume_ceremony(ceremony_id, "authentication") - .await - }, - async move { - two.passkeys() - .consume_ceremony(ceremony_id, "authentication") - .await - } - ); - assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); - - let credential_id = vec![7_u8; 32]; - database - .passkeys() - .insert(&InsertPasskey { - id: TokenId::new(), - credential_id: credential_id.clone(), - user_id: first, - credential: serde_json::json!({"fixture":true}), - friendly_name: "First".into(), - }) - .await - .expect("passkey"); - assert!(matches!( - database - .passkeys() - .insert(&InsertPasskey { - id: TokenId::new(), - credential_id, - user_id: second, - credential: serde_json::json!({"fixture":true}), - friendly_name: "Duplicate".into() - }) - .await, - Err(DatabaseError::Conflict) - )); - - for suffix in 0_u8..20 { - let mut additional_credential_id = vec![suffix; 32]; - additional_credential_id.push(42); - database - .passkeys() - .insert(&InsertPasskey { - id: TokenId::new(), - credential_id: additional_credential_id, - user_id: first, - credential: serde_json::json!({"fixture":true}), - friendly_name: format!("Additional {suffix}"), - }) - .await - .expect("additional passkey"); - } - assert_eq!( - database - .passkeys() - .list_active(first) - .await - .expect("list every passkey") - .len(), - 21 - ); - - let normalized = format!("race-{}@example.com", UserId::new()); - let one = database.clone(); - let two = database.clone(); - let first_claim = InsertVerifiedEmail { - id: TokenId::new(), - user_id: first, - normalized_email: normalized.clone(), - is_primary: true, - verified_at: Utc::now(), - }; - let second_claim = InsertVerifiedEmail { - id: TokenId::new(), - user_id: second, - normalized_email: normalized, - is_primary: true, - verified_at: Utc::now(), - }; - let (left, right) = tokio::join!( - async move { - let mut tx = one.begin().await?; - tx.emails().insert_verified(&first_claim).await?; - tx.commit().await - }, - async move { - let mut tx = two.begin().await?; - tx.emails().insert_verified(&second_claim).await?; - tx.commit().await - } - ); - assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); - - let profile = database - .users() - .find_by_id(first) - .await - .expect("lookup") - .expect("user"); - database - .users() - .update_profile(&UpdateUserProfile { - id: first, - expected_version: profile.profile_version, - username: profile.username.clone(), - display_name: "Updated".into(), - }) - .await - .expect("first update"); - assert!(matches!( - database - .users() - .update_profile(&UpdateUserProfile { - id: first, - expected_version: profile.profile_version, - username: profile.username, - display_name: "Stale".into() - }) - .await, - Err(DatabaseError::Conflict) - )); - - let session_id = SessionId::new(); - database - .sessions() - .insert(&InsertSession { - id: session_id, - user_id: first, - authentication_methods: vec![AuthenticationMethod::Passkey], - authenticated_at: Utc::now(), - expires_at: Utc::now() + ChronoDuration::hours(1), - user_agent_family: None, - }) - .await - .expect("session"); - let purpose_id = TokenId::new(); - database - .passkeys() - .insert_purpose_authorization(&InsertPurposeAuthorization { - id: purpose_id, - user_id: first, - session_id, - purpose: "manage-passkeys".into(), - expires_at: Utc::now() + ChronoDuration::minutes(2), - }) - .await - .expect("purpose authorization"); - assert!( - database - .passkeys() - .purpose_authorization_is_active(purpose_id, first, session_id, "manage-passkeys") - .await - .expect("active purpose authorization") - ); - let one = database.clone(); - let two = database.clone(); - let (left, right) = tokio::join!( - async move { - one.passkeys() - .consume_purpose_authorization(purpose_id, first, session_id, "manage-passkeys") - .await - }, - async move { - two.passkeys() - .consume_purpose_authorization(purpose_id, first, session_id, "manage-passkeys") - .await - } - ); - assert_eq!( - usize::from(matches!(left, Ok(true))) + usize::from(matches!(right, Ok(true))), - 1 - ); - let revoked_purpose_id = TokenId::new(); - database - .passkeys() - .insert_purpose_authorization(&InsertPurposeAuthorization { - id: revoked_purpose_id, - user_id: first, - session_id, - purpose: "manage-passkeys".into(), - expires_at: Utc::now() + ChronoDuration::minutes(2), - }) - .await - .expect("purpose authorization invalidated by logout"); - assert!( - database - .sessions() - .revoke(session_id) - .await - .expect("revoke") - ); - assert!( - !database - .sessions() - .revoke(session_id) - .await - .expect("idempotent revoke") - ); - assert!( - !database - .passkeys() - .purpose_authorization_is_active( - revoked_purpose_id, - first, - session_id, - "manage-passkeys" - ) - .await - .expect("revoked-session purpose lookup") - ); - assert!( - !database - .passkeys() - .consume_purpose_authorization(revoked_purpose_id, first, session_id, "manage-passkeys") - .await - .expect("revoked-session purpose consumption") - ); - - let event = |kind: &str| AppendInternalEvent { - id: TokenId::new(), - aggregate_type: "user".into(), - aggregate_id: first, - event_type: kind.into(), - schema_version: 1, - payload: serde_json::json!({}), - }; - let sequence_one = database - .internal_events() - .append(&event("profile.updated")) - .await - .expect("event one"); - let sequence_two = database - .internal_events() - .append(&event("profile.updated")) - .await - .expect("event two"); - assert_eq!((sequence_one, sequence_two), (1, 2)); - - let disabled_one = insert_user(&database, "disabled_a").await; - let disabled_two = insert_user(&database, "disabled_b").await; - database - .users() - .set_status(disabled_one, AccountStatus::Disabled) - .await - .expect("disable"); - database - .users() - .set_status(disabled_two, AccountStatus::Disabled) - .await - .expect("disable"); - let shared = format!("disabled-{}@example.com", UserId::new()); - database - .emails() - .insert_verified(&InsertVerifiedEmail { - id: TokenId::new(), - user_id: disabled_one, - normalized_email: shared.clone(), - is_primary: true, - verified_at: Utc::now(), - }) - .await - .expect("email one"); - database - .emails() - .insert_verified(&InsertVerifiedEmail { - id: TokenId::new(), - user_id: disabled_two, - normalized_email: shared, - is_primary: true, - verified_at: Utc::now(), - }) - .await - .expect("email two"); - let one = database.clone(); - let two = database.clone(); - let (left, right) = tokio::join!( - async move { - one.users() - .set_status(disabled_one, AccountStatus::Active) - .await - }, - async move { - two.users() - .set_status(disabled_two, AccountStatus::Active) - .await - } - ); - assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); - - // Verified-email insertion and disablement must serialize on the user row. - // Regardless of which operation wins, lookup must never expose a disabled - // account through stale ownership state. - for _ in 0..20 { - let user = insert_user(&database, "disable_email_race").await; - let normalized = format!("disable-race-{user}@example.com"); - database - .emails() - .insert_verified(&InsertVerifiedEmail { - id: TokenId::new(), - user_id: user, - normalized_email: normalized.clone(), - is_primary: true, - verified_at: Utc::now(), - }) - .await - .expect("initial email"); - let one = database.clone(); - let two = database.clone(); - let concurrent_email = InsertVerifiedEmail { - id: TokenId::new(), - user_id: user, - normalized_email: normalized.clone(), - is_primary: false, - verified_at: Utc::now(), - }; - let (disabled, inserted) = tokio::join!( - async move { one.users().set_status(user, AccountStatus::Disabled).await }, - async move { two.emails().insert_verified(&concurrent_email).await } - ); - assert!(disabled.expect("disable race")); - inserted.expect("concurrent email"); - assert!( - database - .emails() - .find_active_verified(&normalized) - .await - .expect("active email lookup") - .is_none() - ); - } - - // Updating user_id affects both sides of the deferred primary-email - // invariant. A transfer must not strand the source with no primary. - let source = insert_user(&database, "transfer_source").await; - let destination = insert_user(&database, "transfer_destination").await; - let primary_id = TokenId::new(); - database - .emails() - .insert_verified(&InsertVerifiedEmail { - id: primary_id, - user_id: source, - normalized_email: format!("transfer-primary-{source}@example.com"), - is_primary: true, - verified_at: Utc::now(), - }) - .await - .expect("source primary"); - database - .emails() - .insert_verified(&InsertVerifiedEmail { - id: TokenId::new(), - user_id: source, - normalized_email: format!("transfer-secondary-{source}@example.com"), - is_primary: false, - verified_at: Utc::now(), - }) - .await - .expect("source secondary"); - database - .users() - .set_status(source, AccountStatus::Disabled) - .await - .expect("disable transfer source"); - let raw = sqlx::PgPool::connect(&env::var("TEST_DATABASE_URL").expect("database URL")) - .await - .expect("raw constraint test connection"); - let mut transfer = raw.begin().await.expect("begin transfer"); - sqlx::query("UPDATE user_emails SET user_id=$1 WHERE id=$2") - .bind(destination.as_uuid()) - .bind(primary_id.as_uuid()) - .execute(&mut *transfer) - .await - .expect("update remains deferred"); - assert!(transfer.commit().await.is_err()); - raw.close().await; -} diff --git a/crates/database/tests/security.rs b/crates/database/tests/security.rs new file mode 100644 index 000000000..a52f886fd --- /dev/null +++ b/crates/database/tests/security.rs @@ -0,0 +1,126 @@ +//! Persistence guarantees behind invitations and reusable management windows. +use chrono::{Duration, Utc}; +use piquel_auth_protocol::{AuthenticationMethod, SessionId, UserId}; +use piquel_repository::{Database, DatabaseConfig, InsertSession, InsertUser}; + +#[expect( + clippy::too_many_lines, + reason = "Keep the invitation rollback and session lifecycle scenario together." +)] +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn invitation_redemption_and_management_lifecycle() { + let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let db = Database::connect( + DatabaseConfig::new_development(&url, 5, std::time::Duration::from_secs(5)) + .expect("config"), + ) + .await + .expect("connect"); + db.run_migrations().await.expect("migrate"); + let user = UserId::new(); + let digest = user.as_uuid().as_bytes().repeat(2); + db.security() + .create_invitation(&digest, Utc::now() + Duration::minutes(1)) + .await + .expect("invite"); + let mut tx = db.begin().await.expect("transaction"); + assert!( + tx.security() + .redeem_invitation(&digest) + .await + .expect("redeem") + ); + tx.rollback().await.expect("rollback"); + assert!( + db.security() + .invitation_active(&digest) + .await + .expect("rollback preserves invitation") + ); + let redeem = || async { + db.security() + .redeem_invitation(&digest) + .await + .expect("redemption") + }; + let (a, b) = tokio::join!(redeem(), redeem()); + assert_ne!(a, b, "exactly one concurrent redemption succeeds"); + db.users() + .insert(&InsertUser { + id: user, + username: format!("test_{user}"), + display_name: "Security test".into(), + }) + .await + .expect("user"); + let session = SessionId::new(); + let other = SessionId::new(); + let now = Utc::now(); + for id in [session, other] { + db.sessions() + .insert(&InsertSession { + id, + user_id: user, + authentication_methods: vec![AuthenticationMethod::Federation], + authenticated_at: now, + expires_at: now + Duration::seconds(3), + user_agent_family: None, + }) + .await + .expect("session"); + } + assert!( + !db.sessions() + .management_active(session) + .await + .expect("social has no grant") + ); + let expiry = db + .sessions() + .grant_management(session) + .await + .expect("grant"); + assert!( + expiry <= now + Duration::seconds(3), + "management cannot outlive session" + ); + for _ in 0..2 { + assert!( + db.sessions() + .management_active(session) + .await + .expect("reusable grant") + ); + } + assert!( + !db.sessions() + .management_active(other) + .await + .expect("grant is session-bound") + ); + db.sessions() + .revoke_other(user, session) + .await + .expect("revoke others"); + assert!( + db.sessions() + .find_active_by_id(other) + .await + .expect("other") + .is_none() + ); + assert!( + db.sessions() + .management_active(session) + .await + .expect("current preserved") + ); + db.sessions().revoke(session).await.expect("logout"); + assert!( + !db.sessions() + .management_active(session) + .await + .expect("logout invalidates grant") + ); +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 000000000..ff5e368b0 --- /dev/null +++ b/deny.toml @@ -0,0 +1,8 @@ +[advisories] +version = 2 + +[licenses] +version = 2 +# Permissive dependencies and unchanged MPL library files may be distributed +# with this Apache-2.0 service; retain their notices in source distributions. +allow = ["Apache-2.0", "MIT", "BSD-3-Clause", "ISC", "Unicode-3.0", "Zlib", "CDLA-Permissive-2.0", "MPL-2.0"] diff --git a/docs/architecture/database-crate.md b/docs/architecture/database-crate.md index 34544855e..8b521a6de 100644 --- a/docs/architecture/database-crate.md +++ b/docs/architecture/database-crate.md @@ -1,1179 +1,40 @@ -# Piquel Database Crate Design - -## 1. Purpose - -The database crate is the single PostgreSQL access layer for the `piquel.fr` monorepo. -It is the only workspace crate permitted to depend directly on SQLx. -It provides typed repositories and transaction APIs to the platform applications while preventing SQLx-specific implementation details from leaking into the rest of the repository. - -The crate exists to: -* Centralize database access -* Keep SQL consistent and reviewable -* Enforce data-access boundaries -* Provide typed repository APIs -* Translate database errors into stable application-facing errors -* Coordinate migrations -* Support safe multi-step transactions -* Make database behavior testable independently of applications - -The crate can be found in `crates/database` & is named `piquel-repository`. - ---- - -## 2. Architectural position - -```text -auth-service ──────┐ -admin-api ─────────┤ -piquel-api ────────┤ -other main apps ───┤ - ▼ - piquel-database - │ - ▼ - SQLx - │ - ▼ - PostgreSQL -``` - -No other application or shared crate may communicate directly with PostgreSQL. -The database crate may depend on shared primitive crates where necessary, but it must not depend on any application. - ---- - -## 3. Goals - -The database crate should: -* Be the only direct SQLx consumer -* Hide pools, connections, transactions, rows, and SQLx errors -* Expose domain-oriented repositories -* Support both non-transactional and transactional operations -* Keep query behavior explicit -* Use typed identifiers and input structures -* Make concurrency semantics visible -* Own database migrations -* Provide integration-test support -* Support distinct database roles for each application -* Preserve clear conceptual ownership of tables - ---- - -## 4. Non-goals - -The database crate is not: -* A generic ORM -* A business-service layer -* An authorization layer -* An authentication-policy engine -* A replacement for application domain logic -* A place for unrelated data transformations -* A way for every application to access every table -* A wrapper exposing arbitrary SQL execution -* A network service - -The crate executes persistence operations. -Applications decide when and why those operations are performed. - ---- - -## 5. Proposed directory structure - -```text -crates/database/ -├── Cargo.toml -├── README.md -├── AGENTS.md -├── migrations/ -│ ├── 0001_initial.sql -│ ├── 0002_authentication.sql -│ ├── 0003_admin.sql -│ ├── 0004_internal_events.sql -│ └── ... -│ -├── src/ -│ ├── lib.rs -│ ├── config.rs -│ ├── connection.rs -│ ├── error.rs -│ ├── transaction.rs -│ ├── health.rs -│ │ -│ ├── models/ -│ │ ├── mod.rs -│ │ ├── user.rs -│ │ ├── email.rs -│ │ ├── passkey.rs -│ │ ├── session.rs -│ │ ├── refresh_token.rs -│ │ ├── oidc_client.rs -│ │ ├── service_identity.rs -│ │ ├── administrator.rs -│ │ └── internal_event.rs -│ │ -│ ├── rows/ -│ │ ├── mod.rs -│ │ ├── user.rs -│ │ ├── session.rs -│ │ └── refresh_token.rs -│ │ -│ ├── repositories/ -│ │ ├── mod.rs -│ │ ├── users.rs -│ │ ├── emails.rs -│ │ ├── passkeys.rs -│ │ ├── sessions.rs -│ │ ├── refresh_tokens.rs -│ │ ├── oidc_clients.rs -│ │ ├── service_identities.rs -│ │ ├── administrators.rs -│ │ └── internal_events.rs -│ │ -│ └── bin/ -│ └── migrate.rs -│ -└── tests/ - ├── common/ - ├── users.rs - ├── sessions.rs - ├── refresh_tokens.rs - └── migrations.rs -``` - -Private modules may be reorganized as the crate evolves. - -The public API should remain centered around: -* `Database` -* Repository handles -* `DatabaseTransaction` -* Public database model types -* Typed database errors - ---- - -## 6. Dependency policy - -`piquel-database` may depend on: -* SQLx -* Tokio -* Thiserror -* Shared Piquel identifier and primitive crates -* Serialization crates where required -* Time and UUID crates -* Tracing for sanitized instrumentation - -Application crates depend on `piquel-database`. -No application may also depend directly on SQLx. - -### 6.1 Tokio - -All asynchronous database operations use Tokio. -The database crate must not create its own Tokio runtime. -It assumes it is called from an existing asynchronous runtime. - -### 6.2 Error crates - -Use `thiserror` for public and internal typed database errors. -Do not expose `anyhow::Error` from public repository methods. -Applications may wrap database errors with `anyhow::Context` at orchestration boundaries. - ---- - -## 7. Public entry point - -The main entry point is a `Database` type. - -```rust -#[derive(Clone)] -pub struct Database { - pool: sqlx::PgPool, -} -``` - -The pool remains private. -Construction should validate configuration and establish the pool. - -```rust -impl Database { - pub async fn connect( - config: DatabaseConfig, - ) -> Result; - - pub async fn health_check( - &self, - ) -> Result<(), DatabaseError>; - - pub async fn begin( - &self, - ) -> Result, DatabaseError>; -} -``` - -Applications must not be able to retrieve the inner `PgPool`. - -Do not implement: -```rust -pub fn pool(&self) -> &sqlx::PgPool; -``` - -Do not implement arbitrary query escape hatches. - ---- - -## 8. Repository access - -The `Database` type exposes focused repository handles. - -```rust -impl Database { - pub fn users(&self) -> UserRepository<'_>; - pub fn emails(&self) -> EmailRepository<'_>; - pub fn passkeys(&self) -> PasskeyRepository<'_>; - pub fn sessions(&self) -> SessionRepository<'_>; - pub fn refresh_tokens(&self) -> RefreshTokenRepository<'_>; - pub fn oidc_clients(&self) -> OidcClientRepository<'_>; - pub fn service_identities(&self) -> ServiceIdentityRepository<'_>; - pub fn administrators(&self) -> AdministratorRepository<'_>; - pub fn internal_events(&self) -> InternalEventRepository<'_>; -} -``` - -Example: -```rust -let user = database - .users() - .find_by_id(&user_id) - .await?; -``` - -Repository objects are lightweight wrappers around a private executor abstraction. -They should not own separate pools. - ---- - -## 9. Repository organization - -Repositories are organized by domain rather than by SQL table count. -A repository may access multiple closely related tables when that matches the domain operation. - -Examples: - -### `UserRepository` - -May access: -* `users` -* Token-visible profile fields -* Account status -* Profile version - -### `EmailRepository` - -May access: -* `user_emails` -* Verification state -* Primary-email state - -### `RefreshTokenRepository` - -May access: -* `refresh_token_families` -* `refresh_tokens` -* Replay-detection state - -Repositories must not grow into application-service layers. -A repository method should describe a persistence operation. - -Good: -```rust -find_by_id -find_by_verified_email -insert -update_display_name -increment_profile_version -consume_for_rotation -revoke_family -``` - -Avoid: -```rust -authenticate_user -decide_account_recovery_policy -authorize_admin_action -choose_social_login_provider -``` - -Those decisions belong to application domain logic. - ---- - -## 10. Public model types - -Public database models represent stored information in a database-independent form. - -Example: -```rust -pub struct StoredUser { - pub id: UserId, - pub username: Username, - pub display_name: DisplayName, - pub profile_version: u64, - pub status: UserStatus, - pub created_at: DateTime, - pub updated_at: DateTime, -} -``` - -These types must not expose: -* SQLx traits as part of their public contract -* PostgreSQL-specific enum representations -* Raw database column names where avoidable -* Database nullability quirks -* Internal surrogate keys when unnecessary - -Input types should be explicit. -```rust -pub struct InsertUser { - pub id: UserId, - pub username: Username, - pub display_name: DisplayName, -} -``` - -Avoid repository methods with long lists of primitive parameters. - ---- - -## 11. Private row types - -SQLx-specific row types remain private. - -```rust -#[derive(sqlx::FromRow)] -struct UserRow { - id: uuid::Uuid, - username: String, - display_name: String, - profile_version: i64, - status: String, - created_at: chrono::DateTime, - updated_at: chrono::DateTime, -} -``` - -Private row types translate into public database models. - -```rust -impl TryFrom for StoredUser { - type Error = DatabaseDataError; - - fn try_from(row: UserRow) -> Result { - // Validate and convert database representation. - } -} -``` - -This translation layer prevents malformed or legacy database values from silently entering application code. - ---- - -## 12. Error design - -The database crate exposes typed errors. - -A possible top-level error: -```rust -#[derive(Debug, thiserror::Error)] -pub enum DatabaseError { - #[error("the requested record was not found")] - NotFound, - - #[error("the operation conflicts with existing data")] - Conflict, - - #[error("the database operation timed out")] - Timeout, - - #[error("the database is unavailable")] - Unavailable, - - #[error("stored database data is invalid")] - InvalidStoredData, - - #[error("the transaction could not be completed")] - TransactionFailed, - - #[error("an unexpected database error occurred")] - Internal, -} -``` - -More specific repository errors may be used where callers need to make decisions. - -Example: - -```rust -#[derive(Debug, thiserror::Error)] -pub enum InsertUserError { - #[error("the username is already in use")] - UsernameConflict, - - #[error("the user identifier already exists")] - UserIdConflict, - - #[error(transparent)] - Database(#[from] DatabaseError), -} -``` - -SQLx errors are translated internally. -Do not expose constraint names to application callers unless they are mapped to stable typed variants. -Do not include SQL statements, credentials, or sensitive values in error messages. - -At application boundaries: -```rust -let user = database - .users() - .find_by_id(&user_id) - .await - .context("failed to load the authenticated user")?; -``` - -The application may use `anyhow` to add operational context while preserving the typed database source error. - ---- - -## 13. Transactions - -The crate must support multi-repository transactions. - -Important transactional flows include: -* Creating a user and initial verified email -* Linking a social identity -* Rotating a refresh token -* Registering a passkey -* Updating a profile and appending an internal event -* Revoking a session and associated refresh-token families - -### 13.1 Wrapped transaction - -Expose a `DatabaseTransaction` wrapper. - -```rust -pub struct DatabaseTransaction<'a> { - inner: sqlx::Transaction<'a, sqlx::Postgres>, -} -``` - -The inner SQLx transaction remains private. - -The transaction exposes the same repository families: -```rust -impl DatabaseTransaction<'_> { - pub fn users(&mut self) -> UserRepository<'_>; - pub fn emails(&mut self) -> EmailRepository<'_>; - pub fn refresh_tokens(&mut self) -> RefreshTokenRepository<'_>; - pub fn internal_events(&mut self) -> InternalEventRepository<'_>; - - pub async fn commit(self) -> Result<(), DatabaseError>; - pub async fn rollback(self) -> Result<(), DatabaseError>; -} -``` - -Example: - -```rust -let mut transaction = database.begin().await?; - -let token = transaction - .refresh_tokens() - .consume_for_rotation(&presented_token) - .await?; - -transaction - .refresh_tokens() - .insert_replacement(&token.family_id, new_token) - .await?; - -transaction.commit().await?; -``` - -### 13.2 Transaction requirements - -* Transactions must not be held across external network calls. -* Transactions should be as short as practical. -* Lock acquisition order should be consistent. -* Repository documentation must identify methods that lock rows. -* Commit failures must be handled as operation failures. -* Dropped uncommitted transactions must roll back. - -### 13.3 Closure-based transactions - -A closure-based helper may be introduced later, but it is not required initially. -Rust async closure lifetimes can make such APIs difficult to use correctly. -The explicit transaction wrapper is the preferred initial design. - ---- - -## 14. Concurrency and locking - -Repository methods must document concurrency behavior where it matters. - -Examples include: -* Refresh-token rotation -* Username allocation -* Primary-email changes -* Passkey insertion -* Aggregate event sequence allocation -* Session revocation - -### 14.1 Refresh-token rotation - -Consuming a refresh token must be atomic. -The operation must ensure that two simultaneous refresh requests cannot both succeed. - -Possible implementations include: -* `SELECT ... FOR UPDATE` -* Atomic `UPDATE ... WHERE consumed_at IS NULL RETURNING ...` -* Serializable transaction semantics where justified - -Prefer explicit atomic statements over broad serializable transactions when possible. - -### 14.2 Optimistic concurrency - -Version columns may be used for mutable records. - -Example: -```sql -UPDATE users -SET - display_name = $1, - profile_version = profile_version + 1, - updated_at = now() -WHERE id = $2 - AND profile_version = $3 -RETURNING profile_version; -``` - -The repository should return a typed conflict when the expected version does not match. - -### 14.3 Advisory locks - -PostgreSQL advisory locks should be used only when row-based locking cannot model the operation clearly. -Every advisory-lock use must be documented. - ---- - -## 15. Query policy - -Queries live in the database crate. -Applications must not construct SQL fragments. - -Prefer: -* Explicit SQL -* Typed parameters -* Bounded result sets -* Stable ordering -* Keyset pagination for large collections -* Database constraints for persistent invariants - -Avoid: -* `SELECT *` -* Unbounded list queries -* Dynamic SQL created from untrusted strings -* Offset pagination for very large or frequently changing tables -* Hidden N+1 query patterns - -### 15.1 Checked SQLx queries - -Prefer SQLx checked-query facilities where practical. -The repository should maintain SQLx offline metadata so that CI does not require a live database merely to compile checked queries. - -A root command should update metadata: -```text -just prepare-sqlx -``` - -Generated SQLx metadata must be updated whenever checked queries or relevant schemas change. -Do not manually edit generated SQLx metadata. - -### 15.2 Query files - -Large or complex queries may live in `.sql` files near the relevant repository module. - -Example: -```text -src/repositories/users/ -├── mod.rs -├── find_by_id.sql -└── search.sql -``` - -Small queries may remain inline when readability is better. - ---- - -## 16. Migrations - -All shared database migrations live in: -```text -crates/database/migrations/ -``` - -Migrations are owned by the monorepo, not by individual application directories. - -### 16.1 Migration rules - -* Every schema change requires a migration. -* Applied migrations are immutable. -* Fix mistakes through a new migration. -* Use descriptive migration names. -* Separate unrelated schema changes. -* Add constraints deliberately. -* Consider existing production data. -* Avoid long table locks where possible. -* Document destructive migrations. -* Review auth-related migrations as security-sensitive changes. - -### 16.2 Migration execution - -Provide a dedicated migration binary: -```text -crates/database/src/bin/migrate.rs -``` - -Example: -```rust -#[tokio::main] -async fn main() -> anyhow::Result<()> { - let config = DatabaseConfig::from_environment()?; - let database = Database::connect(config).await?; - - database - .run_migrations() - .await?; - - Ok(()) -} -``` - -The migration binary may use `anyhow` because it is an application boundary. -Migration library methods should expose typed errors. - -### 16.3 Application startup - -Application replicas should not automatically race to run migrations during ordinary startup. -Migrations should be executed as an explicit release or operational step once the deployment strategy has been selected. - -### 16.4 Backward compatibility - -For changes deployed across multiple applications: -1. Add backward-compatible schema. -2. Deploy code that supports old and new representations. -3. Migrate or backfill data. -4. Deploy code that relies on the new representation. -5. Remove legacy schema in a later migration. - -Avoid schema changes requiring every application to update atomically. - ---- - -## 17. Database roles and permissions - -All main services may use the same PostgreSQL database while authenticating with distinct database roles. - -Example roles: -```text -piquel_auth_service -piquel_admin_api -piquel_main_api -piquel_migration -piquel_readonly_support -``` - -The migration role owns schema changes. -Runtime roles receive only the privileges they require. - -Examples: - -### Auth service - -May require access to: - -* Users -* Emails -* Passkeys -* Federated identities -* Sessions -* Refresh tokens -* OIDC clients -* Service identities -* Authentication audit records -* Internal events - -### Admin API - -May require: -* Read access to central user information -* Access to administrative tables -* Explicit stored procedures or repository operations for permitted account actions - -### Main API - -May require: -* Main product tables -* Limited user-profile reads -* No direct passkey or refresh-token access - -Database permissions are a real security control. -Cargo feature flags are not a security boundary. - ---- - -## 18. Feature-gated repository groups - -The crate may use Cargo features to reduce accidental coupling and compilation surface. - -Example: -```toml -[features] -default = [] -auth = [] -admin = [] -platform = [] -migrations = [] -test-support = [] -``` - -Application dependency: -```toml -piquel-repository = { - workspace == true - features = ["auth"] -} -``` - -Feature gates may control which repository modules are publicly exported. -They do not replace PostgreSQL permissions because a developer can change feature flags. - ---- - -## 19. Conceptual table ownership - -Even with one database crate and one PostgreSQL database, every table has a conceptual owner. - -Example: -```text -auth-service: - users - user_emails - passkey_credentials - external_login_identities - sessions - refresh_token_families - refresh_tokens - oidc_clients - service_identities - authentication_audit_log - -admin-api: - administrators - administrator_roles - support_cases - administrative_notes - -piquel-api: - main product tables -``` - -Cross-domain reads may be legitimate. -Cross-domain writes require deliberate design. -The database crate must not provide generic update methods that allow one application to bypass another domain’s invariants. - ---- - -## 20. Internal events - -The database crate owns persistence for the internal event log. -It does not decide when a domain event should occur. -The calling application decides which event to append. - -The repository provides operations such as: -```rust -transaction - .internal_events() - .append(AppendInternalEvent { - aggregate_type: AggregateType::User, - aggregate_id: user_id.to_string(), - event_type: "user.display_name.changed".into(), - schema_version: 1, - payload, - }) - .await?; -``` - -Account changes and associated event insertion should occur in the same transaction. - -The event repository must support: -* Unique event IDs -* Per-aggregate sequence numbers -* Schema versions -* Append-only behavior -* Future publication state -* Ordered retrieval for a future publisher - -Event payloads must not contain credentials or tokens. - ---- - -## 21. Sensitive data - -The database crate may handle highly sensitive records. - -Examples: -* Refresh-token digests -* Passkey public-key metadata -* Federated identity mappings -* Session records -* Audit records - -Rules: -* Never log raw refresh tokens. -* Never store raw refresh tokens. -* Never log authorization codes. -* Never place secrets in error messages. -* Redact sensitive query parameters from tracing. -* Use constant-time secret comparison where applicable outside SQL. -* Encrypt sensitive stored values where required by the security design. -* Keep token digests distinct from general-purpose password hashing where lookup behavior differs. - -The database crate should expose methods that operate on digests or structured secret inputs rather than returning sensitive internal values unnecessarily. - ---- - -## 22. Pagination - -All list and search repository methods must be bounded. -Prefer keyset pagination. - -Example public request: -```rust -pub struct UserSearchPage { - pub limit: PageSize, - pub after: Option, -} -``` - -Example result: -```rust -pub struct Page { - pub items: Vec, - pub next_cursor: Option, -} -``` - -Limits must have server-enforced maximums. -Do not allow a caller to request an unbounded result set. - ---- - -## 23. Health checks - -The database crate exposes a small health-check operation. - -It should: -* Verify a connection can be acquired -* Execute a lightweight query -* Respect a short timeout -* Avoid running migrations -* Avoid checking every table - -Example: -```rust -pub async fn health_check( - &self, -) -> Result<(), DatabaseHealthError>; -``` - -Applications decide how database health affects readiness. - ---- - -## 24. Observability - -Repository operations may emit sanitized tracing spans and metrics. - -Useful attributes include: -* Repository name -* Operation name -* Outcome category -* Duration -* Number of returned rows -* Whether a transaction was used - -Do not include: -* SQL query parameters -* Tokens -* Email addresses -* User-provided search text -* Unbounded user IDs as metric labels - -SQL text may be available in controlled development logs, but production logging must avoid exposing sensitive values. - ---- - -## 25. Testing strategy - -The database crate requires integration tests against PostgreSQL. -Mocking SQLx is not a substitute for testing actual constraints and transaction behavior. - -### 25.1 Unit tests - -Use unit tests for: -* Row conversion -* Cursor encoding -* Input validation -* Error mapping -* Identifier conversion - -### 25.2 Integration tests - -Use PostgreSQL integration tests for: -* Repository queries -* Constraints -* Transactions -* Locking -* Concurrent refresh-token consumption -* Migration correctness -* Pagination -* Role permissions where practical - -### 25.3 Test isolation - -Each test should use one of: -* A dedicated temporary database -* A dedicated temporary schema -* A transaction rolled back after the test, where concurrency behavior does not require committed state - -Tests must not depend on execution order. - -### 25.4 Migration tests - -CI should verify: -* A fresh database can apply every migration -* The resulting schema supports repository tests -* SQLx metadata matches the current schema and queries -* Important upgrade paths remain valid where supported - -### 25.5 Concurrency tests - -Security-sensitive concurrency requires explicit tests. - -Examples: -* Only one of two simultaneous refresh rotations succeeds. -* Duplicate verified emails cannot be inserted. -* Aggregate event sequence numbers remain unique. -* Passkey credentials remain unique. -* Session revocation is idempotent. - ---- - -## 26. Repository API examples - -### 26.1 User lookup - -```rust -let user = database - .users() - .find_by_id(&user_id) - .await? - .ok_or(UserLookupError::NotFound)?; -``` - -The repository may return `Option` when absence is expected. -Use a typed `NotFound` error when absence represents operation failure. -Choose consistently per method. - -### 26.2 Social identity linking - -```rust -let mut transaction = database.begin().await?; - -if let Some(identity) = transaction - .federated_identities() - .find_by_issuer_and_subject(&issuer, &subject) - .await? -{ - transaction.commit().await?; - return Ok(identity.user_id); -} - -let user = transaction - .users() - .find_by_verified_email(&normalized_email) - .await?; - -let user_id = match user { - Some(user) => user.id, - None => { - transaction - .users() - .insert(new_user) - .await? - .id - } -}; - -transaction - .federated_identities() - .insert(LinkFederatedIdentity { - user_id, - issuer, - subject, - linked_email, - }) - .await?; - -transaction.commit().await?; -``` - -The application decides the linking policy. -The database crate guarantees atomic persistence. - -### 26.3 Profile update with event - -```rust -let mut transaction = database.begin().await?; - -let updated = transaction - .users() - .update_display_name(UpdateDisplayName { - user_id, - expected_profile_version, - display_name, - }) - .await?; - -transaction - .internal_events() - .append(AppendInternalEvent { - aggregate_type: AggregateType::User, - aggregate_id: user_id.to_string(), - event_type: "user.display_name.changed".into(), - schema_version: 1, - payload: serde_json::json!({ - "profile_version": updated.profile_version, - }), - }) - .await?; - -transaction.commit().await?; -``` - ---- - -## 27. Prohibited database patterns - -The following are not allowed: - -```rust -// Exposing SQLx: -pub fn pool(&self) -> &sqlx::PgPool; - -// Accepting arbitrary SQL: -pub async fn execute(&self, query: &str); - -// Returning SQLx errors: -pub async fn find_user(...) -> Result; - -// Letting applications supply raw executors: -pub async fn find_user( - executor: impl sqlx::Executor<'_>, - ... -); - -// Application-owned raw SQL: -sqlx::query!("DELETE FROM refresh_tokens ..."); -``` - -Also prohibited: -* Business policy hidden inside repository code -* Unbounded list methods -* Logging query parameters containing personal or secret data -* Updating auth-critical tables through generic map-based APIs -* Automatic migrations from every application replica -* Schema changes without migrations -* Modifying an applied migration -* Returning private row types publicly -* Database feature flags treated as security controls - ---- - -## 28. Adding a repository method - -Before adding a repository method, determine: -1. Which domain owns the operation? -2. Is this persistence behavior or business policy? -3. Does an existing method already support it? -4. Must it participate in a transaction? -5. What happens under concurrent calls? -6. What database constraints enforce the invariant? -7. What typed errors must the caller handle? -8. Does the result need pagination? -9. Does it expose sensitive data? -10. Which database roles should be permitted to execute it? - -The method should be named after the persistence action, not the HTTP endpoint that currently needs it. - ---- - -## 29. Adding a table - -Every new table must have: -* A conceptual owner -* A migration -* Appropriate primary and foreign keys -* Required uniqueness constraints -* Timestamp policy -* Deletion or retention policy -* Repository ownership -* Permission grants -* Test coverage -* Documentation when security-sensitive - -Do not add tables as general-purpose dumping grounds for JSON. -JSON columns are acceptable when the data is genuinely flexible or event-shaped, but core searchable invariants should use typed columns. - ---- - -## 30. Crate evolution - -The database crate should begin as one crate. -Do not split it into multiple database crates merely because it contains several repositories. - -Consider splitting only when: -* Compile times become materially problematic -* Domains require genuinely different databases -* Release boundaries diverge -* Security boundaries require separate packages -* The public API becomes difficult to navigate despite clear modules - -A single well-structured crate is preferable to many thin crates that all expose SQLx-adjacent details. - ---- - -## 31. Guiding principles - -The database crate follows these principles: -1. SQLx stays private. -2. PostgreSQL behavior is explicit. -3. Repositories model persistence operations. -4. Applications own business policy. -5. Transactions span repository operations safely. -6. Database constraints protect persistent invariants. -7. Typed errors replace leaked driver errors. -8. Migrations are deliberate and immutable. -9. Shared storage does not erase domain ownership. -10. Security-sensitive data receives security-sensitive APIs. - -The central rule is: -> Applications describe the persistence operation they need; the database crate decides how that operation is performed safely in PostgreSQL. +# PostgreSQL boundary + +`crates/database` is the only SQLx consumer. It exposes `Database`, validated +`DatabaseConfig`, typed repository handles, and `DatabaseTransaction`. Pools, +connections, rows and raw SQL remain private. Application modules choose policy; +repository methods enforce atomic persistence and return contextual errors. + +Repository modules separate identity/passkeys, OIDC and federation. Transactions +expose the same repository families as `Database`. User, session and credential +locks serialize security-sensitive changes. Acquire account locks before session +and credential locks. Credentials are rechecked under lock before authentication +updates; a ceremony snapshot cannot override newer counters or revocation. + +Important invariants: + +- Opaque browser tokens and invitation/OAuth lookup secrets are stored as digests. +- Ceremonies are browser-bound, expire and are consumed once, even for invalid + authentication responses. Their serialized WebAuthn state contains challenges + and stays server-side; do not log it. +- Account, initial credential, optional social identity, invitation redemption and + initial session commit in one transaction. +- A session-bound management expiry is checked inside the mutation transaction. + It permits repeated changes for two minutes and does not outlive the session. +- Account locking protects the last-passkey guard from concurrent removals. +- Active provider subjects and active provider-per-account links are unique. + Unlink marks the identity revoked and releases both constraints. +- Verified email ownership is unique across active accounts. Email is optional; + explicit provider linking never transfers ownership of another account's email. +- Authorization codes are single-use and bound to client, redirect and PKCE. + Refresh tokens rotate transactionally, remain bound to their client/session, + and reuse revokes the family. + +The prototype schema is disposable. The release requires a fresh database; +subsequent released migrations must be immutable. Run migrations with +`auth-service migrate`; startup does not silently mutate the schema. + +Every five minutes the service purges bounded batches of expired ephemeral state. +Security audit history is retained. Tests that use `TEST_DATABASE_URL` are explicitly +marked ignored by the ordinary unit test runner; the documented database test +command includes them and must use a disposable database. diff --git a/docs/architecture/monorepo.md b/docs/architecture/monorepo.md index a81185ca5..5ab233ddb 100644 --- a/docs/architecture/monorepo.md +++ b/docs/architecture/monorepo.md @@ -1,895 +1,36 @@ -# Piquel Monorepo Structure and Contribution Guidelines - -## 1. Purpose - -This document explains how the `piquel.fr` monorepo is organized and establishes rules for modifying it safely. - -It is intended for: - -* Human contributors -* Coding agents -* Code-review agents -* Repository automation -* Future maintainers - -Before making structural changes, adding dependencies, creating a new service, or moving code between packages, contributors should read this document. -The main objective is to keep the repository understandable and prevent accidental coupling between applications. - -This document contains the global vision. Only add parts described here when -they are actually needed. Adding a bunch of empty crates is unnecessary. - ---- - -## 2. Repository scope - -The monorepo contains the services and interfaces that make up the main `piquel.fr` platform. - -This includes: - -* The central authentication service at `auth.piquel.fr` -* The authentication frontend -* Administrative APIs -* Administrative frontends -* The main `piquel.fr` backend -* The main `piquel.fr` frontend -* Shared Rust libraries -* Shared frontend packages -* Shared database access -* Internal protocol definitions -* Monitoring configuration -* Architecture and operational documentation - -Independent downstream products are not part of this monorepo. - -Those products live in separate repositories and integrate with the platform through the published Piquel authentication SDK and public authentication protocols. - ---- - -## 3. Architectural model - -The monorepo contains multiple deployable applications that share: - -* A repository -* A PostgreSQL database -* Common Rust crates -* Common protocol definitions -* Common frontend packages where useful -* Common monitoring conventions - -Sharing a repository and database does not mean every application may modify every part of the system. - -Each application still has clear responsibilities. - -In particular: - -* `auth-service` owns authentication and identity invariants. -* Administrative applications perform explicit administrative operations. -* Frontends communicate through APIs rather than accessing data directly. -* Shared crates provide reusable infrastructure and protocol code. -* The database crate is the only crate that communicates directly with PostgreSQL through SQLx. - ---- - -## 4. Repository overview - -```text -piquel/ -├── apps/ -│ ├── auth-service/ -│ ├── auth-web/ -│ ├── admin-api/ -│ ├── admin-web/ -│ ├── piquel-api/ -│ └── piquel-web/ -│ -├── crates/ -│ ├── database/ -│ ├── auth-sdk/ -│ ├── auth-middleware/ -│ ├── auth-client/ -│ ├── auth-protocol/ -│ ├── service-auth/ -│ ├── configuration/ -│ ├── telemetry/ -│ └── test-support/ -│ -├── packages/ -│ ├── auth-client-js/ -│ ├── ui/ -│ ├── design-tokens/ -│ ├── eslint-config/ -│ └── typescript-config/ -│ -├── proto/ -│ └── piquel/ -│ └── auth/ -│ └── v1/ -│ -├── infra/ -│ └── monitoring/ -│ -├── docs/ -│ ├── architecture/ -│ ├── security/ -│ ├── decisions/ -│ └── operations/ -│ -├── scripts/ -├── plans/ -├── Cargo.toml -├── Cargo.lock -├── package.json -├── pnpm-workspace.yaml -└── justfile -``` - -Not every directory must exist immediately. Add a directory only when it has a concrete use. - -Do not create placeholder packages or speculative abstraction layers. - ---- - -## 5. Root-level responsibilities - -### `Cargo.toml` - -The root Cargo workspace defines all Rust applications and libraries. - -All dependencies & versions should be declared in `[workspace.dependencies]`. - -Applications and crates must still list the dependencies they use explicitly. - -Example: - -```toml -[workspace] -resolver = "2" -members = [ - "apps/auth-service", - "apps/admin-api", - "apps/piquel-api", - "crates/*", -] - -[workspace.dependencies] -anyhow = "1" -thiserror = "2" -tokio = { version = "1", features = ["full"] } -tracing = "0.1" -serde = { version = "1", features = ["derive"] } -``` - -### `package.json` and `pnpm-workspace.yaml` - -The root JavaScript workspace manages frontend applications and shared packages. -Use `pnpm` for workspace dependency management. -A package must not depend on another application under `apps/`. -Shared frontend code belongs under `packages/`. - -### `justfile` - -The root `justfile` provides consistent development commands. - -Typical commands include: - -```text -just test -just lint -just format -just check -just dev-auth -just dev-admin -just migrate -just generate-proto -just prepare-sqlx -``` - -Commands should delegate to Cargo, pnpm, Protobuf tools, and other underlying tooling rather than hiding important behavior in large shell scripts. - ---- - -## 6. Applications - -Everything under `apps/` is a deployable application. -Applications may depend on shared crates and packages. -Applications must not depend directly on another application. -Invalid dependency: - -```text -apps/admin-api - └── imports apps/auth-service -``` - -Valid dependency: - -```text -apps/admin-api - ├── depends on crates/database - ├── depends on crates/auth-client - └── depends on crates/auth-protocol -``` - -### 6.1 `apps/auth-service` - -The central authentication authority served at `auth.piquel.fr`. - -It owns: - -* Piquel accounts -* Passkey authentication -* Social authentication -* OIDC and OAuth endpoints -* Login sessions -* Access-token issuance -* Refresh-token rotation -* Service authentication -* Internal authentication RPC -* Authentication audit events -* Authentication-related internal events - -Its internal modules may include: - -```text -apps/auth-service/src/ -├── account/ -├── email/ -├── federation/ -├── oidc/ -├── passkey/ -├── session/ -├── token/ -├── service_identity/ -├── rpc/ -├── audit/ -├── event_log/ -├── lib.rs -└── main.rs -``` - -These modules are internal implementation details. -Do not extract an internal module into a shared crate unless another application has a real, justified need for the same behavior. -Authentication policy and authentication invariants must remain owned by `auth-service`. - -### 6.2 `apps/auth-web` - -The user-facing frontend for `auth.piquel.fr`. -It may contain: - -* Login pages -* Passkey registration -* Social login -* OAuth consent -* Session management -* Account security settings -* Authentication error pages - -It communicates through supported HTTP APIs. -It must not receive internal service credentials. -It must not access PostgreSQL directly. - -### 6.3 `apps/admin-api` - -The trusted administrative backend. - -It may provide operations such as: -* Searching users -* Viewing account state -* Reviewing security events -* Disabling accounts -* Revoking sessions -* Managing administrative roles - -It may use the shared database crate for explicitly supported administrative data access. -It must not duplicate authenticaton policy. -Security-sensitive account mutations should be implemented through well-defined database operations or auth-service RPC methods, depending on which component owns the invariant. -Do not modify authentication tables with ad hoc queries. - -### 6.4 `apps/admin-web` - -The administrative frontend. -It calls `admin-api`. - -It must not: -* Access the database -* Hold database credentials -* Hold internal service private keys -* Call privileged internal RPC endpoints directly from browser code - -### 6.5 `apps/piquel-api` - -The backend for the main `piquel.fr` product. -It may use: - -* `crates/database` -* `crates/auth-middleware` -* `crates/auth-client` -* `crates/auth-protocol` -* Shared configuration and telemetry crates - -It validates Piquel access tokens through the authentication SDK. -It owns its product-specific authorization and business rules. - -### 6.6 `apps/piquel-web` - -The frontend for the main `piquel.fr` product. -It uses the public authentication flow and communicates with `piquel-api`. -It must not contain server credentials in browser bundles. - ---- - -## 7. Shared Rust crates - -Everything under `crates/` is reusable Rust code. -Shared crates must have clear responsibilities and stable public interfaces. -They must not become containers for unrelated utilities. - -### 7.1 `crates/database` - -The only crate permitted to depend directly on SQLx. - -It owns: -* PostgreSQL connection management -* SQL queries -* Database row mappings -* Repository implementations -* Wrapped database transactions -* Migrations -* Database error translation - -Other applications and crates use its repository API. -They must not receive raw SQLx pools, rows, transactions, or errors. - -A more detailed design is maintained in: - -```text -docs/architecture/database-crate.md -``` - -### 7.2 `crates/auth-protocol` - -Contains authentication protocol types shared between trusted Rust components. - -Examples: -* `UserId` -* `SessionId` -* `ClientId` -* `ServiceId` -* Access-token claims -* Service-token claims -* Authentication method enums -* Stable internal error codes - -It must not contain: -* SQLx row types -* Database schema details -* Auth-service business logic -* Web-framework-specific middleware - -### 7.3 `crates/auth-middleware` - -Contains framework-neutral JWT authentication logic and optional web-framework adapters. -It owns the `AuthMiddleware` builder. - -Responsibilities include: -* JWT extraction -* Signature validation -* Issuer validation -* Audience validation -* Expiry validation -* JWKS caching -* Construction of a validated principal - -Audience validation must remain mandatory for production use. - -### 7.4 `crates/auth-client` - -Contains the client for the private authentication RPC API. - -It may wrap generated gRPC clients with: -* Service-token injection -* Deadlines -* Retry policy -* Error translation -* Tracing -* Safe configuration defaults - -### 7.5 `crates/auth-sdk` - -Provides the main ergonomic SDK facade. - -It may re-export selected functionality from: -* `auth-protocol` -* `auth-middleware` -* `auth-client` -* `service-auth` - -Downstream repositories should normally depend on this crate rather than understanding the monorepo’s internal crate layout. -Avoid placing all implementation code directly into this facade crate. - -### 7.6 `crates/service-auth` - -Contains service-level authentication support. - -Responsibilities may include: -* Signed service assertions -* Short-lived service-token retrieval -* Token caching -* Token renewal -* RPC metadata injection - -### 7.7 `crates/configuration` - -Contains shared configuration loading and validation. - -It may define: -* Environment configuration helpers -* Typed duration parsing -* URL parsing -* Secret references -* Common environment names - -It must not contain application-specific business configuration. - -### 7.8 `crates/telemetry` - -Contains shared logging, tracing, and metrics initialization. - -It may define: -* Standard tracing configuration -* Request IDs -* OpenTelemetry integration -* Metric naming conventions -* Sensitive-data redaction helpers - -### 7.9 `crates/test-support` - -Contains test-only helpers shared by multiple Rust packages. - -Examples: -* Test database setup -* Fixture builders -* Token factories -* Mock OIDC providers -* Test service identities - -Production crates must not depend on `test-support` outside development or test configurations. - ---- - -## 8. Shared frontend packages - -Shared JavaScript and TypeScript packages live under `packages/`. - -### 8.1 `packages/auth-client-js` - -Provides browser-safe authentication helpers. - -It may include: -* Authorization URL construction -* PKCE helpers -* Callback processing -* Session-aware frontend utilities - -It must not contain: -* Internal service authentication -* Private keys -* Database access -* Privileged RPC clients - -### 8.2 `packages/ui` - -Contains reusable UI components. -Keep it framework-specific or framework-neutral according to actual use. -Do not create React and Svelte wrappers until both are needed. - -### 8.3 `packages/design-tokens` - -Contains shared visual constants such as: -* CSS variables -* Typography definitions -* Spacing scales -* Border radii -* Semantic colors - -### 8.4 Configuration packages - -Shared ESLint and TypeScript settings belong in dedicated packages rather than being copied across applications. - ---- - -## 9. Protocol definitions - -Internal Protobuf definitions live under: -```text -proto/piquel/auth/v1/ -``` - -Protocol files are not owned by a specific application because both the server and clients consume them. - -Rules: -* Use versioned packages. -* Never reuse deleted field numbers. -* Reserve removed field names and numbers. -* Prefer additive changes. -* Avoid exposing database row structure. -* Keep browser clients away from private RPC protocols. -* Regenerate clients through repository commands rather than editing generated code. - -Generated code should either be checked in consistently according to a documented repository policy. - ---- - -## 10. Database ownership - -The main Piquel services share one PostgreSQL database because their core information is closely related. -All PostgreSQL access goes through `crates/database`. - -This rule applies even when a query appears trivial. - -Do not: -* Add SQLx directly to an application -* Create an application-specific database pool -* Run raw SQL from an application -* Expose a `PgPool` from the database crate -* Expose a SQLx transaction from the database crate -* Return `sqlx::Error` from a public repository API - -The shared database does not remove domain ownership. - -Examples: -* Auth tables are owned conceptually by `auth-service`. -* Administrative tables are owned conceptually by `admin-api`. -* Main product tables are owned conceptually by `piquel-api`. - -Repository methods should make ownership clear. -Applications must not modify another domain’s sensitive data through generic repository escape hatches. - ---- - -## 11. Infrastructure directory - -The monorepo does not currently prescribe a deployment platform or delivery pipeline. -Do not add speculative Kubernetes, Terraform, Docker Compose, or provider-specific deployment structures until a deployment strategy is selected. - -For now, `infra/` contains monitoring configuration only: -```text -infra/ -└── monitoring/ - ├── dashboards/ - ├── alerts/ - ├── recording-rules/ - └── README.md -``` - -### 11.1 Dashboards - -Contains version-controlled monitoring dashboards for: -* Authentication -* API traffic -* Database health -* Redis health -* RPC traffic -* Frontend errors -* Platform-level availability - -### 11.2 Alerts - -Contains alert definitions for conditions such as: -* Elevated login failure rates -* Refresh-token replay detection -* Token-signing failures -* Database connection exhaustion -* High request latency -* Elevated server error rates -* RPC authentication failures -* Redis outages -* Background task failures - -### 11.3 Recording rules - -Contains precomputed metric expressions where the selected monitoring system supports them. - -### 11.4 Monitoring rules - -Monitoring configuration must not contain: -* Secrets -* Raw user identifiers -* Email addresses -* Tokens -* Authorization headers -* High-cardinality unbounded labels - -Application instrumentation belongs in the relevant application or telemetry crate. -The `infra/monitoring` directory contains the configuration that consumes that instrumentation. - ---- - -## 12. Documentation - -Repository documentation lives under `docs/`. -```text -docs/ -├── architecture/ -├── security/ -├── decisions/ -└── operations/ -``` - -### `docs/architecture` - -Contains durable system and component designs. - -Examples: -* Authentication architecture -* Monorepo structure -* Database crate design -* RPC architecture - -### `docs/security` - -Contains threat models, accepted risks, security requirements, and incident-related procedures. - -### `docs/decisions` - -Contains architectural decision records. - -Use an ADR when changing a major boundary, including: -* Database ownership -* Authentication-token structure -* Frontend framework policy -* RPC protocol choice -* Deployment platform -* Migration strategy - -### `docs/operations` - -Contains operational procedures such as: -* Database migration -* Signing-key rotation -* Service-key rotation -* Backup restoration -* Incident response - -Keep documentation updated when changing the architecture it describes. - ---- - -## 13. Rust stack guidelines - -These guidelines are repository defaults and may be updated through an architectural decision. - -### 13.1 Asynchronous runtime - -Use Tokio for asynchronous Rust. - -Rules: -* Application binaries own runtime startup through `#[tokio::main]`. -* Shared libraries expose asynchronous functions without creating their own runtime. -* Do not call `Runtime::new()` inside reusable libraries. -* Avoid blocking operations on Tokio worker threads. -* Use `spawn_blocking` for unavoidable blocking work. -* Make cancellation behavior explicit for long-running tasks. -* Use timeouts on network and RPC operations. - -### 13.2 Error handling - -Use `thiserror` for typed library and domain errors. - -Example: -```rust -#[derive(Debug, thiserror::Error)] -pub enum AuthenticationError { - #[error("the access token has expired")] - TokenExpired, - - #[error("the token audience is invalid")] - InvalidAudience, - - #[error("the signing key is unavailable")] - SigningKeyUnavailable, -} -``` - -Use `anyhow` at application boundaries for: -* Application startup -* CLI commands -* Top-level task orchestration -* Error context in binaries -* Operations where callers do not need to match error variants - -Example: -```rust -async fn main_inner() -> anyhow::Result<()> { - let config = load_config() - .context("failed to load auth-service configuration")?; - - run(config).await -} -``` - -Do not expose `anyhow::Error` from reusable public crate APIs when callers need structured handling. - -General rule: - -```text -Libraries and domains: thiserror -Application boundaries and orchestration: anyhow -``` - -### 13.3 Dependency discipline - -Before adding a dependency: -* Confirm an existing workspace dependency does not already solve the problem. -* Prefer well-maintained crates with narrow responsibilities. -* Avoid adding two libraries for the same purpose. -* Add versions through `[workspace.dependencies]`. -* Avoid large default feature sets when only a subset is needed. -* Consider security and maintenance history. - ---- - -## 14. Frontend stack guidelines - -Frontends may use SvelteKit or React-based frameworks. -Do not force all frontends onto one framework unless a project-wide decision has been made. -Shared browser packages should avoid framework coupling where practical. - -Rules: -* Do not place secrets in browser environment variables. -* Do not expose internal RPC endpoints to browser clients. -* Do not store refresh tokens in `localStorage`. -* Prefer generated or typed API clients. -* Validate external data at runtime where necessary. -* Keep authentication protocol logic in shared auth packages rather than duplicating it across frontends. - ---- - -## 15. Dependency direction - -The intended dependency direction is: - -```text -applications - │ - ├── domain-focused shared crates - ├── auth SDK crates - ├── database crate - ├── configuration - └── telemetry - -database crate - │ - ├── SQLx - └── shared primitive types - -auth middleware - │ - └── auth protocol - -auth client - │ - ├── generated RPC protocol - ├── service auth - └── auth protocol -``` - -Dependencies must not form cycles. -Applications are leaves of the dependency graph. No reusable crate may depend on an application. - ---- - -## 16. Agent modification rules - -Coding agents must follow these rules unless the task explicitly overrides them. - -### Before modifying code - -1. Identify the owning application or crate. -2. Read the closest architecture document. -3. Inspect existing patterns before creating a new abstraction. -4. Check workspace dependencies before adding a crate. -5. Determine whether a protocol or migration change is required. - -### While modifying code - -1. Do not import code from another application. -2. Do not add SQLx outside `crates/database`. -3. Do not expose raw database handles. -4. Do not bypass audience validation. -5. Do not log credentials or tokens. -6. Do not add deployment-specific infrastructure without an explicit decision. -7. Do not modify generated code manually. -8. Do not place business logic in generic utility crates. -9. Do not create a shared crate for code used by only one application. -10. Keep public APIs smaller than internal APIs. - -### After modifying code - -1. Run formatting. -2. Run linting. -3. Run affected tests. -4. Run workspace checks when practical. -5. Update protocol fixtures after protocol changes. -6. Update SQLx metadata after checked-query changes. -7. Add or update migrations for schema changes. -8. Update documentation when an architectural rule changes. - -### The `plans` directory - -This directory contains active plans that agents are working on (writing or -implementing). It should not contain any deployed code or configuration. - ---- - -## 17. Prohibited patterns - -The following patterns are not allowed without an explicit architectural decision: - -```text -apps/admin-api importing apps/auth-service -apps/piquel-api importing apps/admin-api -SQLx as an application dependency -Returning PgPool from crates/database -Returning sqlx::Error from crates/database -Raw SQL embedded in application code -Frontends calling internal gRPC APIs -Browser bundles containing service credentials -Universal JWT audiences -Disabling JWT expiry validation -Disabling JWT audience validation -Using display names or usernames as foreign keys -Adding speculative deployment infrastructure -Creating a miscellaneous shared-utils crate -``` - ---- - -## 18. Adding a new application - -Before adding a new application under `apps/`, document: -* Its user-facing or internal purpose -* Its deployment boundary -* Its data ownership -* Its authentication model -* Which shared crates it requires -* Whether it requires new database repositories -* Whether it requires new public or internal protocols - -A new application should be independently buildable and testable. -Do not create a separate application merely to split code that belongs in one process. - ---- - -## 19. Adding a new shared crate - -Create a new shared crate only when: -* At least two consumers require the functionality, or -* It represents a critical boundary worth isolating, such as database access or authentication middleware - -The crate must have: -* A single clear purpose -* A documented public API -* No dependency on applications -* Typed errors -* Tests for public behavior - -Avoid generic names such as: -```text -common -shared -utils -helpers -``` - -Prefer names that describe responsibility. - ---- - -## 20. Guiding principle - -The repository is a monorepo for coordinated development, not permission to ignore architectural boundaries. - -The central rule is: -> Share infrastructure and stable interfaces deliberately, while keeping domain ownership explicit. - -Contributors should prefer clear dependencies, typed APIs, and explicit ownership over shortcuts that create hidden coupling. +# Monorepo boundaries + +This repository contains piquel.fr and its services. The current implemented scope +is authentication and the piquel.fr account settings frontend. + +| Location | Responsibility | +| --- | --- | +| `apps/auth-service` | Rust auth authority, browser ceremonies, social adapters, OIDC, settings API, CLI | +| `apps/auth-web` | Static SvelteKit auth pages embedded by the Rust build | +| `apps/piquel-web` | Static SvelteKit account settings calling the auth API | +| `packages/browser` | Shared browser API/WebAuthn helpers and presentation styles | +| `crates/database` | PostgreSQL connections, migrations and typed persistence operations | +| `crates/auth-protocol` | Shared identity/session/token IDs and authentication enums | +| `crates/configuration` | URL and redacted secret-reference validation | +| `crates/telemetry` | Tracing initialization | + +Only the database crate accesses SQLx. Auth-service owns authentication policy; +frontends never receive database credentials or provider secrets. Add new crates +only when another actual consumer needs them. + +The auth runtime is one executable and one HTTP listener. Login assets are built +before Rust and embedded in the executable. Account settings remain on piquel.fr; +its exact origin can call the public auth API with the auth host's cookie. Passkey +operations redirect to auth.piquel.fr. The permanent WebAuthn RP ID is the auth +hostname, never a wildcard over piquel.fr subdomains. + +The auth binary also runs explicit migrations and generates invitations. PostgreSQL +stores sessions, WebAuthn challenges, OAuth state, pending social identities, +invitations, consent, refresh tokens, rate limits and security audit records. +No separate cache, RPC service, Node server, event bus or key-management service is +required. External applications consume standard OIDC with static client registration. + +The accepted release scope is in [plans/auth/README.md](../../plans/auth/README.md). +Build/configuration and testing instructions are in the root README. Deployment, +infrastructure, public application registration, SDKs and account recovery are +outside this release. diff --git a/justfile b/justfile index 3be8a612d..7758891c9 100644 --- a/justfile +++ b/justfile @@ -1,25 +1,29 @@ +# Build browser assets before compiling the single auth executable. +build: + pnpm build + cargo build --release -p auth-service + format: - @cargo fmt --all + cargo fmt --all lint: - @cargo clippy --workspace + cargo clippy --workspace --all-targets + pnpm check check: - @cargo check --workspace --all-targets + cargo check --workspace --all-targets test: - @cargo nextest run --workspace + cargo nextest run --workspace +# TEST_DATABASE_URL must identify a disposable local database. test-database: - @echo "No test database is configured; database tests will not run." - -doc-test: - @cargo test --doc --workspace + test -n "${TEST_DATABASE_URL:?Set a disposable TEST_DATABASE_URL}" + cargo nextest run -p auth-service -p piquel-repository --run-ignored all migrate: - @cargo run -p piquel-repository --bin migrate - -prepare-sqlx: - @cargo sqlx prepare --workspace + cargo run -p auth-service -- migrate -validate: lint check test test-database doc-test +audit: + cargo deny check advisories licenses + pnpm audit diff --git a/package.json b/package.json new file mode 100644 index 000000000..6ea8e71e2 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "piquel-fr", + "private": true, + "packageManager": "pnpm@11.25.0", + "scripts": { + "build": "pnpm -r build", + "check": "pnpm -r check", + "test:browser": "playwright test" + }, + "devDependencies": { + "@playwright/test": "1.63.0" + } +} diff --git a/packages/browser/package.json b/packages/browser/package.json new file mode 100644 index 000000000..d26ef5334 --- /dev/null +++ b/packages/browser/package.json @@ -0,0 +1,7 @@ +{ + "name": "@piquel/browser", + "private": true, + "version": "0.1.0", + "type": "module", + "exports": { ".": "./src/index.ts", "./style.css": "./src/style.css" } +} diff --git a/packages/browser/src/index.ts b/packages/browser/src/index.ts new file mode 100644 index 000000000..f49984dbc --- /dev/null +++ b/packages/browser/src/index.ts @@ -0,0 +1,76 @@ +export type Provider = 'github' | 'google'; +export type PasskeyKind = 'standard' | 'google_password_manager'; +export type Session = { user: { id: string; username: string; display_name: string }; management_expires_at: string | null }; +export type Configuration = { settings_url: string; providers: Provider[]; invite_required: boolean }; +export const providerName = (provider: Provider) => provider === 'github' ? 'GitHub' : 'Google'; + +/** The auth cookie remains HttpOnly on the auth host, including for settings requests. */ +export class AuthApi { + constructor(readonly origin = '') {} + async request(path: string, method = 'GET', body?: unknown): Promise { + const response = await fetch(`${this.origin}${path}`, { + method, credentials: 'include', + headers: method === 'GET' ? {} : { 'content-type': 'application/json', 'x-piquel-csrf': '1' }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) + }); + if (!response.ok) { + const problem: unknown = await response.json().catch(() => null); + const message = problem && typeof problem === 'object' && 'error' in problem && typeof problem.error === 'string' ? problem.error : null; + const protocolErrors: Record = { + invalid_request: 'This sign-in request is invalid or expired. Start again from the application.', + access_denied: 'Sign-in was cancelled or access was declined.', + login_required: 'Please sign in again.', + consent_required: 'Review the application’s requested access to continue.', + server_error: 'Sign-in is temporarily unavailable. Please try again.', + temporarily_unavailable: 'Sign-in is temporarily unavailable. Please try again.' + }; + throw new Error(response.status === 401 ? 'Please sign in again.' : response.status === 429 ? 'Too many attempts. Wait a moment and try again.' : message ? protocolErrors[message] ?? message : 'This action could not be completed. Please try again.'); + } + return response.status === 204 ? undefined as T : response.json(); + } + async form(path: string, body: URLSearchParams): Promise<{ redirect_url: string }> { + const response = await fetch(`${this.origin}${path}`, { method: 'POST', credentials: 'include', headers: { 'x-piquel-csrf': '1' }, body }); + if (!response.ok) throw new Error('This request has expired. Please start again.'); + return response.json(); + } +} + +type EncodedDescriptor = Omit & { id: string }; +type CreationOptions = Omit & { challenge: string; user: Omit & { id: string }; excludeCredentials?: EncodedDescriptor[] }; +type RequestOptions = Omit & { challenge: string; allowCredentials?: EncodedDescriptor[] }; +type Ceremony = { ceremony_id: string; public_key: { publicKey: T } }; +function decode(value: string): ArrayBuffer { return Uint8Array.from(atob(value.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)).buffer; } +function encode(value: ArrayBuffer): string { return btoa(String.fromCharCode(...new Uint8Array(value))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } +function descriptor(value: EncodedDescriptor): PublicKeyCredentialDescriptor { return { ...value, id: decode(value.id) }; } +export function passkeysAvailable(): boolean { return typeof window !== 'undefined' && window.isSecureContext && 'PublicKeyCredential' in window; } + +/** All ceremonies run on the auth origin; serialized WebAuthn wrappers contain publicKey. */ +export class Passkeys { + constructor(readonly api: AuthApi) {} + async authenticate(username?: string, manage = false): Promise { + const path = manage ? '/account/passkeys/authorize' : '/webauthn/authenticate'; + const start = await this.api.request>(`${path}/start`, 'POST', username ? { username } : {}); + const options = start.public_key.publicKey; + const credential = await navigator.credentials.get({ publicKey: { ...options, challenge: decode(options.challenge), allowCredentials: options.allowCredentials?.map(descriptor) } }) as PublicKeyCredential | null; + if (!credential) throw new Error('Passkey verification was cancelled.'); + const response = credential.response as AuthenticatorAssertionResponse; + await this.api.request(`${path}/finish`, 'POST', { ceremony_id: start.ceremony_id, credential: { id: credential.id, rawId: encode(credential.rawId), type: credential.type, response: { authenticatorData: encode(response.authenticatorData), clientDataJSON: encode(response.clientDataJSON), signature: encode(response.signature), userHandle: response.userHandle ? encode(response.userHandle) : null }, clientExtensionResults: credential.getClientExtensionResults() } }); + } + async register(friendlyName: string, account?: { username: string; invitation?: string }, kind: PasskeyKind = 'standard'): Promise { + const path = account ? '/webauthn/register' : '/account/passkeys/enroll'; + const start = await this.api.request>(`${path}/start`, 'POST', { ...account, passkey_kind: kind }); + const options = start.public_key.publicKey; + const credential = await navigator.credentials.create({ publicKey: { ...options, challenge: decode(options.challenge), user: { ...options.user, id: decode(options.user.id) }, excludeCredentials: options.excludeCredentials?.map(descriptor) } }) as PublicKeyCredential | null; + if (!credential) throw new Error('Passkey creation was cancelled.'); + const response = credential.response as AuthenticatorAttestationResponse; + await this.api.request(`${path}/finish`, 'POST', { ceremony_id: start.ceremony_id, friendly_name: friendlyName, credential: { id: credential.id, rawId: encode(credential.rawId), type: credential.type, response: { attestationObject: encode(response.attestationObject), clientDataJSON: encode(response.clientDataJSON), transports: response.getTransports() }, clientExtensionResults: credential.getClientExtensionResults() } }); + } +} + +export function errorMessage(error: unknown): string { return error instanceof DOMException ? 'The passkey request was cancelled or unavailable. Try again or use another device.' : error instanceof Error ? error.message : 'Something went wrong. Please try again.'; } +export function safeDestination(value: string | null, settingsUrl: string): string { + if (!value) return settingsUrl; + const candidate = new URL(value, window.location.origin); + if (candidate.origin === window.location.origin && value.startsWith('/') && !value.startsWith('//')) return candidate.href; + return candidate.href === new URL(settingsUrl).href ? candidate.href : settingsUrl; +} diff --git a/packages/browser/src/style.css b/packages/browser/src/style.css new file mode 100644 index 000000000..7fca7533e --- /dev/null +++ b/packages/browser/src/style.css @@ -0,0 +1,2 @@ +:root{font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#182e29;background:#f5f6f0;font-synthesis:none;font-weight:400;--green:#184f40;--muted:#596b62;--line:#dce2d8} +*{box-sizing:border-box}body{margin:0}a{color:var(--green);text-underline-offset:3px}button,input{font:inherit}button,a,input{touch-action:manipulation}button:focus-visible,a:focus-visible,input:focus-visible{outline:3px solid #ab7900;outline-offset:4px}button,.button{display:inline-flex;justify-content:center;align-items:center;gap:.5rem;background:var(--green);color:white;border:1px solid var(--green);border-radius:9px;min-height:46px;padding:.7rem 1.1rem;font-weight:600;cursor:pointer;text-decoration:none}button:hover,.button:hover{filter:brightness(1.12)}button:disabled{opacity:.55;cursor:wait}.secondary{color:var(--green);background:white;border-color:#b7c5b8}.danger{color:#a1252b;background:white;border-color:#d7adb0}.text-button{background:none;color:var(--green);border-color:transparent;padding:.3rem;min-height:36px;font-size:.9rem}input{width:100%;min-height:46px;border:1px solid #a9b8aa;border-radius:8px;padding:.7rem .8rem;background:#fff;color:inherit}label{display:grid;gap:.45rem;font-size:.9rem;font-weight:600}form,.stack{display:grid;gap:1rem}.row{display:flex;align-items:center;gap:.7rem;flex-wrap:wrap}.between{justify-content:space-between}h1{font-size:clamp(2rem,6vw,2.9rem);letter-spacing:-.055em;line-height:1.08;font-weight:600;margin:.6rem 0 1rem}h2{font-size:1.15rem;letter-spacing:-.02em;margin:0}p{line-height:1.6;margin:.6rem 0;color:var(--muted)}.eyebrow{font-size:.75rem;letter-spacing:.15em;text-transform:uppercase;font-weight:700;color:var(--green)}.card{background:#fff;border:1px solid var(--line);border-radius:14px;padding:1.4rem}.notice{border-radius:9px;background:#edf2e8;border:1px solid #d5e0cb;padding:.9rem 1rem;font-size:.9rem}.error{border-color:#e5b8b8;color:#86272b;background:#fff1f0}.muted,.help{font-size:.88rem;color:var(--muted)}.divider{display:flex;align-items:center;gap:1rem;color:#718074;font-size:.8rem;margin:.3rem 0}.divider:before,.divider:after{content:"";height:1px;flex:1;background:var(--line)}.brand{display:inline-flex;align-items:center;gap:.65rem;text-decoration:none;color:#182e29;font-size:1.1rem;font-weight:750;letter-spacing:-.04em}.mark{display:grid;place-items:center;width:29px;height:29px;background:var(--green);color:white;border-radius:8px;font-size:20px}.shell{max-width:1080px;margin:auto;padding:2rem 1.3rem}.auth-shell{max-width:460px;margin:clamp(2rem,9vh,6rem) auto 3rem}.auth-shell footer{margin-top:2rem;border-top:1px solid var(--line);padding-top:1rem}.full{width:100%}.badge{font-size:.75rem;border-radius:20px;padding:.3rem .65rem;color:var(--green);background:#e9f0e4}.list{list-style:none;padding:0;margin:0}.list>li{padding:1.15rem 0;border-bottom:1px solid var(--line)}.list>li:last-child{border:0}.settings{max-width:760px;margin:3rem auto}.settings-header{margin-bottom:2rem}.settings .card{margin:1rem 0}.empty{padding:1rem 0}small{font-size:.78rem;color:var(--muted)}@media(max-width:520px){.shell{padding:1.3rem 1rem}.card{padding:1.1rem}.auth-shell{margin-top:2rem}.row.actions>*{flex:1}.settings{margin-top:2rem}} diff --git a/plans/auth.md b/plans/auth.md deleted file mode 100644 index fe082417e..000000000 --- a/plans/auth.md +++ /dev/null @@ -1,1641 +0,0 @@ -# Piquel Authentication Service -## Architecture and Technical Design Specification -**Status:** Draft -**Version:** 0.1 -**Scope:** First production iteration -## 1. Executive summary -Piquel Auth is a centralized identity and authentication platform shared by multiple independent Piquel products. -A person has one global Piquel account. That account can be used to authenticate with any Piquel product, while each product remains operationally and logically independent. - -Piquel Auth provides: -- Passkey authentication -- Federated authentication through approved external identity providers -- OpenID Connect and OAuth-compatible public endpoints -- Short-lived, audience-restricted access tokens -- Rotating, centrally revocable refresh tokens -- Central account and session management -- A private RPC API for trusted downstream services -- Service-to-auth-service authentication -- Rust SDKs for token validation and protocol integration -- An internal event log for future event broadcasting - -Piquel Auth is deployed as one stateless application process that can run as multiple replicas. PostgreSQL is the authoritative state store. Redis may be used for disposable coordination, rate limiting, and short-lived state. - -Downstream products: -- Store only the global Piquel user ID as their identity reference -- Validate access tokens locally -- Own their product-specific permissions and data -- Own credentials for product-specific external integrations -- Use the Piquel SDK for authentication integration - -The first iteration intentionally excludes cross-product service delegation, a distributed user-event system, deletion orchestration, TOTP, and centrally stored external API credentials. -## 2. Goals -### 2.1 Global identity -Every person has one Piquel account with one immutable user ID. -The same account can be used across all Piquel products. -A user may authenticate through any supported authentication method linked to the account. -### 2.2 Independent products -Each product remains independent. -Products do not call one another and do not exchange user tokens with one another. -Each product: -- Has its own client registration -- Has its own API audience -- Receives its own access tokens -- Receives its own refresh-token families -- Owns its own application data -- Owns its own product authorization model -### 2.3 Centralized authentication -Piquel Auth owns: -- Accounts -- Verified email addresses -- Usernames and display names -- Passkeys -- Federated login identities -- Login sessions -- Refresh tokens -- OIDC client registrations -- Service identities -- Signing keys -- Authentication audit information - -Downstream products must not store: -- Passkey credentials -- Piquel refresh tokens -- Social-login credentials used to authenticate a Piquel account -- Piquel session cookies -- Authentication secrets belonging to another product -### 2.4 Low-latency request authentication -Ordinary product API requests must not require a network call to Piquel Auth. -Products validate short-lived access JWTs locally using cached public signing keys. -### 2.5 Strong product isolation -An access token issued for one product API must not be accepted by another product API. -Audience validation is mandatory. -### 2.6 Easy integration -A first-party Rust SDK provides: -- Login-flow helpers -- Callback validation -- Token refresh handling -- JWT validation -- Web-framework middleware -- Internal RPC clients -- Service-token management -- Helpers for product-owned OAuth integrations -## 3. Non-goals for the first iteration -The following capabilities are explicitly outside the initial scope: -- TOTP or authenticator-app codes -- Cross-product service-to-service delegation -- OAuth Token Exchange between products -- A centralized vault for product-specific GitHub, Google, or similar credentials -- A production event broker -- Guaranteed user-event delivery to downstream products -- Distributed account-deletion orchestration -- Pairwise or product-specific Piquel identities -- Third-party developer registration -- Dynamic client registration -- Risk-based authentication -- Automatic fraud detection -- Enterprise identity federation -- Organization-level identity administration -The initial internal event log must be designed so that reliable event broadcasting can be added later. -## 4. System context -```text - Public clients - Web, native, desktop, CLI - │ - │ OIDC / OAuth / account APIs - ▼ - ┌─────────────────────────┐ - │ Piquel Auth │ - │ │ - │ Passkeys │ - │ Social login │ - │ OIDC authorization │ - │ Token issuance │ - │ Session management │ - │ Internal RPC API │ - │ Internal event log │ - └────────────┬────────────┘ - │ - ┌────────────────┼─────────────────┐ - ▼ ▼ ▼ - PostgreSQL Redis Key-management system - authoritative data disposable signing and encryption - state - - ▲ - │ authenticated internal RPC - ┌─────────────────┼──────────────────┐ - │ │ │ - Product A API Product B API Product C API - │ │ │ - └──── independently validate JWTs ──┘ -``` -Piquel Auth is one deployable executable. -Its internal modules are code boundaries rather than independently deployed services. -## 5. Internal module structure -The Piquel Auth process should be organized into modules with explicit ownership boundaries. -```text -account -email -passkey -federation -session -oidc -token -service_identity -internal_rpc -event_log -audit -administration -storage -crypto -``` -### 5.1 Account module -Owns: -- Global users -- Username -- Display name -- Account status -- Account creation and disabling -- Profile versions -### 5.2 Email module -Owns: -- Email normalization -- Verification status -- Primary email selection -- Unique verified-email constraints -### 5.3 Passkey module -Owns: -- WebAuthn registration ceremonies -- WebAuthn authentication ceremonies -- Stored public-key credentials -- Credential metadata -- Passkey addition and removal -### 5.4 Federation module -Owns: -- Social-login initiation -- Provider callback validation -- External issuer and subject mappings -- Email-based automatic account linking -- Provider metadata -### 5.5 Session module -Owns: -- Central Piquel login sessions -- Product-specific authorization sessions -- Session revocation -- Authentication timestamps -- Authentication methods -### 5.6 OIDC module -Owns: -- Authorization endpoint -- Token endpoint -- UserInfo endpoint -- Discovery metadata -- OIDC client validation -- Redirect URI validation -- Authorization Code flow -- PKCE -- State and nonce processing -### 5.7 Token module -Owns: -- Access-token issuance -- ID-token issuance -- Refresh-token issuance -- Refresh-token rotation -- Refresh-token replay detection -- Signing-key selection -- Token revocation -### 5.8 Service identity module -Owns: -- Downstream service registrations -- Service public keys -- Service assertion verification -- Short-lived internal service tokens -- Internal RPC permissions -### 5.9 Internal RPC module -Owns: -- Private service-facing APIs -- Service authentication middleware -- Method-level authorization -- Request deadlines and limits -### 5.10 Event-log module -Owns: -- Append-only internal domain events -- Aggregate sequence numbers -- Event schema versions -- Future publication metadata -### 5.11 Audit module -Owns: -- Authentication security events -- Administrative actions -- Session changes -- Credential changes -- Social identity linking -The security audit log is separate from the future integration event stream. -## 6. Identity model -### 6.1 Global user ID -Every account has one immutable identifier. -UUIDv7 is recommended. - -The precise representation may differ, but it must be: -- Globally unique -- Immutable -- Never reassigned -- Unrelated to email, username, or provider identity -- Suitable for storage by downstream services -The global user ID is exposed as the OIDC `sub` claim. -### 6.2 Mutable profile fields -The central profile initially contains: -- User ID -- Username -- Display name -- Verified email addresses -- Primary email address -- Profile version -- Account status -- Created timestamp -- Updated timestamp -A downstream product must never use username, display name, or email as a database identity key. -Only the global user ID is authoritative for identity references. -### 6.3 Profile version -Each user has a monotonically increasing `profile_version`. -It is incremented whenever token-visible profile data changes, including: -- Username -- Display name -- Primary email, if later included in tokens -- Other future token-visible fields -The access token includes the current profile version. -Products may use it to detect that locally cached presentation data is stale. -## 7. Authentication methods -Piquel Auth supports two authentication categories: -1. Piquel passkeys -2. Approved social identity providers -TOTP is not supported. -### 7.1 Passkeys -Passkeys are implemented using WebAuthn. -The Piquel authentication domain is the WebAuthn relying party. -```text -auth.piquel.fr -``` - -Stored passkey information includes: -```text -credential_id -user_id -public_key -signature_counter -transports -backup_eligible -backup_state -friendly_name -created_at -last_used_at -``` -Private keys never reach Piquel Auth. -Passkey operations include: -- Register passkey -- Authenticate with passkey -- List registered passkeys -- Rename passkey -- Remove passkey -### 7.2 Social login -Approved providers may be used as complete authentication methods. -Examples may include: -- Google -- GitHub -- Apple -- Microsoft -The provider configuration is controlled by Piquel Auth. -Each provider identity is stored using: -```text -issuer -subject -user_id -provider_name -linked_email -created_at -last_used_at -``` - -The permanent identity key is: -```text -(issuer, subject) -``` -Email is used only during initial account matching. -### 7.3 Automatic email-based linking -For the first iteration, a new social identity is automatically linked to an existing Piquel account when the provider supplies an email matching an existing account. -The flow is: -1. Validate the external provider response. -2. Obtain the stable provider issuer and subject. -3. Obtain an email that the provider declares verified. -4. Look up an existing identity by `(issuer, subject)`. -5. If found, authenticate the linked Piquel account. -6. Otherwise, normalize the verified email. -7. Look up an existing Piquel account with that verified normalized email. -8. If found, link the new provider identity to that account. -9. Otherwise, create a new Piquel account. -10. Record a security audit event. -After linking, future authentication uses `(issuer, subject)`, not email. -Automatic linking must not occur when: -- The provider does not assert that the email is verified -- No usable email is returned -- Multiple accounts match because of inconsistent legacy data -- The provider is not explicitly approved for automatic linking -Email normalization must be conservative. - -It may include: -- Unicode normalization where appropriate -- Domain-name case normalization -- Local-part handling consistent with the system’s documented email policy - -It must not: -- Remove plus-address suffixes -- Remove dots from Gmail addresses -- Apply provider-specific mailbox transformations -- Guess that two different addresses are equivalent -### 7.4 Social login and passkey recovery -For the first iteration, a fresh social login is considered sufficient to regain full account access, including passkey management. -This means a social login may be used to: -- View passkey metadata -- Register a passkey -- Remove a passkey -- Recover an account without an existing passkey -After social authentication, the interface should recommend registering a passkey. -Passkey registration is not mandatory. -This is an explicitly accepted first-iteration security trade-off. The architecture must make it possible to introduce stronger assurance requirements later without changing account identifiers or provider mappings. -## 8. Public protocol surface -The public API remains standards-oriented and HTTP-based. -### 8.1 Required endpoints -```text -GET /.well-known/openid-configuration -GET /.well-known/jwks.json - -GET /oauth/authorize -POST /oauth/token -POST /oauth/revoke -GET /oidc/userinfo -GET /oidc/logout - -POST /webauthn/register/start -POST /webauthn/register/finish -POST /webauthn/authenticate/start -POST /webauthn/authenticate/finish - -GET /login/{provider} -GET /login/{provider}/callback -``` -Exact paths may change, but discovery metadata must remain authoritative. -### 8.2 Supported authorization flow -The primary flow is: -```text -Authorization Code with PKCE -``` -PKCE is required for all clients. -The authorization request must validate: -- Registered client ID -- Exact redirect URI -- Response type -- Requested scopes -- Requested audience or resource -- PKCE challenge -- State -- Nonce when required -- Prompt and login requirements -- Maximum authentication age when requested -### 8.3 Client registration -Each product client has a static administrative registration. -A registration includes: -```text -client_id -display_name -application_type -allowed_redirect_uris -allowed_post_logout_redirect_uris -allowed_scopes -allowed_audiences -token_endpoint_auth_method -access_token_lifetime -refresh_token_policy -enabled -``` -Dynamic client registration is not supported in the first iteration. -## 9. Token architecture -Piquel Auth issues three user-related token types: -1. ID token -2. Access token -3. Refresh token -A fourth short-lived token may be issued for purpose-bound sensitive operations. -## 10. ID token -The ID token is an OIDC token intended for the application client. -It describes: -- The authenticated account -- The authentication event -- The intended client -- The authentication time -- The methods used - -It must not be used as an API access token. -Representative claims: -```json -{ - "iss": "https://auth.piquel.example", - "sub": "0198a346-1e13-7d91-bf85-15d90f7e2885", - "aud": "product-a-web", - "nonce": "client-generated-nonce", - "name": "Piquel Chips", - "preferred_username": "piquel", - "amr": ["passkey"], - "auth_time": 1783771200, - "iat": 1783771200, - "exp": 1783771500 -} -``` -## 11. Access token -### 11.1 Purpose -The access token authenticates a user to one specific product API. -It is: -- A signed JWT -- Short-lived -- Validated locally -- Restricted to an audience -- Not centrally introspected during ordinary requests -### 11.2 Lifetime -The default lifetime is: `5 minutes` -Individual clients may receive a stricter lifetime, but products must not configure a longer lifetime without an explicit security decision. -### 11.3 Representative claims -```json -{ - "iss": "https://auth.piquel.example", - "sub": "0198a346-1e13-7d91-bf85-15d90f7e2885", - "aud": "product-a-api", - "client_id": "product-a-web", - "sid": "ses_0198a34d", - "jti": "at_0198a351", - - "username": "piquel", - "name": "Piquel Chips", - "profile_version": 12, - - "amr": ["passkey"], - "auth_time": 1783771200, - - "iat": 1783771200, - "nbf": 1783771200, - "exp": 1783771500 -} -``` -### 11.4 JWT header -```json -{ - "typ": "at+jwt", - "alg": "ES256", - "kid": "signing-key-2026-07" -} -``` -Only explicitly approved asymmetric algorithms are accepted. -Symmetric JWT signing must not be used between Piquel Auth and downstream products. -### 11.5 Embedded profile information -The access token includes: -- User ID -- Username -- Display name -- Profile version -This allows products to render common user-interface elements without querying Piquel Auth on every page load. -These claims are snapshots. -They may remain stale for the remainder of the token lifetime. -Products must not use username or display name for: -- Authorization decisions -- Database ownership -- Unique identity constraints -- Permanent references -Only `sub` is the stable user identity. -### 11.6 Audience isolation -Every product API has a unique audience. -Examples: -```text -product-a-api -product-b-api -product-c-api -``` -A Product A API token must be rejected by Product B regardless of whether its signature and expiry are valid. -Audience validation is mandatory and cannot be disabled in production SDK middleware. -### 11.7 Required validation -A resource server must validate: -- Token presence -- Token structure -- `typ` -- Allowed signing algorithm -- Signature -- Known signing key -- Exact issuer -- Expected audience -- Subject format -- Issued-at time -- Not-before time -- Expiry -- Required claims -- Configured clock tolerance -A valid signature alone is never sufficient. -## 12. Refresh token -### 12.1 Purpose -A refresh token continues a product-specific user session. -It is used to obtain: -- A new access token -- A new ID token when appropriate -- A replacement refresh token -It may also be used to identify the session that is requesting the beginning of a sensitive-operation flow. -It must not directly authorize a sensitive account mutation. -### 12.2 Representation -The refresh token is an opaque, high-entropy random credential. -It is not a JWT. -It contains no client-readable user information. -Conceptually, the server-side record identifies the user, client, session, and token family. -Example wire representation: -```text -prt_v1_. -``` -The database stores: -- An indexed token identifier -- A cryptographic hash or keyed digest of the secret -- Server-side metadata -The raw refresh token is never stored. -### 12.3 Server-side record -```text -refresh_tokens --------------- -id -token_id -secret_digest -token_family_id -user_id -client_id -session_id -allowed_audience -granted_scopes -created_at -expires_at -last_used_at -rotated_from_id -consumed_at -revoked_at -revocation_reason -``` -### 12.4 Product and device isolation -Refresh-token families are specific to: -- User -- Product client -- Device or installation -- Login session - -Example: -```text -User -├── Product A / laptop / family A1 -├── Product A / phone / family A2 -├── Product B / laptop / family B1 -└── Product C / CLI / family C1 -``` -Revoking one family does not revoke unrelated product sessions. -### 12.5 Rotation -Every successful refresh rotates the token. -The transaction must: -1. Lock or atomically consume the current token. -2. Verify that it is active. -3. Mark it consumed. -4. Create a replacement token in the same family. -5. Issue a new access token. -6. Commit all changes atomically. -7. Return the replacement refresh token. -### 12.6 Replay detection -If an already consumed refresh token is presented again: -1. Treat the event as possible credential theft. -2. Revoke the complete refresh-token family. -3. Record a security event. -4. Reject the request. -5. Optionally notify the user. -### 12.7 Revocation -Refresh tokens may be revoked by: -- Explicit product logout -- Global logout -- User session management -- Account disabling -- Passwordless credential changes where policy requires it -- Replay detection -- Administrative action -- Security incident response -Revocation is immediate at Piquel Auth. -A previously issued access JWT may remain valid until its expiry, subject to its five-minute maximum lifetime. -### 12.8 Refresh-token security classification -A refresh token is a high-value credential. -Immediate revocability does not make theft harmless. An attacker may use a stolen token before its theft is detected. -Refresh tokens must therefore receive stronger storage protection than access tokens. - -For browser applications: -- Prefer a backend-for-frontend architecture. -- Store refresh tokens server-side where possible. -- Otherwise use a Secure, HttpOnly, SameSite cookie. -- Never expose refresh tokens to JavaScript. -- Never store refresh tokens in `localStorage`. - -For native applications: -- Use operating-system secure credential storage. -- Bind sessions to the application client. -- Use PKCE. -## 13. Sensitive operations -Sensitive operations include: -- Adding or removing passkeys -- Changing the primary email -- Linking or unlinking a social login -- Revoking all sessions -- Deleting an account -- Exporting sensitive account information -- Changing security-critical profile settings -A refresh token may establish which session is requesting the operation, but it does not directly approve the mutation. -### 13.1 Flow -1. The client requests a sensitive operation. -2. Piquel Auth checks the current product session. -3. Piquel Auth requires fresh authentication. -4. The user authenticates with a passkey or approved social provider. -5. Piquel Auth issues a short-lived purpose-bound authorization token. -6. The client submits the mutation with that token. -7. Piquel Auth validates the token’s audience, purpose, expiry, and user. -8. The mutation is performed. -9. The token may be marked used where single-use behavior is required. -### 13.2 Purpose token -Example: -```json -{ - "iss": "https://auth.piquel.example", - "sub": "0198a346-1e13-7d91-bf85-15d90f7e2885", - "aud": "piquel-account-management", - "purpose": "manage-passkeys", - "sid": "ses_0198a34d", - "auth_time": 1783771400, - "iat": 1783771400, - "exp": 1783771520, - "jti": "step_0198a360" -} -``` -Recommended lifetime: -```text -2 minutes -``` -Under the first-iteration policy, either a fresh passkey authentication or a fresh approved social login satisfies the operation. -## 14. Sessions and single sign-on -Piquel Auth maintains a central login session. -When a user visits a second Piquel product: -1. The product redirects the user to Piquel Auth. -2. Piquel Auth detects the existing central session. -3. Piquel Auth evaluates the new client request. -4. Piquel Auth issues a new authorization code. -5. The new product exchanges it for its own tokens. -6. The user does not need to authenticate again unless policy requires it. -The products do not share refresh tokens. -The products do not accept one another’s access tokens. -Single sign-on is achieved through the central Piquel browser session, not through universal bearer credentials. -## 15. Downstream product model -Each product stores the Piquel user ID on domain records. -Example: -```text -projects --------- -id -owner_user_id -name -created_at -``` -The product owns: -- Product roles -- Product permissions -- Product resources -- Product settings -- Product billing -- Product onboarding -- Product-specific OAuth credentials -- Product-specific audit records -Piquel Auth does not decide whether a user may edit a particular product resource. -Piquel Auth proves who the user is. The product decides what that user may do. -## 16. Internal API architecture -### 16.1 Protocol choice -The private service API should use RPC. -The recommended first implementation is: -```text -gRPC over HTTP/2 -Protocol Buffers -Rust Tonic client and server -``` -RPC is suitable because the private API: -- Is consumed by controlled first-party services -- Benefits from generated typed clients -- Has a relatively small number of explicit operations -- Requires strict request and response schemas -- Needs deadlines and structured errors -- Does not need browser compatibility -- Can evolve through versioned Protobuf packages -Public OIDC and OAuth endpoints remain HTTP-based. -### 16.2 Network boundary -The internal RPC server must: -- Listen on a separate port or listener -- Be inaccessible from the public internet -- Require TLS -- Require an authenticated service identity -- Enforce method-specific permissions -- Enforce request deadlines -- Enforce message-size limits -- Avoid exposing gRPC reflection publicly in production -Private networking is an additional control, not a substitute for authentication. -### 16.3 Initial RPC surface -```protobuf -syntax = "proto3"; - -package piquel.auth.v1; - -service AuthService { - rpc GetUser(GetUserRequest) - returns (GetUserResponse); - - rpc BatchGetUsers(BatchGetUsersRequest) - returns (BatchGetUsersResponse); - - rpc GetSessionStatus(GetSessionStatusRequest) - returns (GetSessionStatusResponse); - - rpc RevokeSession(RevokeSessionRequest) - returns (RevokeSessionResponse); - - rpc RevokeAllUserSessions(RevokeAllUserSessionsRequest) - returns (RevokeAllUserSessionsResponse); - - rpc GetServiceConfiguration(GetServiceConfigurationRequest) - returns (GetServiceConfigurationResponse); -} -``` - -Potential later methods: -```protobuf -rpc DisableUser(DisableUserRequest) - returns (DisableUserResponse); - -rpc GetProfileVersion(GetProfileVersionRequest) - returns (GetProfileVersionResponse); - -rpc ConfirmSensitiveOperation(ConfirmSensitiveOperationRequest) - returns (ConfirmSensitiveOperationResponse); -``` -### 16.4 RPC non-goals -The RPC service should not be called for every product request. -It should not provide a general `ValidateAccessToken` method for normal JWT validation. -Local JWT validation remains the ordinary request path. -RPC is used for operations requiring authoritative current state, such as: -- Reading the latest central profile -- Batch-resolving users -- Checking session status -- Revoking sessions -- Administrative account changes -## 17. Service-level authentication -The user’s access token authenticates the user. -A separate service credential authenticates the downstream product backend. -These identities must not be conflated. -### 17.1 Service registration -Each backend has a service identity: -```text -service_id -display_name -public_keys -allowed_rpc_methods -allowed_user_data_fields -enabled -created_at -``` - -Example: -```text -svc_product_a_backend -``` -### 17.2 Service credential -The service owns an asymmetric private key. -Piquel Auth stores only the corresponding public key. -At runtime: -1. The service creates a short-lived signed client assertion. -2. It sends the assertion to the internal service-token endpoint. -3. Piquel Auth verifies the signature and service registration. -4. Piquel Auth issues a short-lived service JWT. -5. The SDK caches the service token. -6. The SDK renews it before expiry. -7. The service token is attached to internal RPC metadata. -### 17.3 Service token -Representative claims: -```json -{ - "iss": "https://auth.piquel.example", - "sub": "svc_product_a_backend", - "aud": "piquel-internal-api", - "scope": "users:read sessions:revoke", - "iat": 1783771200, - "nbf": 1783771200, - "exp": 1783771500, - "jti": "st_0198a36e" -} -``` -Recommended lifetime: -```text -5 minutes -``` -### 17.4 Service-token management -The SDK is responsible for: -- Creating signed service assertions -- Obtaining service tokens -- Caching active tokens -- Refreshing before expiry -- Avoiding duplicate simultaneous refreshes -- Adding the token to RPC metadata -- Retrying once after an authentication failure when safe -- Redacting tokens from logs and errors -The service-token manager must be concurrency-safe. -### 17.5 Administrative service management -Service registration and key rotation are separate administrative operations. -They are not ordinary runtime SDK calls. -Administrative capabilities include: -- Create service identity -- Add public key -- Remove public key -- Rotate key -- Disable service -- Configure RPC permissions -- Review service audit history -## 18. Rust SDK architecture -The SDK should be divided into focused crates or modules. -Recommended structure: -```text -piquel-auth-core -piquel-auth-client -piquel-auth-middleware -piquel-auth-rpc -piquel-auth-oauth -piquel-auth-axum -``` -The exact crate split may initially be simplified, but the public API should preserve these conceptual boundaries. -### 18.1 Core crate -Provides: -- User ID type -- Client ID type -- Audience type -- Token claim types -- Validated principal type -- Error types -- Shared configuration types -### 18.2 Application client -Provides: -- OIDC discovery loading -- Authorization URL construction -- State generation -- Nonce generation -- PKCE generation -- Callback processing -- Code exchange -- Refresh -- Logout -- Current-user extraction -### 18.3 RPC client -Provides generated or wrapped gRPC clients. -It automatically integrates with the service-token manager. -### 18.4 OAuth helper module -Provides reusable primitives for product-owned external integrations: -- OAuth state creation and verification -- PKCE generation and validation -- Authorization URL construction -- Callback parsing -- Token response parsing -- Provider error normalization -- Secret redaction -- Webhook-signature primitives where appropriate - -The downstream product remains responsible for: -- Registering its external provider application -- Selecting scopes -- Persisting provider credentials -- Refreshing provider credentials -- Revoking provider access -- Product-specific consent -- Provider-specific API calls - -Piquel Auth does not store these product integration credentials. -## 19. AuthMiddleware builder -The SDK exposes an `AuthMiddleware` builder. -The builder creates a reusable request-authentication component for a specific product API. -### 19.1 Example -```rust -use std::time::Duration; - -use piquel_auth::{ - AuthMiddleware, - AuthMiddlewareError, -}; - -let auth_middleware = AuthMiddleware::builder() - .issuer("https://auth.piquel.example") - .audience("product-a-api") - .jwks_uri("https://auth.piquel.example/.well-known/jwks.json") - .allowed_algorithm("ES256") - .clock_tolerance(Duration::from_secs(30)) - .require_claim("sub") - .require_claim("sid") - .require_claim("username") - .require_claim("name") - .require_claim("profile_version") - .build() - .await?; -``` - -Framework integrations may then expose it as a layer: -```rust -use axum::{ - routing::get, - Router, -}; - -let app = Router::new() - .route("/me", get(get_current_user)) - .layer(auth_middleware.into_axum_layer()); -``` - -Alternatively, the framework-neutral authenticator may be called directly: -```rust -let principal = auth_middleware - .authenticate_request(&request) - .await?; -``` -### 19.2 Mandatory production settings -The following settings are mandatory: -- Issuer -- Audience -- Allowed signing algorithm -- JWKS source -Production construction must fail when any are missing. -Audience verification cannot be disabled. -Signature verification cannot be disabled. -Expiry verification cannot be disabled. -### 19.3 Builder options -Potential builder methods include: -```rust -AuthMiddleware::builder() - .issuer(...) - .audience(...) - .jwks_uri(...) - .allowed_algorithm(...) - .clock_tolerance(...) - .required_scope(...) - .require_claim(...) - .bearer_header(...) - .jwks_cache_ttl(...) - .http_client(...) - .on_authentication_failure(...) - .build() - .await -``` -Options intended only for tests must be gated behind explicit testing APIs or feature flags. -### 19.4 Validation sequence -The middleware performs validation in a strict sequence: -1. Read the `Authorization` header. -2. Require the `Bearer` scheme. -3. Reject multiple or malformed credentials. -4. Parse the JWT header. -5. Require `typ = at+jwt`. -6. Require an explicitly allowed algorithm. -7. Read `kid`. -8. Resolve the corresponding public key. -9. Verify the signature. -10. Parse the claims. -11. Verify the exact issuer. -12. Verify the configured audience. -13. Verify expiry. -14. Verify not-before. -15. Verify issued-at sanity. -16. Validate required claim types. -17. Validate the Piquel user ID format. -18. Construct an immutable validated principal. -### 19.5 JWKS handling -The middleware maintains an in-memory JWKS cache. -Behavior: -- Fetch keys during startup or first use. -- Respect a bounded cache lifetime. -- Refresh keys when the cache expires. -- On an unknown `kid`, perform at most one controlled refresh. -- Rate-limit unknown-key refresh attempts. -- Preserve currently valid old keys during server-side rotation. -- Fail closed when a key cannot be resolved. -- Never accept a key supplied by the JWT itself. -A malicious stream of random `kid` values must not cause unbounded calls to Piquel Auth. -### 19.6 Validated principal -The middleware returns a validated application-facing type: -```rust -#[derive(Clone, Debug)] -pub struct AuthenticatedUser { - pub user_id: UserId, - pub session_id: SessionId, - pub client_id: ClientId, - pub username: String, - pub display_name: String, - pub profile_version: u64, - pub authentication_methods: Vec, - pub authenticated_at: chrono::DateTime, -} -``` -The raw JWT should not be required by ordinary handlers. -When advanced use requires it, access to raw claims should be explicit rather than the default API. -### 19.7 Error model -Internal SDK errors may include: -```rust -pub enum AuthenticationError { - MissingAuthorizationHeader, - InvalidAuthorizationHeader, - UnsupportedAuthorizationScheme, - MalformedToken, - InvalidTokenType, - UnsupportedAlgorithm, - MissingKeyId, - UnknownSigningKey, - InvalidSignature, - InvalidIssuer, - InvalidAudience, - TokenExpired, - TokenNotYetValid, - InvalidIssuedAt, - MissingClaim(&'static str), - InvalidClaim(&'static str), - JwksUnavailable, -} -``` - -HTTP framework adapters should map: -- Missing or invalid authentication to `401 Unauthorized` -- Valid authentication with insufficient product permission to `403 Forbidden` -Detailed cryptographic errors must not be returned to untrusted clients. -### 19.8 Scope handling -Piquel access tokens may later include scopes. -The middleware may optionally enforce required scopes: -```rust -let middleware = AuthMiddleware::builder() - .issuer(...) - .audience("product-a-api") - .required_scope("profile:read") - .build() - .await?; -``` -Product-specific resource authorization remains outside the authentication middleware. -## 20. Product integration flow -A typical web product integration is: -```text -1. User opens Product A. -2. Product A finds no valid local access token. -3. Product A starts OIDC Authorization Code with PKCE. -4. Browser is redirected to Piquel Auth. -5. User authenticates, or an existing Piquel session is reused. -6. Piquel Auth returns an authorization code. -7. Product A exchanges the code. -8. Product A receives: - - ID token - - Product A access JWT - - Product A refresh token -1. Product A calls Product A API with the access JWT. -2. Product A API validates the JWT locally through AuthMiddleware. -3. Product A API uses `sub` as the global user ID. -4. When the JWT expires, Product A rotates the refresh token. -``` -## 21. Login user experience -### 21.1 Available methods -The Piquel login interface offers: -- Sign in with a passkey -- Sign in with approved external providers -### 21.2 Social-first accounts -When a user authenticates socially and has no passkey, the account interface should display a recommendation such as: - -> Add a passkey for faster, phishing-resistant access to your Piquel account. - -The recommendation is non-blocking. -### 21.3 Terminology -The interface must distinguish: -- **Sign in with GitHub**: use GitHub to authenticate the Piquel account -- **Connect GitHub**: allow one product to call GitHub APIs -These are separate flows and separate credentials. -## 22. Product-owned external OAuth integrations -Each product owns its external API integrations. -For example, Product A may own a GitHub App and store the resulting GitHub user or installation tokens. -Piquel Auth does not become the universal storage system for these tokens. -This provides: -- Independent provider permission boundaries -- Separate provider registrations -- Reduced compromise blast radius -- Product-specific consent -- Product-specific revocation -- Easier use of GitHub Apps and similar provider-native models - -The Piquel SDK may simplify implementation but does not take ownership of credentials. -## 23. Data model -Representative tables follow. -### 23.1 Users -```text -users ------ -id -username -display_name -profile_version -status -created_at -updated_at -``` -### 23.2 Emails -```text -user_emails ------------ -id -user_id -original_email -normalized_email -is_primary -verified_at -created_at -updated_at -``` -Constraint: -```text -UNIQUE (normalized_email) -``` -for active verified identities under the chosen account model. -### 23.3 Passkeys -```text -passkey_credentials -------------------- -id -user_id -credential_id -public_key -signature_counter -transports -backup_eligible -backup_state -friendly_name -created_at -last_used_at -revoked_at -``` -Constraint: -```text -UNIQUE (credential_id) -``` -### 23.4 Federated identities -```text -external_login_identities -------------------------- -id -user_id -issuer -subject -provider_name -linked_email -created_at -last_used_at -revoked_at -``` -Constraint: -```text -UNIQUE (issuer, subject) -``` -### 23.5 Sessions -```text -sessions --------- -id -user_id -created_at -last_authenticated_at -last_seen_at -expires_at -revoked_at -authentication_methods -client_metadata -``` -### 23.6 Refresh-token families -```text -refresh_token_families ----------------------- -id -user_id -client_id -session_id -created_at -expires_at -revoked_at -revocation_reason -``` -### 23.7 Refresh tokens -```text -refresh_tokens --------------- -id -token_id -secret_digest -family_id -rotated_from_id -created_at -expires_at -consumed_at -last_used_at -revoked_at -``` -### 23.8 OIDC clients -```text -oidc_clients ------------- -id -client_id -display_name -application_type -enabled -created_at -updated_at -``` -Supporting tables may contain redirect URIs, audiences, scopes, and keys. -### 23.9 Service identities -```text -service_identities ------------------- -id -service_id -display_name -enabled -created_at -updated_at -``` -### 23.10 Service keys -```text -service_public_keys -------------------- -id -service_identity_id -key_id -algorithm -public_key -created_at -expires_at -revoked_at -``` -### 23.11 Internal events -```text -internal_events ---------------- -event_id -aggregate_type -aggregate_id -aggregate_sequence -event_type -schema_version -payload -created_at -published_at -``` - -Constraint: -```text -UNIQUE (aggregate_type, aggregate_id, aggregate_sequence) -``` -### 23.12 Security audit log -```text -security_audit_log ------------------- -event_id -user_id -service_id -session_id -action -outcome -source_ip -user_agent -request_id -occurred_at -metadata -``` -## 24. Internal event log -The first iteration does not publish events to a broker. -It records internal domain events so that publication may be introduced later. -Account mutations and their event records should be committed in the same database transaction. - -Example event: -```json -{ - "event_id": "evt_0198a37d", - "aggregate_type": "user", - "aggregate_id": "0198a346-1e13-7d91-bf85-15d90f7e2885", - "aggregate_sequence": 12, - "event_type": "user.display_name.changed", - "schema_version": 1, - "payload": { - "profile_version": 12 - }, - "created_at": "2026-07-11T14:32:00Z" -} -``` - -The initial event log must: -- Be append-only -- Use unique event IDs -- Use per-aggregate sequence numbers -- Version payload schemas -- Avoid storing tokens or secrets -- Avoid unnecessary personal data -- Support a future publisher cursor -- Support future at-least-once delivery -Reliable broadcasting and deletion coordination remain out of scope. -## 25. Redis usage -Redis is disposable infrastructure. -Redis should be kept in mind when designing the architecture but does not need to be implemented in this first prototype. -Appropriate uses include: -- Rate limiting -- WebAuthn ceremony state -- OAuth state and nonce state -- Short-lived PKCE transaction state -- Replay protection -- Distributed locks where strictly necessary -- JWKS or metadata caching -- Service-token refresh coordination -- Temporary session-status caching - -Redis must not be the only storage location for: -- Users -- Passkeys -- Refresh-token records -- OIDC clients -- Service identities -- Revocations -- Audit logs -- Internal events -- Signing-key metadata - -The system must preserve account integrity if Redis is flushed. -## 26. Cryptographic key management -Piquel Auth uses asymmetric signing keys for access tokens, ID tokens, purpose tokens, and internal service tokens. -Requirements: -- Private signing keys are not stored unencrypted in PostgreSQL. -- Private keys are not included directly in application configuration. -- A KMS or HSM-backed design is preferred. -- Public keys are exposed through JWKS where appropriate. -- Keys have stable `kid` identifiers. -- Key rotation supports an overlap period. -- Old public keys remain available until all issued tokens have expired. -- New tokens use only the active signing key. -- Key-use permissions are restricted to Piquel Auth. -- Development and production keys are separate. - -No token verifier may accept an algorithm selected solely from an untrusted token header. -## 27. Security requirements -### 27.1 Transport -- TLS is required for every public and internal connection. -- Internal traffic must not rely on network location alone. -- Cookies containing security state must use `Secure`. -- Session cookies must use `HttpOnly`. -- SameSite policy must be explicitly selected per flow. -### 27.2 OAuth and OIDC -- Redirect URIs use exact matching. -- PKCE is mandatory. -- State is mandatory for browser authorization flows. -- Nonces are validated when ID tokens are issued to relevant clients. -- Authorization codes are single-use. -- Authorization codes have a very short lifetime. -- Authorization codes are bound to the client and redirect URI. -- Token endpoint errors do not expose sensitive details. -### 27.3 WebAuthn -- Challenges are cryptographically random. -- Challenges are single-use. -- Challenges have short expiration. -- Expected origin is validated. -- Expected relying-party ID is validated. -- User verification requirements are explicitly configured. -- Credential IDs are unique. -### 27.4 Tokens -- Access tokens last approximately five minutes. -- Refresh tokens rotate on every use. -- Refresh-token replay revokes the family. -- Tokens are never logged. -- Authorization headers are removed from error telemetry. -- Token-bearing URLs are not supported. -- JWT verification fails closed. -- Audience validation is mandatory. -### 27.5 Logging -Logs must not contain: -- Access tokens -- Refresh tokens -- Authorization codes -- OAuth state secrets -- PKCE verifiers -- WebAuthn challenges -- Social-provider access tokens -- Private keys -- Session cookies - -Structured logs should contain: -- Request ID -- Service identity -- Client ID -- User ID when appropriate -- Operation -- Result category -- Latency -- Sanitized error code -### 27.6 Database -- Connections require TLS where supported. -- Authentication uses dedicated credentials. -- Application privileges follow least privilege. -- Sensitive columns use application-layer encryption where appropriate. -- Migrations are reviewed as security-sensitive changes. -## 28. Deployment model -Piquel Auth runs as multiple interchangeable replicas. -Each replica may handle: -- Public OIDC requests -- Passkey requests -- Social callbacks -- Token issuance -- Internal RPC requests -- Internal event-log writes -Replicas do not store authoritative state locally. -### 28.1 Required infrastructure -```text -Piquel Auth replicas -PostgreSQL -Load balancer or ingress -KMS or equivalent key protection -``` -A message broker is not required in the first iteration. -### 28.2 Replica behavior -Replicas must: -- Use shared PostgreSQL state -- Use shared signing-key configuration -- Be safe under concurrent refresh requests -- Be safe under concurrent social-login callbacks -- Avoid process-local session authority -- Support graceful shutdown -- Stop accepting new requests before termination -- Complete or cancel in-flight transactions safely -### 28.3 Health endpoints -Recommended endpoints: -```text -GET /health/live -GET /health/ready -``` -Liveness indicates that the process is running. -Readiness indicates that the replica can safely serve traffic, including required database and key-management dependencies. -## 29. Availability behavior -### 29.1 Piquel Auth unavailable -Existing five-minute access tokens continue to work until expiry because products validate them locally. -During an outage: -- Existing API requests with valid tokens continue. -- New logins fail. -- Token refresh fails. -- New service tokens may fail after cached service tokens expire. -- Account-management operations fail. -- Internal RPC calls fail. -The SDK must use deadlines and must not retry indefinitely. -### 29.3 PostgreSQL unavailable -Piquel Auth becomes unready for operations requiring authoritative state. -Downstream services may continue accepting already issued access JWTs until expiry. -## 30. Observability -Metrics should include: -- Login attempts by method -- Login successes and failures -- Passkey registration outcomes -- Social-provider callback failures -- Authorization-code exchanges -- Refresh success rate -- Refresh-token replay detections -- Token issuance latency -- RPC request latency -- RPC authorization failures -- JWKS refresh failures -- Active sessions -- Service-token issuance failures -- Database transaction failures -- Redis failures -- Rate-limit actions -No metric labels may contain raw tokens, email addresses, or unbounded user identifiers. -Tracing must redact authorization metadata. -## 31. Accepted first-iteration risks -The following risks are knowingly accepted: -### 31.1 Social-provider trust -A supported social provider is trusted as an authentication method equivalent to Piquel’s own login for first-iteration account access. -Compromise of that provider account may therefore compromise the Piquel account. -### 31.2 Automatic email linking -A newly observed provider identity may be linked automatically to an existing Piquel account based on a provider-verified matching email. -This creates account-linking risk if a provider’s email assurance is weaker than expected. -Mitigations retained in the first iteration are: -- Explicit provider allowlist -- Verified-email requirement -- Permanent issuer-and-subject mapping after linking -- Conservative email normalization -- Security audit entry -- User notification -### 31.3 Social recovery of passkeys -A fresh social login may manage passkeys. -This weakens the security boundary of passkey recovery. -The data model and purpose-token flow should allow this policy to be tightened later. -### 31.4 Access-token revocation delay -A revoked session’s existing access token may remain usable for up to approximately five minutes. -This is accepted to avoid an authentication-service call on every request. -### 31.5 No event broadcasting -Products do not receive reliable real-time profile, deletion, or account-status events in the first iteration. -Products must treat access-token profile fields as short-lived snapshots. -## 32. Future extensions -The architecture should support later addition of: -- Durable event publication -- Consumer subscriptions -- Account-deletion orchestration -- User-event acknowledgements -- Stricter social-account linking -- Passkey-required high-assurance operations -- Explicit authentication assurance levels -- Suspicious-login detection -- Device-bound sessions -- Sender-constrained refresh tokens -- Product-specific consent screens -- Administrative organization accounts -- External provider connector framework -- User-facing session and device management -- Pairwise subject identifiers for third-party clients -- Selective token introspection for exceptional operations -- Redis caching -## 33. Initial implementation sequence -### Phase 1: Core identity -Implement: -- User model -- Email model -- Passkey registration -- Passkey login -- Central session -- Basic account interface -### Phase 2: OIDC and tokens -Implement: -- Discovery -- Authorization Code with PKCE -- Client registration -- ID tokens -- Audience-specific access JWTs -- Opaque rotating refresh tokens -- JWKS -- Revocation -### Phase 3: SDK and first product -Implement: -- Rust core SDK -- `AuthMiddleware` builder -- Axum integration -- Token refresh client -- First product integration -- JWKS rotation tests -### Phase 4: Social login -Implement: -- First approved provider -- Verified-email extraction -- Automatic email matching -- Issuer-and-subject linking -- Passkey recommendation -- Social recovery -### Phase 5: Internal RPC -Implement: -- Service identities -- Signed service assertions -- Service-token manager -- gRPC server -- Generated Rust client -- User and session methods -### Phase 6: Hardening -Implement: -- Rate limiting -- Audit log -- Internal event log -- Key rotation -- Refresh-token replay response -- Backup and restore testing -- Security testing -- Incident-response procedures -## 34. Final architecture summary -Piquel Auth provides one global identity across multiple independent products. -The core model is: -```text -One global Piquel user ID -One central authentication authority -One replicated stateless auth process -One central single-sign-on session - -Per product: - One or more OIDC clients - One API audience - Separate access tokens - Separate refresh-token families - Separate application data - Separate authorization rules -``` -Ordinary product requests use five-minute audience-specific JWTs validated locally through the Piquel SDK. -Refresh tokens are opaque, rotating, product-specific, revocable, and stored only by the appropriate client environment. -Sensitive operations require fresh authentication and receive purpose-bound authorization rather than relying directly on a refresh token. -The private API uses authenticated gRPC. Each downstream backend has a distinct service identity and obtains short-lived service tokens through SDK-managed asymmetric authentication. -The SDK’s `AuthMiddleware` builder makes secure token verification the default by requiring an issuer, audience, trusted JWKS source, approved algorithm, time validation, and required claims. -Passkeys and approved social providers are both supported login methods. Provider-verified matching emails are automatically associated with existing accounts in the first iteration. Social login may recover and manage passkeys, with the associated risk explicitly documented. -The event system begins as an internal transactional event log. Reliable broadcasting and deletion workflows are deferred without preventing their later implementation. diff --git a/plans/auth/00-foundation.md b/plans/auth/00-foundation.md deleted file mode 100644 index 6ba1361a6..000000000 --- a/plans/auth/00-foundation.md +++ /dev/null @@ -1,82 +0,0 @@ -# 00 — Workspace, protocol, and persistence foundation - -## Goal - -Create the smallest real Rust workspace on which the auth service can be built: -typed protocol primitives, the sole PostgreSQL access crate, configuration and -telemetry support, and an executable `auth-service` shell. This plan establishes -boundaries; it does not implement login, OIDC, or a frontend. - -## Scope - -1. Expand root `Cargo.toml` to list only the concrete members introduced here: - `apps/auth-service`, `crates/auth-protocol`, `crates/database`, - `crates/configuration`, and `crates/telemetry`. Declare all shared dependency - versions in `[workspace.dependencies]`; member manifests opt in explicitly. - Use Tokio, typed errors, UUIDv7 support, time/URL/serialization, tracing, and - SQLx only where each is actually needed. Add a root `justfile` only for - commands that now work: format, check, test, migrate, and SQLx preparation. -2. Add `crates/auth-protocol` as a framework- and SQLx-free crate. Define - validated newtypes and serde representations for `UserId` (UUIDv7), - `SessionId`, `ClientId`, `Audience`, `ServiceId`, `TokenId`, and common - authentication-method and account-status enums. Include shared, stable token - claim structs only where a downstream verifier will need them. Reject invalid - wire values at parsing boundaries; do not expose database rows or policy. -3. Add `crates/configuration` for reusable parsing/validation of environment - values, durations, URLs, and secret references. Application-specific auth - settings belong in `apps/auth-service`, composed from these primitives. -4. Add `crates/telemetry` with sanitized tracing/metrics initialization and - reusable redaction helpers. Its public API must make it hard to attach - authorization headers or secrets accidentally; it must not become a generic - utility crate. -5. Create `crates/database` (`piquel-repository`) according to the database - architecture: private pool/executor/row types; public `Database`, typed - configuration and errors, health check, explicit transaction wrapper, and - domain repository handles. Do not export a `PgPool`, a SQLx transaction, raw - SQL, or `sqlx::Error`. Start with public module/model/repository scaffolding - only for users, emails, sessions, audit events, internal events, passkeys, - OIDC/token records, federation, and service identities; implementations land - with the owning feature plans. -6. Add the migration runner binary and the initial migration layout. The first - migration may create PostgreSQL extensions/types needed by later auth tables, - but must not create speculative feature tables. Establish a documented local - test database configuration and integration-test harness that uses isolated - databases/schemas and never depends on test ordering. -7. Add `apps/auth-service` as one deployable binary plus internal `lib.rs`. - It loads typed configuration, initializes telemetry, connects through - `Database`, exposes `/health/live` and `/health/ready`, and shuts down - gracefully. Readiness checks database and required key-provider configuration - availability without minting tokens. Keep future modules private under - `src/`; do not extract auth policy into a crate. - -## Required interfaces and decisions - -- Decide and document the UUIDv7 generation/parsing crate and canonical string - representation. All IDs must be immutable and downstream-safe. -- Define `DatabaseError`/connection/health error categories that preserve the - distinction between conflict, unavailable, invalid stored data, and internal - failure without leaking SQL details. -- Establish an explicit configuration shape for public base URL, database, - public/internal listener addresses, TLS/key-provider references, and log - settings. Secrets are references or redacted wrappers, never debug output. -- The internal RPC listener is configured now but not exposed until plan 06; - public and private traffic must not be unintentionally multiplexed later. - -## Tests and acceptance criteria - -- `cargo fmt --check`, `cargo clippy --workspace --all-targets`, and - `cargo test --workspace` pass. -- Protocol ID parsing/serialization and invalid-value tests exist. -- Database integration tests verify connection/health behavior and prove that - no public API exposes raw SQLx types. -- Auth-service liveness works without dependencies; readiness fails closed when - the database or configured key dependency is unavailable, and succeeds with - test substitutes. -- The repository documents how to run migrations and the database tests. Do not - add deployment-specific infrastructure. - -## Handoff - -Plan 01 owns the first real auth migration and repository behavior. Preserve -the public `Database`/transaction shape so it can carry a user creation, audit -entry, and internal event in one short transaction. diff --git a/plans/auth/01-identity-sessions.md b/plans/auth/01-identity-sessions.md deleted file mode 100644 index 0d6993bc5..000000000 --- a/plans/auth/01-identity-sessions.md +++ /dev/null @@ -1,85 +0,0 @@ -# 01 — Core identity, email, sessions, audit, and internal events - -## Goal - -Implement the authoritative account state that all authentication methods use: -global users, conservative verified emails, central login sessions, security -audit records, and an append-only transactional domain-event log. - -## Prerequisite - -Plan 00 is complete, including an integration-testable database crate. - -## Scope - -1. Add immutable auth-owned migrations for `users`, `user_emails`, `sessions`, - `security_audit_log`, and `internal_events`. Use UUIDv7 primary identities - (or documented compatible representation), UTC timestamps, foreign keys, and - deliberate indexes. Add a partial/conditional uniqueness constraint so a - normalized email cannot be verified for two active accounts; do not use a - blanket unique constraint that prevents unverified onboarding states. Ensure - exactly one primary verified email per account when an account has one. -2. Implement typed public database models, private SQLx row conversion, and - focused repositories for persistence actions such as user insert/find/status - update/profile update, verified-email lookup/insert/primary selection, - session create/find/touch/revoke, audit append, and event append. Use - explicit input structures and typed conflicts. All list APIs are bounded. -3. Extend `DatabaseTransaction` with those repository families. Document row - locks and write integration tests for duplicate verified email rejection, - primary-email integrity, idempotent session revocation, and per-aggregate - event sequence uniqueness. Allocate event sequence numbers transactionally; - event append and the state mutation it describes must commit together. -4. Add private `account`, `email`, `session`, `audit`, and `event_log` modules to - `apps/auth-service`. They own validation and policy, while repositories only - persist. Implement account creation with an optional already-verified email - as one short transaction and append both security audit/event entries as - appropriate. Accounts must be able to start passkey-first with no email; - social linking will create an initial verified email from its verified claim. -5. Define and document conservative email normalization: Unicode handling where - chosen, domain case normalization, and a clear local-part rule. It must not - strip plus suffixes, remove dots, or apply provider-specific equivalence. - Make normalization a tested domain function, not a SQL expression. -6. Implement central session state with authentication time/methods, expiry, - last-seen tracking, client metadata minimization, and revocation. This plan - exposes service-layer methods, not public login endpoints; plan 02 will - establish the browser cookie after a successful authentication ceremony. -7. Provide narrow account/profile read and mutation interfaces needed by later - plans. A display-name/username change increments `profile_version` using - optimistic concurrency and emits an event. Downstream identity is always - `UserId`; username/display name are presentation snapshots only. - -## Data and security rules - -- `users` contains immutable ID, username, display name, monotonically - increasing profile version, account status, and timestamps. Enforce username - uniqueness according to a separately documented validation policy. -- The design does not authorize an email-delivery/verification protocol or mail - provider. This plan owns verified-email persistence and normalization only; - do not fabricate verification emails/endpoints. A later approved plan must - add the delivery, proof, expiry, and recovery policy before arbitrary email - entry can become verified. -- Audit rows record action/outcome and sanitized request metadata; they never - include token values, emails as metric labels, or raw client secrets. -- `internal_events` is append-only with unique event ID and - `(aggregate_type, aggregate_id, aggregate_sequence)`. Payloads are versioned - JSON events, never credentials; `published_at` is future-publication metadata - only, not a broker implementation. -- Account disabling and session revocation must be idempotent and provide the - state needed for later refresh-family revocation. Do not pretend existing - access JWTs can be immediately revoked. - -## Tests and acceptance criteria - -- PostgreSQL integration tests cover constraints, transactions, optimistic - profile updates, concurrent email conflict, session revocation, and event - sequencing. -- Unit tests cover normalization edge cases and profile-version behavior. -- Auth-service tests prove an account creation transaction leaves no partial - user/email/event/audit state if any insert fails. -- Checked-query metadata and migration tests are updated where applicable. - -## Handoff - -Plan 02 consumes account/session services and adds passkey state. Plan 03 adds -OIDC sessions/codes and refresh-token families. Do not add passkey, token, or -federated identity tables in this plan. diff --git a/plans/auth/02-passkeys.md b/plans/auth/02-passkeys.md deleted file mode 100644 index ed5eca212..000000000 --- a/plans/auth/02-passkeys.md +++ /dev/null @@ -1,74 +0,0 @@ -# 02 — Passkey authentication and central browser sessions - -## Goal - -Add WebAuthn as the first authentication method, including durable credential -storage, short-lived ceremony state, central login-session cookies, and -account-security operations protected by fresh authentication. - -## Prerequisite - -Plans 00–01 are complete. Confirm the selected WebAuthn library supports the -required relying-party/origin validation and exposes no private-key handling. - -## Scope - -1. Add `passkey_credentials` migration and repository/model support. Persist - credential ID (unique), user ID, public key, signature counter, transports, - backup eligibility/state, friendly name, created/last-used/revoked fields. - Use typed binary/structured representations and validate database values at - row conversion. Private keys must never enter the service or database. -2. Add private `passkey` domain module. Configure the RP ID and expected origin - from validated auth-service configuration (`auth.piquel.fr` in production). - Explicitly select user-verification policy. Produce opaque, single-use, - cryptographically random registration/authentication challenges with short - expiry; validate origin, RP ID, challenge, authenticator result, and - signature-counter behavior before persistence. -3. Store ceremony state in a replaceable short-lived state abstraction. The - first implementation may use protected server-side/session storage, but it - must be safe across stateless replicas and survive no longer than its TTL. - Redis is optional and must not become authoritative; document the chosen - backend and failure behavior. Never put challenge secrets in URLs or logs. -4. Implement supported public HTTP endpoints in `apps/auth-service`: - `POST /webauthn/register/start`, `/finish`, `/authenticate/start`, and - `/finish`. Registration supports two explicit server-selected intents: - passkey-first account bootstrap (collect and validate required profile fields, - then create user and credential atomically) and adding a credential to an - existing account (requires central session plus fresh, purpose-bound - authorization). The bootstrap path creates no unverified email and must not - claim email ownership. Authentication start/finish creates or refreshes a - central session. Map malformed/expired/replayed ceremony state to generic - client-safe errors. -5. Implement secure central-session cookie issuance, parsing, renewal, logout - clearing, and revocation lookup. Cookies are Secure and HttpOnly, have an - explicitly selected SameSite policy compatible with OIDC/social redirects, - use a host-safe name/path/domain, and contain only an opaque reference (or - authenticated equivalent), never a bearer access/refresh token. -6. Provide passkey list/rename/remove service endpoints for the future auth-web. - Addition/removal must require a purpose token created after fresh passkey - authentication. Build a narrowly scoped reauthentication/purpose-token - mechanism now: ES256-signed, `aud=piquel-account-management`, user/session - bound, operation purpose bound, roughly two-minute expiry, and optional - single-use persistence when an operation needs it. A refresh token cannot - authorize these changes. -7. Append security audit and internal event records for credential enrollment, - use, rename, removal, and ceremony failures where safe. Update last-used and - signature counter atomically with successful authentication. - -## Tests and acceptance criteria - -- Unit tests cover ceremony expiry, single use, purpose/audience/user/session - mismatch, cookie construction, and no-secret error formatting. -- Integration tests use a standards-conformant WebAuthn test authenticator (or - vetted test fixture) to prove successful register/login, duplicate credential - rejection, invalid origin/RP/challenge rejection, revoked credential - rejection, and concurrent credential uniqueness. -- A multi-replica-style test proves ceremony/session state is not process-local. -- HTTP tests assert security headers/cookie attributes and generic public error - responses; tracing tests assert challenges and credential material are absent. - -## Handoff - -Plan 03 reuses central sessions for SSO and fresh-login requirements. Plan 05 -may treat a successful approved social login as a fresh authentication under the -first-iteration policy; keep the purpose-token assurance model extensible. diff --git a/plans/auth/03-oidc-token-lifecycle.md b/plans/auth/03-oidc-token-lifecycle.md deleted file mode 100644 index 664498617..000000000 --- a/plans/auth/03-oidc-token-lifecycle.md +++ /dev/null @@ -1,80 +0,0 @@ -# 03 — OIDC, JWT issuance, refresh rotation, and revocation - -## Goal - -Implement the public standards-oriented authorization surface: static client -registration, Authorization Code with PKCE, SSO-aware authorization, signed ID -and access tokens, opaque rotating refresh tokens, discovery/JWKS, and logout -or revocation. - -## Prerequisite - -Plans 00–02 are complete. A production key-management integration must be -selected before deployment; test keys are allowed only in explicit test/dev -configuration. - -## Scope - -1. Add migrations/repositories for static OIDC clients and their allowed exact - redirect/post-logout URIs, scopes, audiences, and authentication methods; - authorization codes; refresh-token families/tokens; and token-purpose use - records if needed. Authorization codes bind client, exact redirect URI, user, - session, PKCE challenge/method, nonce, requested grant, expiry, and one-time - consumption. Refresh token records store an indexed token ID and keyed digest - only—never the raw value—and families bind user/client/session/device scope. -2. Implement auth-service `oidc` and `token` modules. Static client management - is an administrative/bootstrap concern; dynamic registration is out of scope. - Validate client enabled state, exact URI, `response_type=code`, allowed - scopes/audience, required PKCE challenge (S256), state, nonce where ID token - applies, `prompt`, `max_age`, and current session/authentication state. -3. Serve `/.well-known/openid-configuration`, `/.well-known/jwks.json`, - `GET /oauth/authorize`, `POST /oauth/token`, `POST /oauth/revoke`, - `GET /oidc/userinfo`, and `GET /oidc/logout`. Discovery is authoritative for - actual endpoint paths. Authorization response failures must redirect only to - a validated registered URI; token errors reveal no secrets. -4. On code exchange, atomically consume the code and issue: an ID token for the - client, a five-minute maximum `at+jwt` ES256 access token for the registered - API audience, and a product/device-specific opaque refresh token when the - grant permits it. Claims must implement the design: exact issuer, UUIDv7 - `sub`, client ID, `sid`, `jti`, profile snapshot/version, `amr`, auth time, - and correct time claims. ID tokens use client audience/nonce and must not be - accepted as API tokens. Never allow a client to request another product's - audience. -5. Implement signing behind a key-provider interface in auth-service. It selects - the active asymmetric key and stable `kid`; JWKS publishes public keys, - retains old keys through the issued-token overlap, and rejects unapproved - algorithms. Private keys are not configuration literals or plaintext - PostgreSQL data. Use a narrowly controlled dev/test signer only outside - production. -6. Parse `prt_v1_.` strictly and verify the secret with a - constant-time appropriate primitive. Refresh in one short transaction: lock - or atomic-consume active token, confirm family/session/client/audience status, - mark consumed, insert replacement, then commit before returning it. A replay - of a consumed token revokes its whole family atomically, audits the incident, - and returns an invalid-grant result. Concurrent refresh attempts must allow - exactly one success. -7. Implement revocation/logout semantics for one refresh family, central session, - and all user sessions, with idempotent operations and audit/event entries. - Clearly document the accepted maximum five-minute access-JWT tail. UserInfo - accepts only an appropriate valid access token and returns only granted, - allowed claims. - -## Tests and acceptance criteria - -- Protocol tests cover every required request validation and prohibit wildcard or - prefix redirect matching, missing PKCE, code reuse, wrong verifier/client/URI, - audience escalation, expired code, and invalid nonce handling. -- JWT fixtures verify headers (`typ=at+jwt`, ES256, known `kid`) and every claim - contract. JWKS rotation tests prove both overlap verification and retired-key - rejection. -- PostgreSQL concurrency tests prove one refresh succeeds and replay revokes the - family. Tests confirm raw refresh tokens/digests never appear in logs/errors. -- End-to-end browser-flow tests cover SSO through an existing central session, - code exchange, token refresh, revoke/logout, and the inability to use an ID - token at an API resource boundary. - -## Handoff - -Plan 04 consumes discovery/JWKS and claims as the downstream SDK contract. Plan -06 may reuse the signer but issues distinct service tokens and does not reuse -user access-token audiences. diff --git a/plans/auth/04-sdk-resource-validation.md b/plans/auth/04-sdk-resource-validation.md deleted file mode 100644 index bc8b12901..000000000 --- a/plans/auth/04-sdk-resource-validation.md +++ /dev/null @@ -1,61 +0,0 @@ -# 04 — Rust SDK and local resource-server validation - -## Goal - -Provide the stable integration surface that lets independent downstream products -perform secure OIDC flows and validate audience-restricted access tokens locally -without a per-request auth-service call. - -## Prerequisite - -Plans 00 and 03 are complete and expose stable discovery/JWKS/token fixtures. - -## Scope - -1. Create only the justified shared crates: `crates/auth-middleware` for - framework-neutral validation (plus optional Axum adapter), `crates/auth-sdk` - as the ergonomic facade, and an auth application-client module/crate only if - it has a second consumer or is the public downstream boundary. Keep shared - types in `auth-protocol`; do not move auth-service policy into the SDK. -2. Implement OIDC discovery fetch/cache, authorization URL construction, random - state/nonce/PKCE generation, callback state validation, code exchange, - refresh, and logout helpers. Browser-safe parts can later back - `packages/auth-client-js`, but this plan must not put refresh tokens in - JavaScript or prescribe product storage beyond the documented BFF/secure - cookie/native secure-store rules. -3. Implement the `AuthMiddleware` builder. Production construction requires - exact issuer, expected audience, trusted JWKS source, and an explicit allowed - asymmetric algorithm. It may not disable signature, expiry, or audience - verification. Test-only bypasses, if any, must be unmistakably feature-gated. -4. Enforce the specified validation sequence: one well-formed Bearer header; - parse header; require `typ=at+jwt`, allowed alg, and `kid`; resolve a trusted - JWKS key; verify signature; then validate exact issuer/audience, exp/nbf/iat, - required claim types, and `UserId` format. Return an immutable - `AuthenticatedUser`, not a raw JWT by default. Framework adapters map auth - failures to 401 only; product authorization stays 403/business code. -5. Implement bounded in-memory JWKS caching: startup/first-use fetch, TTL, - controlled single refresh on unknown `kid`, rate limiting of unknown-key - refreshes, old-key overlap support, and fail-closed behavior. Never trust - JWT-embedded keys or token-selected algorithms. -6. Define typed, redacted errors and tracing. Provide optional required-scope - checking without implying that product resource authorization belongs here. - Re-export the intended downstream API from `auth-sdk`; downstream consumers - should not need workspace-internal crate knowledge. - -## Tests and acceptance criteria - -- Compatibility fixtures from plan 03 validate a real access token and reject - ID/service/purpose tokens, incorrect audience/issuer/typ/alg, expiry, nbf, - malformed IDs, multiple headers, and bad signatures. -- Mock HTTP tests prove JWKS TTL behavior, one bounded unknown-`kid` refresh, - key-rotation overlap, rate limiting, and fail-closed network failures. -- Compile tests/examples demonstrate an Axum integration and direct - framework-neutral use. Public APIs use typed errors and contain no SQLx, - service private keys, or raw credential logging. -- Add a downstream-consumer compatibility test or minimal external-style sample - that depends only on the intended SDK facade. - -## Handoff - -The SDK contract becomes a compatibility boundary. Plans 06 and 07 can add -separate RPC/UI integrations, but may not weaken resource-server validation. diff --git a/plans/auth/05-federation.md b/plans/auth/05-federation.md deleted file mode 100644 index c4fcc0eb8..000000000 --- a/plans/auth/05-federation.md +++ /dev/null @@ -1,67 +0,0 @@ -# 05 — Approved social login and automatic account linking - -## Goal - -Add one approved external identity provider as a complete authentication method -while enforcing stable issuer/subject identity, verified-email-only automatic -linking, and the first-iteration social-recovery policy. - -## Prerequisite - -Plans 01–02 are complete. Select the first provider and record its issuer, -OIDC/OAuth metadata source, required verified-email claim semantics, key -validation, and whether it is explicitly allowed to auto-link before coding. - -## Scope - -1. Add a migration and repository/model for `external_login_identities` with - unique `(issuer, subject)`, user foreign key, provider name, linked email, - timestamps, and revocation. Store provider client secrets through the - configuration/secret-reference boundary, never in the database or logs. -2. Add a private `federation` module and provider adapter interface inside - auth-service. It owns provider allowlisting, initiation, callback validation, - issuer/subject extraction, verified-email verification, metadata/JWKS use, - provider error normalization, and state/nonce/PKCE transaction handling. - Do not create a generalized connector platform; implement only the selected - provider behind a small testable interface. -3. Serve `GET /login/{provider}` and `/login/{provider}/callback`. Bind the - initiation transaction to the browser/session and return URL, expiry, state, - nonce, and PKCE data. Validate it exactly once on callback before provider - token processing. Use server-to-server token exchange with deadlines and - safe retries; provider credentials are transient and redacted. -4. Implement the linking transaction exactly: find by issuer/subject; otherwise - require an asserted verified, usable provider email; normalize it using plan - 01 policy; find exactly one active Piquel user by verified email; link if one - exists; create a new account and verified email if none exists; reject - ambiguous/disabled/unverified/not-approved cases. Rely on unique constraints - and map concurrent races to safe re-read/retry behavior. Email never becomes - the durable provider key after this step. -5. Successful social login establishes/updates the central session with the - social authentication method and can satisfy fresh authentication for - passkey-management purpose tokens, as explicitly accepted in the design. - Record auditing/event entries for link, login, rejection, and recovery - actions; arrange user notification through a future-safe interface without - implementing an unselected mail system. -6. Expose narrow authenticated operations to list/link/unlink social identities - for later UI. Linking/unlinking requires a purpose token and must not permit - removing the account's last viable login method. The exact recovery policy is - enforced in auth-service, not repositories. - -## Tests and acceptance criteria - -- Adapter contract tests use signed provider fixtures and mock discovery/JWKS - endpoints; cover invalid issuer/signature/nonce/state/PKCE/callback and - missing or unverified email. -- Transaction tests cover existing mapping, one matching account, no account, - duplicate mapping race, ambiguous legacy data, disabled user, and no - provider-specific email rewriting. -- End-to-end tests show social SSO, a new account, automatic linking, and fresh - social reauthentication enabling a passkey operation under the accepted policy. -- Logs/traces/errors contain no social access/refresh tokens, callback codes, or - state secrets. - -## Handoff - -Plan 07 presents the provider choice and post-social passkey recommendation. -Future providers require their own reviewed plan; do not add them by copying -provider-specific assumptions. diff --git a/plans/auth/06-service-rpc.md b/plans/auth/06-service-rpc.md deleted file mode 100644 index c8514cb2b..000000000 --- a/plans/auth/06-service-rpc.md +++ /dev/null @@ -1,66 +0,0 @@ -# 06 — Service identities and private gRPC API - -## Goal - -Implement authenticated, authorized internal RPC for exceptional authoritative -operations while preserving local JWT validation as the normal product request -path. - -## Prerequisite - -Plans 00, 01, and 03 are complete. Decide the protobuf generation/check-in -policy and TLS certificate source before adding generated code. - -## Scope - -1. Add versioned definitions under `proto/piquel/auth/v1/` for exactly the - initial `AuthService` methods: `GetUser`, `BatchGetUsers`, - `GetSessionStatus`, `RevokeSession`, `RevokeAllUserSessions`, and - `GetServiceConfiguration`. Define request/response fields and stable error - mapping without exposing database rows. Reserve deleted field numbers/names; - generate clients through repository tooling, never hand-edit output. -2. Add migrations/repositories for service identities, public keys, permitted - RPC methods/data fields, and supporting audit state. A registration has - service ID, display name, enabled status, asymmetric public keys with `kid`, - algorithm/lifetime/revocation, and explicit permissions. Runtime services - never write their registration or rotate their own keys. -3. Implement `service_identity` inside auth-service and a small - `crates/service-auth` boundary. A backend signs a short-lived client - assertion with its private key; auth-service verifies issuer/audience/time, - assertion identity and key status, replay controls where required, and then - issues a distinct five-minute service JWT for `piquel-internal-api`. User and - service claims/audiences must remain non-interchangeable. -4. Expose the service-token endpoint only on the private surface (or another - deliberately protected internal endpoint) with TLS, strict body limits and - deadlines. Use the signing/key-provider contract from plan 03 but a distinct - token type and validation rules. Audit issuance failures and administrative - changes without storing assertions/tokens. -5. Implement the separate internal Tonic listener in auth-service. Require TLS - and service-token metadata, validate it before dispatch, enforce method/data - permissions per service identity, default deadlines/message-size limits, and - disable public reflection. RPC methods use typed repository/domain APIs and - are bounded (especially batch reads); there is no `ValidateAccessToken` RPC. -6. Add `crates/auth-client` plus SDK re-exports. It wraps generated clients with - concurrency-safe service-token caching/early renewal, request metadata, - deadlines, sanitized tracing, and at most one safe retry after authentication - failure. It must not retry non-idempotent revocations blindly or create a - Tokio runtime. Keep a clear public API that downstream backends can use. - -## Tests and acceptance criteria - -- Protobuf compatibility lint/tests verify package versioning and reserved - fields. Generated code is reproducible from documented commands. -- Tests reject disabled/unknown services, invalid/expired/assertion replayed - credentials, wrong audience/token type, revoked keys, missing TLS identity, - oversized/deadline-exceeded requests, and unauthorized method/data access. -- gRPC integration tests validate service-token injection/renewal under - concurrent callers, bounded retry behavior, permission filtering, and - idempotent revocation semantics. -- Demonstrate that ordinary access-token validation remains entirely local via - the SDK; no product request needs this RPC service. - -## Handoff - -Plan 08 operationalizes service-key rotation and RPC monitoring. Administrative -registration/key rotation needs a reviewed administrative workflow; do not put -those privileges in the SDK or browser UI. diff --git a/plans/auth/07-auth-web.md b/plans/auth/07-auth-web.md deleted file mode 100644 index a610a3b0c..000000000 --- a/plans/auth/07-auth-web.md +++ /dev/null @@ -1,64 +0,0 @@ -# 07 — Auth web experience and public-flow integration - -## Goal - -Deliver the user-facing `auth.piquel.fr` experience over the supported HTTP -API: login, passkey enrollment/security management, social sign-in, OIDC -authorization, session/logout behavior, and safe error handling. - -## Prerequisite - -Plans 02, 03, and 05 are complete. Select SvelteKit or a React-based framework -using repository policy before scaffolding `apps/auth-web`; do not introduce a -second frontend framework without a concrete need. - -## Scope - -1. Create `apps/auth-web` as an independently deployable frontend that calls - public auth HTTP APIs only. Add it to the JS workspace only when a real - `package.json`/pnpm workspace is introduced. It has no PostgreSQL access, - service credentials, private keys, or internal gRPC client. -2. Build the login/continuation screens for passkey authentication and approved - social provider initiation. Handle WebAuthn browser capability/errors, - double-submit prevention, generic authentication failure messages, return to - a validated OIDC transaction, and an authenticated existing central session. - Preserve server-provided transaction correlation without exposing secrets. -3. Implement OIDC authorization UX: interpret only server-validated request - details, show the requested product/client/audience/scopes, continue or deny, - and redirect only through the server's validated path. Do not implement a - product-specific consent system beyond the first-iteration behavior defined - by the service; do not trust query display fields as authorization inputs. -4. Provide account-security screens backed by the API: list/rename/remove - passkeys, add passkey after fresh authentication, list social identities, - sign out, and session status where the server exposes it. All sensitive - mutations use the short-lived purpose-token flow, never a refresh token in - browser JavaScript. -5. After a successful social sign-in for an account without passkeys, show the - non-blocking recommendation to add one. Use distinct language for “Sign in - with GitHub” (identity authentication) and “Connect GitHub” (a product-owned - external integration, deliberately not implemented here). -6. Build accessible loading, error, expired-session, unsupported-browser, and - security-sensitive confirmation states. Apply CSP, secure asset handling, - CSRF defenses for cookie-authenticated mutations, and no-store/cache-control - for token/authorization pages. Never place authorization codes, state, - challenge data, user tokens, or private configuration in analytics/client - logs. - -## Tests and acceptance criteria - -- Browser-level tests cover passkey start/finish, social redirect/callback, - SSO authorization continuation, cancellation, logout, reauthentication for a - sensitive passkey action, and generic error behavior. -- Accessibility tests cover keyboard-only navigation, labeled controls, focus - behavior after failures, and provider/passkey alternatives. -- Build/static inspection proves no internal endpoint, secret, service key, or - refresh-token localStorage use is present. HTTP tests assert CSP/CSRF/cache - headers and endpoint-origin protections. -- Product-flow tests verify all post-auth redirects are accepted only after - server-side exact redirect-URI validation. - -## Handoff - -Plan 08 adds the security/operational validation around this UI. Account -deletion, TOTP, product OAuth credential management, and full user-device -management remain intentionally deferred. diff --git a/plans/auth/08-hardening-operations.md b/plans/auth/08-hardening-operations.md deleted file mode 100644 index c5cff8eae..000000000 --- a/plans/auth/08-hardening-operations.md +++ /dev/null @@ -1,71 +0,0 @@ -# 08 — Security hardening, observability, and operational readiness - -## Goal - -Turn the implemented first iteration into an operable, security-reviewed auth -service: abuse controls, data-protection checks, monitoring, key lifecycle, -backup/restore evidence, and cross-boundary failure tests. - -## Prerequisite - -Plans 00–07 are complete. This plan must not silently expand scope into an event -broker, Redis-as-authority, or a deployment platform that has not been chosen. - -## Scope - -1. Add rate limiting and replay/abuse controls for login, WebAuthn ceremonies, - authorization/token endpoints, provider callbacks, service assertions, and - unknown-`kid` JWKS refreshes. Redis may be selected as disposable shared - coordination only after failure-mode design; PostgreSQL remains authoritative - for identities, sessions, refresh revocation, audit, events, and key metadata. - Define fail-open/fail-closed behavior per endpoint and test Redis loss. -2. Finalize production key-provider integration and a documented signing-key - rotation procedure: stable `kid`, active key selection, JWKS overlap until all - affected token classes expire, distinct development/production keys, access - restriction to auth-service, and readiness failure if required keys cannot be - used. Add the parallel administrative service-public-key rotation procedure. -3. Instrument sanitized metrics/traces for the design’s login, credential, - authorization-code, token/refresh replay, JWKS, RPC, DB, Redis, and rate-limit - outcomes. Keep labels bounded; never use emails, raw IDs, tokens, headers, or - unbounded user data. Add dashboards/alerts only under `infra/monitoring/` and - only in the format supported by the chosen monitoring stack. -4. Complete health and graceful-shutdown behavior. Liveness stays process-only; - readiness verifies PostgreSQL plus required key dependencies and fails closed. - On termination, stop intake, honor bounded request/RPC deadlines, and roll - back unfinished transactions. Verify replica safety for concurrent social - callbacks, refreshes, and ceremony/session coordination. -5. Add operational docs under `docs/operations/` for migrations/release order, - signing/service-key rotation, auth outage behavior, token replay incident, - backup restoration, and audit-log investigation. Add/update security docs for - accepted risks (social trust/linking/recovery and five-minute JWT tail) and - the redaction/data-retention policy. Use ADRs only if these choices change a - documented architecture boundary. -6. Perform security-focused test work: fuzz/property tests for token/refresh - parsing and redirect validation, negative OIDC/WebAuthn/provider/RPC tests, - database permission tests when roles are provisioned, dependency/security - audit, migration-from-empty and upgrade-path tests, and backup/restore drills - that validate authentication invariants without copying sensitive test data. - -## Release gates - -- A key rotation in a test environment proves new issuance, old-key verification - during overlap, and old-key removal only after expiry. -- Loss of Redis (if used) does not corrupt authoritative state; the documented - endpoint degradation behavior is observed. -- An intentional refresh replay produces one family revocation, audit/metric - signal, a generic client error, and no leaked token material. -- Multi-replica integration tests prove no double code exchange, refresh - rotation, event sequence, or identity link can succeed. -- Dashboards/alerts contain no secret/high-cardinality labels; alert simulations - cover elevated login failure, replay, signing, DB, and RPC-auth failures. -- Full workspace formatting, linting, unit/integration/browser tests, migration - tests, and SQLx metadata checks pass. Record any remaining accepted risk rather - than masking it with an untested control. - -## Explicitly deferred - -Do not implement a broker/consumer delivery system, deletion orchestration, -TOTP, risk-based authentication, third-party registration, token exchange, -central storage of product external-provider credentials, or provider framework -generalization. The transactional event log remains a foundation for later work, -not a claim of delivered event publishing. diff --git a/plans/auth/README.md b/plans/auth/README.md index e76629472..9898a2b37 100644 --- a/plans/auth/README.md +++ b/plans/auth/README.md @@ -1,38 +1,30 @@ -# Authentication implementation plan index +# Accepted authentication release -Implement these plans in numeric order. Each plan is intentionally a reviewable -vertical slice with explicit prerequisites; do not start a later plan by -recreating boundaries established by an earlier one. +This plan supersedes the prototype's phased OIDC/SDK/RPC/frontend/operations stack. +The implementation may reuse sound pieces; prototype compatibility is unnecessary. -| Plan | Outcome | Depends on | -| --- | --- | --- | -| [00-foundation.md](00-foundation.md) | Workspace, typed auth protocol, database crate, and configuration/telemetry foundations | — | -| [01-identity-sessions.md](01-identity-sessions.md) | Accounts, verified emails, central sessions, audit trail, and transactional event log | 00 | -| [02-passkeys.md](02-passkeys.md) | WebAuthn registration/authentication and a central browser session | 01 | -| [03-oidc-token-lifecycle.md](03-oidc-token-lifecycle.md) | OIDC Authorization Code + PKCE, signed tokens, refresh rotation, JWKS, and revocation | 01, 02 | -| [04-sdk-resource-validation.md](04-sdk-resource-validation.md) | Published Rust SDK surface and mandatory local access-token validation | 00, 03 | -| [05-federation.md](05-federation.md) | First approved social provider and safe automatic account linking | 01, 02 | -| [06-service-rpc.md](06-service-rpc.md) | Service identities, short-lived service tokens, private gRPC, and typed client | 00, 01, 03 | -| [07-auth-web.md](07-auth-web.md) | User-facing login, authorization, account-security, and error UI | 02, 03, 05 | -| [08-hardening-operations.md](08-hardening-operations.md) | Security hardening, observability, key rotation, operational runbooks, and end-to-end tests | 00–07 | +The agreed design tree: -## Shared constraints +- Registration: invitation-only by default, runtime switch for public signup, + CLI-generated single-use expiring links, username-based passkey-only accounts, + optional email established from a verified linked provider. +- Authentication: discoverable synced passkeys with username fallback; GitHub and + Google for ordinary sign-in; social-first signup must enroll its first key. +- Settings: piquel.fr frontend, public auth API, auth-host WebAuthn ceremonies; + passkey confirmation opens a reusable fixed two-minute window for every sensitive + change; no social renewal; never remove the last passkey. +- Identity linking: matching email prompts, never auto-links; passkey proof required; + declining cancels; explicit linking supports different/missing emails; one identity + per provider; unlink first is the only transfer mechanism; local email stays stable. +- OIDC: configured public/confidential web clients, code + S256 PKCE, remembered + consent with explicit trusted-client bypass, optional rotating refresh tokens. +- Sessions: 30-day absolute cap, five-minute access tokens, logout blocks future + central SSO/refresh; credential removal revokes other central sessions. +- Packaging: one Rust auth binary with static SvelteKit auth assets and migration/ + invitation commands; separately built piquel.fr settings; PostgreSQL only. +- Deferred: recovery, public client registration, native/device/machine flows, + immediate application-wide logout, SDK/RPC scaffolding, deployment and infrastructure. -- Read `docs/architecture/monorepo.md` before changing workspace structure and - `docs/architecture/database-crate.md` before changing persistence. -- `crates/database` (package name `piquel-repository`) is the only SQLx - consumer. Applications receive `Database` and typed repository APIs only. -- Keep policy in `apps/auth-service`; keep stable shared protocol types in - `crates/auth-protocol`; do not create speculative crates or applications. -- Public endpoints are HTTP/OIDC. Private RPC is gRPC on a separate, - authenticated listener. Browser code never receives service credentials. -- Preserve exact audience validation and five-minute maximum access-token - lifetime. Never log credentials, token material, codes, PKCE verifiers, - WebAuthn challenges, or provider credentials. -- Each schema change is an immutable migration in `crates/database/migrations/`; - update SQLx metadata when checked queries are used. Application replicas do - not automatically run migrations. - -The design intentionally defers a broker, Redis implementation, deletion -orchestration, TOTP, third-party/dynamic client registration, and product-owned -external OAuth credential storage. Do not add them in these plans. +Validation includes actual PostgreSQL transactions, signed WebAuthn assertions, +local signed provider fixtures and real browser flows. Physical Apple/Google device +checks and live provider login are separate evidence, never implied by virtual tests. diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 000000000..bc263054d --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests/browser', + workers: 1, + forbidOnly: Boolean(process.env.CI), + retries: 0, + timeout: 60_000, + use: { + baseURL: process.env.E2E_AUTH_URL ?? 'http://localhost:3000', + // Authentication artifacts must never be included in screenshots or traces. + trace: 'off', screenshot: 'off', video: 'off', + launchOptions: { executablePath: process.env.CHROMIUM_EXECUTABLE }, + ignoreHTTPSErrors: Boolean(process.env.E2E_ALLOW_SELF_SIGNED_TLS) + }, + projects: [{ name: 'chromium', use: { browserName: 'chromium' } }] +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 000000000..7a24058e0 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,902 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +catalogs: + default: + '@sveltejs/adapter-static': + specifier: 3.0.10 + version: 3.0.10 + '@sveltejs/kit': + specifier: 2.70.3 + version: 2.70.3 + '@sveltejs/vite-plugin-svelte': + specifier: 7.3.0 + version: 7.3.0 + svelte: + specifier: 5.57.0 + version: 5.57.0 + svelte-check: + specifier: 4.7.6 + version: 4.7.6 + typescript: + specifier: 6.0.3 + version: 6.0.3 + vite: + specifier: 8.3.0 + version: 8.3.0 + +overrides: + cookie@<0.7.0: 0.7.2 + +importers: + + .: + devDependencies: + '@playwright/test': + specifier: 1.63.0 + version: 1.63.0 + + apps/auth-web: + dependencies: + '@piquel/browser': + specifier: workspace:* + version: link:../../packages/browser + devDependencies: + '@sveltejs/adapter-static': + specifier: 'catalog:' + version: 3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0))(svelte@5.57.0)(typescript@6.0.3)(vite@8.3.0)) + '@sveltejs/kit': + specifier: 'catalog:' + version: 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0))(svelte@5.57.0)(typescript@6.0.3)(vite@8.3.0) + '@sveltejs/vite-plugin-svelte': + specifier: 'catalog:' + version: 7.3.0(svelte@5.57.0)(vite@8.3.0) + svelte: + specifier: 'catalog:' + version: 5.57.0 + svelte-check: + specifier: 'catalog:' + version: 4.7.6(picomatch@4.0.7)(svelte@5.57.0)(typescript@6.0.3) + typescript: + specifier: 'catalog:' + version: 6.0.3 + vite: + specifier: 'catalog:' + version: 8.3.0 + + apps/piquel-web: + dependencies: + '@piquel/browser': + specifier: workspace:* + version: link:../../packages/browser + devDependencies: + '@sveltejs/adapter-static': + specifier: 'catalog:' + version: 3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0))(svelte@5.57.0)(typescript@6.0.3)(vite@8.3.0)) + '@sveltejs/kit': + specifier: 'catalog:' + version: 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0))(svelte@5.57.0)(typescript@6.0.3)(vite@8.3.0) + '@sveltejs/vite-plugin-svelte': + specifier: 'catalog:' + version: 7.3.0(svelte@5.57.0)(vite@8.3.0) + svelte: + specifier: 'catalog:' + version: 5.57.0 + svelte-check: + specifier: 'catalog:' + version: 4.7.6(picomatch@4.0.7)(svelte@5.57.0)(typescript@6.0.3) + typescript: + specifier: 'catalog:' + version: 6.0.3 + vite: + specifier: 'catalog:' + version: 8.3.0 + + packages/browser: {} + +packages: + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@oxc-project/types@0.149.0': + resolution: {integrity: sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==} + + '@playwright/test@1.63.0': + resolution: {integrity: sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==} + engines: {node: '>=20'} + hasBin: true + + '@polka/url@1.0.0-next.29': + resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} + + '@rolldown/binding-android-arm-eabi@1.2.8': + resolution: {integrity: sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.8': + resolution: {integrity: sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.8': + resolution: {integrity: sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.8': + resolution: {integrity: sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.8': + resolution: {integrity: sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.8': + resolution: {integrity: sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.8': + resolution: {integrity: sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.8': + resolution: {integrity: sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.8': + resolution: {integrity: sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.8': + resolution: {integrity: sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.8': + resolution: {integrity: sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.8': + resolution: {integrity: sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.8': + resolution: {integrity: sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.8': + resolution: {integrity: sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.8': + resolution: {integrity: sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@sveltejs/acorn-typescript@1.0.13': + resolution: {integrity: sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==} + peerDependencies: + acorn: ^8.9.0 + + '@sveltejs/adapter-static@3.0.10': + resolution: {integrity: sha512-7D9lYFWJmB7zxZyTE/qxjksvMqzMuYrrsyh1f4AlZqeZeACPRySjbC3aFiY55wb1tWUaKOQG9PVbm74JcN2Iew==} + peerDependencies: + '@sveltejs/kit': ^2.0.0 + + '@sveltejs/kit@2.70.3': + resolution: {integrity: sha512-UDvEYuZqAMbfB/oXIoqKvbKcb7YczK5zYrzmsGV1zRJk03jntwp8dXiYoIJotxAndsKvcPFtx9H1GRSKFdSHgg==} + engines: {node: '>=18.13'} + hasBin: true + peerDependencies: + '@opentelemetry/api': ^1.0.0 + '@sveltejs/vite-plugin-svelte': ^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0 + svelte: ^4.0.0 || ^5.0.0-next.0 + typescript: ^5.3.3 || ^6.0.0 + vite: ^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0 + peerDependenciesMeta: + '@opentelemetry/api': + optional: true + typescript: + optional: true + + '@sveltejs/load-config@0.2.3': + resolution: {integrity: sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==} + engines: {node: '>= 18.0.0'} + + '@sveltejs/vite-plugin-svelte@7.3.0': + resolution: {integrity: sha512-QbRoJyD92e9R0ufeQIWRHrCC0ObcqSv/aBDdrQMoU+sypav3cDx5wytdQ6GLdXjEMO6xjrXGzfkUygng8JMv0A==} + engines: {node: ^20.19 || ^22.12 || >=24} + peerDependencies: + svelte: ^5.46.4 + vite: ^8.0.0-beta.7 || ^8.0.0 + + '@types/cookie@0.6.0': + resolution: {integrity: sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + acorn@8.18.0: + resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} + engines: {node: '>=0.4.0'} + hasBin: true + + aria-query@5.3.1: + resolution: {integrity: sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==} + engines: {node: '>= 0.4'} + + axobject-query@4.1.0: + resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} + engines: {node: '>= 0.4'} + + chokidar@4.0.3: + resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} + engines: {node: '>= 14.16.0'} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + cookie@0.7.2: + resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} + engines: {node: '>= 0.6'} + + deepmerge@4.3.1: + resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} + engines: {node: '>=0.10.0'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + devalue@5.9.2: + resolution: {integrity: sha512-po4PAY5c53tw5XMocSnf8A/5OHhbbUftpr93aEN6BBoAdntUmK7vu7wOATqvt7cXO7m1Cl4gMVn6p7n6n4mj0w==} + + esm-env@1.2.2: + resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==} + + esrap@2.3.7: + resolution: {integrity: sha512-n2nf7fZR3c9yXf0BPEuHuXqT+KW0SJVj4cN5FMEkpCZ3scLjOQWpiccyCxVzCC2q1wubTghuEGzngJY/7Ah0Ow==} + peerDependencies: + '@typescript-eslint/types': ^8.2.0 + peerDependenciesMeta: + '@typescript-eslint/types': + optional: true + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + is-reference@3.0.3: + resolution: {integrity: sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==} + + kleur@4.1.5: + resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} + engines: {node: '>=6'} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + locate-character@3.0.0: + resolution: {integrity: sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + magic-string@1.3.1: + resolution: {integrity: sha512-rm91zr2Ou+XueDTohjQQjdQEcYM6zVi8KVUCG8Ec3vHwUEKrhSdCNyfuIywkA6hcCAteIn0ZOtAHA6eGpiX+Pg==} + + mri@1.2.0: + resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} + engines: {node: '>=4'} + + mrmime@2.0.1: + resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} + engines: {node: '>=10'} + + nanoid@3.3.19: + resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + playwright-core@1.63.0: + resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.63.0: + resolution: {integrity: sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==} + engines: {node: '>=20'} + hasBin: true + + postcss@8.5.28: + resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} + engines: {node: ^10 || ^12 || >=14} + + readdirp@4.1.2: + resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} + engines: {node: '>= 14.18.0'} + + rolldown@1.2.8: + resolution: {integrity: sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + sade@1.8.1: + resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==} + engines: {node: '>=6'} + + set-cookie-parser@3.1.2: + resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==} + + sirv@3.0.2: + resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} + engines: {node: '>=18'} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + svelte-check@4.7.6: + resolution: {integrity: sha512-t2scM//ZuVbSY/T2w6FSBw1v9s2NEmh/g+sy1lqtosW5ylBV5AF4wFb1Ts9Kf3MbfPDUDJDZ9L436YT0SPTdvw==} + engines: {node: '>= 18.0.0'} + hasBin: true + peerDependencies: + svelte: ^4.0.0 || ^5.0.0-next.0 + typescript: ^5.0.0 || ^6.0.0 + + svelte@5.57.0: + resolution: {integrity: sha512-NdbDn7fl4be1ViUG0oq/lvG6OZy3oENolV2ONjiqqsfVoeAfzaQAKUcEX3MrQod/Bebv1PgwET9rfXhgn9s4Kg==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + totalist@3.0.1: + resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==} + engines: {node: '>=6'} + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + vite@8.3.0: + resolution: {integrity: sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitefu@1.1.3: + resolution: {integrity: sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==} + peerDependencies: + vite: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + vite: + optional: true + + zimmerframe@1.1.5: + resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==} + +snapshots: + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@oxc-project/types@0.149.0': {} + + '@playwright/test@1.63.0': + dependencies: + playwright: 1.63.0 + + '@polka/url@1.0.0-next.29': {} + + '@rolldown/binding-android-arm-eabi@1.2.8': + optional: true + + '@rolldown/binding-android-arm64@1.2.8': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.8': + optional: true + + '@rolldown/binding-darwin-x64@1.2.8': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.8': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.8': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.8': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.8': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.8': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.8': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.8': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@standard-schema/spec@1.1.0': {} + + '@sveltejs/acorn-typescript@1.0.13(acorn@8.18.0)': + dependencies: + acorn: 8.18.0 + + '@sveltejs/adapter-static@3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0))(svelte@5.57.0)(typescript@6.0.3)(vite@8.3.0))': + dependencies: + '@sveltejs/kit': 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0))(svelte@5.57.0)(typescript@6.0.3)(vite@8.3.0) + + '@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0))(svelte@5.57.0)(typescript@6.0.3)(vite@8.3.0)': + dependencies: + '@standard-schema/spec': 1.1.0 + '@sveltejs/acorn-typescript': 1.0.13(acorn@8.18.0) + '@sveltejs/vite-plugin-svelte': 7.3.0(svelte@5.57.0)(vite@8.3.0) + '@types/cookie': 0.6.0 + acorn: 8.18.0 + cookie: 0.7.2 + devalue: 5.9.2 + esm-env: 1.2.2 + kleur: 4.1.5 + magic-string: 0.30.21 + mrmime: 2.0.1 + set-cookie-parser: 3.1.2 + sirv: 3.0.2 + svelte: 5.57.0 + vite: 8.3.0 + optionalDependencies: + typescript: 6.0.3 + + '@sveltejs/load-config@0.2.3': {} + + '@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.0)(vite@8.3.0)': + dependencies: + deepmerge: 4.3.1 + magic-string: 1.3.1 + obug: 2.2.1 + svelte: 5.57.0 + vite: 8.3.0 + vitefu: 1.1.3(vite@8.3.0) + + '@types/cookie@0.6.0': {} + + '@types/estree@1.0.9': {} + + acorn@8.18.0: {} + + aria-query@5.3.1: {} + + axobject-query@4.1.0: {} + + chokidar@4.0.3: + dependencies: + readdirp: 4.1.2 + + clsx@2.1.1: {} + + cookie@0.7.2: {} + + deepmerge@4.3.1: {} + + detect-libc@2.1.2: {} + + devalue@5.9.2: {} + + esm-env@1.2.2: {} + + esrap@2.3.7: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + is-reference@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + kleur@4.1.5: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + locate-character@3.0.0: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@1.3.1: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + mri@1.2.0: {} + + mrmime@2.0.1: {} + + nanoid@3.3.19: {} + + obug@2.2.1: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + playwright-core@1.63.0: {} + + playwright@1.63.0: + dependencies: + playwright-core: 1.63.0 + + postcss@8.5.28: + dependencies: + nanoid: 3.3.19 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + readdirp@4.1.2: {} + + rolldown@1.2.8: + dependencies: + '@oxc-project/types': 0.149.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.8 + '@rolldown/binding-android-arm64': 1.2.8 + '@rolldown/binding-darwin-arm64': 1.2.8 + '@rolldown/binding-darwin-x64': 1.2.8 + '@rolldown/binding-freebsd-x64': 1.2.8 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.8 + '@rolldown/binding-linux-arm64-gnu': 1.2.8 + '@rolldown/binding-linux-arm64-musl': 1.2.8 + '@rolldown/binding-linux-ppc64-gnu': 1.2.8 + '@rolldown/binding-linux-s390x-gnu': 1.2.8 + '@rolldown/binding-linux-x64-gnu': 1.2.8 + '@rolldown/binding-linux-x64-musl': 1.2.8 + '@rolldown/binding-openharmony-arm64': 1.2.8 + '@rolldown/binding-win32-arm64-msvc': 1.2.8 + '@rolldown/binding-win32-x64-msvc': 1.2.8 + + sade@1.8.1: + dependencies: + mri: 1.2.0 + + set-cookie-parser@3.1.2: {} + + sirv@3.0.2: + dependencies: + '@polka/url': 1.0.0-next.29 + mrmime: 2.0.1 + totalist: 3.0.1 + + source-map-js@1.2.1: {} + + svelte-check@4.7.6(picomatch@4.0.7)(svelte@5.57.0)(typescript@6.0.3): + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@sveltejs/load-config': 0.2.3 + chokidar: 4.0.3 + fdir: 6.5.0(picomatch@4.0.7) + picocolors: 1.1.1 + sade: 1.8.1 + svelte: 5.57.0 + typescript: 6.0.3 + transitivePeerDependencies: + - picomatch + + svelte@5.57.0: + dependencies: + '@jridgewell/remapping': 2.3.5 + '@jridgewell/sourcemap-codec': 1.6.0 + '@sveltejs/acorn-typescript': 1.0.13(acorn@8.18.0) + '@types/estree': 1.0.9 + acorn: 8.18.0 + aria-query: 5.3.1 + axobject-query: 4.1.0 + clsx: 2.1.1 + devalue: 5.9.2 + esm-env: 1.2.2 + esrap: 2.3.7 + is-reference: 3.0.3 + locate-character: 3.0.0 + magic-string: 0.30.21 + zimmerframe: 1.1.5 + transitivePeerDependencies: + - '@typescript-eslint/types' + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + totalist@3.0.1: {} + + typescript@6.0.3: {} + + vite@8.3.0: + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.8 + tinyglobby: 0.2.17 + optionalDependencies: + fsevents: 2.3.3 + + vitefu@1.1.3(vite@8.3.0): + optionalDependencies: + vite: 8.3.0 + + zimmerframe@1.1.5: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 000000000..492018630 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,19 @@ +packages: + - apps/* + - packages/* + +catalog: + '@sveltejs/adapter-static': 3.0.10 + '@sveltejs/kit': 2.70.3 + '@sveltejs/vite-plugin-svelte': 7.3.0 + svelte: 5.57.0 + svelte-check: 4.7.6 + typescript: 6.0.3 + vite: 8.3.0 + +onlyBuiltDependencies: + - esbuild + +# SvelteKit's cookie API is compatible with the security-patched 0.7 series. +overrides: + cookie@<0.7.0: 0.7.2 diff --git a/tests/browser/README.md b/tests/browser/README.md new file mode 100644 index 000000000..05af82d44 --- /dev/null +++ b/tests/browser/README.md @@ -0,0 +1,49 @@ +The browser suite uses the real auth binary and PostgreSQL, with Chromium's virtual +WebAuthn authenticator. It does not intercept or mock API responses. Use an isolated +database: tests create accounts and credentials. + +Build `apps/piquel-web` with `VITE_AUTH_ORIGIN` set to the auth origin. Serve that +static build at the service's configured settings URL, then set `E2E_AUTH_URL` +and `E2E_SETTINGS_URL` and run `pnpm test:browser`. If signup requires an invitation, +provide an unused `E2E_INVITATION`. Both origins must support secure contexts; +loopback HTTP requires the service's explicit development mode. + +For the verified local configuration, use `AUTH_PUBLIC_BASE_URL=http://localhost:3000`, +`AUTH_PUBLIC_LISTENER=127.0.0.1:3000`, `AUTH_SETTINGS_URL=http://localhost:4173/settings`, +and `AUTH_DEVELOPMENT_MODE=true`. Set `AUTH_CLIENTS_FILE` to a JSON file containing: + +```json +[ + { + "id": "browser-e2e", + "display_name": "Browser E2E", + "redirect_uris": ["http://localhost:4173/callback"], + "post_logout_uris": ["http://localhost:4173/settings"], + "allowed_scopes": ["openid", "profile", "email"], + "allow_refresh": false, + "trusted": false + } +] +``` + +Omitting `client_secret` makes this a public browser client. Start the auth service +with this configuration and an isolated `AUTH_DATABASE_URL`, then build and serve +settings with `VITE_AUTH_ORIGIN=http://localhost:3000`. Run the suite with +`E2E_AUTH_URL=http://localhost:3000` and +`E2E_SETTINGS_URL=http://localhost:4173/settings`. The callback URL is a test +destination: the suite captures its code and returns to settings before exchanging +it, so no callback implementation is required in the settings frontend. + +The suite checks consent, a browser PKCE exchange, an actual +ID-token signature using JWKS and WebCrypto, userinfo CORS, code replay rejection, +and a subsequent `prompt=none` request using remembered consent. Passkey-only +accounts must not acquire email claims. + +`CHROMIUM_EXECUTABLE` can select an existing Chromium installation. +`E2E_ALLOW_SELF_SIGNED_TLS=1` permits local test certificates only. + +The virtual authenticator registers credentials with backup eligibility and backup +state enabled, exercising server acceptance of synced passkeys. Apple/Google +password-manager synchronization and live Google/GitHub callbacks also need a +manual check with actual providers/devices; this suite does not claim to verify +those external systems. diff --git a/tests/browser/account.spec.ts b/tests/browser/account.spec.ts new file mode 100644 index 000000000..7ec3b626a --- /dev/null +++ b/tests/browser/account.spec.ts @@ -0,0 +1,121 @@ +import { expect, test } from '@playwright/test'; + +/** Runs against the real Rust binary and an isolated PostgreSQL database. */ +test('passkey lifecycle, protected settings and browser OIDC consent with SSO', async ({ page, context }) => { + const settingsUrl = process.env.E2E_SETTINGS_URL; + if (!settingsUrl) throw new Error('Set E2E_SETTINGS_URL to the separately served piquel-web frontend, with VITE_AUTH_ORIGIN matching E2E_AUTH_URL.'); + const authUrl = process.env.E2E_AUTH_URL ?? 'http://localhost:3000'; + const username = `browser_${Date.now().toString(36)}`; + const cdp = await context.newCDPSession(page); + await cdp.send('WebAuthn.enable'); + const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { + protocol: 'ctap2', transport: 'internal', hasResidentKey: true, + hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true, + defaultBackupEligibility: true, defaultBackupState: true + } }); + try { + const invitation = process.env.E2E_INVITATION; + await page.goto(`/register${invitation ? `?invitation=${encodeURIComponent(invitation)}` : ''}`); + await page.getByLabel('Username', { exact: true }).fill(username); + await page.getByLabel('Passkey name', { exact: true }).fill('Synced passkey'); + await page.getByRole('button', { name: 'Create account with a passkey' }).click(); + await expect(page).toHaveURL(settingsUrl); + await expect(page.getByText(`@${username}`, { exact: true })).toBeVisible(); + + const redirectUri = new URL('/callback', settingsUrl).href; + const oidc = await page.evaluate(async () => { + const encode = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); + const verifier = encode(crypto.getRandomValues(new Uint8Array(32))); + return { verifier, challenge: encode(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))), state: crypto.randomUUID(), nonce: crypto.randomUUID() }; + }); + const authorization = new URL('/oauth/authorize', authUrl); + authorization.search = new URLSearchParams({ client_id: 'browser-e2e', redirect_uri: redirectUri, response_type: 'code', scope: 'openid profile email', code_challenge: oidc.challenge, code_challenge_method: 'S256', state: oidc.state, nonce: oidc.nonce }).toString(); + await page.goto(authorization.href); + await expect(page.getByRole('heading', { name: /^Continue to / })).toBeVisible(); + await page.getByRole('button', { name: 'Continue', exact: true }).click(); + await page.waitForURL(url => url.origin === new URL(redirectUri).origin && url.pathname === '/callback'); + const callback = new URL(page.url()); + expect(callback.searchParams.get('state')).toBe(oidc.state); + expect(callback.searchParams.has('error')).toBe(false); + const code = callback.searchParams.get('code'); + expect(code).toBeTruthy(); + // Execute token handling on the genuine client origin, under its real CSP and CORS policy. + await page.goto(settingsUrl); + const exchange = await page.evaluate(async ({ origin, redirectUri, code, verifier, nonce }) => { + const body = new URLSearchParams({ grant_type: 'authorization_code', client_id: 'browser-e2e', redirect_uri: redirectUri, code: code!, code_verifier: verifier }); + const response = await fetch(`${origin}/oauth/token`, { method: 'POST', body }); + if (!response.ok) return { status: response.status }; + const tokens = await response.json(); + const decode = (value: string) => Uint8Array.from(atob(value.replace(/-/g, '+').replace(/_/g, '/')), character => character.charCodeAt(0)); + const [header, payload, signature] = tokens.id_token.split('.'); + const metadata = JSON.parse(new TextDecoder().decode(decode(header))); + const claims = JSON.parse(new TextDecoder().decode(decode(payload))); + const jwks = await fetch(`${origin}/.well-known/jwks.json`).then(result => result.json()); + const jwk = jwks.keys.find((key: JsonWebKey & { kid: string }) => key.kid === metadata.kid); + const key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']); + const signatureValid = metadata.alg === 'RS256' && await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, decode(signature), new TextEncoder().encode(`${header}.${payload}`)); + const userinfoResponse = await fetch(`${origin}/oidc/userinfo`, { headers: { authorization: `Bearer ${tokens.access_token}` } }); + const userinfo = await userinfoResponse.json(); + const session = await fetch(`${origin}/session`, { credentials: 'include' }).then(result => result.json()); + const replay = await fetch(`${origin}/oauth/token`, { method: 'POST', body }); + return { status: response.status, signatureValid, correctClaims: claims.iss === origin && claims.aud === 'browser-e2e' && claims.nonce === nonce && claims.sub === session.user.id, hasRefreshToken: 'refresh_token' in tokens, userinfoStatus: userinfoResponse.status, sameUser: userinfo.sub === session.user.id, username: userinfo.preferred_username, hasEmail: 'email' in userinfo || 'email_verified' in userinfo || 'email' in claims || 'email_verified' in claims, replayStatus: replay.status }; + }, { origin: authUrl, redirectUri, code, verifier: oidc.verifier, nonce: oidc.nonce }); + expect(exchange).toEqual({ status: 200, signatureValid: true, correctClaims: true, hasRefreshToken: false, userinfoStatus: 200, sameUser: true, username, hasEmail: false, replayStatus: 400 }); + + authorization.searchParams.set('prompt', 'none'); + authorization.searchParams.set('state', `${oidc.state}-sso`); + await page.goto(authorization.href); + await page.waitForURL(url => url.origin === new URL(redirectUri).origin && url.pathname === '/callback'); + const sso = new URL(page.url()); + expect(sso.searchParams.get('state')).toBe(`${oidc.state}-sso`); + expect(sso.searchParams.has('error')).toBe(false); + expect(sso.searchParams.get('code')).toBeTruthy(); + expect(sso.searchParams.get('code')).not.toBe(code); + await page.goto(settingsUrl); + await expect(page.getByRole('button', { name: 'Rename Synced passkey' })).toBeDisabled(); + + const rejected = await page.evaluate(async (origin) => { + const options = { credentials: 'include' as const }; + const list = await fetch(`${origin}/account/passkeys`, options).then(response => response.json()); + return fetch(`${origin}/account/passkeys/${list[0].id}`, { ...options, method: 'PATCH', headers: { 'content-type': 'application/json', 'x-piquel-csrf': '1' }, body: JSON.stringify({ friendly_name: 'Unauthorized rename' }) }).then(response => response.status); + }, authUrl); + expect(rejected).toBeGreaterThanOrEqual(400); + + await page.getByRole('link', { name: 'Unlock with a passkey' }).click(); + await page.getByRole('button', { name: 'Verify with a passkey' }).click(); + await expect(page).toHaveURL(settingsUrl); + await expect(page.getByText('Security settings unlocked', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'Rename Synced passkey' }).click(); + await page.getByLabel('Passkey name', { exact: true }).fill('My synced passkey'); + await page.getByRole('button', { name: 'Save name' }).click(); + await expect(page.getByText('My synced passkey', { exact: true })).toBeVisible(); + + await cdp.send('WebAuthn.setAutomaticPresenceSimulation', { authenticatorId, enabled: false }); + const second = await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { + protocol: 'ctap2', transport: 'usb', hasResidentKey: true, + hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true + } }); + await page.getByRole('link', { name: 'Add a passkey', exact: true }).click(); + await page.getByLabel('Passkey name', { exact: true }).fill('Second passkey'); + await page.getByRole('button', { name: 'Verify and add passkey' }).click(); + await expect(page).toHaveURL(settingsUrl); + await expect(page.getByText('Second passkey', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'Remove Second passkey', exact: true }).click(); + await page.getByRole('button', { name: 'Confirm removal' }).click(); + await expect(page.getByText('Second passkey', { exact: true })).not.toBeVisible(); + await expect(page.getByRole('button', { name: 'Remove My synced passkey', exact: true })).toBeDisabled(); + await cdp.send('WebAuthn.removeVirtualAuthenticator', { authenticatorId: second.authenticatorId }); + await cdp.send('WebAuthn.setAutomaticPresenceSimulation', { authenticatorId, enabled: true }); + const lastPasskey = await page.evaluate(async (origin) => { + const list = await fetch(`${origin}/account/passkeys`, { credentials: 'include' }).then(response => response.json()); + return fetch(`${origin}/account/passkeys/${list[0].id}`, { credentials: 'include', method: 'DELETE', headers: { 'x-piquel-csrf': '1' } }).then(response => response.status); + }, authUrl); + expect(lastPasskey).toBeGreaterThanOrEqual(400); + + await page.getByRole('button', { name: 'Sign out', exact: true }).click(); + await page.getByRole('link', { name: 'Sign in', exact: true }).click(); + await page.getByRole('button', { name: 'Sign in with a passkey', exact: true }).click(); + await expect(page).toHaveURL(settingsUrl); + await expect(page.getByText(`@${username}`, { exact: true })).toBeVisible(); + } finally { await cdp.send('WebAuthn.removeVirtualAuthenticator', { authenticatorId }); } +});