bedrock_agentcore/identity/
workload_identity.rs1use std::{
4 collections::HashMap,
5 fmt,
6 sync::Arc,
7 time::{Duration, SystemTime, UNIX_EPOCH},
8};
9
10use aws_credential_types::{
11 Credentials,
12 provider::{self, ProvideCredentials, SharedCredentialsProvider, error::CredentialsError, future},
13};
14use aws_runtime::auth::{PayloadSigningOverride, SigV4OperationSigningConfig, sigv4};
15use aws_sdk_bedrockagentcore::config::endpoint::{DefaultResolver, Params, ResolveEndpoint};
16use aws_smithy_async::time::SharedTimeSource;
17use aws_smithy_runtime::client::{
18 identity::IdentityCache,
19 orchestrator::operation::Operation,
20 retries::classifiers::{HttpStatusCodeClassifier, TransientErrorClassifier},
21};
22use aws_smithy_runtime_api::client::{
23 auth::{AuthSchemeOptionResolverParams, SharedAuthScheme, static_resolver::StaticAuthSchemeOptionResolver},
24 identity::SharedIdentityResolver,
25 orchestrator::{HttpRequest, HttpResponse, OrchestratorError, SensitiveOutput},
26 result::SdkError,
27 runtime_components::RuntimeComponentsBuilder,
28 runtime_plugin::StaticRuntimePlugin,
29};
30use aws_smithy_types::{
31 DateTime, body::SdkBody, config_bag::Layer, date_time::Format, retry::RetryConfig, timeout::TimeoutConfig,
32};
33use aws_types::{SdkConfig, SigningName, region::SigningRegion};
34use bytes::Bytes;
35use http_body_util::Full;
36use serde_json::{Value, json};
37use sha2::{Digest, Sha256};
38
39use crate::context::{self, WorkloadIdentityContexts};
40
41const OPERATION: &str = "GetIAMWorkloadIdentityCredentials";
42const PATH: &str = "/identities/GetIAMWorkloadIdentityCredentials";
43const UNKNOWN_OPERATION: &str = "UnknownOperationException";
44const USER_AGENT: &str =
45 concat!("bedrock-agentcore-rust/", env!("CARGO_PKG_VERSION"), " (feature=workload-identity-credentials)");
46const REFRESH_BEFORE_EXPIRY: Duration = Duration::from_secs(15 * 60);
48const REFRESH_REQUIRED_BEFORE_EXPIRY: Duration = Duration::from_secs(10 * 60);
51const REFRESH_TOKEN_MARGIN: Duration = Duration::from_secs(60);
53const UNAVAILABLE_BACKOFF: Duration = Duration::from_secs(30);
56const UNAVAILABLE_BACKOFF_MAX: Duration = Duration::from_secs(5 * 60);
57
58#[derive(Clone)]
114pub struct WorkloadIdentityCredentials {
115 inner: Arc<Inner>,
116}
117
118struct Inner {
119 config: SdkConfig,
120 time: SharedTimeSource,
121 state: tokio::sync::Mutex<State>,
123}
124
125#[derive(Default)]
126struct State {
127 latest: Option<(String, WorkloadIdentityContexts)>,
129 issued: HashMap<String, Issued>,
131 unavailable_until: Option<SystemTime>,
132 unavailable_backoff: Duration,
133}
134
135struct Issued {
136 credentials: Credentials,
137 refresh_token: Option<String>,
138 refresh_token_expiration: Option<SystemTime>,
139}
140
141impl fmt::Debug for Issued {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.debug_struct("Issued").field("expiry", &self.credentials.expiry()).finish_non_exhaustive()
144 }
145}
146
147struct ExchangeRequest(Bytes);
149
150impl fmt::Debug for ExchangeRequest {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 f.write_str("ExchangeRequest")
153 }
154}
155
156#[derive(Debug)]
159struct ExchangeError {
160 status: Option<u16>,
161 code: Option<String>,
162}
163
164impl ExchangeError {
165 const UNEXPECTED_RESPONSE: &str = "UnexpectedResponse";
166
167 fn is(&self, code: &str) -> bool {
168 self.code.as_deref() == Some(code)
169 }
170}
171
172impl fmt::Display for ExchangeError {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 write!(f, "{OPERATION} failed")?;
175 if let Some(status) = self.status {
176 write!(f, ": HTTP {status}")?;
177 }
178 if let Some(code) = &self.code {
179 write!(f, " ({code})")?;
180 }
181 Ok(())
182 }
183}
184
185impl std::error::Error for ExchangeError {}
186
187impl WorkloadIdentityCredentials {
188 pub fn new(config: &SdkConfig) -> Self {
191 let time = config.time_source().unwrap_or_default();
192 Self { inner: Arc::new(Inner { config: config.clone(), time, state: tokio::sync::Mutex::default() }) }
193 }
194
195 pub fn configure(config: &SdkConfig) -> SdkConfig {
198 config
199 .to_builder()
200 .credentials_provider(SharedCredentialsProvider::new(Self::new(config)))
201 .identity_cache(IdentityCache::no_cache())
202 .build()
203 }
204
205 async fn base(&self) -> provider::Result {
206 match self.inner.config.credentials_provider() {
207 Some(base) => base.provide_credentials().await,
208 None => Err(CredentialsError::not_loaded("the configuration has no credentials provider")),
209 }
210 }
211
212 async fn resolve(&self) -> provider::Result {
213 let mut state = self.inner.state.lock().await;
214 let current =
215 context::current().map(|ctx| (ctx.session_id().to_owned(), ctx.workload_identity_contexts().clone()));
216 let in_request = current.is_some();
217 let found = current.or_else(|| state.latest.clone()).and_then(|(session, contexts)| {
218 let context = contexts.get(&session)?;
219 Some((session, contexts, context))
220 });
221 let Some((session, contexts, context)) = found else {
222 if in_request && state.latest.is_some() {
225 return Err(CredentialsError::provider_error("the session has no workload identity context"));
226 }
227 return self.base().await;
228 };
229 state.latest = Some((session.clone(), contexts));
230 let now = self.inner.time.now();
231 if state.unavailable_until.is_some_and(|until| now < until) {
232 return self.base().await;
233 }
234 let current = state.issued.get(&session).map(|issued| issued.credentials.clone());
235 let expiry = current.as_ref().and_then(Credentials::expiry);
236 let remaining = expiry.and_then(|expiry| expiry.duration_since(now).ok()).unwrap_or_default();
237 if let Some(current) = ¤t
238 && remaining > REFRESH_BEFORE_EXPIRY
239 {
240 return Ok(current.clone());
241 }
242
243 match self.obtain(state.issued.get(&session), &context, now).await {
244 Ok(mut issued) => {
245 if state.unavailable_until.take().is_some() {
246 tracing::warn!("workload identity credentials are available again");
247 }
248 state.unavailable_backoff = Duration::ZERO;
249 if issued.refresh_token.is_none()
250 && let Some(previous) = state.issued.remove(&session)
251 {
252 issued.refresh_token = previous.refresh_token;
253 issued.refresh_token_expiration = previous.refresh_token_expiration;
254 }
255 let credentials = issued.credentials.clone();
256 state.issued.retain(|_, issued| issued.credentials.expiry().is_some_and(|expiry| now < expiry));
258 state.issued.insert(session, issued);
259 Ok(credentials)
260 }
261 Err(error) if error.is(UNKNOWN_OPERATION) => {
262 let backoff = (state.unavailable_backoff * 2).clamp(UNAVAILABLE_BACKOFF, UNAVAILABLE_BACKOFF_MAX);
263 if state.unavailable_until.is_none() {
264 tracing::warn!(
265 seconds = backoff.as_secs(),
266 "workload identity credentials are not available, using the execution role credentials"
267 );
268 }
269 state.unavailable_backoff = backoff;
270 state.unavailable_until = Some(now + backoff);
271 self.base().await
272 }
273 Err(error) => match current {
274 Some(current) if remaining > REFRESH_REQUIRED_BEFORE_EXPIRY => {
275 tracing::warn!(%error, "workload identity credentials were not renewed, using the current ones");
276 Ok(current)
277 }
278 _ => Err(CredentialsError::provider_error(error)),
279 },
280 }
281 }
282
283 async fn obtain(&self, current: Option<&Issued>, context: &str, now: SystemTime) -> Result<Issued, ExchangeError> {
286 let refresh_token = current.and_then(|issued| {
287 let usable =
288 issued.refresh_token_expiration.is_none_or(|expiration| now + REFRESH_TOKEN_MARGIN < expiration);
289 issued.refresh_token.as_ref().filter(|_| usable)
290 });
291 if let Some(refresh_token) = refresh_token {
292 match self.call(json!({ "mode": { "refresh": { "refreshToken": refresh_token } } })).await {
293 Err(error) if error.status == Some(400) => {}
295 result => return result,
296 }
297 }
298 self.call(json!({ "mode": { "issue": { "encryptedContext": context } } })).await
299 }
300
301 async fn call(&self, body: Value) -> Result<Issued, ExchangeError> {
302 let config = &self.inner.config;
303 let failed = |code: &str| ExchangeError { status: None, code: Some(code.to_owned()) };
304 let region = config.region().ok_or_else(|| failed("NoRegion"))?;
305 let params = Params::builder()
306 .region(region.as_ref())
307 .set_endpoint(config.endpoint_url().map(str::to_owned))
308 .set_use_fips(config.use_fips())
309 .set_use_dual_stack(config.use_dual_stack())
310 .build()
311 .map_err(|_| failed("NoEndpoint"))?;
312 let endpoint = DefaultResolver::new().resolve_endpoint(¶ms).await.map_err(|_| failed("NoEndpoint"))?;
313 let base = config.credentials_provider().ok_or_else(|| failed("NoCredentialsProvider"))?;
314
315 let mut layer = Layer::new("WorkloadIdentityCredentials");
316 layer.store_put(AuthSchemeOptionResolverParams::new(()));
317 layer.store_put(SigV4OperationSigningConfig {
318 region: Some(SigningRegion::from(region.clone())),
319 name: Some(SigningName::from_static("bedrock-agentcore")),
320 ..Default::default()
321 });
322 layer.store_put(SensitiveOutput);
323 let body = Bytes::from(body.to_string());
327 let hash: String = Sha256::digest(&body).iter().map(|byte| format!("{byte:02x}")).collect();
328 layer.store_put(PayloadSigningOverride::Precomputed(hash));
329 let auth = RuntimeComponentsBuilder::new("WorkloadIdentityCredentials")
330 .with_auth_scheme_option_resolver(Some(StaticAuthSchemeOptionResolver::new(vec![sigv4::SCHEME_ID])))
331 .with_auth_scheme(SharedAuthScheme::new(sigv4::SigV4AuthScheme::new()))
332 .with_identity_cache(Some(IdentityCache::no_cache()))
333 .with_identity_resolver(sigv4::SCHEME_ID, SharedIdentityResolver::new(base));
334
335 let mut operation = Operation::builder()
336 .service_name("bedrock-agentcore")
337 .operation_name(OPERATION)
338 .endpoint_url(endpoint.url())
339 .runtime_plugin(StaticRuntimePlugin::new().with_config(layer.freeze()).with_runtime_components(auth))
340 .time_source(self.inner.time.clone())
341 .timeout_config(
342 TimeoutConfig::builder()
343 .connect_timeout(Duration::from_secs(2))
344 .read_timeout(Duration::from_secs(5))
345 .build(),
346 )
347 .standard_retry(&RetryConfig::standard().with_max_attempts(4))
348 .retry_classifier(TransientErrorClassifier::<ExchangeError>::new())
349 .retry_classifier(HttpStatusCodeClassifier::new_from_codes(vec![429, 500, 502, 503, 504]))
350 .serializer(|body: ExchangeRequest| {
351 let request = http::Request::post(PATH)
353 .header(http::header::CONTENT_TYPE, "application/json")
354 .header(http::header::USER_AGENT, USER_AGENT);
355 let request = request.header(http::header::CONTENT_LENGTH, body.0.len());
356 let stream = SdkBody::retryable(move || SdkBody::from_body_1_x(Full::new(body.0.clone())));
357 Ok(HttpRequest::try_from(request.body(stream)?)?)
358 })
359 .deserializer(parse);
360 if let Some(http_client) = config.http_client() {
361 operation = operation.http_client(http_client);
362 }
363 if let Some(sleep) = config.sleep_impl() {
364 operation = operation.sleep_impl(sleep);
365 }
366 operation.build().invoke(ExchangeRequest(body)).await.map_err(|error| match error {
367 SdkError::ServiceError(error) => error.into_err(),
368 SdkError::TimeoutError(_) => failed("Timeout"),
369 SdkError::ResponseError(_) => failed(ExchangeError::UNEXPECTED_RESPONSE),
370 _ => failed("RequestNotSent"),
371 })
372 }
373}
374
375fn parse(response: &HttpResponse) -> Result<Issued, OrchestratorError<ExchangeError>> {
376 let status = response.status().as_u16();
377 let body: Option<Value> = response.body().bytes().and_then(|bytes| serde_json::from_slice(bytes).ok());
378 let failed = |code: Option<&str>| {
379 OrchestratorError::operation(ExchangeError { status: Some(status), code: code.map(str::to_owned) })
380 };
381 if !response.status().is_success() {
382 let code = response.headers().get("x-amzn-errortype").filter(|code| !code.is_empty()).or_else(|| {
383 let body = body.as_ref()?;
384 ["__type", "code", "Code"].iter().find_map(|name| body.get(name)?.as_str())
385 });
386 let code = code.map(|code| code.split(':').next().unwrap_or(code).rsplit('#').next().unwrap_or(code));
388 return Err(failed(code));
389 }
390 issued(body.as_ref()).ok_or_else(|| failed(Some(ExchangeError::UNEXPECTED_RESPONSE)))
391}
392
393fn issued(body: Option<&Value>) -> Option<Issued> {
394 let body = body?;
395 let credentials = body.get("credentials")?;
396 let text = |value: &Value, name: &str| value.get(name).and_then(Value::as_str).map(str::to_owned);
397 let mut builder = Credentials::builder()
398 .access_key_id(text(credentials, "accessKeyId")?)
399 .secret_access_key(text(credentials, "secretAccessKey")?)
400 .session_token(text(credentials, "sessionToken")?)
401 .expiry(time(credentials.get("expiration")?)?)
402 .provider_name("AgentCoreWorkloadIdentity");
403 let account = text(body, "assumedRoleArn").and_then(|arn| arn.split(':').nth(4).map(str::to_owned));
405 if let Some(account) = account.filter(|account| !account.is_empty()) {
406 builder = builder.account_id(account);
407 }
408 Some(Issued {
409 credentials: builder.build(),
410 refresh_token: text(body, "refreshToken"),
411 refresh_token_expiration: body.get("refreshTokenExpiration").and_then(time),
412 })
413}
414
415fn time(value: &Value) -> Option<SystemTime> {
417 match value {
418 Value::Number(seconds) => UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(seconds.as_f64()?).ok()?),
419 Value::String(text) => DateTime::from_str(text, Format::DateTimeWithOffset).ok()?.try_into().ok(),
420 _ => None,
421 }
422}
423
424impl ProvideCredentials for WorkloadIdentityCredentials {
425 fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>
426 where
427 Self: 'a,
428 {
429 future::ProvideCredentials::new(self.resolve())
430 }
431}
432
433impl fmt::Debug for WorkloadIdentityCredentials {
434 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435 f.debug_struct("WorkloadIdentityCredentials").finish_non_exhaustive()
436 }
437}