diff --git a/.cargo/audit.toml b/.cargo/audit.toml new file mode 100644 index 0000000..9ece048 --- /dev/null +++ b/.cargo/audit.toml @@ -0,0 +1,5 @@ +# Mirrors deny.toml. Reason: Tessera only verifies RSA signatures with public keys +# (openidconnect core/crypto.rs); runtime code never performs RSA private-key operations +# (test fixtures sign tokens with throwaway keys). +[advisories] +ignore = ["RUSTSEC-2023-0071"] diff --git a/Cargo.lock b/Cargo.lock index d081204..d670b42 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,7 +8,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "generic-array", ] @@ -20,7 +20,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] @@ -119,10 +119,20 @@ checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" dependencies = [ "base64ct", "blake2", - "cpufeatures", + "cpufeatures 0.2.17", "password-hash", ] +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -225,6 +235,12 @@ dependencies = [ "tracing", ] +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base64" version = "0.22.1" @@ -232,10 +248,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] -name = "base64ct" -version = "1.0.1" +name = "base64" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a32fd6af2b5827bce66c29053ba0e7c42b9dcab01835835058558c10851a46b" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bitflags" @@ -249,7 +271,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -261,6 +283,24 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -291,6 +331,23 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -321,7 +378,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "inout", ] @@ -344,7 +401,7 @@ dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim", + "strsim 0.10.0", ] [[package]] @@ -374,12 +431,30 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.10.1" @@ -402,6 +477,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -411,6 +492,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "cron" version = "0.12.1" @@ -422,6 +512,22 @@ dependencies = [ "once_cell", ] +[[package]] +name = "crypto-bigint" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -429,10 +535,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core", + "rand_core 0.6.4", "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "getrandom 0.4.3", + "hybrid-array", + "rand_core 0.10.1", +] + [[package]] name = "ctr" version = "0.9.2" @@ -442,11 +559,125 @@ dependencies = [ "cipher", ] +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", + "subtle", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim 0.11.1", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "deadpool" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +dependencies = [ + "deadpool-runtime", + "lazy_static", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468 0.7.0", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.3", + "pem-rfc7468 1.0.0", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] [[package]] name = "digest" @@ -454,17 +685,114 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "dunce" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.3", + "digest 0.11.3", + "elliptic-curve", + "rfc6979", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", +] + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "pkcs8 0.11.0", + "signature 3.0.0", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.11.1", + "signature 3.0.0", + "subtle", + "zeroize", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct", + "crypto-bigint", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff", + "group", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "encoding_rs" version = "0.8.44" @@ -513,12 +841,34 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" @@ -540,12 +890,65 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -564,8 +967,13 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -587,8 +995,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -598,8 +1008,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -612,6 +1025,42 @@ dependencies = [ "polyval", ] +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff", + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.2.6", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.14.5" @@ -642,6 +1091,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + [[package]] name = "hex" version = "0.4.3" @@ -654,7 +1109,16 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", ] [[package]] @@ -708,6 +1172,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "subtle", + "typenum", + "zeroize", +] + [[package]] name = "hyper" version = "1.12.0" @@ -716,7 +1191,9 @@ checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", + "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -725,6 +1202,23 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", ] [[package]] @@ -733,13 +1227,22 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", + "httparse", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", "tower-service", + "tracing", ] [[package]] @@ -766,6 +1269,116 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[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 = "include_dir" version = "0.7.4" @@ -785,6 +1398,17 @@ dependencies = [ "quote", ] +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.2.6" @@ -805,18 +1429,85 @@ dependencies = [ "generic-array", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is_terminal_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jiff" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -843,6 +1534,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -850,6 +1544,12 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libsqlite3-sys" version = "0.39.1" @@ -867,6 +1567,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "lock_api" version = "0.4.14" @@ -882,6 +1588,12 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "matchers" version = "0.2.0" @@ -978,12 +1690,47 @@ 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 0.8.8", + "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-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +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" @@ -991,6 +1738,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "oauth2" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" +dependencies = [ + "base64 0.22.1", + "chrono", + "getrandom 0.2.17", + "http", + "rand 0.8.8", + "reqwest", + "serde", + "serde_json", + "serde_path_to_error", + "sha2 0.10.8", + "thiserror 1.0.69", + "url", ] [[package]] @@ -1011,12 +1789,80 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "openidconnect" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df0d098a59353679624d406825940139e2b2d554a52b64c9fb1b1bc42a11fe5c" +dependencies = [ + "base64 0.22.1", + "chrono", + "dyn-clone", + "ed25519-dalek", + "getrandom 0.4.3", + "hmac 0.12.1", + "http", + "itertools", + "log", + "oauth2", + "p256", + "p384", + "rand 0.8.8", + "rsa", + "serde", + "serde-value", + "serde_json", + "serde_path_to_error", + "serde_plain", + "serde_with", + "sha2 0.10.8", + "subtle", + "thiserror 1.0.69", + "url", +] + [[package]] name = "openssl-probe" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primefield", + "primeorder", + "sha2 0.11.1", +] + +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa", + "elliptic-curve", + "fiat-crypto", + "primefield", + "primeorder", + "sha2 0.11.1", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -1047,7 +1893,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" dependencies = [ "base64ct", - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -1057,10 +1903,28 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64", + "base64 0.22.1", "serde_core", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1091,6 +1955,37 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -1104,11 +1999,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "opaque-debug", "universal-hash", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "powerfmt" version = "0.2.1" @@ -1124,6 +2043,33 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.2", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro-error" version = "1.0.4" @@ -1157,6 +2103,62 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -1180,7 +2182,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -1190,7 +2203,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1202,6 +2215,21 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "rcgen" version = "0.13.2" @@ -1224,6 +2252,26 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "regex" version = "1.13.1" @@ -1253,6 +2301,54 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint", + "hmac 0.13.0", +] + [[package]] name = "ring" version = "0.17.14" @@ -1267,6 +2363,27 @@ dependencies = [ "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 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sha2 0.10.8", + "signature 2.2.0", + "spki 0.7.3", + "subtle", + "zeroize", +] + [[package]] name = "rsqlite-vfs" version = "0.2.0" @@ -1291,6 +2408,21 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.6" @@ -1338,6 +2470,7 @@ version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" dependencies = [ + "web-time", "zeroize", ] @@ -1383,12 +2516,50 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der 0.8.3", + "hybrid-array", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -1412,6 +2583,12 @@ dependencies = [ "libc", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1422,6 +2599,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float", + "serde", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -1466,6 +2653,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_plain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50" +dependencies = [ + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1478,6 +2674,49 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.2.6", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -1491,8 +2730,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -1520,6 +2770,26 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -1560,6 +2830,26 @@ version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", +] + [[package]] name = "sqlite-wasm-rs" version = "0.6.3" @@ -1570,12 +2860,24 @@ dependencies = [ "rsqlite-vfs", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "strsim" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subtle" version = "2.6.1" @@ -1619,6 +2921,20 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] [[package]] name = "tempfile" @@ -1638,14 +2954,14 @@ name = "tessera-agent" version = "0.1.0" dependencies = [ "anyhow", - "base64", + "base64 0.22.1", "clap", "hex", "rustls", "rustls-native-certs", "serde", "serde_json", - "sha2", + "sha2 0.10.8", "tempfile", "tessera-core", "tessera-providers", @@ -1665,7 +2981,7 @@ dependencies = [ "hex", "serde", "serde_json", - "sha2", + "sha2 0.10.8", "tempfile", "tessera-core", "tessera-demo", @@ -1683,7 +2999,7 @@ dependencies = [ "hex", "serde", "serde_json", - "sha2", + "sha2 0.10.8", "thiserror 1.0.69", "utoipa", "uuid", @@ -1711,22 +3027,25 @@ dependencies = [ "anyhow", "argon2", "axum", - "base64", + "base64 0.22.1", "chrono", "chrono-tz", "cron", "hex", + "hmac 0.12.1", "hyper", "hyper-util", "include_dir", - "indexmap", - "rand", + "indexmap 2.2.6", + "openidconnect", + "rand 0.8.8", "rcgen", + "rsa", "rusqlite", "rustls", "serde", "serde_json", - "sha2", + "sha2 0.10.8", "tempfile", "tessera-core", "tessera-demo", @@ -1741,6 +3060,7 @@ dependencies = [ "tracing-subscriber", "utoipa", "uuid", + "wiremock", ] [[package]] @@ -1769,11 +3089,11 @@ dependencies = [ "argon2", "chrono", "hex", - "hmac", - "rand", + "hmac 0.12.1", + "rand 0.8.8", "serde", "serde_json", - "sha2", + "sha2 0.10.8", "tempfile", "tessera-core", "thiserror 1.0.69", @@ -1843,6 +3163,7 @@ dependencies = [ "powerfmt", "serde_core", "time-core", + "time-macros", ] [[package]] @@ -1851,6 +3172,32 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -1939,9 +3286,11 @@ dependencies = [ "pin-project-lite", "tokio", "tokio-util", + "tower", "tower-layer", "tower-service", "tracing", + "url", ] [[package]] @@ -2018,6 +3367,12 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -2042,7 +3397,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "subtle", ] @@ -2052,19 +3407,47 @@ 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.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "utoipa" version = "4.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5afb1a60e207dca502682537fefcfd9921e71d0b83e9576060f09abc6efab23" dependencies = [ - "indexmap", + "indexmap 2.2.6", "serde", "serde_json", "utoipa-gen", @@ -2122,6 +3505,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2140,6 +3532,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.130" @@ -2172,6 +3575,35 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi-util" version = "0.1.11" @@ -2322,6 +3754,47 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wiremock" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +dependencies = [ + "assert-json-diff", + "base64 0.22.1", + "deadpool", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "yasna" version = "0.5.2" @@ -2331,6 +3804,29 @@ dependencies = [ "time", ] +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -2351,12 +3847,66 @@ dependencies = [ "syn 2.0.119", ] +[[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.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + [[package]] name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/crates/tessera-hub/Cargo.toml b/crates/tessera-hub/Cargo.toml index 8dc5efd..f74c928 100644 --- a/crates/tessera-hub/Cargo.toml +++ b/crates/tessera-hub/Cargo.toml @@ -35,6 +35,7 @@ uuid.workspace = true hex.workspace = true sha2.workspace = true base64 = "0.22" +openidconnect = { version = "=4.1.0", default-features = false, features = ["reqwest", "rustls-tls"] } tempfile.workspace = true indexmap = "=2.2.6" hyper = { version = "=1.12.0", features = ["server", "http1"] } @@ -45,4 +46,7 @@ tower = { workspace = true } [dev-dependencies] rcgen = "=0.13.2" +wiremock = "=0.6.5" +rsa = { version = "=0.9.10", features = ["sha2"] } +hmac.workspace = true tokio.workspace = true diff --git a/crates/tessera-hub/src/admin.rs b/crates/tessera-hub/src/admin.rs index 67cc454..22ec3d7 100644 --- a/crates/tessera-hub/src/admin.rs +++ b/crates/tessera-hub/src/admin.rs @@ -167,36 +167,69 @@ mod tests { } } +/// Issuer of the break-glass operator row. It is not an `https://` URL, so no +/// OIDC provider can ever produce an identity that maps onto it. +pub const EMERGENCY_ISSUER: &str = "local:emergency"; + #[derive(Clone)] pub struct SessionGate { config: Option>, - state: std::sync::Arc>, -} - -#[derive(Default)] -struct SessionState { - sessions: std::collections::HashMap, - attempts: std::collections::VecDeque, + db: crate::db::Db, + /// Fingerprint of the OIDC configuration (issuer, client, admin mapping). + /// OIDC sessions only count while the same configuration is active. + oidc_fp: Option, + attempts: std::sync::Arc>>, } struct OperatorConfig { name: String, password_hash: String, + /// Sessions are bound to this value, so unsetting or rotating the operator + /// hash invalidates every emergency session even though they persist. + fingerprint: String, } #[derive(Clone)] pub struct BrowserSession { pub id: uuid::Uuid, - pub csrf: uuid::Uuid, + pub csrf: String, pub actor: String, - expires: std::time::Instant, + /// Read by per-user revoke and the OIDC login path (M3/M5). + #[allow(dead_code)] + pub user_id: String, + pub auth_method: String, + /// May use the management API. A signed-in user without a grant is `false`. + pub admin: bool, + pub expires_at: i64, +} + +impl BrowserSession { + /// Audit identity. Never derived from IdP-supplied names: OIDC users are + /// identified by their stable user id, so a username of "operator" cannot + /// be mistaken for the emergency account. + pub fn principal(&self) -> crate::auth::Principal { + match self.auth_method.as_str() { + "oidc" => crate::auth::Principal::Oidc(self.user_id.clone()), + _ => crate::auth::Principal::Emergency(self.actor.clone()), + } + } +} + +fn fingerprint(password_hash: &str) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(format!("tessera-operator-credential-v1:{password_hash}"))) +} + +fn unix_now() -> i64 { + chrono::Utc::now().timestamp() } impl SessionGate { pub const COOKIE: &str = "__Host-tessera-session"; - pub const DURATION: std::time::Duration = std::time::Duration::from_secs(8 * 3600); + pub const DURATION: std::time::Duration = + std::time::Duration::from_secs(crate::db::sessions::ABSOLUTE_SECS as u64); - pub fn from_env() -> anyhow::Result { + pub fn from_env(db: crate::db::Db, oidc_fp: Option) -> anyhow::Result { let config = match std::env::var("TESSERA_OPERATOR_PASSWORD_HASH") { Ok(password_hash) => { let name = @@ -215,6 +248,7 @@ impl SessionGate { "operator password requires Argon2id" ); Some(std::sync::Arc::new(OperatorConfig { + fingerprint: fingerprint(&password_hash), name, password_hash, })) @@ -222,62 +256,132 @@ impl SessionGate { Err(std::env::VarError::NotPresent) => None, Err(_) => anyhow::bail!("operator password hash must be UTF-8"), }; - Ok(Self { - config, - state: Default::default(), - }) + Ok(Self { config, db, oidc_fp, attempts: Default::default() }) } + /// Any browser login method is configured (emergency password and/or OIDC). pub fn enabled(&self) -> bool { + self.config.is_some() || self.oidc_fp.is_some() + } + + /// The emergency password form is available. + pub fn password_enabled(&self) -> bool { self.config.is_some() } pub fn active(&self, headers: &HeaderMap) -> Option { + self.active_at(headers, unix_now()) + } + + pub(crate) fn active_at(&self, headers: &HeaderMap, now: i64) -> Option { let id = cookie_id(headers)?; - let mut state = self.state.lock().unwrap(); - state - .sessions - .retain(|_, session| session.expires > std::time::Instant::now()); - state.sessions.get(&id).cloned() + let stored = match self.db.lookup_session(&id.to_string(), now) { + Ok(found) => found?, + Err(error) => { + tracing::error!("session lookup failed: {error:#}"); + return None; + } + }; + // Sessions only count while the credential/configuration that created + // them is still the active one, so unsetting or rotating either revokes them. + let expected = match stored.auth_method.as_str() { + "password" => self.config.as_ref().map(|config| config.fingerprint.as_str()), + "oidc" => self.oidc_fp.as_deref(), + _ => None, + }?; + if stored.credential_fp.as_deref() != Some(expected) { + return None; + } + Some(BrowserSession { + id, + csrf: crate::db::sessions::csrf_token(&id.to_string()), + actor: stored.display_name, + user_id: stored.user_id, + auth_method: stored.auth_method, + admin: stored.admin, + expires_at: stored.expires_at, + }) } pub fn login(&self, headers: &HeaderMap, password: &str) -> Result { use argon2::PasswordVerifier; let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?; { - let mut state = self.state.lock().unwrap(); - state - .attempts - .retain(|attempt| attempt.elapsed() < std::time::Duration::from_secs(60)); - if state.attempts.len() >= 10 { + let mut attempts = self.attempts.lock().unwrap(); + attempts.retain(|attempt| attempt.elapsed() < std::time::Duration::from_secs(60)); + if attempts.len() >= 10 { return Err(StatusCode::TOO_MANY_REQUESTS); } - state.attempts.push_back(std::time::Instant::now()); + attempts.push_back(std::time::Instant::now()); } let hash = argon2::PasswordHash::new(&config.password_hash) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; argon2::Argon2::default() .verify_password(password.as_bytes(), &hash) .map_err(|_| StatusCode::UNAUTHORIZED)?; - if let Some(id) = cookie_id(headers) { - self.remove(id); - } - let session = BrowserSession { - id: uuid::Uuid::new_v4(), - csrf: uuid::Uuid::new_v4(), - actor: config.name.clone(), - expires: std::time::Instant::now() + Self::DURATION, + let internal = |error: anyhow::Error| { + tracing::error!("session create failed: {error:#}"); + StatusCode::INTERNAL_SERVER_ERROR }; - let mut state = self.state.lock().unwrap(); - state - .sessions - .retain(|_, session| session.expires > std::time::Instant::now()); - state.sessions.insert(session.id, session.clone()); - Ok(session) + // A new ID on every login: a pre-existing cookie never survives (fixation). + if let Some(old) = cookie_id(headers) { + self.remove(old); + } + let now = unix_now(); + let user_id = self + .db + .upsert_user(EMERGENCY_ISSUER, &config.name, &config.name, now) + .map_err(internal)?; + let id = uuid::Uuid::new_v4(); + let created = self + .db + .create_session(&id.to_string(), &user_id, "password", Some(&config.fingerprint), true, now) + .map_err(internal)?; + if !created { + // Inactive user row: the break-glass account has been disabled. + return Err(StatusCode::UNAUTHORIZED); + } + Ok(BrowserSession { + id, + csrf: crate::db::sessions::csrf_token(&id.to_string()), + actor: config.name.clone(), + user_id, + auth_method: "password".into(), + admin: true, + expires_at: now + crate::db::sessions::ABSOLUTE_SECS, + }) + } + + /// Start an OIDC-backed session for a verified identity. The caller has + /// already validated the ID token; `admin` comes from the configured mapping. + pub fn create_oidc( + &self, + user_id: &str, + display_name: &str, + admin: bool, + now: i64, + ) -> anyhow::Result { + let fp = self.oidc_fp.as_deref().ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?; + let id = uuid::Uuid::new_v4(); + anyhow::ensure!( + self.db.create_session(&id.to_string(), user_id, "oidc", Some(fp), admin, now)?, + "user is disabled" + ); + Ok(BrowserSession { + id, + csrf: crate::db::sessions::csrf_token(&id.to_string()), + actor: display_name.to_string(), + user_id: user_id.to_string(), + auth_method: "oidc".into(), + admin, + expires_at: now + crate::db::sessions::ABSOLUTE_SECS, + }) } pub fn remove(&self, id: uuid::Uuid) { - self.state.lock().unwrap().sessions.remove(&id); + if let Err(error) = self.db.revoke_session(&id.to_string()) { + tracing::error!("session revoke failed: {error:#}"); + } } } @@ -315,25 +419,147 @@ pub fn print_operator_hash() -> anyhow::Result<()> { #[cfg(test)] impl SessionGate { - pub fn fixture() -> Self { + pub fn fixture(db: crate::db::Db) -> Self { use argon2::password_hash::{PasswordHasher, SaltString}; let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap(); let password_hash = argon2::Argon2::default() .hash_password(b"fixture-operator-password", &salt) .unwrap() .to_string(); + Self::with_hash(db, "fixture-operator", password_hash) + } + + pub fn with_hash(db: crate::db::Db, name: &str, password_hash: String) -> Self { Self { config: Some(std::sync::Arc::new(OperatorConfig { - name: "fixture-operator".into(), + name: name.into(), + fingerprint: fingerprint(&password_hash), password_hash, })), - state: Default::default(), + db, + oidc_fp: None, + attempts: Default::default(), } } + /// Same database, no operator configured (hash unset after a restart). + pub fn without_operator(db: crate::db::Db) -> Self { + Self { config: None, db, oidc_fp: None, attempts: Default::default() } + } + + pub fn with_oidc(mut self, fingerprint: &str) -> Self { + self.oidc_fp = Some(fingerprint.into()); + self + } + pub fn expire(&self) { - for session in self.state.lock().unwrap().sessions.values_mut() { - session.expires = std::time::Instant::now(); - } + self.db.expire_all_sessions(); + } +} + +#[cfg(test)] +mod session_gate_tests { + use super::*; + use axum::http::HeaderValue; + + fn hash(password: &str, salt: &[u8]) -> String { + use argon2::password_hash::{PasswordHasher, SaltString}; + argon2::Argon2::default() + .hash_password(password.as_bytes(), &SaltString::encode_b64(salt).unwrap()) + .unwrap() + .to_string() + } + + fn cookie(session: &BrowserSession) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + axum::http::header::COOKIE, + HeaderValue::from_str(&format!("{}={}", SessionGate::COOKIE, session.id)).unwrap(), + ); + headers + } + + async fn db() -> (tempfile::TempDir, crate::db::Db) { + let dir = tempfile::tempdir().unwrap(); + let db = crate::db::Db::connect(&dir.path().join("t.db")).await.unwrap(); + db.migrate().await.unwrap(); + (dir, db) + } + + #[tokio::test] + async fn a_session_outlives_a_restart_only_with_the_same_operator_credential() { + let (_dir, db) = db().await; + let first = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one")); + let session = first.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + // restart with the same credential: still valid + let restarted = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one")); + assert!(restarted.active(&cookie(&session)).is_some()); + // hash rotated after a suspected compromise: old cookie is dead + let rotated = SessionGate::with_hash(db.clone(), "ops", hash("another-long-password", b"salt-number-two")); + assert!(rotated.active(&cookie(&session)).is_none()); + // emergency login disabled by unsetting the hash: old cookie is dead + assert!(SessionGate::without_operator(db.clone()).active(&cookie(&session)).is_none()); + // and it comes back only if the exact credential is configured again + assert!(restarted.active(&cookie(&session)).is_some()); + } + + #[tokio::test] + async fn login_replaces_a_presented_session_id() { + let (_dir, db) = db().await; + let gate = SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one")); + let old = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + let new = gate.login(&cookie(&old), "correct-horse-battery").unwrap(); + assert_ne!(old.id, new.id); + assert!(gate.active(&cookie(&old)).is_none()); + assert!(gate.active(&cookie(&new)).is_some()); + assert_eq!(old.user_id, new.user_id, "same break-glass user row across logins"); + } + + #[tokio::test] + async fn absolute_expiry_and_user_revoke_apply_to_the_gate() { + let (_dir, db) = db().await; + let gate = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one")); + let session = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + let now = unix_now(); + assert!(gate.active_at(&cookie(&session), now + 60).is_some()); + assert!(gate.active_at(&cookie(&session), now + crate::db::sessions::ABSOLUTE_SECS).is_none()); + assert_eq!(db.revoke_user_sessions(&session.user_id).unwrap(), 1); + assert!(gate.active(&cookie(&session)).is_none()); + assert!(gate.login(&HeaderMap::new(), "correct-horse-battery").is_ok()); + } + + #[tokio::test] + async fn the_csrf_token_is_stable_for_a_session_and_not_the_cookie() { + let (_dir, db) = db().await; + let gate = SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one")); + let session = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + let again = gate.active(&cookie(&session)).unwrap(); + assert_eq!(session.csrf, again.csrf); + assert!(!session.csrf.contains(&session.id.to_string())); + } + + #[tokio::test] + async fn oidc_sessions_end_when_the_oidc_configuration_changes_or_is_removed() { + let (_dir, db) = db().await; + let user = db.upsert_user("https://idp.example", "alice", "Alice", unix_now()).unwrap(); + let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a"); + let session = gate.create_oidc(&user, "Alice", true, unix_now()).unwrap(); + assert_eq!(session.principal().fields().0, format!("oidc:{user}")); + assert!(gate.active(&cookie(&session)).is_some()); + // admin mapping changed (different fingerprint) or OIDC switched off: dead + assert!(SessionGate::without_operator(db.clone()).with_oidc("fp-b").active(&cookie(&session)).is_none()); + assert!(SessionGate::without_operator(db.clone()).active(&cookie(&session)).is_none()); + // configuration restored: the same session is valid again + assert!(SessionGate::without_operator(db).with_oidc("fp-a").active(&cookie(&session)).is_some()); + } + + #[tokio::test] + async fn an_oidc_display_name_never_becomes_the_emergency_principal() { + let (_dir, db) = db().await; + let user = db.upsert_user("https://idp.example", "mallory", "operator", unix_now()).unwrap(); + let session = SessionGate::without_operator(db).with_oidc("fp").create_oidc(&user, "operator", false, unix_now()).unwrap(); + let (id, kind, method) = session.principal().fields(); + assert_eq!((kind, method), ("user", "oidc")); + assert!(id.starts_with("oidc:") && !id.contains("emergency")); } } diff --git a/crates/tessera-hub/src/api/auth_contract.rs b/crates/tessera-hub/src/api/auth_contract.rs index 5ff1e6e..cdf6652 100644 --- a/crates/tessera-hub/src/api/auth_contract.rs +++ b/crates/tessera-hub/src/api/auth_contract.rs @@ -18,6 +18,7 @@ fn every_registered_path_has_an_authorization_contract() { include_str!("restore.rs"), include_str!("catalog.rs"), include_str!("session.rs"), + include_str!("oidc.rs"), ] { for route in source.split(".route(").skip(1) { let path = route.split('"').nth(1).expect("route literal"); @@ -36,7 +37,7 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") .await .unwrap(); - state.sessions = crate::admin::SessionGate::fixture(); + state.sessions = crate::admin::SessionGate::fixture(state.db.clone()); state.admin.token = Some("synthetic-admin".into()); let outpost = uuid::Uuid::new_v4(); state diff --git a/crates/tessera-hub/src/api/mod.rs b/crates/tessera-hub/src/api/mod.rs index f7e653b..d48ac40 100644 --- a/crates/tessera-hub/src/api/mod.rs +++ b/crates/tessera-hub/src/api/mod.rs @@ -1,11 +1,14 @@ mod catalog; mod jobs; +mod oidc; mod orbit; mod restore; mod routes; mod session; #[cfg(test)] mod auth_contract; +#[cfg(test)] +mod oidc_tests; pub use orbit::run_orbit_internal; pub use routes::router; diff --git a/crates/tessera-hub/src/api/oidc.rs b/crates/tessera-hub/src/api/oidc.rs new file mode 100644 index 0000000..a38fd70 --- /dev/null +++ b/crates/tessera-hub/src/api/oidc.rs @@ -0,0 +1,160 @@ +//! Browser SSO endpoints. Both are public GET navigations: the IdP redirects +//! the browser back here. No tokens are ever sent to the browser, and every +//! redirect target is fixed (`/`), so there is no `next` parameter to abuse. +use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal}; +use crate::oidc::OidcError; +use crate::state::HubState; +use axum::{ + extract::{Query, State}, + http::{header, HeaderMap, HeaderValue, StatusCode}, + response::{IntoResponse, Redirect, Response}, + routing::get, + Router, +}; +use serde::Deserialize; + +const CORRELATION: &str = "__Host-tessera-oidc"; + +pub(super) fn routes() -> Router { + Router::new() + .route("/api/v1/auth/oidc/login", get(login)) + .route("/api/v1/auth/oidc/callback", get(callback)) +} + +#[derive(Deserialize)] +struct CallbackQuery { + code: Option, + state: Option, + error: Option, +} + +fn now() -> i64 { + chrono::Utc::now().timestamp() +} + +/// Correlation cookie: SameSite=Lax so it survives the IdP's cross-site GET +/// redirect, while the session cookie itself stays Strict. +fn correlation_cookie(value: Option<&str>) -> HeaderValue { + let text = format!( + "{CORRELATION}={}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={}", + value.unwrap_or_default(), + if value.is_some() { crate::db::oidc_login::TTL_SECS } else { 0 }, + ); + HeaderValue::from_str(&text).expect("cookie is ASCII") +} + +fn no_store(headers: &mut HeaderMap) { + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); +} + +fn correlation_from(headers: &HeaderMap) -> Option { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|h| h.to_str().ok()) + .flat_map(|line| line.split(';')) + .find_map(|pair| { + let (name, value) = pair.trim().split_once('=')?; + (name == CORRELATION && !value.is_empty() && value.len() <= 128).then(|| value.to_string()) + }) +} + +async fn login(State(state): State) -> Response { + let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() }; + let begun = match oidc.begin().await { + Ok(begun) => begun, + Err(_) => return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await, + }; + let browser = uuid::Uuid::new_v4().to_string(); + let stored = state.db.begin_oidc_login(&begun.state, &browser, &begun.nonce, &begun.verifier, now()); + if !matches!(stored, Ok(true)) { + return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await; + } + let mut response = Redirect::to(&begun.url).into_response(); + no_store(response.headers_mut()); + response.headers_mut().append(header::SET_COOKIE, correlation_cookie(Some(&browser))); + response +} + +async fn callback(State(state): State, headers: HeaderMap, Query(query): Query) -> Response { + let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() }; + let outcome = complete(&state, &oidc, &headers, query).await; + let mut response = match outcome { + Ok(session) => { + let mut response = Redirect::to("/").into_response(); + if let Ok(cookie) = super::session::session_cookie(Some(&session.id.to_string())) { + response.headers_mut().append(header::SET_COOKIE, cookie); + } + response + } + Err(code) => Redirect::to(&format!("/?auth_error={code}")).into_response(), + }; + no_store(response.headers_mut()); + // The correlation cookie is single-use whatever happened. + response.headers_mut().append(header::SET_COOKIE, correlation_cookie(None)); + response +} + +/// Returns the new session, or a fixed error code that is safe to show. +async fn complete( + state: &HubState, + oidc: &crate::oidc::OidcProvider, + headers: &HeaderMap, + query: CallbackQuery, +) -> Result { + let request = uuid::Uuid::new_v4(); + let audit = |principal: &Principal, outcome| { + let _ = state.db.audit_event(principal, AuditAction::Login, AuditResource::Session, outcome, request); + }; + let Some(state_param) = query.state.as_deref() else { + audit(&Principal::Anonymous, AuditOutcome::Failed); + return Err("invalid_state"); + }; + let browser = correlation_from(headers); + let transaction = state.db.consume_oidc_login(state_param, browser.as_deref(), now()); + let Ok(Some((nonce, verifier))) = transaction else { + audit(&Principal::Anonymous, AuditOutcome::Failed); + return Err("invalid_state"); + }; + if query.error.is_some() { + // The IdP refused (for example access_denied); nothing from it is echoed. + audit(&Principal::Anonymous, AuditOutcome::Failed); + return Err("denied"); + } + let Some(code) = query.code.as_deref().filter(|c| !c.is_empty() && c.len() <= 2048) else { + audit(&Principal::Anonymous, AuditOutcome::Failed); + return Err("failed"); + }; + let identity = match oidc.finish(code, &nonce, &verifier).await { + Ok(identity) => identity, + Err(error) => { + audit(&Principal::Anonymous, AuditOutcome::Failed); + return Err(if matches!(error, OidcError::Unavailable) { "unavailable" } else { "failed" }); + } + }; + let admin = oidc.config.is_admin(&identity); + let now = now(); + let session = state + .db + .upsert_user(&identity.issuer, &identity.subject, &identity.display_name, now) + .map_err(anyhow::Error::from) + .and_then(|user_id| state.sessions.create_oidc(&user_id, &identity.display_name, admin, now)); + match session { + Ok(session) => { + audit(&session.principal(), AuditOutcome::Succeeded); + Ok(session) + } + Err(error) => { + tracing::warn!("OIDC session not created: {error:#}"); + audit(&Principal::Anonymous, AuditOutcome::Failed); + Err("disabled") + } + } +} + +async fn failure(state: &HubState, code: &'static str, status: StatusCode) -> Response { + let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::Login, AuditResource::Session, AuditOutcome::Failed, uuid::Uuid::new_v4()); + let mut response = (status, code).into_response(); + no_store(response.headers_mut()); + response +} diff --git a/crates/tessera-hub/src/api/oidc_tests.rs b/crates/tessera-hub/src/api/oidc_tests.rs new file mode 100644 index 0000000..2014f14 --- /dev/null +++ b/crates/tessera-hub/src/api/oidc_tests.rs @@ -0,0 +1,552 @@ +//! End-to-end OIDC login against a mock IdP. Tokens are hand-built and signed +//! with throwaway RSA keys generated in this process, so every negative case +//! (wrong nonce, issuer, audience, signature, `alg: none`, HS256, rotation) is +//! a real failure of verification, not of the fixture. +use crate::admin::SessionGate; +use crate::oidc::{OidcConfig, OidcProvider}; +use crate::state::HubState; +use axum::body::{to_bytes, Body}; +use axum::extract::ConnectInfo; +use axum::http::{header, Request, Response, StatusCode}; +use base64::Engine; +use hmac::{Hmac, Mac}; +use rsa::pkcs1v15::SigningKey; +use rsa::signature::{SignatureEncoding, Signer}; +use rsa::traits::PublicKeyParts; +use rsa::RsaPrivateKey; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; +use tower::ServiceExt; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, Request as MockRequest, Respond, ResponseTemplate}; + +const CLIENT_ID: &str = "tessera"; +const CLIENT_SECRET: &str = "synthetic-client-secret"; +const REDIRECT: &str = "https://hub.example/api/v1/auth/oidc/callback"; + +fn b64(bytes: impl AsRef<[u8]>) -> String { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) +} + +/// Index 0 = the IdP's key, 1 = its rotated key, 2 = an attacker's key. +fn keys() -> &'static [RsaPrivateKey; 3] { + static KEYS: OnceLock<[RsaPrivateKey; 3]> = OnceLock::new(); + KEYS.get_or_init(|| { + let mut rng = rand::rngs::OsRng; + [0, 1, 2].map(|_| RsaPrivateKey::new(&mut rng, 2048).unwrap()) + }) +} + +#[derive(Clone)] +struct Scenario { + nonce: String, + challenge: String, + sub: Option, + name: Option, + email: Option, + iss: Option, + aud: Value, + azp: Option, + exp_in: i64, + alg: &'static str, + signer: usize, + kid: &'static str, + groups: Option, + token_status: u16, +} + +impl Default for Scenario { + fn default() -> Self { + Self { + nonce: String::new(), + challenge: String::new(), + sub: Some("admin-sub".into()), + name: Some("Ada Admin".into()), + email: None, + iss: None, + aud: json!(CLIENT_ID), + azp: None, + exp_in: 3600, + alg: "RS256", + signer: 0, + kid: "k1", + groups: None, + token_status: 200, + } + } +} + +struct Idp { + server: MockServer, + scenario: Arc>, + jwks: Arc>>, +} + +struct TokenEndpoint { + scenario: Arc>, + issuer: String, +} + +fn sign(alg: &str, kid: &str, signer: usize, claims: &Value) -> String { + let header = json!({"alg": alg, "typ": "JWT", "kid": kid}); + let signing_input = format!("{}.{}", b64(header.to_string()), b64(claims.to_string())); + let signature = match alg { + "RS256" => b64(SigningKey::::new(keys()[signer].clone()).sign(signing_input.as_bytes()).to_bytes()), + "HS256" => { + let mut mac = Hmac::::new_from_slice(CLIENT_SECRET.as_bytes()).unwrap(); + mac.update(signing_input.as_bytes()); + b64(mac.finalize().into_bytes()) + } + _ => String::new(), // alg "none" + }; + format!("{signing_input}.{signature}") +} + +impl Respond for TokenEndpoint { + fn respond(&self, request: &MockRequest) -> ResponseTemplate { + let scenario = self.scenario.lock().unwrap().clone(); + if scenario.token_status != 200 { + return ResponseTemplate::new(scenario.token_status); + } + let form: std::collections::HashMap = + openidconnect::url::form_urlencoded::parse(&request.body).into_owned().collect(); + // Real PKCE check: S256(code_verifier) must equal the challenge sent at /authorize. + let verifier = form.get("code_verifier").cloned().unwrap_or_default(); + if b64(Sha256::digest(verifier.as_bytes())) != scenario.challenge || form.get("code").map(String::as_str) != Some("good-code") { + return ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"})); + } + let now = chrono::Utc::now().timestamp(); + let mut claims = json!({ + "iss": scenario.iss.clone().unwrap_or_else(|| self.issuer.clone()), + "aud": scenario.aud, + "exp": now + scenario.exp_in, + "iat": now, + "nonce": scenario.nonce, + }); + let object = claims.as_object_mut().unwrap(); + if let Some(sub) = &scenario.sub { + object.insert("sub".into(), json!(sub)); + } + if let Some(name) = &scenario.name { + object.insert("preferred_username".into(), json!(name)); + } + if let Some(email) = &scenario.email { + object.insert("email".into(), json!(email)); + } + if let Some(azp) = &scenario.azp { + object.insert("azp".into(), json!(azp)); + } + if let Some(groups) = &scenario.groups { + object.insert("groups".into(), groups.clone()); + } + ResponseTemplate::new(200).set_body_json(json!({ + "access_token": "synthetic-access-token-never-shown", + "token_type": "Bearer", + "expires_in": 3600, + "id_token": sign(scenario.alg, scenario.kid, scenario.signer, &claims), + })) + } +} + +impl Idp { + async fn start() -> Self { + // Generate the RSA keys up front: inside a mock handler, a slow debug-build + // keygen would eat the hub's HTTP timeout. + tokio::task::spawn_blocking(|| { keys(); }).await.unwrap(); + let server = MockServer::start().await; + let scenario = Arc::new(Mutex::new(Scenario::default())); + let jwks = Arc::new(Mutex::new(vec![("k1", 0usize)])); + let issuer = server.uri(); + Mock::given(method("GET")).and(path("/.well-known/openid-configuration")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "issuer": issuer, + "authorization_endpoint": format!("{issuer}/authorize"), + "token_endpoint": format!("{issuer}/token"), + "jwks_uri": format!("{issuer}/jwks"), + "response_types_supported": ["code"], + "subject_types_supported": ["public"], + "id_token_signing_alg_values_supported": ["RS256"], + }))) + .mount(&server).await; + let served = jwks.clone(); + Mock::given(method("GET")).and(path("/jwks")) + .respond_with(move |_: &MockRequest| { + let keys_json: Vec = served.lock().unwrap().iter().map(|(kid, index)| { + let public = keys()[*index].to_public_key(); + json!({"kty":"RSA","use":"sig","alg":"RS256","kid":kid, + "n": b64(public.n().to_bytes_be()), "e": b64(public.e().to_bytes_be())}) + }).collect(); + ResponseTemplate::new(200).set_body_json(json!({"keys": keys_json})) + }) + .mount(&server).await; + Mock::given(method("POST")).and(path("/token")) + .respond_with(TokenEndpoint { scenario: scenario.clone(), issuer }) + .mount(&server).await; + Self { server, scenario, jwks } + } + + fn issuer(&self) -> String { + self.server.uri() + } + + async fn hits(&self, route: &str) -> usize { + self.server.received_requests().await.unwrap().iter().filter(|r| r.url.path() == route).count() + } +} + +struct Harness { + app: axum::Router, + state: HubState, + idp: Idp, + _dir: tempfile::TempDir, +} + +fn config(idp: &Idp) -> OidcConfig { + let mut config = OidcConfig::new(&idp.issuer(), CLIENT_ID, CLIENT_SECRET, REDIRECT); + config.admin_subjects.insert("admin-sub".into()); + config.admin_groups.insert("tessera-admins".into()); + config +} + +async fn harness_with(min_refresh: Duration) -> Harness { + let idp = Idp::start().await; + let dir = tempfile::tempdir().unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let config = config(&idp); + state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc(&config.fingerprint()); + state.oidc = Some(Arc::new(OidcProvider::new(config).unwrap().with_min_refresh(min_refresh))); + let app = crate::api::router(state.clone()); + Harness { app, state, idp, _dir: dir } +} + +async fn harness() -> Harness { + harness_with(Duration::from_secs(60)).await +} + +fn get(uri: &str, cookies: &[String]) -> Request { + let mut request = Request::builder().uri(uri).extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())); + if !cookies.is_empty() { + request = request.header(header::COOKIE, cookies.join("; ")); + } + request.body(Body::empty()).unwrap() +} + +fn set_cookies(response: &Response) -> Vec { + response.headers().get_all(header::SET_COOKIE).iter().map(|v| v.to_str().unwrap().to_string()).collect() +} + +fn cookie_pair(set_cookie: &str) -> String { + set_cookie.split(';').next().unwrap().to_string() +} + +fn location(response: &Response) -> String { + response.headers()[header::LOCATION].to_str().unwrap().to_string() +} + +struct Started { + state: String, + correlation: String, +} + +impl Harness { + async fn call(&self, request: Request) -> Response { + self.app.clone().oneshot(request).await.unwrap() + } + + /// Visit /login, check the authorization request, and arm the IdP with the + /// nonce and PKCE challenge the hub generated. + async fn start(&self) -> Started { + let response = self.call(get("/api/v1/auth/oidc/login", &[])).await; + assert!(response.status().is_redirection(), "login redirects, got {}", response.status()); + let target = openidconnect::url::Url::parse(&location(&response)).unwrap(); + assert!(target.as_str().starts_with(&format!("{}/authorize", self.idp.issuer()))); + let q: std::collections::HashMap = target.query_pairs().into_owned().collect(); + assert_eq!(q["response_type"], "code"); + assert_eq!(q["client_id"], CLIENT_ID); + assert_eq!(q["redirect_uri"], REDIRECT); + assert_eq!(q["code_challenge_method"], "S256"); + assert!(q["scope"].split(' ').any(|s| s == "openid")); + assert!(!q.contains_key("next") && !q.contains_key("client_secret")); + let cookies = set_cookies(&response); + assert_eq!(cookies.len(), 1); + for flag in ["HttpOnly", "Secure", "SameSite=Lax", "Path=/"] { + assert!(cookies[0].contains(flag), "{flag} in {}", cookies[0]); + } + assert!(cookies[0].starts_with("__Host-tessera-oidc=")); + { + let mut scenario = self.idp.scenario.lock().unwrap(); + scenario.nonce = q["nonce"].clone(); + scenario.challenge = q["code_challenge"].clone(); + } + Started { state: q["state"].clone(), correlation: cookie_pair(&cookies[0]) } + } + + async fn callback(&self, started: &Started, query: &str) -> Response { + self.call(get(&format!("/api/v1/auth/oidc/callback?{query}"), &[started.correlation.clone()])).await + } + + /// Full successful-or-not login with the current scenario. + async fn login(&self) -> (Response, Started) { + let started = self.start().await; + let response = self.callback(&started, &format!("code=good-code&state={}", started.state)).await; + (response, started) + } + + fn mutate(&self, change: impl FnOnce(&mut Scenario)) { + change(&mut self.idp.scenario.lock().unwrap()); + } + + fn count(&self, table: &str) -> i64 { + rusqlite::Connection::open(self.state.data_dir.join("tessera.db")) + .unwrap() + .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0)) + .unwrap() + } + + fn query(&self, sql: &str) -> T { + rusqlite::Connection::open(self.state.data_dir.join("tessera.db")).unwrap().query_row(sql, [], |r| r.get(0)).unwrap() + } +} + +fn session_cookie(response: &Response) -> String { + let cookies = set_cookies(response); + let session = cookies.iter().find(|c| c.starts_with("__Host-tessera-session=") && !c.contains("Max-Age=0")).expect("session cookie"); + for flag in ["HttpOnly", "Secure", "SameSite=Strict"] { + assert!(session.contains(flag)); + } + cookie_pair(session) +} + +async fn json_body(response: Response) -> Value { + serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()).unwrap() +} + +#[tokio::test] +async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() { + let h = harness().await; + let (response, started) = h.login().await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert_eq!(location(&response), "/", "fixed redirect target"); + let cookies = set_cookies(&response); + assert_eq!(cookies.len(), 2, "session cookie plus cleared correlation cookie: {cookies:?}"); + assert!(cookies.iter().any(|c| c.starts_with("__Host-tessera-oidc=;") && c.contains("Max-Age=0"))); + let session = session_cookie(&response); + let headers_text = format!("{:?}", response.headers()); + assert!(!headers_text.contains("synthetic-access-token") && !headers_text.contains("eyJ")); + assert!(to_bytes(response.into_body(), 4096).await.unwrap().is_empty()); + + let me = h.call(get("/api/v1/me", &[session.clone()])).await; + assert_eq!(me.status(), StatusCode::OK); + let me = json_body(me).await; + assert_eq!(me["kind"], "user"); + assert_eq!(me["auth_method"], "oidc"); + assert!(me["id"].as_str().unwrap().starts_with("oidc:")); + assert_eq!(me["display_name"], "Ada Admin"); + assert_eq!(me["capabilities"][0], "admin"); + assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::OK); + + // Identity is (issuer, subject); the transaction was consumed; the audit actor is the stable user id. + let issuer: String = h.query("SELECT issuer FROM users"); + assert_eq!(issuer, h.idp.issuer()); + assert_eq!(h.count("oidc_login"), 0); + let actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='auth.login' AND outcome='succeeded'"); + assert_eq!(actor, me["id"]); + // PKCE verified by the IdP and the code is not reusable by replaying the callback. + let replay = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + assert_eq!(location(&replay), "/?auth_error=invalid_state"); + assert!(set_cookies(&replay).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0"))); + assert_eq!(h.count("sessions"), 1); +} + +#[tokio::test] +async fn a_signed_in_user_without_a_grant_gets_identity_but_no_api_access() { + let h = harness().await; + // Display name "operator" must not be mistaken for the emergency account. + h.mutate(|s| { s.sub = Some("plain-user".into()); s.name = Some("operator".into()); }); + let (response, _) = h.login().await; + assert_eq!(location(&response), "/"); + let session = session_cookie(&response); + + let me = json_body(h.call(get("/api/v1/me", &[session.clone()])).await).await; + assert_eq!(me["capabilities"].as_array().unwrap().len(), 0); + assert!(me["id"].as_str().unwrap().starts_with("oidc:"), "{me}"); + let status = json_body(h.call(get("/api/v1/operator/session", &[session.clone()])).await).await; + assert_eq!(status["authorized"], false); + assert_eq!(status["actor"], "operator"); + assert!(status["csrf"].is_string(), "can still sign out"); + assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::FORBIDDEN); + let denied_actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='denied' ORDER BY id DESC LIMIT 1"); + assert!(denied_actor.starts_with("oidc:"), "audited as the OIDC user, not emergency:operator: {denied_actor}"); + + let logout = Request::builder().method("DELETE").uri("/api/v1/operator/session") + .extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())) + .header(header::COOKIE, session.clone()) + .header("x-tessera-csrf", status["csrf"].as_str().unwrap()) + .body(Body::empty()).unwrap(); + assert_eq!(h.call(logout).await.status(), StatusCode::NO_CONTENT); + assert_eq!(h.call(get("/api/v1/me", &[session])).await.status(), StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn admin_comes_from_a_verified_group_claim_and_a_bad_claim_grants_nothing() { + let h = harness().await; + for (groups, expect_admin) in [ + (Some(json!(["dev", "tessera-admins"])), true), + (Some(json!("tessera-admins")), true), + (Some(json!(["dev"])), false), + (Some(json!({"tessera-admins": true})), false), + (Some(json!([["tessera-admins"]])), false), + (None, false), + ] { + h.mutate(|s| { s.sub = Some("group-user".into()); s.groups = groups.clone(); }); + let (response, _) = h.login().await; + let session = session_cookie(&response); + let expected = if expect_admin { StatusCode::OK } else { StatusCode::FORBIDDEN }; + assert_eq!(h.call(get("/api/v1/orbits", &[session])).await.status(), expected, "{groups:?}"); + } +} + +#[tokio::test] +async fn the_same_email_under_a_different_subject_is_a_different_user() { + let h = harness().await; + for sub in ["sub-a", "sub-b", "sub-a"] { + h.mutate(|s| { s.sub = Some(sub.into()); s.email = Some("same@example.com".into()); }); + let (response, _) = h.login().await; + assert_eq!(location(&response), "/"); + } + assert_eq!(h.count("users"), 2, "two subjects, no linking by email; the repeat logs in as the first"); +} + +#[tokio::test] +async fn invalid_tokens_never_create_a_session_or_a_user() { + let _ = tracing_subscriber::fmt().with_test_writer().try_init(); + let h = harness().await; + let cases: Vec<(&str, Box)> = vec![ + ("wrong nonce", Box::new(|s| s.nonce = "not-the-nonce".into())), + ("wrong issuer", Box::new(|s| s.iss = Some("https://evil.example".into()))), + ("wrong audience", Box::new(|s| s.aud = json!("someone-else"))), + ("extra audience without azp", Box::new(|s| s.aud = json!([CLIENT_ID, "other"]))), + ("azp is another client", Box::new(|s| { s.aud = json!([CLIENT_ID, "other"]); s.azp = Some("other".into()); })), + ("expired", Box::new(|s| s.exp_in = -3600)), + ("signed by an attacker key", Box::new(|s| s.signer = 2)), + ("alg none", Box::new(|s| s.alg = "none")), + ("HS256 with the client secret", Box::new(|s| s.alg = "HS256")), + ("no subject", Box::new(|s| s.sub = None)), + ("empty subject", Box::new(|s| s.sub = Some(String::new()))), + ]; + for (name, change) in cases { + h.mutate(|s| *s = Scenario::default()); + let started = h.start().await; + h.mutate(|s| change(s)); + let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + let target = location(&response); + assert!(target == "/?auth_error=failed", "{name}: {target}"); + assert!(set_cookies(&response).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")), "{name}"); + assert_eq!(h.count("sessions"), 0, "{name}"); + assert_eq!(h.count("users"), 0, "{name}"); + } +} + +#[tokio::test] +async fn login_transactions_cannot_be_replayed_borrowed_or_forged() { + let h = harness().await; + // Another browser (no / wrong correlation cookie) holding the right state. + let started = h.start().await; + let no_cookie = h.call(get(&format!("/api/v1/auth/oidc/callback?code=good-code&state={}", started.state), &[])).await; + assert_eq!(location(&no_cookie), "/?auth_error=invalid_state"); + let again = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + assert_eq!(location(&again), "/?auth_error=invalid_state", "a failed attempt burns the transaction"); + + let started = h.start().await; + let wrong = Started { state: started.state.clone(), correlation: "__Host-tessera-oidc=forged".into() }; + assert_eq!(location(&h.callback(&wrong, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state"); + + // Unknown, missing and mismatched state. + let started = h.start().await; + assert_eq!(location(&h.callback(&started, "code=good-code&state=made-up").await), "/?auth_error=invalid_state"); + assert_eq!(location(&h.callback(&started, "code=good-code").await), "/?auth_error=invalid_state"); + + // Expired transaction. + let started = h.start().await; + rusqlite::Connection::open(h.state.data_dir.join("tessera.db")).unwrap().execute("UPDATE oidc_login SET expires_at = 1", []).unwrap(); + assert_eq!(location(&h.callback(&started, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state"); + + // The IdP reporting an error: shown as a fixed code, nothing echoed, transaction consumed. + let started = h.start().await; + let denied = h.callback(&started, &format!("error=access_denied&error_description=secret-detail&state={}", started.state)).await; + assert_eq!(location(&denied), "/?auth_error=denied"); + assert!(!format!("{:?}", denied.headers()).contains("secret-detail")); + assert_eq!(h.count("oidc_login"), 0); + assert_eq!(h.count("sessions"), 0); + + // A wrong code is rejected by the IdP. + let started = h.start().await; + assert_eq!(location(&h.callback(&started, &format!("code=bad-code&state={}", started.state)).await), "/?auth_error=failed"); + assert_eq!(h.count("sessions"), 0); + let failed: i64 = h.query("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='failed' AND actor_id='anonymous'"); + assert!(failed >= 6); +} + +#[tokio::test] +async fn rotated_signing_keys_are_picked_up_but_refreshes_are_rate_limited() { + let h = harness_with(Duration::from_millis(1)).await; + let (first, _) = h.login().await; + assert_eq!(location(&first), "/"); + assert_eq!(h.idp.hits("/jwks").await, 1); + + // The IdP rotates: new key and kid, old key withdrawn. The cached key set is stale. + *h.idp.jwks.lock().unwrap() = vec![("k2", 1)]; + h.mutate(|s| { s.signer = 1; s.kid = "k2"; }); + tokio::time::sleep(Duration::from_millis(5)).await; + let (after, _) = h.login().await; + assert_eq!(location(&after), "/", "refreshed once and verified with the new key"); + assert_eq!(h.idp.hits("/jwks").await, 2); + + // With the default 60s gap, a flood of bad signatures cannot hammer the IdP. + let limited = harness().await; + for _ in 0..4 { + limited.mutate(|s| *s = Scenario::default()); + let started = limited.start().await; + limited.mutate(|s| s.signer = 2); + let r = limited.callback(&started, &format!("code=good-code&state={}", started.state)).await; + assert_eq!(location(&r), "/?auth_error=failed"); + } + assert!(limited.idp.hits("/.well-known/openid-configuration").await <= 2); +} + +#[tokio::test] +async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() { + // Cold start with the IdP down: no redirect, no transaction stored. + let cold = harness().await; + cold.idp.server.reset().await; + let down = cold.call(get("/api/v1/auth/oidc/login", &[])).await; + assert_eq!(down.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(cold.count("oidc_login"), 0); + + // Warm cache, then the token endpoint dies mid-login. + let h = harness().await; + let (ok, _) = h.login().await; + assert_eq!(location(&ok), "/"); + h.mutate(|s| s.token_status = 500); + let started = h.start().await; // metadata is cached, so /login still works + let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + assert!(response.status().is_redirection()); + assert!(location(&response).starts_with("/?auth_error=")); + h.idp.server.reset().await; + let started = h.start().await; + let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + assert!(location(&response).starts_with("/?auth_error="), "{}", location(&response)); +} + +#[tokio::test] +async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() { + let dir = tempfile::tempdir().unwrap(); + let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let app = crate::api::router(state); + for uri in ["/api/v1/auth/oidc/login", "/api/v1/auth/oidc/callback?code=x&state=y"] { + assert_eq!(app.clone().oneshot(get(uri, &[])).await.unwrap().status(), StatusCode::NOT_FOUND); + } +} diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index 36b51fe..3222609 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -237,7 +237,7 @@ struct ReconstituteStartResponse { pub(super) struct OperatorActor { pub(super) name: String, browser: bool, - principal: Principal, + pub(super) principal: Principal, request_id: Uuid, } @@ -263,16 +263,18 @@ pub(super) fn require_admin_mutation( authorize_operator(state, peer, headers, true) } -fn authorize_operator( +pub(super) fn authorize_operator( state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, ) -> Result { let request_id = Uuid::new_v4(); - let attempted_actor = state.sessions.active(headers) - .map(|session| Principal::Emergency(session.actor)).unwrap_or(Principal::Anonymous); - let result = authorize_operator_inner(state, peer, headers, mutation, request_id); + // Resolve the session once: each lookup is a DB query and may slide the idle window. + let session = state.sessions.active(headers); + let attempted_actor = session.as_ref() + .map(|session| session.principal()).unwrap_or(Principal::Anonymous); + let result = authorize_operator_inner(state, peer, headers, mutation, request_id, session); let actor = result.as_ref().map(|actor| &actor.principal).unwrap_or(&attempted_actor); state.db.audit_event(actor, AuditAction::Authorization, AuditResource::Api, if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied }, request_id) @@ -282,16 +284,21 @@ fn authorize_operator( fn authorize_operator_inner( state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid, + session: Option, ) -> Result { if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() { return Ok(OperatorActor { name: "api-token".into(), browser: false, principal: Principal::Service("legacy-admin-token"), request_id }); } - if let Some(session) = state.sessions.active(headers) { + if let Some(session) = session { + // Signed in is not the same as allowed: a user without a grant gets 403. + if !session.admin { + return Err(StatusCode::FORBIDDEN); + } if mutation { super::session::require_csrf(headers, &session.csrf.to_string())?; } - return Ok(OperatorActor { principal: Principal::Emergency(session.actor.clone()), + return Ok(OperatorActor { principal: session.principal(), name: session.actor, browser: true, request_id }); } if !state.sessions.enabled() { @@ -327,6 +334,7 @@ pub fn router(state: HubState) -> Router { .merge(super::jobs::routes()) .merge(super::catalog::routes()) .merge(super::session::routes()) + .merge(super::oidc::routes()) .merge(super::restore::routes()) .with_state(state); diff --git a/crates/tessera-hub/src/api/session.rs b/crates/tessera-hub/src/api/session.rs index 07acb20..699d744 100644 --- a/crates/tessera-hub/src/api/session.rs +++ b/crates/tessera-hub/src/api/session.rs @@ -13,9 +13,11 @@ use std::net::SocketAddr; #[derive(Serialize)] struct Status { login_enabled: bool, + oidc_enabled: bool, authorized: bool, actor: Option, csrf: Option, + expires_at: Option, } #[derive(Deserialize)] @@ -28,6 +30,7 @@ pub(super) fn routes() -> Router { Router::new() .route("/api/v1/operator/session", get(status).delete(logout)) .route("/api/v1/operator/login", post(login)) + .route("/api/v1/me", get(me)) } async fn status( @@ -36,20 +39,52 @@ async fn status( headers: HeaderMap, ) -> (HeaderMap, Json) { let browser = state.sessions.active(&headers); - let authorized = browser.is_some() - || (!state.sessions.enabled() && state.admin.token.is_none() + let authorized = browser.as_ref().is_some_and(|session| session.admin) + || (browser.is_none() && !state.sessions.enabled() && state.admin.token.is_none() && state.admin.authorize(peer, &headers).is_ok()); ( no_store(), Json(Status { - login_enabled: state.sessions.enabled(), + login_enabled: state.sessions.password_enabled(), + oidc_enabled: state.oidc.is_some(), authorized, actor: browser.as_ref().map(|session| session.actor.clone()), + expires_at: browser.as_ref().map(|session| session.expires_at), csrf: browser.map(|session| session.csrf.to_string()), }), ) } +#[derive(Serialize)] +struct Me { + id: String, + kind: &'static str, + auth_method: &'static str, + display_name: String, + capabilities: Vec<&'static str>, +} + +/// The caller's own identity. Every authenticated principal is an administrator +/// until scoped grants exist (M5), which is what `capabilities` reports. +async fn me( + ConnectInfo(peer): ConnectInfo, + State(state): State, + headers: HeaderMap, +) -> Result<(HeaderMap, Json), StatusCode> { + // A signed-in user without a grant still gets their identity (capabilities empty). + if let Some(session) = state.sessions.active(&headers) { + let (id, kind, auth_method) = session.principal().fields(); + let capabilities = if session.admin { vec!["admin"] } else { vec![] }; + return Ok((no_store(), Json(Me { id, kind, auth_method, display_name: session.actor, capabilities }))); + } + let actor = super::routes::authorize_operator(&state, peer, &headers, false)?; + let (id, kind, auth_method) = actor.principal.fields(); + Ok(( + no_store(), + Json(Me { id, kind, auth_method, display_name: actor.name.clone(), capabilities: vec!["admin"] }), + )) +} + async fn login( State(state): State, headers: HeaderMap, @@ -75,13 +110,15 @@ async fn login( .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let mut headers = no_store(); - headers.insert(header::SET_COOKIE, cookie(Some(&session.id.to_string()))?); + headers.insert(header::SET_COOKIE, session_cookie(Some(&session.id.to_string()))?); Ok(( headers, Json(Status { login_enabled: true, + oidc_enabled: state.oidc.is_some(), authorized: true, actor: Some(session.actor), + expires_at: Some(session.expires_at), csrf: Some(session.csrf.to_string()), }), )) @@ -97,7 +134,7 @@ async fn logout( .ok_or(StatusCode::UNAUTHORIZED)?; require_csrf(&headers, &session.csrf.to_string())?; state.sessions.remove(session.id); - state.db.audit_event(&Principal::Emergency(session.actor.clone()), AuditAction::Logout, + state.db.audit_event(&session.principal(), AuditAction::Logout, AuditResource::Session, AuditOutcome::Succeeded, uuid::Uuid::new_v4()) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; state @@ -106,7 +143,7 @@ async fn logout( .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let mut headers = no_store(); - headers.insert(header::SET_COOKIE, cookie(None)?); + headers.insert(header::SET_COOKIE, session_cookie(None)?); Ok((StatusCode::NO_CONTENT, headers)) } @@ -128,7 +165,7 @@ fn no_store() -> HeaderMap { headers } -fn cookie(id: Option<&str>) -> Result { +pub(super) fn session_cookie(id: Option<&str>) -> Result { let value = format!( "{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}", SessionGate::COOKIE, @@ -155,7 +192,7 @@ mod tests { let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") .await .unwrap(); - state.sessions = SessionGate::fixture(); + state.sessions = SessionGate::fixture(state.db.clone()); state.admin.token = Some("fixture-api-token".into()); let app = crate::api::router(state.clone()); let request = |method: &str, uri: &str, body: &'static str| { @@ -281,4 +318,58 @@ mod tests { assert!(!values.contains(secret)); } } + + #[tokio::test] + async fn me_reports_the_caller_and_rejects_anonymous() { + let dir = tempfile::tempdir().unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") + .await + .unwrap(); + state.sessions = SessionGate::fixture(state.db.clone()); + let app = crate::api::router(state); + let peer = || ConnectInfo("127.0.0.1:1234".parse::().unwrap()); + let anonymous = app + .clone() + .oneshot(Request::builder().uri("/api/v1/me").extension(peer()).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED); + let login = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/operator/login") + .extension(peer()) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(r#"{"password":"fixture-operator-password"}"#)) + .unwrap(), + ) + .await + .unwrap(); + let cookie = HeaderValue::from_str( + login.headers()[header::SET_COOKIE].to_str().unwrap().split(';').next().unwrap(), + ) + .unwrap(); + let me = app + .oneshot( + Request::builder() + .uri("/api/v1/me") + .extension(peer()) + .header(header::COOKIE, cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(me.status(), StatusCode::OK); + assert_eq!(me.headers()[header::CACHE_CONTROL], "no-store"); + let body: serde_json::Value = + serde_json::from_slice(&to_bytes(me.into_body(), 4096).await.unwrap()).unwrap(); + assert_eq!(body["id"], "emergency:fixture-operator"); + assert_eq!(body["kind"], "user"); + assert_eq!(body["auth_method"], "password"); + assert_eq!(body["capabilities"][0], "admin"); + assert!(!body.to_string().contains("csrf")); + } } diff --git a/crates/tessera-hub/src/auth.rs b/crates/tessera-hub/src/auth.rs index b05fd3c..bbae5ea 100644 --- a/crates/tessera-hub/src/auth.rs +++ b/crates/tessera-hub/src/auth.rs @@ -4,6 +4,8 @@ use uuid::Uuid; #[derive(Clone, Debug)] pub enum Principal { Emergency(String), + /// OIDC user, by stable `users.id` (never by a name supplied by the IdP). + Oidc(String), Service(&'static str), Outpost(Uuid), Anonymous, @@ -14,6 +16,7 @@ impl Principal { pub fn fields(&self) -> (String, &'static str, &'static str) { match self { Self::Emergency(name) => (format!("emergency:{name}"), "user", "password"), + Self::Oidc(id) => (format!("oidc:{id}"), "user", "oidc"), Self::Service(id) => (id.to_string(), "service", "api_token"), Self::Outpost(id) => (id.to_string(), "outpost", "outpost_token"), Self::Anonymous => ("anonymous".into(), "anonymous", "none"), diff --git a/crates/tessera-hub/src/db.rs b/crates/tessera-hub/src/db.rs index d4591a4..bcfb728 100644 --- a/crates/tessera-hub/src/db.rs +++ b/crates/tessera-hub/src/db.rs @@ -1,6 +1,8 @@ mod jobs; mod restore; mod audit; +pub mod sessions; +pub(crate) mod oidc_login; pub(crate) use restore::restore_target_mismatch; use anyhow::Result; @@ -104,6 +106,8 @@ impl Db { jobs::migrate(&conn)?; restore::migrate(&conn)?; audit::migrate(&conn)?; + sessions::migrate(&conn)?; + oidc_login::migrate(&conn)?; Ok(()) } diff --git a/crates/tessera-hub/src/db/oidc_login.rs b/crates/tessera-hub/src/db/oidc_login.rs new file mode 100644 index 0000000..81f6461 --- /dev/null +++ b/crates/tessera-hub/src/db/oidc_login.rs @@ -0,0 +1,99 @@ +//! One-time OIDC login transactions (state, nonce, PKCE verifier) bound to the +//! browser that started them. +use super::*; +use crate::db::sessions::session_digest; + +pub const TTL_SECS: i64 = 600; +/// `/login` is a public GET that inserts a row; bound the table. +const MAX_PENDING: i64 = 500; + +pub(super) fn migrate(conn: &Connection) -> Result<()> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS oidc_login ( + state_digest TEXT PRIMARY KEY, + browser_digest TEXT NOT NULL, + nonce TEXT NOT NULL, + pkce_verifier TEXT NOT NULL, + expires_at INTEGER NOT NULL + );", + )?; + Ok(()) +} + +impl Db { + /// Store a transaction. Returns false when too many are pending. + pub fn begin_oidc_login(&self, state: &str, browser: &str, nonce: &str, verifier: &str, now: i64) -> Result { + let conn = self.conn.lock().unwrap(); + conn.execute("DELETE FROM oidc_login WHERE expires_at <= ?1", params![now])?; + let pending: i64 = conn.query_row("SELECT COUNT(*) FROM oidc_login", [], |r| r.get(0))?; + if pending >= MAX_PENDING { + return Ok(false); + } + conn.execute( + "INSERT INTO oidc_login(state_digest,browser_digest,nonce,pkce_verifier,expires_at) VALUES (?1,?2,?3,?4,?5)", + params![session_digest(state), session_digest(browser), nonce, verifier, now + TTL_SECS], + )?; + Ok(true) + } + + /// Atomically consume the transaction for `state`. Any attempt burns it, + /// including one from a browser that does not hold the correlation cookie, + /// so a leaked `state` cannot be retried. Returns `(nonce, verifier)` only + /// for the right browser, before expiry, exactly once. + pub fn consume_oidc_login(&self, state: &str, browser: Option<&str>, now: i64) -> Result> { + let conn = self.conn.lock().unwrap(); + let row: Option<(String, String, String, i64)> = conn + .query_row( + "DELETE FROM oidc_login WHERE state_digest=?1 RETURNING browser_digest,nonce,pkce_verifier,expires_at", + params![session_digest(state)], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ) + .optional()?; + Ok(row.and_then(|(bound, nonce, verifier, expires)| { + (browser.is_some_and(|b| session_digest(b) == bound) && expires > now).then_some((nonce, verifier)) + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn db() -> (tempfile::TempDir, Db) { + let dir = tempfile::tempdir().unwrap(); + let db = Db::connect(&dir.path().join("t.db")).await.unwrap(); + db.migrate().await.unwrap(); + (dir, db) + } + + #[tokio::test] + async fn a_transaction_is_single_use_and_bound_to_its_browser() { + let (_dir, db) = db().await; + assert!(db.begin_oidc_login("s1", "b1", "n", "v", 100).unwrap()); + assert_eq!(db.consume_oidc_login("s1", Some("b1"), 101).unwrap(), Some(("n".into(), "v".into()))); + assert_eq!(db.consume_oidc_login("s1", Some("b1"), 102).unwrap(), None, "replay"); + db.begin_oidc_login("s2", "b2", "n", "v", 100).unwrap(); + assert_eq!(db.consume_oidc_login("s2", Some("other"), 101).unwrap(), None, "wrong browser"); + assert_eq!(db.consume_oidc_login("s2", Some("b2"), 102).unwrap(), None, "burned by the failed attempt"); + db.begin_oidc_login("s3", "b3", "n", "v", 100).unwrap(); + assert_eq!(db.consume_oidc_login("s3", None, 101).unwrap(), None, "no cookie"); + db.begin_oidc_login("s4", "b4", "n", "v", 100).unwrap(); + assert_eq!(db.consume_oidc_login("s4", Some("b4"), 100 + TTL_SECS).unwrap(), None, "expired"); + } + + #[tokio::test] + async fn only_digests_of_state_and_browser_are_keys_and_pending_rows_are_capped() { + let (_dir, db) = db().await; + db.begin_oidc_login("raw-state", "raw-browser", "n", "v", 1).unwrap(); + let (state, browser): (String, String) = db + .conn.lock().unwrap() + .query_row("SELECT state_digest,browser_digest FROM oidc_login", [], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap(); + assert!(!state.contains("raw-state") && !browser.contains("raw-browser")); + for i in 0..MAX_PENDING { + let _ = db.begin_oidc_login(&format!("s{i}"), "b", "n", "v", 1); + } + assert!(!db.begin_oidc_login("one-too-many", "b", "n", "v", 1).unwrap()); + assert!(db.begin_oidc_login("after-expiry", "b", "n", "v", 1 + TTL_SECS).unwrap()); + } +} diff --git a/crates/tessera-hub/src/db/sessions.rs b/crates/tessera-hub/src/db/sessions.rs new file mode 100644 index 0000000..3e5238f --- /dev/null +++ b/crates/tessera-hub/src/db/sessions.rs @@ -0,0 +1,281 @@ +//! Persistent users and browser sessions. +//! +//! Only a digest of the session ID is stored. Revocation is explicit (rows are +//! deleted in a transaction and the user's generation is bumped) because SQLite +//! foreign keys are not enabled on this connection. +use super::*; +use sha2::{Digest, Sha256}; + +pub const IDLE_SECS: i64 = 30 * 60; +pub const ABSOLUTE_SECS: i64 = 8 * 3600; +/// `last_seen` is only rewritten when it is this stale, to avoid a write per request. +const TOUCH_AFTER_SECS: i64 = 60; + +/// Digest used as the primary key; the raw session ID never reaches the database. +pub fn session_digest(id: &str) -> String { + hex::encode(Sha256::digest(format!("tessera-session-v1:{id}"))) +} + +/// CSRF token derived from the session ID with a different domain prefix, so it +/// can be shown to the page without being usable as the stored digest. +pub fn csrf_token(id: &str) -> String { + hex::encode(Sha256::digest(format!("tessera-csrf-v1:{id}"))) +} + +pub struct StoredSession { + pub user_id: String, + pub display_name: String, + pub auth_method: String, + pub credential_fp: Option, + pub admin: bool, + pub expires_at: i64, +} + +pub(super) fn migrate(conn: &Connection) -> Result<()> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + issuer TEXT NOT NULL, + subject TEXT NOT NULL, + display_name TEXT NOT NULL, + active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)), + generation INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + last_login_at INTEGER, + UNIQUE(issuer, subject) + ); + CREATE TABLE IF NOT EXISTS sessions ( + token_digest TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + generation INTEGER NOT NULL, + auth_method TEXT NOT NULL, + credential_fp TEXT, + auth_time INTEGER NOT NULL, + created_at INTEGER NOT NULL, + last_seen INTEGER NOT NULL, + expires_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS sessions_user ON sessions(user_id); + CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires_at);", + )?; + // Added after the first M2 build; default 0 keeps old rows without admin rights. + super::ensure_column(conn, "sessions", "admin", "INTEGER NOT NULL DEFAULT 0")?; + Ok(()) +} + +impl Db { + /// Find or create the user for a stable `(issuer, subject)` identity. + pub fn upsert_user(&self, issuer: &str, subject: &str, display_name: &str, now: i64) -> Result { + let conn = self.conn.lock().unwrap(); + conn.execute( + "INSERT INTO users(id,issuer,subject,display_name,created_at,last_login_at) + VALUES (?1,?2,?3,?4,?5,?5) + ON CONFLICT(issuer,subject) DO UPDATE SET display_name=excluded.display_name, last_login_at=excluded.last_login_at", + params![Uuid::new_v4().to_string(), issuer, subject, display_name, now], + )?; + Ok(conn.query_row( + "SELECT id FROM users WHERE issuer=?1 AND subject=?2", + params![issuer, subject], + |row| row.get(0), + )?) + } + + /// Create a session for an active user. Returns false when the user is + /// missing or inactive. Expired rows are purged opportunistically. + pub fn create_session( + &self, + id: &str, + user_id: &str, + auth_method: &str, + credential_fp: Option<&str>, + admin: bool, + now: i64, + ) -> Result { + let conn = self.conn.lock().unwrap(); + conn.execute("DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", params![now, IDLE_SECS])?; + let inserted = conn.execute( + "INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin) + SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7 FROM users WHERE id=?2 AND active=1", + params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin], + )?; + Ok(inserted == 1) + } + + /// Validate a session in one statement (user active, generation current, + /// absolute and idle deadlines), then slide the idle window. The touch is an + /// UPDATE only, so a stale write can never recreate a revoked row. + pub fn lookup_session(&self, id: &str, now: i64) -> Result> { + let digest = session_digest(id); + let conn = self.conn.lock().unwrap(); + let found: Option<(StoredSession, i64)> = conn + .query_row( + "SELECT s.user_id,u.display_name,s.auth_method,s.credential_fp,s.expires_at,s.last_seen,s.admin + FROM sessions s JOIN users u ON u.id=s.user_id + WHERE s.token_digest=?1 AND u.active=1 AND s.generation=u.generation + AND s.expires_at>?2 AND s.last_seen+?3>?2", + params![digest, now, IDLE_SECS], + |row| { + Ok(( + StoredSession { + user_id: row.get(0)?, + display_name: row.get(1)?, + auth_method: row.get(2)?, + credential_fp: row.get(3)?, + expires_at: row.get(4)?, + admin: row.get(6)?, + }, + row.get(5)?, + )) + }, + ) + .optional()?; + let Some((session, last_seen)) = found else { return Ok(None) }; + if now - last_seen >= TOUCH_AFTER_SECS { + conn.execute("UPDATE sessions SET last_seen=?2 WHERE token_digest=?1", params![digest, now])?; + } + Ok(Some(session)) + } + + pub fn revoke_session(&self, id: &str) -> Result<()> { + self.conn.lock().unwrap().execute("DELETE FROM sessions WHERE token_digest=?1", params![session_digest(id)])?; + Ok(()) + } + + /// Used by the per-user revoke endpoint planned for M5 (admin). + #[allow(dead_code)] + /// Invalidate every session of a user, including any created concurrently + /// from the previous generation. Returns the number of rows removed. + pub fn revoke_user_sessions(&self, user_id: &str) -> Result { + let mut conn = self.conn.lock().unwrap(); + let tx = conn.transaction()?; + tx.execute("UPDATE users SET generation=generation+1 WHERE id=?1", params![user_id])?; + let removed = tx.execute("DELETE FROM sessions WHERE user_id=?1", params![user_id])?; + tx.commit()?; + Ok(removed) + } + + #[cfg(test)] + pub fn expire_all_sessions(&self) { + self.conn.lock().unwrap().execute("UPDATE sessions SET expires_at=0", []).unwrap(); + } + + #[cfg(test)] + pub fn session_rows(&self) -> i64 { + self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0)).unwrap() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn db() -> (tempfile::TempDir, Db) { + let dir = tempfile::tempdir().unwrap(); + let db = Db::connect(&dir.path().join("t.db")).await.unwrap(); + db.migrate().await.unwrap(); + (dir, db) + } + + #[tokio::test] + async fn idle_and_absolute_deadlines_use_the_supplied_clock() { + let (_dir, db) = db().await; + let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap(); + assert!(db.create_session("a", &user, "password", Some("fp"), true, 1000).unwrap()); + assert!(db.lookup_session("a", 1000 + IDLE_SECS - 1).unwrap().is_some()); + // sliding: the touch above moved last_seen, so a request just inside the + // new idle window is still fine, one beyond it is not + assert!(db.lookup_session("a", 1000 + 2 * IDLE_SECS - 2).unwrap().is_some()); + assert!(db.lookup_session("a", 1000 + 3 * IDLE_SECS).unwrap().is_none()); + assert!(db.create_session("b", &user, "password", None, true, 5000).unwrap()); + let mut now = 5000; + while now + IDLE_SECS - 10 < 5000 + ABSOLUTE_SECS { + now += IDLE_SECS - 10; + assert!(db.lookup_session("b", now).unwrap().is_some(), "active at {now}"); + } + // keeps being used, yet the absolute deadline still ends it + assert!(db.lookup_session("b", 5000 + ABSOLUTE_SECS).unwrap().is_none()); + } + + #[tokio::test] + async fn only_a_digest_is_stored_and_csrf_is_not_the_key() { + let (_dir, db) = db().await; + let user = db.upsert_user("local:emergency", "ops", "ops", 1).unwrap(); + db.create_session("raw-session-id", &user, "password", None, true, 1).unwrap(); + let conn = db.conn.lock().unwrap(); + let key: String = conn.query_row("SELECT token_digest FROM sessions", [], |r| r.get(0)).unwrap(); + assert_ne!(key, "raw-session-id"); + assert_eq!(key, session_digest("raw-session-id")); + assert_ne!(key, csrf_token("raw-session-id")); + let stored: String = conn + .query_row("SELECT group_concat(token_digest||user_id||auth_method||coalesce(credential_fp,'')) FROM sessions", [], |r| r.get(0)) + .unwrap(); + assert!(!stored.contains("raw-session-id")); + } + + #[tokio::test] + async fn revoked_sessions_cannot_be_resurrected_by_a_late_touch() { + let (_dir, db) = db().await; + let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap(); + db.create_session("a", &user, "password", None, true, 1000).unwrap(); + db.revoke_session("a").unwrap(); + assert!(db.lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS).unwrap().is_none()); + assert_eq!(db.session_rows(), 0); + } + + #[tokio::test] + async fn per_user_revoke_ends_all_sessions_and_allows_a_new_login() { + let (_dir, db) = db().await; + let one = db.upsert_user("https://idp.example", "alice", "Alice", 10).unwrap(); + let two = db.upsert_user("https://idp.example", "bob", "Bob", 10).unwrap(); + for id in ["a1", "a2"] { + db.create_session(id, &one, "oidc", None, true, 10).unwrap(); + } + db.create_session("b1", &two, "oidc", None, true, 10).unwrap(); + assert_eq!(db.revoke_user_sessions(&one).unwrap(), 2); + assert!(db.lookup_session("a1", 11).unwrap().is_none()); + assert!(db.lookup_session("a2", 11).unwrap().is_none()); + assert!(db.lookup_session("b1", 11).unwrap().is_some()); + assert!(db.create_session("a3", &one, "oidc", None, true, 12).unwrap()); + assert!(db.lookup_session("a3", 13).unwrap().is_some()); + } + + #[tokio::test] + async fn inactive_users_have_no_valid_or_new_sessions() { + let (_dir, db) = db().await; + let user = db.upsert_user("https://idp.example", "carol", "Carol", 10).unwrap(); + db.create_session("c1", &user, "oidc", None, true, 10).unwrap(); + db.conn.lock().unwrap().execute("UPDATE users SET active=0 WHERE id=?1", params![user]).unwrap(); + assert!(db.lookup_session("c1", 11).unwrap().is_none()); + assert!(!db.create_session("c2", &user, "oidc", None, true, 11).unwrap()); + assert!(!db.create_session("c3", "no-such-user", "oidc", None, true, 11).unwrap()); + } + + #[tokio::test] + async fn issuer_and_subject_identify_the_user_not_the_display_name() { + let (_dir, db) = db().await; + let first = db.upsert_user("https://idp.example", "sub-1", "Sam", 1).unwrap(); + let again = db.upsert_user("https://idp.example", "sub-1", "Samuel", 2).unwrap(); + let other_subject = db.upsert_user("https://idp.example", "sub-2", "Sam", 3).unwrap(); + let other_issuer = db.upsert_user("https://other.example", "sub-1", "Sam", 4).unwrap(); + assert_eq!(first, again); + assert_ne!(first, other_subject); + assert_ne!(first, other_issuer); + } + + #[tokio::test] + async fn sessions_survive_reopening_the_database_but_expired_ones_do_not() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("t.db"); + { + let db = Db::connect(&path).await.unwrap(); + db.migrate().await.unwrap(); + let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap(); + db.create_session("live", &user, "password", Some("fp"), true, 1000).unwrap(); + db.create_session("old", &user, "password", Some("fp"), true, 1000).unwrap(); + } + let db = Db::connect(&path).await.unwrap(); + db.migrate().await.unwrap(); + assert!(db.lookup_session("live", 1000 + 60).unwrap().is_some()); + assert!(db.lookup_session("old", 1000 + ABSOLUTE_SECS + 1).unwrap().is_none()); + } +} diff --git a/crates/tessera-hub/src/main.rs b/crates/tessera-hub/src/main.rs index b8c165c..1b8915d 100644 --- a/crates/tessera-hub/src/main.rs +++ b/crates/tessera-hub/src/main.rs @@ -3,6 +3,7 @@ mod auth; mod api; mod db; mod mtls; +mod oidc; mod scheduler; mod state; mod upload; diff --git a/crates/tessera-hub/src/oidc.rs b/crates/tessera-hub/src/oidc.rs new file mode 100644 index 0000000..c6ce51a --- /dev/null +++ b/crates/tessera-hub/src/oidc.rs @@ -0,0 +1,466 @@ +//! OpenID Connect relying party: authorization code flow with PKCE. +//! +//! Protocol work (discovery, token exchange, ID-token signature, issuer, +//! audience, expiry and nonce checks) is done by the `openidconnect` crate. +//! This module owns configuration, key/metadata refresh policy and the mapping +//! from verified claims to a Tessera identity. Tokens never leave this module: +//! the caller only receives an [`Identity`]. +use anyhow::{bail, Context, Result}; +use openidconnect::core::{ + CoreAuthenticationFlow, CoreClient, CoreProviderMetadata, +}; +use openidconnect::reqwest; +use openidconnect::{ + AccessTokenHash, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EndpointMaybeSet, + EndpointNotSet, EndpointSet, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, + PkceCodeVerifier, RedirectUrl, Scope, TokenResponse, +}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::sync::{Mutex, RwLock}; + +pub const CALLBACK_PATH: &str = "/api/v1/auth/oidc/callback"; +/// How long discovery metadata and signing keys are trusted without a refresh. +const METADATA_TTL: Duration = Duration::from_secs(600); +/// Minimum gap between refresh attempts, so unknown `kid`s cannot hammer the IdP. +const REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(60); + +type Client = CoreClient< + EndpointSet, + EndpointNotSet, + EndpointNotSet, + EndpointNotSet, + EndpointMaybeSet, + EndpointMaybeSet, +>; + +#[derive(Clone)] +pub struct OidcConfig { + pub issuer: String, + pub client_id: String, + client_secret: String, + pub redirect_url: String, + pub admin_subjects: BTreeSet, + pub admin_groups: BTreeSet, + pub groups_claim: String, + pub ca_file: Option, +} + +impl OidcConfig { + /// Read `TESSERA_OIDC_*`. `Ok(None)` when no issuer is configured. + /// A plain-http issuer is only accepted for a loopback host while + /// `TESSERA_LOCAL_DEVELOPMENT` is on. + pub fn from_env(local_development: bool) -> Result> { + let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()); + let Some(issuer) = var("TESSERA_OIDC_ISSUER") else { return Ok(None) }; + let need = |name: &str| var(name).with_context(|| format!("{name} is required when TESSERA_OIDC_ISSUER is set")); + let list = |name: &str| -> BTreeSet { + var(name).map(|v| v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default() + }; + let config = Self { + issuer, + client_id: need("TESSERA_OIDC_CLIENT_ID")?, + client_secret: need("TESSERA_OIDC_CLIENT_SECRET")?, + redirect_url: need("TESSERA_OIDC_REDIRECT_URL")?, + admin_subjects: list("TESSERA_OIDC_ADMIN_SUBJECTS"), + admin_groups: list("TESSERA_OIDC_ADMIN_GROUPS"), + groups_claim: var("TESSERA_OIDC_GROUPS_CLAIM").unwrap_or_else(|| "groups".into()), + ca_file: var("TESSERA_OIDC_CA_FILE").map(PathBuf::from), + }; + config.validate(local_development)?; + Ok(Some(config)) + } + + pub fn validate(&self, allow_loopback_http: bool) -> Result<()> { + check_url("TESSERA_OIDC_ISSUER", &self.issuer, allow_loopback_http)?; + check_url("TESSERA_OIDC_REDIRECT_URL", &self.redirect_url, allow_loopback_http)?; + let redirect = url_parts(&self.redirect_url)?; + if redirect.path() != CALLBACK_PATH || redirect.query().is_some() || redirect.fragment().is_some() { + bail!("TESSERA_OIDC_REDIRECT_URL must end with exactly {CALLBACK_PATH}"); + } + if self.admin_subjects.is_empty() && self.admin_groups.is_empty() { + bail!("OIDC needs TESSERA_OIDC_ADMIN_SUBJECTS or TESSERA_OIDC_ADMIN_GROUPS; otherwise nobody could administer the hub"); + } + Ok(()) + } + + /// Test constructor; the secret stays private to this module. + #[cfg(test)] + pub fn new(issuer: &str, client_id: &str, client_secret: &str, redirect_url: &str) -> Self { + Self { + issuer: issuer.into(), + client_id: client_id.into(), + client_secret: client_secret.into(), + redirect_url: redirect_url.into(), + admin_subjects: BTreeSet::new(), + admin_groups: BTreeSet::new(), + groups_claim: "groups".into(), + ca_file: None, + } + } + + /// Identifies this configuration for session binding. It covers who may + /// administer, so removing an admin and restarting demotes their session. + /// The client secret is deliberately excluded: rotating it needs no logout. + pub fn fingerprint(&self) -> String { + let mut hash = Sha256::new(); + hash.update(b"tessera-oidc-v1"); + for part in [self.issuer.as_str(), &self.client_id, &self.groups_claim] { + hash.update([0]); + hash.update(part.as_bytes()); + } + for set in [&self.admin_subjects, &self.admin_groups] { + hash.update([1]); + for item in set.iter() { + hash.update([0]); + hash.update(item.as_bytes()); + } + } + hex::encode(hash.finalize()) + } + + /// Admin comes only from configuration matched against verified claims. + /// A missing or malformed group claim never grants anything. + pub fn is_admin(&self, identity: &Identity) -> bool { + self.admin_subjects.contains(&identity.subject) + || identity.groups.iter().any(|group| self.admin_groups.contains(group)) + } +} + +fn url_parts(value: &str) -> Result { + openidconnect::url::Url::parse(value).with_context(|| format!("invalid URL {value}")) +} + +fn check_url(name: &str, value: &str, allow_loopback_http: bool) -> Result<()> { + let url = url_parts(value).with_context(|| name.to_string())?; + match url.scheme() { + "https" => Ok(()), + "http" if allow_loopback_http + && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) => Ok(()), + _ => bail!("{name} must be an https:// URL (plain http is only accepted for loopback with TESSERA_LOCAL_DEVELOPMENT)"), + } +} + +/// A verified identity. Display name is an attribute only, never an identifier. +#[derive(Debug, Clone)] +pub struct Identity { + pub issuer: String, + pub subject: String, + pub display_name: String, + pub groups: Vec, +} + +#[derive(Debug)] +pub enum OidcError { + /// IdP could not be reached and nothing usable is cached. + Unavailable, + /// The IdP response failed a protocol check. + Rejected, +} + +struct Cached { + client: Arc, + fetched_at: Instant, +} + +pub struct OidcProvider { + pub config: OidcConfig, + http: reqwest::Client, + cache: RwLock>, + /// Serialises refreshes; never held while the cache lock is held. + refresh: Mutex>, + min_refresh: Duration, +} + +pub struct Begin { + pub url: String, + pub state: String, + pub nonce: String, + pub verifier: String, +} + +impl OidcProvider { + pub fn new(config: OidcConfig) -> Result { + let mut builder = reqwest::Client::builder() + // Following redirects would turn discovery/JWKS fetches into an SSRF primitive. + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(5)) + .timeout(Duration::from_secs(15)); + if let Some(path) = &config.ca_file { + let pem = std::fs::read(path).with_context(|| format!("read {}", path.display()))?; + builder = builder.add_root_certificate(reqwest::Certificate::from_pem(&pem).context("TESSERA_OIDC_CA_FILE")?); + } + Ok(Self { + http: builder.build().context("build OIDC HTTP client")?, + config, + cache: RwLock::new(None), + refresh: Mutex::new(None), + min_refresh: REFRESH_MIN_INTERVAL, + }) + } + + #[cfg(test)] + pub fn with_min_refresh(mut self, gap: Duration) -> Self { + self.min_refresh = gap; + self + } + + async fn discover(&self) -> Result { + let metadata = CoreProviderMetadata::discover_async(IssuerUrl::new(self.config.issuer.clone())?, &self.http).await?; + Ok(CoreClient::from_provider_metadata( + metadata, + ClientId::new(self.config.client_id.clone()), + Some(ClientSecret::new(self.config.client_secret.clone())), + ) + .set_redirect_uri(RedirectUrl::new(self.config.redirect_url.clone())?)) + } + + /// Cached client, refreshed when stale. On refresh failure a previously + /// fetched client keeps working (IdP outage), a missing one is `Unavailable`. + /// `force` re-fetches keys for an unknown `kid` but is rate limited. + async fn client(&self, force: bool) -> Result, OidcError> { + let current = { + let guard = self.cache.read().await; + guard.as_ref().map(|c| (c.client.clone(), c.fetched_at)) + }; + let fresh = |at: Instant| at.elapsed() < METADATA_TTL; + if let Some((client, at)) = ¤t { + if fresh(*at) && !force { + return Ok(client.clone()); + } + } + let mut last_attempt = self.refresh.lock().await; + // Someone else may have refreshed while we waited for the lock. + let cached = self.cache.read().await.as_ref().map(|c| (c.client.clone(), c.fetched_at)); + if let Some((client, at)) = &cached { + if fresh(*at) && !force { + return Ok(client.clone()); + } + } + // Without any cached client, retry sooner so recovery after an outage is quick. + let gap = if cached.is_some() { self.min_refresh } else { self.min_refresh.min(Duration::from_secs(5)) }; + if last_attempt.is_some_and(|t| t.elapsed() < gap) { + return cached.map(|(c, _)| c).ok_or(OidcError::Unavailable); + } + *last_attempt = Some(Instant::now()); + match self.discover().await { + Ok(client) => { + let client = Arc::new(client); + *self.cache.write().await = Some(Cached { client: client.clone(), fetched_at: Instant::now() }); + Ok(client) + } + Err(error) => { + tracing::warn!("OIDC discovery failed: {error:#}"); + current.map(|(c, _)| c).ok_or(OidcError::Unavailable) + } + } + } + + /// Build the authorization redirect. The caller stores `state`, `nonce` and + /// `verifier` as a one-time login transaction bound to the browser. + pub async fn begin(&self) -> Result { + let client = self.client(false).await?; + let (challenge, verifier) = PkceCodeChallenge::new_random_sha256(); + let (url, state, nonce) = client + .authorize_url(CoreAuthenticationFlow::AuthorizationCode, CsrfToken::new_random, Nonce::new_random) + .add_scope(Scope::new("profile".into())) + .set_pkce_challenge(challenge) + .url(); + Ok(Begin { + url: url.to_string(), + state: state.secret().clone(), + nonce: nonce.secret().clone(), + verifier: verifier.secret().clone(), + }) + } + + /// Exchange the code and verify the ID token. Details go to the log; the + /// caller only sees `Unavailable` or `Rejected`. + pub async fn finish(&self, code: &str, nonce: &str, verifier: &str) -> Result { + let client = self.client(false).await?; + let response = client + .exchange_code(AuthorizationCode::new(code.to_string())) + .map_err(|_| OidcError::Unavailable)? + .set_pkce_verifier(PkceCodeVerifier::new(verifier.to_string())) + .request_async(&self.http) + .await + .map_err(|error| { + tracing::warn!("OIDC token exchange failed: {error}"); + match error { + openidconnect::RequestTokenError::Request(_) => OidcError::Unavailable, + _ => OidcError::Rejected, + } + })?; + let id_token = response.id_token().ok_or_else(|| { + tracing::warn!("OIDC token response has no ID token"); + OidcError::Rejected + })?; + let nonce = Nonce::new(nonce.to_string()); + let mut client = client; + for attempt in 0..2 { + match verify(&client, id_token, response.access_token(), &nonce, &self.config.groups_claim) { + Ok(identity) => return Ok(identity), + // Keys may have rotated since the last fetch: refresh once and retry. + Err(Verify::Signature) if attempt == 0 => client = self.client(true).await?, + Err(_) => break, + } + } + Err(OidcError::Rejected) + } +} + +enum Verify { + Signature, + Other, +} + +/// All checks on one ID token: signature, issuer, audience, expiry and nonce +/// (library), access-token hash, then mapping to an owned [`Identity`]. +fn verify( + client: &Client, + id_token: &openidconnect::core::CoreIdToken, + access_token: &openidconnect::AccessToken, + nonce: &Nonce, + groups_claim: &str, +) -> Result { + let verifier = client.id_token_verifier(); + let claims = id_token.claims(&verifier, nonce).map_err(|error| { + tracing::warn!("OIDC ID token rejected: {error}"); + if matches!(error, openidconnect::ClaimsVerificationError::SignatureVerification(_)) { + Verify::Signature + } else { + Verify::Other + } + })?; + if let Some(expected) = claims.access_token_hash() { + let actual = id_token + .signing_alg() + .ok() + .and_then(|alg| id_token.signing_key(&verifier).ok().map(|key| (alg, key))) + .and_then(|(alg, key)| AccessTokenHash::from_token(access_token, alg, key).ok()); + if actual.as_ref() != Some(expected) { + tracing::warn!("OIDC access token hash mismatch"); + return Err(Verify::Other); + } + } + let subject = claims.subject().as_str().to_string(); + if subject.is_empty() || subject.len() > 255 { + tracing::warn!("OIDC ID token has an unusable subject"); + return Err(Verify::Other); + } + let display_name = claims + .preferred_username() + .map(|n| n.as_str().to_string()) + .or_else(|| claims.name().and_then(|n| n.get(None)).map(|n| n.as_str().to_string())) + .unwrap_or_else(|| subject.clone()) + .chars() + .take(128) + .collect(); + // The signature was verified by `claims()` above, so reading one more + // claim from the same token is safe. Missing or malformed means no groups. + let groups = groups_from_token(&id_token.to_string(), groups_claim); + Ok(Identity { issuer: claims.issuer().as_str().to_string(), subject, display_name, groups }) +} + +fn groups_from_token(jwt: &str, claim: &str) -> Vec { + use base64::Engine; + let Some(payload) = jwt.split('.').nth(1) else { return vec![] }; + let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload) else { return vec![] }; + let Ok(value) = serde_json::from_slice::(&bytes) else { return vec![] }; + match value.get(claim) { + Some(serde_json::Value::String(one)) => vec![one.clone()], + Some(serde_json::Value::Array(items)) => { + items.iter().filter_map(|item| item.as_str().map(str::to_string)).collect() + } + _ => vec![], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config() -> OidcConfig { + let mut config = OidcConfig::new("https://idp.example/realm", "tessera", "secret", "https://hub.example/api/v1/auth/oidc/callback"); + config.admin_subjects.insert("admin-sub".into()); + config + } + + #[test] + fn http_issuers_are_rejected_unless_loopback_in_local_development() { + let mut c = config(); + assert!(c.validate(false).is_ok()); + c.issuer = "http://idp.example".into(); + assert!(c.validate(false).is_err()); + assert!(c.validate(true).is_err(), "non-loopback http stays rejected"); + c.issuer = "http://localhost:8080/realms/t".into(); + assert!(c.validate(false).is_err()); + assert!(c.validate(true).is_ok(), "loopback http issuer in local development"); + c.redirect_url = "http://hub.example/api/v1/auth/oidc/callback".into(); + assert!(c.validate(true).is_err(), "non-loopback http redirect stays rejected"); + c.redirect_url = "http://localhost:8787/api/v1/auth/oidc/callback".into(); + assert!(c.validate(true).is_ok()); + assert!(c.validate(false).is_err()); + } + + #[test] + fn redirect_url_must_be_the_exact_callback_and_an_admin_mapping_is_required() { + let mut c = config(); + c.redirect_url = "https://hub.example/other".into(); + assert!(c.validate(false).is_err()); + c.redirect_url = "https://hub.example/api/v1/auth/oidc/callback?x=1".into(); + assert!(c.validate(false).is_err()); + let mut c = config(); + c.admin_subjects.clear(); + assert!(c.validate(false).is_err(), "no way to administer"); + c.admin_groups.insert("tessera-admins".into()); + assert!(c.validate(false).is_ok()); + } + + #[test] + fn admin_mapping_uses_subject_or_verified_group_only() { + let mut c = config(); + c.admin_groups.insert("tessera-admins".into()); + let id = |sub: &str, groups: &[&str]| Identity { + issuer: "i".into(), + subject: sub.into(), + display_name: "operator".into(), + groups: groups.iter().map(|g| g.to_string()).collect(), + }; + assert!(c.is_admin(&id("admin-sub", &[]))); + assert!(c.is_admin(&id("someone", &["tessera-admins"]))); + assert!(!c.is_admin(&id("someone", &["other"]))); + assert!(!c.is_admin(&id("someone", &[])), "missing groups claim grants nothing"); + assert!(!c.is_admin(&id("operator", &[])), "display name is not an identifier"); + } + + #[test] + fn fingerprint_changes_with_the_admin_mapping_but_not_the_client_secret() { + let base = config(); + let mut rotated = config(); + rotated.client_secret = "new-secret".into(); + assert_eq!(base.fingerprint(), rotated.fingerprint()); + let mut demoted = config(); + demoted.admin_subjects.clear(); + demoted.admin_subjects.insert("someone-else".into()); + assert_ne!(base.fingerprint(), demoted.fingerprint()); + let mut renamed = config(); + renamed.groups_claim = "roles".into(); + assert_ne!(base.fingerprint(), renamed.fingerprint()); + } + + #[test] + fn groups_accept_a_string_or_array_and_ignore_anything_else() { + use base64::Engine; + let jwt = |json: &str| format!("h.{}.s", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json)); + assert_eq!(groups_from_token(&jwt(r#"{"groups":["a","b"]}"#), "groups"), ["a", "b"]); + assert_eq!(groups_from_token(&jwt(r#"{"groups":"solo"}"#), "groups"), ["solo"]); + assert!(groups_from_token(&jwt(r#"{"groups":{"a":1}}"#), "groups").is_empty()); + assert!(groups_from_token(&jwt(r#"{"groups":[1,null]}"#), "groups").is_empty()); + assert!(groups_from_token(&jwt(r#"{"other":["a"]}"#), "groups").is_empty()); + assert!(groups_from_token("not-a-jwt", "groups").is_empty()); + } +} diff --git a/crates/tessera-hub/src/state.rs b/crates/tessera-hub/src/state.rs index d70361c..4603e58 100644 --- a/crates/tessera-hub/src/state.rs +++ b/crates/tessera-hub/src/state.rs @@ -40,6 +40,7 @@ pub struct HubState { pub active_orbits: Arc>>, pub admin: AdminGate, pub sessions: SessionGate, + pub oidc: Option>, pub wormhole_mtls: bool, /// Token uploads are accepted on this listener. Plain HTTP turns this off /// when wormhole mTLS is required, so those routes are not a bypass. @@ -61,15 +62,18 @@ impl HubState { Vault::init(&vault_path, vault_pass)? }; + let admin = AdminGate::from_env()?; + let oidc_config = crate::oidc::OidcConfig::from_env(admin.local_development)?; Ok(Self { - db, + db: db.clone(), data_dir, offsite: None, vault: Arc::new(RwLock::new(vault)), reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())), active_orbits: Arc::new(Mutex::new(HashSet::new())), - admin: AdminGate::from_env()?, - sessions: SessionGate::from_env()?, + admin, + sessions: SessionGate::from_env(db.clone(), oidc_config.as_ref().map(|c| c.fingerprint()))?, + oidc: oidc_config.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new)).transpose()?, wormhole_mtls: false, accept_plain_upload: true, }) diff --git a/deny.toml b/deny.toml index d3031d1..4f20e76 100644 --- a/deny.toml +++ b/deny.toml @@ -6,6 +6,9 @@ all-features = false version = 2 # Unmaintained warnings are tracked, not ignored silently; see tasks/auth-plan.md (M1). unmaintained = "workspace" +ignore = [ + { id = "RUSTSEC-2023-0071", reason = "Marvin attack concerns RSA private-key operations. Tessera only verifies ID-token signatures with public keys (openidconnect core/crypto.rs); runtime code never calls an RSA private-key operation; only test fixtures sign tokens with throwaway keys. No patched rsa 0.9 exists. Revisit when openidconnect moves to rsa >= 0.10." }, +] [licenses] version = 2 @@ -13,6 +16,7 @@ allow = [ "MIT", "MIT-0", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "ISC", "BSD-2-Clause", "BSD-3-Clause", "Unicode-3.0", "Zlib", "CC0-1.0", "BSL-1.0", "Unlicense", + "CDLA-Permissive-2.0", # webpki-roots: Mozilla CA data "AGPL-3.0-or-later", # Tessera's own crates ] confidence-threshold = 0.9 diff --git a/docs/DATABASE-CAPTURE.md b/docs/DATABASE-CAPTURE.md index d0d5047..c56bcf7 100644 --- a/docs/DATABASE-CAPTURE.md +++ b/docs/DATABASE-CAPTURE.md @@ -173,3 +173,43 @@ tessera legacy-import --bucket legacy-bucket --prefix billing/ --orbit-id ORBIT_ Repeat without `--inventory-only` to import. The JSON report includes the source key, ETag, size, last-modified timestamp, and Tessera snapshot ID. Conditional reads reject changed objects between listing and download. A persistent receipt prevents reimport after local retention and GC. [AWS S3 CLI inventory](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects-v2.html), [AWS S3 conditional download](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html). Add `--history /path/to/consistent-history.sqlite` to archive a consistent SQLite export of the old job history. Save the reported history ID and retrieve it with `tessera legacy-history HISTORY_UUID history.sqlite` on the vault host. Inspect the retrieved copy read-only. Legacy SQL archives retain their original bytes and can be applied to a temporary database with the matching engine client. + +## OIDC sign-in (single issuer) + +Set `TESSERA_OIDC_ISSUER` to enable browser SSO (authorization code + PKCE S256, +Tessera is a confidential client). When it is set, these are also required: + +| Variable | Meaning | +| --- | --- | +| `TESSERA_OIDC_CLIENT_ID`, `TESSERA_OIDC_CLIENT_SECRET` | Client registered at the IdP. The secret is only read from the environment and never logged. | +| `TESSERA_OIDC_REDIRECT_URL` | Public, static callback, exactly `https:///api/v1/auth/oidc/callback`. It is never derived from `Host` or `X-Forwarded-*`. | +| `TESSERA_OIDC_ADMIN_SUBJECTS` | Comma-separated `sub` values that may administer the hub. | +| `TESSERA_OIDC_ADMIN_GROUPS` | Comma-separated group names that may administer the hub. | +| `TESSERA_OIDC_GROUPS_CLAIM` | ID-token claim that carries groups (default `groups`; string or array of strings). | +| `TESSERA_OIDC_CA_FILE` | Optional PEM bundle for an IdP behind a private CA. | + +At least one admin subject or group is mandatory, otherwise startup fails: with +no mapping nobody could administer the hub. Issuer and redirect URL must be +`https://`; plain http is accepted only for a loopback host together with +`TESSERA_LOCAL_DEVELOPMENT=true`. + +Behaviour to know about: + +- Users are identified by `(issuer, subject)`, never by email or display name. + There is no auto-link by email and no first-user-becomes-admin. +- A user who signs in but matches no admin mapping gets a "No access yet" page and + `403` on every management API. They can still call `GET /api/v1/me` and sign out. +- Group membership is read at sign-in. A change at the IdP applies at the next + sign-in, at most 8 hours later (absolute session limit); there is no back-channel + logout or SCIM yet. +- Changing the issuer, client ID, admin subjects/groups or groups claim ends every + existing OIDC session. Rotating the client secret does not. +- Sign-out ends the Tessera session only. The IdP session stays, so the next + "Sign in with SSO" may not ask for a password. RP-initiated logout is not implemented. +- ID tokens must be signed with RS256 (the library default). An IdP that signs + with another algorithm is rejected until that is made configurable. +- The emergency operator password keeps working beside SSO and is shown under + "Emergency operator sign-in" when SSO is on. +- No IdP token is stored or sent to the browser; the browser only receives the + Tessera session cookie. + diff --git a/tasks/auth-endpoint-contract.md b/tasks/auth-endpoint-contract.md index cccf76f..084d8c8 100644 --- a/tasks/auth-endpoint-contract.md +++ b/tasks/auth-endpoint-contract.md @@ -17,6 +17,9 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin. | /api-doc/openapi.json | GET | public | — | — | schema tanpa config/secret | | /api/v1/operator/session | GET | public | — | current session | status, actor, CSRF sesi sendiri; no-store | | /api/v1/operator/session | DELETE | human | session.self | current session | tidak ada; CSRF wajib | +| /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store | +| /api/v1/auth/oidc/login | GET | public | — | OIDC configured | redirect to the IdP; sets one-time Lax correlation cookie; 404 when OIDC is off | +| /api/v1/auth/oidc/callback | GET | public | — | login transaction + correlation cookie | redirect to `/`; session cookie only on success, fixed error code otherwise; no tokens | | /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store | | /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter | | /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin | diff --git a/tasks/auth-plan.md b/tasks/auth-plan.md index f72354e..78bf637 100644 --- a/tasks/auth-plan.md +++ b/tasks/auth-plan.md @@ -24,25 +24,30 @@ Bukti: `cargo test --workspace` hijau (jumlah tes sama dengan sebelum upgrade), Belum terbukti: build image Docker `rust:1.89`, dan tes Restic ignored. Belum ada CI di repo, jadi gate ini baru jalan manual (`cargo audit`, `cargo deny check`). Sisa catatan: `rsa` 0.9 (RUSTSEC-2023-0071) baru muncul saat `openidconnect` masuk di M3; dikecualikan dengan alasan reachability di sana, bukan sekarang. -## M2 — User dan sesi persisten +## M2 — User dan sesi persisten (selesai di working tree, belum di-commit, 14 November 2026) Hasil: identitas per orang dan sesi yang bertahan setelah restart. -- Tabel `users` (UNIQUE issuer+subject, status aktif) dan `sessions` (digest ID, user, CSRF, created/last_seen/expires, auth_time, auth method, revocation generation). -- Store sesi sendiri di rusqlite, bukan `tower-sessions`: UPDATE-only save, key digest, idle 30 menit dan absolute 8 jam, revoke per sesi dan per user, rotasi ID saat login. Alasan: adapter yang aman sudah meniru hampir semua logika library, dan library membawa `axum-core` ganda. -- Ganti `SessionGate` in-memory. Akun darurat (password) tetap login lewat jalur yang sama sebagai principal `Emergency`. -- `GET /me` mengembalikan identitas dan capabilities aman. -Selesai bila: tes fake clock (idle/absolute), session fixation, CSRF, revoke saat request konkuren tidak menghidupkan sesi lagi, restart mempertahankan sesi valid dan menolak yang kedaluwarsa. +- Tabel `users` (UNIQUE issuer+subject, `active`, `generation`) dan `sessions` (digest SHA-256 dari ID, user, generation, auth method, credential fingerprint, auth_time, last_seen, expires_at) di `db/sessions.rs`. Store sendiri di rusqlite, bukan `tower-sessions`. +- Validasi sesi satu statement: user aktif, generation cocok, absolute 8 jam, idle 30 menit; geser idle lewat UPDATE-only (tidak bisa menghidupkan baris yang sudah dicabut). Revoke per user menaikkan generation dan menghapus baris dalam satu transaksi. Foreign key SQLite tidak aktif di koneksi ini, jadi tidak diandalkan. +- Akun darurat adalah baris user dengan issuer `local:emergency` (bukan URL, tidak bisa ditabrak issuer OIDC). Sesi password terikat ke fingerprint hash operator: hash dilepas atau diganti saat restart membuat cookie lama mati. Ini menjaga perilaku lama (restart memutus sesi) sekarang sesi persisten. +- CSRF diturunkan dari ID sesi dengan prefix berbeda dari digest penyimpanan, jadi tidak perlu disimpan dan tidak bisa dipakai sebagai kunci. +- `authorize_operator` melakukan satu lookup sesi per request (sebelumnya dua). +- `GET /api/v1/me` (identitas, kind, auth method, nama, capabilities; no-store) masuk kontrak endpoint. `GET /operator/session` kini juga mengembalikan `expires_at`. +Bukti: `cargo test --workspace` hijau (hub 33 tes, naik dari 21: deadline dengan clock injeksi, hanya digest tersimpan, touch setelah revoke, revoke per user lalu login ulang, user nonaktif, restart/reopen DB, hash diganti/dilepas, fixation, `/me`); `cargo audit` 0 vulnerability, `cargo deny` ok. Proses nyata: login, restart dengan hash sama → 200, hash diganti → 401, hash dilepas → cookie tidak dianggap sesi, hash asli lagi → sesi pulih. +Belum ada: endpoint HTTP revoke per user dan nonaktifkan user (fungsi store `revoke_user_sessions` sudah ada dan dites; endpoint admin menunggu M5), pembersihan sesi kedaluwarsa hanya terjadi saat ada login baru, dan limiter login masih in-memory (M4). -## M3 — Login OIDC +## M3 — Login OIDC (selesai di working tree, belum di-commit, 14 November 2026) -Hasil: SSO berfungsi; ini inti permintaan. -- `openidconnect` 4.x, confidential client, Authorization Code + PKCE S256, redirect URI statis dari config, redirect HTTP dimatikan untuk discovery/token/JWKS. -- Transaksi login singkat, sekali pakai, terikat cookie korelasi SameSite=Lax terpisah. Validasi state, nonce, iss, aud, exp, alg allowlist; JWKS di-cache dengan refresh terbatas. -- User dibuat/dicocokkan lewat (issuer, subject), tanpa auto-link email, tanpa auto-admin. User baru tanpa grant mendapat halaman "belum punya akses". -- Admin ditentukan config eksplisit: daftar subject atau satu claim grup. Claim grup hilang tidak menambah hak. -- Endpoint: `/auth/oidc/login`, `/auth/oidc/callback`, logout lokal (+ RP-initiated logout bila IdP mendukung). -- UI: tombol SSO di `OperatorGate`, login darurat dipisah, halaman tanpa akses. -Selesai bila: tes wiremock untuk signature/alg/iss/aud/nonce/state salah, replay callback, token kedaluwarsa, JWKS rotasi dan outage; satu lari nyata dengan Keycloak fixture lewat browser (cookie lintas situs, logout, user tanpa grant). +Hasil: SSO berfungsi sebagai login utama; akun darurat tetap ada. +- `openidconnect` 4.1 (reqwest + rustls), confidential client, code + PKCE S256, redirect URI statis, redirect HTTP dimatikan, timeout connect 5 detik dan total 15 detik. Konfigurasi `TESSERA_OIDC_*` divalidasi saat startup (https wajib, http hanya loopback + local development, mapping admin wajib). Dokumentasi ada di `docs/DATABASE-CAPTURE.md`. +- Transaksi login satu kali pakai (digest state dan cookie korelasi SameSite=Lax terpisah, TTL 10 menit, maksimal 500 baris). Percobaan apa pun, termasuk dari browser tanpa cookie, menghanguskan transaksi. +- Verifikasi ID token oleh library: signature RS256, iss, aud (audiens lain ditolak), azp, exp, nonce, access-token hash. Metadata dan JWKS di-cache 10 menit; saat IdP mati cache lama tetap dipakai; kegagalan signature memicu satu refresh (dibatasi 60 detik) lalu coba ulang. +- Identitas (issuer, subject) tanpa auto-link email. Admin hanya dari config (subject atau grup di claim terverifikasi; claim hilang atau salah bentuk tidak memberi apa pun). User tanpa grant mendapat sesi tapi `403` di semua API manajemen; `/me`, status sesi, dan logout tetap jalan. Principal audit `oidc:`, tidak pernah dari nama IdP. +- Sesi OIDC terikat ke fingerprint config (issuer, client, mapping admin): mengubah mapping atau mematikan OIDC mengakhiri sesi. +- UI: tombol "Sign in with SSO", form password darurat dipisah, halaman "No access yet", pesan error dari kode tetap (`auth_error`). +Bukti: `cargo test --workspace` hijau (hub 51 tes, stabil 5/5 run). Tes end-to-end dengan IdP palsu dan token yang ditandatangani kunci RSA uji: admin lewat subject dan grup, user tanpa grant, claim grup rusak, email sama subject beda, nonce/issuer/audience/azp/expired/signature penyerang/alg none/HS256 salah, replay/cookie salah/state palsu/transaksi kedaluwarsa, rotasi JWKS dan pembatasan refresh, IdP mati (cold dan warm), OIDC nonaktif → 404. `cargo audit` hanya warning `proc-macro-error`; `rsa` dikecualikan dengan alasan tertulis (`deny.toml`, `.cargo/audit.toml`). Rehearsal nyata: Keycloak 26.1 di Docker + hub nyata + browser: login Alice (grup admin) → UI terbuka, `/me` oidc admin; Bob → "No access yet", `/orbits` 403; logout lokal; pesan error callback palsu. Cookie `__Host-` Secure bekerja di `http://localhost`. DB dan log tidak memuat token, secret, atau password. +Belum ada / batas: RP-initiated logout dan back-channel logout (logout hanya mengakhiri sesi Tessera, sesi IdP tetap), re-auth dan `max_age` untuk akses sensitif, ES256/PS256 (hanya RS256), limiter pada `/login` dan `/callback` (M4; yang ada hanya batas 500 transaksi pending), revokasi perubahan grup IdP hanya saat sign-in berikutnya (maksimal 8 jam), uji dengan IdP organisasi target, uji logout/MFA di IdP target. +Catatan operasional: image Keycloak 26.1 tertinggal di Docker lokal (~500 MB), container sudah dihapus. ## M4 — Hardening kredensial diff --git a/web/src/api.ts b/web/src/api.ts index ae086c3..e166f4e 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -52,9 +52,11 @@ export type CreateOrbitInput = { export type OperatorSession = { login_enabled: boolean; + oidc_enabled: boolean; authorized: boolean; actor: string | null; csrf: string | null; + expires_at: number | null; }; let csrf: string | null = null; diff --git a/web/src/components/operator/OperatorGate.tsx b/web/src/components/operator/OperatorGate.tsx index fc88c2b..96a7648 100644 --- a/web/src/components/operator/OperatorGate.tsx +++ b/web/src/components/operator/OperatorGate.tsx @@ -1,8 +1,25 @@ -import { useState, type FormEvent, type ReactNode } from "react"; +import { useEffect, useState, type FormEvent, type ReactNode } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { fetchOperatorSession, loginOperator, logoutOperator } from "../../api"; import { Button } from "../ui/Button"; +const SSO_ERRORS: Record = { + invalid_state: "That sign-in expired or was started in another browser. Please try again.", + denied: "The identity provider declined the sign-in.", + unavailable: "The identity provider is unreachable. Try again shortly.", + disabled: "This account is disabled.", + failed: "Sign-in could not be completed. Ask an administrator if it keeps happening.", +}; + +/** Read the fixed error code the SSO callback leaves in the URL, then remove it. */ +function useSsoError() { + const [code] = useState(() => new URLSearchParams(window.location.search).get("auth_error")); + useEffect(() => { + if (code) window.history.replaceState(null, "", window.location.pathname); + }, [code]); + return code ? SSO_ERRORS[code] ?? SSO_ERRORS.failed : undefined; +} + export function OperatorGate({ children, }: { @@ -17,6 +34,7 @@ export function OperatorGate({ }); const [pending, setPending] = useState(false); const [error, setError] = useState(); + const ssoError = useSsoError(); async function submit(event: FormEvent) { event.preventDefault(); @@ -37,44 +55,70 @@ export function OperatorGate({ } } + async function signOut() { + if (!session.isSuccess) return; + await queryClient.cancelQueries({ queryKey: ["operator-session"] }); + await logoutOperator(); + queryClient.setQueryData(["operator-session"], { + login_enabled: session.data.login_enabled, oidc_enabled: session.data.oidc_enabled, + authorized: false, actor: null, csrf: null, expires_at: null, + }); + queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" }); + } + if (session.isSuccess && session.data.authorized) { const actor = session.data.actor ?? undefined; - return children({ - actor, - onLogout: actor ? async () => { - await queryClient.cancelQueries({ queryKey: ["operator-session"] }); - await logoutOperator(); - queryClient.setQueryData(["operator-session"], { - login_enabled: true, authorized: false, actor: null, csrf: null, - }); - queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" }); - } : undefined, - }); + return children({ actor, onLogout: actor ? signOut : undefined }); } return (

Tessera / Backup control

-

Operator sign-in

+

Sign in

{session.isPending ?

Connecting to the hub…

: session.isError ? (

Could not reach the hub.

- ) : session.data.login_enabled ? ( -
- - {error &&

{error}

} - -
+ ) : session.data.actor ? ( +
+

No access yet

+

+ You are signed in as {session.data.actor}, but this account has not been granted access to Tessera. + Ask an administrator to add you, then sign in again. +

+ +
+ ) : session.data.login_enabled || session.data.oidc_enabled ? ( +
+ {ssoError &&

{ssoError}

} + {session.data.oidc_enabled && ( + + Sign in with SSO + + )} + {session.data.login_enabled && ( +
+ {session.data.oidc_enabled && ( + Emergency operator sign-in + )} +
+ + {error &&

{error}

} + +
+
+ )} +
) :

Browser sign-in is disabled on this hub.

}