From 523ed73fdfcdac62f44d760faed30941c0dbbe94 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 16:15:24 +0200 Subject: [PATCH 1/9] =?UTF-8?q?feat(auth):=20rfc=200029=20green=20(verifie?= =?UTF-8?q?r)=20=E2=80=94=20local=20OIDC=20JWT=20verification?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The core `auth::oidc` module behind the `oidc` feature (RFC 0029 §3.2): - `OidcVerifier::discover` fetches the issuer's discovery document + JWKS once at construction (issuer equality enforced against the discovery `issuer` field); `verify` is local thereafter — signature against the cached keys, `iss`/`aud`/`exp`/`nbf` with the configured clock skew, claims resolved onto the RFC 0026 `(name, tenants)` binding via `tenant_claim`/`name_claim`. - JWKS rotation: an unseen `kid` triggers one throttled refetch (REFRESH_MIN_INTERVAL); keys outside the §3.2 asymmetric allow-list are skipped at cache time, each decode pins its cached key's algorithm, so `alg: none` and HMAC — including the public-key-as-HMAC-secret downgrade — never verify. - Every rejection is the same undifferentiated `None` (§3.2 no-oracle); no token, claims, or key material reaches any error/Debug surface. Two bugs caught by the first complete test run: - jsonwebtoken 10 only ships a CryptoProvider behind the umbrella `rust_crypto` feature — the granular `rsa`+`p256` selection compiled key types but panicked on every decode. The umbrella feature is now used; the allow-list stays enforced by the verifier (cache filter + per-key pin + per-decode Validation), proven by the matrix's HMAC downgrade arm against compiled-in HMAC. - `Validation.validate_nbf` defaults to off, so a token with `nbf` 300 s in the future verified. Enabled (validates when present; required set stays `exp`/`iss`/`aud`). Evidence: RFC0029.2 verification matrix (happy path + expired / premature-nbf / wrong-aud / wrong-iss / corrupted-signature / alg-none / HMAC-downgrade / non-JWT arms), RFC0029.6 rotation (new-kid refetch + removed-kid rejection), discovery issuer-mismatch/unusable-JWKS rejection — all against a local fixture issuer. Full gate: 968 passed / 0 failed, clippy pedantic, rustdoc, fmt. The ingest/query bindings (tower layer, `enforcement_store()` retirement) and the Dex testcontainers arm (.7) follow as the next slices; RFC status stays `red` until they land. Co-Authored-By: Claude Fable 5 --- Cargo.lock | 465 ++++++++++++- crates/ourios-core/Cargo.toml | 35 + .../ourios-core/src/{auth.rs => auth/mod.rs} | 21 + crates/ourios-core/src/auth/oidc.rs | 647 ++++++++++++++++++ crates/ourios-server/src/auth.rs | 2 + crates/ourios-server/src/config/file.rs | 4 + 6 files changed, 1171 insertions(+), 3 deletions(-) rename crates/ourios-core/src/{auth.rs => auth/mod.rs} (97%) create mode 100644 crates/ourios-core/src/auth/oidc.rs diff --git a/Cargo.lock b/Cargo.lock index a28209310..0f56c37d3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -460,6 +460,8 @@ dependencies = [ "percent-encoding", "pin-project-lite", "serde_core", + "serde_json", + "serde_path_to_error", "sync_wrapper", "tokio", "tower", @@ -485,12 +487,24 @@ dependencies = [ "tower-service", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bit-set" version = "0.8.0" @@ -836,6 +850,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-random" version = "0.1.18" @@ -980,6 +1000,18 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -1020,6 +1052,33 @@ dependencies = [ "memchr", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "darling" version = "0.23.0" @@ -1663,6 +1722,17 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.8" @@ -1679,7 +1749,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -1720,12 +1792,71 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "either" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "email_address" version = "0.2.9" @@ -1789,6 +1920,22 @@ dependencies = [ "web-time", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1966,6 +2113,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -2013,6 +2161,17 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "h2" version = "0.4.15" @@ -2099,6 +2258,24 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "home" version = "0.5.12" @@ -2219,6 +2396,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", + "webpki-roots", ] [[package]] @@ -2527,11 +2705,38 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "jsonwebtoken" +version = "10.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc" +dependencies = [ + "base64", + "ed25519-dalek", + "getrandom 0.2.17", + "hmac", + "js-sys", + "p256", + "p384", + "pem", + "rand 0.8.6", + "rsa", + "serde", + "serde_json", + "sha2 0.10.9", + "signature", + "simple_asn1", + "zeroize", +] + [[package]] name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] [[package]] name = "lexical-core" @@ -2738,6 +2943,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.6", + "smallvec", + "zeroize", +] + [[package]] name = "num-cmp" version = "0.1.0" @@ -2978,13 +3199,20 @@ version = "0.1.1" name = "ourios-core" version = "0.1.1" dependencies = [ + "axum", + "base64", "blake3", + "jsonwebtoken", "opentelemetry", "opentelemetry-proto", "opentelemetry_sdk", "ourios-semconv", "ourios-telemetry", + "p256", "proptest", + "rand 0.8.6", + "reqwest", + "serde", "serde_json", "subtle", "tokio", @@ -3031,7 +3259,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.11.0", "tokio", ] @@ -3163,6 +3391,30 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + [[package]] name = "page_size" version = "0.6.0" @@ -3269,6 +3521,25 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -3331,6 +3602,27 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.33" @@ -3395,6 +3687,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -3415,7 +3716,7 @@ dependencies = [ "bitflags", "num-traits", "rand 0.9.4", - "rand_chacha", + "rand_chacha 0.9.0", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -3547,13 +3848,24 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" dependencies = [ - "rand_chacha", + "rand_chacha 0.9.0", "rand_core 0.9.5", ] @@ -3568,6 +3880,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_chacha" version = "0.9.0" @@ -3578,6 +3900,15 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "rand_core" version = "0.9.5" @@ -3737,6 +4068,17 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", + "webpki-roots", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", ] [[package]] @@ -3796,6 +4138,26 @@ dependencies = [ "syn", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -3971,6 +4333,20 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -4060,6 +4436,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_repr" version = "0.1.20" @@ -4128,6 +4515,17 @@ dependencies = [ "unsafe-libyaml", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha2" version = "0.11.0" @@ -4164,6 +4562,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -4176,6 +4584,18 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + [[package]] name = "siphasher" version = "1.0.3" @@ -4210,6 +4630,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "sse-stream" version = "0.2.3" @@ -4952,6 +5388,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi" version = "0.3.9" @@ -5298,6 +5743,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "zerotrie" diff --git a/crates/ourios-core/Cargo.toml b/crates/ourios-core/Cargo.toml index e8c0f1dbc..b866cb804 100644 --- a/crates/ourios-core/Cargo.toml +++ b/crates/ourios-core/Cargo.toml @@ -48,6 +48,32 @@ opentelemetry = { version = "0.32", default-features = false, features = ["metri # counters' metric names + `ourios.tenant` attribute key (§6.8). # Zero-dep leaf crate. ourios-semconv = { path = "../ourios-semconv" } +# RFC 0029 §3.2 OIDC verification (feature `oidc`; only the two +# enforcement consumers — ourios-ingester and ourios-server — enable +# it, so the miner/parquet/wal build graphs stay untouched, per the +# RFC 0028 build-feedback posture). `jsonwebtoken` with the RustCrypto +# backend: the umbrella `rust_crypto` feature is required — the crate's +# CryptoProvider only exists behind it (granular `rsa`/`p256` compile +# key types but no provider, and every decode panics). The §3.2 +# asymmetric allow-list (RS256/ES256 family) is enforced by the +# verifier: JWKS caching keeps only allow-listed key families, each +# decode pins the cached key's algorithm, so `alg: none` and HMAC are +# rejected whatever a token's header claims. +jsonwebtoken = { version = "10", default-features = false, features = ["rust_crypto", "use_pem"], optional = true } +# JWKS discovery + rotation refetch (§3.2: the issuer is contacted at +# startup, on rotation, and on kid misses — never per request). +# Already in the dep tree via `object_store`'s S3 backend, same +# rustls stack — no new cargo-deny surface. +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"], optional = true } +# Derive for the discovery-document subset the verifier reads. +serde = { version = "1", default-features = false, features = ["derive"], optional = true } +# Async runtime types for the JWKS cache (`RwLock`) and the verifier's +# refresh path. Runtime-free feature set; the binary provides the runtime. +tokio = { version = "1", default-features = false, features = ["sync"], optional = true } + +[features] +# The RFC 0029 OIDC bearer layer (verifier + JWKS cache). +oidc = ["dep:jsonwebtoken", "dep:reqwest", "dep:serde", "dep:tokio"] [dev-dependencies] # `init_in_memory` collects the alias counters' exported metric stream @@ -58,6 +84,15 @@ ourios-telemetry = { path = "../ourios-telemetry", features = ["testing"] } # round-trip (#130). proptest = "=1.11.0" tokio = { version = "=1.52.3", default-features = false, features = ["rt", "rt-multi-thread", "macros"] } +# Loopback fixture issuer (discovery + JWKS + rotation) for the RFC 0029 +# §5.2/§5.6 verification-matrix and rotation tests — test-only. +axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] } +# Mints the fixture issuer's ES256 keypair at test runtime (instant P-256 +# keygen; no committed private-key fixtures for scanners to flag). +p256 = { version = "0.13", default-features = false, features = ["ecdsa", "pkcs8", "pem", "arithmetic"] } +rand = "0.8" +# base64url (no pad) for the fixture issuer's JWK coordinates. +base64 = "0.22" opentelemetry_sdk = { version = "=0.32.1", default-features = false, features = ["metrics", "testing"] } [lints] diff --git a/crates/ourios-core/src/auth.rs b/crates/ourios-core/src/auth/mod.rs similarity index 97% rename from crates/ourios-core/src/auth.rs rename to crates/ourios-core/src/auth/mod.rs index 0787cac5e..9b24bedae 100644 --- a/crates/ourios-core/src/auth.rs +++ b/crates/ourios-core/src/auth/mod.rs @@ -16,6 +16,9 @@ //! and validation errors name an entry's `name`/index, never its token //! (RFC 0026 §3.1 / RFC 0020 §3.5). +#[cfg(feature = "oidc")] +pub mod oidc; + use std::collections::BTreeSet; use std::fmt; @@ -69,6 +72,8 @@ pub struct OidcSpec { pub tenant_claim: Option, /// The claim feeding the audit/metric label. Defaults to `sub`. pub name_claim: Option, + /// `exp`/`nbf` clock-skew allowance in seconds (§3.2). Defaults to 60. + pub clock_skew_secs: Option, } /// The validated `auth.oidc` configuration (RFC 0029 §3.1). @@ -78,6 +83,7 @@ pub struct OidcConfig { audience: String, tenant_claim: String, name_claim: String, + clock_skew_secs: u64, } impl OidcConfig { @@ -104,6 +110,12 @@ impl OidcConfig { pub fn name_claim(&self) -> &str { &self.name_claim } + + /// The `exp`/`nbf` clock-skew allowance in seconds (§3.2). + #[must_use] + pub fn clock_skew_secs(&self) -> u64 { + self.clock_skew_secs + } } /// The resolved `auth` section (RFC 0026 §3.1 + RFC 0029 §3.1): the static @@ -180,11 +192,19 @@ pub fn build_oidc_config(spec: &OidcSpec) -> Result { None => "sub".to_string(), some => required("name_claim", some)?, }; + let clock_skew_secs = match spec.clock_skew_secs.as_deref() { + None => 60, + Some(raw) => raw.trim().parse().map_err(|_| { + "auth.oidc.clock_skew_secs must be a non-negative integer number of seconds (RFC 0029 §3.2)" + .to_string() + })?, + }; Ok(OidcConfig { issuer: required("issuer", spec.issuer.as_deref())?, audience: required("audience", spec.audience.as_deref())?, tenant_claim: required("tenant_claim", spec.tenant_claim.as_deref())?, name_claim, + clock_skew_secs, }) } @@ -488,6 +508,7 @@ mod tests { audience: Some("ourios".to_string()), tenant_claim: Some("ourios_tenants".to_string()), name_claim: None, + clock_skew_secs: None, } } diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs new file mode 100644 index 000000000..995938b6f --- /dev/null +++ b/crates/ourios-core/src/auth/oidc.rs @@ -0,0 +1,647 @@ +//! The RFC 0029 OIDC verifier: local JWT verification against a cached +//! JWKS, resolving verified claims onto the RFC 0026 `(name, tenants)` +//! binding. +//! +//! Verification is **local** (§3.2): a signature check against cached +//! keys plus `iss`/`aud`/`exp`/`nbf` validation — the issuer is contacted +//! only at construction ([`OidcVerifier::discover`]), and on unseen-`kid` +//! misses (rotation, throttled by `REFRESH_MIN_INTERVAL`). Only the +//! RFC's asymmetric allow-list verifies (`ALLOWED_ALGORITHMS`); +//! `alg: none` and HMAC — including the public-key-as-HMAC-secret +//! downgrade — are rejected by construction because they are never in +//! the validation set. +//! +//! Every rejection collapses to the one undifferentiated +//! unauthenticated-shaped `None` at the +//! resolution layer (§3.2's no-oracle rule); nothing here renders a +//! token, a claims payload, or key material into any error or `Debug` +//! surface. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use jsonwebtoken::jwk::{AlgorithmParameters, JwkSet}; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; +use tokio::sync::RwLock; + +use super::{OidcConfig, TenantSet}; + +/// The §3.2 asymmetric allow-list. `alg: none` and every HMAC variant are +/// outside this set and therefore unverifiable, whatever a token's header +/// claims. +const ALLOWED_ALGORITHMS: [Algorithm; 6] = [ + Algorithm::RS256, + Algorithm::RS384, + Algorithm::RS512, + Algorithm::ES256, + Algorithm::ES384, + // ES512 is not in `jsonwebtoken`'s Algorithm set; PS* completes the + // RSA family. + Algorithm::PS256, +]; + +/// Unseen-`kid` refresh throttle: a burst of unknown-`kid` tokens (a +/// probing client, or the window right after a rotation) collapses to one +/// JWKS fetch per interval rather than one per request. +const REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(5); + +/// The verified identity a token resolves to: the RFC 0026 binding shape, +/// derived from the configured claims' **values** (RFC 0029 §3.2). +#[derive(Debug, Clone)] +pub struct VerifiedIdentity { + /// The `name_claim` value — the audit/metric label. + pub name: String, + /// The `tenant_claim` value, validated into the RFC 0026 set. + pub tenants: TenantSet, +} + +/// Why construction failed. Startup-only; request-path failures are the +/// undifferentiated `None`. +#[derive(Debug)] +pub struct DiscoveryError(String); + +impl std::fmt::Display for DiscoveryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +impl std::error::Error for DiscoveryError {} + +/// The subset of `/.well-known/openid-configuration` the verifier needs. +#[derive(serde::Deserialize)] +struct DiscoveryDocument { + issuer: String, + jwks_uri: String, +} + +/// One cached verification key. +struct CachedKey { + key: DecodingKey, + /// The key's own algorithm family, pinned from the JWK (never from a + /// presented token's header — the header only *selects* the key). + algorithm: Algorithm, +} + +/// The RFC 0029 §3.2 verifier: config + cached JWKS + the refresh path. +pub struct OidcVerifier { + config: OidcConfig, + http: reqwest::Client, + jwks_uri: String, + keys: RwLock>, + last_refresh: RwLock, + refresh_min_interval: Duration, +} + +impl std::fmt::Debug for OidcVerifier { + /// Issuer and audience only — never key material. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OidcVerifier") + .field("issuer", &self.config.issuer()) + .field("audience", &self.config.audience()) + .finish_non_exhaustive() + } +} + +impl OidcVerifier { + /// Fetch the issuer's discovery document and initial JWKS (RFC 0029 + /// §3.2 — the startup contact). With no cached keys nothing could + /// verify, so a failure here is a startup error, not a degraded mode. + /// + /// # Errors + /// + /// [`DiscoveryError`] on an unreachable issuer, a discovery document + /// whose `issuer` disagrees with the configured one (a misdirected or + /// spoofed root would otherwise silently verify nothing), or an + /// unusable JWKS. + pub async fn discover(config: OidcConfig) -> Result { + let http = reqwest::Client::new(); + let discovery_url = format!( + "{}/.well-known/openid-configuration", + config.issuer().trim_end_matches('/') + ); + let document: DiscoveryDocument = fetch_json(&http, &discovery_url).await?; + if document.issuer.trim_end_matches('/') != config.issuer().trim_end_matches('/') { + return Err(DiscoveryError(format!( + "issuer mismatch: the discovery document names a different issuer \ + than the configured {} (RFC 0029 §3.2)", + config.issuer(), + ))); + } + let jwks: JwkSet = fetch_json(&http, &document.jwks_uri).await?; + let keys = cache_keys(&jwks); + if keys.is_empty() { + return Err(DiscoveryError( + "the issuer's JWKS holds no usable RS*/ES*/PS* keys with key ids \ + (RFC 0029 §3.2 verifies the asymmetric allow-list only)" + .to_string(), + )); + } + Ok(Self { + config, + http, + jwks_uri: document.jwks_uri, + keys: RwLock::new(keys), + last_refresh: RwLock::new(Instant::now()), + refresh_min_interval: REFRESH_MIN_INTERVAL, + }) + } + + /// Verify a presented bearer as a JWT and resolve it to the RFC 0026 + /// binding shape (§3.2). + /// + /// `None` for every rejected shape — not-a-JWT, disallowed algorithm, + /// unknown `kid` (after at most one throttled JWKS refresh), bad + /// signature, `iss`/`aud`/`exp`/`nbf` failures, or claims that do not + /// carry the configured tenant/name values. The caller maps `None` + /// onto the one undifferentiated 401; no reason leaves this function. + pub async fn verify(&self, token: &str) -> Option { + let header = decode_header(token).ok()?; + if !ALLOWED_ALGORITHMS.contains(&header.alg) { + return None; + } + let kid = header.kid?; + + let claims = if let Some(claims) = self.try_decode(token, &kid, header.alg).await { + claims + } else { + // Unseen kid (or a key swap): refresh once, throttled, and + // retry — the §3.2 rotation path. + self.refresh_keys().await?; + self.try_decode(token, &kid, header.alg).await? + }; + self.resolve_identity(&claims) + } + + /// Decode + validate against the currently cached key for `kid`. + /// `None` on an unknown kid, an alg/key family mismatch, or any + /// validation failure. + async fn try_decode( + &self, + token: &str, + kid: &str, + token_alg: Algorithm, + ) -> Option> { + let keys = self.keys.read().await; + let cached = keys.get(kid)?; + // The token's header must claim the key's own algorithm — a header + // is never allowed to re-type a key (the downgrade shape). + if cached.algorithm != token_alg { + return None; + } + let mut validation = Validation::new(cached.algorithm); + validation.set_issuer(&[self.config.issuer()]); + validation.set_audience(&[self.config.audience()]); + validation.set_required_spec_claims(&["exp", "iss", "aud"]); + // Off by default in jsonwebtoken; §3.2 validates `nbf` when the + // token carries it (it stays optional — only `exp`/`iss`/`aud` + // are required above). + validation.validate_nbf = true; + validation.leeway = self.config.clock_skew_secs(); + decode::>(token, &cached.key, &validation) + .ok() + .map(|data| data.claims) + } + + /// Map the configured claims' values onto the binding shape. `None` + /// when the tenant claim is missing/mistyped/invalid or the name claim + /// is not a non-empty string — an identity the audit surface cannot + /// label is not an identity. + fn resolve_identity( + &self, + claims: &serde_json::Map, + ) -> Option { + let name = claims.get(self.config.name_claim())?.as_str()?; + if name.is_empty() { + return None; + } + let tenants: Vec = claims + .get(self.config.tenant_claim())? + .as_array()? + .iter() + .map(|value| value.as_str().map(str::to_string)) + .collect::>()?; + let tenants = validate_tenant_list(&tenants)?; + Some(VerifiedIdentity { + name: name.to_string(), + tenants, + }) + } + + /// Refetch the JWKS (rotation / unseen kid), throttled to one fetch + /// per [`REFRESH_MIN_INTERVAL`]. `None` when throttled or when the + /// fetch fails — the cached set stays authoritative either way. + async fn refresh_keys(&self) -> Option<()> { + { + let last = self.last_refresh.read().await; + if last.elapsed() < self.refresh_min_interval { + return None; + } + } + let mut last = self.last_refresh.write().await; + // Re-check under the write lock: a concurrent refresher may have + // just fetched, and one fetch per interval is the whole point. + if last.elapsed() < self.refresh_min_interval { + return None; + } + *last = Instant::now(); + let jwks: JwkSet = fetch_json(&self.http, &self.jwks_uri).await.ok()?; + let fresh = cache_keys(&jwks); + *self.keys.write().await = fresh; + Some(()) + } +} + +/// GET + JSON-decode one document, with a bounded timeout. +async fn fetch_json( + http: &reqwest::Client, + url: &str, +) -> Result { + let response = http + .get(url) + .timeout(Duration::from_secs(10)) + .send() + .await + .and_then(reqwest::Response::error_for_status) + .map_err(|e| DiscoveryError(format!("fetch {url}: {e}")))?; + let bytes = response + .bytes() + .await + .map_err(|e| DiscoveryError(format!("read {url}: {e}")))?; + serde_json::from_slice(&bytes).map_err(|e| DiscoveryError(format!("decode {url}: {e}"))) +} + +/// Index a JWKS by `kid`, keeping only keys in the allow-list families. +/// Keys without a `kid` are skipped (the verifier selects by kid); an +/// individually malformed key is skipped rather than failing the set — +/// issuers routinely publish keys for algorithms a client does not use. +fn cache_keys(jwks: &JwkSet) -> HashMap { + let mut keys = HashMap::new(); + for jwk in &jwks.keys { + let Some(kid) = jwk.common.key_id.clone() else { + continue; + }; + let algorithm = match &jwk.algorithm { + AlgorithmParameters::RSA(_) => match jwk.common.key_algorithm { + Some(jsonwebtoken::jwk::KeyAlgorithm::RS384) => Algorithm::RS384, + Some(jsonwebtoken::jwk::KeyAlgorithm::RS512) => Algorithm::RS512, + Some(jsonwebtoken::jwk::KeyAlgorithm::PS256) => Algorithm::PS256, + _ => Algorithm::RS256, + }, + AlgorithmParameters::EllipticCurve(ec) => match ec.curve { + jsonwebtoken::jwk::EllipticCurve::P256 => Algorithm::ES256, + jsonwebtoken::jwk::EllipticCurve::P384 => Algorithm::ES384, + _ => continue, + }, + _ => continue, + }; + let Ok(key) = DecodingKey::from_jwk(jwk) else { + continue; + }; + keys.insert(kid, CachedKey { key, algorithm }); + } + keys +} + +/// Validate a tenant-claim value with the RFC 0026 §3.1 list rules (the +/// wildcard alone, else non-empty ids without surrounding whitespace). +fn validate_tenant_list(tenants: &[String]) -> Option { + if tenants.is_empty() { + return None; + } + if tenants.iter().any(|t| t == "*") { + if tenants.len() > 1 { + return None; + } + return Some(TenantSet::All); + } + if tenants.iter().any(|t| t.is_empty() || t.trim() != t) { + return None; + } + Some(TenantSet::Listed(tenants.iter().cloned().collect())) +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, RwLock as StdRwLock}; + use std::time::{SystemTime, UNIX_EPOCH}; + + use axum::Json; + use axum::extract::State; + use axum::routing::get; + use base64::Engine as _; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use jsonwebtoken::{EncodingKey, Header}; + use p256::ecdsa::SigningKey; + use p256::pkcs8::EncodePrivateKey as _; + use serde_json::{Value, json}; + + use super::super::{OidcSpec, TenantSet, build_oidc_config}; + use super::{Duration, OidcVerifier}; + + /// One fixture signing key: the private half for minting, the public + /// half as a JWK. Generated at test runtime — no committed key + /// material. + fn make_key(kid: &str) -> (EncodingKey, Value) { + let signing = SigningKey::random(&mut rand::rngs::OsRng); + let pem = signing + .to_pkcs8_pem(p256::pkcs8::LineEnding::LF) + .expect("pkcs8 pem"); + let encoding = EncodingKey::from_ec_pem(pem.as_bytes()).expect("encoding key"); + let point = signing.verifying_key().to_encoded_point(false); + let jwk = json!({ + "kty": "EC", "crv": "P-256", "use": "sig", "alg": "ES256", "kid": kid, + "x": URL_SAFE_NO_PAD.encode(point.x().expect("x")), + "y": URL_SAFE_NO_PAD.encode(point.y().expect("y")), + }); + (encoding, jwk) + } + + /// A loopback issuer serving discovery + a swappable JWKS — the §6 + /// fixture-issuer tier (no container). + async fn serve_issuer(jwks: Arc>) -> String { + serve_issuer_claiming(None, jwks).await + } + + /// The fixture, optionally publishing a discovery document that names + /// a *different* issuer than the one it serves under (the §3.2 + /// mismatch arm). + async fn serve_issuer_claiming(claimed: Option<&str>, jwks: Arc>) -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind fixture issuer"); + let issuer = format!("http://{}", listener.local_addr().expect("addr")); + let discovery = json!({ + "issuer": claimed.unwrap_or(&issuer), + "jwks_uri": format!("{issuer}/jwks"), + }); + let app = axum::Router::new() + .route( + "/.well-known/openid-configuration", + get(|State((discovery, _)): DiscState| async move { Json(discovery) }), + ) + .route( + "/jwks", + get(|State((_, jwks)): DiscState| async move { + let current = jwks.read().expect("jwks lock").clone(); + Json(current) + }), + ) + .with_state((discovery, jwks)); + tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve issuer"); + }); + issuer + } + + type DiscState = State<(Value, Arc>)>; + + fn now_secs() -> i64 { + i64::try_from( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("epoch") + .as_secs(), + ) + .expect("fits") + } + + /// Standard well-formed claims for the fixture audience. + fn claims(issuer: &str) -> Value { + json!({ + "iss": issuer, "aud": "ourios", "exp": now_secs() + 600, + "sub": "edge-collector", "ourios_tenants": ["acme", "globex"], + }) + } + + fn mint(encoding: &EncodingKey, kid: &str, claims: &Value) -> String { + let mut header = Header::new(super::Algorithm::ES256); + header.kid = Some(kid.to_string()); + jsonwebtoken::encode(&header, claims, encoding).expect("mint") + } + + fn config_for(issuer: &str) -> super::OidcConfig { + build_oidc_config(&OidcSpec { + issuer: Some(issuer.to_string()), + audience: Some("ourios".to_string()), + tenant_claim: Some("ourios_tenants".to_string()), + name_claim: None, + clock_skew_secs: Some("0".to_string()), + }) + .expect("valid config") + } + + /// Scenario RFC0029.2 — the verification matrix against the fixture + /// issuer: one valid acceptance, and every rejected shape collapsing + /// to `None` (the caller's one undifferentiated 401). + /// See `docs/rfcs/0029-oidc-bearer-layer.md` §5. + #[tokio::test] + async fn rfc0029_2_verification_matrix() { + let (encoding, jwk) = make_key("key-1"); + let jwks = Arc::new(StdRwLock::new(json!({ "keys": [jwk] }))); + let issuer = serve_issuer(jwks).await; + let verifier = OidcVerifier::discover(config_for(&issuer)) + .await + .expect("discover"); + + // (a) valid: accepted, claims' values resolve the binding. + let identity = verifier + .verify(&mint(&encoding, "key-1", &claims(&issuer))) + .await + .expect("valid token verifies"); + assert_eq!(identity.name, "edge-collector"); + assert!(identity.tenants.allows("acme")); + assert!(!identity.tenants.allows("initech")); + + // (b)–(e) claim failures: expired, nbf in the future (beyond the + // zero configured skew), wrong audience, wrong issuer. + let mut expired = claims(&issuer); + expired["exp"] = json!(now_secs() - 30); + let mut premature = claims(&issuer); + premature["nbf"] = json!(now_secs() + 300); + let mut wrong_aud = claims(&issuer); + wrong_aud["aud"] = json!("someone-else"); + let mut wrong_iss = claims(&issuer); + wrong_iss["iss"] = json!("https://evil.example"); + for (arm, bad) in [ + ("expired", &expired), + ("nbf beyond skew", &premature), + ("wrong aud", &wrong_aud), + ("wrong iss", &wrong_iss), + ] { + assert!( + verifier + .verify(&mint(&encoding, "key-1", bad)) + .await + .is_none(), + "{arm} must be rejected" + ); + } + + // (f) corrupted signature. + let valid = mint(&encoding, "key-1", &claims(&issuer)); + let corrupted = format!("{}AAAA", &valid[..valid.len() - 4]); + assert!(verifier.verify(&corrupted).await.is_none(), "bad signature"); + + // (g)/(h) algorithm shapes outside the asymmetric allow-list: + // `alg: none` and an HMAC header over the same kid (the + // public-key-as-secret downgrade). Hand-encoded — the point is the + // header, not the signature, and rejection must precede any + // signature work. + let payload = URL_SAFE_NO_PAD.encode(claims(&issuer).to_string()); + for (arm, header) in [ + ("alg none", r#"{"alg":"none","kid":"key-1"}"#), + ( + "hmac downgrade", + r#"{"alg":"HS256","typ":"JWT","kid":"key-1"}"#, + ), + ] { + let crafted = format!( + "{}.{payload}.{}", + URL_SAFE_NO_PAD.encode(header), + URL_SAFE_NO_PAD.encode("forged") + ); + assert!(verifier.verify(&crafted).await.is_none(), "{arm}"); + } + + // (i) not a JWT at all; and a JWT with no kid never matches. + assert!(verifier.verify("tok-static-shaped").await.is_none()); + let no_kid = jsonwebtoken::encode( + &Header::new(super::Algorithm::ES256), + &claims(&issuer), + &encoding, + ) + .expect("mint"); + assert!(verifier.verify(&no_kid).await.is_none(), "kid required"); + + // Claim-shape failures: a tenant claim that is not a string list, + // an empty list, a whitespace-broken id, and a missing name claim. + for (arm, mutate) in [ + ("tenant claim not a list", json!("acme")), + ("empty tenant list", json!([])), + ("whitespace tenant", json!([" acme"])), + ("wildcard plus id", json!(["*", "acme"])), + ] { + let mut bad = claims(&issuer); + bad["ourios_tenants"] = mutate; + assert!( + verifier + .verify(&mint(&encoding, "key-1", &bad)) + .await + .is_none(), + "{arm}" + ); + } + let mut no_name = claims(&issuer); + no_name.as_object_mut().expect("map").remove("sub"); + assert!( + verifier + .verify(&mint(&encoding, "key-1", &no_name)) + .await + .is_none(), + "an identity the audit surface cannot label is not an identity" + ); + + // Wildcard resolves to the RFC 0026 all-tenants set. + let mut wildcard = claims(&issuer); + wildcard["ourios_tenants"] = json!(["*"]); + let identity = verifier + .verify(&mint(&encoding, "key-1", &wildcard)) + .await + .expect("wildcard verifies"); + assert_eq!(identity.tenants, TenantSet::All); + } + + /// Scenario RFC0029.6 — JWKS rotation: an unseen `kid` triggers a + /// refetch and the new key's token verifies without restart; the + /// withdrawn key's tokens are rejected once the refreshed set drops + /// it. See `docs/rfcs/0029-oidc-bearer-layer.md` §5. + #[tokio::test] + async fn rfc0029_6_jwks_rotation() { + let (old_encoding, old_jwk) = make_key("key-old"); + let jwks = Arc::new(StdRwLock::new(json!({ "keys": [old_jwk] }))); + let issuer = serve_issuer(Arc::clone(&jwks)).await; + let mut verifier = OidcVerifier::discover(config_for(&issuer)) + .await + .expect("discover"); + // The production throttle is real time; the test injects zero so + // rotation is immediate rather than a 5-second sleep. + verifier.refresh_min_interval = Duration::ZERO; + + let old_token = mint(&old_encoding, "key-old", &claims(&issuer)); + assert!( + verifier.verify(&old_token).await.is_some(), + "pre-rotation token verifies against the startup JWKS" + ); + + // Rotate: the issuer withdraws key-old and publishes key-new. + let (new_encoding, new_jwk) = make_key("key-new"); + *jwks.write().expect("jwks lock") = json!({ "keys": [new_jwk] }); + + let new_token = mint(&new_encoding, "key-new", &claims(&issuer)); + assert!( + verifier.verify(&new_token).await.is_some(), + "unseen kid refetches the JWKS and verifies without restart" + ); + assert!( + verifier.verify(&old_token).await.is_none(), + "the withdrawn key's tokens are rejected once the set drops it" + ); + } + + /// Startup arms: a discovery document naming a different issuer and a + /// JWKS with no usable keys are construction errors, not degraded + /// modes (§3.2 — with no cached keys nothing could verify). + #[tokio::test] + async fn discovery_rejects_issuer_mismatch_and_unusable_jwks() { + let (_, jwk) = make_key("key-1"); + let jwks = Arc::new(StdRwLock::new(json!({ "keys": [jwk] }))); + let issuer = serve_issuer(jwks).await; + + let mut config = OidcSpec { + issuer: Some("https://somewhere-else.example".to_string()), + audience: Some("ourios".to_string()), + tenant_claim: Some("ourios_tenants".to_string()), + name_claim: None, + clock_skew_secs: None, + }; + // Point the config at the fixture's address under a different + // issuer name: unreachable → fetch error, which also covers the + // unreachable-issuer startup arm. + let err = OidcVerifier::discover(build_oidc_config(&config).expect("valid")) + .await + .expect_err("unreachable issuer fails startup"); + assert!(err.to_string().contains("fetch"), "{err}"); + + config.issuer = Some(issuer.clone()); + let empty = Arc::new(StdRwLock::new(json!({ "keys": [] }))); + let empty_issuer = serve_issuer(empty).await; + config.issuer = Some(empty_issuer); + let err = OidcVerifier::discover(build_oidc_config(&config).expect("valid")) + .await + .expect_err("an empty JWKS fails startup"); + assert!(err.to_string().contains("JWKS"), "{err}"); + + // Issuer mismatch: the fixture serves under its own address but + // publishes a document claiming a different issuer — a misdirected + // or spoofed discovery root fails construction, never silently + // verifies. + let (_, jwk) = make_key("key-1"); + let lying = Arc::new(StdRwLock::new(json!({ "keys": [jwk] }))); + let lying_issuer = + serve_issuer_claiming(Some("https://somewhere-else.example"), lying).await; + config.issuer = Some(lying_issuer); + let err = OidcVerifier::discover(build_oidc_config(&config).expect("valid")) + .await + .expect_err("a disagreeing discovery document fails startup"); + assert!(err.to_string().contains("issuer mismatch"), "{err}"); + + // And the agreeing fixture constructs. + config.issuer = Some(issuer); + assert!( + OidcVerifier::discover(build_oidc_config(&config).expect("valid")) + .await + .is_ok() + ); + } +} diff --git a/crates/ourios-server/src/auth.rs b/crates/ourios-server/src/auth.rs index 31cbc590c..79c596ff0 100644 --- a/crates/ourios-server/src/auth.rs +++ b/crates/ourios-server/src/auth.rs @@ -43,6 +43,7 @@ pub fn build_auth_config(section: Option<&AuthSection>) -> Result, + /// `exp`/`nbf` clock-skew allowance in seconds (default 60). + #[serde(deserialize_with = "scalar_opt")] + pub clock_skew_secs: Option, } /// One `auth.tokens[…]` entry (RFC 0026 §3.1). @@ -466,6 +469,7 @@ impl AuthSection { substitute(&mut oidc.audience, lookup)?; substitute(&mut oidc.tenant_claim, lookup)?; substitute(&mut oidc.name_claim, lookup)?; + substitute(&mut oidc.clock_skew_secs, lookup)?; } Ok(()) } From b90cce5069011a92f54b1992de9452610885de4a Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 16:37:21 +0200 Subject: [PATCH 2/9] fix(auth): refetch only on unknown kid, backdated first-refresh, full PS family MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round on the verifier: - try_decode now returns a three-way DecodeAttempt; only UnknownKid may trigger the throttled JWKS refetch — validation failures are terminal, so invalid tokens can no longer drive issuer traffic (pinned by a fixture-issuer fetch counter in the matrix test). - last_refresh is backdated one interval at construction so the FIRST unseen-kid miss refreshes immediately; the rotation test now runs under the real production throttle instead of injecting zero. - PS384/PS512 join the allow-list and the JWKS cache mapping — the "PS* completes the RSA family" comment is now true. - The unreachable-issuer arm uses a just-closed loopback port instead of an external hostname (no DNS/egress dependency in CI). Co-Authored-By: Claude Fable 5 --- crates/ourios-core/src/auth/oidc.rs | 146 +++++++++++++++++++--------- 1 file changed, 100 insertions(+), 46 deletions(-) diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index 995938b6f..f3b6f6c49 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -29,15 +29,17 @@ use super::{OidcConfig, TenantSet}; /// The §3.2 asymmetric allow-list. `alg: none` and every HMAC variant are /// outside this set and therefore unverifiable, whatever a token's header /// claims. -const ALLOWED_ALGORITHMS: [Algorithm; 6] = [ +const ALLOWED_ALGORITHMS: [Algorithm; 8] = [ Algorithm::RS256, Algorithm::RS384, Algorithm::RS512, Algorithm::ES256, + // ES512 is not in `jsonwebtoken`'s Algorithm set. Algorithm::ES384, - // ES512 is not in `jsonwebtoken`'s Algorithm set; PS* completes the - // RSA family. + // PS256/384/512 complete the RSA family. Algorithm::PS256, + Algorithm::PS384, + Algorithm::PS512, ]; /// Unseen-`kid` refresh throttle: a burst of unknown-`kid` tokens (a @@ -45,6 +47,15 @@ const ALLOWED_ALGORITHMS: [Algorithm; 6] = [ /// JWKS fetch per interval rather than one per request. const REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(5); +/// One decode attempt against the current key cache. `UnknownKid` is the +/// only outcome that may trigger a (throttled) JWKS refetch — the §3.2 +/// rotation path; everything else is a terminal rejection. +enum DecodeAttempt { + Verified(serde_json::Map), + UnknownKid, + Rejected, +} + /// The verified identity a token resolves to: the RFC 0026 binding shape, /// derived from the configured claims' **values** (RFC 0029 §3.2). #[derive(Debug, Clone)] @@ -142,7 +153,15 @@ impl OidcVerifier { http, jwks_uri: document.jwks_uri, keys: RwLock::new(keys), - last_refresh: RwLock::new(Instant::now()), + // Backdated one interval so the FIRST unseen-kid miss can + // refresh immediately — the throttle bounds the gap *between* + // refreshes, not the time to the first one (a rotation just + // before startup must not eat a 401 window). + last_refresh: RwLock::new( + Instant::now() + .checked_sub(REFRESH_MIN_INTERVAL) + .unwrap_or_else(Instant::now), + ), refresh_min_interval: REFRESH_MIN_INTERVAL, }) } @@ -162,32 +181,38 @@ impl OidcVerifier { } let kid = header.kid?; - let claims = if let Some(claims) = self.try_decode(token, &kid, header.alg).await { - claims - } else { - // Unseen kid (or a key swap): refresh once, throttled, and - // retry — the §3.2 rotation path. - self.refresh_keys().await?; - self.try_decode(token, &kid, header.alg).await? + let claims = match self.try_decode(token, &kid, header.alg).await { + DecodeAttempt::Verified(claims) => claims, + DecodeAttempt::UnknownKid => { + // Unseen kid: refresh once, throttled, and retry — the §3.2 + // rotation path. Only a key miss refetches: any other + // failure is terminal, because a refetch cannot make an + // invalid token valid and invalid tokens must not be able + // to drive issuer traffic. + self.refresh_keys().await?; + match self.try_decode(token, &kid, header.alg).await { + DecodeAttempt::Verified(claims) => claims, + _ => return None, + } + } + DecodeAttempt::Rejected => return None, }; self.resolve_identity(&claims) } - /// Decode + validate against the currently cached key for `kid`. - /// `None` on an unknown kid, an alg/key family mismatch, or any - /// validation failure. - async fn try_decode( - &self, - token: &str, - kid: &str, - token_alg: Algorithm, - ) -> Option> { + /// Decode + validate against the currently cached key for `kid`, + /// distinguishing the one outcome that may refetch (an unknown `kid`) + /// from terminal rejections (alg/key family mismatch, any validation + /// failure). + async fn try_decode(&self, token: &str, kid: &str, token_alg: Algorithm) -> DecodeAttempt { let keys = self.keys.read().await; - let cached = keys.get(kid)?; + let Some(cached) = keys.get(kid) else { + return DecodeAttempt::UnknownKid; + }; // The token's header must claim the key's own algorithm — a header // is never allowed to re-type a key (the downgrade shape). if cached.algorithm != token_alg { - return None; + return DecodeAttempt::Rejected; } let mut validation = Validation::new(cached.algorithm); validation.set_issuer(&[self.config.issuer()]); @@ -198,9 +223,11 @@ impl OidcVerifier { // are required above). validation.validate_nbf = true; validation.leeway = self.config.clock_skew_secs(); - decode::>(token, &cached.key, &validation) - .ok() - .map(|data| data.claims) + match decode::>(token, &cached.key, &validation) + { + Ok(data) => DecodeAttempt::Verified(data.claims), + Err(_) => DecodeAttempt::Rejected, + } } /// Map the configured claims' values onto the binding shape. `None` @@ -286,6 +313,8 @@ fn cache_keys(jwks: &JwkSet) -> HashMap { Some(jsonwebtoken::jwk::KeyAlgorithm::RS384) => Algorithm::RS384, Some(jsonwebtoken::jwk::KeyAlgorithm::RS512) => Algorithm::RS512, Some(jsonwebtoken::jwk::KeyAlgorithm::PS256) => Algorithm::PS256, + Some(jsonwebtoken::jwk::KeyAlgorithm::PS384) => Algorithm::PS384, + Some(jsonwebtoken::jwk::KeyAlgorithm::PS512) => Algorithm::PS512, _ => Algorithm::RS256, }, AlgorithmParameters::EllipticCurve(ec) => match ec.curve { @@ -323,6 +352,7 @@ fn validate_tenant_list(tenants: &[String]) -> Option { #[cfg(test)] mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, RwLock as StdRwLock}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -358,15 +388,20 @@ mod tests { } /// A loopback issuer serving discovery + a swappable JWKS — the §6 - /// fixture-issuer tier (no container). - async fn serve_issuer(jwks: Arc>) -> String { + /// fixture-issuer tier (no container). Returns the issuer URL and a + /// counter of `/jwks` fetches (construction is fetch #1), so tests can + /// assert exactly when the verifier goes back to the issuer. + async fn serve_issuer(jwks: Arc>) -> (String, Arc) { serve_issuer_claiming(None, jwks).await } /// The fixture, optionally publishing a discovery document that names /// a *different* issuer than the one it serves under (the §3.2 /// mismatch arm). - async fn serve_issuer_claiming(claimed: Option<&str>, jwks: Arc>) -> String { + async fn serve_issuer_claiming( + claimed: Option<&str>, + jwks: Arc>, + ) -> (String, Arc) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind fixture issuer"); @@ -375,26 +410,28 @@ mod tests { "issuer": claimed.unwrap_or(&issuer), "jwks_uri": format!("{issuer}/jwks"), }); + let jwks_hits = Arc::new(AtomicUsize::new(0)); let app = axum::Router::new() .route( "/.well-known/openid-configuration", - get(|State((discovery, _)): DiscState| async move { Json(discovery) }), + get(|State((discovery, _, _)): DiscState| async move { Json(discovery) }), ) .route( "/jwks", - get(|State((_, jwks)): DiscState| async move { + get(|State((_, jwks, hits)): DiscState| async move { + hits.fetch_add(1, Ordering::SeqCst); let current = jwks.read().expect("jwks lock").clone(); Json(current) }), ) - .with_state((discovery, jwks)); + .with_state((discovery, jwks, Arc::clone(&jwks_hits))); tokio::spawn(async move { axum::serve(listener, app).await.expect("serve issuer"); }); - issuer + (issuer, jwks_hits) } - type DiscState = State<(Value, Arc>)>; + type DiscState = State<(Value, Arc>, Arc)>; fn now_secs() -> i64 { i64::try_from( @@ -439,7 +476,7 @@ mod tests { async fn rfc0029_2_verification_matrix() { let (encoding, jwk) = make_key("key-1"); let jwks = Arc::new(StdRwLock::new(json!({ "keys": [jwk] }))); - let issuer = serve_issuer(jwks).await; + let (issuer, jwks_hits) = serve_issuer(jwks).await; let verifier = OidcVerifier::discover(config_for(&issuer)) .await .expect("discover"); @@ -542,6 +579,16 @@ mod tests { "an identity the audit surface cannot label is not an identity" ); + // None of the rejections above may drive issuer traffic: every arm + // used a cached kid (or died before key lookup), so the only JWKS + // fetch on record is construction's. Only an unknown kid refetches + // (the rotation test's territory). + assert_eq!( + jwks_hits.load(Ordering::SeqCst), + 1, + "invalid tokens must not trigger JWKS refetches" + ); + // Wildcard resolves to the RFC 0026 all-tenants set. let mut wildcard = claims(&issuer); wildcard["ourios_tenants"] = json!(["*"]); @@ -560,13 +607,15 @@ mod tests { async fn rfc0029_6_jwks_rotation() { let (old_encoding, old_jwk) = make_key("key-old"); let jwks = Arc::new(StdRwLock::new(json!({ "keys": [old_jwk] }))); - let issuer = serve_issuer(Arc::clone(&jwks)).await; - let mut verifier = OidcVerifier::discover(config_for(&issuer)) + let (issuer, _) = serve_issuer(Arc::clone(&jwks)).await; + let verifier = OidcVerifier::discover(config_for(&issuer)) .await .expect("discover"); - // The production throttle is real time; the test injects zero so - // rotation is immediate rather than a 5-second sleep. - verifier.refresh_min_interval = Duration::ZERO; + // No throttle injection: `last_refresh` is backdated at + // construction, so the FIRST unseen-kid miss refreshes under the + // real production interval — this test proves that. (The later + // withdrawn-key arm is then throttled, and rejects via the + // unknown-kid path without a refetch, which is also correct.) let old_token = mint(&old_encoding, "key-old", &claims(&issuer)); assert!( @@ -596,18 +645,23 @@ mod tests { async fn discovery_rejects_issuer_mismatch_and_unusable_jwks() { let (_, jwk) = make_key("key-1"); let jwks = Arc::new(StdRwLock::new(json!({ "keys": [jwk] }))); - let issuer = serve_issuer(jwks).await; + let (issuer, _) = serve_issuer(jwks).await; + // A just-closed loopback port: immediate connection-refused, no + // DNS or egress dependency (CI runs with restricted networks). + let unreachable = { + let l = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + format!("http://{}", l.local_addr().expect("addr")) + }; let mut config = OidcSpec { - issuer: Some("https://somewhere-else.example".to_string()), + issuer: Some(unreachable), audience: Some("ourios".to_string()), tenant_claim: Some("ourios_tenants".to_string()), name_claim: None, clock_skew_secs: None, }; - // Point the config at the fixture's address under a different - // issuer name: unreachable → fetch error, which also covers the - // unreachable-issuer startup arm. let err = OidcVerifier::discover(build_oidc_config(&config).expect("valid")) .await .expect_err("unreachable issuer fails startup"); @@ -615,7 +669,7 @@ mod tests { config.issuer = Some(issuer.clone()); let empty = Arc::new(StdRwLock::new(json!({ "keys": [] }))); - let empty_issuer = serve_issuer(empty).await; + let (empty_issuer, _) = serve_issuer(empty).await; config.issuer = Some(empty_issuer); let err = OidcVerifier::discover(build_oidc_config(&config).expect("valid")) .await @@ -628,7 +682,7 @@ mod tests { // verifies. let (_, jwk) = make_key("key-1"); let lying = Arc::new(StdRwLock::new(json!({ "keys": [jwk] }))); - let lying_issuer = + let (lying_issuer, _) = serve_issuer_claiming(Some("https://somewhere-else.example"), lying).await; config.issuer = Some(lying_issuer); let err = OidcVerifier::discover(build_oidc_config(&config).expect("valid")) From 9ef2ff183c140912cf074a8a4622fc9248eb4dd0 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 16:39:58 +0200 Subject: [PATCH 3/9] style(auth): drop the test import the un-zeroed throttle left unused Co-Authored-By: Claude Fable 5 --- crates/ourios-core/src/auth/oidc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index f3b6f6c49..d90616f67 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -367,7 +367,7 @@ mod tests { use serde_json::{Value, json}; use super::super::{OidcSpec, TenantSet, build_oidc_config}; - use super::{Duration, OidcVerifier}; + use super::OidcVerifier; /// One fixture signing key: the private half for minting, the public /// half as a JWK. Generated at test runtime — no committed key From 1eace54366796711925550d62d1c63a64a5c3c4a Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 17:29:10 +0200 Subject: [PATCH 4/9] fix(auth): jwks without alg pin the key family, not RS256 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An RSA JWK published without alg (the common issuer shape) now verifies any allow-listed RSA-family algorithm (RS*/PS*) instead of silently pinning RS256 and rejecting the rest; an explicit alg still pins exactly that algorithm, and EC keys stay curve-determined. Cross-family re-typing remains impossible. Pinned by a fixture test (checked-in RSA PEM — debug-build keygen is too slow per test): RS256/384/512 verify against the alg-less JWK, an ES256 header selecting the RSA key rejects. Co-Authored-By: Claude Fable 5 --- crates/ourios-core/src/auth/oidc.rs | 113 +++++++++++++++--- .../ourios-core/testdata/rfc0029-test-rsa.pem | 28 +++++ 2 files changed, 124 insertions(+), 17 deletions(-) create mode 100644 crates/ourios-core/testdata/rfc0029-test-rsa.pem diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index d90616f67..e55c8ec07 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -89,9 +89,14 @@ struct DiscoveryDocument { /// One cached verification key. struct CachedKey { key: DecodingKey, - /// The key's own algorithm family, pinned from the JWK (never from a - /// presented token's header — the header only *selects* the key). - algorithm: Algorithm, + /// The algorithms this key may verify, pinned from the JWK itself + /// (never from a presented token's header — the header only *selects* + /// the key). A JWK carrying an explicit `alg` pins exactly that + /// algorithm; one without pins its whole key *family* (issuers + /// routinely omit `alg`, and an RSA key legitimately signs any RS*/PS* + /// variant). Cross-family re-typing — the HMAC/EC downgrade shapes — + /// stays impossible. + allowed: Vec, } /// The RFC 0029 §3.2 verifier: config + cached JWKS + the refresh path. @@ -209,12 +214,13 @@ impl OidcVerifier { let Some(cached) = keys.get(kid) else { return DecodeAttempt::UnknownKid; }; - // The token's header must claim the key's own algorithm — a header - // is never allowed to re-type a key (the downgrade shape). - if cached.algorithm != token_alg { + // The token's header must claim an algorithm the key itself + // permits — a header is never allowed to re-type a key into + // another family (the downgrade shape). + if !cached.allowed.contains(&token_alg) { return DecodeAttempt::Rejected; } - let mut validation = Validation::new(cached.algorithm); + let mut validation = Validation::new(token_alg); validation.set_issuer(&[self.config.issuer()]); validation.set_audience(&[self.config.audience()]); validation.set_required_spec_claims(&["exp", "iss", "aud"]); @@ -308,18 +314,36 @@ fn cache_keys(jwks: &JwkSet) -> HashMap { let Some(kid) = jwk.common.key_id.clone() else { continue; }; - let algorithm = match &jwk.algorithm { + use jsonwebtoken::jwk::KeyAlgorithm; + let allowed: Vec = match &jwk.algorithm { AlgorithmParameters::RSA(_) => match jwk.common.key_algorithm { - Some(jsonwebtoken::jwk::KeyAlgorithm::RS384) => Algorithm::RS384, - Some(jsonwebtoken::jwk::KeyAlgorithm::RS512) => Algorithm::RS512, - Some(jsonwebtoken::jwk::KeyAlgorithm::PS256) => Algorithm::PS256, - Some(jsonwebtoken::jwk::KeyAlgorithm::PS384) => Algorithm::PS384, - Some(jsonwebtoken::jwk::KeyAlgorithm::PS512) => Algorithm::PS512, - _ => Algorithm::RS256, + // Explicit `alg` pins exactly that algorithm. + Some(KeyAlgorithm::RS256) => vec![Algorithm::RS256], + Some(KeyAlgorithm::RS384) => vec![Algorithm::RS384], + Some(KeyAlgorithm::RS512) => vec![Algorithm::RS512], + Some(KeyAlgorithm::PS256) => vec![Algorithm::PS256], + Some(KeyAlgorithm::PS384) => vec![Algorithm::PS384], + Some(KeyAlgorithm::PS512) => vec![Algorithm::PS512], + // No `alg`: the whole RSA family — issuers routinely omit + // it, and rejecting their RS384/PS* tokens would be a + // false negative, not a hardening. + None => vec![ + Algorithm::RS256, + Algorithm::RS384, + Algorithm::RS512, + Algorithm::PS256, + Algorithm::PS384, + Algorithm::PS512, + ], + // An RSA key claiming a non-RSA algorithm is malformed: + // skip-don't-fail, like any other unusable key. + Some(_) => continue, }, + // For EC the curve *is* the algorithm; a present `alg` can + // only agree or be malformed, so the curve decides. AlgorithmParameters::EllipticCurve(ec) => match ec.curve { - jsonwebtoken::jwk::EllipticCurve::P256 => Algorithm::ES256, - jsonwebtoken::jwk::EllipticCurve::P384 => Algorithm::ES384, + jsonwebtoken::jwk::EllipticCurve::P256 => vec![Algorithm::ES256], + jsonwebtoken::jwk::EllipticCurve::P384 => vec![Algorithm::ES384], _ => continue, }, _ => continue, @@ -327,7 +351,7 @@ fn cache_keys(jwks: &JwkSet) -> HashMap { let Ok(key) = DecodingKey::from_jwk(jwk) else { continue; }; - keys.insert(kid, CachedKey { key, algorithm }); + keys.insert(kid, CachedKey { key, allowed }); } keys } @@ -387,6 +411,21 @@ mod tests { (encoding, jwk) } + /// A fixed RSA test key (checked-in PEM — debug-build RSA keygen is + /// too slow to run per test) whose JWK deliberately omits `alg`: the + /// shape issuers commonly publish, which must pin the whole RSA + /// family rather than defaulting to RS256. + fn make_rsa_key_without_alg(kid: &str) -> (EncodingKey, Value) { + let pem = include_bytes!("../../testdata/rfc0029-test-rsa.pem"); + let encoding = EncodingKey::from_rsa_pem(pem).expect("rsa pem"); + let jwk = json!({ + "kty": "RSA", "use": "sig", "kid": kid, + "n": "sS2e5TBHMyHx5m_yq1ChQFBk31gRLuNW8xyOFVgVKxFo7itxZaR2gEEGq7kRnr6IXFrk7qFPAOdUfvDkDk9GcAciLmN9_I7LrqBIcOhj_UJKYZn2_Gw9zaaH1LyAcafu5fAOid3jYApEyz-GeC10reaXxoxdOivfl_Bta0T_q9kNUSPXDTID3KfzdbCIsM1mMax67-eNZNLicZmpKPwDqzIn_rPsRpAVbF5xtqjklbCJHXaPQGxm-rcMo7-vLngplhP4N6d6G0m-jWHNnO9heKL-_npDDquvej6zZ1fYl3WJdWpy_-BxFO07WqQAvxWAkTI0l1szBEsm8dKWv1dbrQ", + "e": "AQAB", + }); + (encoding, jwk) + } + /// A loopback issuer serving discovery + a swappable JWKS — the §6 /// fixture-issuer tier (no container). Returns the issuer URL and a /// counter of `/jwks` fetches (construction is fetch #1), so tests can @@ -638,6 +677,46 @@ mod tests { ); } + /// A JWK published without `alg` (the common issuer shape) pins its + /// key *family*: RS384/RS512/PS* tokens verify against the same RSA + /// key, while a cross-family header (the ES/HMAC re-typing shapes) + /// still rejects. + #[tokio::test] + async fn jwk_without_alg_accepts_its_family_only() { + let (rsa_encoding, rsa_jwk) = make_rsa_key_without_alg("key-rsa"); + let jwks = Arc::new(StdRwLock::new(json!({ "keys": [rsa_jwk] }))); + let (issuer, _) = serve_issuer(jwks).await; + let verifier = OidcVerifier::discover(config_for(&issuer)) + .await + .expect("discover"); + + for alg in [ + super::Algorithm::RS256, + super::Algorithm::RS384, + super::Algorithm::RS512, + ] { + let mut header = Header::new(alg); + header.kid = Some("key-rsa".to_string()); + let token = + jsonwebtoken::encode(&header, &claims(&issuer), &rsa_encoding).expect("mint rsa"); + assert!( + verifier.verify(&token).await.is_some(), + "{alg:?} verifies against the alg-less RSA JWK" + ); + } + + // Cross-family: an ES256 header selecting the RSA key must reject + // before any signature work (family pin, not just bad-signature). + let (ec_encoding, _) = make_key("unpublished"); + let mut header = Header::new(super::Algorithm::ES256); + header.kid = Some("key-rsa".to_string()); + let cross = jsonwebtoken::encode(&header, &claims(&issuer), &ec_encoding).expect("mint"); + assert!( + verifier.verify(&cross).await.is_none(), + "a header must not re-type an RSA key into the EC family" + ); + } + /// Startup arms: a discovery document naming a different issuer and a /// JWKS with no usable keys are construction errors, not degraded /// modes (§3.2 — with no cached keys nothing could verify). diff --git a/crates/ourios-core/testdata/rfc0029-test-rsa.pem b/crates/ourios-core/testdata/rfc0029-test-rsa.pem new file mode 100644 index 000000000..0b45a1930 --- /dev/null +++ b/crates/ourios-core/testdata/rfc0029-test-rsa.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCxLZ7lMEczIfHm +b/KrUKFAUGTfWBEu41bzHI4VWBUrEWjuK3FlpHaAQQaruRGevohcWuTuoU8A51R+ +8OQOT0ZwByIuY338jsuuoEhw6GP9Qkphmfb8bD3NpofUvIBxp+7l8A6J3eNgCkTL +P4Z4LXSt5pfGjF06K9+X8G1rRP+r2Q1RI9cNMgPcp/N1sIiwzWYxrHrv541k0uJx +mako/AOrMif+s+xGkBVsXnG2qOSVsIkddo9AbGb6twyjv68ueCmWE/g3p3obSb6N +Yc2c72F4ov7+ekMOq696PrNnV9iXdYl1anL/4HEU7TtapAC/FYCRMjSXWzMESybx +0pa/V1utAgMBAAECggEBALBbOYrleClkQ1Tc3044jpjmrNFG5qumLDkGlkKWj1N0 +G97drRzADBfzIcGyD+DTxAUxkCgatfmvSQKlokrAC9ucriBAdfn65LCn6BNCraw7 +3K+zwg1VbFsTxKYzDyKSRo/nV4FRNG63KeypCZ77l+U03qQJuQ4a949UCIW6g0a3 +uDDpy98F6j4LTSbRcIY8voSRICTqV6RCJSiEpOtdi6suOE4LpD+FfGOAGn0dt1aD +A+ZokjpWDxVre5dc8j1cHSX5VVEfPvkkasRJa9Uk3QZq8XTBFDzJy0N6KO1r6NQH +SUjg5OJ49OA+H3/DBS1PzGBBedC8OyLvwpdKFNOYcSECgYEA3+Mkl5p2vimqDlQg +/NIzPYyQCnUqhU13lcTH0poniLpirXP5Opi6aycmCZhAi93+IymGJ9vfl+qXzdc1 +k0Y0YSyDIPc7MQ/C4lEO7HegmEIkZZFLrY5nH5/jYhZyOSfxsmHIVqkJZYKjgk++ +20h87gs1u5sAvax8KQJRNqo/gUUCgYEAypdhPaXH6GOXX5diaRrHHRkiHn2n/6PA +r0HWaYjH2va8mreLyt99tEALylJrtDzKkygEkqDQ2i3MzjZv6UwOiuOo3mZttKF5 +8wueCv1EsxsMJRXIms6uVv/LNFcFCFzEiVZ1BjZIq7WgjRH2/qZTFphAPR9JwrU1 +pOgU6phb80kCgYB6vZM9DfCVVlAlpNek4zQ2RQ5evVc/V3X9BLGr8tlDqzMX9qGn +Dz38Kq0+y1pvk5eU/VnQFkmhhnoM3jQ/9lgXAgktlHy96+8ild/Bod/IOVKs4BgG +ITDF9Kj7CGU8knp+Gf90Cx3cqd8sPL3ciAP9mOWvYU3prlsvPFb7yiAgpQKBgQCC +D7Fz/GxcuyNBUVTymShfe/U1kgI60owvd5sJYbC82E65HUD324c+Iyfumf9fVO/Q +jY5x/CBZEbI8aSJrqlJjxEhzj1q67jf2Wuz5rSNfwOuJG3UQPcQbQljYn00x0yyx +5vl2JX9+DTqnlnL1hR4ukUwccWvPPrrTxdM30NynUQKBgH3IdpkquLqeO+4uEXpU +KjcbN2+8p523wF+Y1d7n98bExTV2DknR4uqfiQpLLIead9V0hMj333XshTaazzsR +B1K3NwQQDPfqaojOukCOUhUuY5cNBjfAcjMUfxXHBmGbaM6CbobjexVHlJX/rz0O +hfwf1cZqgVGL+GG7BHZTyj+k +-----END PRIVATE KEY----- From 6282442368626260c058ac109fe1cb987654db39 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 17:30:20 +0200 Subject: [PATCH 5/9] style(auth): hoist the KeyAlgorithm import out of the cache loop Co-Authored-By: Claude Fable 5 --- crates/ourios-core/src/auth/oidc.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index e55c8ec07..9024edba1 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -20,7 +20,7 @@ use std::collections::HashMap; use std::time::{Duration, Instant}; -use jsonwebtoken::jwk::{AlgorithmParameters, JwkSet}; +use jsonwebtoken::jwk::{AlgorithmParameters, JwkSet, KeyAlgorithm}; use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; use tokio::sync::RwLock; @@ -314,7 +314,6 @@ fn cache_keys(jwks: &JwkSet) -> HashMap { let Some(kid) = jwk.common.key_id.clone() else { continue; }; - use jsonwebtoken::jwk::KeyAlgorithm; let allowed: Vec = match &jwk.algorithm { AlgorithmParameters::RSA(_) => match jwk.common.key_algorithm { // Explicit `alg` pins exactly that algorithm. From 710fed5f60f177417e86080698784c5640dbacff Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 18:26:51 +0200 Subject: [PATCH 6/9] test(auth): generate the RSA fixture key at runtime, not from a committed PEM MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A checked-in private key trips secret scanners and contradicts the crate's own fixture policy (the P-256 comment: "no committed private-key fixtures for scanners to flag"). The RSA-family fixture is now generated once per test process (OnceLock; 1024-bit — the tests exercise signature shape, not strength, so unoptimized keygen stays fast) via an explicit `rsa` dev-dependency (already in the tree through jsonwebtoken's rust_crypto backend). The unconditional dev-dep surfaces RUSTSEC-2023-0071 (Marvin) in cargo-deny's default graph; accepted in deny.toml with the usage argument: the advisory concerns private-key-operation timing, and Ourios only ever *verifies* against public JWKS keys — no RSA private-key operation exists outside throwaway test fixtures. Co-Authored-By: Claude Fable 5 --- Cargo.lock | 1 + crates/ourios-core/Cargo.toml | 5 ++++ crates/ourios-core/src/auth/oidc.rs | 27 ++++++++++++------ .../ourios-core/testdata/rfc0029-test-rsa.pem | 28 ------------------- deny.toml | 11 ++++++++ 5 files changed, 36 insertions(+), 36 deletions(-) delete mode 100644 crates/ourios-core/testdata/rfc0029-test-rsa.pem diff --git a/Cargo.lock b/Cargo.lock index 0f56c37d3..9a4ea7d1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3212,6 +3212,7 @@ dependencies = [ "proptest", "rand 0.8.6", "reqwest", + "rsa", "serde", "serde_json", "subtle", diff --git a/crates/ourios-core/Cargo.toml b/crates/ourios-core/Cargo.toml index b866cb804..0b3ec4c38 100644 --- a/crates/ourios-core/Cargo.toml +++ b/crates/ourios-core/Cargo.toml @@ -90,6 +90,11 @@ axum = { version = "0.8", default-features = false, features = ["http1", "tokio" # Mints the fixture issuer's ES256 keypair at test runtime (instant P-256 # keygen; no committed private-key fixtures for scanners to flag). p256 = { version = "0.13", default-features = false, features = ["ecdsa", "pkcs8", "pem", "arithmetic"] } +# Mints the RSA-family fixture key at test runtime for the same reason — +# 1024-bit keygen (test-only; signature shape, not strength, is under +# test) keeps it fast in unoptimized builds. Already in the tree via +# jsonwebtoken's rust_crypto backend. +rsa = { version = "0.9", default-features = false, features = ["std", "pem"] } rand = "0.8" # base64url (no pad) for the fixture issuer's JWK coordinates. base64 = "0.22" diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index 9024edba1..d9c06f64a 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -410,17 +410,28 @@ mod tests { (encoding, jwk) } - /// A fixed RSA test key (checked-in PEM — debug-build RSA keygen is - /// too slow to run per test) whose JWK deliberately omits `alg`: the - /// shape issuers commonly publish, which must pin the whole RSA - /// family rather than defaulting to RS256. + /// The RSA-family fixture key, generated once per test process (no + /// committed private-key fixtures for scanners to flag — same policy + /// as the P-256 fixture). 1024-bit keeps unoptimized keygen fast; the + /// tests exercise signature *shape*, not strength. Its JWK + /// deliberately omits `alg`: the shape issuers commonly publish, + /// which must pin the whole RSA family rather than defaulting to + /// RS256. fn make_rsa_key_without_alg(kid: &str) -> (EncodingKey, Value) { - let pem = include_bytes!("../../testdata/rfc0029-test-rsa.pem"); - let encoding = EncodingKey::from_rsa_pem(pem).expect("rsa pem"); + use rsa::traits::PublicKeyParts; + static KEY: std::sync::OnceLock<(String, Vec, Vec)> = std::sync::OnceLock::new(); + let (pem, n, e) = KEY.get_or_init(|| { + let key = rsa::RsaPrivateKey::new(&mut rand::rngs::OsRng, 1024).expect("rsa keygen"); + let pem = rsa::pkcs8::EncodePrivateKey::to_pkcs8_pem(&key, rsa::pkcs8::LineEnding::LF) + .expect("pkcs8 pem") + .to_string(); + (pem, key.n().to_bytes_be(), key.e().to_bytes_be()) + }); + let encoding = EncodingKey::from_rsa_pem(pem.as_bytes()).expect("rsa pem"); let jwk = json!({ "kty": "RSA", "use": "sig", "kid": kid, - "n": "sS2e5TBHMyHx5m_yq1ChQFBk31gRLuNW8xyOFVgVKxFo7itxZaR2gEEGq7kRnr6IXFrk7qFPAOdUfvDkDk9GcAciLmN9_I7LrqBIcOhj_UJKYZn2_Gw9zaaH1LyAcafu5fAOid3jYApEyz-GeC10reaXxoxdOivfl_Bta0T_q9kNUSPXDTID3KfzdbCIsM1mMax67-eNZNLicZmpKPwDqzIn_rPsRpAVbF5xtqjklbCJHXaPQGxm-rcMo7-vLngplhP4N6d6G0m-jWHNnO9heKL-_npDDquvej6zZ1fYl3WJdWpy_-BxFO07WqQAvxWAkTI0l1szBEsm8dKWv1dbrQ", - "e": "AQAB", + "n": URL_SAFE_NO_PAD.encode(n), + "e": URL_SAFE_NO_PAD.encode(e), }); (encoding, jwk) } diff --git a/crates/ourios-core/testdata/rfc0029-test-rsa.pem b/crates/ourios-core/testdata/rfc0029-test-rsa.pem deleted file mode 100644 index 0b45a1930..000000000 --- a/crates/ourios-core/testdata/rfc0029-test-rsa.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCxLZ7lMEczIfHm -b/KrUKFAUGTfWBEu41bzHI4VWBUrEWjuK3FlpHaAQQaruRGevohcWuTuoU8A51R+ -8OQOT0ZwByIuY338jsuuoEhw6GP9Qkphmfb8bD3NpofUvIBxp+7l8A6J3eNgCkTL -P4Z4LXSt5pfGjF06K9+X8G1rRP+r2Q1RI9cNMgPcp/N1sIiwzWYxrHrv541k0uJx -mako/AOrMif+s+xGkBVsXnG2qOSVsIkddo9AbGb6twyjv68ueCmWE/g3p3obSb6N -Yc2c72F4ov7+ekMOq696PrNnV9iXdYl1anL/4HEU7TtapAC/FYCRMjSXWzMESybx -0pa/V1utAgMBAAECggEBALBbOYrleClkQ1Tc3044jpjmrNFG5qumLDkGlkKWj1N0 -G97drRzADBfzIcGyD+DTxAUxkCgatfmvSQKlokrAC9ucriBAdfn65LCn6BNCraw7 -3K+zwg1VbFsTxKYzDyKSRo/nV4FRNG63KeypCZ77l+U03qQJuQ4a949UCIW6g0a3 -uDDpy98F6j4LTSbRcIY8voSRICTqV6RCJSiEpOtdi6suOE4LpD+FfGOAGn0dt1aD -A+ZokjpWDxVre5dc8j1cHSX5VVEfPvkkasRJa9Uk3QZq8XTBFDzJy0N6KO1r6NQH -SUjg5OJ49OA+H3/DBS1PzGBBedC8OyLvwpdKFNOYcSECgYEA3+Mkl5p2vimqDlQg -/NIzPYyQCnUqhU13lcTH0poniLpirXP5Opi6aycmCZhAi93+IymGJ9vfl+qXzdc1 -k0Y0YSyDIPc7MQ/C4lEO7HegmEIkZZFLrY5nH5/jYhZyOSfxsmHIVqkJZYKjgk++ -20h87gs1u5sAvax8KQJRNqo/gUUCgYEAypdhPaXH6GOXX5diaRrHHRkiHn2n/6PA -r0HWaYjH2va8mreLyt99tEALylJrtDzKkygEkqDQ2i3MzjZv6UwOiuOo3mZttKF5 -8wueCv1EsxsMJRXIms6uVv/LNFcFCFzEiVZ1BjZIq7WgjRH2/qZTFphAPR9JwrU1 -pOgU6phb80kCgYB6vZM9DfCVVlAlpNek4zQ2RQ5evVc/V3X9BLGr8tlDqzMX9qGn -Dz38Kq0+y1pvk5eU/VnQFkmhhnoM3jQ/9lgXAgktlHy96+8ild/Bod/IOVKs4BgG -ITDF9Kj7CGU8knp+Gf90Cx3cqd8sPL3ciAP9mOWvYU3prlsvPFb7yiAgpQKBgQCC -D7Fz/GxcuyNBUVTymShfe/U1kgI60owvd5sJYbC82E65HUD324c+Iyfumf9fVO/Q -jY5x/CBZEbI8aSJrqlJjxEhzj1q67jf2Wuz5rSNfwOuJG3UQPcQbQljYn00x0yyx -5vl2JX9+DTqnlnL1hR4ukUwccWvPPrrTxdM30NynUQKBgH3IdpkquLqeO+4uEXpU -KjcbN2+8p523wF+Y1d7n98bExTV2DknR4uqfiQpLLIead9V0hMj333XshTaazzsR -B1K3NwQQDPfqaojOukCOUhUuY5cNBjfAcjMUfxXHBmGbaM6CbobjexVHlJX/rz0O -hfwf1cZqgVGL+GG7BHZTyj+k ------END PRIVATE KEY----- diff --git a/deny.toml b/deny.toml index ec0feb206..84673d55d 100644 --- a/deny.toml +++ b/deny.toml @@ -24,6 +24,17 @@ ignore = [ # DataFusion/Arrow upgrade, epic #314). "RUSTSEC-2026-0194", "RUSTSEC-2026-0195", + # reason: `rsa` Marvin timing side-channel (RUSTSEC-2023-0071, no patch + # released) leaks *private-key* material through private-key-operation + # timing. Ourios never performs RSA private-key operations: the RFC 0029 + # verifier (jsonwebtoken's rust_crypto backend, `oidc` feature) only + # verifies signatures against the issuer's *public* JWKS keys, and the + # ourios-core dev-dependency only generates throwaway per-test-process + # fixture keys that never leave the test. No token is ever signed and no + # RSA private key exists in production. Re-evaluate if we ever sign + # (issuer-side) rather than verify, or when the constant-time rewrite + # ships upstream. + "RUSTSEC-2023-0071", ] [licenses] From 9445dfab7dd8adc33a731d16ade6e336eb205d68 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 18:36:00 +0200 Subject: [PATCH 7/9] fix(auth): retain the key cache on an empty jwks refresh; ec alg must agree with its curve MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An empty refreshed set is an issuer glitch, not a total withdrawal — wiping the cache would fail all verification until the next refresh. An EC JWK whose explicit alg disagrees with its curve is skipped as malformed (the comment previously claimed this; now the code does it). Both pinned by tests. Co-Authored-By: Claude Fable 5 --- crates/ourios-core/src/auth/oidc.rs | 87 ++++++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 9 deletions(-) diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index d9c06f64a..d5287fb8c 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -262,8 +262,13 @@ impl OidcVerifier { } /// Refetch the JWKS (rotation / unseen kid), throttled to one fetch - /// per [`REFRESH_MIN_INTERVAL`]. `None` when throttled or when the - /// fetch fails — the cached set stays authoritative either way. + /// per [`REFRESH_MIN_INTERVAL`]. `None` when throttled, when the fetch + /// fails, or when the refetched set filters down to zero usable keys — + /// the cached set stays authoritative in every one of those cases. A + /// real rotation always publishes at least one usable key, so an empty + /// result is treated as an issuer glitch (availability) rather than a + /// total withdrawal; withdrawn keys still stop verifying on the next + /// non-empty refresh. async fn refresh_keys(&self) -> Option<()> { { let last = self.last_refresh.read().await; @@ -280,6 +285,9 @@ impl OidcVerifier { *last = Instant::now(); let jwks: JwkSet = fetch_json(&self.http, &self.jwks_uri).await.ok()?; let fresh = cache_keys(&jwks); + if fresh.is_empty() { + return None; + } *self.keys.write().await = fresh; Some(()) } @@ -338,13 +346,24 @@ fn cache_keys(jwks: &JwkSet) -> HashMap { // skip-don't-fail, like any other unusable key. Some(_) => continue, }, - // For EC the curve *is* the algorithm; a present `alg` can - // only agree or be malformed, so the curve decides. - AlgorithmParameters::EllipticCurve(ec) => match ec.curve { - jsonwebtoken::jwk::EllipticCurve::P256 => vec![Algorithm::ES256], - jsonwebtoken::jwk::EllipticCurve::P384 => vec![Algorithm::ES384], - _ => continue, - }, + // For EC the curve *is* the algorithm; a present `alg` must + // agree with it or the key is malformed (skip-don't-fail). + AlgorithmParameters::EllipticCurve(ec) => { + let (derived, agreeing) = match ec.curve { + jsonwebtoken::jwk::EllipticCurve::P256 => { + (Algorithm::ES256, KeyAlgorithm::ES256) + } + jsonwebtoken::jwk::EllipticCurve::P384 => { + (Algorithm::ES384, KeyAlgorithm::ES384) + } + _ => continue, + }; + match jwk.common.key_algorithm { + None => vec![derived], + Some(ka) if ka == agreeing => vec![derived], + Some(_) => continue, + } + } _ => continue, }; let Ok(key) = DecodingKey::from_jwk(jwk) else { @@ -727,6 +746,56 @@ mod tests { ); } + /// A refresh that fetches an *empty* usable-key set retains the + /// cached keys (issuer glitch ≠ total withdrawal): verification of + /// already-cached kids survives, and the withdrawn-key semantics + /// resume on the next non-empty refresh. + #[tokio::test] + async fn empty_jwks_refresh_retains_the_cached_set() { + let (encoding, jwk) = make_key("key-1"); + let jwks = Arc::new(StdRwLock::new(json!({ "keys": [jwk] }))); + let (issuer, jwks_hits) = serve_issuer(Arc::clone(&jwks)).await; + let verifier = OidcVerifier::discover(config_for(&issuer)) + .await + .expect("discover"); + + // The issuer glitches to an empty set; an unseen kid triggers the + // (backdated-allowed) refresh, which must not wipe the cache. + *jwks.write().expect("jwks lock") = json!({ "keys": [] }); + let ghost = mint(&encoding, "key-ghost", &claims(&issuer)); + assert!(verifier.verify(&ghost).await.is_none(), "unknown kid"); + assert_eq!( + jwks_hits.load(Ordering::SeqCst), + 2, + "the unseen kid did refetch" + ); + + let cached = mint(&encoding, "key-1", &claims(&issuer)); + assert!( + verifier.verify(&cached).await.is_some(), + "the cached key survives an empty-JWKS refresh" + ); + } + + /// An EC JWK whose explicit `alg` disagrees with its curve is + /// malformed and skipped (the curve is authoritative); an agreeing + /// `alg` caches normally. + #[test] + fn ec_jwk_with_disagreeing_alg_is_skipped() { + let (_, mut jwk) = make_key("key-ec"); + jwk["alg"] = json!("ES384"); // P-256 curve claiming ES384: malformed + let set: super::JwkSet = serde_json::from_value(json!({ "keys": [jwk] })).expect("jwk set"); + assert!( + super::cache_keys(&set).is_empty(), + "curve/alg disagreement must skip the key" + ); + + let (_, agreeing) = make_key("key-ec2"); // fixture sets alg: ES256 + let set: super::JwkSet = + serde_json::from_value(json!({ "keys": [agreeing] })).expect("jwk set"); + assert_eq!(super::cache_keys(&set).len(), 1, "agreeing alg caches"); + } + /// Startup arms: a discovery document naming a different issuer and a /// JWKS with no usable keys are construction errors, not degraded /// modes (§3.2 — with no cached keys nothing could verify). From fb72467bd78313f68fc4976048cc73ccaf750dd7 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 18:47:19 +0200 Subject: [PATCH 8/9] fix(auth): rfc 7517 usage gating; ps* in the family test; dead test assignment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keys declaring use: enc or key_ops without verify never cache (RFC 7517 gating, pinned by test); the alg-less family test now exercises PS256/384/512 too (fixture bumped to 2048 bits — PS512's PSS salt+hash exceeds 1024); the discovery test's overwritten issuer assignment is gone. Co-Authored-By: Claude Fable 5 --- crates/ourios-core/Cargo.toml | 7 ++--- crates/ourios-core/src/auth/oidc.rs | 44 ++++++++++++++++++++++++++--- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/crates/ourios-core/Cargo.toml b/crates/ourios-core/Cargo.toml index 0b3ec4c38..ec36f4c78 100644 --- a/crates/ourios-core/Cargo.toml +++ b/crates/ourios-core/Cargo.toml @@ -90,10 +90,9 @@ axum = { version = "0.8", default-features = false, features = ["http1", "tokio" # Mints the fixture issuer's ES256 keypair at test runtime (instant P-256 # keygen; no committed private-key fixtures for scanners to flag). p256 = { version = "0.13", default-features = false, features = ["ecdsa", "pkcs8", "pem", "arithmetic"] } -# Mints the RSA-family fixture key at test runtime for the same reason — -# 1024-bit keygen (test-only; signature shape, not strength, is under -# test) keeps it fast in unoptimized builds. Already in the tree via -# jsonwebtoken's rust_crypto backend. +# Mints the RSA-family fixture key at test runtime for the same reason +# (2048-bit — PS512 needs >1024 — generated once per test process). +# Already in the tree via jsonwebtoken's rust_crypto backend. rsa = { version = "0.9", default-features = false, features = ["std", "pem"] } rand = "0.8" # base64url (no pad) for the fixture issuer's JWK coordinates. diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index d5287fb8c..62357abc9 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -322,6 +322,19 @@ fn cache_keys(jwks: &JwkSet) -> HashMap { let Some(kid) = jwk.common.key_id.clone() else { continue; }; + // RFC 7517 usage gating: a key declaring itself for encryption + // (`use: "enc"`) or whose `key_ops` omit `verify` is not a + // signature-verification key — never cache it, whatever its shape. + // Absent fields impose no restriction (the common issuer shape). + match &jwk.common.public_key_use { + None | Some(jsonwebtoken::jwk::PublicKeyUse::Signature) => {} + Some(_) => continue, + } + if let Some(ops) = &jwk.common.key_operations + && !ops.contains(&jsonwebtoken::jwk::KeyOperations::Verify) + { + continue; + } let allowed: Vec = match &jwk.algorithm { AlgorithmParameters::RSA(_) => match jwk.common.key_algorithm { // Explicit `alg` pins exactly that algorithm. @@ -431,8 +444,8 @@ mod tests { /// The RSA-family fixture key, generated once per test process (no /// committed private-key fixtures for scanners to flag — same policy - /// as the P-256 fixture). 1024-bit keeps unoptimized keygen fast; the - /// tests exercise signature *shape*, not strength. Its JWK + /// as the P-256 fixture). 2048-bit — PS512's PSS salt+hash needs more + /// than 1024 bits — generated once per process to bound the cost. Its JWK /// deliberately omits `alg`: the shape issuers commonly publish, /// which must pin the whole RSA family rather than defaulting to /// RS256. @@ -440,7 +453,7 @@ mod tests { use rsa::traits::PublicKeyParts; static KEY: std::sync::OnceLock<(String, Vec, Vec)> = std::sync::OnceLock::new(); let (pem, n, e) = KEY.get_or_init(|| { - let key = rsa::RsaPrivateKey::new(&mut rand::rngs::OsRng, 1024).expect("rsa keygen"); + let key = rsa::RsaPrivateKey::new(&mut rand::rngs::OsRng, 2048).expect("rsa keygen"); let pem = rsa::pkcs8::EncodePrivateKey::to_pkcs8_pem(&key, rsa::pkcs8::LineEnding::LF) .expect("pkcs8 pem") .to_string(); @@ -723,6 +736,9 @@ mod tests { super::Algorithm::RS256, super::Algorithm::RS384, super::Algorithm::RS512, + super::Algorithm::PS256, + super::Algorithm::PS384, + super::Algorithm::PS512, ] { let mut header = Header::new(alg); header.kid = Some("key-rsa".to_string()); @@ -777,6 +793,27 @@ mod tests { ); } + /// RFC 7517 usage gating: `use: "enc"` and `key_ops` without + /// `verify` never cache; `use: "sig"` (the fixture default) does. + #[test] + fn non_verification_jwks_are_skipped() { + let (_, mut enc_use) = make_key("key-enc"); + enc_use["use"] = json!("enc"); + let set: super::JwkSet = + serde_json::from_value(json!({ "keys": [enc_use] })).expect("jwk set"); + assert!(super::cache_keys(&set).is_empty(), "use: enc must skip"); + + let (_, mut no_verify) = make_key("key-ops"); + no_verify.as_object_mut().expect("map").remove("use"); + no_verify["key_ops"] = json!(["sign"]); + let set: super::JwkSet = + serde_json::from_value(json!({ "keys": [no_verify] })).expect("jwk set"); + assert!( + super::cache_keys(&set).is_empty(), + "key_ops without verify must skip" + ); + } + /// An EC JWK whose explicit `alg` disagrees with its curve is /// malformed and skipped (the curve is authoritative); an agreeing /// `alg` caches normally. @@ -825,7 +862,6 @@ mod tests { .expect_err("unreachable issuer fails startup"); assert!(err.to_string().contains("fetch"), "{err}"); - config.issuer = Some(issuer.clone()); let empty = Arc::new(StdRwLock::new(json!({ "keys": [] }))); let (empty_issuer, _) = serve_issuer(empty).await; config.issuer = Some(empty_issuer); From d731ea93d09dfcdffea2c3c433eec35e12e3f7eb Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 7 Jul 2026 18:54:00 +0200 Subject: [PATCH 9/9] fix(auth): bound issuer document reads at 1 mib; scope the deny note to production fetch_json streams via chunk() and rejects past the bound instead of buffering an arbitrary-size discovery/JWKS response (pinned by test); the RUSTSEC-2023-0071 note now acknowledges test-only signing. Co-Authored-By: Claude Fable 5 --- crates/ourios-core/src/auth/oidc.rs | 47 ++++++++++++++++++++++++++--- deny.toml | 5 +-- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/crates/ourios-core/src/auth/oidc.rs b/crates/ourios-core/src/auth/oidc.rs index 62357abc9..68c709a8e 100644 --- a/crates/ourios-core/src/auth/oidc.rs +++ b/crates/ourios-core/src/auth/oidc.rs @@ -293,22 +293,38 @@ impl OidcVerifier { } } -/// GET + JSON-decode one document, with a bounded timeout. +/// Documents the verifier fetches (discovery, JWKS) are a few KiB in +/// practice; anything past this is a misconfigured or hostile issuer, and +/// the fetch fails rather than buffering it. +const MAX_DOCUMENT_BYTES: usize = 1024 * 1024; + +/// GET + JSON-decode one document, with a bounded timeout and a bounded +/// body size (streamed via `chunk`, so an oversized response is rejected +/// without ever being fully buffered). async fn fetch_json( http: &reqwest::Client, url: &str, ) -> Result { - let response = http + let mut response = http .get(url) .timeout(Duration::from_secs(10)) .send() .await .and_then(reqwest::Response::error_for_status) .map_err(|e| DiscoveryError(format!("fetch {url}: {e}")))?; - let bytes = response - .bytes() + let mut bytes = Vec::new(); + while let Some(chunk) = response + .chunk() .await - .map_err(|e| DiscoveryError(format!("read {url}: {e}")))?; + .map_err(|e| DiscoveryError(format!("read {url}: {e}")))? + { + if bytes.len() + chunk.len() > MAX_DOCUMENT_BYTES { + return Err(DiscoveryError(format!( + "read {url}: response exceeds the {MAX_DOCUMENT_BYTES}-byte document bound" + ))); + } + bytes.extend_from_slice(&chunk); + } serde_json::from_slice(&bytes).map_err(|e| DiscoveryError(format!("decode {url}: {e}"))) } @@ -762,6 +778,27 @@ mod tests { ); } + /// An issuer returning an oversized document fails discovery at the + /// byte bound instead of buffering it. + #[tokio::test] + async fn oversized_discovery_document_is_rejected() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let issuer = format!("http://{}", listener.local_addr().expect("addr")); + let app = axum::Router::new().route( + "/.well-known/openid-configuration", + get(|| async { "x".repeat(2 * 1024 * 1024) }), + ); + tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve"); + }); + let err = OidcVerifier::discover(config_for(&issuer)) + .await + .expect_err("an oversized document fails startup"); + assert!(err.to_string().contains("document bound"), "{err}"); + } + /// A refresh that fetches an *empty* usable-key set retains the /// cached keys (issuer glitch ≠ total withdrawal): verification of /// already-cached kids survives, and the withdrawn-key semantics diff --git a/deny.toml b/deny.toml index 84673d55d..dc77b4b1a 100644 --- a/deny.toml +++ b/deny.toml @@ -30,8 +30,9 @@ ignore = [ # verifier (jsonwebtoken's rust_crypto backend, `oidc` feature) only # verifies signatures against the issuer's *public* JWKS keys, and the # ourios-core dev-dependency only generates throwaway per-test-process - # fixture keys that never leave the test. No token is ever signed and no - # RSA private key exists in production. Re-evaluate if we ever sign + # fixture keys (tests DO sign with those, locally and ephemerally). In + # production no token is ever signed and no RSA private key exists — + # the timing side-channel has nothing to leak. Re-evaluate if we ever sign # (issuer-side) rather than verify, or when the constant-time rewrite # ships upstream. "RUSTSEC-2023-0071",