From ab91f0ff0a0e47917419ec1a0f57854b1fa18b37 Mon Sep 17 00:00:00 2001 From: Anthony Ronning <101225832+AnthonyRonning@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:08:56 -0800 Subject: [PATCH] OpenSecret: move from our tinfoil-rs fork to upstream 0.3 Upstream tinfoil-rs now verifies V3 attestation for a named enclave, so the fork that added it is no longer needed. Pin v0.3.0-rc.4. The SDK pins a dedicated guest to one repository. The approved tag, digest and launch measurement move into a policy check that runs on every verification of that client. Only the SEV-SNP launch measurement is pinned now; a TDX guest is never approved. Every verification has a freshness deadline, the shared router's too. A verification is renewed an hour ahead of it without a request in hand, and a client that still expires is replaced as before. Co-Authored-By: Claude --- services/opensecret/Cargo.lock | 454 ++++---------- services/opensecret/Cargo.toml | 2 +- services/opensecret/deny.toml | 8 +- services/opensecret/docs/nitro-deploy.md | 3 +- .../docs/tinfoil-rust-sdk-parity.md | 13 +- services/opensecret/flake.nix | 4 +- services/opensecret/src/maple_inference.rs | 493 +++++++++------ services/opensecret/src/provider_client.rs | 559 +++++++++--------- .../src/provider_client/attested.rs | 288 +++++++++ 9 files changed, 1017 insertions(+), 807 deletions(-) create mode 100644 services/opensecret/src/provider_client/attested.rs diff --git a/services/opensecret/Cargo.lock b/services/opensecret/Cargo.lock index c24acdd9f..18dec734b 100644 --- a/services/opensecret/Cargo.lock +++ b/services/opensecret/Cargo.lock @@ -134,45 +134,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "async-openai" -version = "0.41.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3007014661d5b98168b7b6f1014147bce8b1362a194783543eeb9f6117a20be9" -dependencies = [ - "async-openai-macros", - "base64 0.22.1", - "bytes", - "derive_builder", - "eventsource-stream", - "futures", - "getrandom 0.3.4", - "rand 0.9.5", - "reqwest 0.13.4", - "secrecy", - "serde", - "serde_json", - "serde_urlencoded", - "thiserror 2.0.18", - "tokio", - "tokio-stream", - "tokio-util", - "tower 0.5.2", - "tracing", - "url", -] - -[[package]] -name = "async-openai-macros" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "492a944774207eed3acf425214eadbd6ce84a2b89331164ff1c11bae92b26302" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "async-stream" version = "0.3.6" @@ -192,7 +153,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -203,7 +164,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -585,7 +546,7 @@ checksum = "8d7396fd9500589e62e460e987ecb671bad374934e55ec3b5f498cc7a8a8a7b7" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -715,7 +676,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -760,6 +721,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64-simd" version = "0.8.0" @@ -914,26 +881,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bitfield" -version = "0.19.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21ba6517c6b0f2bf08be60e187ab64b038438f22dd755614d8fe4d4098c46419" -dependencies = [ - "bitfield-macros", -] - -[[package]] -name = "bitfield-macros" -version = "0.19.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f48d6ace212fdf1b45fd6b566bb40808415344642b76c3224c07c8df9da81e97" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "bitflags" version = "1.3.2" @@ -1159,6 +1106,18 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "cms" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" +dependencies = [ + "const-oid 0.9.6", + "der", + "spki", + "x509-cert", +] + [[package]] name = "combine" version = "4.6.7" @@ -1342,7 +1301,6 @@ dependencies = [ "fiat-crypto 0.3.0", "rustc_version", "subtle", - "zeroize", ] [[package]] @@ -1353,7 +1311,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1387,7 +1345,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn", + "syn 2.0.119", ] [[package]] @@ -1401,7 +1359,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn", + "syn 2.0.119", ] [[package]] @@ -1412,7 +1370,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core 0.20.10", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1423,7 +1381,7 @@ checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" dependencies = [ "darling_core 0.21.3", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1439,12 +1397,6 @@ dependencies = [ "parking_lot_core", ] -[[package]] -name = "data-encoding" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" - [[package]] name = "dbl" version = "0.3.2" @@ -1475,7 +1427,7 @@ checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1487,37 +1439,6 @@ dependencies = [ "powerfmt", ] -[[package]] -name = "derive_builder" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" -dependencies = [ - "derive_builder_macro", -] - -[[package]] -name = "derive_builder_core" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" -dependencies = [ - "darling 0.20.10", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "derive_builder_macro" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" -dependencies = [ - "derive_builder_core", - "syn", -] - [[package]] name = "diesel" version = "2.3.10" @@ -1549,7 +1470,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1562,7 +1483,7 @@ dependencies = [ "dsl_auto_type", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1571,7 +1492,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe2444076b48641147115697648dc743c2c00b61adade0f01ce67133c7babe8c" dependencies = [ - "syn", + "syn 2.0.119", ] [[package]] @@ -1598,27 +1519,6 @@ dependencies = [ "ctutils", ] -[[package]] -name = "dirs" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.61.2", -] - [[package]] name = "displaydoc" version = "0.2.5" @@ -1627,7 +1527,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1653,7 +1553,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1728,7 +1628,6 @@ dependencies = [ "ed25519 3.0.0", "sha2 0.11.0", "subtle", - "zeroize", ] [[package]] @@ -1750,7 +1649,6 @@ dependencies = [ "generic-array", "group", "hkdf", - "pem-rfc7468", "pkcs8", "rand_core 0.6.4", "sec1", @@ -1783,17 +1681,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "eventsource-stream" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab" -dependencies = [ - "futures-core", - "nom", - "pin-project-lite", -] - [[package]] name = "fancy-regex" version = "0.12.0" @@ -1952,7 +1839,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2022,11 +1909,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", - "js-sys", "libc", "r-efi 5.3.0", "wasip2", - "wasm-bindgen", ] [[package]] @@ -2517,7 +2402,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2575,12 +2460,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "iocuddle" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8972d5be69940353d5347a1344cb375d9b457d6809b428b05bb1ca2fb9ce007" - [[package]] name = "ipnet" version = "2.9.0" @@ -2605,7 +2484,7 @@ dependencies = [ "jni-sys", "log", "simd_cesu8", - "thiserror 2.0.18", + "thiserror 2.0.21", "walkdir", "windows-link", ] @@ -2620,7 +2499,7 @@ dependencies = [ "quote", "rustc_version", "simd_cesu8", - "syn", + "syn 2.0.119", ] [[package]] @@ -2639,7 +2518,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" dependencies = [ "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2732,15 +2611,6 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" -[[package]] -name = "libredox" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" -dependencies = [ - "libc", -] - [[package]] name = "linux-raw-sys" version = "0.4.14" @@ -2798,7 +2668,7 @@ checksum = "5cf92c10c7e361d6b99666ec1c6f9805b0bea2c3bd8c78dc6fe98ac5bd78db11" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2831,22 +2701,6 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2934,16 +2788,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c" -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - [[package]] name = "nonzero_ext" version = "0.3.0" @@ -3026,7 +2870,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64 0.22.1", + "base64 0.21.7", "chrono", "getrandom 0.2.15", "http 1.5.0", @@ -3098,7 +2942,7 @@ dependencies = [ "pulldown-cmark-to-cmark", "rand_core 0.6.4", "regex", - "reqwest 0.13.4", + "reqwest 0.13.5", "resend-rs", "rustls", "secp256k1", @@ -3108,7 +2952,7 @@ dependencies = [ "serde_json", "sha2 0.10.8", "subtle", - "syn", + "syn 2.0.119", "thiserror 1.0.63", "tiktoken-rs", "tinfoil", @@ -3148,7 +2992,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -3175,12 +3019,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - [[package]] name = "outref" version = "0.5.1" @@ -3299,7 +3137,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -3422,7 +3260,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -3499,7 +3337,7 @@ dependencies = [ "rustc-hash 2.1.3", "rustls", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -3521,7 +3359,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -3685,17 +3523,6 @@ dependencies = [ "bitflags 2.13.0", ] -[[package]] -name = "redox_users" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" -dependencies = [ - "getrandom 0.2.15", - "libredox", - "thiserror 2.0.18", -] - [[package]] name = "regex" version = "1.11.3" @@ -3774,11 +3601,11 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.13.4" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", "futures-core", "futures-util", @@ -3791,7 +3618,6 @@ dependencies = [ "hyper-util", "js-sys", "log", - "mime_guess", "percent-encoding", "pin-project-lite", "rustls", @@ -3814,21 +3640,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "reqwest-middleware" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bc3f1384cffa4f274dad2d4ddd73aed32fed8f786d96c6be8aa4e5fd3c3b58" -dependencies = [ - "anyhow", - "async-trait", - "http 1.5.0", - "reqwest 0.13.4", - "serde", - "thiserror 2.0.18", - "tower-service", -] - [[package]] name = "resend-rs" version = "0.9.1" @@ -3929,7 +3740,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", - "log", "once_cell", "ring", "rustls-pki-types", @@ -4079,16 +3889,6 @@ dependencies = [ "cc", ] -[[package]] -name = "secrecy" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" -dependencies = [ - "serde", - "zeroize", -] - [[package]] name = "security-framework" version = "2.11.1" @@ -4177,7 +3977,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4215,29 +4015,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sev" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5031e00ad6d00d24f6b9990a181fdc8dc6e6222ba9ef657f2d8cf29e4c36b948" -dependencies = [ - "base64 0.22.1", - "bitfield", - "bitflags 2.13.0", - "byteorder", - "dirs", - "hex", - "iocuddle", - "lazy_static", - "libc", - "p384", - "rsa", - "sha2 0.10.8", - "static_assertions", - "uuid", - "x509-cert", -] - [[package]] name = "sha1" version = "0.10.7" @@ -4411,12 +4188,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - [[package]] name = "strsim" version = "0.11.1" @@ -4440,6 +4211,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "0.1.2" @@ -4463,7 +4245,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4490,11 +4272,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -4505,18 +4287,18 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -4577,54 +4359,31 @@ dependencies = [ [[package]] name = "tinfoil" -version = "0.2.1-maple.1" -source = "git+https://github.com/MaplePrivacyLabs/tinfoil-rs.git?rev=f0fef79eec6a5a2c8592cf8aff4b90ab556acfbc#f0fef79eec6a5a2c8592cf8aff4b90ab556acfbc" +version = "0.3.0-rc.4" +source = "git+https://github.com/tinfoilsh/tinfoil-rs?tag=v0.3.0-rc.4#4d15bea8c30064a219a3047f3e539e5825d5e07f" dependencies = [ - "async-openai", - "async-stream", - "async-trait", - "base64 0.22.1", - "bytes", - "const-oid 0.9.6", - "data-encoding", - "der", - "digest 0.10.7", - "dirs", - "ecdsa", - "ed25519-dalek 3.0.0", - "flate2", "futures-util", "getrandom 0.3.4", - "hex", "http 1.5.0", - "libc", - "p256", - "p384", - "pem", - "regex", - "reqwest 0.13.4", - "reqwest-middleware", - "rsa", + "http-body 1.0.1", + "http-body-util", + "reqwest 0.13.5", "rustls", + "rustls-webpki", "serde", "serde_json", - "sev", "sha2 0.10.8", - "thiserror 2.0.18", - "time", "tinfoil-ehbp", - "tls_codec", + "tinfoil-verifier", "tokio", - "tokio-rustls", - "tower 0.5.2", + "url", "webpki-roots", - "x509-cert", ] [[package]] name = "tinfoil-ehbp" -version = "0.3.1" -source = "git+https://github.com/tinfoilsh/encrypted-http-body-protocol?rev=93cc1fa1ad61e19f9a34fb23cb5b5d5635d3edb0#93cc1fa1ad61e19f9a34fb23cb5b5d5635d3edb0" +version = "0.6.0" +source = "git+https://github.com/tinfoilsh/encrypted-http-body-protocol?tag=v0.6.0#a681fafe19ddf5ce67048f936e4e65293f72168e" dependencies = [ "aes-gcm", "async-stream", @@ -4636,7 +4395,7 @@ dependencies = [ "http 1.5.0", "http-body-util", "rand 0.9.5", - "reqwest 0.13.4", + "reqwest 0.13.5", "serde", "serde_json", "sha2 0.10.8", @@ -4645,6 +4404,24 @@ dependencies = [ "zeroize", ] +[[package]] +name = "tinfoil-verifier" +version = "0.3.0-rc.4" +source = "git+https://github.com/tinfoilsh/tinfoil-rs?tag=v0.3.0-rc.4#4d15bea8c30064a219a3047f3e539e5825d5e07f" +dependencies = [ + "base64 0.22.1", + "cms", + "der", + "ecdsa", + "ed25519-dalek 3.0.0", + "getrandom 0.3.4", + "p256", + "p384", + "rsa", + "sha2 0.10.8", + "x509-cert", +] + [[package]] name = "tinystr" version = "0.7.6" @@ -4688,7 +4465,7 @@ checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4716,7 +4493,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -4739,17 +4516,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-stream" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - [[package]] name = "tokio-util" version = "0.7.19" @@ -4791,10 +4557,8 @@ dependencies = [ "pin-project-lite", "sync_wrapper 1.0.1", "tokio", - "tokio-util", "tower-layer", "tower-service", - "tracing", ] [[package]] @@ -4868,7 +4632,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -5041,7 +4805,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -5154,7 +4918,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 2.0.119", "wasm-bindgen-shared", ] @@ -5429,7 +5193,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", "synstructure", ] @@ -5451,7 +5215,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -5471,7 +5235,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", "synstructure", ] @@ -5493,7 +5257,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -5515,5 +5279,5 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] diff --git a/services/opensecret/Cargo.toml b/services/opensecret/Cargo.toml index 196ed21d4..d60bb6e94 100644 --- a/services/opensecret/Cargo.toml +++ b/services/opensecret/Cargo.toml @@ -75,7 +75,7 @@ tiktoken-rs = "0.5" once_cell = "1.19" pulldown-cmark = { version = "0.13.6", default-features = false } pulldown-cmark-to-cmark = "22.0.0" -tinfoil = { git = "https://github.com/MaplePrivacyLabs/tinfoil-rs.git", rev = "f0fef79eec6a5a2c8592cf8aff4b90ab556acfbc" } +tinfoil = { git = "https://github.com/tinfoilsh/tinfoil-rs", tag = "v0.3.0-rc.4", default-features = false } rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } [dev-dependencies] diff --git a/services/opensecret/deny.toml b/services/opensecret/deny.toml index 3f304ef32..157d470d6 100644 --- a/services/opensecret/deny.toml +++ b/services/opensecret/deny.toml @@ -5,10 +5,10 @@ unsound = "all" unmaintained = "none" ignore = [ { id = "RUSTSEC-2023-0071", reason = "No patched rsa release; Tinfoil uses RSA public-key verification only, while the advisory affects private-key operations" }, - # Reviewed for Tinfoil f0fef79eec6a5a2c8592cf8aff4b90ab556acfbc and - # EHBP 93cc1fa1ad61e19f9a34fb23cb5b5d5635d3edb0. This exception is local - # to the backend; an advisory-ID ignore does not enforce these source pins. - { id = "RUSTSEC-2026-0387", reason = "Pinned Tinfoil f0fef79 uses crypto-bigint 0.5.5 only for public-input P-256/P-384 attestation and Sigstore verification. Production EHBP key agreement uses X25519/dalek. Re-review when Tinfoil/EHBP pins, crypto consumers or HPKE suite selection change; remove after upgrading the affected dependency." }, + # Reviewed for Tinfoil v0.3.0-rc.4 (4d15bea8) and EHBP v0.6.0 (a681fafe). + # This exception is local to the backend; an advisory-ID ignore does not + # enforce these source pins. + { id = "RUSTSEC-2026-0387", reason = "Tinfoil v0.3.0-rc.4 reaches crypto-bigint 0.5.5 only through p256/p384, to verify ECDSA signatures over public attestation and Sigstore data. OpenSecret uses the TLS transport mode, so EHBP's HPKE (X25519/dalek) is compiled but not used. Re-review when Tinfoil/EHBP pins, crypto consumers or HPKE suite selection change; remove after upgrading the affected dependency." }, ] [bans] diff --git a/services/opensecret/docs/nitro-deploy.md b/services/opensecret/docs/nitro-deploy.md index 6a7f9e0f8..11441d28b 100644 --- a/services/opensecret/docs/nitro-deploy.md +++ b/services/opensecret/docs/nitro-deploy.md @@ -1220,7 +1220,8 @@ sudo vim /etc/nitro_enclaves/vsock-proxy.yaml Add these lines: ``` - {address: github-proxy.tinfoil.sh, port: 443} -# Retained unchanged by this migration; tinfoil-rs v0.2.0 embeds its trust root. +# Retained unchanged; tinfoil-rs 0.3 verifies offline and no longer contacts the +# GitHub, Sigstore TUF or KDS hosts. Router discovery still needs atc.tinfoil.sh. - {address: tuf-repo-cdn.sigstore.dev, port: 443} - {address: kds-proxy.tinfoil.sh, port: 443} - {address: atc.tinfoil.sh, port: 443} diff --git a/services/opensecret/docs/tinfoil-rust-sdk-parity.md b/services/opensecret/docs/tinfoil-rust-sdk-parity.md index c129d0af4..e6bed6436 100644 --- a/services/opensecret/docs/tinfoil-rust-sdk-parity.md +++ b/services/opensecret/docs/tinfoil-rust-sdk-parity.md @@ -30,6 +30,12 @@ streaming SSE, terminal framing, and numeric usage. Run it only through the Tier 3 procedure in `.agents/skills/validate-opensecret/SKILL.md`. +`provider_client::tests::live_maple_guests_attest_and_complete_through_the_direct_transport` +is ignored for the same reason and needs the dedicated Maple inference +credential. It proves that each dedicated guest verifies against its compiled +release policy and serves models, one completion and one stream through the +production transport. + If raw live evidence is needed, keep it outside the repository, use a non-secret credential label, and redact authorization and attestation metadata. The live test proves that provider and moment only; it does not prove @@ -39,7 +45,12 @@ provider, EIF identity, or deployment. ## Trust and lifecycle Preserve Tinfoil discovery, attestation, origin-bound TLS, bounded recovery, -connection reuse, and the no-downgrade rule. Retry only failures known to occur +connection reuse, and the no-downgrade rule. The SDK verifies V3 attestation +documents offline and enforces a freshness deadline on every verification; +OpenSecret renews a verification ahead of that deadline without a request in +hand, and replaces a client that still expires. The SDK pins a dedicated guest +to one repository; `src/maple_inference.rs` narrows each verification to the +approved tag, digest and launch measurement. Retry only failures known to occur before request acceptance; do not replay ambiguous completion requests or retain request bodies in shared recovery work. diff --git a/services/opensecret/flake.nix b/services/opensecret/flake.nix index 00c9b070d..cea202a52 100644 --- a/services/opensecret/flake.nix +++ b/services/opensecret/flake.nix @@ -569,8 +569,8 @@ cargoLock = { lockFile = ./Cargo.lock; outputHashes = { - "tinfoil-0.2.1-maple.1" = "sha256-vdpdRjBwQ7wyyyuTRZROpRJ7i8OttSrXjJxBG9vBs8s="; - "tinfoil-ehbp-0.3.1" = "sha256-BSSob5uyIIOw/Zr5aZFTU0GOM5imxk7KoZ5g+I4+s70="; + "tinfoil-0.3.0-rc.4" = "sha256-s9w+CRyd0Smtc9INMuy0OZDcKtgF2vNByXZhmFkjQBs="; + "tinfoil-ehbp-0.6.0" = "sha256-JjMZvXuCJOFRkAugN3YJGrHR/6o9thm4SEezqZbHzVU="; }; }; nativeBuildInputs = [ diff --git a/services/opensecret/src/maple_inference.rs b/services/opensecret/src/maple_inference.rs index 8c6ed4eea..5700f0895 100644 --- a/services/opensecret/src/maple_inference.rs +++ b/services/opensecret/src/maple_inference.rs @@ -4,9 +4,13 @@ //! node update. DNS, the API credential, or a server-supplied release reference //! never authorizes a new measurement. This is ordinary attested HTTPS using //! Tinfoil's direct V3 path; it does not use shared-router discovery. +//! +//! Tinfoil's verifier authenticates the hardware evidence and proves that the +//! guest runs a signed release of the pinned repository. [`MaplePolicy`] then +//! narrows that to the exact releases approved here. use crate::provider_registry::MapleInstanceId; -use tinfoil::{ApprovedRelease, DirectPolicy, Measurement, PinnedRelease, PredicateType}; +use tinfoil::verifier::{Measurement, Register, VerifiedFacts}; /// Backend-owned identity, address, and approved release set for one guest. /// Each guest has an independent verifier/client even when its release pins are @@ -158,25 +162,21 @@ struct ReleasePin { repo: &'static str, tag: &'static str, digest: &'static str, - registers: &'static [&'static str], + /// The AMD SEV-SNP launch measurement of the release. Every guest is an + /// AMD host; a TDX guest is never approved, so no TDX registers are pinned. + snp_launch: &'static str, } // Keep each guest's release pins independent, even while both run the same // artifact. A staged i02 update must never broaden i01's attestation policy. -// These identify the published artifact and full multiplatform measurement, -// not a cached live quote. Remove retired entries after rollout completes. -// Registers are the SEV-SNP measurement, then TDX RTMR1 and RTMR2, the order -// the verifier compares them in. +// These identify the published artifact and its launch measurement, not a +// cached live quote. Remove retired entries after rollout completes. // i01 serves the uncensored model; i02 independently serves stock DeepSeek. const I01_CURRENT_RELEASE: ReleasePin = ReleasePin { repo: "MaplePrivacyLabs/inference-deepseek-uncensored", tag: "v0.1.0+b300", digest: "6a8e906bc31caaccf5b6bbe84dec99c7213ec1d77aa360df464d531744590ac2", - registers: &[ - "9e01436661dff4702b622a51a7bbcb83ce0a61d0c2bdc2de5a2492fc1dec70bb1997df829147a154e11fdfc6dbe044fe", - "758adac43a82a5f3146342660caefea0a7714414dd9055c4a56d1502273d85bbad86d625096a206c9335c23d05df3f99", - "898884507ffe6bb1d51aa3bf548d8748043aa8e2018d545424c312e7a39109d75f30760f0d4124ae2cf5c89cf07db8dd", - ], + snp_launch: "9e01436661dff4702b622a51a7bbcb83ce0a61d0c2bdc2de5a2492fc1dec70bb1997df829147a154e11fdfc6dbe044fe", }; // Only the new stock release is approved. The former uncensored i02 release @@ -185,11 +185,7 @@ const I02_CURRENT_RELEASE: ReleasePin = ReleasePin { repo: "MaplePrivacyLabs/inference-deepseek", tag: "v0.1.2", digest: "4bc5f2119cb55e125c9cc5c57e3fe120df98f8145dc675c8d201ac01882989ec", - registers: &[ - "3f35fb1e92c599564e85e2b9adae8778bf8a9f553a8c936132301f09d4aa31a4a505b1c8f96cef407c53f4df67d23030", - "758adac43a82a5f3146342660caefea0a7714414dd9055c4a56d1502273d85bbad86d625096a206c9335c23d05df3f99", - "ce37a33da28a5dd43d0d1469903adf8e2589d4ff61f3277ff5796bb5485ba413eac27aee572e0973bde858621a71783b", - ], + snp_launch: "3f35fb1e92c599564e85e2b9adae8778bf8a9f553a8c936132301f09d4aa31a4a505b1c8f96cef407c53f4df67d23030", }; // The published, measured artifact that serves the stock Kimi K3.1 Pro @@ -200,49 +196,134 @@ const I03_CURRENT_RELEASE: ReleasePin = ReleasePin { repo: "MaplePrivacyLabs/inference-kimi-k3-1-pro", tag: "v0.2.5", digest: "04f20127da49f217f38ab77811fbc28569d3d3449a3e9d3df60a6d013619df48", - registers: &[ - "abf70017eeafe941c049b3b49c04619a7d34d8827fe1ea8026e00205b638d96319fa4525f7aa468e7c4f09650c9deb13", - "758adac43a82a5f3146342660caefea0a7714414dd9055c4a56d1502273d85bbad86d625096a206c9335c23d05df3f99", - "dccca72bf432e2d6d1cb4002c0ab7020d05467d6328f4f8152e2cb7d7ebd7aeef69850bcef2ac301433906ea53273955", - ], + snp_launch: "abf70017eeafe941c049b3b49c04619a7d34d8827fe1ea8026e00205b638d96319fa4525f7aa468e7c4f09650c9deb13", }; +/// One release a guest may run: the repository that published it, the exact +/// artifact, and the launch measurement the hardware must report. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ApprovedRelease { + repo: &'static str, + tag: &'static str, + digest: &'static str, + snp_launch: Register, +} + +/// The complete set of releases one guest may run. It is built once from the +/// compiled pins and never changes, so initialization, recovery and renewal +/// all verify against the same list. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct MaplePolicy { + approved: Vec, +} + +/// A compiled pin that is not a usable release identity. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct InvalidMaplePolicy; + +/// The guest verified, but as a release this policy does not approve. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[error("verified release is not approved for this guest")] +pub(crate) struct ReleaseNotApproved; + +impl MaplePolicy { + fn new( + pins: impl IntoIterator, + ) -> Result { + let approved = pins + .into_iter() + .map(|pin| { + let well_formed = !pin.repo.is_empty() + && !pin.tag.is_empty() + && pin.digest.len() == 64 + && pin + .digest + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')); + let snp_launch = pin.snp_launch.parse::(); + match (well_formed, snp_launch) { + (true, Ok(snp_launch)) => Ok(ApprovedRelease { + repo: pin.repo, + tag: pin.tag, + digest: pin.digest, + snp_launch, + }), + _ => Err(InvalidMaplePolicy), + } + }) + .collect::, _>>()?; + Ok(Self { approved }) + } + + /// The repositories to verify the guest against, in approval order and + /// without repeats. The verifier pins one repository per attempt. + pub(crate) fn repos(&self) -> Vec<&'static str> { + let mut repos = Vec::new(); + for release in &self.approved { + if !repos.contains(&release.repo) { + repos.push(release.repo); + } + } + repos + } + + /// Accept a verification only when repository, tag, digest and the + /// launch measurement the hardware signed all belong to one approved + /// release. Fields of two different releases never combine. + pub(crate) fn check(&self, verified: &VerifiedFacts) -> Result<(), ReleaseNotApproved> { + let Measurement::SevSnp { launch } = verified.enclave_measurement() else { + return Err(ReleaseNotApproved); + }; + self.check_identity( + verified.config_repo(), + verified.code_tag(), + verified.code_digest(), + launch, + ) + } + + fn check_identity( + &self, + repo: &str, + tag: &str, + digest: &str, + snp_launch: &Register, + ) -> Result<(), ReleaseNotApproved> { + let digest = digest.strip_prefix("sha256:").unwrap_or(digest); + self.approved + .iter() + .any(|release| { + release.repo == repo + && release.tag == tag + && release.digest == digest + && release.snp_launch == *snp_launch + }) + .then_some(()) + .ok_or(ReleaseNotApproved) + } +} + impl MapleEndpoint { /// The verifier policy for this guest's approved releases. /// /// A guest with none is unconfigured: it has no policy, so it gets no /// verifier and no network initialization. This is distinct from a /// malformed configured policy, which remains a startup error. - pub(crate) fn direct_policy(&self) -> Result, tinfoil::Error> { - let approved = approved_releases(self); - if approved.is_empty() { - return Ok(None); - } - DirectPolicy::new(approved).map(Some) + pub(crate) fn direct_policy(&self) -> Result, InvalidMaplePolicy> { + let policy = MaplePolicy::new( + self.current_release + .into_iter() + .chain(self.staged_releases.iter()), + )?; + Ok((!policy.approved.is_empty()).then_some(policy)) } } -fn approved_releases(endpoint: &MapleEndpoint) -> Vec { - endpoint - .current_release - .into_iter() - .chain(endpoint.staged_releases.iter()) - .map(|pin| ApprovedRelease { - release: PinnedRelease { - repo: pin.repo.to_owned(), - tag: pin.tag.to_owned(), - digest: pin.digest.to_owned(), - }, - measurement: Measurement { - type_: PredicateType::SnpTdxMultiPlatformV1, - registers: pin - .registers - .iter() - .map(|register| (*register).to_owned()) - .collect(), - }, - }) - .collect() +#[cfg(test)] +pub(crate) fn empty_policy_for_test() -> MaplePolicy { + MaplePolicy { + approved: Vec::new(), + } } #[cfg(test)] @@ -466,6 +547,29 @@ mod tests { } } + fn pins(endpoint: &MapleEndpoint) -> Vec<&'static ReleasePin> { + endpoint + .current_release + .into_iter() + .chain(endpoint.staged_releases.iter()) + .collect() + } + + fn policy_for(endpoint: &MapleEndpoint) -> MaplePolicy { + MaplePolicy::new(pins(endpoint)).expect("compiled pins must form a valid policy") + } + + fn approves(policy: &MaplePolicy, pin: &ReleasePin) -> bool { + policy + .check_identity( + pin.repo, + pin.tag, + pin.digest, + &pin.snp_launch.parse().expect("test launch measurement"), + ) + .is_ok() + } + #[test] fn dedicated_policies_are_complete_and_explicit_for_each_guest() { let mut hosts = std::collections::HashSet::new(); @@ -473,30 +577,26 @@ mod tests { let endpoint = endpoint(instance); assert_eq!(endpoint.instance, instance); assert!(hosts.insert(endpoint.host)); + // Every production guest has an approved release, so each is configured. + assert!(endpoint.current_release.is_some(), "{}", endpoint.host); let policy = endpoint .direct_policy() - .expect("compiled current/staged pins must form a valid policy"); + .expect("compiled current/staged pins must form a valid policy") + .expect("every production guest is configured"); let serialized = format!("{policy:?}"); - for pin in endpoint - .current_release - .into_iter() - .chain(endpoint.staged_releases.iter()) - { + for pin in pins(endpoint) { assert!(serialized.contains(pin.repo)); assert!(serialized.contains(pin.tag)); assert!(serialized.contains(pin.digest)); - for register in pin.registers { - assert!(serialized.contains(register)); - } + assert!(serialized.contains(pin.snp_launch)); + assert!(approves(&policy, pin)); + assert!(policy.repos().contains(&pin.repo)); } let url = reqwest::Url::parse(endpoint.base_url).unwrap(); assert_eq!(url.scheme(), "https"); assert_eq!(url.host_str(), Some(endpoint.host)); assert!(url.port().is_none()); assert_eq!(url.path(), "/"); - // Every production guest has an approved release, so each is configured. - assert!(endpoint.current_release.is_some(), "{}", endpoint.host); - assert!(policy.is_some(), "{}", endpoint.host); } assert_eq!(endpoint(MapleInstanceId::I01).host, "i01.tfinf.maple.ai"); assert_eq!(endpoint(MapleInstanceId::I02).host, "i02.tfinf.maple.ai"); @@ -517,11 +617,17 @@ mod tests { assert_eq!(unpinned.base_url, pinned.base_url); assert!(unpinned.current_release.is_none()); assert!(unpinned.staged_releases.is_empty()); - assert!(approved_releases(unpinned).is_empty()); + assert!(pins(unpinned).is_empty()); // Unconfigured is a valid state, distinct from a malformed policy. assert!(matches!(unpinned.direct_policy(), Ok(None))); // An empty set is never a policy that approves everything. - assert!(DirectPolicy::new(Vec::new()).is_err()); + let empty = empty_policy_for_test(); + assert!(empty.repos().is_empty()); + for instance in MapleInstanceId::ALL { + for pin in pins(endpoint(instance)) { + assert!(!approves(&empty, pin)); + } + } // Pins compiled for this and the other guests do not reach it. for instance in MapleInstanceId::ALL { assert!(endpoint(instance).direct_policy().unwrap().is_some()); @@ -534,7 +640,7 @@ mod tests { repo: I03_CURRENT_RELEASE.repo, tag: "test-i03-only-stage", digest: I03_CURRENT_RELEASE.digest, - registers: I03_CURRENT_RELEASE.registers, + snp_launch: I03_CURRENT_RELEASE.snp_launch, }; const STAGED_ONLY_I03_ENDPOINT: MapleEndpoint = MapleEndpoint { instance: MapleInstanceId::I03, @@ -543,10 +649,13 @@ mod tests { current_release: None, staged_releases: &[I03_TEST_STAGE], }; - let staged = approved_releases(&STAGED_ONLY_I03_ENDPOINT); - assert_eq!(staged.len(), 1); - assert_eq!(staged[0].release.tag, I03_TEST_STAGE.tag); - assert!(STAGED_ONLY_I03_ENDPOINT.direct_policy().unwrap().is_some()); + let staged = STAGED_ONLY_I03_ENDPOINT + .direct_policy() + .unwrap() + .expect("a staged release alone is a policy"); + assert_eq!(staged.approved.len(), 1); + assert!(approves(&staged, &I03_TEST_STAGE)); + assert!(!approves(&staged, &I03_CURRENT_RELEASE)); } #[test] @@ -554,67 +663,114 @@ mod tests { let i03 = endpoint(MapleInstanceId::I03); assert_eq!(i03.host, "i03.tfinf.maple.ai"); assert!(i03.staged_releases.is_empty()); - let approved = approved_releases(i03); - assert_eq!(approved.len(), 1); - let release = &approved[0]; - assert_eq!( - release.release.repo, - "MaplePrivacyLabs/inference-kimi-k3-1-pro" - ); - assert_eq!(release.release.tag, "v0.2.5"); + let policy = i03 + .direct_policy() + .expect("the pin is a well-formed policy") + .expect("a pinned guest is configured"); + assert_eq!(policy.approved.len(), 1); + let release = &policy.approved[0]; + assert_eq!(release.repo, "MaplePrivacyLabs/inference-kimi-k3-1-pro"); + assert_eq!(release.tag, "v0.2.5"); assert_eq!( - release.release.digest, + release.digest, "04f20127da49f217f38ab77811fbc28569d3d3449a3e9d3df60a6d013619df48" ); assert_eq!( - release.measurement.type_, - PredicateType::SnpTdxMultiPlatformV1 + release.snp_launch.to_string(), + "abf70017eeafe941c049b3b49c04619a7d34d8827fe1ea8026e00205b638d96319fa4525f7aa468e7c4f09650c9deb13" ); - assert_eq!(release.measurement.registers, [ - "abf70017eeafe941c049b3b49c04619a7d34d8827fe1ea8026e00205b638d96319fa4525f7aa468e7c4f09650c9deb13", - "758adac43a82a5f3146342660caefea0a7714414dd9055c4a56d1502273d85bbad86d625096a206c9335c23d05df3f99", - "dccca72bf432e2d6d1cb4002c0ab7020d05467d6328f4f8152e2cb7d7ebd7aeef69850bcef2ac301433906ea53273955", - ]); - let policy = i03 - .direct_policy() - .expect("the pin is a well-formed policy") - .expect("a pinned guest is configured"); - let serialized = format!("{policy:?}"); - assert!(serialized.contains("MaplePrivacyLabs/inference-kimi-k3-1-pro")); - assert!(serialized.contains(&release.release.digest)); + assert_eq!(policy.repos(), ["MaplePrivacyLabs/inference-kimi-k3-1-pro"]); } /// Copying another guest's pin onto i03, or i03's onto another guest, must /// fail: the Kimi checkpoint has its own artifact and its own measurement. #[test] fn i03_pin_is_not_another_guests_pin() { - let i03 = &approved_releases(endpoint(MapleInstanceId::I03))[0]; + let i03 = policy_for(endpoint(MapleInstanceId::I03)); for other in [MapleInstanceId::I01, MapleInstanceId::I02] { - let approved = approved_releases(endpoint(other)); - assert!(!approved.is_empty(), "{other:?}"); - for release in approved { - assert_ne!(release.release.repo, i03.release.repo, "{other:?}"); - assert_ne!(release.release.digest, i03.release.digest, "{other:?}"); - assert_ne!( - release.measurement.registers[0], i03.measurement.registers[0], - "{other:?}" - ); - assert_ne!( - release.measurement.registers, i03.measurement.registers, - "{other:?}" - ); + let policy = policy_for(endpoint(other)); + assert!(!policy.approved.is_empty(), "{other:?}"); + assert!(!approves(&policy, &I03_CURRENT_RELEASE), "{other:?}"); + for release in &policy.approved { + assert_ne!(release.repo, i03.approved[0].repo, "{other:?}"); + assert_ne!(release.digest, i03.approved[0].digest, "{other:?}"); + assert_ne!(release.snp_launch, i03.approved[0].snp_launch, "{other:?}"); } + for pin in pins(endpoint(other)) { + assert!(!approves(&i03, pin), "{other:?}"); + } + } + } + + #[test] + fn a_release_is_approved_only_as_a_whole() { + let policy = policy_for(endpoint(MapleInstanceId::I02)); + let pin = &I02_CURRENT_RELEASE; + let launch: Register = pin.snp_launch.parse().unwrap(); + let other_launch: Register = I01_CURRENT_RELEASE.snp_launch.parse().unwrap(); + + assert!(policy + .check_identity(pin.repo, pin.tag, pin.digest, &launch) + .is_ok()); + // The verifier may report the digest with its algorithm prefix. + assert!(policy + .check_identity( + pin.repo, + pin.tag, + &format!("sha256:{}", pin.digest), + &launch + ) + .is_ok()); + + for (repo, tag, digest, launch) in [ + (I01_CURRENT_RELEASE.repo, pin.tag, pin.digest, &launch), + (pin.repo, "v0.1.1", pin.digest, &launch), + (pin.repo, pin.tag, I01_CURRENT_RELEASE.digest, &launch), + (pin.repo, pin.tag, pin.digest, &other_launch), + (pin.repo, pin.tag, "", &launch), + ("", "", "", &launch), + ] { + assert_eq!( + policy.check_identity(repo, tag, digest, launch), + Err(ReleaseNotApproved) + ); + } + } + + #[test] + fn malformed_pins_are_a_policy_error_and_no_pins_are_no_policy() { + const BAD_LAUNCH: ReleasePin = ReleasePin { + repo: I02_CURRENT_RELEASE.repo, + tag: I02_CURRENT_RELEASE.tag, + digest: I02_CURRENT_RELEASE.digest, + snp_launch: "not-a-measurement", + }; + const BAD_DIGEST: ReleasePin = ReleasePin { + repo: I02_CURRENT_RELEASE.repo, + tag: I02_CURRENT_RELEASE.tag, + digest: "sha256:4bc5f2119cb55e125c9cc5c57e3fe120df98f8145dc675c8d201ac01882989ec", + snp_launch: I02_CURRENT_RELEASE.snp_launch, + }; + const NO_REPO: ReleasePin = ReleasePin { + repo: "", + tag: I02_CURRENT_RELEASE.tag, + digest: I02_CURRENT_RELEASE.digest, + snp_launch: I02_CURRENT_RELEASE.snp_launch, + }; + for pin in [&BAD_LAUNCH, &BAD_DIGEST, &NO_REPO] { + assert_eq!(MaplePolicy::new([pin]), Err(InvalidMaplePolicy)); } + assert!(MaplePolicy::new([]).unwrap().repos().is_empty()); } #[test] fn staging_i02_release_does_not_approve_it_for_i01() { // Synthetic release identity is local to this test; no endpoint uses it. const I02_TEST_STAGE: ReleasePin = ReleasePin { - repo: I02_CURRENT_RELEASE.repo, + repo: "MaplePrivacyLabs/test-i02-only-stage", tag: "test-i02-only-stage", digest: I02_CURRENT_RELEASE.digest, - registers: I02_CURRENT_RELEASE.registers, + snp_launch: I02_CURRENT_RELEASE.snp_launch, }; const STAGED_I02_ENDPOINT: MapleEndpoint = MapleEndpoint { instance: MapleInstanceId::I02, @@ -624,45 +780,40 @@ mod tests { staged_releases: &[I02_TEST_STAGE], }; - let i01_approved = approved_releases(endpoint(MapleInstanceId::I01)); - let current_i02_approved = approved_releases(endpoint(MapleInstanceId::I02)); - let staged_i02_approved = approved_releases(&STAGED_I02_ENDPOINT); - assert_eq!(i01_approved.len(), 1); - assert_eq!(current_i02_approved.len(), 1); - assert_eq!(staged_i02_approved.len(), 2); - assert_eq!(staged_i02_approved[1].release.tag, I02_TEST_STAGE.tag); - assert!(i01_approved - .iter() - .all(|approved| approved.release.tag != I02_TEST_STAGE.tag)); - DirectPolicy::new(i01_approved).expect("i01 current policy remains valid"); - DirectPolicy::new(staged_i02_approved).expect("i02 staged policy remains valid"); + let i01 = policy_for(endpoint(MapleInstanceId::I01)); + let current_i02 = policy_for(endpoint(MapleInstanceId::I02)); + let staged_i02 = policy_for(&STAGED_I02_ENDPOINT); + assert_eq!(i01.approved.len(), 1); + assert_eq!(current_i02.approved.len(), 1); + assert_eq!(staged_i02.approved.len(), 2); + // The current release stays first, so it is the first one verified. + assert_eq!( + staged_i02.repos(), + [I02_CURRENT_RELEASE.repo, I02_TEST_STAGE.repo] + ); + assert!(approves(&staged_i02, &I02_TEST_STAGE)); + assert!(approves(&staged_i02, &I02_CURRENT_RELEASE)); + assert!(!approves(¤t_i02, &I02_TEST_STAGE)); + assert!(!approves(&i01, &I02_TEST_STAGE)); } #[test] fn stock_i02_approves_only_its_new_release() { - let approved = approved_releases(endpoint(MapleInstanceId::I02)); - assert_eq!(approved.len(), 1); - let release = &approved[0]; - assert_eq!(release.release.repo, "MaplePrivacyLabs/inference-deepseek"); - assert_eq!(release.release.tag, "v0.1.2"); + let policy = policy_for(endpoint(MapleInstanceId::I02)); + assert_eq!(policy.approved.len(), 1); + let release = &policy.approved[0]; + assert_eq!(release.repo, "MaplePrivacyLabs/inference-deepseek"); + assert_eq!(release.tag, "v0.1.2"); assert_eq!( - release.release.digest, + release.digest, "4bc5f2119cb55e125c9cc5c57e3fe120df98f8145dc675c8d201ac01882989ec" ); assert_eq!( - release.measurement.type_, - PredicateType::SnpTdxMultiPlatformV1 + release.snp_launch.to_string(), + "3f35fb1e92c599564e85e2b9adae8778bf8a9f553a8c936132301f09d4aa31a4a505b1c8f96cef407c53f4df67d23030" ); - assert_eq!(release.measurement.registers, [ - "3f35fb1e92c599564e85e2b9adae8778bf8a9f553a8c936132301f09d4aa31a4a505b1c8f96cef407c53f4df67d23030", - "758adac43a82a5f3146342660caefea0a7714414dd9055c4a56d1502273d85bbad86d625096a206c9335c23d05df3f99", - "ce37a33da28a5dd43d0d1469903adf8e2589d4ff61f3277ff5796bb5485ba413eac27aee572e0973bde858621a71783b", - ]); - assert!(approved.iter().all(|release| { - release.release.repo != I01_CURRENT_RELEASE.repo - && release.release.digest != I01_CURRENT_RELEASE.digest - && release.measurement.registers[0] != I01_CURRENT_RELEASE.registers[0] - })); + assert_eq!(policy.repos(), ["MaplePrivacyLabs/inference-deepseek"]); + assert!(!approves(&policy, &I01_CURRENT_RELEASE)); for instance in [MapleInstanceId::I02, MapleInstanceId::I01] { assert!(endpoint(instance).direct_policy().unwrap().is_some()); } @@ -670,70 +821,48 @@ mod tests { #[test] fn uncensored_i01_approves_only_its_new_release() { - let prepared = approved_releases(endpoint(MapleInstanceId::I01)); - assert_eq!(prepared.len(), 1); + let policy = policy_for(endpoint(MapleInstanceId::I01)); + assert_eq!(policy.approved.len(), 1); + let release = &policy.approved[0]; assert_eq!( - prepared[0].release.repo, + release.repo, "MaplePrivacyLabs/inference-deepseek-uncensored" ); - assert_eq!(prepared[0].release.tag, "v0.1.0+b300"); + assert_eq!(release.tag, "v0.1.0+b300"); assert_eq!( - prepared[0].release.digest, + release.digest, "6a8e906bc31caaccf5b6bbe84dec99c7213ec1d77aa360df464d531744590ac2" ); assert_eq!( - prepared[0].measurement.type_, - PredicateType::SnpTdxMultiPlatformV1 + release.snp_launch.to_string(), + "9e01436661dff4702b622a51a7bbcb83ce0a61d0c2bdc2de5a2492fc1dec70bb1997df829147a154e11fdfc6dbe044fe" ); - assert_eq!(prepared[0].measurement.registers, [ - "9e01436661dff4702b622a51a7bbcb83ce0a61d0c2bdc2de5a2492fc1dec70bb1997df829147a154e11fdfc6dbe044fe", - "758adac43a82a5f3146342660caefea0a7714414dd9055c4a56d1502273d85bbad86d625096a206c9335c23d05df3f99", - "898884507ffe6bb1d51aa3bf548d8748043aa8e2018d545424c312e7a39109d75f30760f0d4124ae2cf5c89cf07db8dd", - ]); - assert_ne!(prepared[0].release.repo, I02_CURRENT_RELEASE.repo); - assert_ne!(prepared[0].release.digest, I02_CURRENT_RELEASE.digest); - assert_ne!( - prepared[0].measurement.registers[0], - I02_CURRENT_RELEASE.registers[0] + assert_eq!( + policy.repos(), + ["MaplePrivacyLabs/inference-deepseek-uncensored"] ); + assert!(!approves(&policy, &I02_CURRENT_RELEASE)); } #[test] - fn retired_guest_roles_are_not_approved_on_either_endpoint() { + fn retired_releases_are_not_approved_on_either_guest() { for instance in MapleInstanceId::ALL { assert!(endpoint(instance).staged_releases.is_empty()); - for approved in approved_releases(endpoint(instance)) { - for (retired_digest, retired_snp) in [ - ( - "7f421e8aefdd63181b71b9d202ac6a3b05b976c6ecb156354a20ff691931f5be", - "f645aa2a679cf7ed575bb5d9d2fa18104d24ae545950d6c3669b6af1d81328f099f3437f9129c608ac9ff5a97927d365", - ), - ( - "1d92cd06f7b47179bf81612f6a41fdb0a329253affef1803f0cdeb5175cc80c4", - "b391ea9621062080c01c3686bb70e8889148f6d6c7ca71eec6c149f4132b50f7b47e251f113a9a0861f05e546203aa39", - ), + for approved in policy_for(endpoint(instance)).approved { + assert_ne!(approved.tag, "v0.1.0"); + for retired_digest in [ + "7f421e8aefdd63181b71b9d202ac6a3b05b976c6ecb156354a20ff691931f5be", + "1d92cd06f7b47179bf81612f6a41fdb0a329253affef1803f0cdeb5175cc80c4", + "2d69e8544e5b2706d0e6004bc0ac925dc9abd79cb284f9400c26c9d145e25b00", ] { - assert_ne!(approved.release.digest, retired_digest); - assert_ne!(approved.measurement.registers[0], retired_snp); + assert_ne!(approved.digest, retired_digest); } - } - } - } - - #[test] - fn retired_release_is_not_approved_on_either_guest() { - for instance in MapleInstanceId::ALL { - for approved in approved_releases(endpoint(instance)) { - assert_ne!(approved.release.tag, "v0.1.0"); - assert_ne!( - approved.release.digest, - "2d69e8544e5b2706d0e6004bc0ac925dc9abd79cb284f9400c26c9d145e25b00" - ); - for retired_register in [ + for retired_launch in [ + "f645aa2a679cf7ed575bb5d9d2fa18104d24ae545950d6c3669b6af1d81328f099f3437f9129c608ac9ff5a97927d365", + "b391ea9621062080c01c3686bb70e8889148f6d6c7ca71eec6c149f4132b50f7b47e251f113a9a0861f05e546203aa39", "d4d5fd1166413a3229a83899b99c06fb8cb904badb2ed5b9b8e6cb7414ad110628b6780eddaf10c42cbc996909145541", - "24e53d3e8a77e9aa9182b61bbddc5138050c5dc00628231c51cfe6798431f64d59af20494708190c7aca85b166675550", ] { - assert!(!approved.measurement.registers.iter().any(|register| register == retired_register)); + assert_ne!(approved.snp_launch.to_string(), retired_launch); } } } diff --git a/services/opensecret/src/provider_client.rs b/services/opensecret/src/provider_client.rs index b8ca04e23..ced1ce0e3 100644 --- a/services/opensecret/src/provider_client.rs +++ b/services/opensecret/src/provider_client.rs @@ -8,12 +8,14 @@ use std::collections::{BTreeMap, HashSet}; use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; -use std::time::Duration; +use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak}; +use std::time::{Duration, SystemTime}; use tokio::sync::Mutex; use tokio::task::JoinHandle; +mod attested; mod diagnostics; +use attested::{AttestationFailureDiagnostic, AttestedClient, ExecuteFailure}; pub use diagnostics::UpstreamDiagnostic; type StandardHttpClient = reqwest::Client; @@ -22,54 +24,13 @@ type TinfoilRefreshTask = JoinHandle AttestationFailureDiagnostic { - // SDK errors can contain arbitrary response text, URLs, and credentials. - // Log only finite labels derived from typed variants, never their payloads. - let category = if error.is_configuration() { - "configuration" - } else if error.is_fetch() { - "fetch" - } else if error.is_attestation() { - "attestation" - } else if error.is_api() { - "api" - } else { - "other" - }; - let reason = match error { - tinfoil::Error::Configuration(_) => "configuration", - tinfoil::Error::Api(_) => "api", - tinfoil::Error::AttestationFetch(_) => "attestation_fetch", - tinfoil::Error::AttestationVerification(_) => "attestation_verification", - tinfoil::Error::CertificateMismatch => "certificate_mismatch", - tinfoil::Error::SigstoreVerification(_) => "sigstore_verification", - tinfoil::Error::GitHub(_) => "github_fetch", - tinfoil::Error::MeasurementMismatch { .. } => "measurement_mismatch", - tinfoil::Error::Tls(_) => "tls_verification", - tinfoil::Error::Ehbp(_) => "ehbp", - tinfoil::Error::EhbpKeyMismatch(_) => "ehbp_key_mismatch", - tinfoil::Error::Network(_) => "network", - tinfoil::Error::UnsupportedFormat(_) => "unsupported_format", - tinfoil::Error::Http(error) if error.is_timeout() => "http_timeout", - tinfoil::Error::Http(error) if error.is_connect() => "http_connect", - tinfoil::Error::Http(error) if error.is_status() => "http_status", - tinfoil::Error::Http(_) => "http", - tinfoil::Error::Json(_) => "json", - tinfoil::Error::Base64(_) => "base64", - tinfoil::Error::Io(_) => "io", - _ => "unknown", - }; - AttestationFailureDiagnostic { category, reason } -} - #[derive(Debug, thiserror::Error)] pub enum ProviderClientError { #[error("failed to build provider HTTP client: {0}")] @@ -252,18 +213,32 @@ fn map_reqwest_send_error(error: reqwest::Error) -> ProviderRequestError { // already-executed request is safe to replay. An expiry concurrent with a reset // does not prove the upstream failed to accept the POST. fn classify_post_execute_failure( - is_connect: bool, + failure: ExecuteFailure, verified_state_current: bool, - message: String, ) -> (ProviderRequestError, bool) { - let error = if is_connect { - ProviderRequestError::Connect(message) - } else { - ProviderRequestError::Send(message) + let error = match failure { + ExecuteFailure::Refused(label) => ProviderRequestError::Build(label.to_owned()), + ExecuteFailure::Unsent(message) => ProviderRequestError::Connect(message), + ExecuteFailure::Ambiguous(message) => ProviderRequestError::Send(message), }; (error, !verified_state_current) } +/// How long to wait before renewing a verification that expires at `expires`. +/// `None` once it has expired: recovery then belongs to initialization. +fn renewal_wait(now: SystemTime, expires: SystemTime, already_tried: bool) -> Option { + let remaining = expires + .duration_since(now) + .ok() + .filter(|left| !left.is_zero())?; + let until_lead = remaining.saturating_sub(ATTESTATION_RENEWAL_LEAD); + Some(if already_tried { + until_lead.max(ATTESTATION_RENEWAL_RETRY) + } else { + until_lead + }) +} + fn current_slot_client( candidate: Option<&Arc>, is_current: impl FnOnce(&T) -> bool, @@ -274,12 +249,15 @@ fn current_slot_client( #[derive(Clone)] struct SecureClientSnapshot { - client: Arc, + client: Arc, + // The SDK holds no credential. The transport's own key travels with the + // verified client it may be sent to. + api_key: Arc, refresh_attempt: u64, } struct SecureClientSlot { - client: Option>, + client: Option>, refresh_attempt: u64, } @@ -289,7 +267,7 @@ enum AttestationTarget { MapleDirect { instance: MapleInstanceId, host: &'static str, - policy: tinfoil::DirectPolicy, + policy: crate::maple_inference::MaplePolicy, }, } @@ -308,18 +286,18 @@ impl AttestationTarget { } } - fn client_is_current(&self, client: &tinfoil::Client) -> bool { - match self { - Self::SharedRouter => true, - Self::MapleDirect { .. } => client.secure_client().is_verified(), - } + // Every verification has a hard freshness deadline. A client past it is + // never handed a request: it is replaced by body-free recovery instead of + // being left to verify again while a caller's request waits on it. + fn client_is_current(&self, client: &AttestedClient) -> bool { + client.is_fresh() } - async fn create_client(&self, api_key: String) -> Result { + async fn create_client(&self) -> Result { match self { - Self::SharedRouter => tinfoil::Client::new_default_with_api_key(api_key).await, + Self::SharedRouter => AttestedClient::connect_router().await, Self::MapleDirect { host, policy, .. } => { - tinfoil::Client::new_direct(*host, api_key, policy.clone()).await + AttestedClient::connect_maple(host, policy).await } } } @@ -330,13 +308,14 @@ type TestClientFactory = Arc< dyn Fn( AttestationTarget, String, - ) -> Pin> + Send>> - + Send + ) -> Pin< + Box> + Send>, + > + Send + Sync, >; struct SecureTinfoilTransport { - api_key: String, + api_key: Arc, target: AttestationTarget, #[cfg(test)] client_factory: Option, @@ -452,7 +431,7 @@ fn spawn_tinfoil_refresh_after_connect_failure( impl SecureTinfoilTransport { fn new(api_key: String, target: AttestationTarget) -> Self { Self { - api_key, + api_key: api_key.into(), target, client: RwLock::new(SecureClientSlot { client: None, @@ -465,12 +444,70 @@ impl SecureTinfoilTransport { } } - async fn create_client(&self) -> Result { + async fn create_client(&self) -> Result { #[cfg(test)] if let Some(factory) = &self.client_factory { - return factory(self.target.clone(), self.api_key.clone()).await; + return factory(self.target.clone(), self.api_key.to_string()).await; } - self.target.create_client(self.api_key.clone()).await + self.target.create_client().await + } + + /// Install a newly verified client and start renewing it. The caller + /// holds the slot's write lock. + fn install( + self: &Arc, + slot: &mut SecureClientSlot, + client: AttestedClient, + ) -> Arc { + let client = Arc::new(client); + slot.client = Some(Arc::clone(&client)); + self.spawn_renewal(Arc::clone(&client)); + client + } + + /// Renew `client`'s verification ahead of its deadline for as long as the + /// slot holds it. Renewal carries no request, so nothing waits on it; a + /// client that still expires is replaced by initialization as before. + fn spawn_renewal(self: &Arc, client: Arc) { + let transport: Weak = Arc::downgrade(self); + tokio::spawn(async move { + let mut tried_for = None; + loop { + let Some(expires) = client.freshness_expires_at() else { + return; + }; + let Some(wait) = + renewal_wait(SystemTime::now(), expires, tried_for == Some(expires)) + else { + return; + }; + tokio::time::sleep(wait).await; + let Some(transport) = transport.upgrade() else { + return; + }; + let still_installed = transport + .read_client() + .client + .as_ref() + .is_some_and(|current| Arc::ptr_eq(current, &client)); + if !still_installed { + return; + } + tried_for = Some(expires); + match client.reverify().await { + Ok(()) => tracing::info!( + provider = transport.target.label(), + "Provider attestation renewed" + ), + Err(diagnostic) => tracing::warn!( + provider = transport.target.label(), + error_category = diagnostic.category, + error_reason = diagnostic.reason, + "Provider attestation renewal failed; keeping the current verification" + ), + } + } + }); } fn read_client(&self) -> RwLockReadGuard<'_, SecureClientSlot> { @@ -492,6 +529,7 @@ impl SecureTinfoilTransport { }) .map(|client| SecureClientSnapshot { client, + api_key: Arc::clone(&self.api_key), refresh_attempt: slot.refresh_attempt, }) } @@ -519,7 +557,7 @@ impl SecureTinfoilTransport { }); } - async fn initialize_until_ready(&self, claim: &mut InitializationClaim) { + async fn initialize_until_ready(self: &Arc, claim: &mut InitializationClaim) { let mut retry_delay = TINFOIL_INITIAL_RETRY_DELAY; loop { @@ -540,7 +578,7 @@ impl SecureTinfoilTransport { match discovery { Ok(Ok(client)) => { let mut slot = self.write_client(); - slot.client = Some(Arc::new(client)); + self.install(&mut slot, client); slot.refresh_attempt = slot.refresh_attempt.wrapping_add(1); // Release the claim while the slot is still write-locked. // A request can only observe the new client after another @@ -552,15 +590,14 @@ impl SecureTinfoilTransport { ); return; } - Ok(Err(error)) => { - let diagnostic = attestation_failure_diagnostic(&error); + Ok(Err(diagnostic)) => { tracing::warn!( retry_delay_seconds = retry_delay.as_secs(), provider = self.target.label(), error_category = diagnostic.category, error_reason = diagnostic.reason, - error_is_attestation = error.is_attestation(), - error_is_fetch = error.is_fetch(), + error_is_attestation = diagnostic.is_attestation(), + error_is_fetch = diagnostic.is_network(), "Provider attestation failed; retrying in background" ); } @@ -628,20 +665,20 @@ impl SecureTinfoilTransport { slot.refresh_attempt = slot.refresh_attempt.wrapping_add(1); match refreshed { Ok(Ok(client)) => { - slot.client = Some(Arc::new(client)); + let client = self.install(&mut slot, client); Ok(SecureClientSnapshot { - client: Arc::clone(slot.client.as_ref().expect("client was just installed")), + client, + api_key: Arc::clone(&self.api_key), refresh_attempt: slot.refresh_attempt, }) } - Ok(Err(error)) => { - let diagnostic = attestation_failure_diagnostic(&error); + Ok(Err(diagnostic)) => { tracing::warn!( provider = self.target.label(), error_category = diagnostic.category, error_reason = diagnostic.reason, - error_is_attestation = error.is_attestation(), - error_is_fetch = error.is_fetch(), + error_is_attestation = diagnostic.is_attestation(), + error_is_fetch = diagnostic.is_network(), "Provider attestation refresh failed; transitioning unavailable" ); slot.client = None; @@ -876,7 +913,7 @@ impl ProviderClient { Ok(Self { tinfoil: TinfoilTransport::Secure(Arc::new(SecureTinfoilTransport { - api_key: "unused-test-key".to_string(), + api_key: "unused-test-key".into(), target: AttestationTarget::SharedRouter, client_factory: None, client: RwLock::new(SecureClientSlot { @@ -986,30 +1023,20 @@ impl ProviderClient { let send = async { match attempt { TinfoilAttempt::Secure(failed_snapshot) => { - let http_client = failed_snapshot.client.http_client().map_err(|error| { - if !transport - .secure() - .target - .client_is_current(&failed_snapshot.client) - { - transport.start_background_initialization(); - transport.secure().target.unavailable() - } else { - ProviderRequestError::Send(error.to_string()) - } - })?; - match http_client.execute(first_request).await { + match failed_snapshot.client.execute(first_request).await { Ok(response) => Ok(response), - // reqwest's typed connect class is limited to connector setup - // (DNS/TCP/TLS). In particular, the SDK's rustls pin mismatch - // arrives here before any HTTP request bytes can be written. - // Request/body/timeout failures are deliberately not replayed by this - // certificate-rotation layer. - Err(error) if error.is_connect() => { + // Proven unsent: the connection was never established + // (DNS/TCP/TLS), or the peer no longer held the attested + // key, which the pinned handshake rejects before any HTTP + // request bytes are written. The SDK has by then already + // verified the same enclave again and tried once more. + // Request/body/timeout failures are deliberately not + // replayed by this certificate-rotation layer. + Err(ExecuteFailure::Unsent(message)) => { prior_failures_for_send .lock() .expect("provider attempt trace mutex poisoned") - .push(ProviderRequestError::Connect(error.to_string())); + .push(ProviderRequestError::Connect(message)); let refreshed = spawn_tinfoil_refresh_after_connect_failure( Arc::clone(transport.secure()), failed_snapshot.clone(), @@ -1026,29 +1053,15 @@ impl ProviderClient { )?; refreshed .client - .http_client() - .map_err(|error| { - if !transport - .secure() - .target - .client_is_current(&refreshed.client) - { - transport.start_background_initialization(); - transport.secure().target.unavailable() - } else { - ProviderRequestError::Send(error.to_string()) - } - })? .execute(retry_request) .await - .map_err(|error| { + .map_err(|failure| { let (error, recover) = classify_post_execute_failure( - error.is_connect(), + failure, transport .secure() .target .client_is_current(&refreshed.client), - error.to_string(), ); if recover { transport.start_background_initialization(); @@ -1056,14 +1069,13 @@ impl ProviderClient { error }) } - Err(error) => { + Err(failure) => { let (error, recover) = classify_post_execute_failure( - error.is_connect(), + failure, transport .secure() .target .client_is_current(&failed_snapshot.client), - error.to_string(), ); if recover { transport.start_background_initialization(); @@ -1132,7 +1144,7 @@ impl ProviderClient { let (base_url, api_key) = match attempt { TinfoilAttempt::Secure(snapshot) => ( format!("https://{}", snapshot.client.enclave()), - snapshot.client.secure_client().api_key(), + &*snapshot.api_key, ), #[cfg(test)] TinfoilAttempt::Plain { @@ -1357,134 +1369,53 @@ mod tests { } } - #[test] - fn attestation_failure_diagnostics_preserve_typed_causes_without_payloads() { - let sensitive = "Bearer diagnostic-secret https://private.invalid/?token=diagnostic-secret\nforged_log=true"; - let cases = [ - ( - tinfoil::Error::Configuration(sensitive.into()), - "configuration", - "configuration", - ), - ( - tinfoil::Error::AttestationFetch(sensitive.into()), - "fetch", - "attestation_fetch", - ), - ( - tinfoil::Error::AttestationVerification(sensitive.into()), - "attestation", - "attestation_verification", - ), - ( - tinfoil::Error::CertificateMismatch, - "attestation", - "certificate_mismatch", - ), - ( - tinfoil::Error::SigstoreVerification(sensitive.into()), - "attestation", - "sigstore_verification", - ), - ( - tinfoil::Error::GitHub(sensitive.into()), - "fetch", - "github_fetch", - ), - ( - tinfoil::Error::MeasurementMismatch { - expected: sensitive.into(), - actual: sensitive.into(), - }, - "attestation", - "measurement_mismatch", - ), - ( - tinfoil::Error::Tls(sensitive.into()), - "attestation", - "tls_verification", - ), - ( - tinfoil::Error::Ehbp(sensitive.into()), - "attestation", - "ehbp", - ), - ( - tinfoil::Error::EhbpKeyMismatch(sensitive.into()), - "attestation", - "ehbp_key_mismatch", - ), - ( - tinfoil::Error::Network(sensitive.into()), - "fetch", - "network", - ), - ( - tinfoil::Error::UnsupportedFormat(sensitive.into()), - "attestation", - "unsupported_format", - ), - ( - tinfoil::Error::Io(std::io::Error::other(sensitive)), - "fetch", - "io", - ), - ( - tinfoil::Error::Json(serde_json::from_value::(json!(sensitive)).unwrap_err()), - "attestation", - "json", - ), - ( - tinfoil::Error::Http( - test_http_client() - .unwrap() - .get("https://private.invalid/?token=diagnostic-secret") - .header("invalid\nheader", sensitive) - .build() - .unwrap_err(), - ), - "fetch", - "http", - ), - ]; - - for (error, category, reason) in cases { - let diagnostic = attestation_failure_diagnostic(&error); - assert_eq!( - diagnostic, - AttestationFailureDiagnostic { category, reason } - ); - let rendered = format!("{diagnostic:?}"); - for forbidden in [ - "Bearer", - "diagnostic-secret", - "private.invalid", - "forged_log", - ] { - assert!(!rendered.contains(forbidden)); - } - } - } - #[test] fn expiry_during_ambiguous_execute_never_makes_the_request_replay_safe() { for verified_state_current in [true, false] { let (error, recover) = classify_post_execute_failure( - false, + ExecuteFailure::Ambiguous("synthetic connection reset after POST".to_owned()), verified_state_current, - "synthetic connection reset after POST".to_owned(), ); assert!(matches!(error, ProviderRequestError::Send(_))); assert_eq!(recover, !verified_state_current); } - let (error, _) = - classify_post_execute_failure(true, false, "synthetic TLS setup failure".to_owned()); + let (error, _) = classify_post_execute_failure( + ExecuteFailure::Unsent("synthetic TLS setup failure".to_owned()), + false, + ); assert!(matches!(error, ProviderRequestError::Connect(_))); + let (error, recover) = + classify_post_execute_failure(ExecuteFailure::Refused("synthetic refusal"), true); + assert!(matches!(error, ProviderRequestError::Build(_))); + assert!(!recover); + } + + #[test] + fn renewal_starts_an_hour_before_expiry_and_paces_its_retries() { + let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000); + let hours = |count: u64| Duration::from_secs(count * 60 * 60); + + // Far from the deadline: wait until the lead time. + assert_eq!(renewal_wait(now, now + hours(48), false), Some(hours(47))); + // Inside the lead time: renew at once, the first time. + assert_eq!( + renewal_wait(now, now + Duration::from_secs(600), false), + Some(Duration::ZERO) + ); + // A renewal that did not move the deadline is not repeated in a loop. + assert_eq!( + renewal_wait(now, now + Duration::from_secs(600), true), + Some(ATTESTATION_RENEWAL_RETRY) + ); + assert_eq!(renewal_wait(now, now + hours(48), true), Some(hours(47))); + // Expired evidence is not renewed in place; initialization replaces it. + assert_eq!(renewal_wait(now, now, false), None); + assert_eq!(renewal_wait(now, now - Duration::from_secs(1), true), None); } #[test] fn populated_noncurrent_slot_is_unavailable_and_can_claim_recovery() { - // The fork separately exercises actual verified-client expiration. + // The SDK separately exercises actual verified-client expiration. // This checks the backend slot selection used by snapshot(): presence // of an Arc alone must not make expired state ready or block recovery. let current = Arc::new(AtomicBool::new(true)); @@ -1707,9 +1638,10 @@ mod tests { .unwrap() .push((instance, host, format!("{policy:?}"), key)); Box::pin(async { - Err(tinfoil::Error::Configuration( - "injected verifier failure".to_owned(), - )) + Err(AttestationFailureDiagnostic { + category: "configuration", + reason: "injected_verifier_failure", + }) }) })); // The same immutable target is used for initialization and refresh. @@ -1741,7 +1673,7 @@ mod tests { #[tokio::test] async fn maple_readiness_and_recovery_are_independent_between_guests() { let pending = Arc::new(SecureTinfoilTransport { - api_key: "dedicated-test-key".to_owned(), + api_key: "dedicated-test-key".into(), target: direct_target_for(MapleInstanceId::I01), client_factory: None, client: RwLock::new(SecureClientSlot { @@ -1754,7 +1686,7 @@ mod tests { let ready_transport = TinfoilTransport::Plain { client: test_http_client().unwrap(), base_url: "http://127.0.0.1:9".to_owned(), - api_key: "dedicated-test-key".to_owned(), + api_key: "dedicated-test-key".into(), }; let mut client = ProviderClient::for_test("http://127.0.0.1:9".to_owned()).unwrap(); client.maple = BTreeMap::from([ @@ -1816,7 +1748,7 @@ mod tests { TinfoilTransport::Plain { client: test_http_client().unwrap(), base_url: format!("http://{address}"), - api_key: "dedicated-test-key".to_owned(), + api_key: "dedicated-test-key".into(), }, ); let request = || { @@ -1950,9 +1882,9 @@ mod tests { let first = observed.fetch_add(1, Ordering::SeqCst) == 0; Box::pin(async move { if first { - Err(tinfoil::Error::MeasurementMismatch { - expected: "approved-measurement".to_owned(), - actual: "unapproved-measurement".to_owned(), + Err(AttestationFailureDiagnostic { + category: "attestation", + reason: "release_not_approved", }) } else { std::future::pending().await @@ -2054,7 +1986,7 @@ mod tests { TinfoilTransport::Plain { client: test_http_client().unwrap(), base_url: format!("http://{address}"), - api_key: "dedicated-test-key".to_owned(), + api_key: "dedicated-test-key".into(), }, ); captures.insert(instance, (address, capture_rx)); @@ -2120,7 +2052,7 @@ mod tests { fn uninitialized_secure_transport() -> Arc { Arc::new(SecureTinfoilTransport { - api_key: "unused-test-key".to_string(), + api_key: "unused-test-key".into(), target: AttestationTarget::SharedRouter, client_factory: None, client: RwLock::new(SecureClientSlot { @@ -2906,26 +2838,11 @@ mod tests { .collect(); model_ids.sort_unstable(); assert_eq!(models["object"], "list"); - assert_eq!( - model_ids, - [ - "doc-upload", - "gemma4-31b", - "gpt-oss-120b", - "gpt-oss-safeguard-120b", - "kimi-k2-6", - "llama3-3-70b", - "nomic-embed-text", - "qwen3-tts", - "voxtral-mini-4b-realtime", - "voxtral-small-24b", - "voxtral-tts", - "websearch", - "whisper-large-v3-turbo", - ] - ); + // Tinfoil's catalog changes without notice; this boundary only needs + // the model that the completion requests below use. + assert!(model_ids.contains(&"gpt-oss-120b")); - let completion_body = br#"{"model":"gpt-oss-120b","messages":[{"role":"user","content":"Reply with exactly: parity-ok"}],"temperature":0,"max_tokens":32,"stream":false}"#.to_vec(); + let completion_body = br#"{"model":"gpt-oss-120b","messages":[{"role":"user","content":"Reply with exactly: parity-ok"}],"temperature":0,"max_tokens":512,"stream":false}"#.to_vec(); let completion = client .send( &provider, @@ -2956,7 +2873,7 @@ mod tests { assert!(completion["usage"]["prompt_tokens"].is_number()); assert!(completion["usage"]["completion_tokens"].is_number()); - let stream_body = br#"{"model":"gpt-oss-120b","messages":[{"role":"user","content":"Reply with exactly: parity-stream-ok"}],"temperature":0,"max_tokens":32,"stream":true,"stream_options":{"include_usage":true}}"#.to_vec(); + let stream_body = br#"{"model":"gpt-oss-120b","messages":[{"role":"user","content":"Reply with exactly: parity-stream-ok"}],"temperature":0,"max_tokens":512,"stream":true,"stream_options":{"include_usage":true}}"#.to_vec(); let stream = client .send( &provider, @@ -3020,7 +2937,7 @@ mod tests { .unwrap_or("unknown"); let manifest = json!({ "captured_at_unix_seconds": captured_at_unix_seconds, - "implementation": "tinfoil-rs v0.2.0 (in-process)", + "implementation": "tinfoil-rs v0.3.0-rc.4 (in-process)", "revision": revision, "working_tree": working_tree_status, "credential_label": credential_label, @@ -3076,4 +2993,104 @@ mod tests { serde_json::to_vec_pretty(&manifest).unwrap(), ); } + + /// Live direct-node attestation through the production transport: each + /// guest verifies against its compiled release policy, then serves models, + /// one completion and one stream over the pinned connection. + #[tokio::test] + #[ignore = "requires the live Maple inference credential and network access"] + async fn live_maple_guests_attest_and_complete_through_the_direct_transport() { + let api_key = std::env::var("MAPLE_INFERENCE_API_KEY").expect("MAPLE_INFERENCE_API_KEY"); + // The shared transport is not used here; its key is never sent. + let client = ProviderClient::new("unused-shared-key".to_owned()) + .await + .unwrap() + .with_maple_api_key(Some(api_key)) + .unwrap(); + let readiness = client.maple_readiness(); + + for instance in MapleInstanceId::ALL { + let provider = maple_proxy_for(instance); + let deadline = tokio::time::Instant::now() + Duration::from_secs(60); + while !readiness.is_ready(instance) { + assert!( + tokio::time::Instant::now() < deadline, + "{instance:?} did not attest within the deadline" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } + + let models = client + .send( + &provider, + ProviderRequest::new(Method::GET, "/v1/models", Duration::from_secs(30)), + ) + .await + .unwrap(); + assert_eq!(models.status_code(), 200); + let models: serde_json::Value = + serde_json::from_slice(&models.bytes().await.unwrap()).unwrap(); + let model = models["data"][0]["id"].as_str().expect("served model id"); + + let completion = client + .send( + &provider, + ProviderRequest::new( + Method::POST, + "/v1/chat/completions", + Duration::from_secs(120), + ) + .content_type("application/json") + .body( + json!({ + "model": model, + "messages": [{"role": "user", "content": "Reply with the single word: pong"}], + "max_tokens": 64, + }) + .to_string(), + ), + ) + .await + .unwrap(); + assert_eq!(completion.status_code(), 200); + let completion: serde_json::Value = + serde_json::from_slice(&completion.bytes().await.unwrap()).unwrap(); + assert_eq!(completion["object"], "chat.completion"); + assert!(completion["usage"]["completion_tokens"].as_u64().unwrap() > 0); + + let stream = client + .send( + &provider, + ProviderRequest::new( + Method::POST, + "/v1/chat/completions", + Duration::from_secs(120), + ) + .content_type("application/json") + .body( + json!({ + "model": model, + "messages": [{"role": "user", "content": "Reply with the single word: pong"}], + "max_tokens": 64, + "stream": true, + "stream_options": {"include_usage": true}, + }) + .to_string(), + ), + ) + .await + .unwrap(); + assert_eq!(stream.status_code(), 200); + let stream = String::from_utf8(stream.bytes().await.unwrap().to_vec()).unwrap(); + let data_frames: Vec<&str> = stream + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .collect(); + assert_eq!(data_frames.last(), Some(&"[DONE]")); + assert!(data_frames.len() > 2); + assert!(data_frames + .iter() + .any(|frame| frame.contains("\"usage\":{"))); + } + } } diff --git a/services/opensecret/src/provider_client/attested.rs b/services/opensecret/src/provider_client/attested.rs new file mode 100644 index 000000000..88c8c4eee --- /dev/null +++ b/services/opensecret/src/provider_client/attested.rs @@ -0,0 +1,288 @@ +//! The attested Tinfoil clients behind the provider transport. +//! +//! Everything that names an SDK type lives here, so the transport above deals +//! only in verified clients, finite failure labels and send outcomes. + +use crate::maple_inference::{MaplePolicy, ReleaseNotApproved}; +use std::error::Error as StdError; +use std::time::SystemTime; +use tinfoil::verifier::{Error as VerifierError, Layer}; +use tinfoil::{EnclaveHttpClient, ErrorKind, RouterHttpClient, Trust}; + +/// Why attestation failed, as finite labels that are safe to log. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct AttestationFailureDiagnostic { + pub(super) category: &'static str, + pub(super) reason: &'static str, +} + +impl AttestationFailureDiagnostic { + pub(super) fn is_attestation(&self) -> bool { + self.category == "attestation" + } + + pub(super) fn is_network(&self) -> bool { + self.category == "network" + } +} + +fn find_in_chain<'a, T: StdError + 'static>(error: &'a (dyn StdError + 'static)) -> Option<&'a T> { + let mut next = Some(error); + while let Some(error) = next { + if let Some(found) = error.downcast_ref::() { + return Some(found); + } + next = error.source(); + } + None +} + +pub(super) fn attestation_failure_diagnostic( + error: &tinfoil::Error, +) -> AttestationFailureDiagnostic { + // SDK errors can contain arbitrary response text, URLs, and document + // contents. Log only finite labels derived from typed causes, never their + // payloads. + let category = match error.kind() { + ErrorKind::Configuration => "configuration", + ErrorKind::Network => "network", + ErrorKind::Attestation => "attestation", + _ => "other", + }; + let reason = if error.is_timeout() { + "timeout" + } else if find_in_chain::(error).is_some() { + "release_not_approved" + } else if let Some(verifier) = find_in_chain::(error) { + match verifier { + VerifierError::Verification(rejected) => match rejected.layer() { + Layer::Envelope => "envelope", + Layer::Provenance => "provenance", + Layer::Quote => "quote", + Layer::Policy => "policy", + _ => "verification", + }, + VerifierError::Usage(_) => "verifier_usage", + _ => "verifier", + } + } else if let Some(http) = find_in_chain::(error) { + if http.is_connect() { + "http_connect" + } else if http.is_timeout() { + "http_timeout" + } else if http.is_status() { + "http_status" + } else { + "http" + } + } else { + category + }; + AttestationFailureDiagnostic { category, reason } +} + +/// What a failed send proves about the request. +#[derive(Debug)] +pub(super) enum ExecuteFailure { + /// The client refused the request before any I/O. Retrying cannot help. + Refused(&'static str), + /// No request bytes reached the enclave: the connection was never + /// established, or the peer did not hold the attested key. In the TLS + /// transport mode an attestation error always precedes the request. + Unsent(String), + /// The request may have been accepted. It must not be replayed. + Ambiguous(String), +} + +fn classify_execute_error(error: &tinfoil::Error) -> ExecuteFailure { + match error.kind() { + ErrorKind::Configuration => ExecuteFailure::Refused("request refused by attested client"), + ErrorKind::Attestation => ExecuteFailure::Unsent(format!( + "attestation failed before the request was sent: {}", + attestation_failure_diagnostic(error).reason + )), + // The SDK strips the URL from the transport error it wraps. + _ if find_in_chain::(error).is_some_and(reqwest::Error::is_connect) => { + ExecuteFailure::Unsent(error.to_string()) + } + _ => ExecuteFailure::Ambiguous(error.to_string()), + } +} + +/// A client that exists has been verified. It pins every connection to the +/// attested TLS key and refuses any other origin. +#[derive(Clone)] +pub(super) enum AttestedClient { + /// Tinfoil's shared router, chosen by discovery. + Router(RouterHttpClient), + /// One dedicated guest that the caller names. + Enclave(EnclaveHttpClient), +} + +impl AttestedClient { + /// Discover and verify Tinfoil's shared router. + pub(super) async fn connect_router() -> Result { + RouterHttpClient::connect() + .await + .map(Self::Router) + .map_err(|error| attestation_failure_diagnostic(&error)) + } + + /// Verify the guest at `host` against the approved releases. The verifier + /// proves a signed release of one repository at a time; the policy check + /// then runs on this and on every later verification of the same client, + /// so a key rotation can never move it to an unapproved release. + pub(super) async fn connect_maple( + host: &str, + policy: &MaplePolicy, + ) -> Result { + let mut failure = AttestationFailureDiagnostic { + category: "configuration", + reason: "no_approved_release", + }; + for repo in policy.repos() { + let approved = policy.clone(); + let connected = EnclaveHttpClient::builder(host, Trust::repo(repo)) + .verification_check(move |verified| Ok(approved.check(verified)?)) + .connect() + .await; + match connected { + Ok(client) => return Ok(Self::Enclave(client)), + Err(error) => failure = attestation_failure_diagnostic(&error), + } + } + Err(failure) + } + + /// The host of the verified enclave. + pub(super) fn enclave(&self) -> &str { + match self { + Self::Router(client) => client.enclave(), + Self::Enclave(client) => client.enclave(), + } + } + + /// When the verification that requests are bound to stops authorizing + /// them. `None` once it has expired or the SDK has discarded it, which it + /// does when the enclave rejects the attested key or a later verification + /// fails attestation. + pub(super) fn freshness_expires_at(&self) -> Option { + match self { + Self::Router(client) => client.current_verification(), + Self::Enclave(client) => client.current_verification(), + } + .and_then(|report| report.verified_facts()?.freshness_expires_at()) + } + + /// Whether the current verification still authorizes requests. Evidence + /// without a deadline never does. + pub(super) fn is_fresh(&self) -> bool { + self.freshness_expires_at() + .is_some_and(|deadline| SystemTime::now() < deadline) + } + + /// Verify again without sending a request. A network failure keeps the + /// current verification until its own deadline; an attestation failure + /// discards it, and the client is then no longer fresh. + pub(super) async fn reverify(&self) -> Result<(), AttestationFailureDiagnostic> { + match self { + Self::Router(client) => client.reverify().await, + Self::Enclave(client) => client.reverify().await, + } + .map(|_| ()) + .map_err(|error| attestation_failure_diagnostic(&error)) + } + + pub(super) async fn execute( + &self, + request: reqwest::Request, + ) -> Result { + match self { + Self::Router(client) => client.execute(request).await, + Self::Enclave(client) => client.execute(request).await, + } + .map_err(|error| classify_execute_error(&error)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FORBIDDEN: [&str; 4] = [ + "Bearer", + "diagnostic-secret", + "private.invalid", + "forged_log", + ]; + + fn assert_no_payload(rendered: &str) { + for forbidden in FORBIDDEN { + assert!(!rendered.contains(forbidden), "{rendered}"); + } + } + + // The SDK's errors cannot be constructed from outside it, so each case + // provokes a real one. None of them leaves the process. + #[tokio::test] + async fn configuration_failures_are_labelled_without_payloads() { + let sensitive = "Bearer diagnostic-secret https://private.invalid/?token=diagnostic-secret\nforged_log=true"; + let error = EnclaveHttpClient::builder(sensitive, Trust::repo("owner/name")) + .connect() + .await + .expect_err("a URL with credentials is not a host"); + let diagnostic = attestation_failure_diagnostic(&error); + assert_eq!( + diagnostic, + AttestationFailureDiagnostic { + category: "configuration", + reason: "configuration", + } + ); + assert!(!diagnostic.is_attestation() && !diagnostic.is_network()); + assert_no_payload(&format!("{diagnostic:?}")); + match classify_execute_error(&error) { + ExecuteFailure::Refused(label) => assert_no_payload(label), + other => panic!("a configuration error must not be retried: {other:?}"), + } + } + + #[tokio::test] + async fn unreachable_guest_is_a_network_failure_that_proves_nothing_was_sent() { + crate::http_client::install_ring_crypto_provider().unwrap(); + // Bind and drop to get a loopback port that refuses connections. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + + let policy = + crate::maple_inference::endpoint(crate::provider_registry::MapleInstanceId::I01) + .direct_policy() + .unwrap() + .unwrap(); + let diagnostic = + match AttestedClient::connect_maple(&format!("127.0.0.1:{port}"), &policy).await { + Ok(_) => panic!("nothing listens on the port"), + Err(diagnostic) => diagnostic, + }; + assert_eq!(diagnostic.category, "network"); + assert_eq!(diagnostic.reason, "http_connect"); + assert!(diagnostic.is_network() && !diagnostic.is_attestation()); + } + + #[tokio::test] + async fn a_policy_without_releases_never_reaches_the_network() { + // `direct_policy` returns no policy for an unconfigured guest; this + // guards the constructor itself. + let empty = crate::maple_inference::empty_policy_for_test(); + assert_eq!( + AttestedClient::connect_maple("i01.tfinf.maple.ai", &empty) + .await + .err(), + Some(AttestationFailureDiagnostic { + category: "configuration", + reason: "no_approved_release", + }) + ); + } +}