Skip to main content

bedrock_agentcore/identity/
workload_identity.rs

1//! Execution role credentials that carry the workload identity of the agent.
2
3use 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)");
46/// New credentials are requested when the current ones have less time left.
47const REFRESH_BEFORE_EXPIRY: Duration = Duration::from_secs(15 * 60);
48/// A failed refresh is an error when the current credentials have less time left.
49/// With more time left, the current credentials are used and the failure is logged.
50const REFRESH_REQUIRED_BEFORE_EXPIRY: Duration = Duration::from_secs(10 * 60);
51/// A refresh token this close to its expiry is not used.
52const REFRESH_TOKEN_MARGIN: Duration = Duration::from_secs(60);
53/// The wait before the exchange is tried again where the service does not support
54/// the operation. It doubles up to the maximum.
55const UNAVAILABLE_BACKOFF: Duration = Duration::from_secs(30);
56const UNAVAILABLE_BACKOFF_MAX: Duration = Duration::from_secs(5 * 60);
57
58/// A credentials provider for the AWS calls of an agent on AgentCore Runtime.
59///
60/// AgentCore Runtime can send an encrypted workload identity context with an
61/// invocation. This provider exchanges it, with the `GetIAMWorkloadIdentityCredentials`
62/// operation, for credentials of the execution role that carry the workload identity of
63/// the agent. AWS clients that use this provider then call other services with those
64/// credentials.
65///
66/// ```no_run
67/// # use bedrock_agentcore::identity::WorkloadIdentityCredentials;
68/// # fn example(config: aws_types::SdkConfig) {
69/// // `config` is the configuration of the agent, for example from `aws_config::load_defaults`.
70/// let config = WorkloadIdentityCredentials::configure(&config);
71/// // Build every AWS client of the agent from the returned configuration.
72/// # let _ = config;
73/// # }
74/// ```
75///
76/// # Which credentials a call gets
77///
78/// - Before any invocation carried a context, the credentials of the configuration
79///   that the provider was created from. On AgentCore Runtime these are the execution
80///   role credentials.
81/// - After that, the credentials for the context of the session of the call. A session
82///   keeps its latest context, so an invocation without one uses the context of an
83///   earlier invocation of the same session. The credentials are requested on the first
84///   AWS call of the session, kept for it, and renewed before they expire. The context,
85///   the credentials and the refresh token of one session are never used for another.
86/// - A call in a session that sent no context fails, when another session sent one.
87/// - When the exchange fails, the call fails. The provider does not go back to the
88///   execution role credentials, because the call would then run without the workload
89///   identity.
90/// - The exception is a service that does not support the operation. The provider then
91///   returns the execution role credentials and tries the exchange again later.
92///
93/// # The request context
94///
95/// The provider reads the session and the context from the ambient
96/// [request context](crate::context) of the AWS call. A task started with
97/// `tokio::spawn` does not inherit it: wrap its future in
98/// [`context::scope`](crate::context::scope). A call outside a request context uses
99/// the session of the latest call that had a context.
100///
101/// # The identity cache
102///
103/// An AWS client keeps the credentials of its provider until they expire. A client
104/// that resolved the execution role credentials at startup would keep them after the
105/// first invocation. [`configure`](Self::configure) turns that cache off, and the
106/// provider keeps the credentials itself. Do the same when you set the provider on a
107/// configuration yourself.
108///
109/// # Other processes
110///
111/// The provider covers the AWS SDK for Rust clients of this process. A child process,
112/// such as the AWS CLI, uses the execution role credentials.
113#[derive(Clone)]
114pub struct WorkloadIdentityCredentials {
115    inner: Arc<Inner>,
116}
117
118struct Inner {
119    config: SdkConfig,
120    time: SharedTimeSource,
121    /// Held during an exchange, so that one exchange runs at a time.
122    state: tokio::sync::Mutex<State>,
123}
124
125#[derive(Default)]
126struct State {
127    /// The session of the latest call that had a context, and the store that holds it.
128    latest: Option<(String, WorkloadIdentityContexts)>,
129    /// The credentials of each session.
130    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
147/// The body of a request. It holds the context or a refresh token.
148struct 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/// A failed exchange. The text has the HTTP status and the error code only, never
157/// content of the request or of the response.
158#[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    /// Creates the provider. It signs the exchange with the credentials provider of
189    /// `config`, and uses the Region, the endpoint URL and the HTTP client of `config`.
190    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    /// Returns `config` with this provider as its credentials provider and without an
196    /// identity cache. Build the AWS clients of the agent from the result.
197    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            // The identity of another session must not sign the calls of this one, and
223            // the execution role alone would drop the workload identity.
224            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) = &current
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                // Sessions that ended leave when their credentials have expired.
257                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    /// Renews the credentials of the session with its refresh token, or requests the
284    /// first ones with the context.
285    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                // The service refused the refresh token. The context may still be valid.
294                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(&params).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        // The runtime prints a body that is in memory when it traces the request. This
324        // body holds the context or a refresh token, so it is given as a stream, which
325        // is not printed. The signer cannot read a stream and gets the hash here.
326        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                // The service refuses a request that has no User-Agent header.
352                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        // `namespace#Code:detail` names the code between the two marks.
387        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    // `arn:partition:service:region:account:resource`
404    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
415/// A timestamp of the service: seconds since the Unix epoch, or RFC 3339 text.
416fn 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}