Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
490 changes: 490 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
7 changes: 7 additions & 0 deletions crates/libsy-llm-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
18 changes: 18 additions & 0 deletions crates/libsy-llm-client/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Duration>,
/// 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<crate::sigv4::SigV4Settings>,
}

impl fmt::Debug for HttpBackendConfig {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -458,6 +475,7 @@ mod tests {
max_retries: 0,
failure_cooldown: Duration::ZERO,
timeout: None,
sigv4: None,
}
}

Expand Down
156 changes: 145 additions & 11 deletions crates/libsy-llm-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ModelId, AtomicU64>,
// 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 {
Expand Down Expand Up @@ -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)?;
Expand All @@ -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()))?;

Expand All @@ -231,6 +235,7 @@ impl TranslatingLlmClient {
is_rate_limit_cooldown_enabled: true,
cooldown_epoch: Instant::now(),
unavailable_until,
credentials: crate::sigv4::CredentialSource::default(),
})
}

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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<reqwest::Request, LlmClientError> {
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,
Expand All @@ -633,7 +655,7 @@ impl TranslatingLlmClient {
target_name: &ModelId,
streaming: bool,
) -> std::result::Result<EncodedResponse, AttemptFailure> {
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
Expand All @@ -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);
Expand Down Expand Up @@ -1596,6 +1638,7 @@ mod tests {
max_retries: 0,
failure_cooldown: Duration::ZERO,
timeout: None,
sigv4: None,
}
}

Expand Down Expand Up @@ -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<dyn Error + Sync + Send + 'static>> {
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<dyn Error + Sync + Send + 'static>> {
Expand Down
1 change: 1 addition & 0 deletions crates/libsy-llm-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
6 changes: 6 additions & 0 deletions crates/libsy-llm-client/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -2023,6 +2024,7 @@ mod tests {
max_retries: 0,
failure_cooldown: std::time::Duration::ZERO,
timeout: None,
sigv4: None,
}),
None,
)])
Expand Down Expand Up @@ -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(&[
Expand Down Expand Up @@ -2864,6 +2867,7 @@ mod tests {
max_retries: 2,
failure_cooldown: cooldown,
timeout: None,
sigv4: None,
})
};
TranslatingLlmClient::new(&[
Expand Down Expand Up @@ -2937,6 +2941,7 @@ mod tests {
max_retries: 0,
failure_cooldown: std::time::Duration::ZERO,
timeout: None,
sigv4: None,
})
};
let client = Arc::new(
Expand Down Expand Up @@ -3037,6 +3042,7 @@ mod tests {
max_retries: 0,
failure_cooldown: std::time::Duration::ZERO,
timeout: None,
sigv4: None,
})
};
let client = Arc::new(
Expand Down
Loading
Loading