bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Execution role credentials that carry the workload identity of the agent.

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)");
/// New credentials are requested when the current ones have less time left.
const REFRESH_BEFORE_EXPIRY: Duration = Duration::from_secs(15 * 60);
/// A failed refresh is an error when the current credentials have less time left.
/// With more time left, the current credentials are used and the failure is logged.
const REFRESH_REQUIRED_BEFORE_EXPIRY: Duration = Duration::from_secs(10 * 60);
/// A refresh token this close to its expiry is not used.
const REFRESH_TOKEN_MARGIN: Duration = Duration::from_secs(60);
/// The wait before the exchange is tried again where the service does not support
/// the operation. It doubles up to the maximum.
const UNAVAILABLE_BACKOFF: Duration = Duration::from_secs(30);
const UNAVAILABLE_BACKOFF_MAX: Duration = Duration::from_secs(5 * 60);

/// A credentials provider for the AWS calls of an agent on AgentCore Runtime.
///
/// AgentCore Runtime can send an encrypted workload identity context with an
/// invocation. This provider exchanges it, with the `GetIAMWorkloadIdentityCredentials`
/// operation, for credentials of the execution role that carry the workload identity of
/// the agent. AWS clients that use this provider then call other services with those
/// credentials.
///
/// ```no_run
/// # use bedrock_agentcore::identity::WorkloadIdentityCredentials;
/// # fn example(config: aws_types::SdkConfig) {
/// // `config` is the configuration of the agent, for example from `aws_config::load_defaults`.
/// let config = WorkloadIdentityCredentials::configure(&config);
/// // Build every AWS client of the agent from the returned configuration.
/// # let _ = config;
/// # }
/// ```
///
/// # Which credentials a call gets
///
/// - Before any invocation carried a context, the credentials of the configuration
///   that the provider was created from. On AgentCore Runtime these are the execution
///   role credentials.
/// - After that, the credentials for the context of the session of the call. A session
///   keeps its latest context, so an invocation without one uses the context of an
///   earlier invocation of the same session. The credentials are requested on the first
///   AWS call of the session, kept for it, and renewed before they expire. The context,
///   the credentials and the refresh token of one session are never used for another.
/// - A call in a session that sent no context fails, when another session sent one.
/// - When the exchange fails, the call fails. The provider does not go back to the
///   execution role credentials, because the call would then run without the workload
///   identity.
/// - The exception is a service that does not support the operation. The provider then
///   returns the execution role credentials and tries the exchange again later.
///
/// # The request context
///
/// The provider reads the session and the context from the ambient
/// [request context](crate::context) of the AWS call. A task started with
/// `tokio::spawn` does not inherit it: wrap its future in
/// [`context::scope`](crate::context::scope). A call outside a request context uses
/// the session of the latest call that had a context.
///
/// # The identity cache
///
/// An AWS client keeps the credentials of its provider until they expire. A client
/// that resolved the execution role credentials at startup would keep them after the
/// first invocation. [`configure`](Self::configure) turns that cache off, and the
/// provider keeps the credentials itself. Do the same when you set the provider on a
/// configuration yourself.
///
/// # Other processes
///
/// The provider covers the AWS SDK for Rust clients of this process. A child process,
/// such as the AWS CLI, uses the execution role credentials.
#[derive(Clone)]
pub struct WorkloadIdentityCredentials {
    inner: Arc<Inner>,
}

struct Inner {
    config: SdkConfig,
    time: SharedTimeSource,
    /// Held during an exchange, so that one exchange runs at a time.
    state: tokio::sync::Mutex<State>,
}

#[derive(Default)]
struct State {
    /// The session of the latest call that had a context, and the store that holds it.
    latest: Option<(String, WorkloadIdentityContexts)>,
    /// The credentials of each session.
    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()
    }
}

/// The body of a request. It holds the context or a refresh token.
struct ExchangeRequest(Bytes);

impl fmt::Debug for ExchangeRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ExchangeRequest")
    }
}

/// A failed exchange. The text has the HTTP status and the error code only, never
/// content of the request or of the response.
#[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 {
    /// Creates the provider. It signs the exchange with the credentials provider of
    /// `config`, and uses the Region, the endpoint URL and the HTTP client of `config`.
    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() }) }
    }

    /// Returns `config` with this provider as its credentials provider and without an
    /// identity cache. Build the AWS clients of the agent from the result.
    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 {
            // The identity of another session must not sign the calls of this one, and
            // the execution role alone would drop the workload identity.
            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) = &current
            && 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();
                // Sessions that ended leave when their credentials have expired.
                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)),
            },
        }
    }

    /// Renews the credentials of the session with its refresh token, or requests the
    /// first ones with the context.
    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 {
                // The service refused the refresh token. The context may still be valid.
                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(&params).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);
        // The runtime prints a body that is in memory when it traces the request. This
        // body holds the context or a refresh token, so it is given as a stream, which
        // is not printed. The signer cannot read a stream and gets the hash here.
        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| {
                // The service refuses a request that has no User-Agent header.
                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())
        });
        // `namespace#Code:detail` names the code between the two marks.
        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");
    // `arn:partition:service:region:account:resource`
    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),
    })
}

/// A timestamp of the service: seconds since the Unix epoch, or RFC 3339 text.
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()
    }
}