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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Per-invocation request context.
//!
//! The runtime server creates one [`RequestContext`] for each invocation and passes it
//! to the handler. The same value is also available without passing it along: call
//! [`current`] anywhere inside the handler's future.
//!
//! # Work that outlives the handler
//!
//! The ambient context covers the handler's future and the body of its response,
//! including a streaming body that is read after the handler returns. A task started with
//! `tokio::spawn` does not inherit it. Move a clone into the task with [`scope`]:
//!
//! ```
//! # use bedrock_agentcore::{RequestContext, context};
//! # async fn handler(ctx: RequestContext) {
//! tokio::spawn(context::scope(ctx.clone(), async {
//!     assert!(context::current().is_some());
//! }));
//! # }
//! ```
//!
//! # Reading credentials
//!
//! Read the workload access token from the context each time an operation needs it.
//! Do not store it in a client or in application state that other requests share. A
//! stored token would be sent on behalf of a later request, which may belong to
//! another user or carry no token at all.

use std::{
    fmt,
    future::Future,
    sync::{Arc, Mutex, PoisonError},
};

use http::{HeaderMap, HeaderName, HeaderValue};

use crate::{Error, ErrorKind, tasks::AsyncTasks};

/// The header that carries the workload access token, in lowercase.
#[cfg(any(feature = "runtime", feature = "identity"))]
pub(crate) const WORKLOAD_ACCESS_TOKEN_HEADER: &str = "x-amz-bedrock-agentcore-identity-wat";

tokio::task_local! {
    static CURRENT: RequestContext;
}

/// Runs `future` with `ctx` as the ambient context returned by [`current`].
///
/// Scopes nest. When `future` completes, the previous ambient context is back in place.
///
/// The context is also in place when `future` is dropped, even if it was never
/// polled, for example in a spawned task that is aborted before it starts.
pub fn scope<F: Future>(ctx: RequestContext, future: F) -> impl Future<Output = F::Output> {
    // Not an `async fn`: the scoped future must exist from this call on, so that
    // dropping it before its first poll still drops `future` inside the context.
    CURRENT.scope(ctx, future)
}

/// Runs `f` with `ctx` as the ambient context. The server uses it around each poll of
/// a response body, which happens after the handler's future has completed.
#[cfg(feature = "runtime")]
pub(crate) fn sync_scope<R>(ctx: RequestContext, f: impl FnOnce() -> R) -> R {
    CURRENT.sync_scope(ctx, f)
}

/// The context of the invocation that the calling code runs in.
///
/// Returns `None` outside an invocation, for example at startup or in a spawned task
/// that was not wrapped in [`scope`].
pub fn current() -> Option<RequestContext> {
    CURRENT.try_with(Clone::clone).ok()
}

/// The workload access token of the invocation that the calling code runs in.
///
/// The token is an owned copy, for a call that needs it outside the context. Code
/// that already holds a [`RequestContext`] can borrow the token with
/// [`RequestContext::workload_access_token`].
///
/// # Errors
///
/// [`ErrorKind::MissingWorkloadToken`] when the call runs outside an invocation, or
/// when the context has no token or an empty one. The text says which.
pub fn workload_access_token() -> Result<WorkloadAccessToken, Error> {
    let ctx = current();
    ctx.as_ref()
        .and_then(|ctx| ctx.workload_access_token().cloned())
        .filter(|token| !token.expose().is_empty())
        .ok_or_else(|| missing_workload_access_token(ctx.is_some()))
}

/// The error for a call that finds no workload access token. The text names the
/// cause and what removes it.
pub(crate) fn missing_workload_access_token(in_request_context: bool) -> Error {
    let message = if in_request_context {
        "No workload access token: the invocation carried none. AgentCore Runtime sends a token only when the \
         caller names a user: a runtimeUserId with IAM authorization, which needs the \
         bedrock-agentcore:InvokeAgentRuntimeForUser permission, or a JWT. A local call must send a token of a \
         workload identity in the X-Amz-Bedrock-AgentCore-Identity-WAT header. The identity module \
         documentation shows how to get one."
    } else {
        "No workload access token: this call ran outside a request context, for example in a task started with \
         tokio::spawn. Wrap the future of the task in bedrock_agentcore::context::scope(ctx.clone(), ..), or give \
         the operation a token with .workload_access_token(..)."
    };
    Error::new(ErrorKind::MissingWorkloadToken, message)
}

/// A workload access token of AgentCore Identity.
///
/// Its `Debug` output never contains the token. Read the value with [`expose`](Self::expose).
#[derive(Clone, PartialEq, Eq)]
pub struct WorkloadAccessToken(String);

impl WorkloadAccessToken {
    /// Wraps a token value.
    pub fn new(token: impl Into<String>) -> Self {
        Self(token.into())
    }

    /// The token value. Keep it out of logs.
    pub fn expose(&self) -> &str {
        &self.0
    }
}

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

/// The encrypted workload identity contexts that an app received, one for each
/// session. Clones share the same store. A session keeps its context for a later
/// invocation that carries none.
#[derive(Clone, Default)]
pub(crate) struct WorkloadIdentityContexts(Arc<Mutex<Vec<(String, String)>>>);

impl WorkloadIdentityContexts {
    /// An app has few sessions at a time. The oldest context leaves when one more arrives.
    const MAX_SESSIONS: usize = 64;

    fn record(&self, session_id: &str, context: String) {
        let mut contexts = self.0.lock().unwrap_or_else(PoisonError::into_inner);
        contexts.retain(|(session, _)| session != session_id);
        if contexts.len() == Self::MAX_SESSIONS {
            contexts.remove(0);
        }
        contexts.push((session_id.to_owned(), context));
    }

    pub(crate) fn get(&self, session_id: &str) -> Option<String> {
        let contexts = self.0.lock().unwrap_or_else(PoisonError::into_inner);
        contexts.iter().find(|(session, _)| session == session_id).map(|(_, context)| context.clone())
    }
}

/// Metadata of one invocation.
///
/// The value is immutable and cheap to clone. Its `Debug` output contains header names
/// but no header values and no token.
#[derive(Clone)]
pub struct RequestContext {
    inner: Arc<Inner>,
}

struct Inner {
    session_id: String,
    request_id: String,
    workload_access_token: Option<WorkloadAccessToken>,
    oauth2_callback_url: Option<String>,
    workload_identity_contexts: WorkloadIdentityContexts,
    headers: HeaderMap,
    request_headers: HeaderMap,
    tasks: AsyncTasks,
}

impl RequestContext {
    /// Starts a context for the session `session_id`.
    ///
    /// The runtime server builds the context of each invocation itself. Use this
    /// builder in tests, or to run code that reads the ambient context outside the
    /// server.
    pub fn builder(session_id: impl Into<String>) -> RequestContextBuilder {
        RequestContextBuilder {
            inner: Inner {
                session_id: session_id.into(),
                request_id: String::new(),
                workload_access_token: None,
                oauth2_callback_url: None,
                workload_identity_contexts: WorkloadIdentityContexts::default(),
                headers: HeaderMap::new(),
                request_headers: HeaderMap::new(),
                tasks: AsyncTasks::new(),
            },
        }
    }

    /// The runtime session ID. It comes from the
    /// `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header, or from the top-level
    /// `sessionId` string of the request body when the header is absent.
    pub fn session_id(&self) -> &str {
        &self.inner.session_id
    }

    /// The request ID. It comes from the `X-Amzn-Bedrock-AgentCore-Runtime-Request-Id`
    /// header. The SDK generates a UUID when the header is absent.
    ///
    /// In tests against AgentCore Runtime the service did not send this header, so
    /// the ID of a deployed agent is the generated UUID. It is not the request ID
    /// that the caller of `InvokeAgentRuntime` receives. To find the log lines of a
    /// call, search for the session ID.
    pub fn request_id(&self) -> &str {
        &self.inner.request_id
    }

    /// The workload access token that AgentCore Runtime sent with this invocation.
    ///
    /// It comes from the `X-Amz-Bedrock-AgentCore-Identity-WAT` header, or from the
    /// `WorkloadAccessToken` header when the first one is absent.
    pub fn workload_access_token(&self) -> Option<&WorkloadAccessToken> {
        self.inner.workload_access_token.as_ref()
    }

    /// The OAuth2 callback URL from the `OAuth2CallbackUrl` header.
    ///
    /// AgentCore Runtime does not add this header. In tests against the service it
    /// passed the header on only when the caller sent it and the request header
    /// allowlist of the agent runtime named it. An agent that needs a callback URL
    /// on AgentCore Runtime sets it on the request, with
    /// `Oauth2TokenBuilder::callback_url`.
    pub fn oauth2_callback_url(&self) -> Option<&str> {
        self.inner.oauth2_callback_url.as_deref()
    }

    /// The encrypted workload identity contexts of the app that received this
    /// invocation. `WorkloadIdentityCredentials` exchanges the one of a session for
    /// credentials.
    #[cfg(feature = "identity")]
    pub(crate) fn workload_identity_contexts(&self) -> &WorkloadIdentityContexts {
        &self.inner.workload_identity_contexts
    }

    /// The request headers that an agent may forward to other services.
    ///
    /// The map holds only `Authorization`, headers whose name starts with
    /// `X-Amzn-Bedrock-AgentCore-Runtime-Custom-`, and
    /// `X-Amz-Bedrock-AgentCore-Identity-WAT`. A header that the request repeats has
    /// one entry, with the values joined by a comma and a space. Every value is marked
    /// sensitive, so `Debug` output of the map does not show it.
    pub fn headers(&self) -> &HeaderMap {
        &self.inner.headers
    }

    /// The headers of the request as the server received them. They include the
    /// headers that the `requestHeaderAllowlist` of the agent runtime lets through,
    /// such as an `X-Api-Key` header, and the `Accept` header.
    ///
    /// The encrypted workload identity context is not in the map. A header that the
    /// request repeats has one entry for each value. Every value is marked
    /// sensitive, so `Debug` output of the map does not show it. Forward only the
    /// headers of [`headers`](Self::headers) to other services.
    pub fn request_headers(&self) -> &HeaderMap {
        &self.inner.request_headers
    }
}

impl RequestContext {
    /// The registry of background work of the app that received this invocation.
    /// Work tracked here makes the app report `HealthyBusy`. See [`crate::tasks`].
    pub fn tasks(&self) -> &AsyncTasks {
        &self.inner.tasks
    }
}

impl fmt::Debug for RequestContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestContext")
            .field("session_id", &self.inner.session_id)
            .field("request_id", &self.inner.request_id)
            .field("workload_access_token", &self.inner.workload_access_token)
            .field("oauth2_callback_url", &self.inner.oauth2_callback_url.as_ref().map(|_| "<set>"))
            .field(
                "workload_identity_context",
                &self.inner.workload_identity_contexts.get(&self.inner.session_id).map(|_| "<set>"),
            )
            .field("headers", &self.inner.headers.keys().map(HeaderName::as_str).collect::<Vec<_>>())
            .finish()
    }
}

/// Builds a [`RequestContext`]. Create one with [`RequestContext::builder`].
#[must_use]
pub struct RequestContextBuilder {
    inner: Inner,
}

impl RequestContextBuilder {
    /// Sets the request ID. The default is a new UUID.
    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
        self.inner.request_id = request_id.into();
        self
    }

    /// Sets the workload access token.
    pub fn workload_access_token(mut self, token: WorkloadAccessToken) -> Self {
        self.inner.workload_access_token = Some(token);
        self
    }

    /// Sets the OAuth2 callback URL.
    pub fn oauth2_callback_url(mut self, url: impl Into<String>) -> Self {
        self.inner.oauth2_callback_url = Some(url.into());
        self
    }

    /// Sets the encrypted workload identity context of the session. The runtime
    /// server reads it from the
    /// `X-Amzn-Bedrock-AgentCore-Runtime-Encrypted-Workload-Identity-Context` header
    /// and keeps it for later invocations of the session. It is not in
    /// [`RequestContext::headers`] and `Debug` does not show it.
    pub fn workload_identity_context(self, context: impl Into<String>) -> Self {
        self.inner.workload_identity_contexts.record(&self.inner.session_id, context.into());
        self
    }

    /// Sets the store that the contexts of all invocations of an app share.
    #[cfg(feature = "runtime")]
    pub(crate) fn workload_identity_contexts(mut self, contexts: WorkloadIdentityContexts) -> Self {
        self.inner.workload_identity_contexts = contexts;
        self
    }

    /// Adds one entry to [`RequestContext::headers`]. The builder applies no filter.
    ///
    /// The value is marked sensitive, so its `Debug` output does not show it.
    pub fn header(mut self, name: HeaderName, mut value: HeaderValue) -> Self {
        value.set_sensitive(true);
        self.inner.headers.append(name, value);
        self
    }

    /// Adds one entry to [`RequestContext::request_headers`].
    ///
    /// The value is marked sensitive, so its `Debug` output does not show it.
    pub fn request_header(mut self, name: HeaderName, mut value: HeaderValue) -> Self {
        value.set_sensitive(true);
        self.inner.request_headers.append(name, value);
        self
    }

    /// Sets the registry returned by [`RequestContext::tasks`]. The default is a new
    /// empty registry.
    pub fn tasks(mut self, tasks: AsyncTasks) -> Self {
        self.inner.tasks = tasks;
        self
    }

    /// Builds the context.
    pub fn build(mut self) -> RequestContext {
        if self.inner.request_id.is_empty() {
            self.inner.request_id = uuid::Uuid::new_v4().to_string();
        }
        RequestContext { inner: Arc::new(self.inner) }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    fn session() -> Option<String> {
        current().map(|ctx| ctx.session_id().to_owned())
    }

    #[tokio::test]
    async fn ambient_context_follows_scopes_and_not_unscoped_tasks() {
        assert_eq!(session(), None, "outside any scope");
        let outer = RequestContext::builder("outer").build();
        let inner = RequestContext::builder("inner").build();

        scope(outer.clone(), async {
            assert_eq!(session().as_deref(), Some("outer"));
            scope(inner, async { assert_eq!(session().as_deref(), Some("inner")) }).await;
            assert_eq!(session().as_deref(), Some("outer"), "the outer context is back after a nested scope");

            let unscoped = tokio::spawn(async { session() });
            let scoped = tokio::spawn(scope(outer.clone(), async { session() }));
            assert_eq!(unscoped.await.unwrap(), None, "a spawned task does not inherit the context");
            assert_eq!(scoped.await.unwrap().as_deref(), Some("outer"));
        })
        .await;
        assert_eq!(session(), None, "after the scope");
    }

    /// Records the ambient session when it is dropped.
    struct RecordsOnDrop(std::sync::Arc<std::sync::Mutex<Option<String>>>);

    impl Drop for RecordsOnDrop {
        fn drop(&mut self) {
            *self.0.lock().unwrap() = Some(session().unwrap_or_else(|| "no context".to_owned()));
        }
    }

    #[tokio::test]
    async fn scoped_future_is_dropped_within_its_context_even_when_it_was_never_polled() {
        let ctx = RequestContext::builder("dropped").build();
        // Dropped directly, and dropped by the runtime when its task is aborted. This
        // runtime has one thread and the test does not yield before the abort.
        for spawned in [false, true] {
            let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
            let guard = RecordsOnDrop(seen.clone());
            let scoped = scope(ctx.clone(), async move {
                let _guard = guard;
            });
            if spawned {
                let task = tokio::spawn(scoped);
                task.abort();
                assert!(task.await.unwrap_err().is_cancelled());
            } else {
                drop(scoped);
            }
            assert_eq!(seen.lock().unwrap().as_deref(), Some("dropped"), "spawned: {spawned}");
        }
    }

    #[tokio::test]
    async fn owned_token_accessor_needs_a_nonempty_token_in_the_ambient_context() {
        let with = |token: Option<&str>| {
            let mut builder = RequestContext::builder("s");
            if let Some(token) = token {
                builder = builder.workload_access_token(WorkloadAccessToken::new(token));
            }
            scope(builder.build(), async { workload_access_token() })
        };
        assert_eq!(with(Some("SECRET-TOKEN")).await.unwrap().expose(), "SECRET-TOKEN");

        // Outside a context, without a token, and with the empty token of a hand-built context.
        let (outside, carried_none) = ("this call ran outside a request context", "the invocation carried none");
        let missing = [
            (workload_access_token(), outside),
            (with(None).await, carried_none),
            (with(Some("")).await, carried_none),
        ];
        for (missing, cause) in missing {
            let error = missing.unwrap_err();
            assert_eq!(error.kind(), ErrorKind::MissingWorkloadToken);
            assert!(error.to_string().contains(cause), "{error}");
        }
        // The borrowed getter still returns the empty token as it was given.
        let ctx = RequestContext::builder("s").workload_access_token(WorkloadAccessToken::new("")).build();
        assert_eq!(ctx.workload_access_token().map(WorkloadAccessToken::expose), Some(""));
    }

    #[test]
    fn built_context_has_a_request_id_and_hides_secrets_in_debug_output() {
        let ctx = RequestContext::builder("s")
            .workload_access_token(WorkloadAccessToken::new("SECRET-TOKEN"))
            .oauth2_callback_url("https://secret.example/callback")
            // The header types are reachable through the crate's re-export of `http`.
            .header(crate::http::header::AUTHORIZATION, crate::http::HeaderValue::from_static("SECRET-AUTH"))
            .build();
        assert_eq!(ctx.request_id().parse::<uuid::Uuid>().unwrap().get_version_num(), 4);
        assert_eq!(ctx.workload_access_token().unwrap().expose(), "SECRET-TOKEN");
        assert_eq!(ctx.oauth2_callback_url(), Some("https://secret.example/callback"));
        assert_eq!(RequestContext::builder("s").request_id("given").build().request_id(), "given");

        let authorization = ctx.headers().get(http::header::AUTHORIZATION).unwrap();
        assert_eq!(authorization, "SECRET-AUTH");
        let debug = format!("{ctx:?} {:?} {:?} {authorization:?}", ctx.workload_access_token(), ctx.headers());
        assert!(debug.contains("authorization") && debug.contains("session_id: \"s\""), "{debug}");
        assert!(!debug.to_lowercase().contains("secret"), "{debug}");
    }
}