From 4636a1d6ef3db5ae8fe9d4cf06d0294456d9a38b Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:02:58 +0200 Subject: [PATCH 01/22] feat(auth): establish service foundation --- Cargo.lock | 2378 +++++++++++++++++ Cargo.toml | 25 +- apps/auth-service/Cargo.toml | 20 + apps/auth-service/src/lib.rs | 80 + apps/auth-service/src/main.rs | 26 + crates/auth-protocol/Cargo.toml | 15 + crates/auth-protocol/src/lib.rs | 197 ++ crates/configuration/Cargo.toml | 14 + crates/configuration/src/lib.rs | 103 + crates/database/Cargo.toml | 23 + crates/database/README.md | 10 + .../migrations/0001_initial_extensions.sql | 2 + crates/database/src/bin/migrate.rs | 12 + crates/database/src/connection.rs | 114 + crates/database/src/error.rs | 43 + crates/database/src/lib.rs | 25 + crates/database/src/repositories.rs | 23 + crates/database/src/transaction.rs | 48 + crates/telemetry/Cargo.toml | 14 + crates/telemetry/src/lib.rs | 36 + justfile | 14 + 21 files changed, 3221 insertions(+), 1 deletion(-) create mode 100644 Cargo.lock create mode 100644 apps/auth-service/Cargo.toml create mode 100644 apps/auth-service/src/lib.rs create mode 100644 apps/auth-service/src/main.rs create mode 100644 crates/auth-protocol/Cargo.toml create mode 100644 crates/auth-protocol/src/lib.rs create mode 100644 crates/configuration/Cargo.toml create mode 100644 crates/configuration/src/lib.rs create mode 100644 crates/database/Cargo.toml create mode 100644 crates/database/README.md create mode 100644 crates/database/migrations/0001_initial_extensions.sql create mode 100644 crates/database/src/bin/migrate.rs create mode 100644 crates/database/src/connection.rs create mode 100644 crates/database/src/error.rs create mode 100644 crates/database/src/lib.rs create mode 100644 crates/database/src/repositories.rs create mode 100644 crates/database/src/transaction.rs create mode 100644 crates/telemetry/Cargo.toml create mode 100644 crates/telemetry/src/lib.rs create mode 100644 justfile diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 000000000..351cef922 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2378 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "auth-service" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "piquel-configuration", + "piquel-repository", + "piquel-telemetry", + "serde", + "tokio", + "tracing", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.2.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "http" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" +dependencies = [ + "bitflags", + "libc", + "plain", + "redox_syscall 0.9.0", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piquel-auth-protocol" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror", + "uuid", +] + +[[package]] +name = "piquel-configuration" +version = "0.1.0" +dependencies = [ + "thiserror", + "url", +] + +[[package]] +name = "piquel-repository" +version = "0.1.0" +dependencies = [ + "anyhow", + "async-trait", + "chrono", + "piquel-auth-protocol", + "sqlx", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "piquel-telemetry" +version = "0.1.0" +dependencies = [ + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_syscall" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5102a6aaa05aa011a238e178e6bca86d2cb56fc9f586d37cb80f5bca6e07759" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls" +version = "0.23.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5fab0d6c3c01ae70085a09cb03d4c7a1d6314e2b3e075392783396d724ca0a" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.8", +] + +[[package]] +name = "webpki-roots" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index b45e0e51f..6b538d029 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,12 @@ [workspace] resolver = "3" -members = [] +members = [ + "apps/auth-service", + "crates/auth-protocol", + "crates/configuration", + "crates/database", + "crates/telemetry", +] [workspace.package] edition = "2024" @@ -16,3 +22,20 @@ missing_docs = "warn" [workspace.lints.clippy] pedantic = "warn" unwrap_used = "warn" + +[workspace.dependencies] +anyhow = "1.0" +async-trait = "0.1" +axum = "0.8" +chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } +http = "1.3" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "migrate", "macros"] } +thiserror = "2.0" +tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net"] } +tower-http = { version = "0.6", features = ["trace"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } +url = { version = "2.5", features = ["serde"] } +uuid = { version = "1.19", features = ["v7", "serde"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml new file mode 100644 index 000000000..46ee8a15a --- /dev/null +++ b/apps/auth-service/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "auth-service" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +anyhow.workspace = true +axum.workspace = true +piquel-configuration = { path = "../../crates/configuration" } +piquel-repository = { path = "../../crates/database" } +piquel-telemetry = { path = "../../crates/telemetry" } +serde.workspace = true +tokio.workspace = true +tracing.workspace = true + +[lints] +workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs new file mode 100644 index 000000000..6939ba33a --- /dev/null +++ b/apps/auth-service/src/lib.rs @@ -0,0 +1,80 @@ +//! The deployable Piquel authentication authority. +// Future policy modules remain private to this application. + +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, time::Duration}; + +/// Typed auth-service configuration. +#[derive(Clone, Debug)] +pub struct AuthConfig { + /// Public issuer/base URL. + pub public_base_url: PublicUrl, + /// Public HTTP listener address. + 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, +} +impl AuthConfig { + /// Loads the minimum service configuration from the environment. + /// + /// # 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")?; + Ok(Self { + public_base_url: PublicUrl::parse(&required("AUTH_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: DatabaseConfig::new(database_url, 10, Duration::from_secs(5)).map_err( + |_| ConfigurationError::Invalid { + name: "AUTH_DATABASE_URL", + }, + )?, + key_provider: SecretReference::parse(&required("AUTH_KEY_PROVIDER")?)?, + }) + } +} + +#[derive(Clone)] +struct AppState { + database: Option, + key_provider_configured: bool, +} + +/// Builds the public health-only router. Liveness has no dependencies; readiness fails closed. +pub fn router(database: Option, key_provider_configured: bool) -> Router { + Router::new() + .route("/health/live", get(|| async { StatusCode::NO_CONTENT })) + .route("/health/ready", get(ready)) + .with_state(AppState { + database, + key_provider_configured, + }) +} + +async fn ready(State(state): State) -> impl IntoResponse { + let Some(database) = state.database else { + return StatusCode::SERVICE_UNAVAILABLE; + }; + if !state.key_provider_configured { + return StatusCode::SERVICE_UNAVAILABLE; + } + match database.health_check().await { + Ok(()) => StatusCode::NO_CONTENT, + Err(_) => StatusCode::SERVICE_UNAVAILABLE, + } +} diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs new file mode 100644 index 000000000..8f10574cc --- /dev/null +++ b/apps/auth-service/src/main.rs @@ -0,0 +1,26 @@ +#![allow(missing_docs)] + +use auth_service::{AuthConfig, router}; +use piquel_repository::Database; +use std::net::SocketAddr; + +#[tokio::main] +async fn main() -> anyhow::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 listener = tokio::net::TcpListener::bind(listener_address).await?; + tracing::info!(%listener_address, "auth service listening"); + axum::serve( + listener, + router(Some(database), config.key_provider.is_configured()), + ) + .with_graceful_shutdown(shutdown_signal()) + .await?; + Ok(()) +} + +async fn shutdown_signal() { + let _ = tokio::signal::ctrl_c().await; +} diff --git a/crates/auth-protocol/Cargo.toml b/crates/auth-protocol/Cargo.toml new file mode 100644 index 000000000..f84654292 --- /dev/null +++ b/crates/auth-protocol/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "piquel-auth-protocol" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +serde.workspace = true +thiserror.workspace = true +uuid.workspace = true + +[lints] +workspace = true diff --git a/crates/auth-protocol/src/lib.rs b/crates/auth-protocol/src/lib.rs new file mode 100644 index 000000000..bc2ae890f --- /dev/null +++ b/crates/auth-protocol/src/lib.rs @@ -0,0 +1,197 @@ +//! Stable, framework-independent values shared by authentication participants. + +use serde::{Deserialize, Serialize}; +use std::{fmt, str::FromStr}; +use thiserror::Error; +use uuid::Uuid; + +/// An invalid protocol value received at a trust boundary. +#[derive(Debug, Clone, Error, PartialEq, Eq)] +#[error("invalid {kind}")] +pub struct InvalidValue { + kind: &'static str, +} + +impl InvalidValue { + const fn new(kind: &'static str) -> Self { + Self { kind } + } +} + +macro_rules! uuid_id { + ($name:ident, $doc:literal) => { + #[doc = $doc] + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] + #[serde(try_from = "String", into = "String")] + pub struct $name(Uuid); + + impl Default for $name { + fn default() -> Self { + Self::new() + } + } + + impl $name { + /// Generates a `UUIDv7` value. + #[must_use] + pub fn new() -> Self { + Self(Uuid::now_v7()) + } + /// Returns the canonical lower-case UUID string. + #[must_use] + pub fn as_uuid(self) -> Uuid { + self.0 + } + } + impl fmt::Display for $name { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(formatter) + } + } + impl FromStr for $name { + type Err = InvalidValue; + fn from_str(value: &str) -> Result { + let parsed = + Uuid::parse_str(value).map_err(|_| InvalidValue::new(stringify!($name)))?; + if parsed.get_version_num() != 7 || parsed.hyphenated().to_string() != value { + return Err(InvalidValue::new(stringify!($name))); + } + Ok(Self(parsed)) + } + } + 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.to_string() + } + } + }; +} + +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")] +pub enum AccountStatus { + /// The account can authenticate. + Active, + /// The account is administratively unavailable. + Disabled, +} + +/// Authentication method recorded on a session or token. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AuthenticationMethod { + /// A `WebAuthn` passkey authenticated the user. + 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)] +mod tests { + use super::*; + + #[test] + fn ids_are_canonical_uuid_v7() { + let id = UserId::new(); + assert_eq!(id.to_string().parse::(), Ok(id)); + assert!( + "00000000-0000-4000-8000-000000000000" + .parse::() + .is_err() + ); + 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/Cargo.toml b/crates/configuration/Cargo.toml new file mode 100644 index 000000000..f447bddef --- /dev/null +++ b/crates/configuration/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "piquel-configuration" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +url.workspace = true + +[lints] +workspace = true diff --git a/crates/configuration/src/lib.rs b/crates/configuration/src/lib.rs new file mode 100644 index 000000000..648239ed0 --- /dev/null +++ b/crates/configuration/src/lib.rs @@ -0,0 +1,103 @@ +//! Small validated configuration primitives. Secrets are references, never values. + +use std::{fmt, net::SocketAddr, str::FromStr, time::Duration}; +use thiserror::Error; +use url::Url; + +/// A configuration parsing error safe to display to an operator. +#[derive(Debug, Error)] +pub enum ConfigurationError { + /// A required variable was not set. + #[error("required configuration {0} is missing")] + Missing(&'static str), + /// The configured value was malformed. + #[error("configuration {name} is invalid")] + Invalid { + /// Name of the invalid setting; its value is deliberately omitted. + name: &'static str, + }, +} + +/// Validated URL that must use HTTPS outside explicitly local development. +#[derive(Clone, Debug)] +pub struct PublicUrl(Url); +impl PublicUrl { + /// Parses a base URL without query or fragment components. + /// + /// # Errors + /// + /// Returns an error when the value is not an absolute HTTP(S) origin. + pub fn parse(value: &str) -> Result { + let url = Url::parse(value).map_err(|_| ConfigurationError::Invalid { name: "URL" })?; + if !matches!(url.scheme(), "https" | "http") + || url.host_str().is_none() + || url.query().is_some() + || url.fragment().is_some() + { + return Err(ConfigurationError::Invalid { name: "URL" }); + } + Ok(Self(url)) + } + /// Returns the parsed URL. + #[must_use] + pub fn as_url(&self) -> &Url { + &self.0 + } +} + +/// A secret-provider locator whose value is deliberately redacted in diagnostics. +#[derive(Clone, PartialEq, Eq)] +pub struct SecretReference(String); +impl SecretReference { + /// Parses a non-empty reference such as `env://AUTH_SIGNING_KEY`. + /// + /// # Errors + /// + /// Returns an error for empty or whitespace-containing references. + pub fn parse(value: &str) -> Result { + if value.trim().is_empty() || value.chars().any(char::is_whitespace) { + return Err(ConfigurationError::Invalid { + name: "secret reference", + }); + } + Ok(Self(value.to_owned())) + } + /// Indicates a configured reference without exposing it. + #[must_use] + pub fn is_configured(&self) -> bool { + true + } +} +impl fmt::Debug for SecretReference { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SecretReference(REDACTED)") + } +} +impl fmt::Display for SecretReference { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("[REDACTED]") + } +} + +/// 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)) +} diff --git a/crates/database/Cargo.toml b/crates/database/Cargo.toml new file mode 100644 index 000000000..01586356d --- /dev/null +++ b/crates/database/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "piquel-repository" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +async-trait.workspace = true +anyhow.workspace = true +chrono.workspace = true +piquel-auth-protocol = { path = "../auth-protocol" } +sqlx.workspace = true +thiserror.workspace = true +tokio.workspace = true +tracing.workspace = true + +[dev-dependencies] +tokio.workspace = true + +[lints] +workspace = true diff --git a/crates/database/README.md b/crates/database/README.md new file mode 100644 index 000000000..f1c1ae74b --- /dev/null +++ b/crates/database/README.md @@ -0,0 +1,10 @@ +# 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. + +Run migrations explicitly with `just migrate "$DATABASE_URL"`. 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. diff --git a/crates/database/migrations/0001_initial_extensions.sql b/crates/database/migrations/0001_initial_extensions.sql new file mode 100644 index 000000000..ff7fb7593 --- /dev/null +++ b/crates/database/migrations/0001_initial_extensions.sql @@ -0,0 +1,2 @@ +-- Reserved initial migration. UUIDv7 values are generated by the application. +-- Tables are introduced only by their owning feature migrations. diff --git a/crates/database/src/bin/migrate.rs b/crates/database/src/bin/migrate.rs new file mode 100644 index 000000000..b29209f99 --- /dev/null +++ b/crates/database/src/bin/migrate.rs @@ -0,0 +1,12 @@ +#![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 new file mode 100644 index 000000000..4efeed937 --- /dev/null +++ b/crates/database/src/connection.rs @@ -0,0 +1,114 @@ +use crate::{ + DatabaseConnectionError, DatabaseError, repositories::*, transaction::DatabaseTransaction, +}; +use sqlx::{PgPool, postgres::PgPoolOptions}; +use std::time::Duration; + +/// Validated database connection configuration. +#[derive(Clone)] +pub struct DatabaseConfig { + url: String, + max_connections: u32, + connect_timeout: Duration, +} +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("max_connections", &self.max_connections) + .field("connect_timeout", &self.connect_timeout) + .finish() + } +} +impl DatabaseConfig { + /// Creates configuration without exposing the URL through `Debug`. + pub fn new( + url: String, + max_connections: u32, + connect_timeout: Duration, + ) -> Result { + if !url.starts_with("postgres://") && !url.starts_with("postgresql://") + || max_connections == 0 + || connect_timeout.is_zero() + { + return Err(DatabaseConnectionError::InvalidConfiguration); + } + Ok(Self { + url, + max_connections, + connect_timeout, + }) + } +} + +/// Typed database boundary. Its pool is intentionally private. +#[derive(Clone)] +pub struct Database { + pool: PgPool, +} +impl Database { + /// Connects without running migrations; releases must run them explicitly. + pub async fn connect(config: DatabaseConfig) -> Result { + let pool = PgPoolOptions::new() + .max_connections(config.max_connections) + .acquire_timeout(config.connect_timeout) + .connect(&config.url) + .await + .map_err(|_| DatabaseConnectionError::Unavailable)?; + Ok(Self { pool }) + } + /// Checks availability with a bounded, non-sensitive query. + pub async fn health_check(&self) -> Result<(), DatabaseError> { + sqlx::query("SELECT 1") + .execute(&self.pool) + .await + .map(|_| ()) + .map_err(crate::error::map_error) + } + /// Opens an explicit short-lived transaction. + pub async fn begin(&self) -> Result, DatabaseError> { + self.pool + .begin() + .await + .map(DatabaseTransaction::new) + .map_err(crate::error::map_error) + } + /// Runs immutable migrations only when explicitly invoked by the migration binary. + pub async fn run_migrations(&self) -> Result<(), DatabaseError> { + sqlx::migrate!("./migrations") + .run(&self.pool) + .await + .map_err(|_| DatabaseError::Internal) + } + pub fn users(&self) -> UserRepository<'_> { + UserRepository::new() + } + pub fn emails(&self) -> EmailRepository<'_> { + EmailRepository::new() + } + pub fn sessions(&self) -> SessionRepository<'_> { + SessionRepository::new() + } + pub fn audit_events(&self) -> AuditEventRepository<'_> { + AuditEventRepository::new() + } + pub fn internal_events(&self) -> InternalEventRepository<'_> { + InternalEventRepository::new() + } + pub fn passkeys(&self) -> PasskeyRepository<'_> { + PasskeyRepository::new() + } + pub fn oidc(&self) -> OidcRepository<'_> { + OidcRepository::new() + } + pub fn tokens(&self) -> TokenRepository<'_> { + TokenRepository::new() + } + pub fn federation(&self) -> FederationRepository<'_> { + FederationRepository::new() + } + pub fn service_identities(&self) -> ServiceIdentityRepository<'_> { + ServiceIdentityRepository::new() + } +} diff --git a/crates/database/src/error.rs b/crates/database/src/error.rs new file mode 100644 index 000000000..1dd17304d --- /dev/null +++ b/crates/database/src/error.rs @@ -0,0 +1,43 @@ +use thiserror::Error; + +/// Stable, non-SQL database failure categories. +#[derive(Debug, 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, +} + +/// Errors that can occur while constructing the database boundary. +#[derive(Debug, Error)] +pub enum DatabaseConnectionError { + #[error("database configuration is invalid")] + InvalidConfiguration, + #[error("database connection is unavailable")] + Unavailable, +} + +pub(crate) fn map_error(error: sqlx::Error) -> DatabaseError { + match error { + sqlx::Error::RowNotFound => DatabaseError::NotFound, + sqlx::Error::PoolTimedOut => DatabaseError::Timeout, + sqlx::Error::PoolClosed | sqlx::Error::Io(_) | sqlx::Error::Tls(_) => { + DatabaseError::Unavailable + } + sqlx::Error::Database(database_error) if database_error.is_unique_violation() => { + DatabaseError::Conflict + } + _ => DatabaseError::Internal, + } +} diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs new file mode 100644 index 000000000..44b710fd5 --- /dev/null +++ b/crates/database/src/lib.rs @@ -0,0 +1,25 @@ +//! 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. +#![allow(missing_docs)] +#![allow( + clippy::missing_errors_doc, + clippy::must_use_candidate, + clippy::wildcard_imports +)] + +mod connection; +mod error; +mod repositories; +mod transaction; + +pub use connection::{Database, DatabaseConfig}; +pub use error::{DatabaseConnectionError, DatabaseError}; +pub use repositories::{ + AuditEventRepository, EmailRepository, FederationRepository, InternalEventRepository, + OidcRepository, PasskeyRepository, ServiceIdentityRepository, SessionRepository, + TokenRepository, UserRepository, +}; +pub use transaction::DatabaseTransaction; diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs new file mode 100644 index 000000000..cca051f13 --- /dev/null +++ b/crates/database/src/repositories.rs @@ -0,0 +1,23 @@ +//! Domain repository handles. SQL implementations are added by owning plans. + +macro_rules! repository { + ($name:ident) => { + /// Focused persistence handle; it has no policy and no public SQL escape hatch. + pub struct $name<'a>(std::marker::PhantomData<&'a mut ()>); + impl<'a> $name<'a> { + pub(crate) const fn new() -> Self { + Self(std::marker::PhantomData) + } + } + }; +} +repository!(UserRepository); +repository!(EmailRepository); +repository!(SessionRepository); +repository!(AuditEventRepository); +repository!(InternalEventRepository); +repository!(PasskeyRepository); +repository!(OidcRepository); +repository!(TokenRepository); +repository!(FederationRepository); +repository!(ServiceIdentityRepository); diff --git a/crates/database/src/transaction.rs b/crates/database/src/transaction.rs new file mode 100644 index 000000000..d86ecb1a6 --- /dev/null +++ b/crates/database/src/transaction.rs @@ -0,0 +1,48 @@ +use crate::{DatabaseError, repositories::*}; +use sqlx::{Postgres, Transaction}; + +/// A private-SQLx transaction with the same typed repository families as `Database`. +pub struct DatabaseTransaction<'a> { + inner: Transaction<'a, Postgres>, +} +impl<'a> DatabaseTransaction<'a> { + pub(crate) const fn new(inner: Transaction<'a, Postgres>) -> Self { + Self { inner } + } + pub fn users(&mut self) -> UserRepository<'_> { + UserRepository::new() + } + pub fn emails(&mut self) -> EmailRepository<'_> { + EmailRepository::new() + } + pub fn sessions(&mut self) -> SessionRepository<'_> { + SessionRepository::new() + } + pub fn audit_events(&mut self) -> AuditEventRepository<'_> { + AuditEventRepository::new() + } + pub fn internal_events(&mut self) -> InternalEventRepository<'_> { + InternalEventRepository::new() + } + pub fn passkeys(&mut self) -> PasskeyRepository<'_> { + PasskeyRepository::new() + } + pub fn oidc(&mut self) -> OidcRepository<'_> { + OidcRepository::new() + } + pub fn tokens(&mut self) -> TokenRepository<'_> { + TokenRepository::new() + } + pub fn federation(&mut self) -> FederationRepository<'_> { + FederationRepository::new() + } + pub fn service_identities(&mut self) -> ServiceIdentityRepository<'_> { + ServiceIdentityRepository::new() + } + pub async fn commit(self) -> Result<(), DatabaseError> { + self.inner.commit().await.map_err(crate::error::map_error) + } + pub async fn rollback(self) -> Result<(), DatabaseError> { + self.inner.rollback().await.map_err(crate::error::map_error) + } +} diff --git a/crates/telemetry/Cargo.toml b/crates/telemetry/Cargo.toml new file mode 100644 index 000000000..a2cb8e0b8 --- /dev/null +++ b/crates/telemetry/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "piquel-telemetry" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +tracing.workspace = true +tracing-subscriber.workspace = true + +[lints] +workspace = true diff --git a/crates/telemetry/src/lib.rs b/crates/telemetry/src/lib.rs new file mode 100644 index 000000000..d5820d719 --- /dev/null +++ b/crates/telemetry/src/lib.rs @@ -0,0 +1,36 @@ +//! Sanitized tracing setup and values for security-sensitive services. + +use std::fmt; +use tracing_subscriber::{EnvFilter, fmt::format::FmtSpan}; + +/// A value deliberately rendered as `[REDACTED]` in all tracing output. +pub struct Redacted(T); +impl Redacted { + /// Wraps a sensitive value before it reaches telemetry. + #[must_use] + pub const fn new(value: T) -> Self { + Self(value) + } +} +impl fmt::Debug for Redacted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("[REDACTED]") + } +} +impl fmt::Display for Redacted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("[REDACTED]") + } +} + +/// Initializes structured stderr tracing with a conservative default filter. +pub fn init(default_filter: &str) { + let filter = + EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_filter)); + tracing_subscriber::fmt() + .with_env_filter(filter) + .with_span_events(FmtSpan::NONE) + .with_target(false) + .compact() + .init(); +} diff --git a/justfile b/justfile new file mode 100644 index 000000000..1e928f98f --- /dev/null +++ b/justfile @@ -0,0 +1,14 @@ +format: + cargo fmt --all + +check: + cargo check --workspace --all-targets + +test: + cargo test --workspace + +migrate database_url: + DATABASE_URL={{database_url}} cargo run -p piquel-repository --bin migrate + +prepare-sqlx: + cargo sqlx prepare --workspace From 5bfe68564d23b5adcb9f3732972255ba25b7ff0e Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 15:04:31 +0200 Subject: [PATCH 02/22] fix(auth): make foundation boundaries executable and fail closed --- .gitignore | 2 + Cargo.lock | 3 + Cargo.toml | 3 +- apps/auth-service/Cargo.toml | 4 + apps/auth-service/src/lib.rs | 130 +++++++++++++++++++++----- apps/auth-service/src/main.rs | 9 +- crates/configuration/src/lib.rs | 106 +++++++++++++++++++-- crates/database/Cargo.toml | 1 + crates/database/README.md | 3 +- crates/database/src/connection.rs | 137 +++++++++++++++++++++++----- crates/database/src/repositories.rs | 26 +++++- crates/database/src/transaction.rs | 20 ++-- justfile | 4 +- 13 files changed, 375 insertions(+), 73 deletions(-) diff --git a/.gitignore b/.gitignore index ad6795588..6da1e4743 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ # will have compiled files and executables debug target +node_modules +.svelte-kit # These are backup files generated by rustfmt **/*.rs.bk diff --git a/Cargo.lock b/Cargo.lock index 351cef922..59850f57e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,12 +63,14 @@ name = "auth-service" version = "0.1.0" dependencies = [ "anyhow", + "async-trait", "axum", "piquel-configuration", "piquel-repository", "piquel-telemetry", "serde", "tokio", + "tower", "tracing", ] @@ -1048,6 +1050,7 @@ dependencies = [ "thiserror", "tokio", "tracing", + "url", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 6b538d029..8b4b12a28 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,8 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "migrate", "macros"] } thiserror = "2.0" -tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net"] } +tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time"] } +tower = { version = "0.5", features = ["util"] } tower-http = { version = "0.6", features = ["trace"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 46ee8a15a..beee79662 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -8,6 +8,7 @@ rust-version.workspace = true [dependencies] anyhow.workspace = true +async-trait.workspace = true axum.workspace = true piquel-configuration = { path = "../../crates/configuration" } piquel-repository = { path = "../../crates/database" } @@ -16,5 +17,8 @@ serde.workspace = true tokio.workspace = true tracing.workspace = true +[dev-dependencies] +tower.workspace = true + [lints] workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 6939ba33a..cca390dff 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -1,10 +1,11 @@ //! 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, time::Duration}; +use std::{env, net::SocketAddr, sync::Arc, time::Duration}; /// Typed auth-service configuration. #[derive(Clone, Debug)] @@ -29,8 +30,22 @@ impl AuthConfig { 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")?)? + } else { + PublicUrl::parse(&required("AUTH_PUBLIC_BASE_URL")?)? + }; + 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", + })?; Ok(Self { - public_base_url: PublicUrl::parse(&required("AUTH_PUBLIC_BASE_URL")?)?, + public_base_url, public_listener: socket_addr( "AUTH_PUBLIC_LISTENER", &required("AUTH_PUBLIC_LISTENER")?, @@ -39,42 +54,113 @@ impl AuthConfig { "AUTH_INTERNAL_LISTENER", &required("AUTH_INTERNAL_LISTENER")?, )?, - database: DatabaseConfig::new(database_url, 10, Duration::from_secs(5)).map_err( - |_| ConfigurationError::Invalid { - name: "AUTH_DATABASE_URL", - }, - )?, + database, key_provider: SecretReference::parse(&required("AUTH_KEY_PROVIDER")?)?, }) } } +/// 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, + 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(|_| ()) + }) + .await + .map_err(|_| ())? + } +} + #[derive(Clone)] struct AppState { - database: Option, - key_provider_configured: bool, + readiness: Arc, } /// Builds the public health-only router. Liveness has no dependencies; readiness fails closed. -pub fn router(database: Option, key_provider_configured: bool) -> Router { +pub fn router(readiness: Arc) -> Router { Router::new() .route("/health/live", get(|| async { StatusCode::NO_CONTENT })) .route("/health/ready", get(ready)) - .with_state(AppState { - database, - key_provider_configured, - }) + .with_state(AppState { readiness }) } async fn ready(State(state): State) -> impl IntoResponse { - let Some(database) = state.database else { - return StatusCode::SERVICE_UNAVAILABLE; - }; - if !state.key_provider_configured { - return StatusCode::SERVICE_UNAVAILABLE; - } - match database.health_check().await { + match state.readiness.check().await { Ok(()) => StatusCode::NO_CONTENT, - Err(_) => StatusCode::SERVICE_UNAVAILABLE, + Err(()) => StatusCode::SERVICE_UNAVAILABLE, + } +} + +#[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))); + 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))) + .oneshot( + axum::http::Request::get("/health/ready") + .body(axum::body::Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + assert_eq!(response.status(), StatusCode::NO_CONTENT); } } diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index 8f10574cc..b0314ffb1 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -1,8 +1,8 @@ #![allow(missing_docs)] -use auth_service::{AuthConfig, router}; +use auth_service::{AuthConfig, ProductionReadiness, router}; use piquel_repository::Database; -use std::net::SocketAddr; +use std::{net::SocketAddr, sync::Arc}; #[tokio::main] async fn main() -> anyhow::Result<()> { @@ -14,7 +14,10 @@ async fn main() -> anyhow::Result<()> { tracing::info!(%listener_address, "auth service listening"); axum::serve( listener, - router(Some(database), config.key_provider.is_configured()), + router(Arc::new(ProductionReadiness::new( + database, + config.key_provider, + ))), ) .with_graceful_shutdown(shutdown_signal()) .await?; diff --git a/crates/configuration/src/lib.rs b/crates/configuration/src/lib.rs index 648239ed0..5623c14b6 100644 --- a/crates/configuration/src/lib.rs +++ b/crates/configuration/src/lib.rs @@ -1,6 +1,11 @@ //! Small validated configuration primitives. Secrets are references, never values. -use std::{fmt, net::SocketAddr, str::FromStr, time::Duration}; +use std::{ + env, fmt, fs, + net::{IpAddr, SocketAddr}, + str::FromStr, + time::Duration, +}; use thiserror::Error; use url::Url; @@ -26,10 +31,10 @@ impl PublicUrl { /// /// # Errors /// - /// Returns an error when the value is not an absolute HTTP(S) origin. + /// Returns an error when the value is not an absolute HTTPS origin. pub fn parse(value: &str) -> Result { let url = Url::parse(value).map_err(|_| ConfigurationError::Invalid { name: "URL" })?; - if !matches!(url.scheme(), "https" | "http") + if url.scheme() != "https" || url.host_str().is_none() || url.query().is_some() || url.fragment().is_some() @@ -38,6 +43,30 @@ impl PublicUrl { } Ok(Self(url)) } + + /// Parses an explicit local-development HTTP(S) base URL. + /// + /// # Errors + /// + /// Returns an error unless the URL uses HTTP(S) and a loopback hostname. + pub fn parse_development(value: &str) -> Result { + let url = Url::parse(value).map_err(|_| ConfigurationError::Invalid { name: "URL" })?; + let host = url + .host_str() + .ok_or(ConfigurationError::Invalid { name: "URL" })?; + let loopback = host.eq_ignore_ascii_case("localhost") + || host + .parse::() + .is_ok_and(|address| address.is_loopback()); + if !loopback + || !matches!(url.scheme(), "http" | "https") + || url.query().is_some() + || url.fragment().is_some() + { + return Err(ConfigurationError::Invalid { name: "URL" }); + } + Ok(Self(url)) + } /// Returns the parsed URL. #[must_use] pub fn as_url(&self) -> &Url { @@ -55,17 +84,60 @@ impl SecretReference { /// /// Returns an error for empty or whitespace-containing references. pub fn parse(value: &str) -> Result { - if value.trim().is_empty() || value.chars().any(char::is_whitespace) { + let allowed = ["env://", "file://", "kms://"]; + if value.trim().is_empty() + || value.chars().any(char::is_whitespace) + || !allowed.iter().any(|prefix| value.starts_with(prefix)) + || allowed.contains(&value) + { return Err(ConfigurationError::Invalid { name: "secret reference", }); } Ok(Self(value.to_owned())) } - /// Indicates a configured reference without exposing it. + /// Resolves environment and file references for local key providers. + /// + /// # Errors + /// + /// Returns an error when the provider is unsupported or the secret is unavailable. + pub fn resolve(&self) -> Result { + let bytes = if let Some(name) = self.0.strip_prefix("env://") { + env::var(name) + .map(String::into_bytes) + .map_err(|_| ConfigurationError::Invalid { + name: "secret reference", + })? + } else if let Some(path) = self.0.strip_prefix("file://") { + fs::read(path).map_err(|_| ConfigurationError::Invalid { + name: "secret reference", + })? + } else { + return Err(ConfigurationError::Invalid { + name: "unsupported key provider", + }); + }; + if bytes.is_empty() { + return Err(ConfigurationError::Invalid { + name: "secret reference", + }); + } + Ok(SecretBytes(bytes)) + } +} + +/// Resolved secret bytes whose diagnostic formatting is always redacted. +pub struct SecretBytes(Vec); +impl SecretBytes { + /// Exposes bytes only to the security component that requested them. #[must_use] - pub fn is_configured(&self) -> bool { - true + pub fn expose_secret(&self) -> &[u8] { + &self.0 + } +} +impl fmt::Debug for SecretBytes { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SecretBytes(REDACTED)") } } impl fmt::Debug for SecretReference { @@ -101,3 +173,23 @@ pub fn seconds(name: &'static str, value: &str) -> Result Result { - if !url.starts_with("postgres://") && !url.starts_with("postgresql://") - || max_connections == 0 - || connect_timeout.is_zero() - { - return Err(DatabaseConnectionError::InvalidConfiguration); - } + Self::validate(&url, max_connections, connect_timeout, false)?; + Ok(Self { + url, + max_connections, + connect_timeout, + }) + } + + /// Creates explicit local-development configuration for a loopback database. + pub fn new_development( + url: String, + max_connections: u32, + connect_timeout: Duration, + ) -> Result { + Self::validate(&url, max_connections, connect_timeout, true)?; Ok(Self { url, max_connections, connect_timeout, }) } + + fn validate( + url: &str, + max_connections: u32, + connect_timeout: Duration, + development: bool, + ) -> Result<(), DatabaseConnectionError> { + let parsed = Url::parse(url).map_err(|_| DatabaseConnectionError::InvalidConfiguration)?; + if !matches!(parsed.scheme(), "postgres" | "postgresql") + || max_connections == 0 + || connect_timeout.is_zero() + { + return Err(DatabaseConnectionError::InvalidConfiguration); + } + let host = parsed + .host_str() + .ok_or(DatabaseConnectionError::InvalidConfiguration)?; + if development { + let loopback = host.eq_ignore_ascii_case("localhost") + || host + .parse::() + .is_ok_and(|address| address.is_loopback()); + if !loopback { + return Err(DatabaseConnectionError::InvalidConfiguration); + } + } else if !parsed + .query_pairs() + .any(|(name, value)| name == "sslmode" && value == "verify-full") + { + return Err(DatabaseConnectionError::InvalidConfiguration); + } + Ok(()) + } } /// Typed database boundary. Its pool is intentionally private. @@ -60,11 +103,14 @@ impl Database { } /// Checks availability with a bounded, non-sensitive query. pub async fn health_check(&self) -> Result<(), DatabaseError> { - sqlx::query("SELECT 1") - .execute(&self.pool) - .await - .map(|_| ()) - .map_err(crate::error::map_error) + tokio::time::timeout( + Duration::from_secs(2), + sqlx::query("SELECT 1").execute(&self.pool), + ) + .await + .map_err(|_| DatabaseError::Timeout)? + .map(|_| ()) + .map_err(crate::error::map_error) } /// Opens an explicit short-lived transaction. pub async fn begin(&self) -> Result, DatabaseError> { @@ -82,33 +128,78 @@ impl Database { .map_err(|_| DatabaseError::Internal) } pub fn users(&self) -> UserRepository<'_> { - UserRepository::new() + UserRepository::from_pool(&self.pool) } pub fn emails(&self) -> EmailRepository<'_> { - EmailRepository::new() + EmailRepository::from_pool(&self.pool) } pub fn sessions(&self) -> SessionRepository<'_> { - SessionRepository::new() + SessionRepository::from_pool(&self.pool) } pub fn audit_events(&self) -> AuditEventRepository<'_> { - AuditEventRepository::new() + AuditEventRepository::from_pool(&self.pool) } pub fn internal_events(&self) -> InternalEventRepository<'_> { - InternalEventRepository::new() + InternalEventRepository::from_pool(&self.pool) } pub fn passkeys(&self) -> PasskeyRepository<'_> { - PasskeyRepository::new() + PasskeyRepository::from_pool(&self.pool) } pub fn oidc(&self) -> OidcRepository<'_> { - OidcRepository::new() + OidcRepository::from_pool(&self.pool) } pub fn tokens(&self) -> TokenRepository<'_> { - TokenRepository::new() + TokenRepository::from_pool(&self.pool) } pub fn federation(&self) -> FederationRepository<'_> { - FederationRepository::new() + FederationRepository::from_pool(&self.pool) } pub fn service_identities(&self) -> ServiceIdentityRepository<'_> { - ServiceIdentityRepository::new() + ServiceIdentityRepository::from_pool(&self.pool) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn production_requires_verified_tls() { + assert!( + DatabaseConfig::new( + "postgres://db.example/piquel".into(), + 1, + Duration::from_secs(1) + ) + .is_err() + ); + assert!( + DatabaseConfig::new( + "postgres://db.example/piquel?sslmode=verify-full".into(), + 1, + Duration::from_secs(1) + ) + .is_ok() + ); + } + + #[test] + fn development_is_loopback_only() { + assert!( + DatabaseConfig::new_development( + "postgres://localhost/piquel".into(), + 1, + Duration::from_secs(1) + ) + .is_ok() + ); + assert!( + DatabaseConfig::new_development( + "postgres://db.example/piquel".into(), + 1, + Duration::from_secs(1) + ) + .is_err() + ); } } diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index cca051f13..54d3ea3cb 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,12 +1,30 @@ -//! Domain repository handles. SQL implementations are added by owning plans. +//! Domain repository handles backed by a private pool or transaction connection. + +use sqlx::{PgConnection, PgPool}; + +#[allow(dead_code)] +pub(crate) enum RepositoryExecutor<'a> { + Pool(&'a PgPool), + Connection(&'a mut PgConnection), +} macro_rules! repository { ($name:ident) => { /// Focused persistence handle; it has no policy and no public SQL escape hatch. - pub struct $name<'a>(std::marker::PhantomData<&'a mut ()>); + pub struct $name<'a> { + #[allow(dead_code)] + pub(crate) executor: RepositoryExecutor<'a>, + } impl<'a> $name<'a> { - pub(crate) const fn new() -> Self { - Self(std::marker::PhantomData) + pub(crate) const fn from_pool(pool: &'a PgPool) -> Self { + Self { + executor: RepositoryExecutor::Pool(pool), + } + } + pub(crate) fn from_connection(connection: &'a mut PgConnection) -> Self { + Self { + executor: RepositoryExecutor::Connection(connection), + } } } }; diff --git a/crates/database/src/transaction.rs b/crates/database/src/transaction.rs index d86ecb1a6..d9316dc72 100644 --- a/crates/database/src/transaction.rs +++ b/crates/database/src/transaction.rs @@ -10,34 +10,34 @@ impl<'a> DatabaseTransaction<'a> { Self { inner } } pub fn users(&mut self) -> UserRepository<'_> { - UserRepository::new() + UserRepository::from_connection(&mut self.inner) } pub fn emails(&mut self) -> EmailRepository<'_> { - EmailRepository::new() + EmailRepository::from_connection(&mut self.inner) } pub fn sessions(&mut self) -> SessionRepository<'_> { - SessionRepository::new() + SessionRepository::from_connection(&mut self.inner) } pub fn audit_events(&mut self) -> AuditEventRepository<'_> { - AuditEventRepository::new() + AuditEventRepository::from_connection(&mut self.inner) } pub fn internal_events(&mut self) -> InternalEventRepository<'_> { - InternalEventRepository::new() + InternalEventRepository::from_connection(&mut self.inner) } pub fn passkeys(&mut self) -> PasskeyRepository<'_> { - PasskeyRepository::new() + PasskeyRepository::from_connection(&mut self.inner) } pub fn oidc(&mut self) -> OidcRepository<'_> { - OidcRepository::new() + OidcRepository::from_connection(&mut self.inner) } pub fn tokens(&mut self) -> TokenRepository<'_> { - TokenRepository::new() + TokenRepository::from_connection(&mut self.inner) } pub fn federation(&mut self) -> FederationRepository<'_> { - FederationRepository::new() + FederationRepository::from_connection(&mut self.inner) } pub fn service_identities(&mut self) -> ServiceIdentityRepository<'_> { - ServiceIdentityRepository::new() + ServiceIdentityRepository::from_connection(&mut self.inner) } pub async fn commit(self) -> Result<(), DatabaseError> { self.inner.commit().await.map_err(crate::error::map_error) diff --git a/justfile b/justfile index 1e928f98f..48beccb43 100644 --- a/justfile +++ b/justfile @@ -7,8 +7,8 @@ check: test: cargo test --workspace -migrate database_url: - DATABASE_URL={{database_url}} cargo run -p piquel-repository --bin migrate +migrate: + cargo run -p piquel-repository --bin migrate prepare-sqlx: cargo sqlx prepare --workspace From e77eeab842221ede7ae0f183c5ced4c8c778d3f1 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 17:39:47 +0200 Subject: [PATCH 03/22] fix(ci): pin the declared Rust toolchain --- rust-toolchain.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain.toml b/rust-toolchain.toml index f4ebfd764..9ff98ae57 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "stable" +channel = "1.97.0" components = [ "rustfmt", "clippy" ] From 9e19a391c0cba1fde9b7d2b69fb26d08d6a69b7c Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:04:54 +0200 Subject: [PATCH 04/22] feat(auth): add identity and session schema --- Cargo.lock | 2 + Cargo.toml | 1 + apps/auth-service/Cargo.toml | 2 + apps/auth-service/src/account.rs | 44 +++++++++++ apps/auth-service/src/audit.rs | 15 ++++ apps/auth-service/src/email.rs | 52 ++++++++++++ apps/auth-service/src/event_log.rs | 14 ++++ apps/auth-service/src/lib.rs | 11 +++ apps/auth-service/src/session.rs | 32 ++++++++ .../migrations/0002_identity_sessions.sql | 79 +++++++++++++++++++ docs/security/email-normalization.md | 7 ++ 11 files changed, 259 insertions(+) create mode 100644 apps/auth-service/src/account.rs create mode 100644 apps/auth-service/src/audit.rs create mode 100644 apps/auth-service/src/email.rs create mode 100644 apps/auth-service/src/event_log.rs create mode 100644 apps/auth-service/src/session.rs create mode 100644 crates/database/migrations/0002_identity_sessions.sql create mode 100644 docs/security/email-normalization.md diff --git a/Cargo.lock b/Cargo.lock index 59850f57e..6453d47c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -65,6 +65,7 @@ dependencies = [ "anyhow", "async-trait", "axum", + "piquel-auth-protocol", "piquel-configuration", "piquel-repository", "piquel-telemetry", @@ -72,6 +73,7 @@ dependencies = [ "tokio", "tower", "tracing", + "unicode-normalization", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 8b4b12a28..09068e410 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,4 +39,5 @@ tower-http = { version = "0.6", features = ["trace"] } tracing = "0.1" 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"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index beee79662..cb033f6c4 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -10,12 +10,14 @@ rust-version.workspace = true anyhow.workspace = true async-trait.workspace = true axum.workspace = true +piquel-auth-protocol = { path = "../../crates/auth-protocol" } piquel-configuration = { path = "../../crates/configuration" } piquel-repository = { path = "../../crates/database" } piquel-telemetry = { path = "../../crates/telemetry" } serde.workspace = true tokio.workspace = true tracing.workspace = true +unicode-normalization.workspace = true [dev-dependencies] tower.workspace = true diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs new file mode 100644 index 000000000..992491cc4 --- /dev/null +++ b/apps/auth-service/src/account.rs @@ -0,0 +1,44 @@ +//! Account policy boundaries; persistence is delegated to the repository crate. + +use piquel_auth_protocol::{AccountStatus, UserId}; + +/// 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, +} + +/// 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::*; + #[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()); + } +} diff --git a/apps/auth-service/src/audit.rs b/apps/auth-service/src/audit.rs new file mode 100644 index 000000000..c632886d7 --- /dev/null +++ b/apps/auth-service/src/audit.rs @@ -0,0 +1,15 @@ +//! 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/email.rs b/apps/auth-service/src/email.rs new file mode 100644 index 000000000..a27845790 --- /dev/null +++ b/apps/auth-service/src/email.rs @@ -0,0 +1,52 @@ +//! Conservative email handling policy. + +use unicode_normalization::UnicodeNormalization; + +/// A normalized email suitable for exact equality checks. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct NormalizedEmail(String); + +impl NormalizedEmail { + /// Returns the database-safe normalized representation. + pub(super) fn as_str(&self) -> &str { + &self.0 + } +} + +/// Normalizes Unicode canonically, lowercases only the domain, and preserves +/// the local part exactly. It intentionally does not remove dots or plus tags. +pub(super) fn normalize(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() || value.len() > 254 || value.chars().any(char::is_control) { + return Err(()); + } + let (local, domain) = value.rsplit_once('@').ok_or(())?; + if local.is_empty() || domain.is_empty() || local.len() > 64 || domain.contains('@') { + return Err(()); + } + let local = local.nfc().collect::(); + let domain = domain.nfc().collect::().to_lowercase(); + if domain.starts_with('.') || domain.ends_with('.') || !domain.contains('.') { + return Err(()); + } + Ok(NormalizedEmail(format!("{local}@{domain}"))) +} + +#[cfg(test)] +mod tests { + use super::normalize; + #[test] + fn preserves_provider_specific_local_part_semantics() { + assert_eq!( + normalize("Ada+jobs@Example.COM") + .expect("valid normalized email") + .as_str(), + "Ada+jobs@example.com" + ); + assert_ne!(normalize("a.da@example.com"), normalize("ada@example.com")); + } + #[test] + fn rejects_ambiguous_values() { + assert!(normalize("not-an-email").is_err()); + } +} diff --git a/apps/auth-service/src/event_log.rs b/apps/auth-service/src/event_log.rs new file mode 100644 index 000000000..d6e5a7a94 --- /dev/null +++ b/apps/auth-service/src/event_log.rs @@ -0,0 +1,14 @@ +//! 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/lib.rs b/apps/auth-service/src/lib.rs index cca390dff..a637575e3 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -7,6 +7,17 @@ use piquel_configuration::{ConfigurationError, PublicUrl, SecretReference, socke 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)] +mod email; +#[allow(dead_code)] +mod event_log; +#[allow(dead_code)] +mod session; + /// Typed auth-service configuration. #[derive(Clone, Debug)] pub struct AuthConfig { diff --git a/apps/auth-service/src/session.rs b/apps/auth-service/src/session.rs new file mode 100644 index 000000000..3953ee3b6 --- /dev/null +++ b/apps/auth-service/src/session.rs @@ -0,0 +1,32 @@ +//! Central-session policy values. + +use piquel_auth_protocol::{AuthenticationMethod, SessionId, UserId}; +use std::time::Duration; + +/// 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, +} + +/// 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(()) +} diff --git a/crates/database/migrations/0002_identity_sessions.sql b/crates/database/migrations/0002_identity_sessions.sql new file mode 100644 index 000000000..cfcd26c4d --- /dev/null +++ b/crates/database/migrations/0002_identity_sessions.sql @@ -0,0 +1,79 @@ +CREATE TABLE users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + profile_version BIGINT NOT NULL DEFAULT 1 CHECK (profile_version > 0), + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE user_emails ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + normalized_email TEXT NOT NULL, + verified_at TIMESTAMPTZ, + is_primary BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (NOT is_primary OR verified_at IS NOT NULL) +); +CREATE INDEX user_emails_user_id_idx ON user_emails (user_id); +CREATE INDEX user_emails_verified_lookup_idx ON user_emails (normalized_email) WHERE verified_at IS NOT NULL; +CREATE UNIQUE INDEX user_emails_one_primary_verified_idx ON user_emails (user_id) WHERE is_primary AND verified_at IS NOT NULL; + +-- A trigger, rather than a blanket unique index, permits a disabled account's +-- verified address to be claimed by one active account while rejecting two +-- active owners. It locks matching verified rows to make concurrent claims safe. +CREATE OR REPLACE FUNCTION enforce_active_verified_email_uniqueness() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.verified_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM user_emails existing + JOIN users existing_user ON existing_user.id = existing.user_id + JOIN users new_user ON new_user.id = NEW.user_id + WHERE existing.normalized_email = NEW.normalized_email + AND existing.id <> NEW.id + AND existing.verified_at IS NOT NULL + AND existing_user.status = 'active' + AND new_user.status = 'active' + ) THEN RAISE EXCEPTION 'verified email already belongs to an active account' USING ERRCODE = 'unique_violation'; END IF; + RETURN NEW; +END $$; +CREATE TRIGGER user_emails_active_verified_unique BEFORE INSERT OR UPDATE OF normalized_email, verified_at, user_id ON user_emails FOR EACH ROW EXECUTE FUNCTION enforce_active_verified_email_uniqueness(); + +CREATE TABLE sessions ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id), + authentication_methods JSONB NOT NULL, + authenticated_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + last_seen_at TIMESTAMPTZ NOT NULL, + user_agent_family TEXT, + revoked_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (expires_at > authenticated_at) +); +CREATE INDEX sessions_active_user_idx ON sessions (user_id, expires_at) WHERE revoked_at IS NULL; + +CREATE TABLE security_audit_log ( + id UUID PRIMARY KEY, + user_id UUID REFERENCES users(id), + action TEXT NOT NULL, + outcome TEXT NOT NULL CHECK (outcome IN ('success', 'failure', 'rejected')), + request_metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + 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/docs/security/email-normalization.md b/docs/security/email-normalization.md new file mode 100644 index 000000000..b34233c40 --- /dev/null +++ b/docs/security/email-normalization.md @@ -0,0 +1,7 @@ +# Email normalization + +Piquel normalizes an email by NFC-normalizing its local and domain components +and lowercasing the domain only. The local part is otherwise preserved exactly: +Piquel does not strip `+` suffixes, remove dots, or apply provider-specific +equivalence. Email is an optional verified contact attribute, never an account +identifier; `UserId` is the downstream identity reference. From 10ce3b6068024eb538f17cf1c11b9586a52ba4d4 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 15:16:31 +0200 Subject: [PATCH 05/22] fix(auth): implement transactional identity repositories --- .dockerignore | 4 + Cargo.lock | 4 + Cargo.toml | 2 +- apps/auth-service/Cargo.toml | 3 + apps/auth-service/src/account.rs | 83 +++++- crates/auth-protocol/src/lib.rs | 12 + crates/database/Cargo.toml | 1 + crates/database/README.md | 5 + .../migrations/0002_identity_sessions.sql | 69 ++++- crates/database/src/lib.rs | 2 + crates/database/src/models.rs | 79 +++++ crates/database/src/repositories.rs | 250 +++++++++++++++- crates/database/tests/Dockerfile | 4 + crates/database/tests/identity.rs | 269 ++++++++++++++++++ justfile | 3 + 15 files changed, 772 insertions(+), 18 deletions(-) create mode 100644 .dockerignore create mode 100644 crates/database/src/models.rs create mode 100644 crates/database/tests/Dockerfile create mode 100644 crates/database/tests/identity.rs diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..2be2db253 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +target +node_modules +.git +.svelte-kit diff --git a/Cargo.lock b/Cargo.lock index 6453d47c1..7d09626ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -65,11 +65,14 @@ dependencies = [ "anyhow", "async-trait", "axum", + "chrono", "piquel-auth-protocol", "piquel-configuration", "piquel-repository", "piquel-telemetry", "serde", + "serde_json", + "thiserror", "tokio", "tower", "tracing", @@ -1048,6 +1051,7 @@ dependencies = [ "async-trait", "chrono", "piquel-auth-protocol", + "serde_json", "sqlx", "thiserror", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 09068e410..05f7b5a21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,7 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "serd http = "1.3" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "migrate", "macros"] } +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "migrate", "macros"] } thiserror = "2.0" tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time"] } tower = { version = "0.5", features = ["util"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index cb033f6c4..00fa7997f 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -10,11 +10,14 @@ rust-version.workspace = true anyhow.workspace = true async-trait.workspace = true axum.workspace = true +chrono.workspace = true piquel-auth-protocol = { path = "../../crates/auth-protocol" } piquel-configuration = { path = "../../crates/configuration" } piquel-repository = { path = "../../crates/database" } piquel-telemetry = { path = "../../crates/telemetry" } serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true tokio.workspace = true tracing.workspace = true unicode-normalization.workspace = true diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs index 992491cc4..27b0fcdc8 100644 --- a/apps/auth-service/src/account.rs +++ b/apps/auth-service/src/account.rs @@ -1,6 +1,13 @@ //! Account policy boundaries; persistence is delegated to the repository crate. -use piquel_auth_protocol::{AccountStatus, UserId}; +use crate::email::normalize; +use chrono::Utc; +use piquel_auth_protocol::{AccountStatus, TokenId, UserId}; +use piquel_repository::{ + AppendAuditEvent, AppendInternalEvent, Database, DatabaseError, InsertUser, + InsertVerifiedEmail, StoredUser, +}; +use thiserror::Error; /// Validated account profile snapshot used by the identity service. #[derive(Clone, Debug, PartialEq, Eq)] @@ -12,6 +19,80 @@ pub(super) struct AccountProfile { pub status: AccountStatus, } +pub(super) struct CreateAccount { + pub username: String, + pub display_name: String, + pub verified_email: Option, +} + +#[derive(Debug, Error)] +pub(super) enum AccountError { + #[error("invalid account profile")] + InvalidProfile, + #[error("account operation failed")] + Database(#[from] DatabaseError), +} + +/// 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) +} + /// Checks the deliberately narrow username policy used for initial accounts. pub(super) fn validate_username(value: &str) -> Result<(), ()> { if !(3..=32).contains(&value.len()) diff --git a/crates/auth-protocol/src/lib.rs b/crates/auth-protocol/src/lib.rs index bc2ae890f..a387322f9 100644 --- a/crates/auth-protocol/src/lib.rs +++ b/crates/auth-protocol/src/lib.rs @@ -42,6 +42,18 @@ macro_rules! uuid_id { pub fn as_uuid(self) -> Uuid { self.0 } + + /// Validates and wraps an existing UUID. + /// + /// # Errors + /// + /// Returns an error unless the value is `UUIDv7`. + pub fn from_uuid(value: Uuid) -> Result { + if value.get_version_num() != 7 { + return Err(InvalidValue::new(stringify!($name))); + } + Ok(Self(value)) + } } impl fmt::Display for $name { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/database/Cargo.toml b/crates/database/Cargo.toml index aa41d327d..63f093a22 100644 --- a/crates/database/Cargo.toml +++ b/crates/database/Cargo.toml @@ -11,6 +11,7 @@ async-trait.workspace = true anyhow.workspace = true chrono.workspace = true piquel-auth-protocol = { path = "../auth-protocol" } +serde_json.workspace = true sqlx.workspace = true thiserror.workspace = true tokio.workspace = true diff --git a/crates/database/README.md b/crates/database/README.md index 742cf4def..17bb72a85 100644 --- a/crates/database/README.md +++ b/crates/database/README.md @@ -9,3 +9,8 @@ Set `DATABASE_URL` in the process environment and run migrations explicitly with 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. + +The ignored PostgreSQL suite is explicit: set `TEST_DATABASE_URL` to an +isolated database and run `just test-database`. The checked-in test Dockerfile +can run the same suite on a container network when the host cannot reach the +database container. diff --git a/crates/database/migrations/0002_identity_sessions.sql b/crates/database/migrations/0002_identity_sessions.sql index cfcd26c4d..bbccfaabb 100644 --- a/crates/database/migrations/0002_identity_sessions.sql +++ b/crates/database/migrations/0002_identity_sessions.sql @@ -21,24 +21,63 @@ CREATE INDEX user_emails_user_id_idx ON user_emails (user_id); CREATE INDEX user_emails_verified_lookup_idx ON user_emails (normalized_email) WHERE verified_at IS NOT NULL; CREATE UNIQUE INDEX user_emails_one_primary_verified_idx ON user_emails (user_id) WHERE is_primary AND verified_at IS NOT NULL; --- A trigger, rather than a blanket unique index, permits a disabled account's --- verified address to be claimed by one active account while rejecting two --- active owners. It locks matching verified rows to make concurrent claims safe. -CREATE OR REPLACE FUNCTION enforce_active_verified_email_uniqueness() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +-- The ownership row makes the no-existing-email concurrency case safe: the +-- normalized address itself is the unique lockable key. +CREATE TABLE active_verified_email_ownership ( + normalized_email TEXT PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE +); + +CREATE OR REPLACE FUNCTION claim_active_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.verified_at IS NOT NULL AND (SELECT status = 'active' FROM users WHERE id = NEW.user_id) THEN + INSERT INTO active_verified_email_ownership(normalized_email, user_id) + VALUES (NEW.normalized_email, NEW.user_id) + ON CONFLICT (normalized_email) DO UPDATE SET user_id = EXCLUDED.user_id + WHERE active_verified_email_ownership.user_id = EXCLUDED.user_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'verified email already belongs to an active account' USING ERRCODE = 'unique_violation'; + END IF; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER user_emails_claim_active_verified BEFORE INSERT OR UPDATE OF normalized_email, verified_at, user_id ON user_emails FOR EACH ROW EXECUTE FUNCTION claim_active_verified_email(); + +CREATE OR REPLACE FUNCTION release_active_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN - IF NEW.verified_at IS NOT NULL AND EXISTS ( - SELECT 1 FROM user_emails existing - JOIN users existing_user ON existing_user.id = existing.user_id - JOIN users new_user ON new_user.id = NEW.user_id - WHERE existing.normalized_email = NEW.normalized_email - AND existing.id <> NEW.id - AND existing.verified_at IS NOT NULL - AND existing_user.status = 'active' - AND new_user.status = 'active' - ) THEN RAISE EXCEPTION 'verified email already belongs to an active account' USING ERRCODE = 'unique_violation'; END IF; + IF OLD.verified_at IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM user_emails e JOIN users u ON u.id=e.user_id + WHERE e.user_id=OLD.user_id AND e.normalized_email=OLD.normalized_email + AND e.verified_at IS NOT NULL AND e.id<>OLD.id AND u.status='active' + ) THEN DELETE FROM active_verified_email_ownership WHERE normalized_email=OLD.normalized_email AND user_id=OLD.user_id; END IF; + RETURN OLD; +END $$; +CREATE TRIGGER user_emails_release_active_verified AFTER DELETE OR UPDATE OF normalized_email, verified_at, user_id ON user_emails FOR EACH ROW EXECUTE FUNCTION release_active_verified_email(); + +CREATE OR REPLACE FUNCTION synchronize_user_email_ownership() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE address TEXT; +BEGIN + IF NEW.status='disabled' THEN DELETE FROM active_verified_email_ownership WHERE user_id=NEW.id; + ELSIF OLD.status='disabled' AND NEW.status='active' THEN + FOR address IN SELECT DISTINCT normalized_email FROM user_emails WHERE user_id=NEW.id AND verified_at IS NOT NULL LOOP + INSERT INTO active_verified_email_ownership(normalized_email,user_id) VALUES(address,NEW.id) + ON CONFLICT(normalized_email) DO UPDATE SET user_id=EXCLUDED.user_id WHERE active_verified_email_ownership.user_id=EXCLUDED.user_id; + IF NOT FOUND THEN RAISE EXCEPTION 'verified email already belongs to an active account' USING ERRCODE='unique_violation'; END IF; + END LOOP; + END IF; RETURN NEW; END $$; -CREATE TRIGGER user_emails_active_verified_unique BEFORE INSERT OR UPDATE OF normalized_email, verified_at, user_id ON user_emails FOR EACH ROW EXECUTE FUNCTION enforce_active_verified_email_uniqueness(); +CREATE TRIGGER users_synchronize_email_ownership BEFORE UPDATE OF status ON users FOR EACH ROW EXECUTE FUNCTION synchronize_user_email_ownership(); + +CREATE OR REPLACE FUNCTION enforce_primary_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE affected UUID := COALESCE(NEW.user_id, OLD.user_id); +BEGIN + IF EXISTS (SELECT 1 FROM user_emails WHERE user_id=affected AND verified_at IS NOT NULL) + AND (SELECT count(*) FROM user_emails WHERE user_id=affected AND verified_at IS NOT NULL AND is_primary) <> 1 + THEN RAISE EXCEPTION 'verified emails require exactly one primary' USING ERRCODE='check_violation'; END IF; + RETURN COALESCE(NEW, OLD); +END $$; +CREATE CONSTRAINT TRIGGER user_emails_exactly_one_primary AFTER INSERT OR UPDATE OR DELETE ON user_emails DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION enforce_primary_verified_email(); CREATE TABLE sessions ( id UUID PRIMARY KEY, diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs index 44b710fd5..78351761e 100644 --- a/crates/database/src/lib.rs +++ b/crates/database/src/lib.rs @@ -12,11 +12,13 @@ mod connection; mod error; +mod models; mod repositories; mod transaction; pub use connection::{Database, DatabaseConfig}; pub use error::{DatabaseConnectionError, DatabaseError}; +pub use models::*; pub use repositories::{ AuditEventRepository, EmailRepository, FederationRepository, InternalEventRepository, OidcRepository, PasskeyRepository, ServiceIdentityRepository, SessionRepository, diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs new file mode 100644 index 000000000..9cde503b6 --- /dev/null +++ b/crates/database/src/models.rs @@ -0,0 +1,79 @@ +use chrono::{DateTime, Utc}; +use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; +use serde_json::Value; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredUser { + pub id: UserId, + pub username: String, + pub display_name: String, + pub profile_version: u64, + pub status: AccountStatus, + pub created_at: DateTime, + pub updated_at: DateTime, +} +#[derive(Clone, Debug)] +pub struct InsertUser { + pub id: UserId, + 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, + pub user_id: UserId, + pub normalized_email: String, + pub verified_at: Option>, + pub is_primary: bool, +} +#[derive(Clone, Debug)] +pub struct InsertVerifiedEmail { + pub id: TokenId, + pub user_id: UserId, + pub normalized_email: String, + pub is_primary: bool, + pub verified_at: DateTime, +} +#[derive(Clone, Debug)] +pub struct InsertSession { + pub id: SessionId, + pub user_id: UserId, + pub authentication_methods: Vec, + pub authenticated_at: DateTime, + pub expires_at: DateTime, + pub user_agent_family: Option, +} +#[derive(Clone, Debug)] +pub struct StoredSession { + pub id: SessionId, + pub user_id: UserId, + pub authentication_methods: Vec, + pub authenticated_at: DateTime, + pub expires_at: DateTime, + pub last_seen_at: DateTime, + pub revoked_at: Option>, +} +#[derive(Clone, Debug)] +pub struct AppendAuditEvent { + pub id: TokenId, + pub user_id: Option, + pub action: String, + 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, +} diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 54d3ea3cb..abc7b202a 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,6 +1,11 @@ //! Domain repository handles backed by a private pool or transaction connection. -use sqlx::{PgConnection, PgPool}; +use crate::{ + AppendAuditEvent, AppendInternalEvent, DatabaseError, InsertSession, InsertUser, + InsertVerifiedEmail, StoredEmail, StoredSession, StoredUser, UpdateUserProfile, +}; +use piquel_auth_protocol::{AccountStatus, SessionId, UserId}; +use sqlx::{PgConnection, PgPool, Row}; #[allow(dead_code)] pub(crate) enum RepositoryExecutor<'a> { @@ -39,3 +44,246 @@ repository!(OidcRepository); repository!(TokenRepository); repository!(FederationRepository); repository!(ServiceIdentityRepository); + +macro_rules! fetch_optional { + ($self:expr, $query:expr) => {{ + match &mut $self.executor { + RepositoryExecutor::Pool(pool) => $query.fetch_optional(*pool).await, + RepositoryExecutor::Connection(connection) => { + $query.fetch_optional(&mut **connection).await + } + } + .map_err(crate::error::map_error) + }}; +} +macro_rules! fetch_one { + ($self:expr, $query:expr) => {{ + match &mut $self.executor { + RepositoryExecutor::Pool(pool) => $query.fetch_one(*pool).await, + RepositoryExecutor::Connection(connection) => $query.fetch_one(&mut **connection).await, + } + .map_err(crate::error::map_error) + }}; +} +macro_rules! execute { + ($self:expr, $query:expr) => {{ + match &mut $self.executor { + RepositoryExecutor::Pool(pool) => $query.execute(*pool).await, + RepositoryExecutor::Connection(connection) => $query.execute(&mut **connection).await, + } + .map_err(crate::error::map_error) + }}; +} + +fn stored_user(row: &sqlx::postgres::PgRow) -> Result { + let status = match row + .try_get::("status") + .map_err(|_| DatabaseError::InvalidStoredData)? + .as_str() + { + "active" => AccountStatus::Active, + "disabled" => AccountStatus::Disabled, + _ => return Err(DatabaseError::InvalidStoredData), + }; + let version = u64::try_from( + row.try_get::("profile_version") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?; + Ok(StoredUser { + id: UserId::from_uuid( + row.try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + username: row + .try_get("username") + .map_err(|_| DatabaseError::InvalidStoredData)?, + display_name: row + .try_get("display_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + profile_version: version, + status, + created_at: row + .try_get("created_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + updated_at: row + .try_get("updated_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} + +impl UserRepository<'_> { + pub async fn insert(&mut self, input: &InsertUser) -> Result { + let row = fetch_one!(self, sqlx::query("INSERT INTO users (id, username, display_name) VALUES ($1, $2, $3) RETURNING id, username, display_name, profile_version, status, created_at, updated_at").bind(input.id.as_uuid()).bind(&input.username).bind(&input.display_name))?; + stored_user(&row) + } + 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 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<'_> { + pub async fn insert_verified( + &mut self, + input: &InsertVerifiedEmail, + ) -> Result { + let row = fetch_one!(self, sqlx::query("INSERT INTO user_emails (id, user_id, normalized_email, verified_at, is_primary) VALUES ($1, $2, $3, $4, $5) RETURNING id, user_id, normalized_email, verified_at, is_primary").bind(input.id.as_uuid()).bind(input.user_id.as_uuid()).bind(&input.normalized_email).bind(input.verified_at).bind(input.is_primary))?; + Ok(StoredEmail { + id: piquel_auth_protocol::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)?, + normalized_email: row + .try_get("normalized_email") + .map_err(|_| DatabaseError::InvalidStoredData)?, + verified_at: row + .try_get("verified_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + is_primary: row + .try_get("is_primary") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + } + pub async fn find_active_verified( + &mut self, + normalized: &str, + ) -> Result, DatabaseError> { + let row = fetch_optional!(self, sqlx::query("SELECT e.id, e.user_id, e.normalized_email, e.verified_at, e.is_primary FROM active_verified_email_ownership o JOIN user_emails e ON e.user_id = o.user_id AND e.normalized_email = o.normalized_email AND e.verified_at IS NOT NULL WHERE o.normalized_email = $1 ORDER BY e.is_primary DESC, e.created_at LIMIT 1").bind(normalized))?; + row.map(|row| { + Ok(StoredEmail { + id: piquel_auth_protocol::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)?, + normalized_email: row + .try_get("normalized_email") + .map_err(|_| DatabaseError::InvalidStoredData)?, + verified_at: row + .try_get("verified_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + is_primary: row + .try_get("is_primary") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + }) + .transpose() + } +} + +impl SessionRepository<'_> { + pub async fn insert(&mut self, input: &InsertSession) -> Result { + let methods = serde_json::to_value(&input.authentication_methods) + .map_err(|_| DatabaseError::Internal)?; + let row = fetch_one!(self, sqlx::query("INSERT INTO sessions (id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at, user_agent_family) VALUES ($1,$2,$3,$4,$5,$4,$6) RETURNING id,user_id,authentication_methods,authenticated_at,expires_at,last_seen_at,revoked_at").bind(input.id.as_uuid()).bind(input.user_id.as_uuid()).bind(methods).bind(input.authenticated_at).bind(input.expires_at).bind(&input.user_agent_family))?; + stored_session(&row) + } + pub async fn find_by_id( + &mut self, + id: SessionId, + ) -> Result, DatabaseError> { + fetch_optional!(self, sqlx::query("SELECT id,user_id,authentication_methods,authenticated_at,expires_at,last_seen_at,revoked_at FROM sessions WHERE id=$1").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 SET last_seen_at=now() WHERE id=$1 AND revoked_at IS NULL AND expires_at>now()").bind(id.as_uuid()))?.rows_affected()==1) + } + pub async fn revoke(&mut self, id: SessionId) -> Result { + Ok(execute!( + self, + sqlx::query("UPDATE sessions SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL") + .bind(id.as_uuid()) + )? + .rows_affected() + == 1) + } +} +fn stored_session(row: &sqlx::postgres::PgRow) -> Result { + let methods: serde_json::Value = row + .try_get("authentication_methods") + .map_err(|_| DatabaseError::InvalidStoredData)?; + Ok(StoredSession { + id: SessionId::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)?, + authentication_methods: serde_json::from_value(methods) + .map_err(|_| DatabaseError::InvalidStoredData)?, + authenticated_at: row + .try_get("authenticated_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + expires_at: row + .try_get("expires_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + last_seen_at: row + .try_get("last_seen_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + revoked_at: row + .try_get("revoked_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} + +impl AuditEventRepository<'_> { + pub async fn append(&mut self, input: &AppendAuditEvent) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("INSERT INTO security_audit_log (id,user_id,action,outcome,request_metadata) VALUES ($1,$2,$3,$4,$5)").bind(input.id.as_uuid()).bind(input.user_id.map(UserId::as_uuid)).bind(&input.action).bind(&input.outcome).bind(&input.request_metadata))?; + 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) + } +} diff --git a/crates/database/tests/Dockerfile b/crates/database/tests/Dockerfile new file mode 100644 index 000000000..031f7b09b --- /dev/null +++ b/crates/database/tests/Dockerfile @@ -0,0 +1,4 @@ +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 new file mode 100644 index 000000000..b93a11f21 --- /dev/null +++ b/crates/database/tests/identity.rs @@ -0,0 +1,269 @@ +#![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, 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 username = format!("{prefix}_{}", &id.to_string()[..8]); + 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; + 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"); + assert!( + database + .sessions() + .revoke(session_id) + .await + .expect("revoke") + ); + assert!( + !database + .sessions() + .revoke(session_id) + .await + .expect("idempotent revoke") + ); + + 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); +} diff --git a/justfile b/justfile index 48beccb43..7f455646b 100644 --- a/justfile +++ b/justfile @@ -7,6 +7,9 @@ check: test: cargo test --workspace +test-database: + cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 + migrate: cargo run -p piquel-repository --bin migrate From 5c16fcc4d4f5b70706d4d9392e3d1b3dfae8825b Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:43:12 +0200 Subject: [PATCH 06/22] fix(auth): make account disablement a session invariant --- apps/auth-service/src/account.rs | 40 +++++++++++++++++++++++++++++ crates/database/src/repositories.rs | 27 ++++++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs index 27b0fcdc8..d3c7a0865 100644 --- a/apps/auth-service/src/account.rs +++ b/apps/auth-service/src/account.rs @@ -93,6 +93,46 @@ pub(super) async fn create( 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) +} + /// Checks the deliberately narrow username policy used for initial accounts. pub(super) fn validate_username(value: &str) -> Result<(), ()> { if !(3..=32).contains(&value.len()) diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index abc7b202a..788391287 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -121,6 +121,12 @@ 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_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, @@ -216,7 +222,10 @@ impl SessionRepository<'_> { pub async fn insert(&mut self, input: &InsertSession) -> Result { let methods = serde_json::to_value(&input.authentication_methods) .map_err(|_| DatabaseError::Internal)?; - let row = fetch_one!(self, sqlx::query("INSERT INTO sessions (id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at, user_agent_family) VALUES ($1,$2,$3,$4,$5,$4,$6) RETURNING id,user_id,authentication_methods,authenticated_at,expires_at,last_seen_at,revoked_at").bind(input.id.as_uuid()).bind(input.user_id.as_uuid()).bind(methods).bind(input.authenticated_at).bind(input.expires_at).bind(&input.user_agent_family))?; + // Lock the account row through insertion so disablement and session + // creation have a single serialization point. A session can never be + // committed for an account that was disabled first. + let row = fetch_one!(self, sqlx::query("WITH active_user AS (SELECT id FROM users WHERE id=$2 AND status='active' FOR UPDATE) INSERT INTO sessions (id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at, user_agent_family) SELECT $1,id,$3,$4,$5,$4,$6 FROM active_user RETURNING id,user_id,authentication_methods,authenticated_at,expires_at,last_seen_at,revoked_at").bind(input.id.as_uuid()).bind(input.user_id.as_uuid()).bind(methods).bind(input.authenticated_at).bind(input.expires_at).bind(&input.user_agent_family))?; stored_session(&row) } pub async fn find_by_id( @@ -225,6 +234,12 @@ impl SessionRepository<'_> { ) -> Result, DatabaseError> { fetch_optional!(self, sqlx::query("SELECT id,user_id,authentication_methods,authenticated_at,expires_at,last_seen_at,revoked_at FROM sessions WHERE id=$1").bind(id.as_uuid()))?.map(|row| stored_session(&row)).transpose() } + pub async fn find_active_by_id( + &mut self, + id: SessionId, + ) -> 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 SET last_seen_at=now() WHERE id=$1 AND revoked_at IS NULL AND expires_at>now()").bind(id.as_uuid()))?.rows_affected()==1) } @@ -237,6 +252,16 @@ 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 From ac051cf022658d6cf3d2756e2981f82fa12855bd Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:06:04 +0200 Subject: [PATCH 07/22] feat(auth): add passkey ceremony foundation --- Cargo.toml | 1 + apps/auth-service/Cargo.toml | 1 + apps/auth-service/src/lib.rs | 2 + apps/auth-service/src/passkey.rs | 74 +++++++++++++++++++ .../migrations/0003_passkey_credentials.sql | 29 ++++++++ 5 files changed, 107 insertions(+) create mode 100644 apps/auth-service/src/passkey.rs create mode 100644 crates/database/migrations/0003_passkey_credentials.sql diff --git a/Cargo.toml b/Cargo.toml index 05f7b5a21..94a653269 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "serd http = "1.3" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +sha2 = "0.10" sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "migrate", "macros"] } thiserror = "2.0" tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 00fa7997f..5747f931f 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -18,6 +18,7 @@ piquel-telemetry = { path = "../../crates/telemetry" } serde.workspace = true serde_json.workspace = true thiserror.workspace = true +sha2.workspace = true tokio.workspace = true tracing.workspace = true unicode-normalization.workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index a637575e3..e8a12feb4 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -16,6 +16,8 @@ mod email; #[allow(dead_code)] mod event_log; #[allow(dead_code)] +mod passkey; +#[allow(dead_code)] mod session; /// Typed auth-service configuration. diff --git a/apps/auth-service/src/passkey.rs b/apps/auth-service/src/passkey.rs new file mode 100644 index 000000000..1f8df8437 --- /dev/null +++ b/apps/auth-service/src/passkey.rs @@ -0,0 +1,74 @@ +//! `WebAuthn` ceremony invariants independent of a particular authenticator crate. + +use piquel_auth_protocol::{SessionId, UserId}; +use sha2::{Digest, Sha256}; +use std::time::{Duration, SystemTime}; + +/// A short-lived server-side ceremony record. The raw challenge remains only in +/// the replaceable state store; persistence stores this digest and metadata. +#[derive(Clone, Debug)] +pub(super) struct Ceremony { + pub user_id: Option, + pub session_id: Option, + pub challenge_digest: [u8; 32], + pub expires_at: SystemTime, + pub consumed: bool, +} + +pub(super) fn challenge_digest(challenge: &[u8]) -> [u8; 32] { + Sha256::digest(challenge).into() +} +pub(super) fn validate_ceremony( + ceremony: &Ceremony, + challenge: &[u8], + now: SystemTime, +) -> Result<(), ()> { + if ceremony.consumed + || now >= ceremony.expires_at + || ceremony.challenge_digest != challenge_digest(challenge) + { + return Err(()); + } + Ok(()) +} +pub(super) fn ceremony_expiry(now: SystemTime) -> SystemTime { + now + Duration::from_mins(5) +} + +/// The values that must be provided by validated production configuration. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct RelyingParty { + pub id: String, + pub expected_origin: String, + pub user_verification_required: bool, +} +impl RelyingParty { + pub(super) fn validate(&self) -> Result<(), ()> { + if self.id.is_empty() + || !self.expected_origin.starts_with("https://") + || !self.expected_origin.contains(&self.id) + { + return Err(()); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn ceremony_is_single_use_and_short_lived() { + let now = SystemTime::now(); + let challenge = b"opaque-test-challenge"; + let ceremony = Ceremony { + user_id: None, + session_id: None, + challenge_digest: challenge_digest(challenge), + expires_at: ceremony_expiry(now), + consumed: false, + }; + assert!(validate_ceremony(&ceremony, challenge, now).is_ok()); + assert!(validate_ceremony(&ceremony, b"wrong", now).is_err()); + } +} diff --git a/crates/database/migrations/0003_passkey_credentials.sql b/crates/database/migrations/0003_passkey_credentials.sql new file mode 100644 index 000000000..d37230d51 --- /dev/null +++ b/crates/database/migrations/0003_passkey_credentials.sql @@ -0,0 +1,29 @@ +CREATE TABLE passkey_credentials ( + id UUID PRIMARY KEY, + credential_id BYTEA NOT NULL UNIQUE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + public_key BYTEA 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, + revoked_at TIMESTAMPTZ +); +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. +CREATE TABLE webauthn_ceremonies ( + id UUID PRIMARY KEY, + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, + ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ('registration', 'authentication')), + challenge_digest BYTEA NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX webauthn_ceremonies_expiry_idx ON webauthn_ceremonies (expires_at) WHERE consumed_at IS NULL; From 76e3c7039dd7f62ee037ae84cac6f99e7bb94679 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 15:26:34 +0200 Subject: [PATCH 08/22] fix(auth): implement verified passkey ceremonies --- Cargo.lock | 614 +++++++++++++++++- Cargo.toml | 4 + apps/auth-service/Cargo.toml | 6 + apps/auth-service/src/lib.rs | 19 +- apps/auth-service/src/main.rs | 15 +- apps/auth-service/src/passkey.rs | 564 ++++++++++++++-- crates/database/Cargo.toml | 1 + .../migrations/0003_passkey_credentials.sql | 9 +- crates/database/src/models.rs | 34 + crates/database/src/repositories.rs | 137 +++- crates/database/tests/identity.rs | 61 +- 11 files changed, 1366 insertions(+), 98 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7d09626ee..58b7b5fc9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,6 +32,67 @@ version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" +[[package]] +name = "asn1-rs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror 1.0.69", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -65,18 +126,25 @@ dependencies = [ "anyhow", "async-trait", "axum", + "base64 0.22.1", "chrono", + "openssl", "piquel-auth-protocol", "piquel-configuration", "piquel-repository", "piquel-telemetry", + "rand 0.8.7", "serde", "serde_json", - "thiserror", + "sha2", + "thiserror 2.0.18", "tokio", "tower", "tracing", "unicode-normalization", + "url", + "webauthn-authenticator-rs", + "webauthn-rs", ] [[package]] @@ -137,6 +205,12 @@ dependencies = [ "tracing", ] +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + [[package]] name = "base64" version = "0.22.1" @@ -149,6 +223,23 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "base64urlsafedata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b08e33815c87d8cadcddb1e74ac307368a3751fbe40c961538afa21a1899f21c" +dependencies = [ + "base64 0.21.7", + "pastey", + "serde", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.0" @@ -273,6 +364,12 @@ version = "0.8.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -283,6 +380,12 @@ dependencies = [ "typenum", ] +[[package]] +name = "data-encoding" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" + [[package]] name = "der" version = "0.7.10" @@ -294,6 +397,26 @@ dependencies = [ "zeroize", ] +[[package]] +name = "der-parser" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "digest" version = "0.10.7" @@ -393,6 +516,21 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -402,6 +540,21 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.32" @@ -446,6 +599,17 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "futures-sink" version = "0.3.32" @@ -464,8 +628,10 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ + "futures-channel", "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -494,6 +660,18 @@ dependencies = [ "wasi", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -502,7 +680,18 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", ] [[package]] @@ -831,7 +1020,7 @@ version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" dependencies = [ - "bitflags", + "bitflags 2.13.0", "libc", "plain", "redox_syscall 0.9.0", @@ -905,6 +1094,12 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "mio" version = "1.2.2" @@ -916,6 +1111,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -925,6 +1130,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -936,11 +1151,28 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand", + "rand 0.8.7", "smallvec", "zeroize", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "num-integer" version = "0.1.46" @@ -970,12 +1202,68 @@ dependencies = [ "libm", ] +[[package]] +name = "oid-registry" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags 2.13.0", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-src" +version = "300.6.1+3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + [[package]] name = "parking" version = "2.2.1" @@ -1005,6 +1293,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -1031,7 +1325,7 @@ name = "piquel-auth-protocol" version = "0.1.0" dependencies = [ "serde", - "thiserror", + "thiserror 2.0.18", "uuid", ] @@ -1039,7 +1333,7 @@ dependencies = [ name = "piquel-configuration" version = "0.1.0" dependencies = [ - "thiserror", + "thiserror 2.0.18", "url", ] @@ -1053,10 +1347,11 @@ dependencies = [ "piquel-auth-protocol", "serde_json", "sqlx", - "thiserror", + "thiserror 2.0.18", "tokio", "tracing", "url", + "uuid", ] [[package]] @@ -1109,6 +1404,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1136,6 +1437,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -1149,8 +1456,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", ] [[package]] @@ -1160,7 +1477,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -1172,13 +1499,22 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "redox_syscall" version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.0", ] [[package]] @@ -1187,7 +1523,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5102a6aaa05aa011a238e178e6bca86d2cb56fc9f586d37cb80f5bca6e07759" dependencies = [ - "bitflags", + "bitflags 2.13.0", ] [[package]] @@ -1234,13 +1570,22 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", "signature", "spki", "subtle", "zeroize", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + [[package]] name = "rustls" version = "0.23.42" @@ -1303,6 +1648,26 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_cbor_2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aec2709de9078e077090abd848e967abab63c9fb3fdb5d4799ad359d8d482c" +dependencies = [ + "half", + "serde", +] + [[package]] name = "serde_core" version = "1.0.228" @@ -1413,7 +1778,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1479,7 +1844,7 @@ version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "chrono", "crc", @@ -1502,7 +1867,7 @@ dependencies = [ "serde_json", "sha2", "smallvec", - "thiserror", + "thiserror 2.0.18", "tokio", "tokio-stream", "tracing", @@ -1556,8 +1921,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" dependencies = [ "atoi", - "base64", - "bitflags", + "base64 0.22.1", + "bitflags 2.13.0", "byteorder", "bytes", "chrono", @@ -1579,7 +1944,7 @@ dependencies = [ "memchr", "once_cell", "percent-encoding", - "rand", + "rand 0.8.7", "rsa", "serde", "sha1", @@ -1587,7 +1952,7 @@ dependencies = [ "smallvec", "sqlx-core", "stringprep", - "thiserror", + "thiserror 2.0.18", "tracing", "uuid", "whoami", @@ -1600,8 +1965,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" dependencies = [ "atoi", - "base64", - "bitflags", + "base64 0.22.1", + "bitflags 2.13.0", "byteorder", "chrono", "crc", @@ -1619,14 +1984,14 @@ dependencies = [ "md-5", "memchr", "once_cell", - "rand", + "rand 0.8.7", "serde", "serde_json", "sha2", "smallvec", "sqlx-core", "stringprep", - "thiserror", + "thiserror 2.0.18", "tracing", "uuid", "whoami", @@ -1652,7 +2017,7 @@ dependencies = [ "serde", "serde_urlencoded", "sqlx-core", - "thiserror", + "thiserror 2.0.18", "tracing", "url", "uuid", @@ -1709,13 +2074,33 @@ dependencies = [ "syn", ] +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1738,6 +2123,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.3" @@ -1799,6 +2214,20 @@ dependencies = [ "futures-core", "pin-project-lite", "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", ] [[package]] @@ -1985,6 +2414,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasite" version = "0.1.0" @@ -2036,6 +2474,107 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "webauthn-attestation-ca" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6475c0bbd1a3f04afaa3e98880408c5be61680c5e6bd3c6f8c250990d5d3e18e" +dependencies = [ + "base64urlsafedata", + "openssl", + "openssl-sys", + "serde", + "tracing", + "uuid", +] + +[[package]] +name = "webauthn-authenticator-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "779e9c80ff248c7e12ea967f909249101f6e86f70fccd742d4b66c490c1710b4" +dependencies = [ + "async-stream", + "async-trait", + "base64 0.21.7", + "base64urlsafedata", + "bitflags 1.3.2", + "futures", + "hex", + "nom", + "num-derive", + "num-traits", + "openssl", + "openssl-sys", + "serde", + "serde_bytes", + "serde_cbor_2", + "serde_json", + "thiserror 1.0.69", + "tokio", + "tokio-stream", + "tracing", + "unicode-normalization", + "url", + "uuid", + "webauthn-rs-core", + "webauthn-rs-proto", +] + +[[package]] +name = "webauthn-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c548915e0e92ee946bbf2aecf01ea21bef53d974b0793cc6732ba81a03fc422" +dependencies = [ + "base64urlsafedata", + "serde", + "tracing", + "url", + "uuid", + "webauthn-rs-core", +] + +[[package]] +name = "webauthn-rs-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "296d2d501feb715d80b8e186fb88bab1073bca17f460303a1013d17b673bea6a" +dependencies = [ + "base64 0.21.7", + "base64urlsafedata", + "der-parser", + "hex", + "nom", + "openssl", + "openssl-sys", + "rand 0.9.5", + "rand_chacha 0.9.0", + "serde", + "serde_cbor_2", + "serde_json", + "thiserror 1.0.69", + "tracing", + "url", + "uuid", + "webauthn-attestation-ca", + "webauthn-rs-proto", + "x509-parser", +] + +[[package]] +name = "webauthn-rs-proto" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c37393beac9c1ed1ca6dbb30b1e01783fb316ab3a45d90ecd48c99052dd7ef1e" +dependencies = [ + "base64 0.21.7", + "base64urlsafedata", + "serde", + "serde_json", + "url", +] + [[package]] name = "webpki-roots" version = "0.26.11" @@ -2271,12 +2810,35 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +[[package]] +name = "x509-parser" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "rusticata-macros", + "thiserror 1.0.69", + "time", +] + [[package]] name = "yoke" version = "0.8.3" diff --git a/Cargo.toml b/Cargo.toml index 94a653269..48b132d36 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,11 +27,14 @@ unwrap_used = "warn" anyhow = "1.0" async-trait = "0.1" axum = "0.8" +base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } http = "1.3" +openssl = { version = "0.10", features = ["vendored"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.10" +rand = "0.8" sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "migrate", "macros"] } thiserror = "2.0" tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time"] } @@ -42,3 +45,4 @@ 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"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 5747f931f..f1c77aa60 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -10,11 +10,14 @@ rust-version.workspace = true anyhow.workspace = true async-trait.workspace = true axum.workspace = true +base64.workspace = true chrono.workspace = true +openssl.workspace = true piquel-auth-protocol = { path = "../../crates/auth-protocol" } piquel-configuration = { path = "../../crates/configuration" } piquel-repository = { path = "../../crates/database" } piquel-telemetry = { path = "../../crates/telemetry" } +rand.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true @@ -22,9 +25,12 @@ sha2.workspace = true tokio.workspace = true tracing.workspace = true unicode-normalization.workspace = true +url.workspace = true +webauthn-rs.workspace = true [dev-dependencies] tower.workspace = true +webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] } [lints] workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index e8a12feb4..6ac0f4872 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -17,6 +17,7 @@ mod email; mod event_log; #[allow(dead_code)] mod passkey; +pub use passkey::PasskeyApplication; #[allow(dead_code)] mod session; @@ -33,6 +34,8 @@ pub struct AuthConfig { pub database: DatabaseConfig, /// Key-provider locator, never a literal key. pub key_provider: SecretReference, + /// `WebAuthn` relying-party identifier. + pub webauthn_rp_id: String, } impl AuthConfig { /// Loads the minimum service configuration from the environment. @@ -69,6 +72,7 @@ impl AuthConfig { )?, database, key_provider: SecretReference::parse(&required("AUTH_KEY_PROVIDER")?)?, + webauthn_rp_id: required("AUTH_WEBAUTHN_RP_ID")?, }) } } @@ -113,11 +117,16 @@ struct AppState { } /// Builds the public health-only router. Liveness has no dependencies; readiness fails closed. -pub fn router(readiness: Arc) -> Router { - Router::new() +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 }) + .with_state(AppState { readiness }); + if let Some(passkeys) = passkeys { + health.merge(passkey::routes(passkeys)) + } else { + health + } } async fn ready(State(state): State) -> impl IntoResponse { @@ -142,7 +151,7 @@ mod tests { #[tokio::test] async fn liveness_has_no_dependencies_and_readiness_fails_closed() { - let app = router(Arc::new(FixedReadiness(false))); + let app = router(Arc::new(FixedReadiness(false)), None); let live = app .clone() .oneshot( @@ -166,7 +175,7 @@ mod tests { #[tokio::test] async fn readiness_succeeds_with_test_substitutes() { - let response = router(Arc::new(FixedReadiness(true))) + let response = router(Arc::new(FixedReadiness(true)), None) .oneshot( axum::http::Request::get("/health/ready") .body(axum::body::Body::empty()) diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index b0314ffb1..2291b52ed 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -1,6 +1,6 @@ #![allow(missing_docs)] -use auth_service::{AuthConfig, ProductionReadiness, router}; +use auth_service::{AuthConfig, PasskeyApplication, ProductionReadiness, router}; use piquel_repository::Database; use std::{net::SocketAddr, sync::Arc}; @@ -10,14 +10,19 @@ async fn main() -> anyhow::Result<()> { let config = AuthConfig::from_environment()?; let listener_address: SocketAddr = config.public_listener; let database = Database::connect(config.database).await?; + let passkeys = PasskeyApplication::new( + database.clone(), + &config.webauthn_rp_id, + config.public_base_url.as_url(), + )?; 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, - ))), + router( + Arc::new(ProductionReadiness::new(database, config.key_provider)), + Some(passkeys), + ), ) .with_graceful_shutdown(shutdown_signal()) .await?; diff --git a/apps/auth-service/src/passkey.rs b/apps/auth-service/src/passkey.rs index 1f8df8437..bb2e734b0 100644 --- a/apps/auth-service/src/passkey.rs +++ b/apps/auth-service/src/passkey.rs @@ -1,74 +1,526 @@ -//! `WebAuthn` ceremony invariants independent of a particular authenticator crate. +//! `WebAuthn` registration/authentication with database-backed single-use state. -use piquel_auth_protocol::{SessionId, UserId}; +use crate::account::{validate_display_name, validate_username}; +use axum::{ + Json, Router, + extract::State, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{IntoResponse, Response}, + routing::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, + InsertSession, InsertUser, +}; +use rand::{RngCore, rngs::OsRng}; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::time::{Duration, SystemTime}; - -/// A short-lived server-side ceremony record. The raw challenge remains only in -/// the replaceable state store; persistence stores this digest and metadata. -#[derive(Clone, Debug)] -pub(super) struct Ceremony { - pub user_id: Option, - pub session_id: Option, - pub challenge_digest: [u8; 32], - pub expires_at: SystemTime, - pub consumed: bool, -} - -pub(super) fn challenge_digest(challenge: &[u8]) -> [u8; 32] { - Sha256::digest(challenge).into() -} -pub(super) fn validate_ceremony( - ceremony: &Ceremony, - challenge: &[u8], - now: SystemTime, -) -> Result<(), ()> { - if ceremony.consumed - || now >= ceremony.expires_at - || ceremony.challenge_digest != challenge_digest(challenge) +use std::sync::Arc; +use thiserror::Error; +use url::Url; +use webauthn_rs::{ + Webauthn, WebauthnBuilder, + prelude::{ + CreationChallengeResponse, Passkey, PasskeyAuthentication, PasskeyRegistration, + PublicKeyCredential, RegisterPublicKeyCredential, RequestChallengeResponse, + }, +}; + +/// Runnable passkey HTTP application state. +#[derive(Clone)] +pub struct PasskeyApplication { + database: Database, + webauthn: Arc, +} + +#[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, + ) -> 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), + }) + } +} + +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(()); + return Err(PasskeyConfigurationError::Invalid); } Ok(()) } -pub(super) fn ceremony_expiry(now: SystemTime) -> SystemTime { - now + Duration::from_mins(5) + +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("/session/logout", post(logout)) + .with_state(application) } -/// The values that must be provided by validated production configuration. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) struct RelyingParty { - pub id: String, - pub expected_origin: String, - pub user_verification_required: bool, +#[derive(Deserialize)] +struct RegistrationStart { + username: String, + display_name: String, } -impl RelyingParty { - pub(super) fn validate(&self) -> Result<(), ()> { - if self.id.is_empty() - || !self.expected_origin.starts_with("https://") - || !self.expected_origin.contains(&self.id) - { - return Err(()); - } - Ok(()) +#[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, +} +#[derive(Deserialize)] +struct RegistrationFinish { + ceremony_id: TokenId, + credential: RegisterPublicKeyCredential, + #[serde(default = "default_passkey_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, + user_id: Some(user_id), + 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); + } + let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; + let ceremony = transaction + .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)?; + 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 { + user_id: UserId, +} +#[derive(Serialize)] +struct AuthenticationStarted { + ceremony_id: TokenId, + public_key: RequestChallengeResponse, +} +#[derive(Serialize, Deserialize)] +struct AuthenticationState { + user_id: UserId, + webauthn: PasskeyAuthentication, +} +#[derive(Deserialize)] +struct AuthenticationFinish { + ceremony_id: TokenId, + credential: PublicKeyCredential, +} + +async fn start_authentication( + State(app): State, + Json(input): Json, +) -> Result, ApiError> { + let stored = app + .database + .passkeys() + .list_active(input.user_id, 20) + .await + .map_err(|_| ApiError)?; + if stored.is_empty() { + return Err(ApiError); + } + let passkeys = stored + .into_iter() + .map(|stored| serde_json::from_value::(stored.credential).map_err(|_| ApiError)) + .collect::, _>>()?; + let (challenge, webauthn) = app + .webauthn + .start_passkey_authentication(&passkeys) + .map_err(|_| ApiError)?; + let state = serde_json::to_value(AuthenticationState { + user_id: input.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(input.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, + })) +} + +async fn finish_authentication( + State(app): State, + Json(input): Json, +) -> Result { + let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; + let ceremony = transaction + .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 stored = transaction + .passkeys() + .find_active_by_credential_id(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)?; + transaction + .passkeys() + .update_after_authentication(result.cred_id().as_ref(), &credential) + .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.authenticate".into(), + outcome: "success".into(), + request_metadata: serde_json::json!({}), + }) + .await + .map_err(|_| ApiError)?; + transaction.commit().await.map_err(|_| ApiError)?; + no_content_with_cookie(&cookie) +} + +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"})), + ) + .into_response() + } +} +impl From for ApiError { + fn from(_: DatabaseError) -> Self { + Self } } #[cfg(test)] mod tests { use super::*; + use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey}; + #[test] - fn ceremony_is_single_use_and_short_lived() { - let now = SystemTime::now(); - let challenge = b"opaque-test-challenge"; - let ceremony = Ceremony { - user_id: None, - session_id: None, - challenge_digest: challenge_digest(challenge), - expires_at: ceremony_expiry(now), - consumed: false, - }; - assert!(validate_ceremony(&ceremony, challenge, now).is_ok()); - assert!(validate_ceremony(&ceremony, b"wrong", now).is_err()); + 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}" + ); + } + 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())); + } + + #[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()); } } diff --git a/crates/database/Cargo.toml b/crates/database/Cargo.toml index 63f093a22..90fcca22c 100644 --- a/crates/database/Cargo.toml +++ b/crates/database/Cargo.toml @@ -17,6 +17,7 @@ thiserror.workspace = true tokio.workspace = true tracing.workspace = true url.workspace = true +uuid.workspace = true [dev-dependencies] tokio.workspace = true diff --git a/crates/database/migrations/0003_passkey_credentials.sql b/crates/database/migrations/0003_passkey_credentials.sql index d37230d51..5961cfbe7 100644 --- a/crates/database/migrations/0003_passkey_credentials.sql +++ b/crates/database/migrations/0003_passkey_credentials.sql @@ -2,7 +2,7 @@ CREATE TABLE passkey_credentials ( id UUID PRIMARY KEY, credential_id BYTEA NOT NULL UNIQUE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, - public_key BYTEA NOT NULL, + 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, @@ -22,8 +22,15 @@ CREATE TABLE webauthn_ceremonies ( session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ('registration', 'authentication')), challenge_digest BYTEA NOT NULL, + state JSONB NOT NULL, expires_at TIMESTAMPTZ NOT NULL, consumed_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX webauthn_ceremonies_expiry_idx ON webauthn_ceremonies (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, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index 9cde503b6..785cebe12 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -77,3 +77,37 @@ pub struct AppendInternalEvent { pub schema_version: u32, pub payload: Value, } + +#[derive(Clone, Debug)] +pub struct InsertPasskey { + pub id: TokenId, + pub credential_id: Vec, + pub user_id: UserId, + pub credential: Value, + pub friendly_name: String, +} +#[derive(Clone, Debug)] +pub struct StoredPasskey { + pub id: TokenId, + pub credential_id: Vec, + pub user_id: UserId, + pub credential: Value, + pub friendly_name: String, + pub revoked_at: Option>, +} +#[derive(Clone, Debug)] +pub struct InsertCeremony { + pub id: TokenId, + pub user_id: Option, + pub session_id: Option, + pub kind: String, + pub challenge_digest: Vec, + pub state: Value, + pub expires_at: DateTime, +} +#[derive(Clone, Debug)] +pub struct ConsumedCeremony { + pub user_id: Option, + pub session_id: Option, + pub state: Value, +} diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 788391287..69244fae4 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,10 +1,11 @@ //! Domain repository handles backed by a private pool or transaction connection. use crate::{ - AppendAuditEvent, AppendInternalEvent, DatabaseError, InsertSession, InsertUser, - InsertVerifiedEmail, StoredEmail, StoredSession, StoredUser, UpdateUserProfile, + AppendAuditEvent, AppendInternalEvent, ConsumedCeremony, DatabaseError, InsertCeremony, + InsertPasskey, InsertSession, InsertUser, InsertVerifiedEmail, StoredEmail, StoredPasskey, + StoredSession, StoredUser, UpdateUserProfile, }; -use piquel_auth_protocol::{AccountStatus, SessionId, UserId}; +use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; use sqlx::{PgConnection, PgPool, Row}; #[allow(dead_code)] @@ -312,3 +313,133 @@ impl InternalEventRepository<'_> { .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))?; + stored_passkey(&row) + } + + pub async fn list_active( + &mut self, + user_id: UserId, + limit: u32, + ) -> Result, DatabaseError> { + let limit = i64::from(limit.min(20)); + let rows = match &mut self.executor { + RepositoryExecutor::Pool(pool) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at LIMIT $2").bind(user_id.as_uuid()).bind(limit).fetch_all(*pool).await, + RepositoryExecutor::Connection(connection) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at LIMIT $2").bind(user_id.as_uuid()).bind(limit).fetch_all(&mut **connection).await, + }.map_err(crate::error::map_error)?; + 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 update_after_authentication( + &mut self, + credential_id: &[u8], + credential: &serde_json::Value, + ) -> Result { + Ok(execute!(self, sqlx::query("UPDATE passkey_credentials SET credential=$1,last_used_at=now() WHERE credential_id=$2 AND revoked_at IS NULL").bind(credential).bind(credential_id))?.rows_affected()==1) + } + + pub async fn rename( + &mut self, + id: TokenId, + user_id: UserId, + name: &str, + ) -> Result { + Ok(execute!(self, sqlx::query("UPDATE passkey_credentials SET friendly_name=$1 WHERE id=$2 AND user_id=$3 AND revoked_at IS NULL").bind(name).bind(id.as_uuid()).bind(user_id.as_uuid()))?.rows_affected()==1) + } + + pub async fn revoke(&mut self, id: TokenId, user_id: UserId) -> Result { + Ok(execute!(self, sqlx::query("UPDATE passkey_credentials SET revoked_at=now() WHERE id=$1 AND user_id=$2 AND revoked_at IS NULL").bind(id.as_uuid()).bind(user_id.as_uuid()))?.rows_affected()==1) + } + + pub async fn insert_ceremony(&mut self, input: &InsertCeremony) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("INSERT INTO webauthn_ceremonies (id,user_id,session_id,ceremony_kind,challenge_digest,state,expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7)").bind(input.id.as_uuid()).bind(input.user_id.map(UserId::as_uuid)).bind(input.session_id.map(SessionId::as_uuid)).bind(&input.kind).bind(&input.challenge_digest).bind(&input.state).bind(input.expires_at))?; + Ok(()) + } + + pub async fn consume_ceremony( + &mut self, + id: TokenId, + kind: &str, + ) -> Result { + let row = fetch_optional!(self, sqlx::query("UPDATE webauthn_ceremonies SET consumed_at=now() WHERE id=$1 AND ceremony_kind=$2 AND consumed_at IS NULL AND expires_at>now() RETURNING user_id,session_id,state").bind(id.as_uuid()).bind(kind))?.ok_or(DatabaseError::NotFound)?; + Ok(ConsumedCeremony { + user_id: row + .try_get::, _>("user_id") + .map_err(|_| DatabaseError::InvalidStoredData)? + .map(UserId::from_uuid) + .transpose() + .map_err(|_| DatabaseError::InvalidStoredData)?, + session_id: row + .try_get::, _>("session_id") + .map_err(|_| DatabaseError::InvalidStoredData)? + .map(SessionId::from_uuid) + .transpose() + .map_err(|_| DatabaseError::InvalidStoredData)?, + state: row + .try_get("state") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + } +} + +fn stored_passkey(row: &sqlx::postgres::PgRow) -> Result { + Ok(StoredPasskey { + id: TokenId::from_uuid( + row.try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + credential_id: row + .try_get("credential_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + user_id: UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + credential: row + .try_get("credential") + .map_err(|_| DatabaseError::InvalidStoredData)?, + friendly_name: row + .try_get("friendly_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + revoked_at: row + .try_get("revoked_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} + +impl SessionRepository<'_> { + pub async fn insert_browser_secret( + &mut self, + session_id: SessionId, + digest: &[u8], + ) -> Result<(), DatabaseError> { + execute!( + self, + sqlx::query( + "INSERT INTO browser_session_secrets(session_id,secret_digest) VALUES($1,$2)" + ) + .bind(session_id.as_uuid()) + .bind(digest) + )?; + Ok(()) + } + + pub async fn find_active_by_browser_secret( + &mut self, + digest: &[u8], + ) -> 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 browser_session_secrets b JOIN sessions s ON s.id=b.session_id WHERE b.secret_digest=$1 AND s.revoked_at IS NULL AND s.expires_at>now()").bind(digest))?.map(|row| stored_session(&row)).transpose() + } +} diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index b93a11f21..feddf68c9 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -3,8 +3,8 @@ use chrono::{Duration as ChronoDuration, Utc}; use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ - AppendInternalEvent, Database, DatabaseConfig, DatabaseError, InsertSession, InsertUser, - InsertVerifiedEmail, UpdateUserProfile, + AppendInternalEvent, Database, DatabaseConfig, DatabaseError, InsertCeremony, InsertPasskey, + InsertSession, InsertUser, InsertVerifiedEmail, UpdateUserProfile, }; use std::{env, time::Duration}; @@ -108,6 +108,63 @@ async fn identity_transactions_and_concurrency_hold() { let first = insert_user(&database, "first").await; let second = insert_user(&database, "second").await; + + 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) + )); + let normalized = format!("race-{}@example.com", UserId::new()); let one = database.clone(); let two = database.clone(); From d7fa9b186bb952d06d47d9743217bfa26075e741 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:45:09 +0200 Subject: [PATCH 09/22] fix(auth): close passkey lifecycle races and add enrollment --- apps/auth-service/src/passkey.rs | 236 +++++++++++++++++++++++++++- crates/database/src/repositories.rs | 20 ++- 2 files changed, 247 insertions(+), 9 deletions(-) diff --git a/apps/auth-service/src/passkey.rs b/apps/auth-service/src/passkey.rs index bb2e734b0..fc6432145 100644 --- a/apps/auth-service/src/passkey.rs +++ b/apps/auth-service/src/passkey.rs @@ -3,10 +3,10 @@ use crate::account::{validate_display_name, validate_username}; use axum::{ Json, Router, - extract::State, + extract::{Path, State}, http::{HeaderMap, HeaderValue, StatusCode, header}, response::{IntoResponse, Response}, - routing::post, + routing::{get, patch, post}, }; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use chrono::{Duration, Utc}; @@ -95,6 +95,13 @@ pub(super) fn routes(application: PasskeyApplication) -> Router { .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", get(list_passkeys)) + .route( + "/account/passkeys/{id}", + patch(rename_passkey).delete(revoke_passkey), + ) .route("/session/logout", post(logout)) .with_state(application) } @@ -241,7 +248,7 @@ async fn finish_registration( #[derive(Deserialize)] struct AuthenticationStart { - user_id: UserId, + username: String, } #[derive(Serialize)] struct AuthenticationStarted { @@ -263,10 +270,18 @@ 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 stored = app .database .passkeys() - .list_active(input.user_id, 20) + .list_active(user.id, 20) .await .map_err(|_| ApiError)?; if stored.is_empty() { @@ -281,7 +296,7 @@ async fn start_authentication( .start_passkey_authentication(&passkeys) .map_err(|_| ApiError)?; let state = serde_json::to_value(AuthenticationState { - user_id: input.user_id, + user_id: user.id, webauthn, }) .map_err(|_| ApiError)?; @@ -291,7 +306,7 @@ async fn start_authentication( .passkeys() .insert_ceremony(&InsertCeremony { id: ceremony_id, - user_id: Some(input.user_id), + user_id: Some(user.id), session_id: None, kind: "authentication".into(), challenge_digest: Sha256::digest(serialized).to_vec(), @@ -327,7 +342,7 @@ async fn finish_authentication( } let stored = transaction .passkeys() - .find_active_by_credential_id(result.cred_id().as_ref()) + .find_active_by_credential_id_for_update(result.cred_id().as_ref()) .await .map_err(|_| ApiError)? .filter(|credential| credential.user_id == state.user_id) @@ -335,11 +350,14 @@ async fn finish_authentication( 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)?; - transaction + 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() @@ -356,6 +374,208 @@ async fn finish_authentication( no_content_with_cookie(&cookie) } +#[derive(Serialize, Deserialize)] +struct EnrollmentState { + user_id: UserId, + session_id: SessionId, + webauthn: PasskeyRegistration, +} + +async fn start_enrollment( + State(app): State, + headers: HeaderMap, +) -> Result, ApiError> { + let session = active_session(&app.database, &headers).await?; + require_fresh_session(&session)?; + 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, + 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); + } + let session = active_session(&app.database, &headers).await?; + require_fresh_session(&session)?; + let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; + let ceremony = transaction + .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 { + return Err(ApiError); + } + let passkey = app + .webauthn + .finish_passkey_registration(&input.credential, &state.webauthn) + .map_err(|_| ApiError)?; + 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, 20) + .await + .map_err(|_| ApiError)?; + Ok(Json( + keys.into_iter() + .map(|key| PasskeyView { + id: key.id, + friendly_name: key.friendly_name, + }) + .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); + } + 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?; + require_fresh_session(&session)?; + let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; + let revoked = transaction + .passkeys() + .revoke_if_not_last(id, session.user_id) + .await + .map_err(|_| ApiError)?; + if !revoked { + return Err(ApiError); + } + 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) +} + +fn require_fresh_session(session: &piquel_repository::StoredSession) -> Result<(), ApiError> { + (Utc::now().signed_duration_since(session.authenticated_at) <= Duration::minutes(10)) + .then_some(()) + .ok_or(ApiError) +} + async fn create_session( transaction: &mut piquel_repository::DatabaseTransaction<'_>, user_id: UserId, diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 69244fae4..5ad3e16ec 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -340,6 +340,13 @@ impl PasskeyRepository<'_> { 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], + ) -> 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 FOR UPDATE").bind(credential_id))?.map(|row| stored_passkey(&row)).transpose() + } + pub async fn update_after_authentication( &mut self, credential_id: &[u8], @@ -357,6 +364,17 @@ impl PasskeyRepository<'_> { Ok(execute!(self, sqlx::query("UPDATE passkey_credentials SET friendly_name=$1 WHERE id=$2 AND user_id=$3 AND revoked_at IS NULL").bind(name).bind(id.as_uuid()).bind(user_id.as_uuid()))?.rows_affected()==1) } + /// Revokes a credential only while another active passkey remains. + /// All of the user's credential rows are locked in one statement so two + /// concurrent removals cannot both pass the last-factor check. + pub async fn revoke_if_not_last( + &mut self, + id: TokenId, + user_id: UserId, + ) -> Result { + Ok(execute!(self, sqlx::query("WITH locked AS MATERIALIZED (SELECT id,revoked_at FROM passkey_credentials WHERE user_id=$2 FOR UPDATE), eligible AS (SELECT 1 FROM locked WHERE id=$1 AND revoked_at IS NULL AND (SELECT count(*) FROM locked WHERE revoked_at IS NULL)>1) UPDATE passkey_credentials SET revoked_at=now() FROM eligible WHERE passkey_credentials.id=$1 AND passkey_credentials.user_id=$2 AND passkey_credentials.revoked_at IS NULL").bind(id.as_uuid()).bind(user_id.as_uuid()))?.rows_affected()==1) + } + pub async fn revoke(&mut self, id: TokenId, user_id: UserId) -> Result { Ok(execute!(self, sqlx::query("UPDATE passkey_credentials SET revoked_at=now() WHERE id=$1 AND user_id=$2 AND revoked_at IS NULL").bind(id.as_uuid()).bind(user_id.as_uuid()))?.rows_affected()==1) } @@ -440,6 +458,6 @@ impl SessionRepository<'_> { &mut self, digest: &[u8], ) -> 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 browser_session_secrets b JOIN sessions s ON s.id=b.session_id WHERE b.secret_digest=$1 AND s.revoked_at IS NULL AND s.expires_at>now()").bind(digest))?.map(|row| stored_session(&row)).transpose() + 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() } } From 0ab0e41a122edf8589e1830cfe4075a47e503983 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:07:38 +0200 Subject: [PATCH 10/22] feat(auth): add oidc token lifecycle primitives --- Cargo.toml | 9 +- apps/auth-service/Cargo.toml | 13 +-- apps/auth-service/src/lib.rs | 2 + apps/auth-service/src/oidc.rs | 94 +++++++++++++++++++ .../database/migrations/0004_oidc_tokens.sql | 6 ++ 5 files changed, 106 insertions(+), 18 deletions(-) create mode 100644 apps/auth-service/src/oidc.rs create mode 100644 crates/database/migrations/0004_oidc_tokens.sql diff --git a/Cargo.toml b/Cargo.toml index 48b132d36..f0ac45af7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,19 +30,16 @@ axum = "0.8" base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } http = "1.3" -openssl = { version = "0.10", features = ["vendored"] } +hmac = "0.12" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.10" -rand = "0.8" -sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "migrate", "macros"] } +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "migrate", "macros"] } thiserror = "2.0" -tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time"] } -tower = { version = "0.5", features = ["util"] } +tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net"] } tower-http = { version = "0.6", features = ["trace"] } tracing = "0.1" 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"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index f1c77aa60..8d46763c1 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -8,29 +8,18 @@ rust-version.workspace = true [dependencies] anyhow.workspace = true -async-trait.workspace = true axum.workspace = true base64.workspace = true -chrono.workspace = true -openssl.workspace = true +hmac.workspace = true piquel-auth-protocol = { path = "../../crates/auth-protocol" } piquel-configuration = { path = "../../crates/configuration" } piquel-repository = { path = "../../crates/database" } piquel-telemetry = { path = "../../crates/telemetry" } -rand.workspace = true serde.workspace = true -serde_json.workspace = true -thiserror.workspace = true sha2.workspace = true tokio.workspace = true tracing.workspace = true unicode-normalization.workspace = true -url.workspace = true -webauthn-rs.workspace = true - -[dev-dependencies] -tower.workspace = true -webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] } [lints] workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 6ac0f4872..16cfc487e 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -16,6 +16,8 @@ mod email; #[allow(dead_code)] mod event_log; #[allow(dead_code)] +mod oidc; +#[allow(dead_code)] mod passkey; pub use passkey::PasskeyApplication; #[allow(dead_code)] diff --git a/apps/auth-service/src/oidc.rs b/apps/auth-service/src/oidc.rs new file mode 100644 index 000000000..3a2b97845 --- /dev/null +++ b/apps/auth-service/src/oidc.rs @@ -0,0 +1,94 @@ +//! Strict `OIDC` request and opaque refresh-token primitives. + +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use hmac::{Hmac, Mac}; +use piquel_auth_protocol::{Audience, ClientId, TokenId}; +use sha2::{Digest, Sha256}; +use std::str::FromStr; + +type HmacSha256 = Hmac; + +pub(super) fn validate_exact_redirect(registered: &[String], requested: &str) -> Result<(), ()> { + if registered.iter().any(|uri| uri == requested) { + Ok(()) + } else { + Err(()) + } +} +pub(super) fn validate_pkce_s256(verifier: &str, challenge: &str) -> Result<(), ()> { + if !(43..=128).contains(&verifier.len()) + || !verifier + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')) + { + return Err(()); + } + let digest = Sha256::digest(verifier.as_bytes()); + if URL_SAFE_NO_PAD.encode(digest) == challenge { + Ok(()) + } else { + Err(()) + } +} +pub(super) struct ParsedRefreshToken { + pub token_id: TokenId, + pub secret: Vec, +} +pub(super) fn parse_refresh_token(value: &str) -> Result { + let (prefix, remainder) = value.split_once('_').ok_or(())?; + if prefix != "prt" { + return Err(()); + } + let (version, remainder) = remainder.split_once('_').ok_or(())?; + if version != "v1" { + return Err(()); + } + let (token_id, secret) = remainder.split_once('.').ok_or(())?; + let secret = URL_SAFE_NO_PAD.decode(secret).map_err(|_| ())?; + if secret.len() < 32 { + return Err(()); + } + Ok(ParsedRefreshToken { + token_id: TokenId::from_str(token_id).map_err(|_| ())?, + secret, + }) +} +pub(super) fn refresh_digest(key: &[u8], secret: &[u8]) -> Result<[u8; 32], ()> { + let mut mac = HmacSha256::new_from_slice(key).map_err(|_| ())?; + mac.update(secret); + Ok(mac.finalize().into_bytes().into()) +} +pub(super) fn exact_audience( + client_audiences: &[Audience], + requested: &Audience, +) -> Result<(), ()> { + if client_audiences.contains(requested) { + Ok(()) + } else { + Err(()) + } +} +#[allow(dead_code)] +pub(super) fn client_id(value: &str) -> Result { + ClientId::from_str(value).map_err(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn prohibits_redirect_prefixes_and_bad_pkce() { + assert!( + validate_exact_redirect( + &["https://a.example/cb".into()], + "https://a.example/cb.evil" + ) + .is_err() + ); + assert!(validate_pkce_s256("short", "x").is_err()); + } + #[test] + fn refresh_parser_is_strict() { + assert!(parse_refresh_token("prt_v1_invalid.not-base64").is_err()); + } +} diff --git a/crates/database/migrations/0004_oidc_tokens.sql b/crates/database/migrations/0004_oidc_tokens.sql new file mode 100644 index 000000000..2578e7b96 --- /dev/null +++ b/crates/database/migrations/0004_oidc_tokens.sql @@ -0,0 +1,6 @@ +CREATE TABLE oidc_clients (id TEXT PRIMARY KEY, enabled BOOLEAN NOT NULL DEFAULT TRUE, 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, PRIMARY KEY (client_id, uri)); +CREATE TABLE authorization_codes (id UUID PRIMARY KEY, 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 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, 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, issued_at TIMESTAMPTZ NOT NULL DEFAULT now(), consumed_at TIMESTAMPTZ, UNIQUE (secret_digest)); From 3613145d4b45962816d05e291929f8e5f36617fb Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 15:35:54 +0200 Subject: [PATCH 11/22] fix(auth): implement OIDC and rotating token lifecycle --- Cargo.lock | 121 +++ Cargo.toml | 10 +- apps/auth-service/Cargo.toml | 13 + apps/auth-service/src/lib.rs | 24 +- apps/auth-service/src/main.rs | 35 +- apps/auth-service/src/oidc.rs | 855 ++++++++++++++++-- .../database/migrations/0004_oidc_tokens.sql | 57 +- crates/database/src/models.rs | 83 ++ crates/database/src/repositories.rs | 209 ++++- crates/database/tests/identity.rs | 91 +- 10 files changed, 1421 insertions(+), 77 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 58b7b5fc9..a49dda2a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -128,7 +128,9 @@ dependencies = [ "axum", "base64 0.22.1", "chrono", + "hmac", "openssl", + "p256", "piquel-auth-protocol", "piquel-configuration", "piquel-repository", @@ -205,6 +207,12 @@ 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" @@ -370,6 +378,18 @@ 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" @@ -446,6 +466,20 @@ 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" @@ -455,6 +489,26 @@ 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" @@ -493,6 +547,16 @@ 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" @@ -647,6 +711,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -683,6 +748,17 @@ dependencies = [ "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", +] + [[package]] name = "half" version = "2.7.1" @@ -1264,6 +1340,18 @@ 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" @@ -1419,6 +1507,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -1543,6 +1640,16 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -1638,6 +1745,20 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index f0ac45af7..bcf266ec8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,15 +31,21 @@ base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } http = "1.3" hmac = "0.12" +http-body-util = "0.1" +openssl = { version = "0.10", features = ["vendored"] } +p256 = { version = "0.13", features = ["ecdsa", "pem", "pkcs8"] } +rand = "0.8" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.10" -sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "migrate", "macros"] } +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "migrate", "macros"] } thiserror = "2.0" -tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net"] } +tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time"] } +tower = { version = "0.5", features = ["util"] } tower-http = { version = "0.6", features = ["trace"] } tracing = "0.1" 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"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 8d46763c1..f2a4d3493 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -8,18 +8,31 @@ rust-version.workspace = true [dependencies] anyhow.workspace = true +async-trait.workspace = true axum.workspace = true base64.workspace = true +chrono.workspace = true hmac.workspace = true +openssl.workspace = true +p256.workspace = true piquel-auth-protocol = { path = "../../crates/auth-protocol" } piquel-configuration = { path = "../../crates/configuration" } piquel-repository = { path = "../../crates/database" } piquel-telemetry = { path = "../../crates/telemetry" } serde.workspace = true +serde_json.workspace = true sha2.workspace = true +rand.workspace = true +thiserror.workspace = true tokio.workspace = true tracing.workspace = true unicode-normalization.workspace = true +url.workspace = true +webauthn-rs.workspace = true + +[dev-dependencies] +tower.workspace = true +webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] } [lints] workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 16cfc487e..610ec3493 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -17,6 +17,7 @@ mod email; mod event_log; #[allow(dead_code)] mod oidc; +pub use oidc::{Es256KeyProvider, OidcApplication}; #[allow(dead_code)] mod passkey; pub use passkey::PasskeyApplication; @@ -38,6 +39,10 @@ pub struct AuthConfig { pub key_provider: SecretReference, /// `WebAuthn` relying-party identifier. pub webauthn_rp_id: String, + /// Enables loopback-only development relaxations. + pub development_mode: bool, + /// Stable identifier published with the active signing key. + pub signing_key_id: String, } impl AuthConfig { /// Loads the minimum service configuration from the environment. @@ -75,6 +80,8 @@ impl AuthConfig { database, key_provider: SecretReference::parse(&required("AUTH_KEY_PROVIDER")?)?, webauthn_rp_id: required("AUTH_WEBAUTHN_RP_ID")?, + development_mode: development, + signing_key_id: required("AUTH_SIGNING_KEY_ID")?, }) } } @@ -119,16 +126,19 @@ struct AppState { } /// Builds the public health-only router. Liveness has no dependencies; readiness fails closed. -pub fn router(readiness: Arc, passkeys: Option) -> Router { +pub fn router( + readiness: Arc, + passkeys: Option, + oidc: 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 { + let router = passkeys.map_or(health.clone(), |passkeys| { health.merge(passkey::routes(passkeys)) - } else { - health - } + }); + oidc.map_or(router.clone(), |oidc| router.merge(oidc::routes(oidc))) } async fn ready(State(state): State) -> impl IntoResponse { @@ -153,7 +163,7 @@ mod tests { #[tokio::test] async fn liveness_has_no_dependencies_and_readiness_fails_closed() { - let app = router(Arc::new(FixedReadiness(false)), None); + let app = router(Arc::new(FixedReadiness(false)), None, None); let live = app .clone() .oneshot( @@ -177,7 +187,7 @@ mod tests { #[tokio::test] async fn readiness_succeeds_with_test_substitutes() { - let response = router(Arc::new(FixedReadiness(true)), None) + let response = router(Arc::new(FixedReadiness(true)), None, None) .oneshot( axum::http::Request::get("/health/ready") .body(axum::body::Body::empty()) diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index 2291b52ed..81fac8895 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -1,6 +1,8 @@ #![allow(missing_docs)] -use auth_service::{AuthConfig, PasskeyApplication, ProductionReadiness, router}; +use auth_service::{ + AuthConfig, Es256KeyProvider, OidcApplication, PasskeyApplication, ProductionReadiness, router, +}; use piquel_repository::Database; use std::{net::SocketAddr, sync::Arc}; @@ -10,11 +12,41 @@ async fn main() -> anyhow::Result<()> { 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 keys = if config.development_mode { + Arc::new(Es256KeyProvider::generate_for_development( + config.signing_key_id.clone(), + )) + } else { + let pem = std::str::from_utf8(key_secret.expose_secret()) + .map_err(|_| anyhow::anyhow!("signing key provider returned invalid data"))?; + Arc::new( + 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(), )?; + let oidc = if config.development_mode { + OidcApplication::new_development( + database.clone(), + config.public_base_url.as_url(), + key_secret.expose_secret(), + keys, + ) + } else { + OidcApplication::new( + database.clone(), + config.public_base_url.as_url(), + key_secret.expose_secret(), + keys, + ) + } + .map_err(|()| anyhow::anyhow!("invalid OIDC configuration"))?; let listener = tokio::net::TcpListener::bind(listener_address).await?; tracing::info!(%listener_address, "auth service listening"); axum::serve( @@ -22,6 +54,7 @@ async fn main() -> anyhow::Result<()> { router( Arc::new(ProductionReadiness::new(database, config.key_provider)), Some(passkeys), + Some(oidc), ), ) .with_graceful_shutdown(shutdown_signal()) diff --git a/apps/auth-service/src/oidc.rs b/apps/auth-service/src/oidc.rs index 3a2b97845..1d99db382 100644 --- a/apps/auth-service/src/oidc.rs +++ b/apps/auth-service/src/oidc.rs @@ -1,94 +1,833 @@ -//! Strict `OIDC` request and opaque refresh-token primitives. +//! Authorization Code + PKCE, ES256 tokens, and rotating opaque refresh tokens. +use axum::{ + Form, Json, Router, + extract::{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 hmac::{Hmac, Mac}; -use piquel_auth_protocol::{Audience, ClientId, TokenId}; +use p256::{ + ecdsa::{ + Signature, SigningKey, + signature::{Signer, Verifier}, + }, + pkcs8::DecodePrivateKey, +}; +use piquel_auth_protocol::{SessionId, TokenId, UserId}; +use piquel_repository::{ + Database, InsertAuthorizationCode, InsertRefreshFamily, InsertRefreshToken, + RefreshRotationError, StoredSession, +}; +use rand::{RngCore, rngs::OsRng}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use std::str::FromStr; +use std::{collections::BTreeSet, str::FromStr, sync::Arc}; +use thiserror::Error; +use url::Url; type HmacSha256 = Hmac; +const OPAQUE_SECRET_BYTES: usize = 32; +const ACCESS_TOKEN_SECONDS: i64 = 300; -pub(super) fn validate_exact_redirect(registered: &[String], requested: &str) -> Result<(), ()> { - if registered.iter().any(|uri| uri == requested) { - Ok(()) - } else { - Err(()) +/// Supplies a stable active ES256 key and its public JWK. +pub trait KeyProvider: Send + Sync { + fn sign(&self, token_type: &str, claims: &Value) -> Result; + fn jwks(&self) -> Value; + fn verify_access(&self, token: &str, issuer: &str) -> Result; +} + +/// Local PEM-backed key provider. Production callers resolve the PEM through a secret reference. +pub struct Es256KeyProvider { + kid: String, + signing: SigningKey, +} + +impl Es256KeyProvider { + /// Loads a 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 { + Ok(Self { + kid: kid.into(), + signing: SigningKey::from_pkcs8_pem(pem).map_err(|_| ())?, + }) + } + + /// Generates an ephemeral key for explicit development and tests only. + #[must_use] + pub fn generate_for_development(kid: impl Into) -> Self { + Self { + kid: kid.into(), + signing: SigningKey::random(&mut OsRng), + } } } -pub(super) fn validate_pkce_s256(verifier: &str, challenge: &str) -> Result<(), ()> { - if !(43..=128).contains(&verifier.len()) - || !verifier - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')) + +impl KeyProvider for Es256KeyProvider { + fn sign(&self, token_type: &str, claims: &Value) -> 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()) + )) + } + + fn jwks(&self) -> Value { + let point = self.signing.verifying_key().to_encoded_point(false); + json!({"keys":[{ + "kty":"EC", "crv":"P-256", "use":"sig", "alg":"ES256", "kid":self.kid, + "x":URL_SAFE_NO_PAD.encode(point.x().expect("uncompressed point")), + "y":URL_SAFE_NO_PAD.encode(point.y().expect("uncompressed point")) + }]}) + } + + fn verify_access(&self, token: &str, issuer: &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: 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!("at+jwt")) + { + 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(|_| ())?; + let claims: Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(claims_part).map_err(|_| ())?) + .map_err(|_| ())?; + let now = Utc::now().timestamp(); + if claims.get("iss") != Some(&json!(issuer)) + || claims + .get("exp") + .and_then(Value::as_i64) + .is_none_or(|exp| exp <= now) + || claims + .get("iat") + .and_then(Value::as_i64) + .is_none_or(|iat| iat > now + 30) + { + return Err(()); + } + Ok(claims) + } +} + +/// Runnable OIDC application state. +#[derive(Clone)] +pub struct OidcApplication { + database: Database, + issuer: String, + refresh_key: Arc<[u8; 32]>, + keys: Arc, +} + +impl OidcApplication { + /// Constructs an OIDC endpoint set with an exact HTTPS issuer. + /// + /// # Errors + /// + /// Returns an error for an insecure issuer or insufficient key material. + #[allow(clippy::result_unit_err)] + pub 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. + #[allow(clippy::result_unit_err)] + pub 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 mut mac = HmacSha256::new_from_slice(secret).map_err(|_| ())?; + mac.update(b"piquel-refresh-token-digest-v1"); + let refresh_key = mac.finalize().into_bytes().into(); + 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/token", post(token)) + .route("/oauth/revoke", post(revoke)) + .route("/oidc/userinfo", get(userinfo)) + .route("/oidc/logout", get(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"], "id_token_signing_alg_values_supported":["ES256"], + "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, + state: String, + nonce: Option, + code_challenge: String, + code_challenge_method: String, + audience: String, + 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::server())? + .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.is_empty() + || q.state.len() > 512 + || q.code_challenge_method != "S256" + || !challenge_valid { - return Err(()); + 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")); + } + if !client.allowed_audiences.contains(&q.audience) { + return Err(fail("invalid_target")); + } + if scopes.contains("openid") && q.nonce.as_deref().is_none_or(str::is_empty) { + return Err(fail("invalid_request")); + } + if q.prompt + .as_deref() + .is_some_and(|value| !matches!(value, "none" | "login")) + { + return Err(fail("invalid_request")); + } + let session = browser_session(&app.database, &headers) + .await + .ok_or_else(|| fail("login_required"))?; + if q.prompt.as_deref() == Some("login") + || q.max_age.is_some_and(|age| { + age < 0 + || Utc::now() + .signed_duration_since(session.authenticated_at) + .num_seconds() + > age + }) + { + return Err(fail("login_required")); + } + let (code, id, secret) = new_opaque("pac_v1"); + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + app.database + .oidc() + .insert_code(&InsertAuthorizationCode { + id, + secret_digest: digest.to_vec(), + client_id: q.client_id, + user_id: session.user_id, + session_id: session.id, + redirect_uri: q.redirect_uri, + pkce_challenge: q.code_challenge, + nonce: q.nonce, + scopes: scopes.into_iter().collect(), + audience: q.audience, + expires_at: Utc::now() + Duration::minutes(2), + }) + .await + .map_err(|_| ApiError::server())?; + let mut location = redirect; + location + .query_pairs_mut() + .append_pair("code", &code) + .append_pair("state", &q.state); + Ok(Redirect::to(location.as_str())) +} + +#[derive(Deserialize)] +struct TokenForm { + grant_type: String, + client_id: String, + code: Option, + redirect_uri: Option, + code_verifier: Option, + refresh_token: Option, +} +#[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, + Form(form): Form, +) -> Result, ApiError> { + 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")), } - let digest = Sha256::digest(verifier.as_bytes()); - if URL_SAFE_NO_PAD.encode(digest) == challenge { - Ok(()) +} + +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::server())?; + let code = tx + .oidc() + .consume_code(id, &digest) + .await + .map_err(|_| ApiError::oauth("invalid_grant"))?; + if code.client_id != form.client_id + || 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_by_id(code.user_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let session = tx + .sessions() + .find_by_id(code.session_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let client = tx + .oidc() + .find_client(&form.client_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_client"))?; + let tokens = issue_tokens( + app, + &client.id, + &code.audience, + &code.scopes, + code.nonce.as_deref(), + &user, + &session, + )?; + 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::server())?; + 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::server())?; + let rotated = match tx.tokens().consume_for_rotation(id, &digest).await { + Ok(value) => value, + Err(RefreshRotationError::Replay) => { + tx.commit().await.map_err(|_| ApiError::server())?; + return Err(ApiError::oauth("invalid_grant")); + } + Err(RefreshRotationError::Invalid) => return Err(ApiError::oauth("invalid_grant")), + }; + if rotated.client_id != form.client_id { + return Err(ApiError::oauth("invalid_grant")); + } + let user = tx + .users() + .find_by_id(rotated.user_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let session = tx + .sessions() + .find_by_id(rotated.session_id) + .await + .map_err(|_| ApiError::server())? + .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: Utc::now() + Duration::days(30), + }) + .await + .map_err(|_| ApiError::server())?; + let mut tokens = issue_tokens( + app, + &rotated.client_id, + &rotated.audience, + &rotated.scopes, + None, + &user, + &session, + )?; + tokens.refresh_token = Some(raw); + tx.commit().await.map_err(|_| ApiError::server())?; + 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 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: Utc::now() + Duration::days(30), + }, + ) + .await + .map_err(|_| ApiError::server())?; + Ok(raw) +} + +fn issue_tokens( + app: &OidcApplication, + client: &str, + audience: &str, + scopes: &[String], + nonce: Option<&str>, + user: &piquel_repository::StoredUser, + session: &StoredSession, +) -> Result { + let now = Utc::now().timestamp(); + let amr = &session.authentication_methods; + let access=app.keys.sign("at+jwt",&json!({"iss":app.issuer,"sub":user.id,"aud":audience,"client_id":client,"sid":session.id,"jti":TokenId::new(),"profile_version":user.profile_version,"preferred_username":user.username,"name":user.display_name,"amr":amr,"auth_time":session.authenticated_at.timestamp(),"scope":scopes.join(" "),"iat":now,"exp":now+ACCESS_TOKEN_SECONDS})).map_err(|()|ApiError::server())?; + let id_token = if scopes.iter().any(|s| s == "openid") { + Some(app.keys.sign("JWT",&json!({"iss":app.issuer,"sub":user.id,"aud":client,"sid":session.id,"nonce":nonce,"profile_version":user.profile_version,"preferred_username":user.username,"name":user.display_name,"auth_time":session.authenticated_at.timestamp(),"amr":amr,"iat":now,"exp":now+ACCESS_TOKEN_SECONDS})).map_err(|()|ApiError::server())?) } else { - Err(()) + None + }; + Ok(TokenResponse { + access_token: access, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_SECONDS, + scope: scopes.join(" "), + id_token, + refresh_token: None, + }) +} + +#[derive(Deserialize)] +struct RevokeForm { + token: String, +} +async fn revoke( + State(app): State, + Form(form): Form, +) -> Result { + 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::server())?; + tx.tokens() + .revoke_family_for_token(id, &digest) + .await + .map_err(|_| ApiError::server())?; + tx.commit().await.map_err(|_| ApiError::server())?; } + Ok(StatusCode::OK) } -pub(super) struct ParsedRefreshToken { - pub token_id: TokenId, - pub secret: Vec, + +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_access(token, &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); + } + Ok(Json(response)) } -pub(super) fn parse_refresh_token(value: &str) -> Result { - let (prefix, remainder) = value.split_once('_').ok_or(())?; - if prefix != "prt" { - return Err(()); + +#[derive(Deserialize)] +struct LogoutQuery { + client_id: Option, + post_logout_redirect_uri: Option, + state: Option, +} +async fn logout( + State(app): State, + headers: HeaderMap, + Query(q): Query, +) -> Result { + if let Some(session) = browser_session(&app.database, &headers).await { + app.database + .sessions() + .revoke(session.id) + .await + .map_err(|_| ApiError::server())?; } - let (version, remainder) = remainder.split_once('_').ok_or(())?; - if version != "v1" { - return Err(()); + if let (Some(client_id), Some(uri)) = (q.client_id, q.post_logout_redirect_uri) { + let client = app + .database + .oidc() + .find_client(&client_id) + .await + .map_err(|_| ApiError::server())? + .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); + } + return Ok(Redirect::to(url.as_str()).into_response()); } - let (token_id, secret) = remainder.split_once('.').ok_or(())?; - let secret = URL_SAFE_NO_PAD.decode(secret).map_err(|_| ())?; - if secret.len() < 32 { - return Err(()); + Ok(StatusCode::NO_CONTENT.into_response()) +} + +async fn browser_session(database: &Database, headers: &HeaderMap) -> Option { + let raw = headers + .get(header::COOKIE)? + .to_str() + .ok()? + .split(';') + .map(str::trim) + .find_map(|part| part.strip_prefix("__Host-piquel_session="))?; + let secret = URL_SAFE_NO_PAD.decode(raw).ok()?; + if secret.len() != OPAQUE_SECRET_BYTES { + return None; } - Ok(ParsedRefreshToken { - token_id: TokenId::from_str(token_id).map_err(|_| ())?, + let digest = Sha256::digest(secret); + database + .sessions() + .find_active_by_browser_secret(&digest) + .await + .ok() + .flatten() +} + +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)) } -pub(super) fn refresh_digest(key: &[u8], secret: &[u8]) -> Result<[u8; 32], ()> { - let mut mac = HmacSha256::new_from_slice(key).map_err(|_| ())?; +fn keyed_digest(key: &[u8], secret: &[u8]) -> Result<[u8; 32], ApiError> { + let mut mac = HmacSha256::new_from_slice(key).map_err(|_| ApiError::server())?; mac.update(secret); Ok(mac.finalize().into_bytes().into()) } -pub(super) fn exact_audience( - client_audiences: &[Audience], - requested: &Audience, -) -> Result<(), ()> { - if client_audiences.contains(requested) { - Ok(()) - } else { - Err(()) +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(()) } -#[allow(dead_code)] -pub(super) fn client_id(value: &str) -> Result { - ClientId::from_str(value).map_err(|_| ()) +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 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(); + } + (self.0, Json(self.1)).into_response() + } } #[cfg(test)] mod tests { use super::*; #[test] - fn prohibits_redirect_prefixes_and_bad_pkce() { - assert!( - validate_exact_redirect( - &["https://a.example/cb".into()], - "https://a.example/cb.evil" - ) - .is_err() - ); + 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()); } #[test] - fn refresh_parser_is_strict() { - assert!(parse_refresh_token("prt_v1_invalid.not-base64").is_err()); + fn jwt_types_are_cryptographically_distinct() { + let keys = Es256KeyProvider::generate_for_development("test"); + let now = Utc::now().timestamp(); + let id = keys + .sign( + "JWT", + &json!({"iss":"https://issuer","exp":now+60,"iat":now}), + ) + .expect("sign"); + assert!(keys.verify_access(&id, "https://issuer").is_err()); + let access = keys + .sign( + "at+jwt", + &json!({"iss":"https://issuer","exp":now+60,"iat":now}), + ) + .expect("sign"); + assert!(keys.verify_access(&access, "https://issuer").is_ok()); } } diff --git a/crates/database/migrations/0004_oidc_tokens.sql b/crates/database/migrations/0004_oidc_tokens.sql index 2578e7b96..9a221f965 100644 --- a/crates/database/migrations/0004_oidc_tokens.sql +++ b/crates/database/migrations/0004_oidc_tokens.sql @@ -1,6 +1,53 @@ -CREATE TABLE oidc_clients (id TEXT PRIMARY KEY, enabled BOOLEAN NOT NULL DEFAULT TRUE, 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, PRIMARY KEY (client_id, uri)); -CREATE TABLE authorization_codes (id UUID PRIMARY KEY, 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 TABLE oidc_clients ( + id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + token_endpoint_auth_method TEXT NOT NULL DEFAULT 'none' CHECK (token_endpoint_auth_method IN ('none')), + 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 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, 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, issued_at TIMESTAMPTZ NOT NULL DEFAULT now(), consumed_at TIMESTAMPTZ, UNIQUE (secret_digest)); + +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); diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index 785cebe12..931141278 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -111,3 +111,86 @@ pub struct ConsumedCeremony { pub session_id: Option, pub state: Value, } + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredOidcClient { + pub id: String, + pub enabled: bool, + pub redirect_uris: Vec, + pub post_logout_uris: Vec, + pub allowed_scopes: Vec, + pub allowed_audiences: Vec, + pub allow_refresh: bool, +} + +#[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, +} + +#[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(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RefreshRotationError { + Invalid, + Replay, +} diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 5ad3e16ec..875349b93 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,8 +1,10 @@ //! Domain repository handles backed by a private pool or transaction connection. use crate::{ - AppendAuditEvent, AppendInternalEvent, ConsumedCeremony, DatabaseError, InsertCeremony, - InsertPasskey, InsertSession, InsertUser, InsertVerifiedEmail, StoredEmail, StoredPasskey, + AppendAuditEvent, AppendInternalEvent, BootstrapOidcClient, ConsumedAuthorizationCode, + ConsumedCeremony, DatabaseError, InsertAuthorizationCode, InsertCeremony, InsertPasskey, + InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, + RefreshRotationError, RotatedRefreshToken, StoredEmail, StoredOidcClient, StoredPasskey, StoredSession, StoredUser, UpdateUserProfile, }; use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; @@ -264,6 +266,209 @@ impl SessionRepository<'_> { .rows_affected()) } } + +impl OidcRepository<'_> { + /// Idempotently provisions a statically reviewed public client and exact URI allowlists. + pub async fn bootstrap_client( + &mut self, + input: &BootstrapOidcClient, + ) -> Result<(), DatabaseError> { + 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("INSERT INTO oidc_clients(id,display_name,allowed_scopes,allowed_audiences,allow_refresh) VALUES($1,$2,$3,$4,$5) 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") + .bind(&input.id).bind(&input.display_name).bind(scopes).bind(audiences).bind(input.allow_refresh))?; + execute!( + self, + sqlx::query("DELETE FROM oidc_redirect_uris WHERE client_id=$1").bind(&input.id) + )?; + for uri in &input.redirect_uris { + execute!(self, sqlx::query("INSERT INTO oidc_redirect_uris(client_id,uri,kind) VALUES($1,$2,'authorization')").bind(&input.id).bind(uri))?; + } + for uri in &input.post_logout_uris { + execute!( + self, + sqlx::query( + "INSERT INTO oidc_redirect_uris(client_id,uri,kind) VALUES($1,$2,'post_logout')" + ) + .bind(&input.id) + .bind(uri) + )?; + } + Ok(()) + } + + pub async fn find_client( + &mut self, + id: &str, + ) -> Result, DatabaseError> { + let row = fetch_optional!(self, sqlx::query("SELECT c.id,c.enabled,c.allowed_scopes,c.allowed_audiences,c.allow_refresh,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)?, + enabled: row + .try_get("enabled") + .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 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 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)?, + }) + } +} + +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], + ) -> 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 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 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").bind(id.as_uuid()).bind(digest)).map_err(|_| RefreshRotationError::Invalid)?.ok_or(RefreshRotationError::Invalid)?; + let family_uuid: uuid::Uuid = row + .try_get("family_id") + .map_err(|_| RefreshRotationError::Invalid)?; + if row + .try_get::>, _>("consumed_at") + .map_err(|_| RefreshRotationError::Invalid)? + .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::Invalid)?; + return Err(RefreshRotationError::Replay); + } + 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::Invalid)? + .rows_affected() + != 1 + { + return Err(RefreshRotationError::Invalid); + } + Ok(RotatedRefreshToken { + family_id: TokenId::from_uuid(family_uuid) + .map_err(|_| RefreshRotationError::Invalid)?, + user_id: UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?, + client_id: row + .try_get("client_id") + .map_err(|_| RefreshRotationError::Invalid)?, + session_id: SessionId::from_uuid( + row.try_get("session_id") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?, + audience: row + .try_get("audience") + .map_err(|_| RefreshRotationError::Invalid)?, + scopes: serde_json::from_value( + row.try_get("scopes") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?, + }) + } + + 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(()) + } +} fn stored_session(row: &sqlx::postgres::PgRow) -> Result { let methods: serde_json::Value = row .try_get("authentication_methods") diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index feddf68c9..f3d98b566 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -3,8 +3,9 @@ use chrono::{Duration as ChronoDuration, Utc}; use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ - AppendInternalEvent, Database, DatabaseConfig, DatabaseError, InsertCeremony, InsertPasskey, - InsertSession, InsertUser, InsertVerifiedEmail, UpdateUserProfile, + AppendInternalEvent, BootstrapOidcClient, Database, DatabaseConfig, DatabaseError, + InsertCeremony, InsertPasskey, InsertRefreshFamily, InsertRefreshToken, InsertSession, + InsertUser, InsertVerifiedEmail, RefreshRotationError, UpdateUserProfile, }; use std::{env, time::Duration}; @@ -139,6 +140,92 @@ async fn identity_transactions_and_concurrency_hold() { ); assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + let refresh_session = SessionId::new(); + database + .sessions() + .insert(&InsertSession { + id: refresh_session, + 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("refresh session"); + let mut setup = database.begin().await.expect("OIDC setup"); + setup + .oidc() + .bootstrap_client(&BootstrapOidcClient { + id: "test-client".into(), + display_name: "Test".into(), + redirect_uris: vec!["https://client.example/callback".into()], + post_logout_uris: vec!["https://client.example/logout".into()], + allowed_scopes: vec!["openid".into(), "offline_access".into()], + allowed_audiences: vec!["test-api".into()], + allow_refresh: true, + }) + .await + .expect("client"); + let family_id = TokenId::new(); + let refresh_id = TokenId::new(); + let digest = vec![9_u8; 32]; + setup + .tokens() + .insert_family( + &InsertRefreshFamily { + id: family_id, + user_id: first, + client_id: "test-client".into(), + session_id: refresh_session, + audience: "test-api".into(), + scopes: vec!["openid".into()], + }, + &InsertRefreshToken { + id: refresh_id, + family_id, + secret_digest: digest.clone(), + expires_at: Utc::now() + ChronoDuration::days(1), + }, + ) + .await + .expect("refresh family"); + setup.commit().await.expect("OIDC setup commit"); + let rotate = |database: Database, replacement: TokenId, digest: Vec| async move { + let mut tx = database.begin().await.expect("rotation transaction"); + match tx.tokens().consume_for_rotation(refresh_id, &digest).await { + Ok(token) => { + tx.tokens() + .insert_token(&InsertRefreshToken { + id: replacement, + family_id: token.family_id, + secret_digest: vec![replacement.as_uuid().as_bytes()[0]; 32], + expires_at: Utc::now() + ChronoDuration::days(1), + }) + .await + .expect("replacement"); + tx.commit().await.expect("rotation commit"); + Ok(replacement) + } + Err(RefreshRotationError::Replay) => { + tx.commit().await.expect("persist replay revocation"); + Err(RefreshRotationError::Replay) + } + Err(error) => Err(error), + } + }; + let replacement_one = TokenId::new(); + let replacement_two = TokenId::new(); + let (left, right) = tokio::join!( + rotate(database.clone(), replacement_one, digest.clone()), + rotate(database.clone(), replacement_two, digest), + ); + assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + assert!( + matches!(left, Err(RefreshRotationError::Replay)) + || matches!(right, Err(RefreshRotationError::Replay)) + ); + let credential_id = vec![7_u8; 32]; database .passkeys() From b1bf5b0434117441b3d2488156aa7801d063ec02 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:51:38 +0200 Subject: [PATCH 12/22] fix(auth): complete authorization and refresh policy flows --- apps/auth-service/src/account.rs | 1 + apps/auth-service/src/oidc.rs | 234 +++++++++++++++--- .../database/migrations/0004_oidc_tokens.sql | 18 ++ crates/database/src/models.rs | 36 ++- crates/database/src/repositories.rs | 213 +++++++++++++--- crates/database/tests/identity.rs | 8 +- 6 files changed, 438 insertions(+), 72 deletions(-) diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs index d3c7a0865..b0e2273ef 100644 --- a/apps/auth-service/src/account.rs +++ b/apps/auth-service/src/account.rs @@ -108,6 +108,7 @@ pub(super) async fn disable(database: &Database, user_id: UserId) -> Result Router { .route("/.well-known/openid-configuration", get(discovery)) .route("/.well-known/jwks.json", get(jwks)) .route("/oauth/authorize", get(authorize)) + .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)) + .route("/oidc/logout", post(logout)) .with_state(application) } @@ -315,45 +321,174 @@ async fn authorize( { return Err(fail("invalid_request")); } - let session = browser_session(&app.database, &headers) - .await - .ok_or_else(|| fail("login_required"))?; - if q.prompt.as_deref() == Some("login") + let session = browser_session(&app.database, &headers).await; + let requires_login = q.prompt.as_deref() == Some("login") + || session.is_none() || q.max_age.is_some_and(|age| { age < 0 - || Utc::now() - .signed_duration_since(session.authenticated_at) - .num_seconds() - > age - }) - { + || session.as_ref().is_none_or(|session| { + Utc::now() + .signed_duration_since(session.authenticated_at) + .num_seconds() + > age + }) + }); + if q.prompt.as_deref() == Some("none") && requires_login { return Err(fail("login_required")); } - let (code, id, secret) = new_opaque("pac_v1"); + let (transaction, id, secret) = new_opaque("par_v1"); let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; app.database .oidc() - .insert_code(&InsertAuthorizationCode { + .insert_authorization_request(&InsertAuthorizationRequest { id, secret_digest: digest.to_vec(), client_id: q.client_id, - user_id: session.user_id, - session_id: session.id, redirect_uri: q.redirect_uri, + client_state: q.state, pkce_challenge: q.code_challenge, nonce: q.nonce, scopes: scopes.into_iter().collect(), audience: q.audience, - expires_at: Utc::now() + Duration::minutes(2), + force_login: q.prompt.as_deref() == Some("login"), + max_age: q.max_age, + expires_at: Utc::now() + Duration::minutes(10), }) .await .map_err(|_| ApiError::server())?; - let mut location = redirect; - location - .query_pairs_mut() - .append_pair("code", &code) - .append_pair("state", &q.state); - Ok(Redirect::to(location.as_str())) + let page = if requires_login { "login" } else { "authorize" }; + Ok(Redirect::to(&format!( + "{}/{page}?transaction={transaction}", + app.issuer + ))) +} + +#[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 { + require_same_origin(&app, &headers)?; + let session = browser_session(&app.database, &headers) + .await + .ok_or_else(ApiError::unauthorized)?; + 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::server())?; + let request = transaction + .oidc() + .consume_authorization_request(id, &digest) + .await + .map_err(|_| ApiError::request())?; + require_authorization_session(&request, &session)?; + let mut redirect = Url::parse(&request.redirect_uri).map_err(|_| ApiError::server())?; + match input.decision.as_str() { + "deny" => { + redirect + .query_pairs_mut() + .append_pair("error", "access_denied") + .append_pair("state", &request.client_state); + } + "approve" => { + let user = transaction + .users() + .find_active_by_id_for_update(session.user_id) + .await + .map_err(|_| ApiError::server())? + .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::server())?; + redirect + .query_pairs_mut() + .append_pair("code", &code) + .append_pair("state", &request.client_state); + } + _ => return Err(ApiError::request()), + } + transaction.commit().await.map_err(|_| ApiError::server())?; + 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::server())? + .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| { + 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)] @@ -414,7 +549,7 @@ async fn exchange_code(app: &OidcApplication, form: TokenForm) -> Result Result value, - Err(RefreshRotationError::Replay) => { + 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::server())?; + tx.commit().await.map_err(|_| ApiError::server())?; + 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::server())?; tx.commit().await.map_err(|_| ApiError::server())?; return Err(ApiError::oauth("invalid_grant")); } @@ -647,8 +810,9 @@ struct LogoutQuery { async fn logout( State(app): State, headers: HeaderMap, - Query(q): Query, + Form(q): Form, ) -> Result { + require_same_origin(&app, &headers)?; if let Some(session) = browser_session(&app.database, &headers).await { app.database .sessions() @@ -676,6 +840,20 @@ async fn logout( Ok(StatusCode::NO_CONTENT.into_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"); + (origin_matches && csrf_header) + .then_some(()) + .ok_or_else(ApiError::request) +} + async fn browser_session(database: &Database, headers: &HeaderMap) -> Option { let raw = headers .get(header::COOKIE)? diff --git a/crates/database/migrations/0004_oidc_tokens.sql b/crates/database/migrations/0004_oidc_tokens.sql index 9a221f965..1f118b16c 100644 --- a/crates/database/migrations/0004_oidc_tokens.sql +++ b/crates/database/migrations/0004_oidc_tokens.sql @@ -32,6 +32,24 @@ CREATE TABLE authorization_codes ( ); 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, + 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), diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index 931141278..502329514 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -115,6 +115,7 @@ pub struct ConsumedCeremony { #[derive(Clone, Debug, PartialEq, Eq)] pub struct StoredOidcClient { pub id: String, + pub display_name: String, pub enabled: bool, pub redirect_uris: Vec, pub post_logout_uris: Vec, @@ -123,6 +124,38 @@ pub struct StoredOidcClient { pub allow_refresh: bool, } +#[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 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 max_age: Option, + pub created_at: DateTime, +} + #[derive(Clone, Debug)] pub struct BootstrapOidcClient { pub id: String, @@ -192,5 +225,6 @@ pub struct RotatedRefreshToken { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RefreshRotationError { Invalid, - Replay, + Replay { user_id: UserId }, + Policy { user_id: UserId }, } diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 875349b93..ed505ff90 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -2,10 +2,11 @@ use crate::{ AppendAuditEvent, AppendInternalEvent, BootstrapOidcClient, ConsumedAuthorizationCode, - ConsumedCeremony, DatabaseError, InsertAuthorizationCode, InsertCeremony, InsertPasskey, - InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, - RefreshRotationError, RotatedRefreshToken, StoredEmail, StoredOidcClient, StoredPasskey, - StoredSession, StoredUser, UpdateUserProfile, + ConsumedCeremony, DatabaseError, InsertAuthorizationCode, InsertAuthorizationRequest, + InsertCeremony, InsertPasskey, InsertRefreshFamily, InsertRefreshToken, InsertSession, + InsertUser, InsertVerifiedEmail, RefreshRotationError, RotatedRefreshToken, + StoredAuthorizationRequest, StoredEmail, StoredOidcClient, StoredPasskey, StoredSession, + StoredUser, UpdateUserProfile, }; use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; use sqlx::{PgConnection, PgPool, Row}; @@ -124,6 +125,12 @@ 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, @@ -273,29 +280,13 @@ impl OidcRepository<'_> { &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("INSERT INTO oidc_clients(id,display_name,allowed_scopes,allowed_audiences,allow_refresh) VALUES($1,$2,$3,$4,$5) 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") - .bind(&input.id).bind(&input.display_name).bind(scopes).bind(audiences).bind(input.allow_refresh))?; - execute!( - self, - sqlx::query("DELETE FROM oidc_redirect_uris WHERE client_id=$1").bind(&input.id) - )?; - for uri in &input.redirect_uris { - execute!(self, sqlx::query("INSERT INTO oidc_redirect_uris(client_id,uri,kind) VALUES($1,$2,'authorization')").bind(&input.id).bind(uri))?; - } - for uri in &input.post_logout_uris { - execute!( - self, - sqlx::query( - "INSERT INTO oidc_redirect_uris(client_id,uri,kind) VALUES($1,$2,'post_logout')" - ) - .bind(&input.id) - .bind(uri) - )?; - } + execute!(self, sqlx::query("WITH upsert AS (INSERT INTO oidc_clients(id,display_name,allowed_scopes,allowed_audiences,allow_refresh) VALUES($1,$2,$3,$4,$5) 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 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))?; Ok(()) } @@ -303,7 +294,7 @@ impl OidcRepository<'_> { &mut self, id: &str, ) -> Result, DatabaseError> { - let row = fetch_optional!(self, sqlx::query("SELECT c.id,c.enabled,c.allowed_scopes,c.allowed_audiences,c.allow_refresh,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))?; + let row = fetch_optional!(self, sqlx::query("SELECT c.id,c.display_name,c.enabled,c.allowed_scopes,c.allowed_audiences,c.allow_refresh,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( @@ -316,6 +307,9 @@ impl OidcRepository<'_> { 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)?, @@ -343,6 +337,36 @@ impl OidcRepository<'_> { 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) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)") + .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))?; + 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.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 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.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, @@ -384,6 +408,89 @@ impl OidcRepository<'_> { } } +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.host_str().is_some() + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() + }) + }; + let valid = 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_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, @@ -408,17 +515,51 @@ impl TokenRepository<'_> { id: TokenId, digest: &[u8], ) -> 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 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 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").bind(id.as_uuid()).bind(digest)).map_err(|_| RefreshRotationError::Invalid)?.ok_or(RefreshRotationError::Invalid)?; + 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 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)).map_err(|_| RefreshRotationError::Invalid)?.ok_or(RefreshRotationError::Invalid)?; let family_uuid: uuid::Uuid = row .try_get("family_id") .map_err(|_| RefreshRotationError::Invalid)?; + let user_id = UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; if row .try_get::>, _>("consumed_at") .map_err(|_| RefreshRotationError::Invalid)? .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::Invalid)?; - return Err(RefreshRotationError::Replay); + return Err(RefreshRotationError::Replay { user_id }); + } + let family_scopes: Vec = serde_json::from_value( + row.try_get("scopes") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; + let allowed_scopes: Vec = serde_json::from_value( + row.try_get("allowed_scopes") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; + let allowed_audiences: Vec = serde_json::from_value( + row.try_get("allowed_audiences") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; + let audience: String = row + .try_get("audience") + .map_err(|_| RefreshRotationError::Invalid)?; + let policy_valid = row + .try_get::("allow_refresh") + .map_err(|_| RefreshRotationError::Invalid)? + && 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::Invalid)?; + return Err(RefreshRotationError::Policy { user_id }); } if execute!( self, @@ -436,11 +577,7 @@ impl TokenRepository<'_> { Ok(RotatedRefreshToken { family_id: TokenId::from_uuid(family_uuid) .map_err(|_| RefreshRotationError::Invalid)?, - user_id: UserId::from_uuid( - row.try_get("user_id") - .map_err(|_| RefreshRotationError::Invalid)?, - ) - .map_err(|_| RefreshRotationError::Invalid)?, + user_id, client_id: row .try_get("client_id") .map_err(|_| RefreshRotationError::Invalid)?, @@ -449,14 +586,8 @@ impl TokenRepository<'_> { .map_err(|_| RefreshRotationError::Invalid)?, ) .map_err(|_| RefreshRotationError::Invalid)?, - audience: row - .try_get("audience") - .map_err(|_| RefreshRotationError::Invalid)?, - scopes: serde_json::from_value( - row.try_get("scopes") - .map_err(|_| RefreshRotationError::Invalid)?, - ) - .map_err(|_| RefreshRotationError::Invalid)?, + audience, + scopes: family_scopes, }) } @@ -468,6 +599,10 @@ impl TokenRepository<'_> { 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()) + } } fn stored_session(row: &sqlx::postgres::PgRow) -> Result { let methods: serde_json::Value = row diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index f3d98b566..4ed55c91f 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -207,9 +207,9 @@ async fn identity_transactions_and_concurrency_hold() { tx.commit().await.expect("rotation commit"); Ok(replacement) } - Err(RefreshRotationError::Replay) => { + Err(error @ RefreshRotationError::Replay { .. }) => { tx.commit().await.expect("persist replay revocation"); - Err(RefreshRotationError::Replay) + Err(error) } Err(error) => Err(error), } @@ -222,8 +222,8 @@ async fn identity_transactions_and_concurrency_hold() { ); assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); assert!( - matches!(left, Err(RefreshRotationError::Replay)) - || matches!(right, Err(RefreshRotationError::Replay)) + matches!(left, Err(RefreshRotationError::Replay { .. })) + || matches!(right, Err(RefreshRotationError::Replay { .. })) ); let credential_id = vec![7_u8; 32]; From 96ef4728c9c7d1ff77286037a8d3fe10d184b466 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 21:58:56 +0200 Subject: [PATCH 13/22] fix justfile merge --- justfile | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/justfile b/justfile index 47d3d6f24..4c2aabf66 100644 --- a/justfile +++ b/justfile @@ -1,22 +1,4 @@ format: -<<<<<<< HEAD - cargo fmt --all - -check: - cargo check --workspace --all-targets - -test: - cargo test --workspace - -test-database: - cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 - -migrate: - cargo run -p piquel-repository --bin migrate - -prepare-sqlx: - cargo sqlx prepare --workspace -======= @cargo fmt --all lint: @@ -28,6 +10,9 @@ check: test: @cargo nextest run --workspace +test-database: + @cargo nextest run -p piquel-repository --test identity -- --ignored --test-threads=1 + doc-test: @cargo test --doc --workspace @@ -36,4 +21,3 @@ migrate: prepare-sqlx: @cargo sqlx prepare --workspace ->>>>>>> main From 5b12045e69eb384d1486686f49068f3e39b9e812 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 22:08:41 +0200 Subject: [PATCH 14/22] fix merge --- Cargo.lock | 12 ------------ apps/auth-service/Cargo.toml | 18 +++++------------- apps/auth-service/src/lib.rs | 3 --- crates/auth-protocol/src/lib.rs | 3 --- crates/database/Cargo.toml | 6 +----- crates/database/README.md | 3 --- crates/database/src/connection.rs | 8 -------- crates/database/src/error.rs | 14 -------------- crates/database/src/lib.rs | 6 ------ crates/database/src/repositories.rs | 13 +++---------- crates/database/src/transaction.rs | 7 ------- 11 files changed, 9 insertions(+), 84 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2e517dc44..7d09626ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -65,27 +65,18 @@ dependencies = [ "anyhow", "async-trait", "axum", -<<<<<<< HEAD "chrono", "piquel-auth-protocol", -======= ->>>>>>> main "piquel-configuration", "piquel-repository", "piquel-telemetry", "serde", -<<<<<<< HEAD "serde_json", "thiserror", "tokio", "tower", "tracing", "unicode-normalization", -======= - "tokio", - "tower", - "tracing", ->>>>>>> main ] [[package]] @@ -1060,10 +1051,7 @@ dependencies = [ "async-trait", "chrono", "piquel-auth-protocol", -<<<<<<< HEAD "serde_json", -======= ->>>>>>> main "sqlx", "thiserror", "tokio", diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 34e08ba26..17a8d6fd3 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -7,29 +7,21 @@ repository.workspace = true rust-version.workspace = true [dependencies] +piquel-configuration.workspace = true +piquel-repository.workspace = true +piquel-telemetry.workspace = true +piquel-auth-protocol.workspace = true + anyhow.workspace = true async-trait.workspace = true axum.workspace = true -<<<<<<< HEAD chrono.workspace = true -piquel-auth-protocol = { path = "../../crates/auth-protocol" } -piquel-configuration = { path = "../../crates/configuration" } -piquel-repository = { path = "../../crates/database" } -piquel-telemetry = { path = "../../crates/telemetry" } serde.workspace = true serde_json.workspace = true thiserror.workspace = true tokio.workspace = true tracing.workspace = true unicode-normalization.workspace = true -======= -piquel-configuration.workspace = true -piquel-repository.workspace = true -piquel-telemetry.workspace = true -serde.workspace = true -tokio.workspace = true -tracing.workspace = true ->>>>>>> main [dev-dependencies] tower.workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 72566bf74..a637575e3 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -7,7 +7,6 @@ use piquel_configuration::{ConfigurationError, PublicUrl, SecretReference, socke use piquel_repository::{Database, DatabaseConfig}; use std::{env, net::SocketAddr, sync::Arc, time::Duration}; -<<<<<<< HEAD #[allow(dead_code)] mod account; #[allow(dead_code)] @@ -19,8 +18,6 @@ mod event_log; #[allow(dead_code)] mod session; -======= ->>>>>>> main /// Typed auth-service configuration. #[derive(Clone, Debug)] pub struct AuthConfig { diff --git a/crates/auth-protocol/src/lib.rs b/crates/auth-protocol/src/lib.rs index 0ecf43cab..a387322f9 100644 --- a/crates/auth-protocol/src/lib.rs +++ b/crates/auth-protocol/src/lib.rs @@ -42,7 +42,6 @@ macro_rules! uuid_id { pub fn as_uuid(self) -> Uuid { self.0 } -<<<<<<< HEAD /// Validates and wraps an existing UUID. /// @@ -55,8 +54,6 @@ macro_rules! uuid_id { } Ok(Self(value)) } -======= ->>>>>>> main } impl fmt::Display for $name { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/database/Cargo.toml b/crates/database/Cargo.toml index ff46ae566..6f2f5b151 100644 --- a/crates/database/Cargo.toml +++ b/crates/database/Cargo.toml @@ -10,12 +10,8 @@ rust-version.workspace = true async-trait.workspace = true anyhow.workspace = true chrono.workspace = true -<<<<<<< HEAD -piquel-auth-protocol = { path = "../auth-protocol" } -serde_json.workspace = true -======= piquel-auth-protocol.workspace = true ->>>>>>> main +serde_json.workspace = true sqlx.workspace = true thiserror.workspace = true tokio.workspace = true diff --git a/crates/database/README.md b/crates/database/README.md index f51a51442..17bb72a85 100644 --- a/crates/database/README.md +++ b/crates/database/README.md @@ -9,11 +9,8 @@ Set `DATABASE_URL` in the process environment and run migrations explicitly with 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. -<<<<<<< HEAD The ignored PostgreSQL suite is explicit: set `TEST_DATABASE_URL` to an isolated database and run `just test-database`. The checked-in test Dockerfile can run the same suite on a container network when the host cannot reach the database container. -======= ->>>>>>> main diff --git a/crates/database/src/connection.rs b/crates/database/src/connection.rs index 56c47b7f5..482fbd00e 100644 --- a/crates/database/src/connection.rs +++ b/crates/database/src/connection.rs @@ -110,11 +110,7 @@ impl Database { .await .map_err(|_| DatabaseError::Timeout)? .map(|_| ()) -<<<<<<< HEAD - .map_err(crate::error::map_error) -======= .map_err(Into::into) ->>>>>>> main } /// Opens an explicit short-lived transaction. pub async fn begin(&self) -> Result, DatabaseError> { @@ -122,11 +118,7 @@ impl Database { .begin() .await .map(DatabaseTransaction::new) -<<<<<<< HEAD - .map_err(crate::error::map_error) -======= .map_err(Into::into) ->>>>>>> main } /// Runs immutable migrations only when explicitly invoked by the migration binary. pub async fn run_migrations(&self) -> Result<(), DatabaseError> { diff --git a/crates/database/src/error.rs b/crates/database/src/error.rs index 2af1862fa..c8eb48e45 100644 --- a/crates/database/src/error.rs +++ b/crates/database/src/error.rs @@ -28,19 +28,6 @@ pub enum DatabaseConnectionError { Unavailable, } -<<<<<<< HEAD -pub(crate) fn map_error(error: sqlx::Error) -> DatabaseError { - match error { - sqlx::Error::RowNotFound => DatabaseError::NotFound, - sqlx::Error::PoolTimedOut => DatabaseError::Timeout, - sqlx::Error::PoolClosed | sqlx::Error::Io(_) | sqlx::Error::Tls(_) => { - DatabaseError::Unavailable - } - sqlx::Error::Database(database_error) if database_error.is_unique_violation() => { - DatabaseError::Conflict - } - _ => DatabaseError::Internal, -======= impl From for DatabaseError { fn from(value: sqlx::Error) -> Self { match value { @@ -52,6 +39,5 @@ impl From for DatabaseError { } _ => Self::Internal, } ->>>>>>> main } } diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs index 85d90fcb4..78351761e 100644 --- a/crates/database/src/lib.rs +++ b/crates/database/src/lib.rs @@ -12,19 +12,13 @@ mod connection; mod error; -<<<<<<< HEAD mod models; -======= ->>>>>>> main mod repositories; mod transaction; pub use connection::{Database, DatabaseConfig}; pub use error::{DatabaseConnectionError, DatabaseError}; -<<<<<<< HEAD pub use models::*; -======= ->>>>>>> main pub use repositories::{ AuditEventRepository, EmailRepository, FederationRepository, InternalEventRepository, OidcRepository, PasskeyRepository, ServiceIdentityRepository, SessionRepository, diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 5ce25e1c4..712a5412f 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,15 +1,11 @@ //! Domain repository handles backed by a private pool or transaction connection. -<<<<<<< HEAD use crate::{ AppendAuditEvent, AppendInternalEvent, DatabaseError, InsertSession, InsertUser, InsertVerifiedEmail, StoredEmail, StoredSession, StoredUser, UpdateUserProfile, }; use piquel_auth_protocol::{AccountStatus, SessionId, UserId}; use sqlx::{PgConnection, PgPool, Row}; -======= -use sqlx::{PgConnection, PgPool}; ->>>>>>> main #[allow(dead_code)] pub(crate) enum RepositoryExecutor<'a> { @@ -48,7 +44,6 @@ repository!(OidcRepository); repository!(TokenRepository); repository!(FederationRepository); repository!(ServiceIdentityRepository); -<<<<<<< HEAD macro_rules! fetch_optional { ($self:expr, $query:expr) => {{ @@ -58,7 +53,7 @@ macro_rules! fetch_optional { $query.fetch_optional(&mut **connection).await } } - .map_err(crate::error::map_error) + .map_err(Into::::into) }}; } macro_rules! fetch_one { @@ -67,7 +62,7 @@ macro_rules! fetch_one { RepositoryExecutor::Pool(pool) => $query.fetch_one(*pool).await, RepositoryExecutor::Connection(connection) => $query.fetch_one(&mut **connection).await, } - .map_err(crate::error::map_error) + .map_err(Into::::into) }}; } macro_rules! execute { @@ -76,7 +71,7 @@ macro_rules! execute { RepositoryExecutor::Pool(pool) => $query.execute(*pool).await, RepositoryExecutor::Connection(connection) => $query.execute(&mut **connection).await, } - .map_err(crate::error::map_error) + .map_err(Into::::into) }}; } @@ -317,5 +312,3 @@ impl InternalEventRepository<'_> { .map_err(|_| DatabaseError::InvalidStoredData) } } -======= ->>>>>>> main diff --git a/crates/database/src/transaction.rs b/crates/database/src/transaction.rs index 736a2f614..f23be5d28 100644 --- a/crates/database/src/transaction.rs +++ b/crates/database/src/transaction.rs @@ -40,16 +40,9 @@ impl<'a> DatabaseTransaction<'a> { ServiceIdentityRepository::from_connection(&mut self.inner) } pub async fn commit(self) -> Result<(), DatabaseError> { -<<<<<<< HEAD - self.inner.commit().await.map_err(crate::error::map_error) - } - pub async fn rollback(self) -> Result<(), DatabaseError> { - self.inner.rollback().await.map_err(crate::error::map_error) -======= self.inner.commit().await.map_err(Into::into) } pub async fn rollback(self) -> Result<(), DatabaseError> { self.inner.rollback().await.map_err(Into::into) ->>>>>>> main } } From 77a35349928e6fb5987faa1adaae2fe085257b53 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 23:12:31 +0200 Subject: [PATCH 15/22] fix docs comment --- crates/auth-protocol/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/auth-protocol/src/lib.rs b/crates/auth-protocol/src/lib.rs index a387322f9..e0e1379cf 100644 --- a/crates/auth-protocol/src/lib.rs +++ b/crates/auth-protocol/src/lib.rs @@ -47,7 +47,7 @@ macro_rules! uuid_id { /// /// # Errors /// - /// Returns an error unless the value is `UUIDv7`. + /// Returns an error if the value is not `UUIDv7`. pub fn from_uuid(value: Uuid) -> Result { if value.get_version_num() != 7 { return Err(InvalidValue::new(stringify!($name))); From d168a77ad114f9ae5e95be8b54c9e48d52996568 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 23:57:30 +0200 Subject: [PATCH 16/22] Harden identity session and email ownership checks - Add active-session/profile helpers and transactional profile updates - Tighten email normalization and enforce active ownership serialization - Scope session and verified-email lookups to active accounts --- apps/auth-service/src/account.rs | 119 +++++++++++++++++- apps/auth-service/src/email.rs | 42 ++++++- apps/auth-service/src/session.rs | 90 +++++++++++++ .../migrations/0002_identity_sessions.sql | 42 +++++-- crates/database/src/repositories.rs | 4 +- crates/database/tests/identity.rs | 90 ++++++++++++- 6 files changed, 366 insertions(+), 21 deletions(-) diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs index d3c7a0865..c4ad55b8c 100644 --- a/apps/auth-service/src/account.rs +++ b/apps/auth-service/src/account.rs @@ -5,7 +5,7 @@ use chrono::Utc; use piquel_auth_protocol::{AccountStatus, TokenId, UserId}; use piquel_repository::{ AppendAuditEvent, AppendInternalEvent, Database, DatabaseError, InsertUser, - InsertVerifiedEmail, StoredUser, + InsertVerifiedEmail, StoredUser, UpdateUserProfile, }; use thiserror::Error; @@ -25,6 +25,13 @@ pub(super) struct CreateAccount { 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")] @@ -33,6 +40,18 @@ pub(super) enum AccountError { 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, @@ -133,6 +152,51 @@ pub(super) async fn disable(database: &Database, user_id: UserId) -> Result 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()) @@ -156,10 +220,63 @@ pub(super) fn validate_display_name(value: &str) -> Result<(), ()> { #[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/email.rs b/apps/auth-service/src/email.rs index a27845790..8420d2325 100644 --- a/apps/auth-service/src/email.rs +++ b/apps/auth-service/src/email.rs @@ -16,20 +16,47 @@ impl NormalizedEmail { /// Normalizes Unicode canonically, lowercases only the domain, and preserves /// the local part exactly. It intentionally does not remove dots or plus tags. pub(super) fn normalize(value: &str) -> Result { - let value = value.trim(); - if value.is_empty() || value.len() > 254 || value.chars().any(char::is_control) { + if value.is_empty() + || value.len() > 254 + || value + .chars() + .any(|character| character.is_control() || character.is_whitespace()) + { return Err(()); } let (local, domain) = value.rsplit_once('@').ok_or(())?; - if local.is_empty() || domain.is_empty() || local.len() > 64 || domain.contains('@') { + if local.is_empty() + || domain.is_empty() + || local.len() > 64 + || local.contains('@') + || local.starts_with('.') + || local.ends_with('.') + || local.contains("..") + { return Err(()); } let local = local.nfc().collect::(); let domain = domain.nfc().collect::().to_lowercase(); - if domain.starts_with('.') || domain.ends_with('.') || !domain.contains('.') { + let normalized = format!("{local}@{domain}"); + if local.len() > 64 || normalized.len() > 254 || !valid_domain(&domain) { return Err(()); } - Ok(NormalizedEmail(format!("{local}@{domain}"))) + Ok(NormalizedEmail(normalized)) +} + +fn valid_domain(domain: &str) -> bool { + let mut count = 0; + let valid = domain.split('.').all(|label| { + count += 1; + !(label.is_empty() + || label.len() > 63 + || label.starts_with('-') + || label.ends_with('-') + || !label + .chars() + .all(|character| character.is_alphanumeric() || character == '-')) + }); + valid && count >= 2 } #[cfg(test)] @@ -48,5 +75,10 @@ mod tests { #[test] fn rejects_ambiguous_values() { assert!(normalize("not-an-email").is_err()); + assert!(normalize("a@b@example.com").is_err()); + assert!(normalize("a b@example.com").is_err()); + assert!(normalize("a@example..com").is_err()); + assert!(normalize("a@-example.com").is_err()); + assert!(normalize(" a@example.com").is_err()); } } diff --git a/apps/auth-service/src/session.rs b/apps/auth-service/src/session.rs index 3953ee3b6..24e59ae1c 100644 --- a/apps/auth-service/src/session.rs +++ b/apps/auth-service/src/session.rs @@ -1,7 +1,10 @@ //! 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)] @@ -13,6 +16,14 @@ pub(super) struct NewSession { 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() @@ -30,3 +41,82 @@ pub(super) fn validate_new_session(session: &NewSession) -> Result<(), ()> { } 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/crates/database/migrations/0002_identity_sessions.sql b/crates/database/migrations/0002_identity_sessions.sql index bbccfaabb..ab1e3e2b8 100644 --- a/crates/database/migrations/0002_identity_sessions.sql +++ b/crates/database/migrations/0002_identity_sessions.sql @@ -29,14 +29,22 @@ CREATE TABLE active_verified_email_ownership ( ); CREATE OR REPLACE FUNCTION claim_active_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE account_active BOOLEAN; BEGIN - IF NEW.verified_at IS NOT NULL AND (SELECT status = 'active' FROM users WHERE id = NEW.user_id) THEN - INSERT INTO active_verified_email_ownership(normalized_email, user_id) - VALUES (NEW.normalized_email, NEW.user_id) - ON CONFLICT (normalized_email) DO UPDATE SET user_id = EXCLUDED.user_id - WHERE active_verified_email_ownership.user_id = EXCLUDED.user_id; - IF NOT FOUND THEN - RAISE EXCEPTION 'verified email already belongs to an active account' USING ERRCODE = 'unique_violation'; + IF NEW.verified_at IS NOT NULL THEN + -- Serialize email claims with status changes. Without this row lock an + -- insert can observe an active account, wait behind disablement, and + -- recreate ownership after the account has become disabled. + SELECT status = 'active' INTO account_active + FROM users WHERE id = NEW.user_id FOR UPDATE; + IF account_active THEN + INSERT INTO active_verified_email_ownership(normalized_email, user_id) + VALUES (NEW.normalized_email, NEW.user_id) + ON CONFLICT (normalized_email) DO UPDATE SET user_id = EXCLUDED.user_id + WHERE active_verified_email_ownership.user_id = EXCLUDED.user_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'verified email already belongs to an active account' USING ERRCODE = 'unique_violation'; + END IF; END IF; END IF; RETURN NEW; @@ -70,12 +78,22 @@ END $$; CREATE TRIGGER users_synchronize_email_ownership BEFORE UPDATE OF status ON users FOR EACH ROW EXECUTE FUNCTION synchronize_user_email_ownership(); CREATE OR REPLACE FUNCTION enforce_primary_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE affected UUID := COALESCE(NEW.user_id, OLD.user_id); +DECLARE + affected UUID; + affected_users UUID[]; BEGIN - IF EXISTS (SELECT 1 FROM user_emails WHERE user_id=affected AND verified_at IS NOT NULL) - AND (SELECT count(*) FROM user_emails WHERE user_id=affected AND verified_at IS NOT NULL AND is_primary) <> 1 - THEN RAISE EXCEPTION 'verified emails require exactly one primary' USING ERRCODE='check_violation'; END IF; - RETURN COALESCE(NEW, OLD); + IF TG_OP = 'INSERT' THEN affected_users := ARRAY[NEW.user_id]; + ELSIF TG_OP = 'DELETE' THEN affected_users := ARRAY[OLD.user_id]; + ELSE affected_users := ARRAY[NEW.user_id, OLD.user_id]; + END IF; + + FOREACH affected IN ARRAY affected_users LOOP + IF EXISTS (SELECT 1 FROM user_emails WHERE user_id=affected AND verified_at IS NOT NULL) + AND (SELECT count(*) FROM user_emails WHERE user_id=affected AND verified_at IS NOT NULL AND is_primary) <> 1 + THEN RAISE EXCEPTION 'verified emails require exactly one primary' USING ERRCODE='check_violation'; END IF; + END LOOP; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; END $$; CREATE CONSTRAINT TRIGGER user_emails_exactly_one_primary AFTER INSERT OR UPDATE OR DELETE ON user_emails DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION enforce_primary_verified_email(); diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 712a5412f..5ec872524 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -190,7 +190,7 @@ impl EmailRepository<'_> { &mut self, normalized: &str, ) -> Result, DatabaseError> { - let row = fetch_optional!(self, sqlx::query("SELECT e.id, e.user_id, e.normalized_email, e.verified_at, e.is_primary FROM active_verified_email_ownership o JOIN user_emails e ON e.user_id = o.user_id AND e.normalized_email = o.normalized_email AND e.verified_at IS NOT NULL WHERE o.normalized_email = $1 ORDER BY e.is_primary DESC, e.created_at LIMIT 1").bind(normalized))?; + let row = fetch_optional!(self, sqlx::query("SELECT e.id, e.user_id, e.normalized_email, e.verified_at, e.is_primary FROM active_verified_email_ownership o JOIN users u ON u.id = o.user_id AND u.status = 'active' JOIN user_emails e ON e.user_id = o.user_id AND e.normalized_email = o.normalized_email AND e.verified_at IS NOT NULL WHERE o.normalized_email = $1 ORDER BY e.is_primary DESC, e.created_at LIMIT 1").bind(normalized))?; row.map(|row| { Ok(StoredEmail { id: piquel_auth_protocol::TokenId::from_uuid( @@ -241,7 +241,7 @@ 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 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 SET last_seen_at=now() WHERE id=$1 AND revoked_at IS NULL AND expires_at>now()").bind(id.as_uuid()))?.rows_affected()==1) + 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!( diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index b93a11f21..9d8c870ef 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -22,7 +22,8 @@ async fn database() -> Database { async fn insert_user(database: &Database, prefix: &str) -> UserId { let id = UserId::new(); - let username = format!("{prefix}_{}", &id.to_string()[..8]); + let identifier = id.to_string(); + let username = format!("{prefix}_{}", &identifier[identifier.len() - 12..]); database .users() .insert(&InsertUser { @@ -266,4 +267,91 @@ async fn identity_transactions_and_concurrency_hold() { } ); 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; } From 4f28f1e737d8c8d355f6ec332088202344263066 Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 15 Jul 2026 00:01:05 +0200 Subject: [PATCH 17/22] fix database error --- crates/database/src/repositories.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 820aef924..259dd95bf 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -329,7 +329,7 @@ impl PasskeyRepository<'_> { let rows = match &mut self.executor { RepositoryExecutor::Pool(pool) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at LIMIT $2").bind(user_id.as_uuid()).bind(limit).fetch_all(*pool).await, RepositoryExecutor::Connection(connection) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at LIMIT $2").bind(user_id.as_uuid()).bind(limit).fetch_all(&mut **connection).await, - }.map_err(crate::error::map_error)?; + }.map_err(Into::::into)?; rows.iter().map(stored_passkey).collect() } From 56b3677c6c21781a9720d434810bdeb6a5cf48c4 Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 15 Jul 2026 00:07:19 +0200 Subject: [PATCH 18/22] fix merge --- crates/database/tests/identity.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index a62e43030..9981f79bc 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -109,7 +109,6 @@ async fn identity_transactions_and_concurrency_hold() { let first = insert_user(&database, "first").await; let second = insert_user(&database, "second").await; -<<<<<<< HEAD let ceremony_id = TokenId::new(); database @@ -167,8 +166,6 @@ async fn identity_transactions_and_concurrency_hold() { Err(DatabaseError::Conflict) )); -======= ->>>>>>> main let normalized = format!("race-{}@example.com", UserId::new()); let one = database.clone(); let two = database.clone(); From 5f91493c7044c2dd01670973a49d006a4e8e758a Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 15 Jul 2026 00:07:25 +0200 Subject: [PATCH 19/22] add validate to justfile --- justfile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/justfile b/justfile index 4c2aabf66..5ac2e7e14 100644 --- a/justfile +++ b/justfile @@ -21,3 +21,6 @@ migrate: prepare-sqlx: @cargo sqlx prepare --workspace + +validate: lint check test test-database doc-test + From c560b55183dbeffa57ae93c5bf3679e2b2cf5493 Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 15 Jul 2026 00:31:18 +0200 Subject: [PATCH 20/22] remove test-database --- crates/database/README.md | 6 ++---- justfile | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/database/README.md b/crates/database/README.md index 17bb72a85..6887f666d 100644 --- a/crates/database/README.md +++ b/crates/database/README.md @@ -10,7 +10,5 @@ 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. -The ignored PostgreSQL suite is explicit: set `TEST_DATABASE_URL` to an -isolated database and run `just test-database`. The checked-in test Dockerfile -can run the same suite on a container network when the host cannot reach the -database container. +Database tests are not currently configured. `just test-database` prints a +message and skips the database suite. diff --git a/justfile b/justfile index 5ac2e7e14..3be8a612d 100644 --- a/justfile +++ b/justfile @@ -11,7 +11,7 @@ test: @cargo nextest run --workspace test-database: - @cargo nextest run -p piquel-repository --test identity -- --ignored --test-threads=1 + @echo "No test database is configured; database tests will not run." doc-test: @cargo test --doc --workspace @@ -23,4 +23,3 @@ prepare-sqlx: @cargo sqlx prepare --workspace validate: lint check test test-database doc-test - From 78b6e1e8560d96b8e0df92567f9f7c19df059363 Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 15 Jul 2026 00:53:45 +0200 Subject: [PATCH 21/22] Support bootstrap and enrollment passkeys - Allow registration ceremonies to start without a user row - Commit ceremony consumption before finishing WebAuthn flows - Add enrollment ceremony support and return all active passkeys --- apps/auth-service/src/passkey.rs | 26 ++++++---- .../migrations/0003_passkey_credentials.sql | 2 +- crates/database/src/repositories.rs | 6 +-- crates/database/tests/identity.rs | 52 +++++++++++++++++++ 4 files changed, 72 insertions(+), 14 deletions(-) diff --git a/apps/auth-service/src/passkey.rs b/apps/auth-service/src/passkey.rs index fc6432145..c18f1d749 100644 --- a/apps/auth-service/src/passkey.rs +++ b/apps/auth-service/src/passkey.rs @@ -163,7 +163,9 @@ async fn start_registration( .passkeys() .insert_ceremony(&InsertCeremony { id: ceremony_id, - user_id: Some(user_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(), @@ -185,8 +187,11 @@ async fn finish_registration( if input.friendly_name.trim().is_empty() || input.friendly_name.chars().count() > 80 { return Err(ApiError); } - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - let ceremony = transaction + // 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 @@ -198,6 +203,7 @@ async fn finish_registration( .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 { @@ -281,7 +287,7 @@ async fn start_authentication( let stored = app .database .passkeys() - .list_active(user.id, 20) + .list_active(user.id) .await .map_err(|_| ApiError)?; if stored.is_empty() { @@ -325,8 +331,8 @@ async fn finish_authentication( State(app): State, Json(input): Json, ) -> Result { - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - let ceremony = transaction + let ceremony = app + .database .passkeys() .consume_ceremony(input.ceremony_id, "authentication") .await @@ -340,6 +346,7 @@ async fn finish_authentication( 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()) @@ -435,8 +442,8 @@ async fn finish_enrollment( } let session = active_session(&app.database, &headers).await?; require_fresh_session(&session)?; - let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; - let ceremony = transaction + let ceremony = app + .database .passkeys() .consume_ceremony(input.ceremony_id, "enrollment") .await @@ -449,6 +456,7 @@ async fn finish_enrollment( .webauthn .finish_passkey_registration(&input.credential, &state.webauthn) .map_err(|_| ApiError)?; + let mut transaction = app.database.begin().await.map_err(|_| ApiError)?; transaction .passkeys() .insert(&InsertPasskey { @@ -489,7 +497,7 @@ async fn list_passkeys( let keys = app .database .passkeys() - .list_active(session.user_id, 20) + .list_active(session.user_id) .await .map_err(|_| ApiError)?; Ok(Json( diff --git a/crates/database/migrations/0003_passkey_credentials.sql b/crates/database/migrations/0003_passkey_credentials.sql index 5961cfbe7..1c4aa8839 100644 --- a/crates/database/migrations/0003_passkey_credentials.sql +++ b/crates/database/migrations/0003_passkey_credentials.sql @@ -20,7 +20,7 @@ CREATE TABLE webauthn_ceremonies ( id UUID PRIMARY KEY, user_id UUID REFERENCES users(id) ON DELETE CASCADE, session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, - ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ('registration', 'authentication')), + ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment')), challenge_digest BYTEA NOT NULL, state JSONB NOT NULL, expires_at TIMESTAMPTZ NOT NULL, diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 259dd95bf..a75953faf 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -323,12 +323,10 @@ impl PasskeyRepository<'_> { pub async fn list_active( &mut self, user_id: UserId, - limit: u32, ) -> Result, DatabaseError> { - let limit = i64::from(limit.min(20)); let rows = match &mut self.executor { - RepositoryExecutor::Pool(pool) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at LIMIT $2").bind(user_id.as_uuid()).bind(limit).fetch_all(*pool).await, - RepositoryExecutor::Connection(connection) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at LIMIT $2").bind(user_id.as_uuid()).bind(limit).fetch_all(&mut **connection).await, + RepositoryExecutor::Pool(pool) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at").bind(user_id.as_uuid()).fetch_all(*pool).await, + RepositoryExecutor::Connection(connection) => sqlx::query("SELECT id,credential_id,user_id,credential,friendly_name,revoked_at FROM passkey_credentials WHERE user_id=$1 AND revoked_at IS NULL ORDER BY created_at").bind(user_id.as_uuid()).fetch_all(&mut **connection).await, }.map_err(Into::::into)?; rows.iter().map(stored_passkey).collect() } diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index 9981f79bc..91a24f106 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -110,6 +110,33 @@ async fn identity_transactions_and_concurrency_hold() { 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"); + let ceremony_id = TokenId::new(); database .passkeys() @@ -166,6 +193,31 @@ async fn identity_transactions_and_concurrency_hold() { 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(); From d38fbdb3fa8c30c0b21686ad1ef8e1456a30515b Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 15 Jul 2026 12:16:28 +0200 Subject: [PATCH 22/22] Add purpose tokens for passkey management - Sign short-lived ES256 tokens for passkey enrollment and revocation - Require fresh purpose authorization before sensitive passkey actions - Add database support and coverage for single-use authorization --- Cargo.lock | 120 ++++ Cargo.toml | 1 + apps/auth-service/Cargo.toml | 1 + apps/auth-service/src/lib.rs | 6 +- apps/auth-service/src/main.rs | 8 +- apps/auth-service/src/passkey.rs | 579 +++++++++++++++++- apps/auth-service/src/signing.rs | 149 +++++ .../migrations/0003_passkey_credentials.sql | 13 +- crates/database/src/models.rs | 8 + crates/database/src/repositories.rs | 32 +- crates/database/tests/identity.rs | 83 ++- 11 files changed, 971 insertions(+), 29 deletions(-) create mode 100644 apps/auth-service/src/signing.rs diff --git a/Cargo.lock b/Cargo.lock index 58b7b5fc9..d75a472eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -129,6 +129,7 @@ dependencies = [ "base64 0.22.1", "chrono", "openssl", + "p256", "piquel-auth-protocol", "piquel-configuration", "piquel-repository", @@ -205,6 +206,12 @@ 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" @@ -370,6 +377,18 @@ 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" @@ -446,6 +465,20 @@ 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" @@ -455,6 +488,26 @@ 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" @@ -493,6 +546,16 @@ 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" @@ -647,6 +710,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -683,6 +747,17 @@ dependencies = [ "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", +] + [[package]] name = "half" version = "2.7.1" @@ -1264,6 +1339,18 @@ 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" @@ -1419,6 +1506,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -1543,6 +1639,16 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -1638,6 +1744,20 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index 094f55542..ecc1cb404 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ 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" diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 3f2b773a5..b63bf7130 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -18,6 +18,7 @@ axum.workspace = true base64.workspace = true chrono.workspace = true openssl.workspace = true +p256.workspace = true rand.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 6ac0f4872..3a107dfcd 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -15,11 +15,12 @@ mod audit; mod email; #[allow(dead_code)] mod event_log; -#[allow(dead_code)] mod passkey; pub use passkey::PasskeyApplication; #[allow(dead_code)] mod session; +mod signing; +pub use signing::Es256KeyProvider; /// Typed auth-service configuration. #[derive(Clone, Debug)] @@ -36,6 +37,8 @@ pub struct AuthConfig { 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, } impl AuthConfig { /// Loads the minimum service configuration from the environment. @@ -73,6 +76,7 @@ impl AuthConfig { 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")?, }) } } diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index 2291b52ed..bb5950aac 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -1,6 +1,6 @@ #![allow(missing_docs)] -use auth_service::{AuthConfig, PasskeyApplication, ProductionReadiness, router}; +use auth_service::{AuthConfig, Es256KeyProvider, PasskeyApplication, ProductionReadiness, router}; use piquel_repository::Database; use std::{net::SocketAddr, sync::Arc}; @@ -10,10 +10,16 @@ async fn main() -> anyhow::Result<()> { 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"); diff --git a/apps/auth-service/src/passkey.rs b/apps/auth-service/src/passkey.rs index c18f1d749..ee164fed7 100644 --- a/apps/auth-service/src/passkey.rs +++ b/apps/auth-service/src/passkey.rs @@ -1,6 +1,9 @@ //! `WebAuthn` registration/authentication with database-backed single-use state. -use crate::account::{validate_display_name, validate_username}; +use crate::{ + Es256KeyProvider, + account::{validate_display_name, validate_username}, +}; use axum::{ Json, Router, extract::{Path, State}, @@ -13,7 +16,7 @@ use chrono::{Duration, Utc}; use piquel_auth_protocol::{AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ AppendAuditEvent, AppendInternalEvent, Database, DatabaseError, InsertCeremony, InsertPasskey, - InsertSession, InsertUser, + InsertPurposeAuthorization, InsertSession, InsertUser, StoredSession, }; use rand::{RngCore, rngs::OsRng}; use serde::{Deserialize, Serialize}; @@ -34,8 +37,15 @@ use webauthn_rs::{ 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")] @@ -52,6 +62,7 @@ impl PasskeyApplication { database: Database, rp_id: &str, origin: &Url, + purpose_keys: Arc, ) -> Result { validate_rp_origin(rp_id, origin)?; let webauthn = WebauthnBuilder::new(rp_id, origin) @@ -62,6 +73,8 @@ impl PasskeyApplication { Ok(Self { database, webauthn: Arc::new(webauthn), + issuer: origin.as_str().trim_end_matches('/').into(), + purpose_keys, }) } } @@ -97,6 +110,14 @@ pub(super) fn routes(application: PasskeyApplication) -> Router { .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}", @@ -284,19 +305,7 @@ async fn start_authentication( .await .map_err(|_| ApiError)? .ok_or(ApiError)?; - let stored = app - .database - .passkeys() - .list_active(user.id) - .await - .map_err(|_| ApiError)?; - if stored.is_empty() { - return Err(ApiError); - } - let passkeys = stored - .into_iter() - .map(|stored| serde_json::from_value::(stored.credential).map_err(|_| ApiError)) - .collect::, _>>()?; + let passkeys = active_passkeys(&app.database, user.id).await?; let (challenge, webauthn) = app .webauthn .start_passkey_authentication(&passkeys) @@ -381,10 +390,207 @@ async fn finish_authentication( 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 + } +} + +#[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); + } + let result = app + .webauthn + .finish_passkey_authentication(&input.credential, &state.webauthn) + .map_err(|_| ApiError)?; + if !result.user_verified() { + return Err(ApiError); + } + + 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)?, + ) + .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, } @@ -393,7 +599,7 @@ async fn start_enrollment( headers: HeaderMap, ) -> Result, ApiError> { let session = active_session(&app.database, &headers).await?; - require_fresh_session(&session)?; + let authorization = require_purpose_authorization(&app, &headers, &session).await?; let user = app .database .users() @@ -408,6 +614,7 @@ async fn start_enrollment( let state = serde_json::to_value(EnrollmentState { user_id: user.id, session_id: session.id, + authorization_id: authorization.jti, webauthn, }) .map_err(|_| ApiError)?; @@ -441,7 +648,7 @@ async fn finish_enrollment( return Err(ApiError); } let session = active_session(&app.database, &headers).await?; - require_fresh_session(&session)?; + let authorization = require_purpose_authorization(&app, &headers, &session).await?; let ceremony = app .database .passkeys() @@ -449,7 +656,10 @@ async fn finish_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 { + if state.user_id != session.user_id + || state.session_id != session.id + || state.authorization_id != authorization.jti + { return Err(ApiError); } let passkey = app @@ -457,6 +667,19 @@ async fn finish_enrollment( .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); + } transaction .passkeys() .insert(&InsertPasskey { @@ -540,8 +763,21 @@ async fn revoke_passkey( Path(id): Path, ) -> Result { let session = active_session(&app.database, &headers).await?; - require_fresh_session(&session)?; + 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, + ) + .await + .map_err(|_| ApiError)?; + if !consumed { + return Err(ApiError); + } let revoked = transaction .passkeys() .revoke_if_not_last(id, session.user_id) @@ -578,10 +814,42 @@ async fn active_session( .ok_or(ApiError) } -fn require_fresh_session(session: &piquel_repository::StoredSession) -> Result<(), ApiError> { - (Utc::now().signed_duration_since(session.authenticated_at) <= Duration::minutes(10)) - .then_some(()) - .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); + } + let active = app + .database + .passkeys() + .purpose_authorization_is_active( + claims.jti, + session.user_id, + session.id, + MANAGE_PASSKEYS_PURPOSE, + ) + .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( @@ -679,8 +947,45 @@ impl From for ApiError { #[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}")); + } + 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() + }; + builder.body(body).expect("request") + } + + 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") + } + #[test] fn rp_origin_rejects_attacker_controlled_urls() { for origin in [ @@ -718,6 +1023,54 @@ mod tests { assert_eq!(session_secret(&headers), Some(secret.to_vec())); } + #[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())); + } + #[test] fn standards_conformant_authenticator_registers_and_authenticates() { let origin = Url::parse("https://auth.example.com").expect("origin"); @@ -751,4 +1104,184 @@ mod tests { .expect("authentication finish"); assert!(result.user_verified()); } + + #[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); + } } diff --git a/apps/auth-service/src/signing.rs b/apps/auth-service/src/signing.rs new file mode 100644 index 000000000..fda48d206 --- /dev/null +++ b/apps/auth-service/src/signing.rs @@ -0,0 +1,149 @@ +//! 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/crates/database/migrations/0003_passkey_credentials.sql b/crates/database/migrations/0003_passkey_credentials.sql index 1c4aa8839..7969d3785 100644 --- a/crates/database/migrations/0003_passkey_credentials.sql +++ b/crates/database/migrations/0003_passkey_credentials.sql @@ -20,7 +20,7 @@ CREATE TABLE webauthn_ceremonies ( id UUID PRIMARY KEY, user_id UUID REFERENCES users(id) ON DELETE CASCADE, session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, - ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment')), + ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment', 'purpose_authentication')), challenge_digest BYTEA NOT NULL, state JSONB NOT NULL, expires_at TIMESTAMPTZ NOT NULL, @@ -29,6 +29,17 @@ 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/src/models.rs b/crates/database/src/models.rs index 785cebe12..c1645f99e 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -111,3 +111,11 @@ 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, +} diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index a75953faf..4b1e9679a 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -2,8 +2,8 @@ use crate::{ AppendAuditEvent, AppendInternalEvent, ConsumedCeremony, DatabaseError, InsertCeremony, - InsertPasskey, InsertSession, InsertUser, InsertVerifiedEmail, StoredEmail, StoredPasskey, - StoredSession, StoredUser, UpdateUserProfile, + InsertPasskey, InsertPurposeAuthorization, InsertSession, InsertUser, InsertVerifiedEmail, + StoredEmail, StoredPasskey, StoredSession, StoredUser, UpdateUserProfile, }; use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; use sqlx::{PgConnection, PgPool, Row}; @@ -406,6 +406,34 @@ 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 { diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index 91a24f106..c5e4a76d7 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -4,7 +4,7 @@ use chrono::{Duration as ChronoDuration, Utc}; use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ AppendInternalEvent, Database, DatabaseConfig, DatabaseError, InsertCeremony, InsertPasskey, - InsertSession, InsertUser, InsertVerifiedEmail, UpdateUserProfile, + InsertPurposeAuthorization, InsertSession, InsertUser, InsertVerifiedEmail, UpdateUserProfile, }; use std::{env, time::Duration}; @@ -136,6 +136,19 @@ async fn identity_transactions_and_concurrency_hold() { }) .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 @@ -291,6 +304,55 @@ async fn identity_transactions_and_concurrency_hold() { }) .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() @@ -305,6 +367,25 @@ async fn identity_transactions_and_concurrency_hold() { .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(),