use std::{
collections::HashMap,
fmt,
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use aws_credential_types::{
Credentials,
provider::{self, ProvideCredentials, SharedCredentialsProvider, error::CredentialsError, future},
};
use aws_runtime::auth::{PayloadSigningOverride, SigV4OperationSigningConfig, sigv4};
use aws_sdk_bedrockagentcore::config::endpoint::{DefaultResolver, Params, ResolveEndpoint};
use aws_smithy_async::time::SharedTimeSource;
use aws_smithy_runtime::client::{
identity::IdentityCache,
orchestrator::operation::Operation,
retries::classifiers::{HttpStatusCodeClassifier, TransientErrorClassifier},
};
use aws_smithy_runtime_api::client::{
auth::{AuthSchemeOptionResolverParams, SharedAuthScheme, static_resolver::StaticAuthSchemeOptionResolver},
identity::SharedIdentityResolver,
orchestrator::{HttpRequest, HttpResponse, OrchestratorError, SensitiveOutput},
result::SdkError,
runtime_components::RuntimeComponentsBuilder,
runtime_plugin::StaticRuntimePlugin,
};
use aws_smithy_types::{
DateTime, body::SdkBody, config_bag::Layer, date_time::Format, retry::RetryConfig, timeout::TimeoutConfig,
};
use aws_types::{SdkConfig, SigningName, region::SigningRegion};
use bytes::Bytes;
use http_body_util::Full;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use crate::context::{self, WorkloadIdentityContexts};
const OPERATION: &str = "GetIAMWorkloadIdentityCredentials";
const PATH: &str = "/identities/GetIAMWorkloadIdentityCredentials";
const UNKNOWN_OPERATION: &str = "UnknownOperationException";
const USER_AGENT: &str =
concat!("bedrock-agentcore-rust/", env!("CARGO_PKG_VERSION"), " (feature=workload-identity-credentials)");
const REFRESH_BEFORE_EXPIRY: Duration = Duration::from_secs(15 * 60);
const REFRESH_REQUIRED_BEFORE_EXPIRY: Duration = Duration::from_secs(10 * 60);
const REFRESH_TOKEN_MARGIN: Duration = Duration::from_secs(60);
const UNAVAILABLE_BACKOFF: Duration = Duration::from_secs(30);
const UNAVAILABLE_BACKOFF_MAX: Duration = Duration::from_secs(5 * 60);
#[derive(Clone)]
pub struct WorkloadIdentityCredentials {
inner: Arc<Inner>,
}
struct Inner {
config: SdkConfig,
time: SharedTimeSource,
state: tokio::sync::Mutex<State>,
}
#[derive(Default)]
struct State {
latest: Option<(String, WorkloadIdentityContexts)>,
issued: HashMap<String, Issued>,
unavailable_until: Option<SystemTime>,
unavailable_backoff: Duration,
}
struct Issued {
credentials: Credentials,
refresh_token: Option<String>,
refresh_token_expiration: Option<SystemTime>,
}
impl fmt::Debug for Issued {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Issued").field("expiry", &self.credentials.expiry()).finish_non_exhaustive()
}
}
struct ExchangeRequest(Bytes);
impl fmt::Debug for ExchangeRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ExchangeRequest")
}
}
#[derive(Debug)]
struct ExchangeError {
status: Option<u16>,
code: Option<String>,
}
impl ExchangeError {
const UNEXPECTED_RESPONSE: &str = "UnexpectedResponse";
fn is(&self, code: &str) -> bool {
self.code.as_deref() == Some(code)
}
}
impl fmt::Display for ExchangeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{OPERATION} failed")?;
if let Some(status) = self.status {
write!(f, ": HTTP {status}")?;
}
if let Some(code) = &self.code {
write!(f, " ({code})")?;
}
Ok(())
}
}
impl std::error::Error for ExchangeError {}
impl WorkloadIdentityCredentials {
pub fn new(config: &SdkConfig) -> Self {
let time = config.time_source().unwrap_or_default();
Self { inner: Arc::new(Inner { config: config.clone(), time, state: tokio::sync::Mutex::default() }) }
}
pub fn configure(config: &SdkConfig) -> SdkConfig {
config
.to_builder()
.credentials_provider(SharedCredentialsProvider::new(Self::new(config)))
.identity_cache(IdentityCache::no_cache())
.build()
}
async fn base(&self) -> provider::Result {
match self.inner.config.credentials_provider() {
Some(base) => base.provide_credentials().await,
None => Err(CredentialsError::not_loaded("the configuration has no credentials provider")),
}
}
async fn resolve(&self) -> provider::Result {
let mut state = self.inner.state.lock().await;
let current =
context::current().map(|ctx| (ctx.session_id().to_owned(), ctx.workload_identity_contexts().clone()));
let in_request = current.is_some();
let found = current.or_else(|| state.latest.clone()).and_then(|(session, contexts)| {
let context = contexts.get(&session)?;
Some((session, contexts, context))
});
let Some((session, contexts, context)) = found else {
if in_request && state.latest.is_some() {
return Err(CredentialsError::provider_error("the session has no workload identity context"));
}
return self.base().await;
};
state.latest = Some((session.clone(), contexts));
let now = self.inner.time.now();
if state.unavailable_until.is_some_and(|until| now < until) {
return self.base().await;
}
let current = state.issued.get(&session).map(|issued| issued.credentials.clone());
let expiry = current.as_ref().and_then(Credentials::expiry);
let remaining = expiry.and_then(|expiry| expiry.duration_since(now).ok()).unwrap_or_default();
if let Some(current) = ¤t
&& remaining > REFRESH_BEFORE_EXPIRY
{
return Ok(current.clone());
}
match self.obtain(state.issued.get(&session), &context, now).await {
Ok(mut issued) => {
if state.unavailable_until.take().is_some() {
tracing::warn!("workload identity credentials are available again");
}
state.unavailable_backoff = Duration::ZERO;
if issued.refresh_token.is_none()
&& let Some(previous) = state.issued.remove(&session)
{
issued.refresh_token = previous.refresh_token;
issued.refresh_token_expiration = previous.refresh_token_expiration;
}
let credentials = issued.credentials.clone();
state.issued.retain(|_, issued| issued.credentials.expiry().is_some_and(|expiry| now < expiry));
state.issued.insert(session, issued);
Ok(credentials)
}
Err(error) if error.is(UNKNOWN_OPERATION) => {
let backoff = (state.unavailable_backoff * 2).clamp(UNAVAILABLE_BACKOFF, UNAVAILABLE_BACKOFF_MAX);
if state.unavailable_until.is_none() {
tracing::warn!(
seconds = backoff.as_secs(),
"workload identity credentials are not available, using the execution role credentials"
);
}
state.unavailable_backoff = backoff;
state.unavailable_until = Some(now + backoff);
self.base().await
}
Err(error) => match current {
Some(current) if remaining > REFRESH_REQUIRED_BEFORE_EXPIRY => {
tracing::warn!(%error, "workload identity credentials were not renewed, using the current ones");
Ok(current)
}
_ => Err(CredentialsError::provider_error(error)),
},
}
}
async fn obtain(&self, current: Option<&Issued>, context: &str, now: SystemTime) -> Result<Issued, ExchangeError> {
let refresh_token = current.and_then(|issued| {
let usable =
issued.refresh_token_expiration.is_none_or(|expiration| now + REFRESH_TOKEN_MARGIN < expiration);
issued.refresh_token.as_ref().filter(|_| usable)
});
if let Some(refresh_token) = refresh_token {
match self.call(json!({ "mode": { "refresh": { "refreshToken": refresh_token } } })).await {
Err(error) if error.status == Some(400) => {}
result => return result,
}
}
self.call(json!({ "mode": { "issue": { "encryptedContext": context } } })).await
}
async fn call(&self, body: Value) -> Result<Issued, ExchangeError> {
let config = &self.inner.config;
let failed = |code: &str| ExchangeError { status: None, code: Some(code.to_owned()) };
let region = config.region().ok_or_else(|| failed("NoRegion"))?;
let params = Params::builder()
.region(region.as_ref())
.set_endpoint(config.endpoint_url().map(str::to_owned))
.set_use_fips(config.use_fips())
.set_use_dual_stack(config.use_dual_stack())
.build()
.map_err(|_| failed("NoEndpoint"))?;
let endpoint = DefaultResolver::new().resolve_endpoint(¶ms).await.map_err(|_| failed("NoEndpoint"))?;
let base = config.credentials_provider().ok_or_else(|| failed("NoCredentialsProvider"))?;
let mut layer = Layer::new("WorkloadIdentityCredentials");
layer.store_put(AuthSchemeOptionResolverParams::new(()));
layer.store_put(SigV4OperationSigningConfig {
region: Some(SigningRegion::from(region.clone())),
name: Some(SigningName::from_static("bedrock-agentcore")),
..Default::default()
});
layer.store_put(SensitiveOutput);
let body = Bytes::from(body.to_string());
let hash: String = Sha256::digest(&body).iter().map(|byte| format!("{byte:02x}")).collect();
layer.store_put(PayloadSigningOverride::Precomputed(hash));
let auth = RuntimeComponentsBuilder::new("WorkloadIdentityCredentials")
.with_auth_scheme_option_resolver(Some(StaticAuthSchemeOptionResolver::new(vec![sigv4::SCHEME_ID])))
.with_auth_scheme(SharedAuthScheme::new(sigv4::SigV4AuthScheme::new()))
.with_identity_cache(Some(IdentityCache::no_cache()))
.with_identity_resolver(sigv4::SCHEME_ID, SharedIdentityResolver::new(base));
let mut operation = Operation::builder()
.service_name("bedrock-agentcore")
.operation_name(OPERATION)
.endpoint_url(endpoint.url())
.runtime_plugin(StaticRuntimePlugin::new().with_config(layer.freeze()).with_runtime_components(auth))
.time_source(self.inner.time.clone())
.timeout_config(
TimeoutConfig::builder()
.connect_timeout(Duration::from_secs(2))
.read_timeout(Duration::from_secs(5))
.build(),
)
.standard_retry(&RetryConfig::standard().with_max_attempts(4))
.retry_classifier(TransientErrorClassifier::<ExchangeError>::new())
.retry_classifier(HttpStatusCodeClassifier::new_from_codes(vec![429, 500, 502, 503, 504]))
.serializer(|body: ExchangeRequest| {
let request = http::Request::post(PATH)
.header(http::header::CONTENT_TYPE, "application/json")
.header(http::header::USER_AGENT, USER_AGENT);
let request = request.header(http::header::CONTENT_LENGTH, body.0.len());
let stream = SdkBody::retryable(move || SdkBody::from_body_1_x(Full::new(body.0.clone())));
Ok(HttpRequest::try_from(request.body(stream)?)?)
})
.deserializer(parse);
if let Some(http_client) = config.http_client() {
operation = operation.http_client(http_client);
}
if let Some(sleep) = config.sleep_impl() {
operation = operation.sleep_impl(sleep);
}
operation.build().invoke(ExchangeRequest(body)).await.map_err(|error| match error {
SdkError::ServiceError(error) => error.into_err(),
SdkError::TimeoutError(_) => failed("Timeout"),
SdkError::ResponseError(_) => failed(ExchangeError::UNEXPECTED_RESPONSE),
_ => failed("RequestNotSent"),
})
}
}
fn parse(response: &HttpResponse) -> Result<Issued, OrchestratorError<ExchangeError>> {
let status = response.status().as_u16();
let body: Option<Value> = response.body().bytes().and_then(|bytes| serde_json::from_slice(bytes).ok());
let failed = |code: Option<&str>| {
OrchestratorError::operation(ExchangeError { status: Some(status), code: code.map(str::to_owned) })
};
if !response.status().is_success() {
let code = response.headers().get("x-amzn-errortype").filter(|code| !code.is_empty()).or_else(|| {
let body = body.as_ref()?;
["__type", "code", "Code"].iter().find_map(|name| body.get(name)?.as_str())
});
let code = code.map(|code| code.split(':').next().unwrap_or(code).rsplit('#').next().unwrap_or(code));
return Err(failed(code));
}
issued(body.as_ref()).ok_or_else(|| failed(Some(ExchangeError::UNEXPECTED_RESPONSE)))
}
fn issued(body: Option<&Value>) -> Option<Issued> {
let body = body?;
let credentials = body.get("credentials")?;
let text = |value: &Value, name: &str| value.get(name).and_then(Value::as_str).map(str::to_owned);
let mut builder = Credentials::builder()
.access_key_id(text(credentials, "accessKeyId")?)
.secret_access_key(text(credentials, "secretAccessKey")?)
.session_token(text(credentials, "sessionToken")?)
.expiry(time(credentials.get("expiration")?)?)
.provider_name("AgentCoreWorkloadIdentity");
let account = text(body, "assumedRoleArn").and_then(|arn| arn.split(':').nth(4).map(str::to_owned));
if let Some(account) = account.filter(|account| !account.is_empty()) {
builder = builder.account_id(account);
}
Some(Issued {
credentials: builder.build(),
refresh_token: text(body, "refreshToken"),
refresh_token_expiration: body.get("refreshTokenExpiration").and_then(time),
})
}
fn time(value: &Value) -> Option<SystemTime> {
match value {
Value::Number(seconds) => UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(seconds.as_f64()?).ok()?),
Value::String(text) => DateTime::from_str(text, Format::DateTimeWithOffset).ok()?.try_into().ok(),
_ => None,
}
}
impl ProvideCredentials for WorkloadIdentityCredentials {
fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>
where
Self: 'a,
{
future::ProvideCredentials::new(self.resolve())
}
}
impl fmt::Debug for WorkloadIdentityCredentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WorkloadIdentityCredentials").finish_non_exhaustive()
}
}