From 8170aefb3dd555fe2591424cfa9fda8fd52caf7c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 15:32:16 -0600 Subject: [PATCH] feat(idp-provider): federated doors + runtime identity linking Implements the door machinery for #13411 (GitHub), #13412 (Google), #13414 (Microsoft) and the linking model of #13415 on the minimal provider (#13409, closed): - GET /door/{name}/start re-validates the RP authorize request with the same checks as /authorize, parks it server-side under a single-use state handle (300 s), and redirects upstream. The callback consumes the handle, exchanges the upstream code, and verifies the upstream identity: OIDC doors check the ID token against the upstream JWKS (iss/aud/exp/nonce, PKCE sent upstream); the GitHub door takes the numeric user id from the user fetch. - The deny-by-default allowlist is enforced in the provider before any link or code exists; success mints one of our own codes into the shared store, so a door login's tokens carry the same account sub and #1253 role claims as a local login's. - Identity store (#13415): SQLite link state seeded from the provider config, append-only event history (rows never hard-deleted), first-allowlisted-login linking written to the history and the audit record, operator link/unlink/links CLI. An unlinked identity is denied at its door while the account stays reachable via the others. - Door client secrets are named env vars only (the launcher fills them from the vault by name); a door without its secret stays disabled and denies at start with an audit record. Tests: 7 new door tests over real HTTP against mock OIDC/GitHub upstreams (full loops, denial/audit, unlink behaviour, state replay, disabled door); 15/15 crate tests pass on the laptop. The live per-door sign-in proofs still need the upstream app registrations recorded on each issue; the issues stay open for those. --- pkgs/idp-provider/Cargo.lock | 812 +++++++++++++++++++++++++- pkgs/idp-provider/Cargo.toml | 1 + pkgs/idp-provider/README.md | 54 ++ pkgs/idp-provider/config.example.json | 2 +- pkgs/idp-provider/examples/test-rp.rs | 44 +- pkgs/idp-provider/src/doors.rs | 514 ++++++++++++++++ pkgs/idp-provider/src/flow.rs | 332 ++++++++--- pkgs/idp-provider/src/identities.rs | 365 ++++++++++++ pkgs/idp-provider/src/lib.rs | 52 ++ pkgs/idp-provider/src/main.rs | 137 ++++- pkgs/idp-provider/src/registry.rs | 83 ++- pkgs/idp-provider/src/upstream.rs | 303 ++++++++++ pkgs/idp-provider/tests/doors.rs | 692 ++++++++++++++++++++++ pkgs/idp-provider/tests/endpoints.rs | 1 + pkgs/idp-provider/tests/flow.rs | 8 + 15 files changed, 3264 insertions(+), 136 deletions(-) create mode 100644 pkgs/idp-provider/src/doors.rs create mode 100644 pkgs/idp-provider/src/identities.rs create mode 100644 pkgs/idp-provider/src/upstream.rs create mode 100644 pkgs/idp-provider/tests/doors.rs diff --git a/pkgs/idp-provider/Cargo.lock b/pkgs/idp-provider/Cargo.lock index cc65b52f1d..1137af331f 100644 --- a/pkgs/idp-provider/Cargo.lock +++ b/pkgs/idp-provider/Cargo.lock @@ -10,7 +10,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] @@ -83,6 +83,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -113,6 +119,12 @@ dependencies = [ "generic-array", ] +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + [[package]] name = "bytes" version = "1.12.2" @@ -144,6 +156,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 = "cipher" version = "0.4.4" @@ -169,6 +198,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 = "crypto-common" version = "0.1.7" @@ -215,6 +253,17 @@ dependencies = [ "subtle", ] +[[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 = "errno" version = "0.3.15" @@ -222,7 +271,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -264,6 +313,15 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -305,8 +363,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +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]] @@ -398,6 +472,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]] @@ -406,13 +497,126 @@ 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]] +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 = "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]] @@ -420,11 +624,12 @@ name = "idp-provider" version = "0.1.0" dependencies = [ "axum", - "base64", + "base64 0.22.1", "der", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", + "reqwest", "rsa", "rusqlite", "serde", @@ -445,12 +650,29 @@ dependencies = [ "generic-array", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -483,6 +705,12 @@ dependencies = [ "vcpkg", ] +[[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" @@ -498,6 +726,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 = "matchit" version = "0.8.4" @@ -524,7 +758,7 @@ checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -538,7 +772,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand", + "rand 0.8.8", "smallvec", "zeroize", ] @@ -666,7 +900,7 @@ checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ "der", "pkcs5", - "rand_core", + "rand_core 0.6.4", "spki", ] @@ -676,6 +910,15 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -694,6 +937,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", + "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.4", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "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" @@ -703,6 +1002,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "rand" version = "0.8.8" @@ -710,7 +1015,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "rand_chacha", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -720,7 +1036,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -729,7 +1045,22 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom", + "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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", ] [[package]] @@ -741,6 +1072,58 @@ dependencies = [ "bitflags", ] +[[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 = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rsa" version = "0.9.10" @@ -754,7 +1137,7 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", "signature", "spki", "subtle", @@ -785,6 +1168,53 @@ 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 = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "ryu" version = "1.0.23" @@ -890,7 +1320,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -917,7 +1347,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -939,7 +1369,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -968,6 +1398,12 @@ 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 = "subtle" version = "2.6.1" @@ -1001,6 +1437,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 = "thiserror" @@ -1022,6 +1472,22 @@ dependencies = [ "syn 3.0.10", ] +[[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 = "tls_codec" version = "0.4.2" @@ -1057,7 +1523,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1071,6 +1537,16 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tower" version = "0.5.3" @@ -1087,6 +1563,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -1119,6 +1613,12 @@ dependencies = [ "once_cell", ] +[[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" @@ -1131,6 +1631,39 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[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 = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "vcpkg" version = "0.2.15" @@ -1143,18 +1676,120 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +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 = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -1164,6 +1799,76 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "x509-cert" version = "0.2.5" @@ -1176,6 +1881,29 @@ dependencies = [ "tls_codec", ] +[[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.64" @@ -1196,6 +1924,27 @@ 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.2" @@ -1216,6 +1965,39 @@ dependencies = [ "syn 2.0.119", ] +[[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/pkgs/idp-provider/Cargo.toml b/pkgs/idp-provider/Cargo.toml index 134bcdbf1d..de7d064c91 100644 --- a/pkgs/idp-provider/Cargo.toml +++ b/pkgs/idp-provider/Cargo.toml @@ -22,6 +22,7 @@ rsa = "0.9" pkcs1 = { version = "0.7", features = ["alloc"] } pkcs8 = { version = "0.10", features = ["encryption", "pem"] } rusqlite = { version = "0.42", features = ["bundled"] } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } [dev-dependencies] tower = { version = "0.5", features = ["util"] } diff --git a/pkgs/idp-provider/README.md b/pkgs/idp-provider/README.md index 4fa789303f..782a93b1b9 100644 --- a/pkgs/idp-provider/README.md +++ b/pkgs/idp-provider/README.md @@ -57,6 +57,8 @@ SSO never rebinds an id key (#2060). | `IDP_PROVIDER_OIDC_KEY` | _(unset)_ | Path to the encrypted Slice 2 OIDC private key. Required when `IDP_PROVIDER_CONFIG` is set. | | `IDP_CA_PASSPHRASE` | _(unset)_ | Passphrase for the signing key, in process memory only (vault name `idp.ca-passphrase`). Required when `IDP_PROVIDER_CONFIG` is set. Never logged, never written to disk by the provider. | | `IDP_PROVIDER_AUDIT_DB` | _(registry config's `audit_db_path`, else in-memory)_ | Append-only audit SQLite path override. | +| `IDP_PROVIDER_IDENTITY_DB` | _(registry config's `identity_db_path`, else in-memory)_ | Identity store (#13415) SQLite path override. | +| `IDP_GITHUB_CLIENT_SECRET` / `IDP_GOOGLE_CLIENT_SECRET` / `IDP_MICROSOFT_CLIENT_SECRET` | _(unset)_ | Federated-door client secrets, in process memory only (vault names `idp.github.client-secret` / `idp.google.client-secret` / `idp.microsoft.client-secret`). A door whose secret is unset stays disabled. | ## Endpoints @@ -73,6 +75,58 @@ SSO never rebinds an id key (#2060). - `POST /token` — `grant_type=authorization_code` exchange with PKCE verification; returns short-lived ID + access tokens. - `GET /userinfo` — Bearer access token in, account claims out. +- `GET /door/{name}/start` — federated door entry: re-validates the authorize request, parks it, redirects upstream. +- `GET /door/{name}/callback` — upstream return: verifies the upstream identity, enforces the allowlist and link state, mints our code, redirects to the relying party. + +## Federated doors (#13411 / #13412 / #13414) + +Configured doors appear on the login form as "Sign in with …" +links to `GET /door/{name}/start`, which re-validates the relying +party's authorize request, parks it server-side under a random +single-use state handle (300 s), and redirects to the upstream. +`GET /door/{name}/callback` consumes the handle, exchanges the +upstream code, and verifies the upstream identity: + +- **OIDC doors** (Google, Microsoft): the upstream ID token's + signature is verified against the upstream JWKS, and `iss` / + `aud` / `exp` / `nonce` are checked. The recorded subject is the + configured claim (`sub`; Microsoft records `oid`, falling back + to `sub`). The provider also sends PKCE (S256) upstream. +- **GitHub door**: the code is exchanged and the user document is + fetched; the subject is the numeric user `id`. + +The deny-by-default allowlist is then enforced in the provider, +exactly as for the local door, and a code of *our own* is minted +into the same code store — a door login's tokens are +indistinguishable from a local login's (same account `sub`, same +role claims). Door client secrets are never in the config file: +each door names an environment variable (`client_secret_env`) the +launcher fills from the vault by name (`idp.github.client-secret` +→ `IDP_GITHUB_CLIENT_SECRET`, `idp.google.client-secret` → +`IDP_GOOGLE_CLIENT_SECRET`, `idp.microsoft.client-secret` → +`IDP_MICROSOFT_CLIENT_SECRET`). A door whose secret is unset — or +an OIDC door without an issuer/JWKS configured — is disabled: its +start endpoint denies with an audit record and the rest of the +provider is unaffected. + +## Account linking (#13415) + +Link state lives in a runtime identity store (SQLite, +`identity_db_path`), not in the config: the config's +`account.identities` list is only the seed. The store keeps one +row per `(provider, subject)` with `active | unlinked` status and +an append-only event history (`seed` / `link` / `relink` / +`unlink`, trigger-protected like the audit table). Rows are never +hard-deleted while the account lives. + +- An allowlisted identity arriving at a door for the first time is + **linked by that login** (actor `door-login`); the event lands in + the identity history *and* the audit record. +- An operator unlinks with `idp-provider unlink + ` (relink: `link`; inspect: `links`). An unlinked + identity's door login is denied (`identity_unlinked`, audited) — + a login never silently undoes an unlink — while the account + stays reachable via the other doors. ## kid convention diff --git a/pkgs/idp-provider/config.example.json b/pkgs/idp-provider/config.example.json index 750b7f264e..77f417c71f 100644 --- a/pkgs/idp-provider/config.example.json +++ b/pkgs/idp-provider/config.example.json @@ -1 +1 @@ -{"_comment":"Example provider registry config for pkgs/idp-provider (Slice 3, #13409). The REAL config lives on-host with the provider (point IDP_PROVIDER_CONFIG at it) and is never committed: it carries the owner's credential HASH. Generate the hash on-host with `IDP_LOCAL_CREDENTIAL=... idp-provider hash-credential`. An empty hash verifies nothing, so this example cannot open the door.","account":{"account_id":"drew","display_name":"Drew","identities":[{"provider":"devtoday-local","subject":"drew"}],"local_credential_hash":"","roles":["owner","orchestrator","agent","read-only"]},"allowlist":["devtoday-local:drew"],"audit_db_path":"/home/user/idp-provider/audit.sqlite3","clients":[{"client_id":"test-rp","name":"Test relying party (Slice 3 loop proof)","redirect_uris":["http://127.0.0.1:8912/callback"]},{"client_id":"devtoday-local-door","name":"devtoday local door client","redirect_uris":["http://127.0.0.1:8913/callback"]}]} \ No newline at end of file +{"_comment":"Example provider registry config for pkgs/idp-provider (Slice 3, #13409; doors #13411/#13412/#13414; linking #13415). The REAL config lives on-host with the provider (point IDP_PROVIDER_CONFIG at it) and is never committed: it carries the owner's credential HASH. Generate the hash on-host with `IDP_LOCAL_CREDENTIAL=... idp-provider hash-credential`. An empty hash verifies nothing, so this example cannot open the door. Door client ids below are placeholders; door client SECRETS are never in this file — each door names the environment variable the launcher fills from the vault by name (idp.github.client-secret -> IDP_GITHUB_CLIENT_SECRET, idp.google.client-secret -> IDP_GOOGLE_CLIENT_SECRET, idp.microsoft.client-secret -> IDP_MICROSOFT_CLIENT_SECRET). A door whose secret env is unset stays disabled. Door endpoints and the Microsoft issuer (the consumers tenant id segment) must be checked against the actual app registrations when they are created. The account.identities list is the identity store's seed; link state after first boot lives in identity_db_path.","account":{"account_id":"drew","display_name":"Drew","identities":[{"provider":"devtoday-local","subject":"drew"}],"local_credential_hash":"","roles":["owner","orchestrator","agent","read-only"]},"allowlist":["devtoday-local:drew"],"audit_db_path":"/home/user/idp-provider/audit.sqlite3","clients":[{"client_id":"test-rp","name":"Test relying party (Slice 3 loop proof)","redirect_uris":["http://127.0.0.1:8912/callback"]},{"client_id":"devtoday-local-door","name":"devtoday local door client","redirect_uris":["http://127.0.0.1:8913/callback"]}],"doors":[{"authorize_url":"https://github.com/login/oauth/authorize","client_id":"REPLACE_WITH_GITHUB_OAUTH_APP_CLIENT_ID","client_secret_env":"IDP_GITHUB_CLIENT_SECRET","display_name":"GitHub","kind":"github","name":"github","scopes":["read:user"],"token_url":"https://github.com/login/oauth/access_token","userinfo_url":"https://api.github.com/user"},{"authorize_url":"https://accounts.google.com/o/oauth2/v2/auth","client_id":"REPLACE_WITH_GOOGLE_OAUTH_CLIENT_ID","client_secret_env":"IDP_GOOGLE_CLIENT_SECRET","display_name":"Google","issuer":"https://accounts.google.com","jwks_uri":"https://www.googleapis.com/oauth2/v3/certs","kind":"oidc","name":"google","scopes":["openid"],"subject_claim":"sub","token_url":"https://oauth2.googleapis.com/token"},{"authorize_url":"https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize","client_id":"REPLACE_WITH_MICROSOFT_APP_CLIENT_ID","client_secret_env":"IDP_MICROSOFT_CLIENT_SECRET","display_name":"Microsoft","issuer":"https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0","jwks_uri":"https://login.microsoftonline.com/consumers/discovery/v2.0/keys","kind":"oidc","name":"microsoft","scopes":["openid"],"subject_claim":"oid","token_url":"https://login.microsoftonline.com/consumers/oauth2/v2.0/token"}],"identity_db_path":"/home/user/idp-provider/identities.sqlite3"} \ No newline at end of file diff --git a/pkgs/idp-provider/examples/test-rp.rs b/pkgs/idp-provider/examples/test-rp.rs index 30bf0675b3..74ab36b455 100644 --- a/pkgs/idp-provider/examples/test-rp.rs +++ b/pkgs/idp-provider/examples/test-rp.rs @@ -71,7 +71,8 @@ fn http( Some(i) => (&rest[..i], &rest[i..]), None => (rest, "/"), }; - let mut stream = TcpStream::connect(authority).map_err(|e| format!("connect {authority}: {e}"))?; + let mut stream = + TcpStream::connect(authority).map_err(|e| format!("connect {authority}: {e}"))?; let mut req = format!("{method} {path} HTTP/1.1\r\nhost: {authority}\r\nconnection: close\r\n"); if let Some(b) = bearer { req.push_str(&format!("authorization: Bearer {b}\r\n")); @@ -113,7 +114,11 @@ fn http( chunked = true; } } - let body = if chunked { dechunk(body) } else { body.to_string() }; + let body = if chunked { + dechunk(body) + } else { + body.to_string() + }; Ok((status, location, body)) } @@ -153,12 +158,18 @@ fn main() { }; // 1. Discovery. - let (status, _l, body) = http("GET", &format!("{issuer}/.well-known/openid-configuration"), None, None) - .unwrap_or_else(|e| run(&e)); + let (status, _l, body) = http( + "GET", + &format!("{issuer}/.well-known/openid-configuration"), + None, + None, + ) + .unwrap_or_else(|e| run(&e)); if status != 200 { run(&format!("discovery status {status}")); } - let discovery: serde_json::Value = serde_json::from_str(&body).unwrap_or_else(|_| run("discovery is not JSON")); + let discovery: serde_json::Value = + serde_json::from_str(&body).unwrap_or_else(|_| run("discovery is not JSON")); if discovery["issuer"] != issuer { run("discovery issuer mismatch"); } @@ -172,7 +183,8 @@ fn main() { if status != 200 { run(&format!("jwks status {status}")); } - let jwks: serde_json::Value = serde_json::from_str(&body).unwrap_or_else(|_| run("jwks is not JSON")); + let jwks: serde_json::Value = + serde_json::from_str(&body).unwrap_or_else(|_| run("jwks is not JSON")); let jwk = &jwks["keys"][0]; let kid = jwk["kid"].as_str().unwrap_or("").to_string(); let decode = |s: &str| B64URL.decode(s).unwrap_or_default(); @@ -197,7 +209,8 @@ fn main() { ("login_id", &login_id), ("credential", &credential), ]); - let (status, location, _body) = http("POST", authz_ep, Some(&form), None).unwrap_or_else(|e| run(&e)); + let (status, location, _body) = + http("POST", authz_ep, Some(&form), None).unwrap_or_else(|e| run(&e)); if mode == "deny" { // The proof's negative case: refusal is the success here. println!( @@ -236,9 +249,14 @@ fn main() { if status != 200 { run(&format!("token status {status}: {body}")); } - let tokens: serde_json::Value = serde_json::from_str(&body).unwrap_or_else(|_| run("token response is not JSON")); - let id_token = tokens["id_token"].as_str().unwrap_or_else(|| run("no id_token")); - let access_token = tokens["access_token"].as_str().unwrap_or_else(|| run("no access_token")); + let tokens: serde_json::Value = + serde_json::from_str(&body).unwrap_or_else(|_| run("token response is not JSON")); + let id_token = tokens["id_token"] + .as_str() + .unwrap_or_else(|| run("no id_token")); + let access_token = tokens["access_token"] + .as_str() + .unwrap_or_else(|| run("no access_token")); // 5. Verify the ID token against the JWKS key. let parts: Vec<&str> = id_token.split('.').collect(); @@ -262,11 +280,13 @@ fn main() { } // 6. Userinfo with the access token. - let (status, _l, body) = http("GET", userinfo_ep, None, Some(access_token)).unwrap_or_else(|e| run(&e)); + let (status, _l, body) = + http("GET", userinfo_ep, None, Some(access_token)).unwrap_or_else(|e| run(&e)); if status != 200 { run(&format!("userinfo status {status}")); } - let userinfo: serde_json::Value = serde_json::from_str(&body).unwrap_or_else(|_| run("userinfo is not JSON")); + let userinfo: serde_json::Value = + serde_json::from_str(&body).unwrap_or_else(|_| run("userinfo is not JSON")); if userinfo["sub"] != claims["sub"] { run("userinfo sub does not match id_token sub"); } diff --git a/pkgs/idp-provider/src/doors.rs b/pkgs/idp-provider/src/doors.rs new file mode 100644 index 0000000000..ca1683625c --- /dev/null +++ b/pkgs/idp-provider/src/doors.rs @@ -0,0 +1,514 @@ +//! Federated door handlers (#13411/#13412/#13414, linking per +//! #13415): `GET /door/{name}/start` and `GET /door/{name}/callback`. +//! +//! The shape mirrors the local door's discipline exactly: +//! +//! - `start` validates the relying party's authorize request with +//! the same checks as `/authorize` (static client registry, +//! redirect URI, code + PKCE S256, `openid` scope) *before* the +//! user is sent anywhere, parks the request server-side under a +//! random state handle, and redirects to the upstream. +//! - `callback` consumes the state handle (single-use), exchanges +//! the upstream code, verifies the upstream identity (OIDC: the +//! ID token's signature against the upstream JWKS plus iss/aud/ +//! exp/nonce; GitHub: the numeric user id), then enforces the +//! deny-by-default allowlist in the provider — before any link or +//! code exists. +//! - Linking (#13415): an allowlisted identity the store has never +//! seen is linked to the account row by this login, with the link +//! written to the identity history and the audit record. An +//! identity an operator has unlinked is denied +//! (`identity_unlinked`) — unlinking is never silently undone by +//! a login. +//! - On success the handler mints one of *our* authorization codes +//! (the same code store as the local door) and redirects to the +//! relying party. Every outcome — redirect, denial, link — is +//! audited; a failed audit write fails the attempt closed. + +use crate::flow::{ + denied, err_json, issue_code, validate_authorize_request, AuthorizeParams, FlowState, +}; +use crate::registry::{now_unix, random_b64url, url_encode}; +use crate::upstream::{ + exchange_upstream_code, fetch_github_user, fetch_upstream_jwks, subject_from_claims, + verify_upstream_id_token, DoorRuntime, +}; +use axum::{ + extract::{Path, Query, State}, + http::{header, StatusCode}, + response::{IntoResponse, Response}, +}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; + +pub const PENDING_TTL_SECS: i64 = 300; + +/// A relying party's authorize request, parked server-side while +/// the user is at the upstream door. +#[derive(Clone)] +pub struct PendingDoor { + pub client_id: String, + pub redirect_uri: String, + pub code_challenge: String, + pub nonce: Option, + pub scope: String, + pub rp_state: Option, + pub door: String, + pub upstream_nonce: Option, + pub pkce_verifier: Option, + pub expires_at: i64, +} + +#[derive(Debug, Default, Deserialize)] +pub struct CallbackParams { + pub code: Option, + pub state: Option, + pub error: Option, +} + +fn find_door<'a>(flow: &'a FlowState, name: &str) -> Option<&'a DoorRuntime> { + flow.doors.iter().find(|d| d.name() == name) +} + +fn endpoint(name: &str) -> String { + format!("door/{name}") +} + +pub async fn door_start( + State(st): State, + Path(name): Path, + Query(p): Query, +) -> Response { + let flow = match &st.flow { + Some(f) => f, + None => { + return err_json( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "authorization flow is not configured on this provider instance", + ) + } + }; + let client_id = p.client_id.clone().unwrap_or_default(); + let door = match find_door(flow, &name) { + Some(d) => d, + None => { + return denied( + flow, + &endpoint(&name), + "unknown_door", + &client_id, + "", + StatusCode::NOT_FOUND, + "invalid_request", + "unknown door", + ) + } + }; + // The relying party's request must be valid before the user is + // sent upstream — same checks (and audit rows) as /authorize. + let valid = match validate_authorize_request(flow, &p) { + Ok(v) => v, + Err(resp) => return resp, + }; + if !door.enabled() { + return denied( + flow, + &endpoint(&name), + "door_not_configured", + &client_id, + "", + StatusCode::SERVICE_UNAVAILABLE, + "temporarily_unavailable", + "this door is not configured on this provider instance", + ); + } + + let handle = random_b64url(32); + let is_oidc = door.config.kind == "oidc"; + let upstream_nonce = if is_oidc { + Some(random_b64url(16)) + } else { + None + }; + let pkce_verifier = if is_oidc { + Some(random_b64url(32)) + } else { + None + }; + let pending = PendingDoor { + client_id: valid.client_id.clone(), + redirect_uri: valid.redirect_uri.clone(), + code_challenge: valid.code_challenge.clone(), + nonce: p.nonce.clone(), + scope: valid.scope.clone(), + rp_state: p.state.clone(), + door: name.clone(), + upstream_nonce: upstream_nonce.clone(), + pkce_verifier: pkce_verifier.clone(), + expires_at: now_unix() + PENDING_TTL_SECS, + }; + match flow.pending_doors.lock() { + Ok(mut map) => { + let now = now_unix(); + map.retain(|_, v| v.expires_at >= now); + map.insert(handle.clone(), pending); + } + Err(_) => { + return err_json( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "door state store unavailable", + ) + } + } + let _ = flow.audit.record( + &endpoint(&name), + "challenge", + "upstream_redirect", + &client_id, + "", + ); + + let callback = door.callback_uri(&flow.issuer); + let mut params: Vec<(&str, String)> = vec![ + ("client_id", door.config.client_id.clone()), + ("redirect_uri", callback), + ("state", handle), + ]; + if is_oidc { + let scope = if door.config.scopes.is_empty() { + "openid".to_string() + } else { + door.config.scopes.join(" ") + }; + params.push(("response_type", "code".to_string())); + params.push(("scope", scope)); + if let Some(nonce) = &upstream_nonce { + params.push(("nonce", nonce.clone())); + } + if let Some(verifier) = &pkce_verifier { + let challenge = crate::b64url(&Sha256::digest(verifier.as_bytes())); + params.push(("code_challenge", challenge)); + params.push(("code_challenge_method", "S256".to_string())); + } + } else { + let scope = if door.config.scopes.is_empty() { + "read:user".to_string() + } else { + door.config.scopes.join(" ") + }; + params.push(("scope", scope)); + } + let query = params + .iter() + .map(|(k, v)| format!("{}={}", url_encode(k), url_encode(v))) + .collect::>() + .join("&"); + let location = format!("{}?{}", door.config.authorize_url, query); + (StatusCode::FOUND, [(header::LOCATION, location)]).into_response() +} + +pub async fn door_callback( + State(st): State, + Path(name): Path, + Query(cb): Query, +) -> Response { + let flow = match &st.flow { + Some(f) => f, + None => { + return err_json( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "authorization flow is not configured on this provider instance", + ) + } + }; + let door = match find_door(flow, &name) { + Some(d) => d.clone(), + None => { + return denied( + flow, + &endpoint(&name), + "unknown_door", + "", + "", + StatusCode::NOT_FOUND, + "invalid_request", + "unknown door", + ) + } + }; + if cb.error.is_some() { + return denied( + flow, + &endpoint(&name), + "upstream_error", + "", + "", + StatusCode::BAD_REQUEST, + "access_denied", + "the upstream door returned an error", + ); + } + // Consume the pending request: single-use, whether the login + // then succeeds or fails. + let handle = cb.state.clone().unwrap_or_default(); + let pending = { + let mut map = match flow.pending_doors.lock() { + Ok(m) => m, + Err(_) => { + return err_json( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "door state store unavailable", + ) + } + }; + map.remove(&handle) + }; + let pending = match pending { + Some(p) if p.expires_at >= now_unix() && p.door == name => p, + _ => { + return denied( + flow, + &endpoint(&name), + "unknown_or_expired_state", + "", + "", + StatusCode::BAD_REQUEST, + "invalid_request", + "door state is unknown, expired, or already used", + ) + } + }; + let client_id = pending.client_id.clone(); + let code = cb.code.clone().unwrap_or_default(); + if code.is_empty() { + return denied( + flow, + &endpoint(&name), + "missing_code", + &client_id, + "", + StatusCode::BAD_REQUEST, + "invalid_request", + "the upstream door returned no code", + ); + } + let callback_uri = door.callback_uri(&flow.issuer); + let token_doc = match exchange_upstream_code( + &flow.http, + &door, + &code, + &callback_uri, + pending.pkce_verifier.as_deref(), + ) + .await + { + Ok(d) => d, + Err(_) => { + return denied( + flow, + &endpoint(&name), + "upstream_exchange_failed", + &client_id, + "", + StatusCode::BAD_GATEWAY, + "server_error", + "the upstream token exchange failed", + ) + } + }; + + // Resolve the verified upstream identity. + let subject = if door.config.kind == "github" { + let access_token = token_doc["access_token"].as_str().unwrap_or(""); + if access_token.is_empty() { + return denied( + flow, + &endpoint(&name), + "upstream_no_access_token", + &client_id, + "", + StatusCode::BAD_GATEWAY, + "server_error", + "the upstream token exchange returned no access token", + ); + } + match fetch_github_user(&flow.http, &door, access_token).await { + Ok(user) => subject_from_claims(&door, &user), + Err(_) => { + return denied( + flow, + &endpoint(&name), + "upstream_user_fetch_failed", + &client_id, + "", + StatusCode::BAD_GATEWAY, + "server_error", + "the upstream user fetch failed", + ) + } + } + } else { + let id_token = token_doc["id_token"].as_str().unwrap_or(""); + if id_token.is_empty() { + return denied( + flow, + &endpoint(&name), + "upstream_no_id_token", + &client_id, + "", + StatusCode::BAD_GATEWAY, + "server_error", + "the upstream token exchange returned no ID token", + ); + } + let jwks_uri = door.config.jwks_uri.clone().unwrap_or_default(); + let jwks = match fetch_upstream_jwks(&flow.http, &jwks_uri).await { + Ok(j) => j, + Err(_) => { + return denied( + flow, + &endpoint(&name), + "upstream_jwks_failed", + &client_id, + "", + StatusCode::BAD_GATEWAY, + "server_error", + "the upstream JWKS fetch failed", + ) + } + }; + match verify_upstream_id_token( + id_token, + &jwks, + &door, + pending.upstream_nonce.as_deref(), + now_unix(), + ) { + Ok(claims) => subject_from_claims(&door, &claims), + Err(_) => { + return denied( + flow, + &endpoint(&name), + "upstream_token_invalid", + &client_id, + "", + StatusCode::FORBIDDEN, + "access_denied", + "the upstream ID token did not verify", + ) + } + } + }; + let subject = match subject { + Some(s) if !s.is_empty() => s, + _ => { + return denied( + flow, + &endpoint(&name), + "upstream_no_subject", + &client_id, + "", + StatusCode::FORBIDDEN, + "access_denied", + "the upstream identity has no subject", + ) + } + }; + let identity_key = format!("{}:{}", door.identity_provider(), subject); + + // Deny-by-default gate, enforced in the provider, before any + // link or code exists. + if !flow.registry.is_allowlisted(&identity_key) { + return denied( + flow, + &endpoint(&name), + "not_allowlisted", + &client_id, + &identity_key, + StatusCode::FORBIDDEN, + "access_denied", + "identity is not on the allowlist", + ); + } + + // Link state (#13415): active proceeds; unlinked is denied (an + // operator's unlink is never silently undone); never-seen is + // linked by this login, with the event in the identity history + // and the audit record. + match flow.identities.status(&name, &subject) { + Ok(Some(ref s)) if s == "active" => {} + Ok(Some(_)) => { + return denied( + flow, + &endpoint(&name), + "identity_unlinked", + &client_id, + &identity_key, + StatusCode::FORBIDDEN, + "access_denied", + "identity is not linked to an account", + ) + } + Ok(None) => { + let account_id = flow.registry.account.account_id.clone(); + match flow + .identities + .link(&name, &subject, &account_id, "door-login") + { + Ok(event) if event != "none" => { + if flow + .audit + .record("link", "allowed", event, &client_id, &identity_key) + .is_err() + { + return err_json( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "audit write failed", + ); + } + } + Ok(_) => {} + Err(_) => { + return err_json( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "identity link failed", + ) + } + } + } + Err(_) => { + return err_json( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "identity store unavailable", + ) + } + } + + // Success: mint one of our own codes, bound to the relying + // party's original request, and hand the user back. + let code = match issue_code( + flow, + &pending.client_id, + &pending.redirect_uri, + &pending.code_challenge, + &identity_key, + pending.nonce.as_deref(), + &pending.scope, + &endpoint(&name), + ) { + Ok(c) => c, + Err(resp) => return resp, + }; + let mut location = format!("{}?code={code}", pending.redirect_uri); + if let Some(state) = &pending.rp_state { + location.push_str(&format!("&state={state}")); + } + (StatusCode::FOUND, [(header::LOCATION, location)]).into_response() +} diff --git a/pkgs/idp-provider/src/flow.rs b/pkgs/idp-provider/src/flow.rs index e19c3a069e..67209aabd2 100644 --- a/pkgs/idp-provider/src/flow.rs +++ b/pkgs/idp-provider/src/flow.rs @@ -9,16 +9,25 @@ //! credential serves a small login form; the form POSTs back to //! `/authorize` with the local credential, which is verified against //! the PBKDF2 hash in the on-host provider config (never in the -//! repo). The deny-by-default allowlist is enforced in the provider -//! before the credential is even checked, and EVERY authorize/token -//! attempt — allowed, denied, or form challenge — is appended to the -//! audit record. A failed audit write fails the attempt closed. +//! repo). The form also lists the configured federated doors +//! (#13411/#13412/#13414), which start at `/door/{name}/start` and +//! are handled in `doors.rs`. +//! +//! The deny-by-default allowlist is enforced in the provider before +//! the credential is even checked, and EVERY authorize/token +//! attempt — allowed, denied, or form challenge — is appended to +//! the audit record. A failed audit write fails the attempt closed. +//! Link state lives in the identity store (#13415): the local door +//! checks it exactly like a federated door does. use crate::audit::AuditLog; +use crate::doors::PendingDoor; +use crate::identities::IdentityStore; use crate::registry::{ - now_unix, random_b64url, verify_credential, ProviderConfig, LOCAL_DOOR_PROVIDER, + now_unix, random_b64url, url_encode, verify_credential, ProviderConfig, LOCAL_DOOR_PROVIDER, }; use crate::signing::TokenSigner; +use crate::upstream::DoorRuntime; use axum::{ extract::{Form, Query, State}, http::{header, HeaderMap, StatusCode}, @@ -49,8 +58,18 @@ pub struct FlowState { pub registry: ProviderConfig, pub signer: TokenSigner, pub audit: Arc, + /// Link state for the account's identities (#13415), seeded + /// from the registry config at construction. + pub identities: Arc, + /// Configured federated doors (empty until doors are + /// registered and configured on-host). + pub doors: Vec, + /// HTTP client for upstream door calls. + pub http: reqwest::Client, + /// Parked federated-door authorize requests, by state handle. + pub pending_doors: Mutex>, codes: Mutex>, - issuer: String, + pub issuer: String, } impl FlowState { @@ -58,12 +77,21 @@ impl FlowState { registry: ProviderConfig, signer: TokenSigner, audit: Arc, + identities: Arc, + doors: Vec, issuer: String, ) -> Self { + // The config's identity list is the store's seed (#13415); + // after seeding, the store is authoritative. + let _ = identities.seed(®istry.account.account_id, ®istry.account.identities); FlowState { registry, signer, audit, + identities, + doors, + http: reqwest::Client::new(), + pending_doors: Mutex::new(HashMap::new()), codes: Mutex::new(HashMap::new()), issuer, } @@ -85,7 +113,7 @@ pub struct AuthorizeParams { pub credential: Option, } -fn err_json(status: StatusCode, error: &str, description: &str) -> Response { +pub(crate) fn err_json(status: StatusCode, error: &str, description: &str) -> Response { ( status, Json(serde_json::json!({"error": error, "error_description": description})), @@ -96,7 +124,7 @@ fn err_json(status: StatusCode, error: &str, description: &str) -> Response { /// Audit-then-error helper: records a denied attempt and returns the /// error response. If the audit write itself fails, the attempt /// still fails (with a plainer error) — never succeeds unaudited. -fn denied( +pub(crate) fn denied( flow: &FlowState, endpoint: &str, reason: &str, @@ -119,38 +147,24 @@ fn html_escape(s: &str) -> String { .replace('"', """) } -fn login_form(p: &AuthorizeParams) -> Html { - let hidden = |name: &str, value: &Option| -> String { - match value { - Some(v) => format!( - "", - html_escape(v) - ), - None => String::new(), - } - }; - let hiddens = [ - hidden("response_type", &p.response_type), - hidden("client_id", &p.client_id), - hidden("redirect_uri", &p.redirect_uri), - hidden("scope", &p.scope), - hidden("state", &p.state), - hidden("nonce", &p.nonce), - hidden("code_challenge", &p.code_challenge), - hidden("code_challenge_method", &p.code_challenge_method), - ] - .concat(); - Html(format!( - "devtoday SSO — local door\ -

devtoday SSO

Sign in with your devtoday local identity.

\ -
{hiddens}\ - \ - \ -
" - )) +/// A relying-party authorize request that passed the static checks +/// shared by every door: known client, registered redirect URI, +/// `response_type=code`, PKCE S256, `openid` scope. +pub struct ValidatedAuthorize { + pub client_id: String, + pub redirect_uri: String, + pub code_challenge: String, + pub scope: String, } -fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { +/// The static authorize-request checks, in the local door's order, +/// with the local door's audit rows. Used by `/authorize` itself +/// and by the federated doors' start handler — a request that +/// would be denied here is denied before the user is sent upstream. +pub(crate) fn validate_authorize_request( + flow: &FlowState, + p: &AuthorizeParams, +) -> Result { let client_id = p.client_id.clone().unwrap_or_default(); let login_id = p.login_id.clone().unwrap_or_default(); let identity_key = if login_id.is_empty() { @@ -159,11 +173,10 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { format!("{LOCAL_DOOR_PROVIDER}:{login_id}") }; - // Static client registry — unknown clients never get a redirect. let client = match flow.registry.client(&client_id) { Some(c) => c, None => { - return denied( + return Err(denied( flow, "authorize", "unknown_client", @@ -172,12 +185,12 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { StatusCode::BAD_REQUEST, "invalid_client", "unknown client_id", - ) + )) } }; let redirect_uri = p.redirect_uri.clone().unwrap_or_default(); if !client.redirect_uris.iter().any(|u| u == &redirect_uri) { - return denied( + return Err(denied( flow, "authorize", "redirect_uri_mismatch", @@ -186,10 +199,10 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { StatusCode::BAD_REQUEST, "invalid_request", "redirect_uri is not registered for this client", - ); + )); } if p.response_type.as_deref() != Some("code") { - return denied( + return Err(denied( flow, "authorize", "unsupported_response_type", @@ -198,12 +211,12 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { StatusCode::BAD_REQUEST, "unsupported_response_type", "only response_type=code is supported", - ); + )); } if p.code_challenge_method.as_deref() != Some("S256") || p.code_challenge.as_deref().unwrap_or("").is_empty() { - return denied( + return Err(denied( flow, "authorize", "pkce_s256_required", @@ -212,11 +225,11 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { StatusCode::BAD_REQUEST, "invalid_request", "PKCE with code_challenge_method=S256 is required", - ); + )); } let scope = p.scope.clone().unwrap_or_default(); if !scope.split_whitespace().any(|s| s == "openid") { - return denied( + return Err(denied( flow, "authorize", "openid_scope_required", @@ -225,8 +238,165 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { StatusCode::BAD_REQUEST, "invalid_scope", "scope must include openid", - ); + )); } + Ok(ValidatedAuthorize { + client_id, + redirect_uri, + code_challenge: p.code_challenge.clone().unwrap_or_default(), + scope, + }) +} + +/// Mint a single-use authorization code bound to an already-gated +/// identity, and audit the issuance under `audit_endpoint` +/// (`authorize` for the local door, `door/{name}` for a federated +/// door). A failed audit write burns the code and fails closed. +pub(crate) fn issue_code( + flow: &FlowState, + client_id: &str, + redirect_uri: &str, + code_challenge: &str, + identity_key: &str, + nonce: Option<&str>, + scope: &str, + audit_endpoint: &str, +) -> Result { + let code = random_b64url(32); + let record = AuthCode { + client_id: client_id.to_string(), + redirect_uri: redirect_uri.to_string(), + code_challenge: code_challenge.to_string(), + account_id: flow.registry.account.account_id.clone(), + identity_key: identity_key.to_string(), + nonce: nonce.map(|s| s.to_string()), + scope: scope.to_string(), + expires_at: now_unix() + CODE_TTL_SECS, + }; + match flow.codes.lock() { + Ok(mut codes) => { + codes.insert(code.clone(), record); + } + Err(_) => { + return Err(err_json( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "code store unavailable", + )) + } + } + if flow + .audit + .record( + audit_endpoint, + "allowed", + "code_issued", + client_id, + identity_key, + ) + .is_err() + { + // Fail closed: an unaudited success is not a success. Burn + // the code we just minted. + if let Ok(mut codes) = flow.codes.lock() { + codes.remove(&code); + } + return Err(err_json( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "audit write failed", + )); + } + Ok(code) +} + +fn login_form(flow: &FlowState, p: &AuthorizeParams) -> Html { + let hidden = |name: &str, value: &Option| -> String { + match value { + Some(v) => format!( + "", + html_escape(v) + ), + None => String::new(), + } + }; + let hiddens = [ + hidden("response_type", &p.response_type), + hidden("client_id", &p.client_id), + hidden("redirect_uri", &p.redirect_uri), + hidden("scope", &p.scope), + hidden("state", &p.state), + hidden("nonce", &p.nonce), + hidden("code_challenge", &p.code_challenge), + hidden("code_challenge_method", &p.code_challenge_method), + ] + .concat(); + // Federated doors: one link per enabled door, carrying the + // relying party's authorize parameters to the door's start + // endpoint (which re-validates them before redirecting). + let door_query = [ + ("response_type", &p.response_type), + ("client_id", &p.client_id), + ("redirect_uri", &p.redirect_uri), + ("scope", &p.scope), + ("state", &p.state), + ("nonce", &p.nonce), + ("code_challenge", &p.code_challenge), + ("code_challenge_method", &p.code_challenge_method), + ] + .iter() + .filter_map(|(k, v)| { + v.as_ref() + .map(|v| format!("{}={}", url_encode(k), url_encode(v))) + }) + .collect::>() + .join("&"); + let door_links = flow + .doors + .iter() + .filter(|d| d.enabled()) + .map(|d| { + let label = if d.config.display_name.is_empty() { + d.name().to_string() + } else { + d.config.display_name.clone() + }; + format!( + "
  • Sign in with {}
  • ", + html_escape(d.name()), + html_escape(&door_query), + html_escape(&label) + ) + }) + .collect::>() + .join(""); + let doors_block = if door_links.is_empty() { + String::new() + } else { + format!("

    Or sign in with a linked door:

      {door_links}
    ") + }; + Html(format!( + "devtoday SSO — local door\ +

    devtoday SSO

    Sign in with your devtoday local identity.

    \ +
    {hiddens}\ + \ + \ +
    {doors_block}" + )) +} + +fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { + let valid = match validate_authorize_request(flow, &p) { + Ok(v) => v, + Err(resp) => return resp, + }; + let client_id = valid.client_id.clone(); + let login_id = p.login_id.clone().unwrap_or_default(); + let identity_key = if login_id.is_empty() { + String::new() + } else { + format!("{LOCAL_DOOR_PROVIDER}:{login_id}") + }; // No credential presented yet: serve the local-door login form. // This is a challenge, not an authentication attempt outcome. @@ -238,7 +408,7 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { &client_id, "", ); - return login_form(&p).into_response(); + return login_form(flow, &p).into_response(); } // Deny-by-default gate, enforced in the provider, BEFORE the @@ -256,7 +426,7 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { "identity is not on the allowlist", ); } - if !flow.registry.is_linked(LOCAL_DOOR_PROVIDER, &login_id) { + if !flow.identities.is_active(LOCAL_DOOR_PROVIDER, &login_id) { return denied( flow, "authorize", @@ -285,52 +455,20 @@ fn authorize(flow: &FlowState, p: AuthorizeParams) -> Response { } // Success: mint a single-use authorization code. - let code = random_b64url(32); - let record = AuthCode { - client_id: client_id.clone(), - redirect_uri: redirect_uri.clone(), - code_challenge: p.code_challenge.clone().unwrap_or_default(), - account_id: flow.registry.account.account_id.clone(), - identity_key: identity_key.clone(), - nonce: p.nonce.clone(), - scope: scope.clone(), - expires_at: now_unix() + CODE_TTL_SECS, + let code = match issue_code( + flow, + &valid.client_id, + &valid.redirect_uri, + &valid.code_challenge, + &identity_key, + p.nonce.as_deref(), + &valid.scope, + "authorize", + ) { + Ok(c) => c, + Err(resp) => return resp, }; - match flow.codes.lock() { - Ok(mut codes) => { - codes.insert(code.clone(), record); - } - Err(_) => { - return err_json( - StatusCode::INTERNAL_SERVER_ERROR, - "server_error", - "code store unavailable", - ) - } - } - if flow - .audit - .record( - "authorize", - "allowed", - "code_issued", - &client_id, - &identity_key, - ) - .is_err() - { - // Fail closed: an unaudited success is not a success. Burn - // the code we just minted. - if let Ok(mut codes) = flow.codes.lock() { - codes.remove(&code); - } - return err_json( - StatusCode::INTERNAL_SERVER_ERROR, - "server_error", - "audit write failed", - ); - } - let mut location = format!("{redirect_uri}?code={code}"); + let mut location = format!("{}?code={code}", valid.redirect_uri); if let Some(state) = &p.state { location.push_str(&format!("&state={state}")); } @@ -560,7 +698,7 @@ pub async fn userinfo(State(st): State, headers: HeaderMap) -> return err_json( StatusCode::UNAUTHORIZED, "invalid_token", - "a Bearer access token is required", + "a Bearer token is required", ) } }; diff --git a/pkgs/idp-provider/src/identities.rs b/pkgs/idp-provider/src/identities.rs new file mode 100644 index 0000000000..e83909e7c1 --- /dev/null +++ b/pkgs/idp-provider/src/identities.rs @@ -0,0 +1,365 @@ +//! Runtime identity store (#13415): the link state of the account's +//! external identities, with an append-only event history. +//! +//! Slice 3 held the account's linked identities as static rows in +//! the provider config. Linking needs runtime state: a door login +//! can link an allowlisted identity, an operator can unlink one, and +//! every transition must be remembered. This store is that state: +//! +//! - `identities` — one row per (provider, subject): status +//! (`active` | `unlinked`), link/unlink timestamps. Rows are never +//! hard-deleted while the account lives; unlinking flips status. +//! - `identity_events` — append-only history (`seed` | `link` | +//! `relink` | `unlink`), protected by the same no-UPDATE / +//! no-DELETE triggers as the audit table, so the continuity of +//! who-was-linked-when survives every later change. +//! +//! The provider config's identity list is the seed: at startup each +//! configured identity that the store has never seen is inserted as +//! active with a `seed` event. After that the store is authoritative. + +use rusqlite::Connection; +use std::path::Path; +use std::sync::Mutex; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityRow { + pub provider: String, + pub subject: String, + pub account_id: String, + pub status: String, // "active" | "unlinked" + pub linked_at: i64, + pub unlinked_at: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityEvent { + pub ts_unix: i64, + pub event: String, // "seed" | "link" | "relink" | "unlink" + pub provider: String, + pub subject: String, + pub account_id: String, + pub actor: String, // "config-seed" | "door-login" | "operator-cli" +} + +pub struct IdentityStore { + conn: Mutex, +} + +impl IdentityStore { + /// Open (or create) the identity database at `path`; `None` opens + /// an in-memory database (tests). + pub fn open(path: Option<&Path>) -> Result { + let conn = match path { + Some(p) => { + if let Some(parent) = p.parent() { + if !parent.as_os_str().is_empty() { + std::fs::create_dir_all(parent).map_err(|e| { + format!( + "failed to create identity db directory {}: {e}", + parent.display() + ) + })?; + } + } + Connection::open(p) + .map_err(|e| format!("failed to open identity db {}: {e}", p.display()))? + } + None => Connection::open_in_memory() + .map_err(|e| format!("failed to open in-memory identity db: {e}"))?, + }; + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS identities ( + provider TEXT NOT NULL, + subject TEXT NOT NULL, + account_id TEXT NOT NULL, + status TEXT NOT NULL, + linked_at INTEGER NOT NULL, + unlinked_at INTEGER, + PRIMARY KEY (provider, subject) + ); + CREATE TABLE IF NOT EXISTS identity_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts_unix INTEGER NOT NULL, + event TEXT NOT NULL, + provider TEXT NOT NULL, + subject TEXT NOT NULL, + account_id TEXT NOT NULL, + actor TEXT NOT NULL + ); + CREATE TRIGGER IF NOT EXISTS identity_events_no_update + BEFORE UPDATE ON identity_events BEGIN + SELECT RAISE(ABORT, 'identity history is append-only'); + END; + CREATE TRIGGER IF NOT EXISTS identity_events_no_delete + BEFORE DELETE ON identity_events BEGIN + SELECT RAISE(ABORT, 'identity history is append-only'); + END;", + ) + .map_err(|e| format!("failed to initialise identity schema: {e}"))?; + Ok(IdentityStore { + conn: Mutex::new(conn), + }) + } + + fn record_event( + conn: &Connection, + event: &str, + provider: &str, + subject: &str, + account_id: &str, + actor: &str, + ) -> Result<(), String> { + conn.execute( + "INSERT INTO identity_events (ts_unix, event, provider, subject, account_id, actor) + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + rusqlite::params![ + crate::registry::now_unix(), + event, + provider, + subject, + account_id, + actor + ], + ) + .map_err(|e| format!("identity event insert failed: {e}"))?; + Ok(()) + } + + /// Insert any configured identity the store has never seen, as + /// active, with a `seed` event. Existing rows are untouched, so + /// an operator unlink survives restarts and config re-reads. + pub fn seed( + &self, + account_id: &str, + identities: &[crate::registry::Identity], + ) -> Result<(), String> { + let conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + for id in identities { + let present: bool = conn + .query_row( + "SELECT COUNT(*) FROM identities WHERE provider = ?1 AND subject = ?2", + rusqlite::params![id.provider, id.subject], + |row| row.get::<_, i64>(0), + ) + .map(|n| n > 0) + .map_err(|e| format!("identity seed check failed: {e}"))?; + if !present { + conn.execute( + "INSERT INTO identities (provider, subject, account_id, status, linked_at, unlinked_at) + VALUES (?1, ?2, ?3, 'active', ?4, NULL)", + rusqlite::params![ + id.provider, + id.subject, + account_id, + crate::registry::now_unix() + ], + ) + .map_err(|e| format!("identity seed insert failed: {e}"))?; + Self::record_event( + &conn, + "seed", + &id.provider, + &id.subject, + account_id, + "config-seed", + )?; + } + } + Ok(()) + } + + /// Current link status of an identity: `Some("active")`, + /// `Some("unlinked")`, or `None` if the store has never seen it. + pub fn status(&self, provider: &str, subject: &str) -> Result, String> { + let conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let mut stmt = conn + .prepare("SELECT status FROM identities WHERE provider = ?1 AND subject = ?2") + .map_err(|e| format!("identity status query failed: {e}"))?; + let mut rows = stmt + .query(rusqlite::params![provider, subject]) + .map_err(|e| format!("identity status query failed: {e}"))?; + match rows + .next() + .map_err(|e| format!("identity row read failed: {e}"))? + { + Some(row) => Ok(Some( + row.get(0) + .map_err(|e| format!("identity row read failed: {e}"))?, + )), + None => Ok(None), + } + } + + /// Is this identity currently linked (active)? Store errors fail + /// closed (treated as not linked). + pub fn is_active(&self, provider: &str, subject: &str) -> bool { + matches!(self.status(provider, subject), Ok(Some(ref s)) if s == "active") + } + + /// Link an identity to the account. Returns the event recorded: + /// `"link"` (first time), `"relink"` (was unlinked), or `"none"` + /// (already active — no event written). + pub fn link( + &self, + provider: &str, + subject: &str, + account_id: &str, + actor: &str, + ) -> Result<&'static str, String> { + let mut conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let tx = conn + .transaction() + .map_err(|e| format!("identity link transaction failed: {e}"))?; + let existing: Option = { + let mut stmt = tx + .prepare("SELECT status FROM identities WHERE provider = ?1 AND subject = ?2") + .map_err(|e| format!("identity link query failed: {e}"))?; + let mut rows = stmt + .query(rusqlite::params![provider, subject]) + .map_err(|e| format!("identity link query failed: {e}"))?; + match rows + .next() + .map_err(|e| format!("identity row read failed: {e}"))? + { + Some(row) => Some( + row.get(0) + .map_err(|e| format!("identity row read failed: {e}"))?, + ), + None => None, + } + }; + let now = crate::registry::now_unix(); + let event = match existing.as_deref() { + Some("active") => "none", + Some(_) => { + tx.execute( + "UPDATE identities SET status = 'active', linked_at = ?1, unlinked_at = NULL + WHERE provider = ?2 AND subject = ?3", + rusqlite::params![now, provider, subject], + ) + .map_err(|e| format!("identity relink failed: {e}"))?; + "relink" + } + None => { + tx.execute( + "INSERT INTO identities (provider, subject, account_id, status, linked_at, unlinked_at) + VALUES (?1, ?2, ?3, 'active', ?4, NULL)", + rusqlite::params![provider, subject, account_id, now], + ) + .map_err(|e| format!("identity link insert failed: {e}"))?; + "link" + } + }; + if event != "none" { + Self::record_event(&tx, event, provider, subject, account_id, actor)?; + } + tx.commit() + .map_err(|e| format!("identity link commit failed: {e}"))?; + Ok(event) + } + + /// Unlink an identity: the row is retained with status + /// `unlinked` and the event joins the history. Returns false + /// when the identity was not active (nothing changed). + pub fn unlink(&self, provider: &str, subject: &str, actor: &str) -> Result { + let mut conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let tx = conn + .transaction() + .map_err(|e| format!("identity unlink transaction failed: {e}"))?; + let row: Option<(String, String)> = { + let mut stmt = tx + .prepare( + "SELECT status, account_id FROM identities WHERE provider = ?1 AND subject = ?2", + ) + .map_err(|e| format!("identity unlink query failed: {e}"))?; + let mut rows = stmt + .query(rusqlite::params![provider, subject]) + .map_err(|e| format!("identity unlink query failed: {e}"))?; + match rows + .next() + .map_err(|e| format!("identity row read failed: {e}"))? + { + Some(row) => Some(( + row.get(0) + .map_err(|e| format!("identity row read failed: {e}"))?, + row.get(1) + .map_err(|e| format!("identity row read failed: {e}"))?, + )), + None => None, + } + }; + let changed = match row { + Some((ref status, ref account_id)) if status == "active" => { + tx.execute( + "UPDATE identities SET status = 'unlinked', unlinked_at = ?1 + WHERE provider = ?2 AND subject = ?3", + rusqlite::params![crate::registry::now_unix(), provider, subject], + ) + .map_err(|e| format!("identity unlink failed: {e}"))?; + Self::record_event(&tx, "unlink", provider, subject, account_id, actor)?; + true + } + _ => false, + }; + tx.commit() + .map_err(|e| format!("identity unlink commit failed: {e}"))?; + Ok(changed) + } + + /// All identity rows (operator read / tests). + pub fn list(&self) -> Result, String> { + let conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let mut stmt = conn + .prepare( + "SELECT provider, subject, account_id, status, linked_at, unlinked_at + FROM identities ORDER BY provider, subject", + ) + .map_err(|e| format!("identity list query failed: {e}"))?; + let rows = stmt + .query_map([], |row| { + Ok(IdentityRow { + provider: row.get(0)?, + subject: row.get(1)?, + account_id: row.get(2)?, + status: row.get(3)?, + linked_at: row.get(4)?, + unlinked_at: row.get(5)?, + }) + }) + .map_err(|e| format!("identity list query failed: {e}"))?; + let mut out = Vec::new(); + for r in rows { + out.push(r.map_err(|e| format!("identity row read failed: {e}"))?); + } + Ok(out) + } + + /// The full append-only event history, in order. + pub fn events(&self) -> Result, String> { + let conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let mut stmt = conn + .prepare( + "SELECT ts_unix, event, provider, subject, account_id, actor + FROM identity_events ORDER BY id ASC", + ) + .map_err(|e| format!("identity events query failed: {e}"))?; + let rows = stmt + .query_map([], |row| { + Ok(IdentityEvent { + ts_unix: row.get(0)?, + event: row.get(1)?, + provider: row.get(2)?, + subject: row.get(3)?, + account_id: row.get(4)?, + actor: row.get(5)?, + }) + }) + .map_err(|e| format!("identity events query failed: {e}"))?; + let mut out = Vec::new(); + for r in rows { + out.push(r.map_err(|e| format!("identity event read failed: {e}"))?); + } + Ok(out) + } +} diff --git a/pkgs/idp-provider/src/lib.rs b/pkgs/idp-provider/src/lib.rs index b59d9a8026..2548c45fca 100644 --- a/pkgs/idp-provider/src/lib.rs +++ b/pkgs/idp-provider/src/lib.rs @@ -6,6 +6,11 @@ //! completing the authorization-code + PKCE (S256) flow, signed //! RS256 with the Slice 2 OIDC private key. //! +//! The federated doors (#13411 GitHub, #13412 Google, #13414 +//! Microsoft) hang off `/door/{name}/start|callback` and link into +//! the same account row; link state lives in the runtime identity +//! store (#13415), seeded from the provider config. +//! //! The JWKS `kid` is the certificate's SHA-256 thumbprint in //! base64url form — the `x5t#S256` convention recorded on #13686 — so //! relying parties can pin either form. The private key is loaded @@ -19,21 +24,26 @@ //! path; SSO never rebinds an id key (#2060). pub mod audit; +pub mod doors; pub mod flow; +pub mod identities; pub mod registry; pub mod signing; +pub mod upstream; use audit::AuditLog; use axum::{routing::get, Json, Router}; use base64::{engine::general_purpose::STANDARD as B64_STD, Engine as _}; use der::Decode; use flow::FlowState; +use identities::IdentityStore; use pkcs1::DecodeRsaPublicKey; use rsa::{traits::PublicKeyParts, RsaPublicKey}; use serde::Serialize; use sha2::{Digest, Sha256}; use std::path::PathBuf; use std::sync::Arc; +use upstream::DoorRuntime; use x509_cert::Certificate; pub const DEFAULT_ISSUER: &str = "http://127.0.0.1:8911"; @@ -56,6 +66,9 @@ pub struct Config { /// Audit DB path override (else the registry config's /// `audit_db_path`, else in-memory). pub audit_db_path: Option, + /// Identity store DB path override (else the registry config's + /// `identity_db_path`, else in-memory). + pub identity_db_path: Option, } impl Config { @@ -73,6 +86,9 @@ impl Config { let audit_db_path = std::env::var("IDP_PROVIDER_AUDIT_DB") .map(PathBuf::from) .ok(); + let identity_db_path = std::env::var("IDP_PROVIDER_IDENTITY_DB") + .map(PathBuf::from) + .ok(); Config { issuer: issuer.trim_end_matches('/').to_string(), bind, @@ -80,6 +96,7 @@ impl Config { provider_config_path, signing_key_path, audit_db_path, + identity_db_path, } } } @@ -232,6 +249,8 @@ pub fn build_app_with_flow(config: Config, jwks: Jwks, flow: Option Result { .clone() .or_else(|| registry.audit_db_path.clone()); let audit = Arc::new(AuditLog::open(audit_path.as_deref())?); + let identity_path = config + .identity_db_path + .clone() + .or_else(|| registry.identity_db_path.clone()); + let identities = Arc::new(IdentityStore::open(identity_path.as_deref())?); + // Resolve each door's client secret from the + // environment variable its config names (the launcher + // fills it from the vault by name). A door without its + // secret — or an OIDC door without issuer/JWKS — stays + // disabled: its start endpoint denies with an audit + // record, and the rest of the provider is unaffected. + let doors: Vec = registry + .doors + .iter() + .map(|d| { + let secret = std::env::var(&d.client_secret_env) + .ok() + .filter(|s| !s.is_empty()); + let rt = DoorRuntime { + config: d.clone(), + client_secret: secret, + }; + if !rt.enabled() { + eprintln!( + "idp-provider: door {} disabled (secret env {} unset or OIDC issuer/JWKS unconfigured)", + d.name, d.client_secret_env + ); + } + rt + }) + .collect(); Some(Arc::new(FlowState::new( registry, signer, audit, + identities, + doors, config.issuer.clone(), ))) } diff --git a/pkgs/idp-provider/src/main.rs b/pkgs/idp-provider/src/main.rs index 5c97d6a5a2..f1f4572466 100644 --- a/pkgs/idp-provider/src/main.rs +++ b/pkgs/idp-provider/src/main.rs @@ -1,13 +1,141 @@ use idp_provider::{app_from_config, Config}; +use std::sync::Arc; + +/// Operator identity-store commands (#13415): link / unlink / links. +/// +/// These run on-host against the same store the server uses. The +/// registry config path comes from `IDP_PROVIDER_CONFIG`; the store +/// path from `IDP_PROVIDER_IDENTITY_DB` or the config's +/// `identity_db_path`. Every change is written to the identity +/// history by the store and mirrored into the audit record, exactly +/// like a door-login link. Run them while the server is stopped or +/// accept that the server's in-memory view is its own connection — +/// SQLite serializes the writes either way. +fn identity_cli(args: &[String]) -> i32 { + let cfg_path = match std::env::var("IDP_PROVIDER_CONFIG") { + Ok(p) => std::path::PathBuf::from(p), + Err(_) => { + eprintln!( + "idp-provider {cmd}: IDP_PROVIDER_CONFIG is not set", + cmd = args[0] + ); + return 2; + } + }; + let registry = match idp_provider::registry::ProviderConfig::load(&cfg_path) { + Ok(r) => r, + Err(e) => { + eprintln!("idp-provider: {e}"); + return 1; + } + }; + let identity_path = std::env::var("IDP_PROVIDER_IDENTITY_DB") + .map(std::path::PathBuf::from) + .ok() + .or_else(|| registry.identity_db_path.clone()); + let store = match idp_provider::identities::IdentityStore::open(identity_path.as_deref()) { + Ok(s) => s, + Err(e) => { + eprintln!("idp-provider: {e}"); + return 1; + } + }; + // Seed first so the CLI sees the same rows the server seeded. + let _ = store.seed(®istry.account.account_id, ®istry.account.identities); + let audit_path = std::env::var("IDP_PROVIDER_AUDIT_DB") + .map(std::path::PathBuf::from) + .ok() + .or_else(|| registry.audit_db_path.clone()); + let audit = idp_provider::audit::AuditLog::open(audit_path.as_deref()) + .map(Arc::new) + .ok(); + + match args[0].as_str() { + "links" => match store.list() { + Ok(rows) => { + for r in rows { + println!( + "{}:{} account={} status={} linked_at={} unlinked_at={}", + r.provider, + r.subject, + r.account_id, + r.status, + r.linked_at, + r.unlinked_at + .map(|t| t.to_string()) + .unwrap_or_else(|| "-".into()) + ); + } + 0 + } + Err(e) => { + eprintln!("idp-provider: {e}"); + 1 + } + }, + "link" | "unlink" => { + let (provider, subject) = match (args.get(1), args.get(2)) { + (Some(p), Some(s)) => (p.clone(), s.clone()), + _ => { + eprintln!("usage: idp-provider {} ", args[0]); + return 2; + } + }; + let identity_key = format!("{provider}:{subject}"); + if args[0] == "link" { + match store.link( + &provider, + &subject, + ®istry.account.account_id, + "operator-cli", + ) { + Ok(event) => { + if event != "none" { + if let Some(a) = &audit { + let _ = a.record("link", "allowed", event, "", &identity_key); + } + } + println!("{identity_key}: {event}"); + 0 + } + Err(e) => { + eprintln!("idp-provider: {e}"); + 1 + } + } + } else { + match store.unlink(&provider, &subject, "operator-cli") { + Ok(true) => { + if let Some(a) = &audit { + let _ = a.record("unlink", "allowed", "unlink", "", &identity_key); + } + println!("{identity_key}: unlinked"); + 0 + } + Ok(false) => { + println!("{identity_key}: not active (nothing changed)"); + 0 + } + Err(e) => { + eprintln!("idp-provider: {e}"); + 1 + } + } + } + } + _ => 2, + } +} #[tokio::main] async fn main() { + let args: Vec = std::env::args().skip(1).collect(); // Operator helper (on-host only): hash a local-door credential // for the provider registry config. The credential is read from // the IDP_LOCAL_CREDENTIAL environment variable; only the // PBKDF2 hash is printed — the plaintext is never written // anywhere by this tool. - if std::env::args().nth(1).as_deref() == Some("hash-credential") { + if args.first().map(|s| s.as_str()) == Some("hash-credential") { match std::env::var("IDP_LOCAL_CREDENTIAL") { Ok(cred) if !cred.is_empty() => { println!("{}", idp_provider::registry::hash_credential(&cred)); @@ -19,6 +147,13 @@ async fn main() { } return; } + // Operator identity-store commands (#13415). + if matches!( + args.first().map(|s| s.as_str()), + Some("link") | Some("unlink") | Some("links") + ) { + std::process::exit(identity_cli(&args)); + } let config = Config::from_env(); let bind = config.bind.clone(); diff --git a/pkgs/idp-provider/src/registry.rs b/pkgs/idp-provider/src/registry.rs index 753ee6c15c..ec05db6e70 100644 --- a/pkgs/idp-provider/src/registry.rs +++ b/pkgs/idp-provider/src/registry.rs @@ -3,13 +3,18 @@ //! and the local-door credential hash. //! //! This is the provider's *config*, loaded from a JSON file whose -//! path is configured at launch. The real file lives on-host with the -//! provider (never in the repo): it carries the owner's credential +//! path is configured at launch. The real file lives on-host with +//! the provider (never in the repo): it carries the owner's credential //! HASH (PBKDF2-HMAC-SHA256 — the plaintext credential is never //! stored anywhere in the provider) and the audit DB location. The //! repo ships `config.example.json` with the hash field empty; an //! empty hash verifies nothing, so the door stays shut until the //! on-host config is written. +//! +//! Federated doors (#13411/#13412/#13414) are configured here too: +//! endpoints and client ids are config, but a door's client SECRET +//! is never in this file — the config names the environment variable +//! the launcher fills from the vault by name. use serde::Deserialize; use sha2::{Digest, Sha256}; @@ -62,6 +67,50 @@ pub struct Account { pub local_credential_hash: String, } +/// One upstream federated door. `name` is also the identity +/// provider key: identities from this door are recorded as +/// `:`. +#[derive(Clone, Debug, Deserialize)] +pub struct UpstreamDoor { + /// "github" | "google" | "microsoft" (any name works; it keys + /// the door's routes, allowlist entries, and identity rows). + pub name: String, + /// "oidc" (Google/Microsoft shape: ID token verified against + /// the upstream JWKS) or "github" (code exchange + user fetch, + /// subject = the numeric user id). + pub kind: String, + #[serde(default)] + pub display_name: String, + pub client_id: String, + /// Name of the environment variable holding the door's client + /// secret. The launcher fills it from the vault by name (e.g. + /// vault `idp.github.client-secret` -> `IDP_GITHUB_CLIENT_SECRET`); + /// the secret itself is never in this config file or the repo. + pub client_secret_env: String, + pub authorize_url: String, + pub token_url: String, + /// OIDC doors: the upstream JWKS URI ID tokens are verified + /// against. + #[serde(default)] + pub jwks_uri: Option, + /// GitHub door: the user endpoint (default + /// `https://api.github.com/user`). + #[serde(default)] + pub userinfo_url: Option, + /// OIDC doors: the expected `iss` of upstream ID tokens. + #[serde(default)] + pub issuer: Option, + /// OIDC doors: which claim names the recorded subject + /// (default `sub`; Microsoft records `oid`, falling back to + /// `sub` when absent). + #[serde(default)] + pub subject_claim: Option, + /// Scopes requested at the upstream (OIDC default `openid`; + /// GitHub default `read:user`). + #[serde(default)] + pub scopes: Vec, +} + #[derive(Clone, Debug, Deserialize)] pub struct ProviderConfig { pub account: Account, @@ -71,9 +120,16 @@ pub struct ProviderConfig { pub allowlist: Vec, #[serde(default)] pub clients: Vec, + /// Federated doors, in login-form order. + #[serde(default)] + pub doors: Vec, /// Audit DB path; when absent the audit log is in-memory only. #[serde(default)] pub audit_db_path: Option, + /// Identity store DB path (#13415); when absent the link state + /// is in-memory only (tests, ephemeral runs). + #[serde(default)] + pub identity_db_path: Option, } impl ProviderConfig { @@ -91,14 +147,6 @@ impl ProviderConfig { pub fn is_allowlisted(&self, identity_key: &str) -> bool { self.allowlist.iter().any(|k| k == identity_key) } - - /// Is `provider:subject` a linked identity of the account row? - pub fn is_linked(&self, provider: &str, subject: &str) -> bool { - self.account - .identities - .iter() - .any(|i| i.provider == provider && i.subject == subject) - } } // ---------- small helpers (time, randomness, credential hashing) ---------- @@ -110,6 +158,21 @@ pub fn now_unix() -> i64 { .unwrap_or(0) } +/// Percent-encode a query component (unreserved characters pass +/// through, everything else becomes `%XX`). +pub fn url_encode(s: &str) -> String { + let mut out = String::new(); + for b in s.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(b as char) + } + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + /// Random bytes from the OS (`/dev/urandom`); used for authorization /// codes, token ids, and credential salts. pub fn random_bytes(n: usize) -> Vec { diff --git a/pkgs/idp-provider/src/upstream.rs b/pkgs/idp-provider/src/upstream.rs new file mode 100644 index 0000000000..9f2c701ba6 --- /dev/null +++ b/pkgs/idp-provider/src/upstream.rs @@ -0,0 +1,303 @@ +//! Upstream federated doors (#13411 GitHub, #13412 Google, #13414 +//! Microsoft): the HTTP client side of talking to an upstream +//! identity provider — authorization-code exchange, upstream +//! ID-token verification against the upstream's JWKS, and the +//! GitHub user fetch. +//! +//! A door's client secret is never in the repo or the provider +//! config file: the config names an environment variable +//! (`client_secret_env`), and the launcher fills it from the vault +//! by name — the same pattern as `idp.ca-passphrase` for the +//! signing key. A door whose secret is absent (or, for OIDC doors, +//! whose expected issuer is unconfigured) is disabled at startup: +//! its start endpoint denies with an audit record and nothing else +//! about the provider changes. +//! +//! Error strings from this module never include upstream response +//! bodies, tokens, or the client secret — an upstream failure is a +//! reason string, not a transcript. + +use crate::registry::UpstreamDoor; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64URL, Engine as _}; +use rsa::pkcs1v15::{Signature, VerifyingKey}; +use rsa::signature::Verifier as _; +use rsa::{BigUint, RsaPublicKey}; +use sha2::Sha256; + +#[derive(Clone)] +pub struct DoorRuntime { + pub config: UpstreamDoor, + /// The door's client secret, resolved from the configured + /// environment variable at startup. `None` = door disabled. + pub client_secret: Option, +} + +impl DoorRuntime { + pub fn name(&self) -> &str { + &self.config.name + } + + pub fn enabled(&self) -> bool { + if self.client_secret.is_none() { + return false; + } + // OIDC doors additionally require the expected issuer and a + // JWKS URI: without them there is nothing to verify against. + if self.config.kind == "oidc" { + return self.config.issuer.is_some() && self.config.jwks_uri.is_some(); + } + true + } + + /// The identity provider key this door mints (`github`, + /// `google`, ...). Allowlist and identity keys are + /// `:`. + pub fn identity_provider(&self) -> &str { + &self.config.name + } + + /// The callback URL the upstream returns to. + pub fn callback_uri(&self, issuer: &str) -> String { + format!("{issuer}/door/{}/callback", self.config.name) + } +} + +/// One RSA key from an upstream JWKS document. +pub struct UpstreamJwk { + pub kid: Option, + pub pubkey: RsaPublicKey, +} + +fn b64url_decode(s: &str) -> Result, String> { + B64URL + .decode(s) + .map_err(|e| format!("base64url decode failed: {e}")) +} + +/// Parse an upstream JWKS JSON document into RSA public keys. +/// Non-RSA keys are skipped (this provider verifies RS256 only). +pub fn parse_upstream_jwks(doc: &serde_json::Value) -> Result, String> { + let keys = doc["keys"] + .as_array() + .ok_or("upstream JWKS has no keys array")?; + let mut out = Vec::new(); + for k in keys { + if k["kty"] != "RSA" { + continue; + } + let (n_s, e_s) = match (k["n"].as_str(), k["e"].as_str()) { + (Some(n), Some(e)) => (n, e), + _ => continue, + }; + let n = BigUint::from_bytes_be(&b64url_decode(n_s)?); + let e = BigUint::from_bytes_be(&b64url_decode(e_s)?); + let pubkey = RsaPublicKey::new(n, e).map_err(|e| format!("upstream JWK invalid: {e}"))?; + out.push(UpstreamJwk { + kid: k["kid"].as_str().map(|s| s.to_string()), + pubkey, + }); + } + if out.is_empty() { + return Err("upstream JWKS contains no usable RSA keys".to_string()); + } + Ok(out) +} + +/// Verify a compact JWS (RS256) against an explicit RSA public key +/// and return (header, claims). Signature only — claim validation +/// (iss/aud/exp/nonce) is the caller's job. +pub fn verify_rs256( + token: &str, + pubkey: &RsaPublicKey, +) -> Result<(serde_json::Value, serde_json::Value), String> { + let parts: Vec<&str> = token.split('.').collect(); + if parts.len() != 3 { + return Err("token is not a compact JWS".to_string()); + } + let header: serde_json::Value = + serde_json::from_slice(&b64url_decode(parts[0])?).map_err(|_| "bad jwt header")?; + if header["alg"] != "RS256" { + return Err("unexpected jwt alg".to_string()); + } + let signature_bytes = b64url_decode(parts[2])?; + let signature = Signature::try_from(signature_bytes.as_slice()) + .map_err(|_| "bad jwt signature encoding")?; + let verifying_key = VerifyingKey::::new(pubkey.clone()); + verifying_key + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) + .map_err(|_| "jwt signature verification failed")?; + let claims: serde_json::Value = + serde_json::from_slice(&b64url_decode(parts[1])?).map_err(|_| "bad jwt claims")?; + Ok((header, claims)) +} + +/// Fetch and parse an upstream JWKS document. +pub async fn fetch_upstream_jwks( + http: &reqwest::Client, + uri: &str, +) -> Result, String> { + let doc: serde_json::Value = http + .get(uri) + .send() + .await + .map_err(|_| "upstream JWKS fetch failed".to_string())? + .error_for_status() + .map_err(|_| "upstream JWKS fetch failed".to_string())? + .json() + .await + .map_err(|_| "upstream JWKS fetch failed".to_string())?; + parse_upstream_jwks(&doc) +} + +/// Exchange an authorization code at the upstream token endpoint. +/// Returns the token endpoint's JSON document. For OIDC doors the +/// PKCE verifier is included; GitHub's token endpoint is asked for +/// JSON explicitly. +pub async fn exchange_upstream_code( + http: &reqwest::Client, + door: &DoorRuntime, + code: &str, + redirect_uri: &str, + pkce_verifier: Option<&str>, +) -> Result { + let secret = door + .client_secret + .as_deref() + .ok_or("door is not configured")?; + let mut form: Vec<(&str, &str)> = vec![ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", redirect_uri), + ("client_id", door.config.client_id.as_str()), + ("client_secret", secret), + ]; + if let Some(v) = pkce_verifier { + form.push(("code_verifier", v)); + } + let doc: serde_json::Value = http + .post(&door.config.token_url) + .header(reqwest::header::ACCEPT, "application/json") + .form(&form) + .send() + .await + .map_err(|_| "upstream token exchange failed".to_string())? + .error_for_status() + .map_err(|_| "upstream token exchange failed".to_string())? + .json() + .await + .map_err(|_| "upstream token exchange failed".to_string())?; + Ok(doc) +} + +/// Verify an upstream OIDC ID token: signature against the +/// upstream JWKS (selected by the header `kid`), then iss / aud / +/// exp / nonce. Returns the token's claims. +pub fn verify_upstream_id_token( + id_token: &str, + jwks: &[UpstreamJwk], + door: &DoorRuntime, + expected_nonce: Option<&str>, + now: i64, +) -> Result { + // Select the verification key by the header kid; fall back to + // trying every key when the token carries no kid. + let header: serde_json::Value = { + let parts: Vec<&str> = id_token.split('.').collect(); + if parts.len() != 3 { + return Err("upstream id token is not a compact JWS".to_string()); + } + serde_json::from_slice(&b64url_decode(parts[0])?).map_err(|_| "bad jwt header")? + }; + let kid = header["kid"].as_str(); + let candidates: Vec<&UpstreamJwk> = match kid { + Some(k) => jwks + .iter() + .filter(|j| j.kid.as_deref() == Some(k)) + .collect(), + None => jwks.iter().collect(), + }; + if candidates.is_empty() { + return Err("upstream id token kid not found in JWKS".to_string()); + } + let mut claims = None; + for jwk in candidates { + if let Ok((_, c)) = verify_rs256(id_token, &jwk.pubkey) { + claims = Some(c); + break; + } + } + let claims = claims.ok_or("upstream id token signature verification failed")?; + + let expected_iss = door.config.issuer.as_deref().unwrap_or(""); + if claims["iss"].as_str() != Some(expected_iss) { + return Err("upstream id token issuer mismatch".to_string()); + } + let aud_ok = match &claims["aud"] { + serde_json::Value::String(s) => s == &door.config.client_id, + serde_json::Value::Array(a) => a + .iter() + .any(|v| v.as_str() == Some(door.config.client_id.as_str())), + _ => false, + }; + if !aud_ok { + return Err("upstream id token audience mismatch".to_string()); + } + if claims["exp"].as_i64().unwrap_or(0) <= now { + return Err("upstream id token expired".to_string()); + } + if let Some(nonce) = expected_nonce { + if claims["nonce"].as_str() != Some(nonce) { + return Err("upstream id token nonce mismatch".to_string()); + } + } + Ok(claims) +} + +/// The subject this door records for a verified upstream identity. +/// OIDC doors use the configured subject claim (`sub` by default; +/// Microsoft records `oid`, falling back to `sub` when absent). +/// GitHub uses the numeric user id from the user document. +pub fn subject_from_claims(door: &DoorRuntime, claims: &serde_json::Value) -> Option { + if door.config.kind == "github" { + return claims["id"] + .as_i64() + .map(|n| n.to_string()) + .or_else(|| claims["id"].as_str().map(|s| s.to_string())); + } + let primary = door.config.subject_claim.as_deref().unwrap_or("sub"); + claims[primary] + .as_str() + .map(|s| s.to_string()) + .or_else(|| claims["sub"].as_str().map(|s| s.to_string())) +} + +/// Fetch the GitHub user document for an upstream access token; +/// the subject is its numeric `id`. +pub async fn fetch_github_user( + http: &reqwest::Client, + door: &DoorRuntime, + access_token: &str, +) -> Result { + let url = door + .config + .userinfo_url + .as_deref() + .unwrap_or("https://api.github.com/user"); + let doc: serde_json::Value = http + .get(url) + .header( + reqwest::header::AUTHORIZATION, + format!("Bearer {access_token}"), + ) + .header(reqwest::header::ACCEPT, "application/vnd.github+json") + .header(reqwest::header::USER_AGENT, "devtoday-idp-provider") + .send() + .await + .map_err(|_| "upstream user fetch failed".to_string())? + .error_for_status() + .map_err(|_| "upstream user fetch failed".to_string())? + .json() + .await + .map_err(|_| "upstream user fetch failed".to_string())?; + Ok(doc) +} diff --git a/pkgs/idp-provider/tests/doors.rs b/pkgs/idp-provider/tests/doors.rs new file mode 100644 index 0000000000..35c9ab4f30 --- /dev/null +++ b/pkgs/idp-provider/tests/doors.rs @@ -0,0 +1,692 @@ +//! Door tests (#13411/#13412/#13414 + linking #13415): the full +//! federated login loop over real HTTP against mock upstreams — +//! a Google-shaped OIDC upstream (authorize/token/JWKS, PKCE and +//! nonce enforced by the mock, ID tokens signed by a throwaway +//! key) and a GitHub-shaped OAuth upstream (code exchange + user +//! fetch, numeric id subject). +//! +//! Proven here: a door login mints tokens for the SAME account as +//! the local door; a first allowlisted login links the identity +//! (audited, history written); a non-allowlisted upstream identity +//! is denied and audited; an operator-unlinked identity is denied +//! while the account stays reachable via the local door, with the +//! history intact; door state handles are single-use; a door +//! without its client secret denies at start. + +use axum::{ + extract::{Form, Query, State}, + http::{header, HeaderMap, StatusCode}, + response::{IntoResponse, Response}, + routing::{get, post}, + Json, Router, +}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64URL, Engine as _}; +use idp_provider::audit::AuditLog; +use idp_provider::flow::FlowState; +use idp_provider::identities::IdentityStore; +use idp_provider::registry::{now_unix, Account, Client, Identity, ProviderConfig, UpstreamDoor}; +use idp_provider::signing::TokenSigner; +use idp_provider::upstream::DoorRuntime; +use idp_provider::{b64url, build_app_with_flow, Config, Jwk, Jwks}; +use rand_core::OsRng; +use rsa::pkcs1v15::{Signature, VerifyingKey}; +use rsa::signature::Verifier; +use rsa::traits::PublicKeyParts; +use rsa::{BigUint, RsaPrivateKey, RsaPublicKey}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +const CLIENT_ID: &str = "test-rp"; +const RP_REDIRECT: &str = "http://127.0.0.1:8912/callback"; +const GOOGLE_SUB: &str = "drew-google-sub"; +const GITHUB_ID: i64 = 424242; +const OWNER_CREDENTIAL: &str = "test-owner-credential"; +const ROLES: [&str; 4] = ["owner", "orchestrator", "agent", "read-only"]; + +// ---------------- mock upstreams ---------------- + +struct MockState { + key: RsaPrivateKey, + issuer: String, + client_id: String, + subject: Mutex, + github_id: Mutex, + last_nonce: Mutex>, + last_challenge: Mutex>, +} + +fn mock_app(state: Arc) -> Router { + Router::new() + .route("/oidc/authorize", get(mock_oidc_authorize)) + .route("/oidc/token", post(mock_oidc_token)) + .route("/oidc/jwks", get(mock_oidc_jwks)) + .route("/gh/authorize", get(mock_gh_authorize)) + .route("/gh/token", post(mock_gh_token)) + .route("/gh/user", get(mock_gh_user)) + .with_state(state) +} + +async fn mock_oidc_authorize( + State(m): State>, + Query(q): Query>, +) -> Response { + *m.last_nonce.lock().unwrap() = q.get("nonce").cloned(); + *m.last_challenge.lock().unwrap() = q.get("code_challenge").cloned(); + let redirect = q.get("redirect_uri").cloned().unwrap_or_default(); + let state = q.get("state").cloned().unwrap_or_default(); + ( + StatusCode::FOUND, + [( + header::LOCATION, + format!("{redirect}?code=mockcode&state={state}"), + )], + ) + .into_response() +} + +async fn mock_oidc_token( + State(m): State>, + Form(f): Form>, +) -> Response { + if f.get("code").map(|s| s.as_str()) != Some("mockcode") { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "bad_code"})), + ) + .into_response(); + } + // The mock enforces PKCE: S256(verifier) must equal the + // challenge it saw at authorize time. + let verifier = f.get("code_verifier").cloned().unwrap_or_default(); + let computed = b64url(&Sha256::digest(verifier.as_bytes())); + if m.last_challenge.lock().unwrap().as_deref() != Some(computed.as_str()) { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "pkce_failed"})), + ) + .into_response(); + } + let now = now_unix(); + let mut claims = serde_json::json!({ + "iss": m.issuer, + "sub": *m.subject.lock().unwrap(), + "aud": m.client_id, + "iat": now, + "exp": now + 600, + }); + if let Some(nonce) = m.last_nonce.lock().unwrap().clone() { + claims["nonce"] = serde_json::Value::String(nonce); + } + let signer = TokenSigner::new(m.key.clone(), "mock-kid".to_string()); + let id_token = signer.sign_jwt(&claims).expect("mock signing"); + Json(serde_json::json!({ + "access_token": "mock-access-token", + "id_token": id_token, + "token_type": "Bearer", + "expires_in": 600, + })) + .into_response() +} + +async fn mock_oidc_jwks(State(m): State>) -> Response { + let pubkey = RsaPublicKey::from(&m.key); + Json(serde_json::json!({ + "keys": [{ + "kty": "RSA", + "use": "sig", + "alg": "RS256", + "kid": "mock-kid", + "n": b64url(&pubkey.n().to_bytes_be()), + "e": b64url(&pubkey.e().to_bytes_be()), + }] + })) + .into_response() +} + +async fn mock_gh_authorize(Query(q): Query>) -> Response { + let redirect = q.get("redirect_uri").cloned().unwrap_or_default(); + let state = q.get("state").cloned().unwrap_or_default(); + ( + StatusCode::FOUND, + [( + header::LOCATION, + format!("{redirect}?code=ghcode&state={state}"), + )], + ) + .into_response() +} + +async fn mock_gh_token(Form(f): Form>) -> Response { + if f.get("code").map(|s| s.as_str()) != Some("ghcode") { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "bad_code"})), + ) + .into_response(); + } + Json(serde_json::json!({ + "access_token": "mock-gh-token", + "scope": "read:user", + "token_type": "bearer", + })) + .into_response() +} + +async fn mock_gh_user(State(m): State>, headers: HeaderMap) -> Response { + let auth = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + if auth != "Bearer mock-gh-token" { + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({"error": "bad_token"})), + ) + .into_response(); + } + Json(serde_json::json!({ + "id": *m.github_id.lock().unwrap(), + "login": "drew", + })) + .into_response() +} + +// ---------------- harness ---------------- + +struct Harness { + issuer: String, + client: reqwest::Client, + audit: Arc, + identities: Arc, + mock: Arc, + provider_pubkey: RsaPublicKey, +} + +async fn harness() -> Harness { + let mut rng = OsRng; + // Mock upstream first (its port feeds the door config). + let mock_listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock"); + let mock_base = format!("http://{}", mock_listener.local_addr().unwrap()); + let mock = Arc::new(MockState { + key: RsaPrivateKey::new(&mut rng, 2048).expect("mock key"), + issuer: mock_base.clone(), + client_id: "mock-google-client".to_string(), + subject: Mutex::new(GOOGLE_SUB.to_string()), + github_id: Mutex::new(GITHUB_ID), + last_nonce: Mutex::new(None), + last_challenge: Mutex::new(None), + }); + let mock2 = mock.clone(); + tokio::spawn(async move { + axum::serve(mock_listener, mock_app(mock2)).await.unwrap(); + }); + + // Provider listener next (its port is the issuer). + let prov_listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind provider"); + let issuer = format!("http://{}", prov_listener.local_addr().unwrap()); + + let provider_key = RsaPrivateKey::new(&mut rng, 2048).expect("provider key"); + let provider_pubkey = RsaPublicKey::from(&provider_key); + let kid = "test-kid".to_string(); + let jwks = Jwks { + keys: vec![Jwk { + kty: "RSA".to_string(), + use_: "sig".to_string(), + alg: "RS256".to_string(), + kid: kid.clone(), + x5t_s256: kid.clone(), + n: b64url(&provider_pubkey.n().to_bytes_be()), + e: b64url(&provider_pubkey.e().to_bytes_be()), + }], + }; + let credential_hash = { + let salt = b"0123456789abcdef"; + let hash = idp_provider::registry::pbkdf2_sha256(OWNER_CREDENTIAL.as_bytes(), salt, 1000); + format!("pbkdf2-sha256$1000${}${}", b64url(salt), b64url(&hash)) + }; + let registry = ProviderConfig { + account: Account { + account_id: "drew".to_string(), + display_name: "Drew".to_string(), + roles: ROLES.iter().map(|s| s.to_string()).collect(), + identities: vec![Identity { + provider: "devtoday-local".to_string(), + subject: "drew".to_string(), + }], + local_credential_hash: credential_hash, + }, + allowlist: vec![ + "devtoday-local:drew".to_string(), + format!("google:{GOOGLE_SUB}"), + format!("github:{GITHUB_ID}"), + ], + clients: vec![Client { + client_id: CLIENT_ID.to_string(), + name: "Test RP".to_string(), + redirect_uris: vec![RP_REDIRECT.to_string()], + }], + doors: vec![ + UpstreamDoor { + name: "google".to_string(), + kind: "oidc".to_string(), + display_name: "Google".to_string(), + client_id: "mock-google-client".to_string(), + client_secret_env: "UNUSED_IN_TESTS".to_string(), + authorize_url: format!("{mock_base}/oidc/authorize"), + token_url: format!("{mock_base}/oidc/token"), + jwks_uri: Some(format!("{mock_base}/oidc/jwks")), + userinfo_url: None, + issuer: Some(mock_base.clone()), + subject_claim: None, + scopes: vec!["openid".to_string()], + }, + UpstreamDoor { + name: "github".to_string(), + kind: "github".to_string(), + display_name: "GitHub".to_string(), + client_id: "mock-gh-client".to_string(), + client_secret_env: "UNUSED_IN_TESTS".to_string(), + authorize_url: format!("{mock_base}/gh/authorize"), + token_url: format!("{mock_base}/gh/token"), + jwks_uri: None, + userinfo_url: Some(format!("{mock_base}/gh/user")), + issuer: None, + subject_claim: None, + scopes: vec!["read:user".to_string()], + }, + UpstreamDoor { + name: "microsoft".to_string(), + kind: "oidc".to_string(), + display_name: "Microsoft".to_string(), + client_id: "mock-ms-client".to_string(), + client_secret_env: "UNUSED_IN_TESTS".to_string(), + authorize_url: format!("{mock_base}/oidc/authorize"), + token_url: format!("{mock_base}/oidc/token"), + jwks_uri: Some(format!("{mock_base}/oidc/jwks")), + userinfo_url: None, + issuer: Some(mock_base.clone()), + subject_claim: Some("oid".to_string()), + scopes: vec!["openid".to_string()], + }, + ], + audit_db_path: None, + identity_db_path: None, + }; + let audit = Arc::new(AuditLog::open(None).expect("audit")); + let identities = Arc::new(IdentityStore::open(None).expect("identity store")); + let doors = vec![ + DoorRuntime { + config: registry.doors[0].clone(), + client_secret: Some("mock-secret".to_string()), + }, + DoorRuntime { + config: registry.doors[1].clone(), + client_secret: Some("mock-secret".to_string()), + }, + // Microsoft is configured but its secret never arrived: + // the door must stay disabled. + DoorRuntime { + config: registry.doors[2].clone(), + client_secret: None, + }, + ]; + let flow = Arc::new(FlowState::new( + registry, + TokenSigner::new(provider_key, kid), + audit.clone(), + identities.clone(), + doors, + issuer.clone(), + )); + let config = Config { + issuer: issuer.clone(), + bind: "127.0.0.1:0".to_string(), + oidc_cert_path: PathBuf::new(), + provider_config_path: None, + signing_key_path: None, + audit_db_path: None, + identity_db_path: None, + }; + let app = build_app_with_flow(config, jwks, Some(flow)); + tokio::spawn(async move { + axum::serve(prov_listener, app).await.unwrap(); + }); + + Harness { + issuer, + client: reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(), + audit, + identities, + mock, + provider_pubkey, + } +} + +fn pkce() -> (String, String) { + let verifier = "test-verifier-0123456789-abcdefghijklmnopqrstuvwxyz"; + let challenge = b64url(&Sha256::digest(verifier.as_bytes())); + (verifier.to_string(), challenge) +} + +fn authorize_query() -> String { + let (_, challenge) = pkce(); + format!( + "response_type=code&client_id={CLIENT_ID}&redirect_uri={}&scope=openid&state=rpstate&nonce=rpnonce&code_challenge={challenge}&code_challenge_method=S256", + url_encode(RP_REDIRECT) + ) +} + +fn url_encode(s: &str) -> String { + idp_provider::registry::url_encode(s) +} + +fn location(resp: &reqwest::Response) -> String { + resp.headers() + .get(header::LOCATION) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_string() +} + +/// Drive one door login from the RP authorize URL through the +/// upstream and back. Returns the final callback response. +async fn drive_door(h: &Harness, door: &str) -> reqwest::Response { + let q = authorize_query(); + let start = format!("{}/door/{door}/start?{q}", h.issuer); + let resp = h.client.get(&start).send().await.expect("door start"); + assert_eq!(resp.status(), 302, "door start should redirect upstream"); + let upstream_url = location(&resp); + assert!( + upstream_url.contains("/authorize"), + "upstream redirect: {upstream_url}" + ); + let resp = h + .client + .get(&upstream_url) + .send() + .await + .expect("upstream authorize"); + assert_eq!(resp.status(), 302, "upstream should redirect back"); + let callback_url = location(&resp); + assert!( + callback_url.contains(&format!("/door/{door}/callback")), + "callback url: {callback_url}" + ); + h.client + .get(&callback_url) + .send() + .await + .expect("door callback") +} + +/// Exchange a code from a callback redirect Location for tokens +/// and verify the ID token against the harness's provider key. +async fn exchange_and_verify(h: &Harness, loc: &str) -> serde_json::Value { + let code = loc + .split("code=") + .nth(1) + .and_then(|s| s.split('&').next()) + .expect("code in redirect") + .to_string(); + let (verifier, _) = pkce(); + let resp = h + .client + .post(format!("{}/token", h.issuer)) + .form(&[ + ("grant_type", "authorization_code"), + ("code", code.as_str()), + ("redirect_uri", RP_REDIRECT), + ("client_id", CLIENT_ID), + ("code_verifier", verifier.as_str()), + ]) + .send() + .await + .expect("token exchange"); + assert_eq!(resp.status(), 200, "token exchange succeeds"); + let doc: serde_json::Value = resp.json().await.expect("token json"); + let id_token = doc["id_token"].as_str().expect("id token"); + verify_with(id_token, &h.provider_pubkey) +} + +fn verify_with(token: &str, pubkey: &RsaPublicKey) -> serde_json::Value { + let parts: Vec<&str> = token.split('.').collect(); + assert_eq!(parts.len(), 3); + let sig_bytes = B64URL.decode(parts[2]).unwrap(); + let signature = Signature::try_from(sig_bytes.as_slice()).unwrap(); + VerifyingKey::::new(pubkey.clone()) + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) + .expect("id token signature verifies"); + serde_json::from_slice(&B64URL.decode(parts[1]).unwrap()).unwrap() +} + +fn audit_has(h: &Harness, endpoint: &str, outcome: &str, reason: &str, identity: &str) -> bool { + h.audit.entries().unwrap().iter().any(|e| { + e.endpoint == endpoint + && e.outcome == outcome + && e.reason == reason + && e.identity == identity + }) +} + +// ---------------- tests ---------------- + +#[tokio::test] +async fn login_form_lists_enabled_doors_only() { + let h = harness().await; + let resp = h + .client + .get(format!("{}/authorize?{}", h.issuer, authorize_query())) + .send() + .await + .expect("authorize form"); + assert_eq!(resp.status(), 200); + let body = resp.text().await.unwrap(); + assert!(body.contains("/door/google/start"), "google listed"); + assert!(body.contains("/door/github/start"), "github listed"); + assert!( + !body.contains("/door/microsoft/start"), + "disabled door not listed" + ); +} + +#[tokio::test] +async fn google_door_full_loop_links_and_reaches_same_account() { + let h = harness().await; + let resp = drive_door(&h, "google").await; + assert_eq!(resp.status(), 302, "callback redirects to the RP"); + assert!( + location(&resp).contains("state=rpstate"), + "rp state echoed to the RP" + ); + let claims = exchange_and_verify(&h, &location(&resp)).await; + assert_eq!(claims["sub"], "drew", "same account as the local door"); + assert_eq!(claims["preferred_username"], format!("google:{GOOGLE_SUB}")); + assert_eq!( + claims["roles"], + serde_json::json!(ROLES), + "account role set on the token" + ); + // First login linked the identity: store row active, history + // has the link, and the audit record carries both events. + assert!(h.identities.is_active("google", GOOGLE_SUB)); + let events = h.identities.events().unwrap(); + assert!(events.iter().any(|e| e.event == "link" + && e.provider == "google" + && e.subject == GOOGLE_SUB + && e.actor == "door-login")); + assert!(audit_has( + &h, + "link", + "allowed", + "link", + &format!("google:{GOOGLE_SUB}") + )); + assert!(audit_has( + &h, + "door/google", + "allowed", + "code_issued", + &format!("google:{GOOGLE_SUB}") + )); + + // Second login: already linked — succeeds, no second link event. + let resp = drive_door(&h, "google").await; + assert_eq!(resp.status(), 302); + let _ = exchange_and_verify(&h, &location(&resp)).await; + let link_events = h + .identities + .events() + .unwrap() + .iter() + .filter(|e| e.event == "link" && e.provider == "google") + .count(); + assert_eq!(link_events, 1, "link recorded once"); +} + +#[tokio::test] +async fn github_door_full_loop_reaches_same_account() { + let h = harness().await; + let resp = drive_door(&h, "github").await; + assert_eq!(resp.status(), 302); + let claims = exchange_and_verify(&h, &location(&resp)).await; + assert_eq!(claims["sub"], "drew", "same account as the other doors"); + assert_eq!( + claims["preferred_username"], + format!("github:{GITHUB_ID}"), + "github subject is the numeric user id" + ); + assert!(h.identities.is_active("github", &GITHUB_ID.to_string())); +} + +#[tokio::test] +async fn google_door_non_allowlisted_denied_and_audited() { + let h = harness().await; + *h.mock.subject.lock().unwrap() = "mallory-sub".to_string(); + let resp = drive_door(&h, "google").await; + assert_eq!(resp.status(), 403, "non-allowlisted identity denied"); + assert!(audit_has( + &h, + "door/google", + "denied", + "not_allowlisted", + "google:mallory-sub" + )); + // No link, no row: the store never saw a linkable identity. + assert_eq!(h.identities.status("google", "mallory-sub").unwrap(), None); +} + +#[tokio::test] +async fn unlinked_identity_denied_but_account_reachable_via_local_door() { + let h = harness().await; + // Link via a first login. + let resp = drive_door(&h, "google").await; + assert_eq!(resp.status(), 302); + let _ = exchange_and_verify(&h, &location(&resp)).await; + // Operator unlinks the Google door. + assert!(h + .identities + .unlink("google", GOOGLE_SUB, "operator-cli") + .unwrap()); + // The door now denies, with the history intact. + let resp = drive_door(&h, "google").await; + assert_eq!(resp.status(), 403); + assert!(audit_has( + &h, + "door/google", + "denied", + "identity_unlinked", + &format!("google:{GOOGLE_SUB}") + )); + let rows = h.identities.list().unwrap(); + let row = rows + .iter() + .find(|r| r.provider == "google") + .expect("row retained after unlink"); + assert_eq!(row.status, "unlinked"); + assert!(row.unlinked_at.is_some()); + let events = h.identities.events().unwrap(); + assert!(events + .iter() + .any(|e| e.event == "link" && e.provider == "google")); + assert!(events + .iter() + .any(|e| e.event == "unlink" && e.provider == "google")); + + // The account is still reachable via the local door. + let (verifier, challenge) = pkce(); + let _ = verifier; + let body = format!( + "response_type=code&client_id={CLIENT_ID}&redirect_uri={}&scope=openid&state=s2&code_challenge={challenge}&code_challenge_method=S256&login_id=drew&credential={}", + url_encode(RP_REDIRECT), + url_encode(OWNER_CREDENTIAL) + ); + let resp = h + .client + .post(format!("{}/authorize", h.issuer)) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(body) + .send() + .await + .expect("local door login"); + assert_eq!(resp.status(), 302, "local door still opens the account"); + let claims = exchange_and_verify(&h, &location(&resp)).await; + assert_eq!(claims["sub"], "drew"); +} + +#[tokio::test] +async fn door_state_handle_is_single_use() { + let h = harness().await; + let q = authorize_query(); + let resp = h + .client + .get(format!("{}/door/google/start?{q}", h.issuer)) + .send() + .await + .unwrap(); + let upstream_url = location(&resp); + let resp = h.client.get(&upstream_url).send().await.unwrap(); + let callback_url = location(&resp); + let first = h.client.get(&callback_url).send().await.unwrap(); + assert_eq!(first.status(), 302, "first use succeeds"); + let replay = h.client.get(&callback_url).send().await.unwrap(); + assert_eq!(replay.status(), 400, "replayed state is denied"); + assert!(audit_has( + &h, + "door/google", + "denied", + "unknown_or_expired_state", + "" + )); +} + +#[tokio::test] +async fn disabled_door_denies_at_start() { + let h = harness().await; + let resp = h + .client + .get(format!( + "{}/door/microsoft/start?{}", + h.issuer, + authorize_query() + )) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 503, "unconfigured door denies"); + assert!(audit_has( + &h, + "door/microsoft", + "denied", + "door_not_configured", + "" + )); +} diff --git a/pkgs/idp-provider/tests/endpoints.rs b/pkgs/idp-provider/tests/endpoints.rs index 7c698f3fed..524a6669b5 100644 --- a/pkgs/idp-provider/tests/endpoints.rs +++ b/pkgs/idp-provider/tests/endpoints.rs @@ -37,6 +37,7 @@ fn test_config() -> Config { provider_config_path: None, signing_key_path: None, audit_db_path: None, + identity_db_path: None, } } diff --git a/pkgs/idp-provider/tests/flow.rs b/pkgs/idp-provider/tests/flow.rs index 47b70a2b10..85a36448c4 100644 --- a/pkgs/idp-provider/tests/flow.rs +++ b/pkgs/idp-provider/tests/flow.rs @@ -87,13 +87,20 @@ fn harness() -> Harness { redirect_uris: vec!["http://127.0.0.1:8913/callback".to_string()], }, ], + doors: vec![], audit_db_path: None, + identity_db_path: None, }; let audit = Arc::new(AuditLog::open(None).expect("in-memory audit")); + let identities = Arc::new( + idp_provider::identities::IdentityStore::open(None).expect("in-memory identity store"), + ); let flow = Arc::new(FlowState::new( registry, TokenSigner::new(key, kid.clone()), audit.clone(), + identities, + vec![], ISSUER.to_string(), )); let config = Config { @@ -103,6 +110,7 @@ fn harness() -> Harness { provider_config_path: None, signing_key_path: None, audit_db_path: None, + identity_db_path: None, }; Harness { app: build_app_with_flow(config, jwks, Some(flow)),