use std::error::Error as _;
use aws_sdk_bedrockagentcore::{
Client,
config::{BehaviorVersion, Credentials, SharedCredentialsProvider, http::HttpResponse},
error::SdkError,
operation::get_resource_api_key::{GetResourceApiKeyError, GetResourceApiKeyOutput},
primitives::SdkBody,
types::error::AccessDeniedException,
};
use aws_smithy_mocks::{Rule, RuleMode, mock, mock_client};
use super::*;
use crate::context::{self, WorkloadAccessToken};
fn token(value: &str) -> WorkloadAccessToken {
WorkloadAccessToken::new(value)
}
fn ctx(value: &str) -> RequestContext {
RequestContext::builder("session").workload_access_token(token(value)).build()
}
fn key_rule(provider: &'static str, wat: &'static str, key: &'static str) -> Rule {
mock!(Client::get_resource_api_key)
.match_requests(move |request| {
request.resource_credential_provider_name() == Some(provider)
&& request.workload_identity_token() == Some(wat)
})
.then_output(move || GetResourceApiKeyOutput::builder().api_key(key).build().unwrap())
}
fn body_rule(body: &'static str) -> Rule {
mock!(Client::get_resource_api_key)
.then_http_response(move || HttpResponse::new(200u16.try_into().unwrap(), SdkBody::from(body)))
}
fn identity(rules: &[&Rule]) -> IdentityClient {
IdentityClient::from_client(mock_client!(aws_sdk_bedrockagentcore, RuleMode::MatchAny, rules))
}
type ApiKeySdkError = SdkError<GetResourceApiKeyError, HttpResponse>;
#[tokio::test]
async fn request_carries_the_provider_and_the_explicit_token_before_the_ambient_one() {
let cases = [
(Some("EXPLICIT"), Some("AMBIENT"), "EXPLICIT"),
(Some("EXPLICIT"), None, "EXPLICIT"),
(None, Some("AMBIENT"), "AMBIENT"),
];
for (explicit, ambient, expected) in cases {
let rule = key_rule("orders", expected, "KEY");
let mut request = identity(&[&rule]).api_key("orders");
if let Some(explicit) = explicit {
request = request.workload_access_token(token(explicit));
}
let key = match ambient {
Some(ambient) => context::scope(ctx(ambient), request.send()).await,
None => request.send().await,
};
assert_eq!(key.unwrap().expose(), "KEY", "{explicit:?} {ambient:?}");
assert_eq!(rule.num_calls(), 1, "{explicit:?} {ambient:?}");
}
}
#[tokio::test]
async fn missing_or_empty_token_fails_before_any_request() {
let rule = key_rule("orders", "AMBIENT", "KEY");
let identity = identity(&[&rule]);
let request = || identity.api_key("orders");
let no_token = RequestContext::builder("session").build();
let failures = [
("outside a context", request().send().await, "outside a request context, for example in a task started"),
(
"context without a token",
context::scope(no_token, request().send()).await,
"the invocation carried none. AgentCore Runtime sends a token only when the caller names a user",
),
(
"context with an empty token",
context::scope(ctx(""), request().send()).await,
"A local call must send a token of a workload identity in the X-Amz-Bedrock-AgentCore-Identity-WAT",
),
(
"explicit empty token",
context::scope(ctx("AMBIENT"), request().workload_access_token(token("")).send()).await,
"The token given to .workload_access_token(..) is empty",
),
];
for (case, result, cause) in failures {
let error = result.unwrap_err();
assert_eq!(error.kind(), ErrorKind::MissingWorkloadToken, "{case}");
assert!(error.to_string().contains(cause), "{case}: {error}");
assert!(error.source().is_none(), "{case}");
}
assert_eq!(rule.num_calls(), 0);
}
fn error_rule(status: u16, error_type: &'static str, request_id: &'static str) -> Rule {
mock!(Client::get_resource_api_key).then_http_response(move || {
let body = SdkBody::from(r#"{"message":"SENTINEL-MESSAGE"}"#);
let mut response = HttpResponse::new(status.try_into().unwrap(), body);
response.headers_mut().insert("x-amzn-errortype", error_type);
response.headers_mut().insert("x-amzn-requestid", request_id);
response
})
}
#[tokio::test]
async fn failed_call_names_the_provider_the_code_the_status_and_the_request_id_and_keeps_its_source() {
let send = |rule: Rule| async move {
identity(&[&rule]).api_key("orders").workload_access_token(token("WAT")).send().await.unwrap_err()
};
let denied = send(error_rule(403, "AccessDeniedException", "request-1")).await;
assert_eq!(denied.kind(), ErrorKind::Service);
assert_eq!(
denied.to_string(),
"GetResourceApiKey for provider orders failed: AccessDeniedException (HTTP 403, request ID: request-1)"
);
let source = denied.source().unwrap().downcast_ref::<ApiKeySdkError>().unwrap();
assert!(source.as_service_error().is_some_and(GetResourceApiKeyError::is_access_denied_exception), "{source}");
let unknown = send(error_rule(404, "ResourceNotFoundException", "request-2")).await;
let text =
"GetResourceApiKey for provider orders failed: ResourceNotFoundException (HTTP 404, request ID: request-2)";
assert_eq!(unknown.to_string(), text);
for error in [&denied, &unknown] {
assert!(!format!("{error} {error:?} {error:#?}").contains("SENTINEL"));
}
let odd = send(error_rule(400, "SENTINEL code", "SENTINEL id")).await;
assert_eq!(odd.to_string(), "GetResourceApiKey for provider orders failed: service error (HTTP 400)");
let modeled = mock!(Client::get_resource_api_key).then_error(|| {
GetResourceApiKeyError::AccessDeniedException(AccessDeniedException::builder().message("denied").build())
});
let text = "GetResourceApiKey for provider orders failed: service error (HTTP 418)";
assert_eq!(send(modeled).await.to_string(), text);
}
#[tokio::test]
async fn error_of_an_undecodable_response_does_not_print_the_api_key_in_the_body() {
let rule = body_rule(r#"{"apiKey":"SENTINEL-KEY""#);
let error = identity(&[&rule]).api_key("orders").workload_access_token(token("WAT")).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::Service);
let text = "GetResourceApiKey for provider orders failed: service error (HTTP 200)";
assert_eq!(error.to_string(), text);
let debug = format!("Error {{ kind: Service, message: {text:?}, .. }}");
assert_eq!(format!("{error:?}"), debug);
assert!(!format!("{error:#?}").contains("SENTINEL"), "{error:#?}");
assert!(error.source().unwrap().is::<ApiKeySdkError>());
}
#[tokio::test]
async fn config_without_a_region_fails_when_the_request_is_sent() {
let config = SdkConfig::builder()
.behavior_version(BehaviorVersion::latest())
.credentials_provider(SharedCredentialsProvider::new(Credentials::for_tests()))
.http_client(aws_smithy_mocks::create_mock_http_client())
.build();
let identity = IdentityClient::new(&config);
let error = identity.api_key("orders").workload_access_token(token("WAT")).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::Service);
assert_eq!(error.to_string(), "GetResourceApiKey for provider orders failed: dispatch failure");
assert!(error.source().unwrap().is::<ApiKeySdkError>());
}
#[test]
fn debug_output_shows_no_secret() {
let rule = key_rule("orders", "WAT", "KEY");
let identity = identity(&[&rule]);
let request = identity.api_key("orders").workload_access_token(token("SECRET-TOKEN"));
let debug = format!("{identity:?} {request:?} {:?} {:#?}", ApiKey::new("SECRET-KEY"), ApiKey::new("SECRET-KEY"));
assert!(debug.contains(r#"provider: "orders""#) && debug.contains("*** Sensitive Data Redacted ***"));
assert!(!debug.contains("SECRET"));
}
mod oauth2 {
use std::{
sync::{Arc, Mutex},
time::Duration,
};
use aws_sdk_bedrockagentcore::{
Config,
config::{Region, retry::RetryConfig},
operation::get_resource_oauth2_token::{
GetResourceOauth2TokenError, GetResourceOauth2TokenInput, GetResourceOauth2TokenOutput,
},
types::{Oauth2FlowType, SessionStatus},
};
use aws_smithy_http_client::test_util::{ReplayEvent, StaticReplayClient};
use aws_smithy_mocks::RuleBuilder;
use futures_core::Stream;
use tokio::time::Instant;
use super::*;
use crate::identity::poller;
const URL: &str = "https://consent.example/SENTINEL-URL";
type Oauth2SdkError = SdkError<GetResourceOauth2TokenError, HttpResponse>;
#[derive(Clone)]
struct Seen {
start: Instant,
requests: Arc<Mutex<Vec<(Duration, GetResourceOauth2TokenInput)>>>,
}
impl Seen {
fn new() -> Self {
Self { start: Instant::now(), requests: Arc::default() }
}
fn rule(
&self,
) -> RuleBuilder<GetResourceOauth2TokenInput, GetResourceOauth2TokenOutput, GetResourceOauth2TokenError>
{
let seen = self.clone();
mock!(Client::get_resource_oauth2_token).match_requests(move |request| {
seen.requests.lock().unwrap().push((seen.start.elapsed(), request.clone()));
true
})
}
fn requests(&self) -> Vec<GetResourceOauth2TokenInput> {
self.requests.lock().unwrap().iter().map(|(_, request)| request.clone()).collect()
}
fn seconds(&self) -> Vec<u64> {
self.requests.lock().unwrap().iter().map(|(at, _)| at.as_secs()).collect()
}
}
fn with_token() -> GetResourceOauth2TokenOutput {
GetResourceOauth2TokenOutput::builder().access_token("TOKEN").build()
}
fn with_url() -> GetResourceOauth2TokenOutput {
GetResourceOauth2TokenOutput::builder()
.authorization_url(URL)
.session_uri("urn:session:1")
.session_status(SessionStatus::InProgress)
.build()
}
fn wat(request: Oauth2TokenBuilder) -> Oauth2TokenBuilder {
request.workload_access_token(token("WAT"))
}
#[tokio::test]
async fn every_flow_returns_the_token_of_the_first_response() {
let flows = [
(AuthFlow::M2m, Oauth2FlowType::M2M),
(AuthFlow::UserFederation, Oauth2FlowType::UserFederation),
(AuthFlow::OnBehalfOfTokenExchange, Oauth2FlowType::OnBehalfOfTokenExchange),
];
for (flow, expected) in flows {
let seen = Seen::new();
let rule = seen.rule().then_output(with_token);
let access = wat(identity(&[&rule]).oauth2_token("orders", flow)).send().await.unwrap();
assert_eq!(access.expose(), "TOKEN");
let [request] = &seen.requests()[..] else { panic!("one request for {flow:?}") };
assert_eq!(request.resource_credential_provider_name(), Some("orders"));
assert_eq!(request.workload_identity_token(), Some("WAT"));
assert_eq!(request.oauth2_flow(), Some(&expected));
assert_eq!(request.scopes, Some(vec![]));
assert_eq!((&request.resources, &request.audiences), (&None, &None));
assert_eq!((request.session_uri(), request.resource_oauth2_return_url()), (None, None));
assert_eq!((request.force_authentication(), request.custom_state()), (None, None));
assert_eq!(request.custom_parameters(), None);
}
}
#[tokio::test]
async fn options_are_sent_as_given_and_lists_are_replaced() {
let seen = Seen::new();
let rule = seen.rule().then_output(with_token);
let identity = identity(&[&rule]);
wat(identity.oauth2_token("orders", AuthFlow::UserFederation))
.scopes(["dropped"])
.scopes(["read", "write"])
.resources(["https://orders.example"])
.audiences(["orders"])
.callback_url("https://app.example/callback")
.force_authentication(true)
.custom_state("STATE")
.custom_parameters([("prompt", "consent")])
.send()
.await
.unwrap();
wat(identity.oauth2_token("orders", AuthFlow::M2m))
.resources(Vec::<String>::new())
.audiences(Vec::<String>::new())
.force_authentication(false)
.send()
.await
.unwrap();
let [full, empty] = &seen.requests()[..] else { panic!("two requests") };
assert_eq!(full.scopes(), ["read", "write"]);
assert_eq!(full.resources, Some(vec!["https://orders.example".to_owned()]));
assert_eq!(full.audiences, Some(vec!["orders".to_owned()]));
assert_eq!(full.resource_oauth2_return_url(), Some("https://app.example/callback"));
assert_eq!((full.force_authentication(), full.custom_state()), (Some(true), Some("STATE")));
assert_eq!(full.custom_parameters().unwrap().get("prompt").map(String::as_str), Some("consent"));
assert_eq!((&empty.resources, &empty.audiences), (&Some(vec![]), &Some(vec![])));
assert_eq!(empty.force_authentication(), Some(false));
}
#[tokio::test]
async fn callback_url_is_the_explicit_one_before_the_one_of_the_context() {
let seen = Seen::new();
let rule = seen.rule().then_output(with_token);
let identity = identity(&[&rule]);
let ambient = RequestContext::builder("session")
.workload_access_token(token("WAT"))
.oauth2_callback_url("https://ambient.example/callback")
.build();
let request = || identity.oauth2_token("orders", AuthFlow::UserFederation);
context::scope(ambient.clone(), request().callback_url("https://explicit.example/callback").send())
.await
.unwrap();
context::scope(ambient, request().send()).await.unwrap();
context::scope(ctx("WAT"), request().send()).await.unwrap();
let urls: Vec<_> =
seen.requests().iter().map(|request| request.resource_oauth2_return_url().map(str::to_owned)).collect();
assert_eq!(
urls,
[
Some("https://explicit.example/callback".to_owned()),
Some("https://ambient.example/callback".to_owned()),
None
]
);
}
#[tokio::test]
async fn token_wins_over_a_url_and_a_response_with_neither_is_an_error() {
let both = mock!(Client::get_resource_oauth2_token).then_output(|| {
GetResourceOauth2TokenOutput::builder().access_token("TOKEN").authorization_url(URL).build()
});
let called = Arc::new(Mutex::new(0));
let count = called.clone();
let access = wat(identity(&[&both]).oauth2_token("orders", AuthFlow::UserFederation))
.on_auth_url(move |_| {
*count.lock().unwrap() += 1;
async { Ok::<_, std::io::Error>(()) }
})
.send()
.await
.unwrap();
assert_eq!((access.expose(), *called.lock().unwrap(), both.num_calls()), ("TOKEN", 0, 1));
let empty = || GetResourceOauth2TokenOutput::builder().access_token("").authorization_url("").build();
for output in [GetResourceOauth2TokenOutput::builder().build(), empty()] {
let rule = mock!(Client::get_resource_oauth2_token).then_output(move || output.clone());
let error =
wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation)).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoTokenOrAuthUrl);
assert_eq!(error.to_string(), "Identity service did not return a token or authorization URL");
assert_eq!(rule.num_calls(), 1);
}
}
#[tokio::test(start_paused = true)]
async fn consent_notifies_once_then_polls_every_five_seconds_with_the_session_of_the_first_response() {
let seen = Seen::new();
let rule = seen
.rule()
.sequence()
.output(with_url)
.output(|| GetResourceOauth2TokenOutput::builder().authorization_url("https://other.example").build())
.output(|| GetResourceOauth2TokenOutput::builder().session_status(SessionStatus::Failed).build())
.output(|| GetResourceOauth2TokenOutput::builder().access_token("").session_uri("urn:other").build())
.output(with_token)
.build();
let urls = Arc::new(Mutex::new(Vec::new()));
let notified = urls.clone();
let access = wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation))
.scopes(["read"])
.audiences(["orders"])
.callback_url("https://app.example/callback")
.custom_state("STATE")
.custom_parameters([("prompt", "consent")])
.force_authentication(true)
.on_auth_url(move |url| {
notified.lock().unwrap().push(url.expose().to_owned());
async { Ok::<_, std::io::Error>(()) }
})
.send()
.await
.unwrap();
assert_eq!(access.expose(), "TOKEN");
assert_eq!(*urls.lock().unwrap(), [URL]);
assert_eq!(seen.seconds(), [0, 5, 10, 15, 20]);
let requests = seen.requests();
assert_eq!((requests[0].session_uri(), requests[0].force_authentication()), (None, Some(true)));
for poll in &requests[1..] {
assert_eq!((poll.session_uri(), poll.force_authentication()), (Some("urn:session:1"), None));
assert_eq!(poll.workload_identity_token(), Some("WAT"));
assert_eq!(poll.resource_credential_provider_name(), Some("orders"));
assert_eq!(poll.oauth2_flow(), Some(&Oauth2FlowType::UserFederation));
assert_eq!(
(poll.scopes(), poll.audiences(), &poll.resources),
(&["read".to_owned()][..], &["orders".to_owned()][..], &None)
);
assert_eq!(poll.resource_oauth2_return_url(), Some("https://app.example/callback"));
assert_eq!(poll.custom_state(), Some("STATE"));
assert_eq!(poll.custom_parameters(), requests[0].custom_parameters());
}
}
#[tokio::test(start_paused = true)]
async fn consent_without_a_callback_or_a_session_uri_still_polls() {
let seen = Seen::new();
let rule = seen
.rule()
.sequence()
.output(|| GetResourceOauth2TokenOutput::builder().authorization_url(URL).build())
.output(with_token)
.build();
let access = wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation)).send().await.unwrap();
assert_eq!(access.expose(), "TOKEN");
assert_eq!(seen.seconds(), [0, 5]);
assert_eq!(seen.requests()[1].session_uri(), None);
}
#[tokio::test(start_paused = true)]
async fn polling_budget_starts_when_the_callback_has_completed() {
let seen = Seen::new();
let rule = seen.rule().sequence().output(with_url).repeatedly().build();
let error = wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation))
.on_auth_url(|_| async {
tokio::time::sleep(Duration::from_secs(100)).await;
Ok::<_, std::io::Error>(())
})
.send()
.await
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::AuthorizationTimedOut);
assert_eq!(
error.to_string(),
"Polling timed out after 600 seconds. User may not have completed authorization."
);
let seconds = seen.seconds();
assert_eq!((seconds.len(), seconds[1], seconds[120]), (121, 105, 700));
assert_eq!(seen.start.elapsed(), Duration::from_secs(700));
}
#[tokio::test]
async fn provider_name_that_the_api_refuses_fails_before_any_request() {
let (key, access) =
(key_rule("orders", "WAT", "KEY"), mock!(Client::get_resource_oauth2_token).then_output(with_token));
let identity = identity(&[&key, &access]);
let too_long = "a".repeat(129);
for name in ["", "orders api", "orders\n", too_long.as_str()] {
let errors = [
identity.api_key(name).workload_access_token(token("WAT")).send().await.unwrap_err(),
wat(identity.oauth2_token(name, AuthFlow::M2m)).send().await.unwrap_err(),
];
for error in errors {
assert_eq!(error.kind(), ErrorKind::InvalidConfig, "{name:?}");
assert!(error.to_string().ends_with(&format!("got {name:?}")), "{error}");
}
}
assert_eq!((key.num_calls(), access.num_calls()), (0, 0));
let longest = "a-B_9".repeat(25) + "abc";
let request = identity.oauth2_token(&longest, AuthFlow::M2m);
assert_eq!((longest.len(), wat(request).send().await.unwrap().expose()), (128, "TOKEN"));
}
#[tokio::test]
async fn token_is_read_where_the_request_is_sent_and_not_where_it_was_built() {
let (first, second) = (key_rule("orders", "FIRST", "KEY-1"), key_rule("orders", "SECOND", "KEY-2"));
let identity = identity(&[&first, &second]);
let request = context::scope(ctx("FIRST"), async { identity.api_key("orders") }).await;
let copy = request.clone();
assert_eq!(context::scope(ctx("SECOND"), request.send()).await.unwrap().expose(), "KEY-2");
assert_eq!(context::scope(ctx("FIRST"), copy.send()).await.unwrap().expose(), "KEY-1");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_requests_of_one_client_use_the_token_of_their_own_context() {
let (first, second) = (key_rule("orders", "FIRST", "KEY-1"), key_rule("orders", "SECOND", "KEY-2"));
let identity = identity(&[&first, &second]);
let tasks: Vec<_> = (0..32)
.map(|i| {
let (wat, key) = if i % 2 == 0 { ("FIRST", "KEY-1") } else { ("SECOND", "KEY-2") };
let identity = identity.clone();
tokio::spawn(context::scope(ctx(wat), async move {
tokio::task::yield_now().await;
assert_eq!(identity.api_key("orders").send().await.unwrap().expose(), key);
}))
})
.collect();
for task in tasks {
task.await.unwrap();
}
assert_eq!((first.num_calls(), second.num_calls()), (16, 16));
}
#[tokio::test]
async fn spawned_task_needs_a_scope_or_an_explicit_token() {
let rule = key_rule("orders", "AMBIENT", "KEY");
let identity = identity(&[&rule]);
let ambient = ctx("AMBIENT");
context::scope(ambient.clone(), async {
let unscoped = tokio::spawn(identity.api_key("orders").send());
assert_eq!(unscoped.await.unwrap().unwrap_err().kind(), ErrorKind::MissingWorkloadToken);
let scoped = tokio::spawn(context::scope(ambient.clone(), identity.api_key("orders").send()));
assert_eq!(scoped.await.unwrap().unwrap().expose(), "KEY");
let explicit = tokio::spawn(identity.api_key("orders").workload_access_token(token("AMBIENT")).send());
assert_eq!(explicit.await.unwrap().unwrap().expose(), "KEY");
})
.await;
assert_eq!(rule.num_calls(), 2);
}
#[tokio::test]
async fn successful_response_without_an_api_key_is_an_error() {
for body in ["{}", r#"{"apiKey":""}"#] {
let rule = body_rule(body);
let error =
identity(&[&rule]).api_key("orders").workload_access_token(token("WAT")).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoApiKey, "{body}");
assert_eq!(error.to_string(), "No API key returned for provider: orders", "{body}");
assert!(error.source().is_none(), "{body}");
assert_eq!(rule.num_calls(), 1, "{body}");
}
let rule = body_rule(r#"{"apiKey":"KEY"}"#);
let key = identity(&[&rule]).api_key("orders").workload_access_token(token("WAT")).send().await.unwrap();
assert_eq!(key.expose(), "KEY");
}
#[tokio::test(start_paused = true)]
async fn poll_interval_and_timeout_replace_the_defaults() {
let seen = Seen::new();
let rule = seen.rule().sequence().output(with_url).repeatedly().build();
let request = || wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation));
let error =
request().poll_interval(Duration::from_secs(2)).timeout(Duration::from_secs(7)).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::AuthorizationTimedOut);
assert_eq!(error.to_string(), "Polling timed out after 7 seconds. User may not have completed authorization.");
assert_eq!((seen.seconds(), seen.start.elapsed()), (vec![0, 2, 4, 6], Duration::from_secs(7)));
for (interval, requests) in [(Duration::from_secs(60), 5), (Duration::MAX, 6)] {
let started = Instant::now();
let error = request().poll_interval(interval).timeout(Duration::from_secs(1)).send().await.unwrap_err();
assert_eq!((error.kind(), started.elapsed()), (ErrorKind::AuthorizationTimedOut, Duration::from_secs(1)));
assert_eq!(seen.seconds().len(), requests, "only the first request of this send was made");
}
let error = request().poll_interval(Duration::ZERO).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidConfig);
assert_eq!(seen.seconds().len(), 6, "a zero interval makes no request");
}
#[tokio::test(start_paused = true)]
async fn poll_that_resumes_after_the_budget_starts_no_request() {
let calls = std::cell::Cell::new(0);
let mut poll = std::pin::pin!(poller::poll(poller::INTERVAL, poller::BUDGET, || {
calls.set(calls.get() + 1);
async { Ok(Some(AccessToken::new("LATE"))) }
}));
assert!(std::future::poll_fn(|cx| std::task::Poll::Ready(poll.as_mut().poll(cx).is_pending())).await);
tokio::time::advance(poller::BUDGET + Duration::from_secs(1)).await;
assert_eq!(poll.await.unwrap_err().kind(), ErrorKind::AuthorizationTimedOut);
assert_eq!(calls.get(), 0);
}
#[tokio::test(start_paused = true)]
async fn stream_yields_the_url_before_the_outcome_and_then_ends() {
let events_within = |rule: Rule, timeout: Duration| async move {
let request = wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation));
let mut stream = std::pin::pin!(request.timeout(timeout).into_stream());
let mut events = Vec::new();
while let Some(event) = std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
events.push(match event {
Ok(Oauth2Event::AuthorizationUrl(url)) => format!("url {}", url.expose()),
Ok(Oauth2Event::Token(token)) => format!("token {}", token.expose()),
Err(error) => format!("error {:?}", error.kind()),
});
}
events
};
let events = |rule: Rule| events_within(rule, Duration::from_secs(600));
let rule = || mock!(Client::get_resource_oauth2_token).sequence();
let (url, token) = (format!("url {URL}"), "token TOKEN".to_owned());
let consent = rule().output(with_url).output(with_token).build();
assert_eq!(events(consent).await, [url.clone(), token.clone()]);
assert_eq!(events(rule().output(with_token).build()).await, [token]);
let denied = || HttpResponse::new(403u16.try_into().unwrap(), SdkBody::from("{}"));
let failed = rule().output(with_url).http_response(denied).build();
assert_eq!(events(failed).await, [url.clone(), "error Service".to_owned()]);
let timed_out = events_within(rule().output(with_url).build(), Duration::ZERO).await;
assert_eq!(timed_out, [url, "error AuthorizationTimedOut".to_owned()]);
}
#[tokio::test(start_paused = true)]
async fn request_started_within_the_budget_may_finish_after_it() {
let start = Instant::now();
let mut calls = 0;
let access = poller::poll(poller::INTERVAL, poller::BUDGET, || {
calls += 1;
let last = calls == 120;
async move {
if last {
tokio::time::sleep(Duration::from_secs(30)).await;
}
Ok(last.then(|| AccessToken::new("LATE")))
}
})
.await
.unwrap();
assert_eq!((access.expose(), calls, start.elapsed()), ("LATE", 120, Duration::from_secs(630)));
}
#[tokio::test(start_paused = true)]
async fn dropped_send_makes_no_further_request() {
let seen = Seen::new();
let rule = seen.rule().sequence().output(with_url).repeatedly().build();
let send = wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation)).send();
assert!(tokio::time::timeout(Duration::from_secs(12), send).await.is_err());
tokio::time::sleep(Duration::from_secs(60)).await;
assert_eq!(seen.seconds(), [0, 5, 10]);
}
#[derive(Debug)]
struct DeliveryFailed(String);
impl std::fmt::Display for DeliveryFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "could not deliver {}", self.0)
}
}
impl std::error::Error for DeliveryFailed {}
#[tokio::test(start_paused = true)]
async fn failed_callback_ends_the_send_without_polling_and_without_printing_its_cause() {
let seen = Seen::new();
let rule = seen.rule().sequence().output(with_url).repeatedly().build();
let error = wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation))
.on_auth_url(|url| async move { Err(DeliveryFailed(url.expose().to_owned())) })
.send()
.await
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::AuthorizationCallbackFailed);
assert_eq!(error.to_string(), "Failed to deliver the authorization URL");
assert_eq!(
format!("{error:?}"),
r#"Error { kind: AuthorizationCallbackFailed, message: "Failed to deliver the authorization URL", .. }"#
);
assert!(!format!("{error:#?}").contains("SENTINEL"), "{error:#?}");
assert_eq!(error.source().unwrap().downcast_ref::<DeliveryFailed>().unwrap().0, URL);
tokio::time::sleep(Duration::from_secs(60)).await;
assert_eq!(seen.seconds(), [0]);
}
#[tokio::test(start_paused = true)]
async fn failed_call_ends_the_send_with_the_sdk_error_as_its_source() {
let denied = || {
let body = SdkBody::from(r#"{"message":"SENTINEL-MESSAGE"}"#);
let mut response = HttpResponse::new(403u16.try_into().unwrap(), body);
response.headers_mut().insert("x-amzn-errortype", "AccessDeniedException");
response.headers_mut().insert("x-amzn-requestid", "request-1");
response
};
let first = mock!(Client::get_resource_oauth2_token).then_http_response(denied);
let later = mock!(Client::get_resource_oauth2_token).sequence().output(with_url).http_response(denied).build();
for (rule, calls) in [(first, 1), (later, 2)] {
let error =
wat(identity(&[&rule]).oauth2_token("orders", AuthFlow::UserFederation)).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::Service);
let text = "GetResourceOauth2Token for provider orders failed: AccessDeniedException (HTTP 403, request ID: request-1)";
assert_eq!(error.to_string(), text);
assert!(!format!("{error:?} {error:#?}").contains("SENTINEL"));
let source = error.source().unwrap().downcast_ref::<Oauth2SdkError>().unwrap();
assert!(source.as_service_error().is_some_and(GetResourceOauth2TokenError::is_access_denied_exception));
assert_eq!(rule.num_calls(), calls);
}
}
#[tokio::test(start_paused = true)]
async fn throttling_is_an_error_once_the_retries_of_the_sdk_are_used_up() {
let throttled = || {
let mut response =
HttpResponse::new(429u16.try_into().unwrap(), SdkBody::from(r#"{"message":"slow down"}"#));
response.headers_mut().insert("x-amzn-errortype", "ThrottlingException");
response.headers_mut().insert("x-amzn-requestid", "request-3");
response
};
let rule = mock!(Client::get_resource_oauth2_token).sequence().http_response(throttled).times(3).build();
let client = mock_client!(aws_sdk_bedrockagentcore, RuleMode::Sequential, [&rule], |config| {
config.retry_config(RetryConfig::standard().with_max_attempts(3))
});
let error =
wat(IdentityClient::from_client(client).oauth2_token("orders", AuthFlow::M2m)).send().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::Service);
let text =
"GetResourceOauth2Token for provider orders failed: ThrottlingException (HTTP 429, request ID: request-3)";
assert_eq!(error.to_string(), text);
let source = error.source().unwrap().downcast_ref::<Oauth2SdkError>().unwrap();
assert!(source.as_service_error().is_some_and(GetResourceOauth2TokenError::is_throttling_exception));
assert_eq!(rule.num_calls(), 3);
}
#[tokio::test(start_paused = true)]
async fn serialized_poll_request_has_the_session_uri_and_no_force_authentication() {
let reply = |body: &'static str| {
let request = http::Request::builder().body(SdkBody::empty()).unwrap();
ReplayEvent::new(request, http::Response::builder().status(200).body(SdkBody::from(body)).unwrap())
};
let http_client = StaticReplayClient::new(vec![
reply(r#"{"authorizationUrl":"https://consent.example","sessionUri":"urn:session:1"}"#),
reply(r#"{"accessToken":"TOKEN"}"#),
]);
let config = Config::builder()
.with_test_defaults_v2()
.region(Region::new("us-west-2"))
.http_client(http_client.clone())
.build();
let access = wat(
IdentityClient::from_client(Client::from_conf(config)).oauth2_token("orders", AuthFlow::UserFederation)
)
.force_authentication(true)
.send()
.await
.unwrap();
assert_eq!(access.expose(), "TOKEN");
let bodies: Vec<serde_json::Value> = http_client
.actual_requests()
.map(|request| serde_json::from_slice(request.body().bytes().unwrap()).unwrap())
.collect();
let [first, poll] = &bodies[..] else { panic!("two requests") };
assert_eq!(first["forceAuthentication"], true);
assert_eq!(first["scopes"], serde_json::json!([]));
assert!(first.get("sessionUri").is_none() && first.get("resources").is_none(), "{first}");
assert_eq!(poll["sessionUri"], "urn:session:1");
assert_eq!(poll["workloadIdentityToken"], "WAT");
assert!(poll.get("forceAuthentication").is_none(), "{poll}");
}
#[tokio::test(start_paused = true)]
async fn concurrent_consents_of_one_client_keep_their_own_token_across_polls() {
let seen = Seen::new();
let rules: Vec<_> = ["first", "second"]
.into_iter()
.map(|provider| {
let seen = seen.clone();
mock!(Client::get_resource_oauth2_token)
.match_requests(move |request| {
let matches = request.resource_credential_provider_name() == Some(provider);
if matches {
seen.requests.lock().unwrap().push((seen.start.elapsed(), request.clone()));
}
matches
})
.sequence()
.output(with_url)
.times(2)
.output(with_token)
.build()
})
.collect();
let identity = identity(&[&rules[0], &rules[1]]);
let send = |provider: &'static str, wat: &'static str| {
context::scope(ctx(wat), identity.oauth2_token(provider, AuthFlow::UserFederation).send())
};
let (first, second) = tokio::join!(send("first", "WAT-1"), send("second", "WAT-2"));
assert_eq!((first.unwrap().expose(), second.unwrap().expose()), ("TOKEN", "TOKEN"));
let requests = seen.requests();
assert_eq!(requests.len(), 6);
for request in requests {
let expected = if request.resource_credential_provider_name() == Some("first") { "WAT-1" } else { "WAT-2" };
assert_eq!(request.workload_identity_token(), Some(expected));
}
}
#[test]
fn debug_output_shows_which_sensitive_options_are_set_and_not_their_values() {
let rule = mock!(Client::get_resource_oauth2_token).then_output(with_token);
let request = identity(&[&rule])
.oauth2_token("orders", AuthFlow::UserFederation)
.workload_access_token(token("SECRET-TOKEN"))
.scopes(["read"])
.callback_url("https://SECRET.example/callback")
.custom_state("SECRET-STATE")
.custom_parameters([("SECRET-NAME", "SECRET-VALUE")])
.on_auth_url(|_| async { Ok::<_, std::io::Error>(()) });
let debug = format!(
"{request:?} {:?} {:?}",
AccessToken::new("SECRET-ACCESS"),
AuthorizationUrl::new("https://SECRET.example")
);
assert!(debug.contains(r#"provider: "orders", flow: UserFederation, scopes: ["read"]"#));
assert!(debug.contains("custom_state: true") && debug.contains("on_auth_url: true"));
assert!(!debug.contains("SECRET"));
}
}
mod propagation {
use std::{
io::Write,
sync::{Arc, Mutex},
};
use aws_sdk_bedrockagentcore::{
Config,
config::{
ConfigBag, Intercept, Layer, Region, RuntimeComponents, SharedHttpClient,
interceptors::{BeforeTransmitInterceptorContextMut, InterceptorContext},
retry::RetryConfig,
},
error::{BoxError, DisplayErrorContext},
primitives::Blob,
types::{Content, Conversational, PayloadType, Role},
};
use aws_smithy_http_client::test_util::infallible_client_fn;
use aws_smithy_runtime_api::client::{
interceptors::context::Input,
orchestrator::{HttpRequest, Metadata},
runtime_components::RuntimeComponentsBuilder,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use super::*;
use crate::context::WORKLOAD_ACCESS_TOKEN_HEADER as WAT_HEADER;
const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
const ARN: &str = "arn:aws:bedrock-agentcore:us-west-2:111122223333:runtime/other-agent";
#[derive(Clone, Default)]
struct Sent(Arc<Mutex<Vec<http::Request<()>>>>);
impl Sent {
fn http_client(&self, statuses: &'static [u16]) -> SharedHttpClient {
let sent = self.clone();
infallible_client_fn(move |request| {
let mut requests = sent.0.lock().unwrap();
let status = statuses.get(requests.len()).copied().unwrap_or(200);
requests.push(request.map(|_| ()));
http::Response::builder().status(status).body("{}").unwrap()
})
}
fn config(&self) -> aws_sdk_bedrockagentcore::config::Builder {
Config::builder()
.with_test_defaults_v2()
.region(Region::new("us-west-2"))
.http_client(self.http_client(&[]))
}
fn identity(&self) -> IdentityClient {
IdentityClient::from_client(Client::from_conf(self.config().build()))
}
fn take(&self) -> Vec<http::Request<()>> {
std::mem::take(&mut self.0.lock().unwrap())
}
fn tokens(&self) -> Vec<String> {
let [request] = &self.take()[..] else { panic!("one request") };
request.headers().get_all(WAT_HEADER).iter().map(|value| value.to_str().unwrap().to_owned()).collect()
}
}
async fn invoke_runtime(client: &Client, session: &str) {
let _ = client
.invoke_agent_runtime()
.agent_runtime_arn(ARN)
.runtime_session_id(session)
.payload(Blob::new("{}"))
.send()
.await;
}
async fn invoke_code_interpreter(client: &Client) {
let _ = client.invoke_code_interpreter().code_interpreter_identifier("aws.codeinterpreter.v1").send().await;
}
async fn create_event(client: &Client) {
let _ = client
.create_event()
.memory_id("memory-1234567890")
.actor_id("actor")
.event_timestamp(aws_sdk_bedrockagentcore::primitives::DateTime::from_secs(0))
.payload(PayloadType::Conversational(
Conversational::builder().content(Content::Text("hello".to_owned())).role(Role::User).build().unwrap(),
))
.send()
.await;
}
#[derive(Debug)]
struct Supplies(&'static str);
impl Intercept for Supplies {
fn name(&self) -> &'static str {
"Supplies"
}
fn modify_before_retry_loop(
&self,
context: &mut BeforeTransmitInterceptorContextMut<'_>,
_runtime_components: &RuntimeComponents,
_cfg: &mut ConfigBag,
) -> Result<(), BoxError> {
context.request_mut().headers_mut().insert(WAT_HEADER, self.0);
Ok(())
}
}
fn assert_wat_is_signed(request: &http::Request<()>) {
let authorization = request.headers()["authorization"].to_str().unwrap();
let (_, signed) = authorization.split_once("SignedHeaders=").expect("SigV4 signed headers");
let (signed, _) = signed.split_once(',').expect("SigV4 signature after the signed headers");
assert!(signed.split(';').any(|name| name == WAT_HEADER), "WAT header must be signed");
}
#[tokio::test]
async fn invocations_carry_the_signed_token_and_other_operations_do_not() {
let sent = Sent::default();
let from_client = sent.identity();
let sdk_config = SdkConfig::builder()
.behavior_version(BehaviorVersion::latest())
.region(Region::new("us-west-2"))
.credentials_provider(SharedCredentialsProvider::new(Credentials::for_tests()))
.http_client(sent.http_client(&[]))
.build();
let from_config = IdentityClient::new(&sdk_config);
for identity in [from_client, from_config] {
context::scope(ctx("AMBIENT-WAT"), async {
invoke_code_interpreter(identity.data_plane()).await;
invoke_runtime(identity.data_plane(), "session").await;
create_event(identity.data_plane()).await;
})
.await;
let [interpreter, runtime, event] = &sent.take()[..] else { panic!("three requests") };
for invocation in [interpreter, runtime] {
assert_eq!(invocation.headers()[WAT_HEADER], "AMBIENT-WAT", "{}", invocation.uri());
assert_wat_is_signed(invocation);
}
assert!(!event.headers().contains_key(WAT_HEADER), "{:?}", event.headers());
}
}
#[tokio::test]
async fn per_call_override_is_signed_and_the_next_invocation_uses_the_context_token() {
let sent = Sent::default();
let identity = sent.identity();
let invoke = identity.data_plane().invoke_agent_runtime().agent_runtime_arn(ARN).payload(Blob::new("{}"));
context::scope(ctx("AMBIENT-WAT"), async {
let _ = invoke
.clone()
.customize()
.mutate_request(|request| {
let headers = request.headers_mut();
assert!(headers.get(WAT_HEADER) == Some("AMBIENT-WAT"), "forwarding must run first");
assert!(headers.get("authorization").is_none(), "signing must run after customization");
headers.insert(WAT_HEADER, "OVERRIDE-WAT");
})
.send()
.await;
let _ = invoke.send().await;
})
.await;
let [customized, ordinary] = &sent.take()[..] else { panic!("expected two invocations") };
for (request, expected) in [(customized, "OVERRIDE-WAT"), (ordinary, "AMBIENT-WAT")] {
assert!(request.headers().get_all(WAT_HEADER).iter().eq([expected]), "expected exactly one WAT value");
assert_wat_is_signed(request);
}
}
#[tokio::test]
async fn header_is_replaced_by_a_token_of_the_context_and_kept_without_one() {
let sent = Sent::default();
let plain = sent.identity();
let supplied =
IdentityClient::from_client(Client::from_conf(sent.config().interceptor(Supplies("SUPPLIED")).build()));
let no_token = RequestContext::builder("session").build();
context::scope(ctx("AMBIENT-WAT"), invoke_runtime(supplied.data_plane(), "s")).await;
assert_eq!(sent.tokens(), ["AMBIENT-WAT"], "one value, of the context");
invoke_runtime(supplied.data_plane(), "s").await;
assert_eq!(sent.tokens(), ["SUPPLIED"]);
for ctx in [no_token, ctx("")] {
context::scope(ctx.clone(), invoke_runtime(supplied.data_plane(), "s")).await;
assert_eq!(sent.tokens(), ["SUPPLIED"]);
context::scope(ctx, invoke_runtime(plain.data_plane(), "s")).await;
assert_eq!(sent.tokens(), [""; 0]);
}
context::scope(ctx("AMBIENT-WAT"), async {
let client = plain.data_plane().clone();
tokio::spawn(async move { invoke_runtime(&client, "s").await }).await.unwrap();
})
.await;
assert_eq!(sent.tokens(), [""; 0]);
}
#[test]
fn rule_selects_operations_by_the_invoke_prefix_of_their_name() {
let headers_after = |operation: Option<&'static str>| {
let mut bag = ConfigBag::base();
if let Some(operation) = operation {
let mut layer = Layer::new("test");
layer.store_put(Metadata::new(operation, "bedrock-agentcore"));
bag.push_layer(layer);
}
let mut context = InterceptorContext::new(Input::doesnt_matter());
context.enter_serialization_phase();
let _ = context.take_input();
context.set_request(HttpRequest::empty());
context.enter_before_transmit_phase();
let components = RuntimeComponentsBuilder::for_tests().build().unwrap();
WatPropagation::new().modify_before_signing(&mut (&mut context).into(), &components, &mut bag).unwrap();
context.request().unwrap().headers().get(WAT_HEADER).map(str::to_owned)
};
let _scope = tokio::runtime::Builder::new_current_thread().build().unwrap();
let cases = [
(Some("InvokeAgentRuntime"), true),
(Some("InvokeBrowser"), true),
(Some("InvokeAnOperationOfALaterVersion"), true),
(Some("CreateEvent"), false),
(Some("GetResourceApiKey"), false),
(Some("invokeLowercase"), false),
(None, false),
];
for (operation, forwarded) in cases {
let header = _scope.block_on(context::scope(ctx("AMBIENT-WAT"), async { headers_after(operation) }));
assert_eq!(header.as_deref(), forwarded.then_some("AMBIENT-WAT"), "{operation:?}");
}
}
#[tokio::test]
async fn token_that_is_not_a_header_value_fails_the_operation_without_showing_it() {
let sent = Sent::default();
let identity = sent.identity();
let error = context::scope(ctx("SENTINEL\nWAT"), async {
identity.data_plane().invoke_agent_runtime().agent_runtime_arn(ARN).payload(Blob::new("{}")).send().await
})
.await
.unwrap_err();
let text = format!("{error:?} {}", DisplayErrorContext(&error));
assert!(text.contains("the workload access token is not a valid HTTP header value"), "{text}");
assert!(!text.contains("SENTINEL"), "{text}");
assert!(sent.take().is_empty());
}
#[tokio::test(start_paused = true)]
async fn every_attempt_of_a_retried_invocation_carries_the_token() {
let sent = Sent::default();
let config = sent
.config()
.http_client(sent.http_client(&[500, 500]))
.retry_config(RetryConfig::standard().with_max_attempts(3));
let identity = IdentityClient::from_client(Client::from_conf(config.build()));
context::scope(ctx("AMBIENT-WAT"), invoke_runtime(identity.data_plane(), "s")).await;
let attempts = sent.take();
assert_eq!(attempts.len(), 3);
assert!(attempts.iter().all(|attempt| attempt.headers()[WAT_HEADER] == "AMBIENT-WAT"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_invocations_of_one_client_carry_the_token_of_their_own_context() {
let sent = Sent::default();
let identity = sent.identity();
let tasks: Vec<_> = (0..32)
.map(|i| {
let identity = identity.clone();
let name = format!("caller-{i}-padded-to-the-length-of-a-session-id");
tokio::spawn(context::scope(ctx(&name), async move {
tokio::task::yield_now().await;
invoke_runtime(identity.data_plane(), &name).await;
}))
})
.collect();
for task in tasks {
task.await.unwrap();
}
let requests = sent.take();
assert_eq!(requests.len(), 32);
for request in requests {
assert_eq!(request.headers()[WAT_HEADER], request.headers()[SESSION_HEADER]);
}
}
#[tokio::test]
async fn interceptor_is_added_once_and_the_configuration_of_the_client_is_kept() {
let sent = Sent::default();
let installed = |client: &Client| {
client.config().interceptors().filter(|interceptor| interceptor.name().ends_with("WatPropagation")).count()
};
let original = Client::from_conf(sent.config().interceptor(Supplies("SUPPLIED")).build());
assert_eq!(installed(&original), 0);
let identity = IdentityClient::from_client(original);
let again = IdentityClient::from_client(identity.data_plane().clone());
let own =
IdentityClient::from_client(Client::from_conf(sent.config().interceptor(WatPropagation::new()).build()));
for identity in [&identity, &again, &own, &identity.clone()] {
assert_eq!(installed(identity.data_plane()), 1);
}
invoke_runtime(again.data_plane(), "s").await;
assert_eq!(sent.tokens(), ["SUPPLIED"]);
let _ = again.api_key("orders").workload_access_token(token("WAT")).send().await;
assert_eq!(sent.take().len(), 1);
}
async fn connection_numbering_server() -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
let mut connection = 0;
loop {
connection += 1;
let (mut stream, _) = listener.accept().await.unwrap();
tokio::spawn(async move {
let mut received = Vec::new();
let mut buffer = [0; 4096];
loop {
let head_end = loop {
if let Some(at) = received.windows(4).position(|window| window == b"\r\n\r\n") {
break at + 4;
}
match stream.read(&mut buffer).await {
Ok(read) if read > 0 => received.extend_from_slice(&buffer[..read]),
_ => return,
}
};
let head = String::from_utf8_lossy(&received[..head_end]).to_lowercase();
let length: usize = head
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.map_or(0, |value| value.trim().parse().unwrap());
while received.len() < head_end + length {
match stream.read(&mut buffer).await {
Ok(read) if read > 0 => received.extend_from_slice(&buffer[..read]),
_ => return,
}
}
received.drain(..head_end + length);
let body = format!(r#"{{"apiKey":"{connection}"}}"#);
let reply = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{body}",
body.len()
);
if stream.write_all(reply.as_bytes()).await.is_err() {
return;
}
}
});
}
});
format!("http://{address}")
}
async fn connection_of(client: &Client) -> String {
client
.get_resource_api_key()
.resource_credential_provider_name("orders")
.workload_identity_token("WAT")
.send()
.await
.unwrap()
.api_key
}
async fn connection_of_identity(identity: &IdentityClient) -> String {
identity.api_key("orders").workload_access_token(token("WAT")).send().await.unwrap().expose().to_owned()
}
#[tokio::test]
async fn wrapped_client_reuses_the_connection_of_the_original_client() {
let endpoint = connection_numbering_server().await;
let config = || {
Config::builder()
.behavior_version(BehaviorVersion::latest())
.region(Region::new("us-west-2"))
.credentials_provider(Credentials::for_tests())
.endpoint_url(&endpoint)
};
let explicit =
Client::from_conf(config().http_client(aws_smithy_http_client::Builder::new().build_http()).build());
let first = connection_of(&explicit).await;
let identity = IdentityClient::from_client(explicit.clone());
assert_eq!(connection_of_identity(&identity).await, first);
assert_eq!(connection_of_identity(&identity.clone()).await, first);
assert_eq!(connection_of(identity.data_plane()).await, first);
assert_eq!(connection_of(&explicit).await, first);
let prepared = Client::from_conf(config().interceptor(WatPropagation::new()).build());
let second = connection_of(&prepared).await;
assert_ne!(second, first);
let identity = IdentityClient::from_client(prepared.clone());
assert_eq!(connection_of_identity(&identity).await, second);
assert_eq!(connection_of_identity(&identity.clone()).await, second);
assert_eq!(connection_of(&prepared).await, second);
}
#[derive(Clone, Default)]
struct Log(Arc<Mutex<Vec<u8>>>);
impl Write for Log {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
async fn log_of_an_invocation(level: tracing::Level) -> String {
let log = Log::default();
let writer = log.clone();
let subscriber = tracing_subscriber::fmt()
.with_max_level(level)
.with_ansi(false)
.with_writer(move || writer.clone())
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
let endpoint = connection_numbering_server().await;
let config = Config::builder()
.behavior_version(BehaviorVersion::latest())
.region(Region::new("us-west-2"))
.credentials_provider(Credentials::for_tests())
.endpoint_url(&endpoint)
.build();
let identity = IdentityClient::from_client(Client::from_conf(config));
context::scope(ctx("SENTINEL-WAT"), invoke_runtime(identity.data_plane(), "s")).await;
String::from_utf8(std::mem::take(&mut log.0.lock().unwrap())).unwrap()
}
#[tokio::test]
async fn dependencies_do_not_log_the_token_at_debug_and_above() {
for level in [tracing::Level::INFO, tracing::Level::DEBUG] {
let log = log_of_an_invocation(level).await;
assert!(!log.contains("SENTINEL"), "{level}: {log}");
}
assert!(
log_of_an_invocation(tracing::Level::DEBUG).await.contains("InvokeAgentRuntime"),
"the log is captured"
);
}
}
mod workload_identity {
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use aws_credential_types::{
Credentials,
provider::{ProvideCredentials, SharedCredentialsProvider},
};
use aws_sdk_bedrockagentcore::{
config::Region,
primitives::{ByteStream, SdkBody},
};
use aws_smithy_async::{
rt::sleep::{SharedAsyncSleep, TokioSleep},
time::TimeSource,
};
use aws_smithy_http_client::test_util::infallible_client_fn;
use aws_types::SdkConfig;
use futures_util::FutureExt;
use serde_json::{Value, json};
use crate::{RequestContext, context, identity::WorkloadIdentityCredentials};
const START: u64 = 1_800_000_000;
#[derive(Clone, Debug)]
struct Clock(Arc<Mutex<SystemTime>>);
impl Clock {
fn advance(&self, seconds: u64) {
*self.0.lock().unwrap() += Duration::from_secs(seconds);
}
}
impl TimeSource for Clock {
fn now(&self) -> SystemTime {
*self.0.lock().unwrap()
}
}
type Reply = (u16, &'static str, Value);
type Outcome = Result<&'static str, &'static str>;
#[derive(Clone, Default)]
struct DataPlane {
replies: Arc<Mutex<VecDeque<Reply>>>,
requests: Arc<Mutex<Vec<(Value, String)>>>,
}
impl DataPlane {
fn reply(&self, status: u16, error_type: &'static str, body: Value) {
self.replies.lock().unwrap().push_back((status, error_type, body));
}
fn issue(&self, key: &str, lifetime: u64, refresh_token: Option<&str>) {
let body = json!({
"credentials": {
"accessKeyId": key,
"secretAccessKey": "SECRET-KEY",
"sessionToken": "SECRET-SESSION",
"expiration": START + lifetime,
},
"assumedRoleArn": "arn:aws:sts::111122223333:assumed-role/agent/session",
"refreshToken": refresh_token,
"refreshTokenExpiration": "2027-01-15T10:00:00Z",
});
self.reply(200, "", body);
}
fn modes(&self) -> Vec<String> {
let requests = self.requests.lock().unwrap();
requests.iter().map(|(body, _)| body["mode"].to_string()).collect()
}
fn provider(&self) -> (WorkloadIdentityCredentials, Clock) {
let clock = Clock(Arc::new(Mutex::new(UNIX_EPOCH + Duration::from_secs(START))));
let data_plane = self.clone();
let http_client = infallible_client_fn(move |request: http::Request<SdkBody>| {
assert_eq!(request.uri().path(), "/identities/GetIAMWorkloadIdentityCredentials");
assert!(request.headers()["user-agent"].to_str().unwrap().starts_with("bedrock-agentcore-rust/"));
let authorization = request.headers()["authorization"].to_str().unwrap().to_owned();
assert!(request.body().bytes().is_none());
let body = ByteStream::new(request.into_body()).collect().now_or_never().unwrap().unwrap();
let body = serde_json::from_slice(&body.into_bytes()).unwrap();
data_plane.requests.lock().unwrap().push((body, authorization));
let (status, error_type, body) =
data_plane.replies.lock().unwrap().pop_front().expect("an exchange that the test did not expect");
let reply = http::Response::builder().status(status).header("x-amzn-errortype", error_type);
reply.body(SdkBody::from(body.to_string())).unwrap()
});
let config = SdkConfig::builder()
.region(Region::new("us-west-2"))
.credentials_provider(SharedCredentialsProvider::new(Credentials::for_tests()))
.http_client(http_client)
.time_source(clock.clone())
.sleep_impl(SharedAsyncSleep::new(TokioSleep::new()))
.build();
(WorkloadIdentityCredentials::new(&config), clock)
}
}
fn request(session: &str, workload_identity_context: Option<&str>) -> RequestContext {
let builder = RequestContext::builder(session);
workload_identity_context
.map_or_else(|| RequestContext::builder(session), |c| builder.workload_identity_context(c))
.build()
}
async fn key(provider: &WorkloadIdentityCredentials, ctx: &RequestContext) -> String {
let credentials = context::scope(ctx.clone(), provider.provide_credentials()).await;
credentials.expect("credentials").access_key_id().to_owned()
}
#[tokio::test]
async fn each_session_gets_the_credentials_of_its_own_context() {
let data_plane = DataPlane::default();
let (provider, clock) = data_plane.provider();
let base = Credentials::for_tests().access_key_id().to_owned();
assert_eq!(provider.provide_credentials().await.unwrap().access_key_id(), base);
assert_eq!(key(&provider, &request("session-0", None)).await, base);
assert!(data_plane.modes().is_empty());
data_plane.issue("DECORATED-1", 3600, None);
let first = request("session-1", Some("CONTEXT-1"));
let credentials = context::scope(first.clone(), provider.provide_credentials()).await.unwrap();
assert_eq!(credentials.access_key_id(), "DECORATED-1");
assert_eq!(credentials.expiry(), Some(UNIX_EPOCH + Duration::from_secs(START + 3600)));
assert_eq!(credentials.account_id().map(|account| account.as_str()), Some("111122223333"));
let authorization = data_plane.requests.lock().unwrap()[0].1.clone();
let scope = format!("Credential={base}/20270115/us-west-2/bedrock-agentcore/aws4_request");
assert!(authorization.contains(&scope), "{authorization}");
assert_eq!(key(&provider, &first).await, "DECORATED-1");
assert_eq!(provider.provide_credentials().await.unwrap().access_key_id(), "DECORATED-1");
data_plane.issue("DECORATED-2", 2 * 3600, Some("REFRESH-2"));
let second = request("session-2", Some("CONTEXT-2"));
assert_eq!(key(&provider, &second).await, "DECORATED-2");
assert_eq!(provider.provide_credentials().await.unwrap().access_key_id(), "DECORATED-2");
assert_eq!(key(&provider, &first).await, "DECORATED-1");
clock.advance(46 * 60);
data_plane.issue("DECORATED-1B", 2 * 3600, None);
assert_eq!(key(&provider, &first).await, "DECORATED-1B");
assert_eq!(key(&provider, &second).await, "DECORATED-2");
assert_eq!(
data_plane.modes(),
[
r#"{"issue":{"encryptedContext":"CONTEXT-1"}}"#,
r#"{"issue":{"encryptedContext":"CONTEXT-2"}}"#,
r#"{"issue":{"encryptedContext":"CONTEXT-1"}}"#,
]
);
let error = context::scope(request("session-3", None), provider.provide_credentials()).await.unwrap_err();
let text = std::error::Error::source(&error).unwrap().to_string();
assert_eq!(text, "the session has no workload identity context");
let debug = format!("{provider:?} {first:?}");
assert!(!debug.contains("CONTEXT") && !debug.contains("SECRET"), "{debug}");
}
#[tokio::test]
async fn credentials_are_renewed_before_they_expire_and_a_failed_renewal_fails_closed() {
let data_plane = DataPlane::default();
let (provider, clock) = data_plane.provider();
let ctx = request("session-1", Some("CONTEXT-1"));
let base = Credentials::for_tests().access_key_id().to_owned();
data_plane.issue("DECORATED-1", 3600, Some("REFRESH-1"));
assert_eq!(key(&provider, &ctx).await, "DECORATED-1");
clock.advance(44 * 60);
assert_eq!(key(&provider, &ctx).await, "DECORATED-1");
clock.advance(2 * 60);
data_plane.issue("DECORATED-2", 2 * 3600, None);
assert_eq!(key(&provider, &ctx).await, "DECORATED-2");
clock.advance(3600);
data_plane.reply(400, "ValidationException", json!({}));
data_plane.issue("DECORATED-3", 3 * 3600, Some("REFRESH-3"));
assert_eq!(key(&provider, &ctx).await, "DECORATED-3");
assert_eq!(
data_plane.modes(),
[
r#"{"issue":{"encryptedContext":"CONTEXT-1"}}"#,
r#"{"refresh":{"refreshToken":"REFRESH-1"}}"#,
r#"{"refresh":{"refreshToken":"REFRESH-1"}}"#,
r#"{"issue":{"encryptedContext":"CONTEXT-1"}}"#,
]
);
clock.advance(3600);
data_plane.reply(403, "AccessDeniedException:http://internal.amazon.com/coral/", json!({}));
assert_eq!(key(&provider, &ctx).await, "DECORATED-3");
clock.advance(5 * 60);
data_plane.reply(403, "", json!({ "__type": "com.amazon.coral.service#AccessDeniedException" }));
let error = context::scope(ctx.clone(), provider.provide_credentials()).await.unwrap_err();
let text = format!("{error} {error:?} {}", std::error::Error::source(&error).unwrap());
assert!(text.contains("GetIAMWorkloadIdentityCredentials failed: HTTP 403 (AccessDeniedException)"), "{text}");
assert!(!text.contains("CONTEXT") && !text.contains("REFRESH") && !text.contains(&base), "{text}");
assert!(data_plane.replies.lock().unwrap().is_empty(), "a reply was not requested");
}
#[tokio::test(start_paused = true)]
async fn exchange_outcomes() {
let issued = || json!({ "credentials": { "accessKeyId": "DECORATED", "secretAccessKey": "s", "sessionToken": "t", "expiration": "2027-01-15T09:00:00Z" } });
let cases: [(&[(u16, Value)], Outcome); 5] = [
(&[(200, issued())], Ok("DECORATED")),
(&[(429, json!({})), (503, json!({})), (200, issued())], Ok("DECORATED")),
(&[(500, json!({})), (500, json!({})), (500, json!({})), (500, json!({}))], Err("HTTP 500")),
(&[(200, json!({ "credentials": { "accessKeyId": "DECORATED" } }))], Err("HTTP 200 (UnexpectedResponse)")),
(&[(404, json!({ "code": "ResourceNotFoundException" }))], Err("HTTP 404 (ResourceNotFoundException)")),
];
for (replies, expected) in cases {
let data_plane = DataPlane::default();
let (provider, _clock) = data_plane.provider();
for (status, body) in replies {
data_plane.reply(*status, "", body.clone());
}
let ctx = request("session-1", Some("CONTEXT-1"));
let result = context::scope(ctx, provider.provide_credentials()).await;
let outcome = result
.as_ref()
.map(Credentials::access_key_id)
.map_err(|error| std::error::Error::source(error).unwrap().to_string());
match expected {
Ok(key) => assert_eq!(outcome.as_deref(), Ok(key), "{replies:?}"),
Err(text) => {
assert!(outcome.as_ref().is_err_and(|error| error.ends_with(text)), "{replies:?}: {outcome:?}")
}
}
assert!(data_plane.replies.lock().unwrap().is_empty(), "{replies:?}: a reply was not requested");
}
}
#[tokio::test]
async fn service_without_the_operation_gets_the_execution_role_credentials_and_is_asked_again_later() {
let data_plane = DataPlane::default();
let (provider, clock) = data_plane.provider();
let ctx = request("session-1", Some("CONTEXT-1"));
let base = Credentials::for_tests().access_key_id().to_owned();
let unknown = || data_plane.reply(404, "UnknownOperationException", json!({}));
unknown();
assert_eq!(key(&provider, &ctx).await, base);
clock.advance(29);
assert_eq!(key(&provider, &ctx).await, base);
clock.advance(2);
unknown();
assert_eq!(key(&provider, &ctx).await, base);
clock.advance(59);
assert_eq!(key(&provider, &ctx).await, base);
assert_eq!(data_plane.modes().len(), 2);
clock.advance(2);
data_plane.issue("DECORATED-1", 3600, None);
assert_eq!(key(&provider, &ctx).await, "DECORATED-1");
}
}