From 92c26d84d5e8fb52f775c5354a8a06711ee83114 Mon Sep 17 00:00:00 2001 From: Flavio Carvalho Date: Mon, 19 Oct 2026 16:47:04 -0400 Subject: [PATCH] feat(llm-client): sign requests with AWS SigV4 Signed-off-by: Flavio Carvalho --- Cargo.lock | 490 ++++++++++++ Cargo.toml | 6 + crates/libsy-llm-client/Cargo.toml | 7 + crates/libsy-llm-client/src/backend.rs | 18 + crates/libsy-llm-client/src/client.rs | 156 +++- crates/libsy-llm-client/src/lib.rs | 1 + crates/libsy-llm-client/src/run.rs | 6 + crates/libsy-llm-client/src/sigv4.rs | 733 ++++++++++++++++++ .../libsy-llm-client/tests/fallback_credit.rs | 1 + crates/switchyard-runner/src/config.rs | 86 +- crates/switchyard-server/tests/server.rs | 1 + docs/reference/toml_schema.md | 4 +- examples/bedrock-sigv4.toml | 57 ++ 13 files changed, 1551 insertions(+), 15 deletions(-) create mode 100644 crates/libsy-llm-client/src/sigv4.rs create mode 100644 examples/bedrock-sigv4.toml diff --git a/Cargo.lock b/Cargo.lock index 8e0eb0a542..19cd8c248f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -163,6 +163,44 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-config" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939e256cfe0ed68e96d32f194339d88210d5c10685cff0787400158f852c6819" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-sdk-sts", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http", + "time", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "aws-credential-types" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "576e8da35751dc85409ec1cd15999f692c277a1fbe9336780fe6f15e49dd637d" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "zeroize", +] + [[package]] name = "aws-lc-rs" version = "1.17.1" @@ -186,6 +224,275 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "aws-runtime" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a" +dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "bytes-utils", + "fastrand", + "http", + "http-body", + "percent-encoding", + "pin-project-lite", + "tracing", + "uuid", +] + +[[package]] +name = "aws-sdk-sts" +version = "1.122.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a10491638d9e560db90c484dbc77d73b8ad202780cdc9b9e92180603acb07ada" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-query", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "fastrand", + "http", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sigv4" +version = "1.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d3d48355cb86b15ccbb38b8bc6b87500c824ee4ed8cbc10a961b435242b5e16" +dependencies = [ + "aws-credential-types", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "form_urlencoded", + "hex", + "hmac", + "http", + "percent-encoding", + "sha2", + "time", + "tracing", +] + +[[package]] +name = "aws-smithy-async" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "aws-smithy-http" +version = "0.64.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8960956e0ee0ca3f3161e62913a61bc65a7ef638ca3ef1d4c7159f8443e398" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "bytes-utils", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "percent-encoding", + "pin-project-lite", + "tracing", +] + +[[package]] +name = "aws-smithy-http-client" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeca69f65362f7375891008ea525fd440ad6db1836458ac188c87b126804114e" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "h2", + "http", + "hyper", + "hyper-rustls", + "hyper-util", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower", + "tracing", +] + +[[package]] +name = "aws-smithy-json" +version = "0.65.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f6835fb38bc6fc8c91e584b0366eb4ff595e5c485134dbf4f0bdeaa18856666" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", +] + +[[package]] +name = "aws-smithy-observability" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c" +dependencies = [ + "aws-smithy-runtime-api", +] + +[[package]] +name = "aws-smithy-query" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165f6265342a313ad6f7a1ac17a0cdba30c522039d3f41d8d6871ce8a2b34ecd" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-smithy-xml", + "urlencoding", +] + +[[package]] +name = "aws-smithy-runtime" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cef0c41e8ca40f74f68ed8ee4d1ddbde12bb847b95ef9b3c025681ddfae58a" +dependencies = [ + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-http-client", + "aws-smithy-observability", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "bytes", + "fastrand", + "http", + "http-body", + "http-body-util", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "aws-smithy-runtime-api" +version = "1.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06788004dea79018413f381891da6dcca23196acd79c4d51b767fbdacc76eae4" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api-macros", + "aws-smithy-types", + "bytes", + "http", + "pin-project-lite", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "aws-smithy-runtime-api-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce237f890a2283c9b328955c3b0918d2d5bf66a1cb6ceccd36a0047246fbc6e6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "aws-smithy-schema" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec8dae1015a6d959a5faf86fbdf77486cfe19e4ccb6ee009d8a46efc45028a4" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "http", +] + +[[package]] +name = "aws-smithy-types" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55752025c39c0e094962fd73f1c57014b191f678612e517f219468e575af9822" +dependencies = [ + "base64-simd", + "bytes", + "bytes-utils", + "http", + "http-body", + "http-body-util", + "itoa", + "num-integer", + "pin-project-lite", + "ryu", + "serde", + "time", +] + +[[package]] +name = "aws-smithy-xml" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6581618a2fd006159016d1c36881d94d61b4a017f4a8d631310875e18252413" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "xmlparser", +] + +[[package]] +name = "aws-types" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba0d970d3947bb064d2ae1d823efa186c1dbde88f88afa8f6549946e5d8deee" +dependencies = [ + "aws-credential-types", + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "rustc_version", + "tracing", +] + [[package]] name = "axum" version = "0.8.9" @@ -266,6 +573,16 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -303,6 +620,15 @@ dependencies = [ "cpufeatures", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "borrow-or-share" version = "0.2.4" @@ -339,6 +665,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "bytes-utils" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" +dependencies = [ + "bytes", + "either", +] + [[package]] name = "cc" version = "1.2.67" @@ -433,6 +769,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "color_quant" version = "1.1.0" @@ -455,6 +797,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -504,12 +852,30 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "ctor" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -534,12 +900,30 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "diff" version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", +] + [[package]] name = "displaydoc" version = "0.2.6" @@ -909,6 +1293,21 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.4.2" @@ -960,6 +1359,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.10.1" @@ -992,6 +1400,7 @@ dependencies = [ "hyper", "hyper-util", "rustls", + "rustls-native-certs", "tokio", "tokio-rustls", "tower-service", @@ -1610,6 +2019,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-integer" version = "0.1.46" @@ -1856,6 +2271,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -2275,6 +2696,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.11" @@ -2619,6 +3046,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -2811,6 +3249,10 @@ name = "switchyard-llm-client" version = "0.4.0" dependencies = [ "async-trait", + "aws-config", + "aws-credential-types", + "aws-sigv4", + "aws-smithy-async", "base64", "dynamo-multimodal", "futures", @@ -3146,6 +3588,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.3" @@ -3478,6 +3950,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -3514,6 +3992,12 @@ dependencies = [ "serde", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -3850,6 +4334,12 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + [[package]] name = "xxhash-rust" version = "0.8.19" diff --git a/Cargo.toml b/Cargo.toml index 9df5aa9535..5400e1d05d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,12 @@ rust-version = "1.96.1" [workspace.dependencies] async-stream = "0.3" async-trait = "0.1.92" +# SigV4 signing for Amazon Bedrock. aws-config needs `rt-tokio`: its credential providers +# panic when they retry without an async sleep. +aws-config = { version = "1", default-features = false, features = ["rustls", "rt-tokio", "behavior-version-latest"] } +aws-credential-types = "1" +aws-sigv4 = { version = "1", default-features = false, features = ["http1", "sign-http"] } +aws-smithy-async = "1" axum = "0.8" base64 = "0.22" clap = "4" diff --git a/crates/libsy-llm-client/Cargo.toml b/crates/libsy-llm-client/Cargo.toml index 77ce908978..087163e9ee 100644 --- a/crates/libsy-llm-client/Cargo.toml +++ b/crates/libsy-llm-client/Cargo.toml @@ -29,6 +29,9 @@ switchyard-libsy.workspace = true switchyard-observability.workspace = true switchyard-protocol.workspace = true switchyard-translation.workspace = true +aws-config.workspace = true +aws-credential-types.workspace = true +aws-sigv4.workspace = true reqwest.workspace = true async-trait.workspace = true futures.workspace = true @@ -45,6 +48,10 @@ tracing-opentelemetry.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["test-util"] } +# `test-util` provides `Credentials::for_tests_with_session_token`. +aws-credential-types = { workspace = true, features = ["test-util"] } +# Checks that a default async sleep exists for the credential providers. +aws-smithy-async.workspace = true # SDK + in-memory exporter to assert what the observability layer records. opentelemetry_sdk = { workspace = true, default-features = true, features = ["metrics", "testing", "trace"] } tracing-subscriber.workspace = true diff --git a/crates/libsy-llm-client/src/backend.rs b/crates/libsy-llm-client/src/backend.rs index bed7e0a7c2..37a5360441 100644 --- a/crates/libsy-llm-client/src/backend.rs +++ b/crates/libsy-llm-client/src/backend.rs @@ -88,6 +88,10 @@ pub struct HttpBackendConfig { /// Deadline for one complete response, including retries, retry delays, and stream reads. /// `None` leaves the wait unbounded. pub timeout: Option, + /// Sign every request with AWS SigV4 instead of sending a configured key, for example to + /// call Amazon Bedrock with IAM credentials. Cannot be combined with `api_key` or + /// `forward_auth`. + pub sigv4: Option, } impl fmt::Debug for HttpBackendConfig { @@ -276,6 +280,19 @@ impl Backend { } } + /// The SigV4 settings for this backend, when it signs rather than sends a key. + pub(crate) fn sigv4(&self) -> Option<&crate::sigv4::SigV4Settings> { + self.config().sigv4.as_ref() + } + + /// Checks the SigV4 settings of a backend that signs. Other backends always pass. + pub(crate) fn validate_sigv4(&self, model_name: &str) -> Result<()> { + match self.sigv4() { + Some(_) => crate::sigv4::validate(self.config(), model_name), + None => Ok(()), + } + } + /// Applies only the caller credential accepted by this provider. pub(crate) fn apply_forwarded_auth( &self, @@ -458,6 +475,7 @@ mod tests { max_retries: 0, failure_cooldown: Duration::ZERO, timeout: None, + sigv4: None, } } diff --git a/crates/libsy-llm-client/src/client.rs b/crates/libsy-llm-client/src/client.rs index 00e6f77b01..25d3e35c99 100644 --- a/crates/libsy-llm-client/src/client.rs +++ b/crates/libsy-llm-client/src/client.rs @@ -164,6 +164,9 @@ pub struct TranslatingLlmClient { cooldown_epoch: Instant, // Milliseconds since cooldown_epoch. Each atomic is independent, so relaxed ordering suffices. unavailable_until: HashMap, + // One provider chain and credential cache per client, loaded on the first signed call and + // shared by its backends. + credentials: crate::sigv4::CredentialSource, } impl TranslatingLlmClient { @@ -198,6 +201,7 @@ impl TranslatingLlmClient { .chain(config.other_backends.iter().flatten()) { backend.validate_configured_headers(&config.target_name)?; + backend.validate_sigv4(&config.target_name)?; #[cfg(feature = "media")] if let Some(media) = &config.media { media.validate(backend.wire_format()).map_err(media_error)?; @@ -218,7 +222,7 @@ impl TranslatingLlmClient { }; let client = build_client(reqwest::Client::builder())?; // A redirect could move provider-specific headers to another origin. - // Forwarded credentials are sent only to the configured URL. + // Forwarded credentials and SigV4-signed requests are sent only to the configured URL. let forward_auth_client = build_client(reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()))?; @@ -231,6 +235,7 @@ impl TranslatingLlmClient { is_rate_limit_cooldown_enabled: true, cooldown_epoch: Instant::now(), unavailable_until, + credentials: crate::sigv4::CredentialSource::default(), }) } @@ -303,9 +308,14 @@ impl TranslatingLlmClient { let builder = self.forward_auth_client.get(url).timeout(timeout); let builder = apply_extra_headers(builder, backend); - let response = backend + let request = backend .apply_auth(builder) - .send() + .build() + .map_err(convert_reqwest_error)?; + let request = self.sign_if_required(request, backend).await?; + let response = self + .forward_auth_client + .execute(request) .await .map_err(convert_reqwest_error)? .error_for_status() @@ -623,6 +633,18 @@ impl TranslatingLlmClient { } } + // Signs the request when the backend uses SigV4. Other requests pass through unchanged. + async fn sign_if_required( + &self, + mut request: reqwest::Request, + backend: &Backend, + ) -> std::result::Result { + if let Some(settings) = backend.sigv4() { + crate::sigv4::sign_request(&mut request, settings, &self.credentials).await?; + } + Ok(request) + } + // Performs one HTTP attempt and retains the retry metadata alongside any error. async fn send_once( &self, @@ -633,7 +655,7 @@ impl TranslatingLlmClient { target_name: &ModelId, streaming: bool, ) -> std::result::Result { - let client = if backend.is_forwarding_auth() { + let client = if backend.is_forwarding_auth() || backend.sigv4().is_some() { &self.forward_auth_client } else { &self.client @@ -644,15 +666,35 @@ impl TranslatingLlmClient { let builder = apply_extra_headers(builder, backend); let builder = backend.apply_auth(builder); - let response = match async { - let request = builder.build()?; - if let Some(body) = request.body().and_then(reqwest::Body::as_bytes) { - crate::payload_capture::record("request", || String::from_utf8_lossy(body)); + // SigV4 signs the built request, because the signature covers the body. Every auth + // mode builds the request here and sends it with `execute`. + let request = match builder.build() { + Ok(request) => request, + Err(error) => { + metrics::record_upstream_attempt(None); + return Err(AttemptFailure { + error: convert_reqwest_error(error), + status: None, + retry_after: None, + }); } - client.execute(request).await + }; + let request = match self.sign_if_required(request, backend).await { + Ok(request) => request, + Err(error) => { + metrics::record_upstream_attempt(None); + return Err(AttemptFailure { + error, + status: None, + retry_after: None, + }); + } + }; + if let Some(body) = request.body().and_then(reqwest::Body::as_bytes) { + crate::payload_capture::record("request", || String::from_utf8_lossy(body)); } - .await - { + + let response = match client.execute(request).await { Ok(response) => response, Err(error) => { metrics::record_upstream_attempt(None); @@ -1596,6 +1638,7 @@ mod tests { max_retries: 0, failure_cooldown: Duration::ZERO, timeout: None, + sigv4: None, } } @@ -3831,6 +3874,97 @@ mod tests { Ok(()) } + // A library caller can set any combination of fields, so the check runs where the client + // is built, not only in the runner. + #[test] + fn sigv4_settings_are_checked_when_the_client_is_built() { + let backend_config = HttpBackendConfig { + sigv4: Some(crate::sigv4::SigV4Settings::new( + crate::sigv4::DEFAULT_SERVICE, + None, + )), + ..config("https://bedrock-runtime.us-east-1.amazonaws.com/anthropic") + }; + let Err(error) = TranslatingLlmClient::new(&[ModelConfig::new( + "claude", + Backend::Anthropic(backend_config), + None, + )]) else { + panic!("sigv4 with an api_key must be refused"); + }; + assert!(error.to_string().contains("one auth mode"), "{error}"); + } + + // reqwest drops `Authorization` on a cross-origin redirect but keeps + // `x-amz-security-token` and, on a 307, the body. + #[tokio::test] + async fn sigv4_requests_do_not_follow_redirects() + -> std::result::Result<(), Box> { + let other_origin = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "1", "model": "gpt", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}], + "usage": {} + }))) + .mount(&other_origin) + .await; + let upstream = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(307).insert_header( + "location", + format!("{}/v1/chat/completions", other_origin.uri()), + )) + .mount(&upstream) + .await; + + let backend_config = HttpBackendConfig { + api_key: None, + sigv4: Some(crate::sigv4::SigV4Settings::new( + crate::sigv4::DEFAULT_SERVICE, + Some("us-east-1".to_string()), + )), + ..config(&format!("{}/v1", upstream.uri())) + }; + let mut client = TranslatingLlmClient::new(&[ModelConfig::new( + "gpt", + Backend::OpenAiChat(backend_config), + None, + )])?; + client.credentials = crate::sigv4::CredentialSource::for_tests( + aws_credential_types::Credentials::for_tests_with_session_token(), + Some("us-east-1"), + ); + + let result = client + .call_rewrite_model(request_for(Some("gpt"), false), None) + .await; + assert!( + result.is_err(), + "a redirect must not complete a signed call" + ); + let signed = upstream + .received_requests() + .await + .ok_or("request recording should be enabled")?; + assert!( + signed + .first() + .ok_or("expected one upstream request")? + .headers + .contains_key("x-amz-security-token") + ); + let redirected = other_origin + .received_requests() + .await + .ok_or("request recording should be enabled")?; + assert!( + redirected.is_empty(), + "the signed request followed a redirect" + ); + Ok(()) + } + #[tokio::test] async fn forward_auth_preserves_anthropic_headers_and_redacts_errors() -> std::result::Result<(), Box> { diff --git a/crates/libsy-llm-client/src/lib.rs b/crates/libsy-llm-client/src/lib.rs index 26bb695a8a..3e80dc4e70 100644 --- a/crates/libsy-llm-client/src/lib.rs +++ b/crates/libsy-llm-client/src/lib.rs @@ -33,6 +33,7 @@ mod openai_decisions; mod payload_capture; mod responses_reasoning; pub mod run; +pub mod sigv4; mod system_one; pub use backend::{Backend, DEFAULT_MAX_RETRIES, HttpBackendConfig}; diff --git a/crates/libsy-llm-client/src/run.rs b/crates/libsy-llm-client/src/run.rs index 078c71632e..7acd266906 100644 --- a/crates/libsy-llm-client/src/run.rs +++ b/crates/libsy-llm-client/src/run.rs @@ -1876,6 +1876,7 @@ mod tests { max_retries: 0, failure_cooldown: std::time::Duration::ZERO, timeout: None, + sigv4: None, }; let backend = if responses { Backend::OpenAiResponses(config) @@ -2023,6 +2024,7 @@ mod tests { max_retries: 0, failure_cooldown: std::time::Duration::ZERO, timeout: None, + sigv4: None, }), None, )]) @@ -2470,6 +2472,7 @@ mod tests { max_retries: 0, failure_cooldown: std::time::Duration::ZERO, timeout: None, + sigv4: None, }); let client = Arc::new( TranslatingLlmClient::new(&[ @@ -2864,6 +2867,7 @@ mod tests { max_retries: 2, failure_cooldown: cooldown, timeout: None, + sigv4: None, }) }; TranslatingLlmClient::new(&[ @@ -2937,6 +2941,7 @@ mod tests { max_retries: 0, failure_cooldown: std::time::Duration::ZERO, timeout: None, + sigv4: None, }) }; let client = Arc::new( @@ -3037,6 +3042,7 @@ mod tests { max_retries: 0, failure_cooldown: std::time::Duration::ZERO, timeout: None, + sigv4: None, }) }; let client = Arc::new( diff --git a/crates/libsy-llm-client/src/sigv4.rs b/crates/libsy-llm-client/src/sigv4.rs new file mode 100644 index 0000000000..add393c078 --- /dev/null +++ b/crates/libsy-llm-client/src/sigv4.rs @@ -0,0 +1,733 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! AWS SigV4 request signing, used to call Amazon Bedrock with IAM credentials. +//! +//! Credentials come from the AWS credential provider chain and are fetched again before they +//! expire, so a long-running router needs no token refresh or restart. +//! +//! The signature covers the method, path, query, host, signed headers and a hash of the body, +//! so signing applies to a built `reqwest::Request`, not to a `RequestBuilder`. The caller +//! sends the signed request with `Client::execute`. Streamed responses need nothing extra, +//! because the request body is complete before the call. + +use std::time::{Duration, SystemTime}; + +use aws_config::{BehaviorVersion, SdkConfig}; +use aws_credential_types::Credentials; +use aws_credential_types::provider::error::CredentialsError; +use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider}; +use aws_sigv4::http_request::{SignableBody, SignableRequest, SigningSettings, sign as sigv4_sign}; +use aws_sigv4::sign::v4; +use tokio::sync::{Mutex, OnceCell}; + +use crate::backend::HttpBackendConfig; +use crate::error::{LlmClientError, Result}; + +/// Default signing service name. +pub const DEFAULT_SERVICE: &str = "bedrock"; + +/// The service and region to sign for. +/// +/// When `region` is unset, the request is signed for the region in its host, such as +/// `us-east-1` in `bedrock-runtime.us-east-1.amazonaws.com`, because AWS rejects a signature +/// for any other region. A host outside AWS, or one without a region, uses the provider +/// chain's region (`AWS_REGION`, the profile, or instance metadata). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SigV4Settings { + pub service: String, + pub region: Option, +} + +impl SigV4Settings { + #[must_use] + pub fn new(service: impl Into, region: Option) -> Self { + Self { + service: service.into(), + region, + } + } +} + +/// The AWS credential provider chain and a cache of its credentials. +/// +/// The chain is loaded on the first signed call, not at config load: loading is async, and a +/// router should start even where no credentials exist yet. The first call then fails with +/// the cause. The same load supplies the fallback region. +/// +/// aws-config's provider chain does not cache credentials (SDK service clients do), so this +/// type caches them. Otherwise every request would read the profile files or call the +/// container endpoint, instance metadata or STS again. +#[derive(Debug, Default)] +pub(crate) struct CredentialSource { + config: OnceCell, + // The last credentials and when to fetch them again. One lock, so one fetch at a time. + cached: Mutex>, +} + +// The timing of the AWS SDK clients' own credential cache (`IdentityCache::lazy`): fetch +// again 10 seconds before credentials expire, and after 15 minutes for credentials that state +// no expiry, such as keys in a profile file that another tool rewrites. +const EXPIRY_BUFFER: Duration = Duration::from_secs(10); +const NO_EXPIRY_LIFETIME: Duration = Duration::from_secs(15 * 60); + +fn refresh_time(expiry: Option, now: SystemTime) -> SystemTime { + match expiry { + Some(expiry) => expiry.checked_sub(EXPIRY_BUFFER).unwrap_or(expiry), + None => now + NO_EXPIRY_LIFETIME, + } +} + +impl CredentialSource { + async fn config(&self) -> &SdkConfig { + self.config + .get_or_init(|| aws_config::load_defaults(BehaviorVersion::latest())) + .await + } + + async fn provider(&self) -> Result { + self.config() + .await + .credentials_provider() + .ok_or_else(|| LlmClientError::Configuration { + message: "sigv4 auth is configured but no AWS credentials provider could be \ + resolved (checked environment, profile and container/instance \ + metadata)" + .to_string(), + }) + } + + async fn credentials(&self) -> Result { + let mut cached = self.cached.lock().await; + let now = SystemTime::now(); + if let Some((credentials, refresh_at)) = cached.as_ref() + && now < *refresh_at + { + return Ok(credentials.clone()); + } + let credentials = self + .provider() + .await? + .provide_credentials() + .await + .map_err(credentials_error)?; + *cached = Some((credentials.clone(), refresh_time(credentials.expiry(), now))); + Ok(credentials) + } + + /// The region the provider chain resolved. Only consulted when neither the client nor + /// the host names one. + async fn chain_region(&self) -> Option { + self.config().await.region().map(ToString::to_string) + } + + // A source that skips the environment: `provider` and `region` stand in for the chain. + #[cfg(test)] + pub(crate) fn for_tests( + provider: impl ProvideCredentials + 'static, + region: Option<&str>, + ) -> Self { + let config = SdkConfig::builder() + .credentials_provider(SharedCredentialsProvider::new(provider)) + .region(region.map(|region| aws_config::Region::new(region.to_string()))) + .build(); + let source = Self::default(); + source.config.set(config).expect("fresh cell"); + source + } +} + +/// Signs `request` in place with SigV4. +/// +/// Returns an error rather than leaving the request unsigned, which the provider would reject +/// with an auth error. +pub(crate) async fn sign_request( + request: &mut reqwest::Request, + settings: &SigV4Settings, + source: &CredentialSource, +) -> Result<()> { + let credentials = source.credentials().await?; + + let host_region = request.url().host_str().and_then(region_from_host); + let region = match (settings.region.clone(), host_region) { + (Some(region), _) => region, + (None, Some(region)) => region.to_string(), + (None, None) => { + source + .chain_region() + .await + .ok_or_else(|| LlmClientError::Configuration { + message: "sigv4 auth needs a region: set it on the llm client, use a \ + base_url whose host names one, or set it in the environment" + .to_string(), + })? + } + }; + + let identity = credentials.into(); + let signing_settings = SigningSettings::default(); + let params = v4::SigningParams::builder() + .identity(&identity) + .region(®ion) + .name(&settings.service) + .time(SystemTime::now()) + .settings(signing_settings) + .build() + .map_err(|error| LlmClientError::Configuration { + message: format!("sigv4 signing params: {error}"), + })?; + + // The signature covers a hash of the body, so the body must be in memory. Upstream + // requests are a GET without a body (`/props`) or buffered JSON. A streaming body is + // refused. + let body_bytes = match request.body() { + None => &[][..], + Some(body) => body + .as_bytes() + .ok_or_else(|| LlmClientError::Configuration { + message: "sigv4 auth cannot sign a streaming request body".to_string(), + })?, + }; + + // SigV4 signs only the headers it lists in `SignedHeaders`, and AWS accepts unsigned + // extra headers. A value that is not visible ASCII cannot be canonicalized, so it is + // sent unsigned rather than failing the request. + let headers: Vec<(&str, &str)> = request + .headers() + .iter() + .filter_map(|(name, value)| value.to_str().ok().map(|value| (name.as_str(), value))) + .collect(); + + let signable = SignableRequest::new( + request.method().as_str(), + request.url().as_str(), + headers.into_iter(), + SignableBody::Bytes(body_bytes), + ) + .map_err(|error| LlmClientError::Configuration { + message: format!("sigv4 signable request: {error}"), + })?; + + let (instructions, _signature) = sigv4_sign(signable, ¶ms.into()) + .map_err(|error| LlmClientError::Configuration { + message: format!("sigv4 signing failed: {error}"), + })? + .into_parts(); + + for (name, value) in instructions.headers() { + let header_name = reqwest::header::HeaderName::try_from(name).map_err(|error| { + LlmClientError::Configuration { + message: format!("sigv4 header name: {error}"), + } + })?; + let mut header_value = reqwest::header::HeaderValue::from_str(value).map_err(|error| { + LlmClientError::Configuration { + message: format!("sigv4 header value: {error}"), + } + })?; + // The signature and the session token stay out of logs, as the other auth modes' + // secrets do. The date and payload hash stay visible. + header_value.set_sensitive( + header_name == reqwest::header::AUTHORIZATION || header_name == "x-amz-security-token", + ); + request.headers_mut().insert(header_name, header_value); + } + Ok(()) +} + +/// Rejects SigV4 settings that could send a signature or another credential to the wrong host. +/// +/// AWS accepts a signed request for about 15 minutes, so anyone who reads one can send it +/// again in that time. Signing keeps the headers it does not set, so a key from another auth +/// mode would be sent along. +pub(crate) fn validate(config: &HttpBackendConfig, model_name: &str) -> Result<()> { + let error = |message: String| LlmClientError::Configuration { + message: format!("model {model_name:?} {message}"), + }; + if config.api_key.is_some() || config.forward_auth { + return Err(error( + "combines sigv4 with api_key or forward_auth; set one auth mode".to_string(), + )); + } + // Plain HTTP stays allowed for loopback, where test servers run. + let url = reqwest::Url::parse(&config.base_url) + .ok() + .filter(|url| url.scheme() == "https" || is_loopback(url)) + .ok_or_else(|| error("needs an https base_url for sigv4".to_string()))?; + if let Some(name) = config.extra_headers.keys().find(|name| { + let name = name.to_ascii_lowercase(); + name == "authorization" || name == "host" || name.starts_with("x-amz-") + }) { + return Err(error(format!( + "extra_headers cannot set {name:?} with sigv4; the signer owns it" + ))); + } + let host = url.host_str().unwrap_or_default(); + if !is_aws_host(host) && !is_loopback(&url) { + tracing::warn!( + model = model_name, + host, + "sigv4 sends signed requests to a host outside AWS" + ); + } + Ok(()) +} + +fn is_loopback(url: &reqwest::Url) -> bool { + match url.host_str() { + Some("localhost") => true, + Some(host) => host + .trim_start_matches('[') + .trim_end_matches(']') + .parse::() + .is_ok_and(|ip| ip.is_loopback()), + None => false, + } +} + +fn is_aws_host(host: &str) -> bool { + [".amazonaws.com", ".amazonaws.com.cn", ".api.aws"] + .iter() + .any(|suffix| host.ends_with(suffix)) +} + +// A timeout or an error inside a credential source, such as instance metadata that briefly +// stops answering, may clear on the next attempt, so it is a transport error, which the +// client retries. Missing or invalid credentials fail at once as configuration errors. +fn credentials_error(error: CredentialsError) -> LlmClientError { + let message = format!("could not resolve AWS credentials for sigv4: {error}"); + match error { + CredentialsError::ProviderTimedOut(_) | CredentialsError::ProviderError(_) => { + LlmClientError::Transport { + source: message.into(), + } + } + _ => LlmClientError::Configuration { message }, + } +} + +/// The AWS region named in an endpoint host, such as `us-east-1` in +/// `bedrock-runtime.us-east-1.amazonaws.com`, `bedrock-runtime-fips.us-east-1.amazonaws.com`, or a +/// VPC endpoint under `bedrock-runtime.us-east-1.vpce.amazonaws.com`. Hosts outside AWS have +/// none, even when a label looks like a region. +fn region_from_host(host: &str) -> Option<&str> { + if !is_aws_host(host) { + return None; + } + host.split('.').find(|label| { + let parts: Vec<&str> = label.split('-').collect(); + let (Some(first), Some(last)) = (parts.first(), parts.last()) else { + return false; + }; + parts.len() >= 3 + && first.len() == 2 + && parts[..parts.len() - 1] + .iter() + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase())) + && !last.is_empty() + && last.bytes().all(|b| b.is_ascii_digit()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use aws_credential_types::Credentials; + + // Temporary credentials with a session token, like those of a role. `for_tests` has no + // session token. + fn fixed_source() -> CredentialSource { + source_with( + Credentials::for_tests_with_session_token(), + Some("us-east-1"), + ) + } + + fn source_with( + provider: impl ProvideCredentials + 'static, + region: Option<&str>, + ) -> CredentialSource { + CredentialSource::for_tests(provider, region) + } + + fn request(body: &str) -> reqwest::Request { + request_to( + "https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1/chat/completions", + body, + ) + } + + fn request_to(url: &str, body: &str) -> reqwest::Request { + reqwest::Client::new() + .post(url) + .header("content-type", "application/json") + .body(body.to_string()) + .build() + .expect("buildable") + } + + #[test] + fn a_default_async_sleep_is_available() { + // The other tests use a fixed provider. The real chain retries, and its providers panic + // without a default async sleep, which aws-config's `rt-tokio` feature provides. + assert!( + aws_smithy_async::rt::sleep::default_async_sleep().is_some(), + "no default AsyncSleep: enable aws-config's `rt-tokio` feature" + ); + } + + #[tokio::test] + async fn signs_with_the_expected_headers() { + let mut req = request(r#"{"model":"m"}"#); + sign_request( + &mut req, + &SigV4Settings::new(DEFAULT_SERVICE, Some("us-east-1".to_string())), + &fixed_source(), + ) + .await + .expect("signs"); + + let auth = req + .headers() + .get(reqwest::header::AUTHORIZATION) + .expect("authorization present"); + assert!(auth.is_sensitive(), "signature must not be logged"); + let auth = String::from_utf8_lossy(auth.as_bytes()).to_string(); + assert!(auth.starts_with("AWS4-HMAC-SHA256"), "got {auth}"); + assert!( + auth.contains("/us-east-1/bedrock/aws4_request"), + "got {auth}" + ); + let date = req.headers().get("x-amz-date").expect("date present"); + assert!(!date.is_sensitive(), "the date is not secret"); + // Temporary credentials add their session token to the request. + let token = req + .headers() + .get("x-amz-security-token") + .expect("session token present"); + assert!(token.is_sensitive(), "session token must not be logged"); + } + + #[tokio::test] + async fn the_signature_covers_the_body() { + let settings = SigV4Settings::new(DEFAULT_SERVICE, Some("us-east-1".to_string())); + let source = fixed_source(); + + let mut one = request(r#"{"model":"a"}"#); + let mut two = request(r#"{"model":"b"}"#); + sign_request(&mut one, &settings, &source) + .await + .expect("signs"); + sign_request(&mut two, &settings, &source) + .await + .expect("signs"); + + // The signature depends on the body. + assert_ne!( + one.headers().get(reqwest::header::AUTHORIZATION), + two.headers().get(reqwest::header::AUTHORIZATION), + ); + } + + #[tokio::test] + async fn a_missing_region_is_an_error_not_an_unsigned_send() { + let source = source_with(Credentials::for_tests_with_session_token(), None); + + // A host without a region, so neither the client, the host nor the environment has one. + let mut req = request_to("https://gateway.example.test/v1/chat/completions", "{}"); + let error = sign_request( + &mut req, + &SigV4Settings::new(DEFAULT_SERVICE, None), + &source, + ) + .await + .expect_err("must refuse"); + assert!(format!("{error}").contains("region"), "got {error}"); + assert!(!req.headers().contains_key(reqwest::header::AUTHORIZATION)); + } + + #[tokio::test] + async fn a_request_without_a_body_is_signed() { + // The llama.cpp `/props` probe is a GET with no body. + let mut req = reqwest::Client::new() + .get("https://bedrock-runtime.us-east-1.amazonaws.com/props") + .build() + .expect("buildable"); + sign_request( + &mut req, + &SigV4Settings::new(DEFAULT_SERVICE, None), + &fixed_source(), + ) + .await + .expect("signs"); + assert!(req.headers().contains_key(reqwest::header::AUTHORIZATION)); + } + + #[derive(Debug)] + struct FailingProvider(fn() -> CredentialsError); + + impl ProvideCredentials for FailingProvider { + fn provide_credentials<'a>( + &'a self, + ) -> aws_credential_types::provider::future::ProvideCredentials<'a> + where + Self: 'a, + { + aws_credential_types::provider::future::ProvideCredentials::ready(Err((self.0)())) + } + } + + #[tokio::test] + async fn only_credential_timeouts_and_source_errors_are_transport_errors() { + // The client retries transport errors, so these decide which failures get another try. + let cases: [(fn() -> CredentialsError, bool); 3] = [ + ( + || CredentialsError::provider_timed_out(Duration::from_secs(1)), + true, + ), + ( + || CredentialsError::provider_error("metadata service returned 503"), + true, + ), + (CredentialsError::not_loaded_no_source, false), + ]; + for (failure, retryable) in cases { + let source = source_with(FailingProvider(failure), None); + let mut req = request("{}"); + let error = sign_request( + &mut req, + &SigV4Settings::new(DEFAULT_SERVICE, None), + &source, + ) + .await + .expect_err("no credentials"); + assert_eq!( + matches!(error, LlmClientError::Transport { .. }), + retryable, + "got {error:?}" + ); + assert!( + format!("{error}").contains("AWS credentials"), + "got {error}" + ); + assert!(!req.headers().contains_key(reqwest::header::AUTHORIZATION)); + } + } + + #[derive(Debug)] + struct CountingProvider { + calls: std::sync::Arc, + expiry: Option, + } + + impl ProvideCredentials for CountingProvider { + fn provide_credentials<'a>( + &'a self, + ) -> aws_credential_types::provider::future::ProvideCredentials<'a> + where + Self: 'a, + { + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + aws_credential_types::provider::future::ProvideCredentials::ready(Ok(Credentials::new( + "AKIDEXAMPLE", + "secret", + Some("token".to_string()), + self.expiry, + "counting", + ))) + } + } + + #[tokio::test] + async fn credentials_are_resolved_again_only_near_expiry() { + // Without the cache, every signed request would call the provider again. + let now = SystemTime::now(); + for (expiry, resolutions) in [ + (None, 1), + (Some(now + Duration::from_secs(3600)), 1), + (Some(now + Duration::from_secs(5)), 3), + ] { + let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let source = source_with( + CountingProvider { + calls: std::sync::Arc::clone(&calls), + expiry, + }, + Some("us-east-1"), + ); + for _ in 0..3 { + sign_request( + &mut request("{}"), + &SigV4Settings::new(DEFAULT_SERVICE, None), + &source, + ) + .await + .expect("signs"); + } + assert_eq!( + calls.load(std::sync::atomic::Ordering::SeqCst), + resolutions, + "expiry {expiry:?}" + ); + } + } + + #[test] + fn credentials_are_kept_until_shortly_before_they_expire() { + let now = SystemTime::now(); + let expiry = now + Duration::from_secs(3600); + assert_eq!(refresh_time(Some(expiry), now), expiry - EXPIRY_BUFFER); + assert_eq!(refresh_time(None, now), now + NO_EXPIRY_LIFETIME); + // Credentials at the end of their life are fetched again on the next request. + assert!(refresh_time(Some(now), now) < now); + } + + #[test] + fn finds_the_region_in_aws_endpoint_hosts() { + for (host, region) in [ + ("bedrock-runtime.us-east-1.amazonaws.com", Some("us-east-1")), + ( + "bedrock-runtime-fips.us-gov-west-1.amazonaws.com", + Some("us-gov-west-1"), + ), + ( + "vpce-0a1b2c-x1y2.bedrock-runtime.eu-central-2.vpce.amazonaws.com", + Some("eu-central-2"), + ), + ( + "bedrock-mantle.ap-southeast-4.api.aws", + Some("ap-southeast-4"), + ), + ("gateway.example.test", None), + ("my-proxy-1.example.com", None), + ("localhost", None), + ] { + assert_eq!(region_from_host(host), region, "{host}"); + } + } + + const BEDROCK_URL: &str = "https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"; + + fn backend_config(base_url: &str) -> HttpBackendConfig { + HttpBackendConfig { + base_url: base_url.to_string(), + api_key: None, + forward_auth: false, + extra_headers: std::collections::BTreeMap::new(), + extra_body: std::collections::BTreeMap::new(), + omit_body_fields: std::collections::BTreeSet::new(), + reasoning_effort: None, + max_retries: 0, + failure_cooldown: std::time::Duration::ZERO, + timeout: None, + sigv4: Some(SigV4Settings::new(DEFAULT_SERVICE, None)), + } + } + + #[test] + fn sigv4_is_the_only_auth_mode() { + let mut with_key = backend_config(BEDROCK_URL); + with_key.api_key = Some("key".to_string()); + let mut forwarding = backend_config(BEDROCK_URL); + forwarding.forward_auth = true; + for config in [with_key, forwarding] { + let error = validate(&config, "m").expect_err("must refuse"); + assert!(format!("{error}").contains("one auth mode"), "got {error}"); + } + validate(&backend_config(BEDROCK_URL), "m").expect("sigv4 alone is valid"); + } + + #[test] + fn a_signed_request_needs_https_except_on_loopback() { + for (base_url, allowed) in [ + (BEDROCK_URL, true), + ("https://gateway.example.test/v1", true), + ("http://127.0.0.1:8080/v1", true), + ("http://localhost:8080/v1", true), + ("http://[::1]:8080/v1", true), + ( + "http://bedrock-runtime.us-east-1.amazonaws.com/openai/v1", + false, + ), + ("http://gateway.example.test/v1", false), + ("not a URL", false), + ] { + assert_eq!( + validate(&backend_config(base_url), "m").is_ok(), + allowed, + "{base_url}" + ); + } + } + + #[test] + fn extra_headers_cannot_set_what_the_signer_sets() { + for name in [ + "Authorization", + "host", + "X-Amz-Date", + "x-amz-security-token", + "x-amz-content-sha256", + ] { + let mut config = backend_config(BEDROCK_URL); + config + .extra_headers + .insert(name.to_string(), "value".to_string()); + let error = validate(&config, "m").expect_err(name); + assert!(format!("{error}").contains(name), "got {error}"); + } + let mut config = backend_config(BEDROCK_URL); + config + .extra_headers + .insert("x-team".to_string(), "value".to_string()); + validate(&config, "m").expect("other headers are allowed"); + } + + #[tokio::test] + async fn an_unset_region_signs_for_the_hosts_region_not_the_environments() { + // The environment says us-east-1 and the endpoint is in us-west-2. Bedrock rejects a + // signature for any region but the endpoint's ("Credential should be scoped to a + // valid region"), so the host's region is used. + let mut req = request_to( + "https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1/chat/completions", + r#"{"model":"m"}"#, + ); + sign_request( + &mut req, + &SigV4Settings::new(DEFAULT_SERVICE, None), + &fixed_source(), + ) + .await + .expect("signs"); + let auth = req + .headers() + .get(reqwest::header::AUTHORIZATION) + .expect("signed"); + let auth = String::from_utf8_lossy(auth.as_bytes()).to_string(); + assert!( + auth.contains("/us-west-2/bedrock/aws4_request"), + "got {auth}" + ); + } + + #[tokio::test] + async fn a_configured_region_wins_over_the_host() { + let mut req = request_to( + "https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1/chat/completions", + r#"{"model":"m"}"#, + ); + let settings = SigV4Settings::new(DEFAULT_SERVICE, Some("eu-west-1".to_string())); + sign_request(&mut req, &settings, &fixed_source()) + .await + .expect("signs"); + let auth = req + .headers() + .get(reqwest::header::AUTHORIZATION) + .expect("signed"); + let auth = String::from_utf8_lossy(auth.as_bytes()).to_string(); + assert!( + auth.contains("/eu-west-1/bedrock/aws4_request"), + "got {auth}" + ); + } +} diff --git a/crates/libsy-llm-client/tests/fallback_credit.rs b/crates/libsy-llm-client/tests/fallback_credit.rs index 74814e3400..1e3ba4abc7 100644 --- a/crates/libsy-llm-client/tests/fallback_credit.rs +++ b/crates/libsy-llm-client/tests/fallback_credit.rs @@ -148,6 +148,7 @@ async fn fallback_credit_retry_child() -> TestResult { max_retries: 0, failure_cooldown: std::time::Duration::ZERO, timeout: None, + sigv4: None, }), None, ) diff --git a/crates/switchyard-runner/src/config.rs b/crates/switchyard-runner/src/config.rs index 3f53031ae7..8a2026213d 100644 --- a/crates/switchyard-runner/src/config.rs +++ b/crates/switchyard-runner/src/config.rs @@ -1513,6 +1513,10 @@ struct LlmClientConfig { api_key_env: Option, #[serde(default)] forward_auth: bool, + /// Sign requests with AWS SigV4 instead of sending a configured key, for example to call + /// Amazon Bedrock with IAM credentials. Cannot be combined with `api_key_env` or + /// `forward_auth`. + sigv4: Option, #[serde(default)] extra_headers: BTreeMap, #[serde(default = "default_max_retries")] @@ -1527,6 +1531,23 @@ struct LlmClientConfig { responses_reasoning: Option, } +/// `sigv4 = {}` to sign for the region in `base_url`'s host, or `sigv4 = { region = "us-east-1" }` +/// to set it. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SigV4ClientConfig { + /// Signing region. Omit to use the region in `base_url`'s host, or the provider chain's + /// (`AWS_REGION`, profile, or instance metadata) when the host names none. + region: Option, + /// Signing service name. Defaults to `bedrock`. + #[serde(default = "default_sigv4_service")] + service: String, +} + +fn default_sigv4_service() -> String { + switchyard_llm_client::sigv4::DEFAULT_SERVICE.to_string() +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] enum ContextDiscovery { @@ -1622,9 +1643,14 @@ fn build_backend( "llm client {client_name} timeout_ms must be at least 1" ))); } - if config.forward_auth && config.api_key_env.is_some() { + // At most one auth mode per llm client. + let declared_auth = usize::from(config.forward_auth) + + usize::from(config.api_key_env.is_some()) + + usize::from(config.sigv4.is_some()); + if declared_auth > 1 { return Err(RunnerError::configuration(format!( - "llm client {client_name} cannot set both forward_auth and api_key_env" + "llm client {client_name} sets more than one of forward_auth, api_key_env and \ + sigv4; set one" ))); } let api_key = config @@ -1643,6 +1669,12 @@ fn build_backend( max_retries: config.max_retries, failure_cooldown: Duration::from_millis(config.failure_cooldown_ms), timeout: config.timeout_ms.map(Duration::from_millis), + sigv4: config.sigv4.as_ref().map(|sigv4| { + switchyard_llm_client::sigv4::SigV4Settings::new( + sigv4.service.clone(), + sigv4.region.clone(), + ) + }), }; let backend = match config.format { ClientFormat::OpenAiChat => Backend::OpenAiChat(http), @@ -3837,6 +3869,37 @@ target = "azure" assert!(!error.contains("DUMMY_SECRET_DO_NOT_LOG"), "{error}"); } + #[test] + fn an_empty_sigv4_table_configures_signing_with_no_pinned_region() { + // `sigv4 = {}` leaves the region unset, so it comes from `base_url`'s host. + let bare = VALID_CONFIG.replacen( + "base_url = \"https://example.test/v1\"", + "base_url = \"https://example.test/v1\"\n\ + sigv4 = {}", + 1, + ); + let config: DeploymentConfig = toml::from_str(&bare).expect("empty sigv4 table parses"); + let client = config + .llm_clients + .values() + .find(|client| client.sigv4.is_some()) + .expect("the sigv4 client"); + let sigv4 = client.sigv4.as_ref().expect("declared"); + assert_eq!(sigv4.region, None, "an omitted region must stay unset"); + assert_eq!(sigv4.service, "bedrock", "service defaults to bedrock"); + + // It also builds a runner. + runner_from_toml(&bare).expect("a bare sigv4 client builds"); + } + + #[test] + fn bedrock_sigv4_example_builds() -> RunnerResult<()> { + let runner = runner_from_toml(include_str!("../../../examples/bedrock-sigv4.toml"))?; + assert!(runner.route("bedrock").is_some()); + assert!(runner.route("bedrock/mixed").is_some()); + Ok(()) + } + #[test] fn forward_auth_rejects_conflicting_credentials() { let competing_auth = VALID_CONFIG.replacen( @@ -3847,9 +3910,26 @@ target = "azure" 1, ); assert!( - error_message(&competing_auth).contains("cannot set both forward_auth and api_key_env") + error_message(&competing_auth).contains("more than one of forward_auth, api_key_env") ); + // sigv4 conflicts with each of the other auth modes. + for other in ["api_key_env = \"UNUSED_TEST_KEY\"", "forward_auth = true"] { + let with_sigv4 = VALID_CONFIG.replacen( + "base_url = \"https://example.test/v1\"", + &format!( + "base_url = \"https://example.test/v1\"\n\ + sigv4 = {{ region = \"us-east-1\" }}\n\ + {other}" + ), + 1, + ); + assert!( + error_message(&with_sigv4).contains("more than one of forward_auth, api_key_env"), + "sigv4 + {other} must conflict" + ); + } + let static_auth = VALID_CONFIG.replacen( "base_url = \"https://example.test\"", "base_url = \"https://example.test\"\n\ diff --git a/crates/switchyard-server/tests/server.rs b/crates/switchyard-server/tests/server.rs index 8ae6b2e07a..b8de983d17 100644 --- a/crates/switchyard-server/tests/server.rs +++ b/crates/switchyard-server/tests/server.rs @@ -833,6 +833,7 @@ fn random_state_with_retries( max_retries, failure_cooldown: std::time::Duration::ZERO, timeout: None, + sigv4: None, }); let target_models = routes .iter() diff --git a/docs/reference/toml_schema.md b/docs/reference/toml_schema.md index 9db694c8d1..0c8573a10d 100644 --- a/docs/reference/toml_schema.md +++ b/docs/reference/toml_schema.md @@ -53,7 +53,8 @@ route reaches no upstream. A file without a `[targets]` table is rejected with | `context_discovery` | No | unset | Set to `"llama_cpp"` to enable `/props` context discovery for VGR efficient targets. Disabled when unset. An explicit route `context_window` takes precedence. | | `api_key_env` | No | unset | Name of the environment variable holding the key. Omit to send no authentication. | | `forward_auth` | No | `false` | Forward the caller's provider credential and application headers. A route's forwarding clients must use one credential family unless they all use the same scheme, host, and port, such as one LLM gateway. | -| `extra_headers` | No | `{}` | Custom HTTP headers sent to the model server. Set credentials with `api_key_env` or `forward_auth`; the server rejects headers owned by the selected auth mode. Header names are case-insensitive. Configured values replace caller values for the same name. | +| `sigv4` | No | unset | Sign every request with AWS SigV4, for Amazon Bedrock. Write `sigv4 = {}` to sign for the region in `base_url`'s host, such as `us-east-1` in `bedrock-runtime.us-east-1.amazonaws.com`. When the host is outside AWS or names no region, the AWS environment's region is used. Write `sigv4 = { region = "us-east-1" }` to set it explicitly. `service` defaults to `"bedrock"`. `base_url` must use `https`, except on `localhost` and other loopback addresses. Anyone who reads a signed request can send it again for about 15 minutes, so point `base_url` only at hosts you trust. Credentials come from the standard AWS credential provider chain, and Switchyard fetches them again shortly before they expire. Profiles that use `sso_session`, `sso_start_url`, `credential_process` or `login_session` are not supported. Cannot be combined with `api_key_env` or `forward_auth`. See [`examples/bedrock-sigv4.toml`](../../examples/bedrock-sigv4.toml). | +| `extra_headers` | No | `{}` | Custom HTTP headers sent to the model server. Set credentials with `forward_auth`, `sigv4` or `api_key_env`; the server rejects headers owned by the selected auth mode. With `sigv4`, these are `authorization`, `host` and every `x-amz-` header. Header names are case-insensitive. Configured values replace caller values for the same name. | | `responses_reasoning` | No | `"auto"` | Responses reasoning replay: `"auto"`, `"preserve_encrypted"`, `"preserve_plaintext"`, or `"drop"`. Only valid for `openai_responses`. | | `fallback_on_rate_limit` | No | `true` | Try another completion candidate after an upstream HTTP 429 exhausts retries. Set to `false` to return the 429 instead. | | `max_retries` | No | `2` | Retry budget, `0`–`10`. | @@ -88,6 +89,7 @@ when no target uses the client. The TOML never contains the secret itself. `api_key_env` names a variable that must exist and be non-empty when the server loads. +With `sigv4`, the TOML holds no credentials at all. Cooldown is enabled by default for 5 seconds. Set `failure_cooldown_ms = 0` to disable it. The cooldown starts after retries are exhausted. diff --git a/examples/bedrock-sigv4.toml b/examples/bedrock-sigv4.toml new file mode 100644 index 0000000000..20f1ba64b6 --- /dev/null +++ b/examples/bedrock-sigv4.toml @@ -0,0 +1,57 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Amazon Bedrock with IAM credentials. Each llm client signs its requests with AWS SigV4, using +# the standard AWS credential chain: environment variables, a profile with access keys or a role +# to assume, a web identity token, or a container or instance role. Profiles that use IAM Identity +# Center (SSO), credential_process or login_session are not supported. No API key is stored here +# or in the environment. +# +# The credentials need bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream on the models +# below, and the account needs Bedrock model access for them. Replace the region and model IDs for +# your account, then run: +# +# switchyard-server --config examples/bedrock-sigv4.toml +schema_version = 1 + +# Claude through Bedrock's Anthropic-compatible API. An empty sigv4 table signs for the region in +# base_url's host, so the region is set in one place. +[llm_clients.bedrock_anthropic] +format = "anthropic_messages" +base_url = "https://bedrock-runtime.us-east-1.amazonaws.com/anthropic" +sigv4 = {} + +# NVIDIA Nemotron and other open-weight models through Bedrock's OpenAI-compatible API. +[llm_clients.bedrock_openai] +format = "openai_chat" +base_url = "https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1" +sigv4 = {} + +# A US cross-Region inference profile. For global routing, use the global profile instead: +# "global.anthropic.claude-haiku-5-5". It may process requests in any commercial AWS Region, +# and needs IAM access to the global inference profile and model. +# base_url stays a regional endpoint either way. +# +# Older Claude models on Bedrock, such as Claude Haiku 4.5 and Claude Sonnet 4.6, reject +# structured output (output_config.format). Add omit_body_fields = ["output_config"] to their +# targets; this also drops any effort setting. +[targets.claude] +id = "us.anthropic.claude-haiku-5-5" +llm_client = "bedrock_anthropic" + +[targets.nemotron] +id = "nvidia.nemotron-nano-3-30b" +llm_client = "bedrock_openai" + +# Every request to Claude. +[routes.claude] +id = "bedrock" +type = "passthrough" +target = "claude" + +# Three in four requests to Nemotron, the rest to Claude. +[routes.mixed] +id = "bedrock/mixed" +type = "random" +targets = ["nemotron", "claude"] +weights = [3, 1]