From 80529abb2526d7f0ac6b9a1b4a2ed4eb625d4041 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:24:48 +0000 Subject: [PATCH 1/3] feat(stack-auth): verify CTS access tokens against the issuer's JWKS Strategies trusted whatever token `authorize` returned. Whoever controls the auth URL (an injected CS_CTS_HOST, a compromised dependency, a poisoned token store) could hand the client a token with any scopes and a `services` claim pointing key requests at a rogue ZeroKMS. `verify_tokens()` on the access-key, OIDC federation, device-session and auto strategy builders now checks every token before `get_token` returns it: RS256 signature under a key from `/.well-known/jwks.json`, `iss`, `exp` (60s leeway) and, when an audience was requested, `aud`. The trusted issuer is the CTS that service discovery names for the region, pinned separately from `base_url` and CS_CTS_HOST; `trusted_issuer(url)` pins another. The JWKS is cached for an hour and refetched early for an unknown `kid` at most once a minute. RSA verification uses aws-lc-rs natively and RustCrypto's `rsa` on wasm32, where aws-lc-rs does not build; the host tests run both backends against the same vectors. Verification is opt-in until the live check added to tests-golang.yml confirms CTS matches these assumptions. Refs CIP-5080 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012Jmn7r23UyoxCG5saYMrgG --- .changeset/auth-verify-cts-tokens.md | 5 + .github/workflows/tests-crates.yml | 7 +- .github/workflows/tests-golang.yml | 6 + Cargo.lock | 108 ++- languages/golang/auth/guest/Cargo.lock | 125 +++ languages/golang/encrypt/guest/Cargo.lock | 115 ++- packages/stack-auth/Cargo.toml | 20 +- packages/stack-auth/README.md | 29 + packages/stack-auth/examples/verify_tokens.rs | 33 + packages/stack-auth/fuzz/Cargo.lock | 125 +++ .../stack-auth/src/access_key_strategy.rs | 51 +- packages/stack-auth/src/auto_strategy.rs | 78 +- .../stack-auth/src/device_session_strategy.rs | 53 ++ packages/stack-auth/src/lib.rs | 1 + .../src/oidc_federation_strategy.rs | 41 +- packages/stack-auth/src/test_support.rs | 159 ++++ packages/stack-auth/src/token_verifier.rs | 472 ++++++++++ .../stack-auth/src/token_verifier/tests.rs | 885 ++++++++++++++++++ packages/stack-auth/src/transport.rs | 19 + packages/stack-encrypt/fuzz/Cargo.lock | 121 ++- packages/stack-kms/fuzz/Cargo.lock | 119 +++ 21 files changed, 2550 insertions(+), 22 deletions(-) create mode 100644 .changeset/auth-verify-cts-tokens.md create mode 100644 packages/stack-auth/examples/verify_tokens.rs create mode 100644 packages/stack-auth/src/token_verifier.rs create mode 100644 packages/stack-auth/src/token_verifier/tests.rs diff --git a/.changeset/auth-verify-cts-tokens.md b/.changeset/auth-verify-cts-tokens.md new file mode 100644 index 0000000000..f763d166a9 --- /dev/null +++ b/.changeset/auth-verify-cts-tokens.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/auth": patch +--- + +The Rust `stack-auth` crate behind `@cipherstash/auth` can now verify the access tokens CTS issues before using them: RS256 signature against the keys CTS publishes at `/.well-known/jwks.json`, plus issuer, expiry and (when requested) audience. The trusted issuer is the CTS for the workspace's region, pinned separately from `CS_CTS_HOST` and any `baseUrl` override. Verification is opt-in in this release and is not yet exposed through the JavaScript API, so `@cipherstash/auth`'s behaviour is unchanged. diff --git a/.github/workflows/tests-crates.yml b/.github/workflows/tests-crates.yml index 40cc572cce..06a075d45c 100644 --- a/.github/workflows/tests-crates.yml +++ b/.github/workflows/tests-crates.yml @@ -136,11 +136,14 @@ jobs: - name: rustdoc run: mise run doc - # The stack-encrypt examples need live credentials, so they are built - # here and run in tests-golang.yml `live`. + # The stack-encrypt examples and stack-auth's `verify_tokens` need live + # credentials, so they are built here and run in tests-golang.yml `live`. - name: Build the stack-encrypt examples run: cargo build --locked -p stack-encrypt --examples + - name: Build the stack-auth verify_tokens example + run: cargo build --locked -p stack-auth --example verify_tokens + # The crates release-plz publishes. `--dry-run` packages and compiles # each the way crates.io would (all five together, so each resolves the # others from cargo's temporary local registry rather than from diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index 9bfff334ab..4d2c8ff705 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -395,6 +395,12 @@ jobs: working-directory: languages/golang run: CGO_ENABLED=0 go test -v ./encrypt/... + # Verifies a real CTS token against CTS's published signing keys: the + # live proof that the token verifier's assumptions (RS256, the region's + # CTS as issuer, keys at its /.well-known/jwks.json) hold. + - name: stack-auth verifies a live CTS token + run: cargo run --locked -p stack-auth --example verify_tokens + - name: stack-encrypt examples run: | for example in encrypted_record mixed_user search_terms zerokms_auth; do diff --git a/Cargo.lock b/Cargo.lock index 5548762390..930fa58fb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -625,6 +625,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-oid" version = "0.10.2" @@ -867,6 +873,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.5" @@ -912,6 +928,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -923,7 +940,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.0", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.1", "ctutils", "zeroize", @@ -1871,6 +1888,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] [[package]] name = "leb128fmt" @@ -2179,6 +2199,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.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.0" @@ -2194,6 +2230,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2293,6 +2339,27 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[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.32" @@ -2782,6 +2849,26 @@ dependencies = [ "serde", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-hash" version = "2.1.1" @@ -3160,6 +3247,7 @@ 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", ] @@ -3229,6 +3317,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -3240,6 +3344,7 @@ name = "stack-auth" version = "0.43.0" dependencies = [ "aquamarine", + "aws-lc-rs", "axum", "base64 0.22.1", "bytes", @@ -3250,6 +3355,7 @@ dependencies = [ "open", "proptest", "reqwest", + "rsa", "rustls", "rustls-platform-verifier", "rustls-webpki", diff --git a/languages/golang/auth/guest/Cargo.lock b/languages/golang/auth/guest/Cargo.lock index ba6588228c..d7370788ae 100644 --- a/languages/golang/auth/guest/Cargo.lock +++ b/languages/golang/auth/guest/Cargo.lock @@ -154,6 +154,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" @@ -335,6 +341,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 = "convert_case" version = "0.10.0" @@ -506,6 +518,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.8" @@ -548,6 +570,7 @@ 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", ] @@ -1104,12 +1127,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "libc" version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.25" @@ -1226,6 +1264,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.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -1241,6 +1295,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1248,6 +1312,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -1317,6 +1382,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.34" @@ -1572,6 +1658,26 @@ dependencies = [ "serde", ] +[[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_version" version = "0.4.1" @@ -1735,6 +1841,7 @@ 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", ] @@ -1772,6 +1879,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1783,11 +1906,13 @@ name = "stack-auth" version = "0.43.0" dependencies = [ "aquamarine", + "aws-lc-rs", "base64", "cts-common", "jsonwebtoken", "miette", "open", + "rsa", "serde", "serde_json", "serde_urlencoded", diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index 46b22fa357..c7a5243bde 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -388,6 +388,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-oid" version = "0.10.2" @@ -580,6 +586,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.8" @@ -622,6 +638,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -633,7 +650,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", "zeroize", @@ -1230,6 +1247,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -1237,6 +1257,12 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.21" @@ -1347,6 +1373,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.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -1362,6 +1404,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1369,6 +1421,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -1438,6 +1491,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.34" @@ -1734,6 +1808,26 @@ dependencies = [ "serde", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -1952,6 +2046,7 @@ 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", ] @@ -1989,6 +2084,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2000,11 +2111,13 @@ name = "stack-auth" version = "0.43.0" dependencies = [ "aquamarine", + "aws-lc-rs", "base64", "cts-common", "jsonwebtoken", "miette", "open", + "rsa", "serde", "serde_json", "serde_urlencoded", diff --git a/packages/stack-auth/Cargo.toml b/packages/stack-auth/Cargo.toml index 3fae08b092..7e6fedf504 100644 --- a/packages/stack-auth/Cargo.toml +++ b/packages/stack-auth/Cargo.toml @@ -30,7 +30,9 @@ serde_json = { workspace = true } serde_urlencoded = "0.7" # `OidcFederationStrategy` keys its per-user token cache on the SHA-256 of # the provider JWT, and stamps that digest on the tokens it persists. -sha2 = "0.10" +# `oid` lets the wasm32 RS256 backend name SHA-256 to `rsa`'s PKCS#1 v1.5 +# verifier (see `token_verifier`). +sha2 = { version = "0.10", features = ["oid"] } stack-profile = { workspace = true } thiserror = { workspace = true } tracing = { workspace = true } @@ -63,6 +65,10 @@ tokio = { workspace = true } # The bundled clients' TLS configuration (`tls`): the platform verifier with # a compiled-in SPKI blocklist around it. Native only, since on wasm32 reqwest # uses the runtime's `fetch`, and only with `http`. +# RS256 verification of CTS access tokens (`token_verifier`). Already in the +# native graph through `jsonwebtoken` and rustls; named directly so the +# verifier does not depend on either. +aws-lc-rs = "1.18" rustls = { workspace = true, optional = true } rustls-platform-verifier = { workspace = true, optional = true } # Its library is named `webpki`. @@ -70,6 +76,11 @@ rustls-webpki = { workspace = true, optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] tokio = { version = "1.47.1", default-features = false, features = ["sync"] } +# RS256 verification of CTS access tokens on wasm32, where aws-lc-rs does not +# build (and is kept out of the WASI guest by `mise run wasm:wasi-check`). +# Public-key operations only: RUSTSEC-2023-0071 (Marvin) is a timing attack +# on private-key decryption and signing, which this crate never does. +rsa = { version = "0.9", default-features = false, features = ["std"] } [features] default = ["http"] @@ -99,12 +110,19 @@ fuzz = [] name = "auto_strategy" required-features = ["http"] +[[example]] +name = "verify_tokens" +required-features = ["http"] + [[example]] name = "device_code" required-features = ["http", "test-utils"] [dev-dependencies] axum = "0.8" +# The wasm32 RS256 backend is compiled and tested on the host too, against the +# same vectors as the native one (`token_verifier::rs256`). +rsa = { version = "0.9", default-features = false, features = ["std"] } cts-common = { workspace = true } mocktail = "0.3.0" # Version matches the existing use in `vitur-server-core`. diff --git a/packages/stack-auth/README.md b/packages/stack-auth/README.md index 8ffeee0727..e07857da01 100644 --- a/packages/stack-auth/README.md +++ b/packages/stack-auth/README.md @@ -178,6 +178,35 @@ Sensitive values ([`SecretToken`]) are automatically zeroized when dropped and are masked in [`Debug`](std::fmt::Debug) output to prevent accidental leaks in logs. +### Verifying tokens + +By default a strategy trusts the token CTS returns. Call `verify_tokens()` on +a strategy builder to check every token before it is handed out: it must be +signed with RS256 by a key that the trusted issuer publishes at +`/.well-known/jwks.json`, name that issuer as `iss`, and not have +expired (and, for an access key strategy with an `audience`, be for that +audience). A token that fails is refused with [`AuthError::InvalidToken`]. + +The trusted issuer is the CTS that serves the workspace's region. It is +pinned separately from the auth URL: `base_url()` and `CS_CTS_HOST` change +where tokens are requested, never which issuer is trusted, so a redirected +auth URL cannot hand the client a token naming its own ZeroKMS endpoint. Use +`trusted_issuer(url)` to trust a different CTS, such as a staging one. + +```rust,no_run +use stack_auth::{AccessKey, AccessKeyStrategy}; +use cts_common::Crn; + +# fn run() -> Result<(), Box> { +let crn: Crn = "crn:ap-southeast-2.aws:ZVATKW3VHMFG27DY".parse()?; +let key: AccessKey = "CSAKmyKeyId.myKeySecret".parse()?; +let strategy = AccessKeyStrategy::builder(crn, key) + .verify_tokens() + .build()?; +# Ok(()) +# } +``` + ## Token refresh All strategies that cache tokens ([`AccessKeyStrategy`], [`DeviceSessionStrategy`], diff --git a/packages/stack-auth/examples/verify_tokens.rs b/packages/stack-auth/examples/verify_tokens.rs new file mode 100644 index 0000000000..b8d7876fdd --- /dev/null +++ b/packages/stack-auth/examples/verify_tokens.rs @@ -0,0 +1,33 @@ +//! Fetches a token from the real CTS and verifies it before using it. +//! +//! `verify_tokens` checks each token against the signing keys CTS publishes +//! at `/.well-known/jwks.json`, where the issuer is the CTS that +//! serves the workspace's region. This is the live check that CTS's tokens +//! and keys are what the verifier expects (RS256, that issuer, a key it +//! publishes), and CI runs it in `tests-golang.yml`'s `live` job. +//! +//! ```sh +//! CS_CLIENT_ACCESS_KEY= CS_WORKSPACE_CRN= cargo run --example verify_tokens +//! ``` +//! +//! It exits non-zero if the token does not verify. + +use stack_auth::{AuthStrategy, AutoStrategy}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + tracing_subscriber::fmt::init(); + + let strategy = AutoStrategy::builder().verify_tokens().detect()?; + let token = strategy.get_token().await?; + + #[allow(clippy::print_stdout)] + { + println!( + "Verified a CTS token for workspace {} issued by {}", + token.workspace_id()?, + token.issuer()? + ); + } + Ok(()) +} diff --git a/packages/stack-auth/fuzz/Cargo.lock b/packages/stack-auth/fuzz/Cargo.lock index 699f876fac..bc1c6c2745 100644 --- a/packages/stack-auth/fuzz/Cargo.lock +++ b/packages/stack-auth/fuzz/Cargo.lock @@ -210,6 +210,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.10.0" @@ -452,6 +458,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 = "convert_case" version = "0.10.0" @@ -648,6 +660,16 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.5" @@ -693,6 +715,7 @@ 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", ] @@ -1535,6 +1558,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "leb128fmt" version = "0.1.0" @@ -1557,6 +1589,12 @@ dependencies = [ "cc", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.12" @@ -1707,6 +1745,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-conv" version = "0.2.0" @@ -1722,6 +1776,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1729,6 +1793,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -1821,6 +1886,27 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[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.32" @@ -2245,6 +2331,26 @@ dependencies = [ "serde", ] +[[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.1" @@ -2517,6 +2623,7 @@ 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", ] @@ -2586,6 +2693,22 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2597,6 +2720,7 @@ name = "stack-auth" version = "0.43.0" dependencies = [ "aquamarine", + "aws-lc-rs", "base64", "bytes", "cts-common", @@ -2604,6 +2728,7 @@ dependencies = [ "miette", "open", "reqwest", + "rsa", "rustls", "rustls-platform-verifier", "rustls-webpki", diff --git a/packages/stack-auth/src/access_key_strategy.rs b/packages/stack-auth/src/access_key_strategy.rs index 86a8b1a5b2..0482a62ec3 100644 --- a/packages/stack-auth/src/access_key_strategy.rs +++ b/packages/stack-auth/src/access_key_strategy.rs @@ -4,6 +4,7 @@ use crate::access_key::AccessKey; use crate::access_key_refresher::AccessKeyRefresher; use crate::auto_refresh::AutoRefresh; use crate::token_store::{NoStore, TokenStore}; +use crate::token_verifier::{self, TokenVerifier, Verification}; use crate::transport::{self, SharedTransport}; use crate::HttpTransport; use crate::{ensure_trailing_slash, AuthError, AuthStrategy, SecretToken, ServiceToken}; @@ -48,6 +49,7 @@ use crate::{ensure_trailing_slash, AuthError, AuthStrategy, SecretToken, Service pub struct AccessKeyStrategy { inner: AutoRefresh, expected_workspace: WorkspaceId, + verifier: Option, } impl AccessKeyStrategy { @@ -90,14 +92,15 @@ impl AccessKeyStrategy { base_url_override: None, token_store: NoStore, transport: None, + verification: Verification::Off, } } } impl AuthStrategy for &AccessKeyStrategy { async fn get_token(self) -> Result { - self.inner - .get_token() + let token = self.inner.get_token().await?; + token_verifier::verify_if(self.verifier.as_ref(), token) .await? .verify_workspace(self.expected_workspace) } @@ -113,6 +116,7 @@ pub struct AccessKeyStrategyBuilder { base_url_override: Option, token_store: S, transport: Option, + verification: Verification, } impl AccessKeyStrategyBuilder { @@ -134,12 +138,45 @@ impl AccessKeyStrategyBuilder { self.transport = transport; self } + + /// The auto strategy's verification setting, handed through. + pub(crate) fn verification(mut self, verification: Verification) -> Self { + self.verification = verification; + self + } + /// Set the audience for token requests. pub fn audience(mut self, audience: impl Into) -> Self { self.audience = Some(audience.into()); self } + /// Verify every token before [`get_token`](AuthStrategy::get_token) + /// returns it, against the CTS that serves the CRN's region. + /// + /// The token must be signed with RS256 by a key that issuer publishes at + /// `/.well-known/jwks.json`, name that issuer as `iss`, and not + /// have expired; when [`audience`](Self::audience) is set, its `aud` must + /// contain it. The issuer is pinned from the CRN's region, not from + /// [`base_url`](Self::base_url) or `CS_CTS_HOST`, so redirecting where + /// tokens are requested does not change which tokens are accepted. A token + /// that fails is refused with [`AuthError::InvalidToken`]. + pub fn verify_tokens(mut self) -> Self { + self.verification = self.verification.enable(); + self + } + + /// Verify every token against `issuer` instead of the region's CTS. + /// + /// Implies [`verify_tokens`](Self::verify_tokens). For a staging CTS or a + /// local one: unlike [`base_url`](Self::base_url) and `CS_CTS_HOST`, + /// which only change where tokens are requested, this changes which + /// issuer is trusted, so set it only from configuration you control. + pub fn trusted_issuer(mut self, issuer: url::Url) -> Self { + self.verification = Verification::Issuer(issuer); + self + } + /// Override the CTS base URL resolved for this strategy. /// /// Takes precedence over both the `CS_CTS_HOST` environment variable and @@ -174,6 +211,7 @@ impl AccessKeyStrategyBuilder { base_url_override: self.base_url_override, token_store: store, transport: self.transport, + verification: self.verification, } } } @@ -195,15 +233,22 @@ impl AccessKeyStrategyBuilder { crate::cts_base_url_from_env()?.unwrap_or(CtsServiceDiscovery::endpoint(region)?) } }; + let transport = transport::resolve(self.transport)?; + // The trusted issuer comes from the region (or an explicit + // `trusted_issuer`), never from `base_url`: see `token_verifier`. + let verifier = + self.verification + .resolve(|| Ok(region), self.audience.clone(), &transport)?; let refresher = AccessKeyRefresher::new( self.access_key, ensure_trailing_slash(base_url), self.audience, - transport::resolve(self.transport)?, + transport, ); Ok(AccessKeyStrategy { inner: AutoRefresh::with_store(refresher, self.token_store), expected_workspace, + verifier, }) } } diff --git a/packages/stack-auth/src/auto_strategy.rs b/packages/stack-auth/src/auto_strategy.rs index 5f7be7735c..0f98ea405e 100644 --- a/packages/stack-auth/src/auto_strategy.rs +++ b/packages/stack-auth/src/auto_strategy.rs @@ -5,6 +5,7 @@ use crate::device_session_strategy::DeviceSessionStrategy; #[cfg(not(target_arch = "wasm32"))] use stack_profile::ProfileStore; +use crate::token_verifier::Verification; use crate::transport::{self, SharedTransport}; use crate::HttpTransport; #[cfg(not(target_arch = "wasm32"))] @@ -86,6 +87,7 @@ impl AutoStrategy { access_key: None, crn: None, transport: None, + verification: Verification::Off, } } @@ -113,6 +115,7 @@ impl AutoStrategy { crn: Option, store: Option, transport: Option, + verification: Verification, ) -> Result { // 1. Access key from environment if let Some(access_key) = access_key { @@ -122,6 +125,7 @@ impl AutoStrategy { let key: crate::AccessKey = access_key.parse()?; let strategy = AccessKeyStrategy::builder(workspace_crn, key) .maybe_transport(transport) + .verification(verification) .build()?; return Ok(Self::AccessKey(strategy)); } @@ -141,7 +145,10 @@ impl AutoStrategy { if let Some(crn) = &crn { builder = builder.workspace_crn(crn); } - let strategy = builder.maybe_transport(transport).build()?; + let strategy = builder + .maybe_transport(transport) + .verification(verification) + .build()?; return Ok(Self::DeviceSession(strategy)); } } @@ -155,6 +162,7 @@ impl AutoStrategy { access_key: Option<&str>, crn: Option, transport: Option, + verification: Verification, ) -> Result { if let Some(access_key) = access_key { let workspace_crn = crn.ok_or(AuthError::MissingWorkspaceCrn( @@ -163,6 +171,7 @@ impl AutoStrategy { let key: crate::AccessKey = access_key.parse()?; let strategy = AccessKeyStrategy::builder(workspace_crn, key) .maybe_transport(transport) + .verification(verification) .build()?; return Ok(Self::AccessKey(strategy)); } @@ -193,6 +202,7 @@ pub struct AutoStrategyBuilder { access_key: Option, crn: Option, transport: Option, + verification: Verification, } impl AutoStrategyBuilder { @@ -203,6 +213,23 @@ impl AutoStrategyBuilder { self } + /// Verify every token the detected strategy returns, against the CTS that + /// serves the workspace's region. See + /// [`AccessKeyStrategyBuilder::verify_tokens`](crate::AccessKeyStrategyBuilder::verify_tokens) + /// and [`DeviceSessionStrategyBuilder::verify_tokens`](crate::DeviceSessionStrategyBuilder::verify_tokens). + pub fn verify_tokens(mut self) -> Self { + self.verification = self.verification.enable(); + self + } + + /// Verify every token against `issuer` instead of the region's CTS. + /// Implies [`verify_tokens`](Self::verify_tokens); set it only from + /// configuration you control. + pub fn trusted_issuer(mut self, issuer: url::Url) -> Self { + self.verification = Verification::Issuer(issuer); + self + } + /// Provide an explicit access key. Takes precedence over env vars. pub fn with_access_key(mut self, access_key: impl Into) -> Self { self.access_key = Some(SecretToken::new(access_key)); @@ -255,6 +282,7 @@ impl AutoStrategyBuilder { crn, store, self.transport, + self.verification, ) } #[cfg(target_arch = "wasm32")] @@ -263,6 +291,7 @@ impl AutoStrategyBuilder { access_key.as_ref().map(SecretToken::as_str), crn, self.transport, + self.verification, ) } } @@ -363,6 +392,7 @@ mod tests { Some(valid_crn()), None, None, + Verification::Off, ); assert!(result.is_ok()); @@ -371,16 +401,26 @@ mod tests { #[test] fn access_key_without_crn_returns_missing_workspace_crn() { - let result = - AutoStrategy::detect_inner(Some("CSAKtestKeyId.testKeySecret"), None, None, None); + let result = AutoStrategy::detect_inner( + Some("CSAKtestKeyId.testKeySecret"), + None, + None, + None, + Verification::Off, + ); assert!(matches!(result, Err(AuthError::MissingWorkspaceCrn(_)))); } #[test] fn invalid_access_key_format_returns_invalid_access_key() { - let result = - AutoStrategy::detect_inner(Some("not-a-valid-key"), Some(valid_crn()), None, None); + let result = AutoStrategy::detect_inner( + Some("not-a-valid-key"), + Some(valid_crn()), + None, + None, + Verification::Off, + ); assert!(matches!(result, Err(AuthError::InvalidAccessKey(_)))); } @@ -391,7 +431,8 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let store = write_token_store(dir.path()); - let result = AutoStrategy::detect_inner(None, None, Some(store), None); + let result = + AutoStrategy::detect_inner(None, None, Some(store), None, Verification::Off); assert!(result.is_ok()); assert!(matches!(result.unwrap(), AutoStrategy::DeviceSession(_))); @@ -405,7 +446,13 @@ mod tests { // The CLI user switches to another workspace with no session. store.init_workspace("AAAAAAAAAAAAAAAA").unwrap(); - let result = AutoStrategy::detect_inner(None, Some(valid_crn()), Some(store), None); + let result = AutoStrategy::detect_inner( + None, + Some(valid_crn()), + Some(store), + None, + Verification::Off, + ); assert!(matches!(result, Ok(AutoStrategy::DeviceSession(_)))); } @@ -416,7 +463,13 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let store = write_token_store(dir.path()); - let result = AutoStrategy::detect_inner(None, Some(valid_crn()), Some(store), None); + let result = AutoStrategy::detect_inner( + None, + Some(valid_crn()), + Some(store), + None, + Verification::Off, + ); assert!(matches!(result, Ok(AutoStrategy::DeviceSession(_)))); } @@ -429,7 +482,8 @@ mod tests { let store = write_token_store(dir.path()); let crn: Crn = "crn:ap-southeast-2.aws:AAAAAAAAAAAAAAAA".parse().unwrap(); - let result = AutoStrategy::detect_inner(None, Some(crn), Some(store), None); + let result = + AutoStrategy::detect_inner(None, Some(crn), Some(store), None, Verification::Off); assert!(matches!(result, Err(AuthError::NotAuthenticated(_)))); } @@ -439,14 +493,15 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let store = ProfileStore::new(dir.path()); - let result = AutoStrategy::detect_inner(None, None, Some(store), None); + let result = + AutoStrategy::detect_inner(None, None, Some(store), None, Verification::Off); assert!(matches!(result, Err(AuthError::NotAuthenticated(_)))); } #[test] fn no_credentials_returns_not_authenticated() { - let result = AutoStrategy::detect_inner(None, None, None, None); + let result = AutoStrategy::detect_inner(None, None, None, None, Verification::Off); assert!(matches!(result, Err(AuthError::NotAuthenticated(_)))); } @@ -462,6 +517,7 @@ mod tests { Some(valid_crn()), Some(store), None, + Verification::Off, ); assert!(result.is_ok()); diff --git a/packages/stack-auth/src/device_session_strategy.rs b/packages/stack-auth/src/device_session_strategy.rs index eee2704a7e..04e4c0134e 100644 --- a/packages/stack-auth/src/device_session_strategy.rs +++ b/packages/stack-auth/src/device_session_strategy.rs @@ -5,6 +5,7 @@ use stack_profile::ProfileStore; use crate::auto_refresh::AutoRefresh; use crate::device_session_refresher::{ensure_workspace, DeviceSessionRefresher}; +use crate::token_verifier::{self, TokenVerifier, Verification}; use crate::transport::{self, SharedTransport}; use crate::{ensure_trailing_slash, AuthError, AuthStrategy, HttpTransport, ServiceToken, Token}; @@ -37,6 +38,7 @@ pub struct DeviceSessionStrategy { crn: Option, /// When set, every token is checked against this workspace. expected_workspace: Option, + verifier: Option, inner: AutoRefresh, } @@ -59,6 +61,7 @@ impl DeviceSessionStrategy { base_url_override: None, transport: None, expected_workspace: None, + verification: Verification::Off, } } @@ -76,6 +79,7 @@ impl DeviceSessionStrategy { base_url_override: None, transport: None, expected_workspace: None, + verification: Verification::Off, } } @@ -90,6 +94,7 @@ impl DeviceSessionStrategy { base_url_override: None, transport: None, expected_workspace: None, + verification: Verification::Off, } } @@ -102,6 +107,7 @@ impl DeviceSessionStrategy { impl AuthStrategy for &DeviceSessionStrategy { async fn get_token(self) -> Result { let token = self.inner.get_token().await?; + let token = token_verifier::verify_if(self.verifier.as_ref(), token).await?; match self.expected_workspace { Some(expected) => token.verify_workspace(expected), None => Ok(token), @@ -130,9 +136,44 @@ pub struct DeviceSessionStrategyBuilder { base_url_override: Option, transport: Option, expected_workspace: Option, + verification: Verification, } impl DeviceSessionStrategyBuilder { + /// Verify every token before [`get_token`](AuthStrategy::get_token) + /// returns it, against the CTS that serves the session's region. + /// + /// The token must be signed with RS256 by a key that issuer publishes at + /// `/.well-known/jwks.json`, name that issuer as `iss`, and not + /// have expired. The issuer is pinned from the region (the one passed to + /// [`with_token`](DeviceSessionStrategy::with_token), or the one saved + /// with the session), not from [`base_url`](Self::base_url), + /// `CS_CTS_HOST` or the saved token's own `iss`, so redirecting where + /// tokens are requested does not change which tokens are accepted. A token + /// that fails is refused with [`AuthError::InvalidToken`]. + pub fn verify_tokens(mut self) -> Self { + self.verification = self.verification.enable(); + self + } + + /// Verify every token against `issuer` instead of the region's CTS. + /// + /// Implies [`verify_tokens`](Self::verify_tokens). For a staging CTS or a + /// local one: unlike [`base_url`](Self::base_url) and `CS_CTS_HOST`, + /// which only change where tokens are requested, this changes which + /// issuer is trusted, so set it only from configuration you control. + pub fn trusted_issuer(mut self, issuer: url::Url) -> Self { + self.verification = Verification::Issuer(issuer); + self + } + + /// The auto strategy's verification setting, handed through. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn verification(mut self, verification: Verification) -> Self { + self.verification = verification; + self + } + /// Pin the strategy to the workspace named by `crn`. /// /// Every token returned by `get_token` is checked against the CRN's @@ -196,6 +237,7 @@ impl DeviceSessionStrategyBuilder { base_url_override, transport, expected_workspace, + verification, } = self; let transport = transport::resolve(transport)?; match source { @@ -210,6 +252,7 @@ impl DeviceSessionStrategyBuilder { base_url_override, transport, expected_workspace, + verification, ), OAuthTokenSource::Store(store) => { let ws_store = match expected_workspace { @@ -221,6 +264,7 @@ impl DeviceSessionStrategyBuilder { base_url_override, transport, expected_workspace, + verification, ) } OAuthTokenSource::WorkspaceStore(store) => Self::build_from_workspace_store( @@ -228,6 +272,7 @@ impl DeviceSessionStrategyBuilder { base_url_override, transport, expected_workspace, + verification, ), } } @@ -240,7 +285,9 @@ impl DeviceSessionStrategyBuilder { base_url_override: Option, transport: SharedTransport, expected_workspace: Option, + verification: Verification, ) -> Result { + let verifier = verification.resolve(|| Ok(region), None, &transport)?; let base_url = match base_url_override { Some(url) => url, None => { @@ -275,6 +322,7 @@ impl DeviceSessionStrategyBuilder { Ok(DeviceSessionStrategy { crn, expected_workspace, + verifier, inner: AutoRefresh::with_token(refresher, token), }) } @@ -285,6 +333,7 @@ impl DeviceSessionStrategyBuilder { base_url_override: Option, transport: SharedTransport, expected_workspace: Option, + verification: Verification, ) -> Result { let token: Token = ws_store.load_profile()?; // Before `AutoRefresh` can see it: refreshing another workspace's @@ -307,6 +356,9 @@ impl DeviceSessionStrategyBuilder { }) .ok(); let device_instance_id = token.device_instance_id().map(String::from); + // The region saved with the session, not the token's `iss`: the + // issuer a saved token names is exactly what is being checked. + let verifier = verification.resolve(|| Ok(Region::new(®ion_str)?), None, &transport)?; let base_url = match base_url_override { Some(url) => url, @@ -325,6 +377,7 @@ impl DeviceSessionStrategyBuilder { Ok(DeviceSessionStrategy { crn, expected_workspace, + verifier, inner: AutoRefresh::with_token(refresher, token), }) } diff --git a/packages/stack-auth/src/lib.rs b/packages/stack-auth/src/lib.rs index 11adc7bb85..db84fb1715 100644 --- a/packages/stack-auth/src/lib.rs +++ b/packages/stack-auth/src/lib.rs @@ -59,6 +59,7 @@ mod error; mod service_token; mod token; mod token_store; +mod token_verifier; mod transport; // The strategies that acquire and refresh tokens over HTTP, and the refresh diff --git a/packages/stack-auth/src/oidc_federation_strategy.rs b/packages/stack-auth/src/oidc_federation_strategy.rs index 177789e53c..bd399db3f3 100644 --- a/packages/stack-auth/src/oidc_federation_strategy.rs +++ b/packages/stack-auth/src/oidc_federation_strategy.rs @@ -9,6 +9,7 @@ use crate::auto_refresh::{AutoRefresh, StickyDenial}; use crate::clock::{system_clock, SharedClock}; use crate::oidc_refresher::{JwtDigest, JwtRefresher, OidcFederation, OidcProvider}; use crate::token_store::{NoStore, TokenStore}; +use crate::token_verifier::{self, TokenVerifier, Verification}; use crate::transport::{self, SharedTransport}; use crate::HttpTransport; use crate::{ensure_trailing_slash, AuthError, AuthStrategy, SecretToken, ServiceToken, Token}; @@ -103,6 +104,7 @@ pub struct OidcFederationStrategy { federation: Arc, store: Arc, expected_workspace: WorkspaceId, + verifier: Option, engines: Mutex>, /// The last account-level refusal (a usage limit, an unprovisioned org), /// remembered for the strategy as a whole. @@ -198,6 +200,7 @@ impl OidcFederationStrategy

{ transport: None, cache_capacity: DEFAULT_CACHE_CAPACITY, clock: system_clock(), + verification: Verification::Off, } } } @@ -382,7 +385,9 @@ impl OidcFederationStrategy { return Err(err); } }; - token.verify_workspace(self.expected_workspace) + token_verifier::verify_if(self.verifier.as_ref(), token) + .await? + .verify_workspace(self.expected_workspace) } } @@ -406,6 +411,7 @@ pub struct OidcFederationStrategyBuilder { transport: Option, cache_capacity: usize, clock: SharedClock, + verification: Verification, } impl OidcFederationStrategyBuilder { @@ -428,6 +434,31 @@ impl OidcFederationStrategyBuilder { self.transport = Some(transport::share(transport)); self } + /// Verify every CTS token before it is returned, against the CTS that + /// serves the CRN's region. + /// + /// The token must be signed with RS256 by a key that issuer publishes at + /// `/.well-known/jwks.json`, name that issuer as `iss`, and not + /// have expired. The issuer is pinned from the CRN's region, not from + /// [`base_url`](Self::base_url) or `CS_CTS_HOST`, so redirecting where + /// tokens are requested does not change which tokens are accepted. A token + /// that fails is refused with [`AuthError::InvalidToken`]. + pub fn verify_tokens(mut self) -> Self { + self.verification = self.verification.enable(); + self + } + + /// Verify every CTS token against `issuer` instead of the region's CTS. + /// + /// Implies [`verify_tokens`](Self::verify_tokens). For a staging CTS or a + /// local one: unlike [`base_url`](Self::base_url) and `CS_CTS_HOST`, + /// which only change where tokens are requested, this changes which + /// issuer is trusted, so set it only from configuration you control. + pub fn trusted_issuer(mut self, issuer: url::Url) -> Self { + self.verification = Verification::Issuer(issuer); + self + } + /// Override the base URL resolved by service discovery. /// /// Takes precedence over both the `CS_CTS_HOST` environment variable and @@ -502,6 +533,7 @@ impl OidcFederationStrategyBuilder { transport: self.transport, cache_capacity: self.cache_capacity, clock: self.clock, + verification: self.verification, } } } @@ -523,16 +555,21 @@ impl OidcFederationStrategyBuilder { crate::cts_base_url_from_env()?.unwrap_or(CtsServiceDiscovery::endpoint(region)?) } }; + let transport = transport::resolve(self.transport)?; + // The trusted issuer comes from the region (or an explicit + // `trusted_issuer`), never from `base_url`: see `token_verifier`. + let verifier = self.verification.resolve(|| Ok(region), None, &transport)?; let federation = OidcFederation::new( expected_workspace, ensure_trailing_slash(base_url), - transport::resolve(self.transport)?, + transport, ); Ok(OidcFederationStrategy { provider: self.oidc_provider, federation: Arc::new(federation), store: Arc::new(self.token_store), expected_workspace, + verifier, engines: Mutex::new(Engines { cache: JwtCache::new(self.cache_capacity), pending: HashMap::new(), diff --git a/packages/stack-auth/src/test_support.rs b/packages/stack-auth/src/test_support.rs index ec6b92ba31..20afbf791f 100644 --- a/packages/stack-auth/src/test_support.rs +++ b/packages/stack-auth/src/test_support.rs @@ -107,3 +107,162 @@ pub(crate) fn jwt_for_principal(workspace: &str, sub: &str) -> String { ) .expect("JWT encode") } + +/// RS256 keys and a stub CTS that signs with them, for exercising token +/// verification (`token_verifier`) without a real CTS. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod signing { + use std::sync::{LazyLock, Mutex}; + + use aws_lc_rs::rand::SystemRandom; + use aws_lc_rs::rsa::{KeyPair, KeySize, PublicKeyComponents}; + use aws_lc_rs::signature::{KeyPair as _, RSA_PKCS1_SHA256}; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use base64::Engine; + + use crate::error::RequestError; + use crate::transport::{HttpRequest, HttpResponse, HttpTransport}; + + /// RSA keys are slow to generate, so each test borrows these. + pub(crate) static KEY_A: LazyLock = LazyLock::new(|| TestKey::generate("key-a")); + pub(crate) static KEY_B: LazyLock = LazyLock::new(|| TestKey::generate("key-b")); + + pub(crate) struct TestKey { + pub(crate) kid: &'static str, + pair: KeyPair, + } + + impl TestKey { + pub(crate) fn generate(kid: &'static str) -> Self { + Self { + kid, + pair: KeyPair::generate(KeySize::Rsa2048).unwrap(), + } + } + + pub(crate) fn components(&self) -> PublicKeyComponents> { + PublicKeyComponents::from(self.pair.public_key()) + } + + pub(crate) fn jwk(&self) -> serde_json::Value { + let public = self.components(); + serde_json::json!({ + "kty": "RSA", + "kid": self.kid, + "alg": "RS256", + "use": "sig", + "n": URL_SAFE_NO_PAD.encode(&public.n), + "e": URL_SAFE_NO_PAD.encode(&public.e), + }) + } + + pub(crate) fn sign(&self, message: &[u8]) -> Vec { + let mut signature = vec![0; self.pair.public_modulus_len()]; + self.pair + .sign( + &RSA_PKCS1_SHA256, + &SystemRandom::new(), + message, + &mut signature, + ) + .unwrap(); + signature + } + + /// A compact JWT over `header` and `claims`, signed with this key. + pub(crate) fn jwt_with_header( + &self, + header: serde_json::Value, + claims: serde_json::Value, + ) -> String { + let signed = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(header.to_string()), + URL_SAFE_NO_PAD.encode(claims.to_string()), + ); + let signature = self.sign(signed.as_bytes()); + format!("{signed}.{}", URL_SAFE_NO_PAD.encode(signature)) + } + + pub(crate) fn jwt(&self, claims: serde_json::Value) -> String { + self.jwt_with_header( + serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": self.kid}), + claims, + ) + } + } + + /// A JWKS publishing `keys`. + pub(crate) fn jwks(keys: &[&TestKey]) -> String { + serde_json::json!({ "keys": keys.iter().map(|key| key.jwk()).collect::>() }) + .to_string() + } + + /// A stub CTS: `POST .../api/authorise` returns `token`, and + /// `GET .../.well-known/jwks.json` returns `jwks`, whatever the host. It + /// records each `(method, url)` it is sent. + pub(crate) struct StubCts { + token: String, + jwks: String, + seen: Mutex>, + } + + impl StubCts { + pub(crate) fn new(token: String, jwks: String) -> Self { + Self { + token, + jwks, + seen: Mutex::new(Vec::new()), + } + } + + /// The URLs of the JWKS requests the stub has seen. + pub(crate) fn jwks_requests(&self) -> Vec { + self.seen + .lock() + .unwrap() + .iter() + .filter(|(method, _)| method == "GET") + .map(|(_, url)| url.clone()) + .collect() + } + } + + impl HttpTransport for StubCts { + async fn send(&self, request: HttpRequest) -> Result { + let url = request.url().clone(); + self.seen + .lock() + .unwrap() + .push((request.method().to_string(), url.to_string())); + let body = match (request.method(), url.path()) { + ("GET", path) if path.ends_with("/.well-known/jwks.json") => self.jwks.clone(), + ("POST", path) if path.ends_with("/api/authorise") => serde_json::json!({ + "accessToken": self.token, + "expiry": u64::from(u32::MAX), + }) + .to_string(), + _ => return Ok(HttpResponse::new(404, Vec::new(), Vec::new())), + }; + Ok(HttpResponse::new(200, Vec::new(), body.into_bytes())) + } + } + + /// CTS claims for `workspace`, issued by `iss`, valid for an hour. + pub(crate) fn claims(iss: &str, workspace: &str) -> serde_json::Value { + let now = web_time::SystemTime::now() + .duration_since(web_time::UNIX_EPOCH) + .unwrap() + .as_secs(); + serde_json::json!({ + "iss": iss, + "sub": "CS|test-principal", + "aud": "test-audience", + "iat": now, + "exp": now + 3600, + "workspace": workspace, + "org_id": "org_test_default", + "scope": "", + }) + } +} diff --git a/packages/stack-auth/src/token_verifier.rs b/packages/stack-auth/src/token_verifier.rs new file mode 100644 index 0000000000..6889fcd9d4 --- /dev/null +++ b/packages/stack-auth/src/token_verifier.rs @@ -0,0 +1,472 @@ +//! Verification of the access tokens CTS issues, before a strategy hands one +//! out. +//! +//! Without it the client trusts whatever `authorize` returned: whoever +//! controls the auth URL (an injected `CS_CTS_HOST`, a compromised +//! dependency, a poisoned token store) can hand the client a token naming +//! any scopes, any issuer and any ZeroKMS endpoint, and the client sends key +//! requests where that token says. +//! +//! A [`TokenVerifier`] checks every token against a **trusted issuer that is +//! pinned separately from the auth URL**: by default the CTS host that +//! service discovery names for the workspace's region, or one set +//! explicitly with a builder's `trusted_issuer`. The base URL override and +//! `CS_CTS_HOST` change where tokens are *requested*; they never change which +//! issuer is *trusted*. For each token it checks, in this order: +//! +//! 1. the header names `RS256` (what CTS signs with) — nothing else, +//! `none` and the HMAC algorithms in particular, is accepted; +//! 2. `iss` is the trusted issuer; +//! 3. `exp` has not passed (with [`LEEWAY_SECS`] of clock skew allowed); +//! 4. `aud` contains the expected audience, when the strategy requested one; +//! 5. the signature verifies under a key from the trusted issuer's JWKS +//! (`/.well-known/jwks.json`), never from a URL the token names. +//! +//! A token that fails any check is refused with one opaque +//! [`AuthError::InvalidToken`]; which check failed is logged at `warn`, and +//! nothing from the token itself is. +//! +//! The JWKS is cached for [`KEYS_TTL_SECS`]. A token signed by a key the +//! cache does not hold triggers one early refetch, so a rotated key works +//! immediately, but no more than once every [`MIN_REFETCH_SECS`], so a run of +//! forged `kid`s cannot turn every call into a request to CTS. + +use std::fmt; + +use cts_common::claims::Audience; +use cts_common::{CtsServiceDiscovery, Region, ServiceDiscovery}; +use url::Url; + +use crate::clock::{system_clock, SharedClock}; +use crate::error::{InvalidToken, ServerError}; +use crate::transport::{self, SharedTransport}; +use crate::{AuthError, ServiceToken}; + +/// Clock skew allowed on `exp`, matching what ZeroKMS allows. +pub(crate) const LEEWAY_SECS: u64 = 60; + +/// How long a fetched JWKS is used before it is fetched again. +pub(crate) const KEYS_TTL_SECS: u64 = 60 * 60; + +/// The shortest interval between two fetches of the JWKS. +pub(crate) const MIN_REFETCH_SECS: u64 = 60; + +/// The only signing algorithm accepted: CTS signs with RSASSA-PKCS1-v1_5 and +/// SHA-256. +const ALGORITHM: &str = "RS256"; + +/// The message every refused token gets. Which check failed is logged, not +/// returned (see the module docs). +const REFUSED: &str = + "the access token could not be verified against the trusted CTS issuer's signing keys"; + +/// What a strategy builder was asked to do about verification. +/// +/// Resolved into a [`TokenVerifier`] at `build`, once the builder knows the +/// region and the transport. +#[derive(Clone, Debug, Default)] +pub(crate) enum Verification { + /// Tokens are not verified (the default, for now). + #[default] + Off, + /// Verify against the CTS that service discovery names for the region. + RegionIssuer, + /// Verify against this issuer. + Issuer(Url), +} + +impl Verification { + /// Verify against the region's CTS, unless an issuer is already pinned. + pub(crate) fn enable(self) -> Self { + match self { + Verification::Off => Verification::RegionIssuer, + pinned => pinned, + } + } + + /// The verifier this setting asks for, or `None` when it is off. + /// + /// `region` is asked for only when the issuer comes from it, so a + /// strategy with verification off fails in no new way. + pub(crate) fn resolve( + self, + region: impl FnOnce() -> Result, + audience: Option, + transport: &SharedTransport, + ) -> Result, AuthError> { + let issuer = match self { + Verification::Off => return Ok(None), + Verification::RegionIssuer => CtsServiceDiscovery::endpoint(region()?)?, + Verification::Issuer(issuer) => issuer, + }; + TokenVerifier::new(issuer, audience, transport.clone(), system_clock()).map(Some) + } +} + +/// `token`, verified by `verifier` when there is one. +pub(crate) async fn verify_if( + verifier: Option<&TokenVerifier>, + token: ServiceToken, +) -> Result { + match verifier { + Some(verifier) => verifier.verify(token).await, + None => Ok(token), + } +} + +/// Verifies CTS access tokens against a pinned issuer's signing keys. See the +/// module docs. +pub(crate) struct TokenVerifier { + issuer: Url, + jwks_url: Url, + audience: Option, + transport: SharedTransport, + clock: SharedClock, + keys: tokio::sync::Mutex, +} + +#[derive(Default)] +struct KeyCache { + keys: Vec, + /// When the keys were last fetched; `None` before the first fetch. + fetched_at: Option, +} + +/// One RSA public key from the JWKS, as big-endian modulus and exponent. +#[derive(Clone)] +struct SigningKey { + kid: Option, + n: Vec, + e: Vec, +} + +impl TokenVerifier { + pub(crate) fn new( + issuer: Url, + audience: Option, + transport: SharedTransport, + clock: SharedClock, + ) -> Result { + let issuer = crate::ensure_trailing_slash(issuer); + let jwks_url = cts_common::oidc::jwks_url(issuer.as_str())?; + Ok(Self { + issuer, + jwks_url, + audience, + transport, + clock, + keys: tokio::sync::Mutex::new(KeyCache::default()), + }) + } + + /// Return `token` if it verifies, else [`AuthError::InvalidToken`]. + /// + /// A failure to fetch the signing keys is the transport's or the + /// server's error ([`AuthError::Request`] or [`AuthError::Server`]), not + /// the token's: it says nothing about whether the token is genuine. + pub(crate) async fn verify(&self, token: ServiceToken) -> Result { + match self.check(token.as_str()).await? { + Ok(()) => Ok(token), + Err(rejection) => { + tracing::warn!( + issuer = %self.issuer, + %rejection, + "refused an access token that did not verify" + ); + Err(AuthError::InvalidToken(InvalidToken(REFUSED.to_string()))) + } + } + } + + /// The outer `Result` is a failure to fetch the keys; the inner one is + /// the verdict on the token. + async fn check(&self, token: &str) -> Result, AuthError> { + let parts = match Parts::split(token) { + Ok(parts) => parts, + Err(rejection) => return Ok(Err(rejection)), + }; + if let Err(rejection) = self.check_claims(&parts) { + return Ok(Err(rejection)); + } + let Some(key) = self.key_for(parts.header.kid.as_deref()).await? else { + return Ok(Err(Rejection::UnknownKey)); + }; + if rs256::verify(&key, parts.signed.as_bytes(), &parts.signature) { + Ok(Ok(())) + } else { + Ok(Err(Rejection::Signature)) + } + } + + fn check_claims(&self, parts: &Parts<'_>) -> Result<(), Rejection> { + if parts.header.alg != ALGORITHM { + return Err(Rejection::Algorithm(parts.header.alg.clone())); + } + let claims = &parts.claims; + let issuer = Url::parse(&claims.iss) + .map(crate::ensure_trailing_slash) + .map_err(|_| Rejection::Issuer)?; + if issuer != self.issuer { + return Err(Rejection::Issuer); + } + if claims.exp.saturating_add(LEEWAY_SECS) <= self.clock.now_unix_secs() { + return Err(Rejection::Expired); + } + if let Some(expected) = &self.audience { + if !claims + .aud + .as_ref() + .is_some_and(|aud| aud.contains(expected)) + { + return Err(Rejection::Audience); + } + } + Ok(()) + } + + /// The key `kid` names, fetching the JWKS when the cache is empty or + /// stale, or when it lacks that key and was not fetched too recently. + /// + /// The lock is held across the fetch, so concurrent callers wait for one + /// request rather than each sending their own. + async fn key_for(&self, kid: Option<&str>) -> Result, AuthError> { + let mut cache = self.keys.lock().await; + let now = self.clock.now_unix_secs(); + let age = cache.fetched_at.map(|at| now.saturating_sub(at)); + let stale = age.is_none_or(|age| age >= KEYS_TTL_SECS); + if !stale { + if let Some(key) = cache.find(kid) { + return Ok(Some(key)); + } + if age.is_some_and(|age| age < MIN_REFETCH_SECS) { + return Ok(None); + } + } + cache.keys = self.fetch_keys().await?; + cache.fetched_at = Some(now); + Ok(cache.find(kid)) + } + + async fn fetch_keys(&self) -> Result, AuthError> { + tracing::debug!(url = %self.jwks_url, "fetching CTS signing keys"); + let response = + transport::get(&self.transport, self.jwks_url.clone(), "application/json").await?; + if !response.is_success() { + return Err(AuthError::Server(ServerError::refused( + response.status(), + &response.text(), + ))); + } + let jwks: Jwks = response.json().map_err(|_| { + AuthError::InvalidToken(InvalidToken( + "CTS's signing keys (its JWKS) could not be read".to_string(), + )) + })?; + Ok(jwks.keys.into_iter().filter_map(Jwk::into_key).collect()) + } +} + +impl KeyCache { + /// The key named `kid`. A token with no `kid` may only use a JWKS that + /// holds exactly one key, so the choice is never a guess. + fn find(&self, kid: Option<&str>) -> Option { + match kid { + Some(kid) => self + .keys + .iter() + .find(|key| key.kid.as_deref() == Some(kid)) + .cloned(), + None => match self.keys.as_slice() { + [only] => Some(only.clone()), + _ => None, + }, + } + } +} + +/// Why a token was refused. Logged, never returned. +#[derive(Debug)] +enum Rejection { + Malformed, + /// The header's algorithm, which CTS chose rather than the caller, so it + /// is safe to log. + Algorithm(String), + Issuer, + Expired, + Audience, + UnknownKey, + Signature, +} + +impl fmt::Display for Rejection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Rejection::Malformed => f.write_str("the token is not a well-formed JWT"), + Rejection::Algorithm(alg) => write!(f, "the token is signed with {alg:?}, not RS256"), + Rejection::Issuer => f.write_str("the token's issuer is not the trusted issuer"), + Rejection::Expired => f.write_str("the token has expired"), + Rejection::Audience => f.write_str("the token is not for the expected audience"), + Rejection::UnknownKey => { + f.write_str("the token's signing key is not one the trusted issuer publishes") + } + Rejection::Signature => f.write_str("the token's signature does not verify"), + } + } +} + +/// A JWT split into what verification needs. +struct Parts<'a> { + header: Header, + claims: Claims, + /// `header.claims`, the bytes the signature covers. + signed: &'a str, + signature: Vec, +} + +#[derive(serde::Deserialize)] +struct Header { + alg: String, + #[serde(default)] + kid: Option, +} + +/// The claims verification checks. The rest are read, unverified, by +/// [`ServiceToken`]; once this check has passed they are the issuer's. +#[derive(serde::Deserialize)] +struct Claims { + iss: String, + exp: u64, + #[serde(default)] + aud: Option, +} + +impl<'a> Parts<'a> { + fn split(token: &'a str) -> Result { + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use base64::Engine; + + let (signed, signature) = token.rsplit_once('.').ok_or(Rejection::Malformed)?; + let (header, claims) = signed.split_once('.').ok_or(Rejection::Malformed)?; + let decode = |segment: &str| { + URL_SAFE_NO_PAD + .decode(segment) + .map_err(|_| Rejection::Malformed) + }; + let header = serde_json::from_slice(&decode(header)?).map_err(|_| Rejection::Malformed)?; + let claims = serde_json::from_slice(&decode(claims)?).map_err(|_| Rejection::Malformed)?; + Ok(Self { + header, + claims, + signed, + signature: decode(signature)?, + }) + } +} + +#[derive(serde::Deserialize)] +struct Jwks { + keys: Vec, +} + +/// One entry of a JWKS. Only RSA signing keys are kept; anything else in the +/// set is ignored rather than failing the whole set. +#[derive(serde::Deserialize)] +struct Jwk { + kty: String, + #[serde(default)] + kid: Option, + #[serde(default)] + alg: Option, + #[serde(default, rename = "use")] + key_use: Option, + #[serde(default)] + n: Option, + #[serde(default)] + e: Option, +} + +impl Jwk { + fn into_key(self) -> Option { + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use base64::Engine; + + if self.kty != "RSA" + || self.alg.as_deref().is_some_and(|alg| alg != ALGORITHM) + || self + .key_use + .as_deref() + .is_some_and(|key_use| key_use != "sig") + { + return None; + } + Some(SigningKey { + kid: self.kid, + n: URL_SAFE_NO_PAD.decode(self.n?).ok()?, + e: URL_SAFE_NO_PAD.decode(self.e?).ok()?, + }) + } +} + +/// RSASSA-PKCS1-v1_5 with SHA-256 over a key from the JWKS. +/// +/// aws-lc-rs where it builds; RustCrypto's `rsa` on wasm32, where it does +/// not. Both refuse a modulus under 2048 bits. The RustCrypto backend is also +/// compiled into the host's tests, so both are run against the same vectors. +mod rs256 { + use super::SigningKey; + + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn verify(key: &SigningKey, message: &[u8], signature: &[u8]) -> bool { + aws_lc::verify(key, message, signature) + } + + #[cfg(target_arch = "wasm32")] + pub(super) fn verify(key: &SigningKey, message: &[u8], signature: &[u8]) -> bool { + rust_crypto::verify(key, message, signature) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(super) mod aws_lc { + use super::SigningKey; + use aws_lc_rs::signature::{RsaPublicKeyComponents, RSA_PKCS1_2048_8192_SHA256}; + + pub(in super::super) fn verify(key: &SigningKey, message: &[u8], signature: &[u8]) -> bool { + RsaPublicKeyComponents { + n: &key.n, + e: &key.e, + } + .verify(&RSA_PKCS1_2048_8192_SHA256, message, signature) + .is_ok() + } + } + + #[cfg(any(target_arch = "wasm32", test))] + pub(super) mod rust_crypto { + use super::SigningKey; + use rsa::pkcs1v15::{Signature, VerifyingKey}; + use rsa::signature::Verifier; + use rsa::{BigUint, RsaPublicKey}; + + const MIN_MODULUS_BITS: usize = 2048; + + pub(in super::super) fn verify(key: &SigningKey, message: &[u8], signature: &[u8]) -> bool { + let n = BigUint::from_bytes_be(&key.n); + if n.bits() < MIN_MODULUS_BITS { + return false; + } + let Ok(public) = RsaPublicKey::new(n, BigUint::from_bytes_be(&key.e)) else { + return false; + }; + let Ok(signature) = Signature::try_from(signature) else { + return false; + }; + VerifyingKey::::new(public) + .verify(message, &signature) + .is_ok() + } + } +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests; diff --git a/packages/stack-auth/src/token_verifier/tests.rs b/packages/stack-auth/src/token_verifier/tests.rs new file mode 100644 index 0000000000..09cf662bc0 --- /dev/null +++ b/packages/stack-auth/src/token_verifier/tests.rs @@ -0,0 +1,885 @@ +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; + +use super::*; +use crate::clock::Clock; +use crate::error::RequestError; +use crate::test_support::signing::{TestKey, KEY_A, KEY_B}; +use crate::transport::{HttpRequest, HttpResponse, HttpTransport}; +use crate::SecretToken; + +const ISSUER: &str = "https://ap-southeast-2.aws.cts.cipherstashmanaged.net/"; +const NOW: u64 = 1_800_000_000; + +fn signing_key(key: &TestKey) -> SigningKey { + let public = key.components(); + SigningKey { + kid: Some(key.kid.to_string()), + n: public.n, + e: public.e, + } +} + +fn claims() -> serde_json::Value { + serde_json::json!({ + "iss": ISSUER, + "sub": "CS|CSAKkeyId", + "aud": "ap-southeast-2.aws.viturhosted.net", + "iat": NOW - 10, + "exp": NOW + 3600, + "workspace": "ZVATKW3VHMFG27DY", + "scope": "", + "services": {"zerokms": "https://ap-southeast-2.aws.viturhosted.net/"}, + }) +} + +fn with(mut claims: serde_json::Value, key: &str, value: serde_json::Value) -> serde_json::Value { + claims[key] = value; + claims +} + +fn token(jwt: String) -> ServiceToken { + ServiceToken::new(SecretToken::new(jwt)) +} + +fn jwks(keys: &[&TestKey]) -> String { + crate::test_support::signing::jwks(keys) +} + +/// A CTS that serves a JWKS and records each URL it is asked for. +struct FakeCts { + status: AtomicU64, + jwks: Mutex, + fail: bool, + requests: Mutex>, +} + +impl FakeCts { + fn serving(jwks: String) -> Arc { + Arc::new(Self { + status: AtomicU64::new(200), + jwks: Mutex::new(jwks), + fail: false, + requests: Mutex::new(Vec::new()), + }) + } + + fn unreachable() -> Arc { + Arc::new(Self { + status: AtomicU64::new(200), + jwks: Mutex::new(String::new()), + fail: true, + requests: Mutex::new(Vec::new()), + }) + } + + fn rotate_to(&self, jwks: String) { + *self.jwks.lock().unwrap() = jwks; + } + + fn requests(&self) -> Vec<(String, String)> { + self.requests.lock().unwrap().clone() + } +} + +impl HttpTransport for FakeCts { + async fn send(&self, request: HttpRequest) -> Result { + self.requests + .lock() + .unwrap() + .push((request.method().to_string(), request.url().to_string())); + if self.fail { + return Err(RequestError(Box::new(std::io::Error::other("unreachable")))); + } + let status = self.status.load(Ordering::SeqCst) as u16; + let body = self.jwks.lock().unwrap().clone().into_bytes(); + Ok(HttpResponse::new(status, Vec::new(), body)) + } +} + +/// A clock the test moves by hand. +struct ManualClock(AtomicU64); + +impl ManualClock { + fn at(now: u64) -> Arc { + Arc::new(Self(AtomicU64::new(now))) + } + + fn advance(&self, secs: u64) { + let _ = self.0.fetch_add(secs, Ordering::SeqCst); + } +} + +impl Clock for ManualClock { + fn now_unix_secs(&self) -> u64 { + self.0.load(Ordering::SeqCst) + } +} + +fn verifier(cts: &Arc, clock: &Arc) -> TokenVerifier { + verifier_for(cts, clock, None) +} + +fn verifier_for( + cts: &Arc, + clock: &Arc, + audience: Option<&str>, +) -> TokenVerifier { + TokenVerifier::new( + ISSUER.parse().unwrap(), + audience.map(str::to_string), + transport::share(Arc::clone(cts)), + clock.clone(), + ) + .unwrap() +} + +/// The verdict: `Ok` with the token back, or the refusal's message. +async fn verdict(verifier: &TokenVerifier, jwt: String) -> Result<(), String> { + match verifier.verify(token(jwt.clone())).await { + Ok(token) => { + assert_eq!(token.as_str(), jwt, "a verified token comes back unchanged"); + Ok(()) + } + Err(AuthError::InvalidToken(InvalidToken(message))) => { + assert!( + !message.contains(&jwt), + "a refusal must not quote the token, got: {message}" + ); + Err(message) + } + Err(other) => panic!("expected InvalidToken, got {other:?}"), + } +} + +mod given_a_token_signed_by_the_trusted_issuer { + use super::*; + + #[tokio::test] + async fn it_is_accepted() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + assert_eq!(verdict(&verifier, KEY_A.jwt(claims())).await, Ok(())); + } + + #[tokio::test] + async fn the_keys_come_from_the_pinned_issuers_jwks() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + assert_eq!( + cts.requests(), + vec![("GET".to_string(), format!("{ISSUER}.well-known/jwks.json"))], + ); + } + + #[tokio::test] + async fn an_issuer_differing_only_by_a_trailing_slash_is_the_same_issuer() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let iss = ISSUER.trim_end_matches('/'); + + let accepted = verdict(&verifier, KEY_A.jwt(with(claims(), "iss", iss.into()))).await; + + assert_eq!(accepted, Ok(())); + } + + #[tokio::test] + async fn a_header_carrying_non_string_fields_is_accepted() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let header = serde_json::json!({"alg": "RS256", "kid": "key-a", "srf": true}); + + let accepted = verdict(&verifier, KEY_A.jwt_with_header(header, claims())).await; + + assert_eq!(accepted, Ok(())); + } + + #[tokio::test] + async fn a_token_without_a_kid_uses_the_only_key() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let header = serde_json::json!({"alg": "RS256"}); + + let accepted = verdict(&verifier, KEY_A.jwt_with_header(header, claims())).await; + + assert_eq!(accepted, Ok(())); + } + + #[tokio::test] + async fn a_token_without_a_kid_is_refused_when_the_jwks_holds_several_keys() { + let cts = FakeCts::serving(jwks(&[&KEY_A, &KEY_B])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let header = serde_json::json!({"alg": "RS256"}); + + let refused = verdict(&verifier, KEY_A.jwt_with_header(header, claims())).await; + + assert!(refused.is_err(), "the key would be a guess"); + } +} + +mod given_a_forged_or_altered_token { + use super::*; + + #[tokio::test] + async fn altered_claims_are_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let genuine = KEY_A.jwt(claims()); + let mut segments: Vec<&str> = genuine.split('.').collect(); + let forged_claims = URL_SAFE_NO_PAD.encode( + with( + claims(), + "services", + serde_json::json!({"zerokms": "https://rogue.example/"}), + ) + .to_string(), + ); + segments[1] = &forged_claims; + + let refused = verdict(&verifier, segments.join(".")).await; + + assert!( + refused.is_err(), + "a re-pointed services claim must not verify" + ); + } + + #[tokio::test] + async fn a_token_signed_by_a_key_the_issuer_does_not_publish_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + // Claims to be key-a, but is signed by key-b. + let header = serde_json::json!({"alg": "RS256", "kid": "key-a"}); + + let refused = verdict(&verifier, KEY_B.jwt_with_header(header, claims())).await; + + assert!(refused.is_err()); + } + + #[tokio::test] + async fn an_hmac_token_is_refused_before_any_key_is_fetched() { + use jsonwebtoken::{encode, EncodingKey, Header}; + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let hs256 = encode( + &Header::default(), + &claims(), + &EncodingKey::from_secret(b"anyone-can-sign-this"), + ) + .unwrap(); + + let refused = verdict(&verifier, hs256).await; + + assert!(refused.is_err()); + assert!( + cts.requests().is_empty(), + "no key fetch for a token that cannot pass" + ); + } + + #[tokio::test] + async fn an_unsigned_token_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let unsigned = format!( + "{}.{}.", + URL_SAFE_NO_PAD.encode(r#"{"alg":"none"}"#), + URL_SAFE_NO_PAD.encode(claims().to_string()), + ); + + assert!(verdict(&verifier, unsigned).await.is_err()); + } + + #[tokio::test] + async fn a_token_that_is_not_a_jwt_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + assert!(verdict(&verifier, "not-a-jwt".to_string()).await.is_err()); + } +} + +mod given_a_token_from_another_issuer { + use super::*; + + #[tokio::test] + async fn it_is_refused_without_fetching_the_issuers_keys() { + // A rogue auth server signing with its own key and publishing its + // own JWKS: the token is internally consistent, but not the trusted + // issuer's. + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let rogue = with(claims(), "iss", "https://rogue.example/".into()); + + let refused = verdict(&verifier, KEY_A.jwt(rogue)).await; + + assert!(refused.is_err()); + assert!( + cts.requests().is_empty(), + "the rogue issuer's JWKS is never asked for" + ); + } + + #[tokio::test] + async fn an_issuer_that_only_shares_a_prefix_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let lookalike = format!("{}evil/", ISSUER); + + let refused = verdict( + &verifier, + KEY_A.jwt(with(claims(), "iss", lookalike.into())), + ) + .await; + + assert!(refused.is_err()); + } +} + +mod given_the_tokens_expiry { + use super::*; + + #[tokio::test] + async fn a_token_past_its_expiry_and_the_leeway_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let expired = with(claims(), "exp", (NOW - LEEWAY_SECS).into()); + + assert!(verdict(&verifier, KEY_A.jwt(expired)).await.is_err()); + } + + #[tokio::test] + async fn a_token_expired_within_the_leeway_is_accepted() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let skewed = with(claims(), "exp", (NOW - LEEWAY_SECS + 1).into()); + + assert_eq!(verdict(&verifier, KEY_A.jwt(skewed)).await, Ok(())); + } + + #[tokio::test] + async fn a_token_without_an_expiry_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + let mut claims = claims(); + let _ = claims.as_object_mut().unwrap().remove("exp"); + + assert!(verdict(&verifier, KEY_A.jwt(claims)).await.is_err()); + } +} + +mod given_an_expected_audience { + use super::*; + + const AUDIENCE: &str = "ap-southeast-2.aws.viturhosted.net"; + + #[tokio::test] + async fn a_token_for_that_audience_is_accepted() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier_for(&cts, &ManualClock::at(NOW), Some(AUDIENCE)); + + assert_eq!(verdict(&verifier, KEY_A.jwt(claims())).await, Ok(())); + } + + #[tokio::test] + async fn an_audience_list_containing_it_is_accepted() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier_for(&cts, &ManualClock::at(NOW), Some(AUDIENCE)); + let listed = with(claims(), "aud", serde_json::json!(["other", AUDIENCE])); + + assert_eq!(verdict(&verifier, KEY_A.jwt(listed)).await, Ok(())); + } + + #[tokio::test] + async fn a_token_for_another_audience_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier_for(&cts, &ManualClock::at(NOW), Some(AUDIENCE)); + let other = with(claims(), "aud", "us-east-1.aws.viturhosted.net".into()); + + assert!(verdict(&verifier, KEY_A.jwt(other)).await.is_err()); + } + + #[tokio::test] + async fn a_token_without_an_audience_is_refused() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let verifier = verifier_for(&cts, &ManualClock::at(NOW), Some(AUDIENCE)); + let mut claims = claims(); + let _ = claims.as_object_mut().unwrap().remove("aud"); + + assert!(verdict(&verifier, KEY_A.jwt(claims)).await.is_err()); + } +} + +mod given_the_key_cache { + use super::*; + + #[tokio::test] + async fn the_jwks_is_fetched_once_while_fresh() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + clock.advance(KEYS_TTL_SECS - 1); + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + assert_eq!(cts.requests().len(), 1); + } + + #[tokio::test] + async fn the_jwks_is_fetched_again_once_stale() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + clock.advance(KEYS_TTL_SECS); + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + assert_eq!(cts.requests().len(), 2); + } + + #[tokio::test] + async fn a_rotated_key_is_fetched_as_soon_as_the_rate_limit_allows() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + cts.rotate_to(jwks(&[&KEY_A, &KEY_B])); + clock.advance(MIN_REFETCH_SECS); + + assert_eq!(verdict(&verifier, KEY_B.jwt(claims())).await, Ok(())); + assert_eq!(cts.requests().len(), 2); + } + + #[tokio::test] + async fn unknown_keys_do_not_refetch_more_than_once_per_interval() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + clock.advance(MIN_REFETCH_SECS - 1); + for _ in 0..3 { + assert!(verdict(&verifier, KEY_B.jwt(claims())).await.is_err()); + } + + assert_eq!( + cts.requests().len(), + 1, + "a run of unknown kids must not hammer CTS" + ); + } + + #[tokio::test] + async fn non_rsa_and_non_signing_keys_in_the_jwks_are_ignored() { + let mut encryption_key = KEY_B.jwk(); + encryption_key["use"] = "enc".into(); + let jwks = serde_json::json!({"keys": [ + {"kty": "EC", "kid": "ec", "crv": "P-256", "x": "AA", "y": "AA"}, + encryption_key, + KEY_A.jwk(), + ]}) + .to_string(); + let cts = FakeCts::serving(jwks); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + assert_eq!(verdict(&verifier, KEY_A.jwt(claims())).await, Ok(())); + assert!( + verdict(&verifier, KEY_B.jwt(claims())).await.is_err(), + "a key published for encryption must not verify a signature" + ); + } +} + +mod given_the_keys_cannot_be_fetched { + use super::*; + + #[tokio::test] + async fn an_unreachable_cts_is_a_request_error() { + let cts = FakeCts::unreachable(); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + let err = verifier + .verify(token(KEY_A.jwt(claims()))) + .await + .unwrap_err(); + + assert!(matches!(err, AuthError::Request(_)), "got {err:?}"); + } + + #[tokio::test] + async fn an_error_status_is_a_server_error() { + let cts = FakeCts::serving("{}".to_string()); + cts.status.store(503, Ordering::SeqCst); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + let err = verifier + .verify(token(KEY_A.jwt(claims()))) + .await + .unwrap_err(); + + assert!(matches!(err, AuthError::Server(_)), "got {err:?}"); + } + + #[tokio::test] + async fn an_unreadable_jwks_refuses_the_token() { + let cts = FakeCts::serving("".to_string()); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + let err = verifier + .verify(token(KEY_A.jwt(claims()))) + .await + .unwrap_err(); + + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + } +} + +mod given_the_verification_setting { + use super::*; + + fn region() -> Region { + Region::aws("ap-southeast-2").unwrap() + } + + #[test] + fn off_builds_no_verifier() { + let cts = transport::share(FakeCts::serving(String::new())); + let resolved = Verification::Off + .resolve(|| Ok(region()), None, &cts) + .unwrap(); + assert!(resolved.is_none()); + } + + #[test] + fn the_region_issuer_is_the_regions_cts() { + let cts = transport::share(FakeCts::serving(String::new())); + let verifier = Verification::RegionIssuer + .resolve(|| Ok(region()), None, &cts) + .unwrap() + .expect("a verifier"); + assert_eq!(verifier.issuer.as_str(), ISSUER); + assert_eq!( + verifier.jwks_url.as_str(), + format!("{ISSUER}.well-known/jwks.json") + ); + } + + #[test] + fn an_explicit_issuer_keeps_its_path() { + let cts = transport::share(FakeCts::serving(String::new())); + let verifier = Verification::Issuer("https://cts.example.com/staging".parse().unwrap()) + .resolve(|| Ok(region()), None, &cts) + .unwrap() + .expect("a verifier"); + assert_eq!(verifier.issuer.as_str(), "https://cts.example.com/staging/"); + assert_eq!( + verifier.jwks_url.as_str(), + "https://cts.example.com/staging/.well-known/jwks.json" + ); + } +} + +/// Both RS256 backends, against the same vectors: the host runs aws-lc-rs, +/// wasm32 runs RustCrypto's `rsa`, and only the host runs tests. +mod given_each_rs256_backend { + use super::*; + + type Backend = fn(&SigningKey, &[u8], &[u8]) -> bool; + + const BACKENDS: [(&str, Backend); 2] = [ + ("aws-lc-rs", rs256::aws_lc::verify), + ("rsa", rs256::rust_crypto::verify), + ]; + + #[test] + fn a_valid_signature_verifies() { + let signature = KEY_A.sign(b"message"); + for (name, verify) in BACKENDS { + assert!( + verify(&signing_key(&KEY_A), b"message", &signature), + "{name}" + ); + } + } + + #[test] + fn a_signature_over_other_bytes_does_not() { + let signature = KEY_A.sign(b"message"); + for (name, verify) in BACKENDS { + assert!( + !verify(&signing_key(&KEY_A), b"massage", &signature), + "{name}" + ); + } + } + + #[test] + fn another_keys_signature_does_not() { + let signature = KEY_B.sign(b"message"); + for (name, verify) in BACKENDS { + assert!( + !verify(&signing_key(&KEY_A), b"message", &signature), + "{name}" + ); + } + } + + #[test] + fn a_truncated_signature_does_not() { + let signature = KEY_A.sign(b"message"); + for (name, verify) in BACKENDS { + assert!( + !verify(&signing_key(&KEY_A), b"message", &signature[1..]), + "{name}" + ); + } + } + + #[test] + fn a_modulus_under_2048_bits_is_refused() { + // Keep key-a's exponent but shorten the modulus: whatever the + // signature, a key this small is not accepted. + let mut short = signing_key(&KEY_A); + short.n.truncate(128); + let signature = KEY_A.sign(b"message"); + for (name, verify) in BACKENDS { + assert!(!verify(&short, b"message", &signature[..128]), "{name}"); + } + } +} + +/// Each strategy builder's `verify_tokens` / `trusted_issuer`, end to end +/// through a stub CTS. +mod given_a_strategy_that_verifies_tokens { + use super::*; + use crate::test_support::signing::{claims as cts_claims, StubCts}; + use crate::{ + AccessKey, AccessKeyStrategy, AuthStrategy, AutoStrategy, DeviceSessionStrategy, + OidcFederationStrategy, OidcProviderFn, + }; + use cts_common::Crn; + + const WORKSPACE: &str = "ZVATKW3VHMFG27DY"; + /// Where the strategies are told to request tokens. Not the issuer. + const AUTH_URL: &str = "https://auth.example.com/"; + + fn crn() -> Crn { + format!("crn:ap-southeast-2.aws:{WORKSPACE}") + .parse() + .unwrap() + } + + fn key() -> AccessKey { + "CSAKkeyId.keySecret".parse().unwrap() + } + + fn genuine() -> String { + KEY_A.jwt(cts_claims(ISSUER, WORKSPACE)) + } + + /// Signed by a key the trusted issuer does not publish, naming a rogue + /// issuer: what an attacker who controls the auth URL would mint. + fn forged() -> String { + KEY_B.jwt(cts_claims("https://rogue.example/", WORKSPACE)) + } + + fn cts(token: String) -> Arc { + Arc::new(StubCts::new(token, jwks(&[&KEY_A]))) + } + + async fn access_key(cts: &Arc, pin: bool) -> Result { + let builder = AccessKeyStrategy::builder(crn(), key()) + .base_url(AUTH_URL.parse().unwrap()) + .transport(Arc::clone(cts)); + let builder = if pin { + builder.trusted_issuer(ISSUER.parse().unwrap()) + } else { + builder.verify_tokens() + }; + builder.build().unwrap().get_token().await + } + + #[tokio::test] + async fn the_access_key_strategy_returns_a_genuine_token() { + let cts = cts(genuine()); + assert!(access_key(&cts, true).await.is_ok()); + } + + #[tokio::test] + async fn the_access_key_strategy_refuses_a_forged_token() { + let cts = cts(forged()); + let err = access_key(&cts, true).await.unwrap_err(); + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + } + + #[tokio::test] + async fn verify_tokens_trusts_the_regions_cts_not_the_auth_url() { + // The auth URL is overridden, as `CS_CTS_HOST` or `base_url` would; + // the issuer the strategy trusts is still the region's CTS, and that + // is where it asks for keys. The token names the region's CTS too, + // so it verifies. + let cts = cts(genuine()); + + assert!(access_key(&cts, false).await.is_ok()); + assert_eq!( + cts.jwks_requests(), + vec![format!("{ISSUER}.well-known/jwks.json")] + ); + } + + #[tokio::test] + async fn verify_tokens_refuses_a_token_from_the_overridden_auth_url() { + let cts = cts(KEY_A.jwt(cts_claims(AUTH_URL, WORKSPACE))); + + let err = access_key(&cts, false).await.unwrap_err(); + + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + assert!(cts.jwks_requests().is_empty()); + } + + #[tokio::test] + async fn the_access_key_strategy_checks_the_requested_audience() { + let cts = cts(genuine()); + let strategy = AccessKeyStrategy::builder(crn(), key()) + .base_url(AUTH_URL.parse().unwrap()) + .transport(Arc::clone(&cts)) + .audience("ap-southeast-2.aws.viturhosted.net") + .verify_tokens() + .build() + .unwrap(); + + // `cts_claims` mints `aud: "test-audience"`. + let err = strategy.get_token().await.unwrap_err(); + + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + } + + #[tokio::test] + async fn without_verification_no_keys_are_fetched() { + let cts = cts(forged()); + let strategy = AccessKeyStrategy::builder(crn(), key()) + .base_url(AUTH_URL.parse().unwrap()) + .transport(Arc::clone(&cts)) + .build() + .unwrap(); + + assert!(strategy.get_token().await.is_ok(), "verification is opt-in"); + assert!(cts.jwks_requests().is_empty()); + } + + async fn oidc(cts: &Arc) -> Result { + let provider = OidcProviderFn::new(|| async { Ok(SecretToken::new("provider.jwt.value")) }); + OidcFederationStrategy::builder(crn(), provider) + .base_url(AUTH_URL.parse().unwrap()) + .transport(Arc::clone(cts)) + .verify_tokens() + .build() + .unwrap() + .get_token() + .await + } + + #[tokio::test] + async fn the_oidc_federation_strategy_returns_a_genuine_token() { + assert!(oidc(&cts(genuine())).await.is_ok()); + } + + #[tokio::test] + async fn the_oidc_federation_strategy_refuses_a_forged_token() { + let err = oidc(&cts(forged())).await.unwrap_err(); + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + } + + async fn device_session(cts: &Arc, jwt: &str) -> Result { + let region = Region::aws("ap-southeast-2").unwrap(); + DeviceSessionStrategy::with_token(region, "client-id", crate::test_support::raw_token(jwt)) + .base_url(AUTH_URL.parse().unwrap()) + .transport(Arc::clone(cts)) + .verify_tokens() + .build() + .unwrap() + .get_token() + .await + } + + #[tokio::test] + async fn the_device_session_strategy_returns_a_genuine_token() { + let cts = cts(String::new()); + assert!(device_session(&cts, &genuine()).await.is_ok()); + } + + #[tokio::test] + async fn the_device_session_strategy_refuses_a_forged_saved_token() { + let cts = cts(String::new()); + let err = device_session(&cts, &forged()).await.unwrap_err(); + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + } + + /// A saved session names its own issuer, which is what is being checked, + /// so the trusted issuer comes from the region saved alongside it. + async fn saved_session(region: &str) -> (Arc, Result) { + let dir = tempfile::tempdir().unwrap(); + let store = stack_profile::ProfileStore::new(dir.path()); + let ws_store = store.workspace_store(WORKSPACE).unwrap(); + let mut saved = crate::test_support::raw_token(&genuine()); + saved.set_region(region); + saved.set_client_id("client-id"); + ws_store.save_profile(&saved).unwrap(); + let cts = cts(String::new()); + let result = DeviceSessionStrategy::with_workspace_store(ws_store) + .transport(Arc::clone(&cts)) + .verify_tokens() + .build() + .unwrap() + .get_token() + .await; + (cts, result) + } + + #[tokio::test] + async fn a_saved_device_session_is_verified_against_its_saved_regions_cts() { + let (cts, result) = saved_session("ap-southeast-2.aws").await; + + assert!(result.is_ok(), "got {result:?}"); + assert_eq!( + cts.jwks_requests(), + vec![format!("{ISSUER}.well-known/jwks.json")] + ); + } + + #[tokio::test] + async fn a_saved_device_session_from_another_regions_cts_is_refused() { + // Signed by the Sydney CTS's key and naming it, but saved as a + // Virginia session: the issuer is not the one the region trusts. + let (_, result) = saved_session("us-east-1.aws").await; + + let err = result.unwrap_err(); + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + } + + #[tokio::test] + async fn the_auto_strategy_hands_verification_to_the_strategy_it_detects() { + let cts = cts(forged()); + let strategy = AutoStrategy::builder() + .with_access_key("CSAKkeyId.keySecret") + .with_workspace_crn(crn()) + .transport(Arc::clone(&cts)) + .trusted_issuer(ISSUER.parse().unwrap()) + .detect() + .unwrap(); + + let err = strategy.get_token().await.unwrap_err(); + + assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + } +} diff --git a/packages/stack-auth/src/transport.rs b/packages/stack-auth/src/transport.rs index d0dd7fead3..447b47dde5 100644 --- a/packages/stack-auth/src/transport.rs +++ b/packages/stack-auth/src/transport.rs @@ -368,6 +368,25 @@ pub(crate) async fn post_form( .await } +/// `GET` `url` with an `accept` header and [`user_agent`], and no body. Used +/// for CTS's public signing keys, so nothing it sends is a secret. +pub(crate) async fn get( + transport: &SharedTransport, + url: Url, + accept: &str, +) -> Result { + let request = HttpRequest { + method: "GET", + url, + headers: Zeroizing::new(vec![ + ("accept".to_string(), accept.to_string()), + ("user-agent".to_string(), user_agent().to_string()), + ]), + body: Zeroizing::new(Vec::new()), + }; + transport.send_dyn(request).await +} + /// `POST` `body` as `content_type`, with `extra` headers first and then /// `content-type` and [`user_agent`]. A failure /// here is the transport's (or the encoder's); the caller lifts it into diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index e2f5a569cc..a212a7ea7e 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -397,6 +397,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-oid" version = "0.10.2" @@ -555,6 +561,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.5" @@ -611,6 +627,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -622,7 +639,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.0", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.1", "ctutils", "zeroize", @@ -1230,6 +1247,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "leb128fmt" version = "0.1.0" @@ -1252,6 +1278,12 @@ dependencies = [ "cc", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.12" @@ -1363,6 +1395,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.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.0" @@ -1378,6 +1426,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1385,6 +1443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -1454,6 +1513,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.32" @@ -1725,6 +1805,26 @@ dependencies = [ "serde", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -1907,6 +2007,7 @@ 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", ] @@ -1944,6 +2045,22 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1955,11 +2072,13 @@ name = "stack-auth" version = "0.43.0" dependencies = [ "aquamarine", + "aws-lc-rs", "base64", "cts-common", "jsonwebtoken", "miette", "open", + "rsa", "serde", "serde_json", "serde_urlencoded", diff --git a/packages/stack-kms/fuzz/Cargo.lock b/packages/stack-kms/fuzz/Cargo.lock index 8c5b3705a6..bbb30695a7 100644 --- a/packages/stack-kms/fuzz/Cargo.lock +++ b/packages/stack-kms/fuzz/Cargo.lock @@ -386,6 +386,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 = "constant_time_eq" version = "0.4.2" @@ -532,6 +538,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.5" @@ -577,6 +593,7 @@ 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", ] @@ -1185,6 +1202,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "leb128fmt" version = "0.1.0" @@ -1207,6 +1233,12 @@ dependencies = [ "cc", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.12" @@ -1318,6 +1350,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-conv" version = "0.2.0" @@ -1333,6 +1381,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1340,6 +1398,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -1422,6 +1481,27 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[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.32" @@ -1721,6 +1801,26 @@ dependencies = [ "serde", ] +[[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_version" version = "0.4.1" @@ -1892,6 +1992,7 @@ 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", ] @@ -1929,6 +2030,22 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1940,11 +2057,13 @@ name = "stack-auth" version = "0.43.0" dependencies = [ "aquamarine", + "aws-lc-rs", "base64", "cts-common", "jsonwebtoken", "miette", "open", + "rsa", "serde", "serde_json", "serde_urlencoded", From 5d15fb06be8ddf5b3e11c40a6c24d5f0c43777c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:28:11 +0000 Subject: [PATCH 2/3] fix(stack-auth): rate-limit failed JWKS fetches and keep cached keys through an outage A failed fetch never moved the refetch clock, so a JWKS outage turned every get_token into a request to CTS. Attempts are now limited to one a minute whether they succeed or fail, and a key already cached still verifies when a refresh fails. An unreadable JWKS is a request error, not the token's. The refused-algorithm log no longer quotes the token's alg, the unverified header and claims are named as such, and the OIDC comments the ticket cites now say it is the provider's JWT that the client cannot verify. Refs CIP-5080 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012Jmn7r23UyoxCG5saYMrgG --- .../src/oidc_federation_strategy.rs | 4 +- packages/stack-auth/src/oidc_refresher.rs | 2 +- packages/stack-auth/src/token_verifier.rs | 109 +++++++++++++----- .../stack-auth/src/token_verifier/tests.rs | 67 ++++++++++- 4 files changed, 145 insertions(+), 37 deletions(-) diff --git a/packages/stack-auth/src/oidc_federation_strategy.rs b/packages/stack-auth/src/oidc_federation_strategy.rs index bd399db3f3..5ff6617801 100644 --- a/packages/stack-auth/src/oidc_federation_strategy.rs +++ b/packages/stack-auth/src/oidc_federation_strategy.rs @@ -44,7 +44,7 @@ pub(crate) const DEFAULT_CACHE_CAPACITY: usize = 1024; /// the call that created the strategy instead, and lose the request. /// /// The cache is keyed on the whole JWT, never on claims read from it (the -/// client cannot verify a JWT, so a forged one naming another user's `sub` +/// client cannot verify the provider's JWT, so a forged one naming another user's `sub` /// must not reach that user's token), and holds at most /// [`cache_capacity`](OidcFederationStrategyBuilder::cache_capacity) JWTs /// (1024 by default), dropping the least recently used. Because @@ -962,7 +962,7 @@ mod tests { /// The cache is keyed on the JWT's bytes, not its claims: a JWT that /// copies a cached user's header and payload under another signature is /// exchanged (and refused here), never served that user's token. The - /// client cannot verify a signature, so a cache keyed on `iss`/`sub` + /// client cannot verify the provider JWT's signature, so a cache keyed on `iss`/`sub` /// would hand this forgery the victim's CTS token without CTS ever /// seeing it. #[tokio::test] diff --git a/packages/stack-auth/src/oidc_refresher.rs b/packages/stack-auth/src/oidc_refresher.rs index 779e89d486..5b56da8141 100644 --- a/packages/stack-auth/src/oidc_refresher.rs +++ b/packages/stack-auth/src/oidc_refresher.rs @@ -112,7 +112,7 @@ where /// is served only to the JWT that produced it. /// /// It is deliberately the *whole JWT*, not the `iss`/`sub` claims read from -/// it. The client cannot verify a JWT's signature, so a cache keyed on claims +/// it. The client cannot verify the provider JWT's signature, so a cache keyed on claims /// would hand a forged JWT carrying a victim's `sub` the victim's cached CTS /// token without CTS ever seeing it. Keyed on the bytes, a forged JWT gets /// its own entry and is refused by CTS. The cost is one exchange each time diff --git a/packages/stack-auth/src/token_verifier.rs b/packages/stack-auth/src/token_verifier.rs index 6889fcd9d4..1069853c8c 100644 --- a/packages/stack-auth/src/token_verifier.rs +++ b/packages/stack-auth/src/token_verifier.rs @@ -27,9 +27,10 @@ //! nothing from the token itself is. //! //! The JWKS is cached for [`KEYS_TTL_SECS`]. A token signed by a key the -//! cache does not hold triggers one early refetch, so a rotated key works -//! immediately, but no more than once every [`MIN_REFETCH_SECS`], so a run of -//! forged `kid`s cannot turn every call into a request to CTS. +//! cache does not hold triggers an early refetch, so a rotated key works +//! immediately. Fetches, successful or failed, are at most one every +//! [`MIN_REFETCH_SECS`], so neither a run of forged `kid`s nor a CTS outage +//! turns every call into a request to CTS. use std::fmt; @@ -130,6 +131,10 @@ struct KeyCache { keys: Vec, /// When the keys were last fetched; `None` before the first fetch. fetched_at: Option, + /// When a fetch was last attempted, successful or not. + attempted_at: Option, + /// Whether that attempt failed. + attempt_failed: bool, } /// One RSA public key from the JWKS, as big-endian modulus and exponent. @@ -200,7 +205,7 @@ impl TokenVerifier { fn check_claims(&self, parts: &Parts<'_>) -> Result<(), Rejection> { if parts.header.alg != ALGORITHM { - return Err(Rejection::Algorithm(parts.header.alg.clone())); + return Err(Rejection::Algorithm); } let claims = &parts.claims; let issuer = Url::parse(&claims.iss) @@ -225,26 +230,60 @@ impl TokenVerifier { } /// The key `kid` names, fetching the JWKS when the cache is empty or - /// stale, or when it lacks that key and was not fetched too recently. + /// stale, or when it lacks that key. + /// + /// No more than one fetch is attempted every [`MIN_REFETCH_SECS`], + /// whether the last one succeeded or failed, so neither a run of forged + /// `kid`s nor a CTS outage turns every call into a request. While a fetch + /// cannot be made or has failed, a key already in the cache is still + /// used, even past [`KEYS_TTL_SECS`]: the keys are public, and a short + /// outage of CTS's JWKS should not refuse tokens they verify. /// /// The lock is held across the fetch, so concurrent callers wait for one /// request rather than each sending their own. async fn key_for(&self, kid: Option<&str>) -> Result, AuthError> { let mut cache = self.keys.lock().await; let now = self.clock.now_unix_secs(); - let age = cache.fetched_at.map(|at| now.saturating_sub(at)); - let stale = age.is_none_or(|age| age >= KEYS_TTL_SECS); - if !stale { - if let Some(key) = cache.find(kid) { - return Ok(Some(key)); + let fresh = cache + .fetched_at + .is_some_and(|at| now.saturating_sub(at) < KEYS_TTL_SECS); + let cached = cache.find(kid); + if fresh && cached.is_some() { + return Ok(cached); + } + let tried_recently = cache + .attempted_at + .is_some_and(|at| now.saturating_sub(at) < MIN_REFETCH_SECS); + if tried_recently { + return match cached { + Some(key) => Ok(Some(key)), + None if cache.attempt_failed => Err(keys_unavailable()), + None => Ok(None), + }; + } + cache.attempted_at = Some(now); + match self.fetch_keys().await { + Ok(keys) => { + cache.keys = keys; + cache.fetched_at = Some(now); + cache.attempt_failed = false; + Ok(cache.find(kid)) } - if age.is_some_and(|age| age < MIN_REFETCH_SECS) { - return Ok(None); + Err(err) => { + cache.attempt_failed = true; + match cached { + Some(key) => { + tracing::warn!( + url = %self.jwks_url, + error = %err, + "could not refresh CTS's signing keys; using the cached ones" + ); + Ok(Some(key)) + } + None => Err(err), + } } } - cache.keys = self.fetch_keys().await?; - cache.fetched_at = Some(now); - Ok(cache.find(kid)) } async fn fetch_keys(&self) -> Result, AuthError> { @@ -257,11 +296,8 @@ impl TokenVerifier { &response.text(), ))); } - let jwks: Jwks = response.json().map_err(|_| { - AuthError::InvalidToken(InvalidToken( - "CTS's signing keys (its JWKS) could not be read".to_string(), - )) - })?; + // An unreadable JWKS is the server's fault, not the token's. + let jwks: Jwks = response.json()?; Ok(jwks.keys.into_iter().filter_map(Jwk::into_key).collect()) } } @@ -284,13 +320,19 @@ impl KeyCache { } } +/// The last fetch of the signing keys failed, and it is too soon to try +/// again. +fn keys_unavailable() -> AuthError { + AuthError::Request(crate::error::RequestError(Box::new(std::io::Error::other( + "CTS's signing keys could not be fetched; retrying at most once a minute", + )))) +} + /// Why a token was refused. Logged, never returned. #[derive(Debug)] enum Rejection { Malformed, - /// The header's algorithm, which CTS chose rather than the caller, so it - /// is safe to log. - Algorithm(String), + Algorithm, Issuer, Expired, Audience, @@ -302,7 +344,7 @@ impl fmt::Display for Rejection { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Rejection::Malformed => f.write_str("the token is not a well-formed JWT"), - Rejection::Algorithm(alg) => write!(f, "the token is signed with {alg:?}, not RS256"), + Rejection::Algorithm => f.write_str("the token is not signed with RS256"), Rejection::Issuer => f.write_str("the token's issuer is not the trusted issuer"), Rejection::Expired => f.write_str("the token has expired"), Rejection::Audience => f.write_str("the token is not for the expected audience"), @@ -314,26 +356,28 @@ impl fmt::Display for Rejection { } } -/// A JWT split into what verification needs. +/// A JWT split into what verification needs. Its header and claims are +/// read before the signature is checked, and are named for it. struct Parts<'a> { - header: Header, - claims: Claims, + header: UnverifiedHeader, + claims: UnverifiedClaims, /// `header.claims`, the bytes the signature covers. signed: &'a str, signature: Vec, } #[derive(serde::Deserialize)] -struct Header { +struct UnverifiedHeader { alg: String, #[serde(default)] kid: Option, } -/// The claims verification checks. The rest are read, unverified, by -/// [`ServiceToken`]; once this check has passed they are the issuer's. +/// The claims verification checks, as the token states them. The rest are +/// read, unverified, by [`ServiceToken`]; once every check has passed they +/// are the issuer's. #[derive(serde::Deserialize)] -struct Claims { +struct UnverifiedClaims { iss: String, exp: u64, #[serde(default)] @@ -410,7 +454,8 @@ impl Jwk { /// RSASSA-PKCS1-v1_5 with SHA-256 over a key from the JWKS. /// /// aws-lc-rs where it builds; RustCrypto's `rsa` on wasm32, where it does -/// not. Both refuse a modulus under 2048 bits. The RustCrypto backend is also +/// not. Not vitaminc, the first choice for crypto here: it has no RSA +/// signature verification. Both refuse a modulus under 2048 bits. The RustCrypto backend is also /// compiled into the host's tests, so both are run against the same vectors. mod rs256 { use super::SigningKey; diff --git a/packages/stack-auth/src/token_verifier/tests.rs b/packages/stack-auth/src/token_verifier/tests.rs index 09cf662bc0..86a0155740 100644 --- a/packages/stack-auth/src/token_verifier/tests.rs +++ b/packages/stack-auth/src/token_verifier/tests.rs @@ -516,6 +516,34 @@ mod given_the_keys_cannot_be_fetched { assert!(matches!(err, AuthError::Request(_)), "got {err:?}"); } + #[tokio::test] + async fn a_failed_fetch_is_not_retried_more_than_once_per_interval() { + let cts = FakeCts::unreachable(); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + + for _ in 0..3 { + let err = verifier + .verify(token(KEY_A.jwt(claims()))) + .await + .unwrap_err(); + assert!(matches!(err, AuthError::Request(_)), "got {err:?}"); + } + assert_eq!( + cts.requests().len(), + 1, + "an outage must not turn every call into a fetch" + ); + + clock.advance(MIN_REFETCH_SECS); + let _ = verifier.verify(token(KEY_A.jwt(claims()))).await; + assert_eq!( + cts.requests().len(), + 2, + "the fetch is retried after the interval" + ); + } + #[tokio::test] async fn an_error_status_is_a_server_error() { let cts = FakeCts::serving("{}".to_string()); @@ -531,7 +559,7 @@ mod given_the_keys_cannot_be_fetched { } #[tokio::test] - async fn an_unreadable_jwks_refuses_the_token() { + async fn an_unreadable_jwks_is_a_request_error_not_the_tokens() { let cts = FakeCts::serving("".to_string()); let verifier = verifier(&cts, &ManualClock::at(NOW)); @@ -540,7 +568,42 @@ mod given_the_keys_cannot_be_fetched { .await .unwrap_err(); - assert!(matches!(err, AuthError::InvalidToken(_)), "got {err:?}"); + assert!(matches!(err, AuthError::Request(_)), "got {err:?}"); + } + + #[tokio::test] + async fn cached_keys_still_verify_when_a_refresh_fails() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + cts.status.store(503, Ordering::SeqCst); + clock.advance(KEYS_TTL_SECS); + + assert_eq!( + verdict(&verifier, KEY_A.jwt(claims())).await, + Ok(()), + "a JWKS outage must not refuse a token the cached keys verify" + ); + assert_eq!(cts.requests().len(), 2, "the refresh was attempted"); + } + + #[tokio::test] + async fn an_unknown_key_during_an_outage_is_not_accepted() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + cts.status.store(503, Ordering::SeqCst); + clock.advance(MIN_REFETCH_SECS); + + let err = verifier + .verify(token(KEY_B.jwt(claims()))) + .await + .unwrap_err(); + assert!(matches!(err, AuthError::Server(_)), "got {err:?}"); } } From 539089441e2c4dadff46bce0a82d3025c6d0922e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:46:00 +0000 Subject: [PATCH 3/3] test(stack-auth): pin the JWKS lifetime, key filters and refusal reasons Kills the surviving mutants in the token verifier: an hour-literal cache test, one JWK filter at a time, a 4096-bit key on both RS256 backends, and distinct refusal reasons. The wasm32 RS256 dispatch is excluded as unreachable in the host build, and the wasm32 detect_inner exclusion follows its new line. Refs CIP-5080 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012Jmn7r23UyoxCG5saYMrgG --- .cargo/mutants.toml | 6 +- packages/stack-auth/src/test_support.rs | 6 +- .../stack-auth/src/token_verifier/tests.rs | 66 +++++++++++++++++++ 3 files changed, 76 insertions(+), 2 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 6cbd589332..f956aedf40 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -62,7 +62,11 @@ exclude_re = [ # Under `http` the body is `false`; the no-`http` arm is pinned by # `a_builder_without_a_transport_is_refused_when_there_is_no_bundled_one`. 'stack-auth/src/error\.rs:\d+:\d+: replace RequestError::is_no_transport -> bool with false$', - 'stack-auth/src/auto_strategy\.rs:150:9: replace AutoStrategy::detect_inner -> Result with Ok\(Default::default\(\)\)$', + 'stack-auth/src/auto_strategy\.rs:167:9: replace AutoStrategy::detect_inner -> Result with Ok\(Default::default\(\)\)$', + # The wasm32 RS256 dispatch (`rs256::verify` over RustCrypto). The native + # one shares its name, so this anchors on the line. The RustCrypto backend + # it calls is compiled into the host tests and pinned there. + 'stack-auth/src/token_verifier\.rs:470:9: replace rs256::verify -> bool with (true|false)$', 'stack-auth/src/token_store\.rs:(261|269):9: replace >::(load|save)', # stack-auth — equivalent. 'stack-auth/src/(access_key|oidc)_refresher\.rs:\d+:\d+: replace )?>::try_credential -> Option with Some\(Default::default\(\)\)$', diff --git a/packages/stack-auth/src/test_support.rs b/packages/stack-auth/src/test_support.rs index 20afbf791f..7954939fb4 100644 --- a/packages/stack-auth/src/test_support.rs +++ b/packages/stack-auth/src/test_support.rs @@ -134,9 +134,13 @@ pub(crate) mod signing { impl TestKey { pub(crate) fn generate(kid: &'static str) -> Self { + Self::generate_with_size(kid, KeySize::Rsa2048) + } + + pub(crate) fn generate_with_size(kid: &'static str, size: KeySize) -> Self { Self { kid, - pair: KeyPair::generate(KeySize::Rsa2048).unwrap(), + pair: KeyPair::generate(size).unwrap(), } } diff --git a/packages/stack-auth/src/token_verifier/tests.rs b/packages/stack-auth/src/token_verifier/tests.rs index 86a0155740..96cae9e058 100644 --- a/packages/stack-auth/src/token_verifier/tests.rs +++ b/packages/stack-auth/src/token_verifier/tests.rs @@ -433,6 +433,37 @@ mod given_the_key_cache { assert_eq!(cts.requests().len(), 1); } + /// Each filter on its own: the key carries key-b's RSA modulus and + /// exponent, so only the named field keeps it out. + #[tokio::test] + async fn a_key_not_typed_rsa_or_not_for_rs256_is_ignored() { + for (field, value) in [("kty", "EC"), ("alg", "RS512"), ("use", "enc")] { + let mut key = KEY_B.jwk(); + key[field] = value.into(); + let jwks = serde_json::json!({"keys": [KEY_A.jwk(), key]}).to_string(); + let cts = FakeCts::serving(jwks); + let verifier = verifier(&cts, &ManualClock::at(NOW)); + + assert!( + verdict(&verifier, KEY_B.jwt(claims())).await.is_err(), + "a key with {field} {value:?} must not verify an RS256 signature" + ); + } + } + + #[tokio::test] + async fn the_jwks_is_reused_for_an_hour() { + let cts = FakeCts::serving(jwks(&[&KEY_A])); + let clock = ManualClock::at(NOW); + let verifier = verifier(&cts, &clock); + + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + clock.advance(59 * 60); + verdict(&verifier, KEY_A.jwt(claims())).await.unwrap(); + + assert_eq!(cts.requests().len(), 1, "an hour-old JWKS is still fresh"); + } + #[tokio::test] async fn the_jwks_is_fetched_again_once_stale() { let cts = FakeCts::serving(jwks(&[&KEY_A])); @@ -652,6 +683,32 @@ mod given_the_verification_setting { } } +mod given_a_refusal { + use super::*; + + /// The log line is the only place a refusal's reason appears, so each + /// one must say something, and something different. + #[test] + fn each_reason_describes_itself() { + let reasons: Vec = [ + Rejection::Malformed, + Rejection::Algorithm, + Rejection::Issuer, + Rejection::Expired, + Rejection::Audience, + Rejection::UnknownKey, + Rejection::Signature, + ] + .iter() + .map(ToString::to_string) + .collect(); + + let distinct: std::collections::HashSet<&String> = reasons.iter().collect(); + assert!(reasons.iter().all(|r| !r.is_empty()), "got {reasons:?}"); + assert_eq!(distinct.len(), reasons.len(), "got {reasons:?}"); + } +} + /// Both RS256 backends, against the same vectors: the host runs aws-lc-rs, /// wasm32 runs RustCrypto's `rsa`, and only the host runs tests. mod given_each_rs256_backend { @@ -675,6 +732,15 @@ mod given_each_rs256_backend { } } + #[test] + fn a_4096_bit_key_verifies() { + let key = TestKey::generate_with_size("key-4096", aws_lc_rs::rsa::KeySize::Rsa4096); + let signature = key.sign(b"message"); + for (name, verify) in BACKENDS { + assert!(verify(&signing_key(&key), b"message", &signature), "{name}"); + } + } + #[test] fn a_signature_over_other_bytes_does_not() { let signature = KEY_A.sign(b"message");