Skip to main content

bedrock_agentcore/
context.rs

1//! Per-invocation request context.
2//!
3//! The runtime server creates one [`RequestContext`] for each invocation and passes it
4//! to the handler. The same value is also available without passing it along: call
5//! [`current`] anywhere inside the handler's future.
6//!
7//! # Work that outlives the handler
8//!
9//! The ambient context covers the handler's future and the body of its response,
10//! including a streaming body that is read after the handler returns. A task started with
11//! `tokio::spawn` does not inherit it. Move a clone into the task with [`scope`]:
12//!
13//! ```
14//! # use bedrock_agentcore::{RequestContext, context};
15//! # async fn handler(ctx: RequestContext) {
16//! tokio::spawn(context::scope(ctx.clone(), async {
17//!     assert!(context::current().is_some());
18//! }));
19//! # }
20//! ```
21//!
22//! # Reading credentials
23//!
24//! Read the workload access token from the context each time an operation needs it.
25//! Do not store it in a client or in application state that other requests share. A
26//! stored token would be sent on behalf of a later request, which may belong to
27//! another user or carry no token at all.
28
29use std::{
30    fmt,
31    future::Future,
32    sync::{Arc, Mutex, PoisonError},
33};
34
35use http::{HeaderMap, HeaderName, HeaderValue};
36
37use crate::{Error, ErrorKind, tasks::AsyncTasks};
38
39/// The header that carries the workload access token, in lowercase.
40#[cfg(any(feature = "runtime", feature = "identity"))]
41pub(crate) const WORKLOAD_ACCESS_TOKEN_HEADER: &str = "x-amz-bedrock-agentcore-identity-wat";
42
43tokio::task_local! {
44    static CURRENT: RequestContext;
45}
46
47/// Runs `future` with `ctx` as the ambient context returned by [`current`].
48///
49/// Scopes nest. When `future` completes, the previous ambient context is back in place.
50///
51/// The context is also in place when `future` is dropped, even if it was never
52/// polled, for example in a spawned task that is aborted before it starts.
53pub fn scope<F: Future>(ctx: RequestContext, future: F) -> impl Future<Output = F::Output> {
54    // Not an `async fn`: the scoped future must exist from this call on, so that
55    // dropping it before its first poll still drops `future` inside the context.
56    CURRENT.scope(ctx, future)
57}
58
59/// Runs `f` with `ctx` as the ambient context. The server uses it around each poll of
60/// a response body, which happens after the handler's future has completed.
61#[cfg(feature = "runtime")]
62pub(crate) fn sync_scope<R>(ctx: RequestContext, f: impl FnOnce() -> R) -> R {
63    CURRENT.sync_scope(ctx, f)
64}
65
66/// The context of the invocation that the calling code runs in.
67///
68/// Returns `None` outside an invocation, for example at startup or in a spawned task
69/// that was not wrapped in [`scope`].
70pub fn current() -> Option<RequestContext> {
71    CURRENT.try_with(Clone::clone).ok()
72}
73
74/// The workload access token of the invocation that the calling code runs in.
75///
76/// The token is an owned copy, for a call that needs it outside the context. Code
77/// that already holds a [`RequestContext`] can borrow the token with
78/// [`RequestContext::workload_access_token`].
79///
80/// # Errors
81///
82/// [`ErrorKind::MissingWorkloadToken`] when the call runs outside an invocation, or
83/// when the context has no token or an empty one. The text says which.
84pub fn workload_access_token() -> Result<WorkloadAccessToken, Error> {
85    let ctx = current();
86    ctx.as_ref()
87        .and_then(|ctx| ctx.workload_access_token().cloned())
88        .filter(|token| !token.expose().is_empty())
89        .ok_or_else(|| missing_workload_access_token(ctx.is_some()))
90}
91
92/// The error for a call that finds no workload access token. The text names the
93/// cause and what removes it.
94pub(crate) fn missing_workload_access_token(in_request_context: bool) -> Error {
95    let message = if in_request_context {
96        "No workload access token: the invocation carried none. AgentCore Runtime sends a token only when the \
97         caller names a user: a runtimeUserId with IAM authorization, which needs the \
98         bedrock-agentcore:InvokeAgentRuntimeForUser permission, or a JWT. A local call must send a token of a \
99         workload identity in the X-Amz-Bedrock-AgentCore-Identity-WAT header. The identity module \
100         documentation shows how to get one."
101    } else {
102        "No workload access token: this call ran outside a request context, for example in a task started with \
103         tokio::spawn. Wrap the future of the task in bedrock_agentcore::context::scope(ctx.clone(), ..), or give \
104         the operation a token with .workload_access_token(..)."
105    };
106    Error::new(ErrorKind::MissingWorkloadToken, message)
107}
108
109/// A workload access token of AgentCore Identity.
110///
111/// Its `Debug` output never contains the token. Read the value with [`expose`](Self::expose).
112#[derive(Clone, PartialEq, Eq)]
113pub struct WorkloadAccessToken(String);
114
115impl WorkloadAccessToken {
116    /// Wraps a token value.
117    pub fn new(token: impl Into<String>) -> Self {
118        Self(token.into())
119    }
120
121    /// The token value. Keep it out of logs.
122    pub fn expose(&self) -> &str {
123        &self.0
124    }
125}
126
127impl fmt::Debug for WorkloadAccessToken {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str("*** Sensitive Data Redacted ***")
130    }
131}
132
133/// The encrypted workload identity contexts that an app received, one for each
134/// session. Clones share the same store. A session keeps its context for a later
135/// invocation that carries none.
136#[derive(Clone, Default)]
137pub(crate) struct WorkloadIdentityContexts(Arc<Mutex<Vec<(String, String)>>>);
138
139impl WorkloadIdentityContexts {
140    /// An app has few sessions at a time. The oldest context leaves when one more arrives.
141    const MAX_SESSIONS: usize = 64;
142
143    fn record(&self, session_id: &str, context: String) {
144        let mut contexts = self.0.lock().unwrap_or_else(PoisonError::into_inner);
145        contexts.retain(|(session, _)| session != session_id);
146        if contexts.len() == Self::MAX_SESSIONS {
147            contexts.remove(0);
148        }
149        contexts.push((session_id.to_owned(), context));
150    }
151
152    pub(crate) fn get(&self, session_id: &str) -> Option<String> {
153        let contexts = self.0.lock().unwrap_or_else(PoisonError::into_inner);
154        contexts.iter().find(|(session, _)| session == session_id).map(|(_, context)| context.clone())
155    }
156}
157
158/// Metadata of one invocation.
159///
160/// The value is immutable and cheap to clone. Its `Debug` output contains header names
161/// but no header values and no token.
162#[derive(Clone)]
163pub struct RequestContext {
164    inner: Arc<Inner>,
165}
166
167struct Inner {
168    session_id: String,
169    request_id: String,
170    workload_access_token: Option<WorkloadAccessToken>,
171    oauth2_callback_url: Option<String>,
172    workload_identity_contexts: WorkloadIdentityContexts,
173    headers: HeaderMap,
174    request_headers: HeaderMap,
175    tasks: AsyncTasks,
176}
177
178impl RequestContext {
179    /// Starts a context for the session `session_id`.
180    ///
181    /// The runtime server builds the context of each invocation itself. Use this
182    /// builder in tests, or to run code that reads the ambient context outside the
183    /// server.
184    pub fn builder(session_id: impl Into<String>) -> RequestContextBuilder {
185        RequestContextBuilder {
186            inner: Inner {
187                session_id: session_id.into(),
188                request_id: String::new(),
189                workload_access_token: None,
190                oauth2_callback_url: None,
191                workload_identity_contexts: WorkloadIdentityContexts::default(),
192                headers: HeaderMap::new(),
193                request_headers: HeaderMap::new(),
194                tasks: AsyncTasks::new(),
195            },
196        }
197    }
198
199    /// The runtime session ID. It comes from the
200    /// `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header, or from the top-level
201    /// `sessionId` string of the request body when the header is absent.
202    pub fn session_id(&self) -> &str {
203        &self.inner.session_id
204    }
205
206    /// The request ID. It comes from the `X-Amzn-Bedrock-AgentCore-Runtime-Request-Id`
207    /// header. The SDK generates a UUID when the header is absent.
208    ///
209    /// In tests against AgentCore Runtime the service did not send this header, so
210    /// the ID of a deployed agent is the generated UUID. It is not the request ID
211    /// that the caller of `InvokeAgentRuntime` receives. To find the log lines of a
212    /// call, search for the session ID.
213    pub fn request_id(&self) -> &str {
214        &self.inner.request_id
215    }
216
217    /// The workload access token that AgentCore Runtime sent with this invocation.
218    ///
219    /// It comes from the `X-Amz-Bedrock-AgentCore-Identity-WAT` header, or from the
220    /// `WorkloadAccessToken` header when the first one is absent.
221    pub fn workload_access_token(&self) -> Option<&WorkloadAccessToken> {
222        self.inner.workload_access_token.as_ref()
223    }
224
225    /// The OAuth2 callback URL from the `OAuth2CallbackUrl` header.
226    ///
227    /// AgentCore Runtime does not add this header. In tests against the service it
228    /// passed the header on only when the caller sent it and the request header
229    /// allowlist of the agent runtime named it. An agent that needs a callback URL
230    /// on AgentCore Runtime sets it on the request, with
231    /// `Oauth2TokenBuilder::callback_url`.
232    pub fn oauth2_callback_url(&self) -> Option<&str> {
233        self.inner.oauth2_callback_url.as_deref()
234    }
235
236    /// The encrypted workload identity contexts of the app that received this
237    /// invocation. `WorkloadIdentityCredentials` exchanges the one of a session for
238    /// credentials.
239    #[cfg(feature = "identity")]
240    pub(crate) fn workload_identity_contexts(&self) -> &WorkloadIdentityContexts {
241        &self.inner.workload_identity_contexts
242    }
243
244    /// The request headers that an agent may forward to other services.
245    ///
246    /// The map holds only `Authorization`, headers whose name starts with
247    /// `X-Amzn-Bedrock-AgentCore-Runtime-Custom-`, and
248    /// `X-Amz-Bedrock-AgentCore-Identity-WAT`. A header that the request repeats has
249    /// one entry, with the values joined by a comma and a space. Every value is marked
250    /// sensitive, so `Debug` output of the map does not show it.
251    pub fn headers(&self) -> &HeaderMap {
252        &self.inner.headers
253    }
254
255    /// The headers of the request as the server received them. They include the
256    /// headers that the `requestHeaderAllowlist` of the agent runtime lets through,
257    /// such as an `X-Api-Key` header, and the `Accept` header.
258    ///
259    /// The encrypted workload identity context is not in the map. A header that the
260    /// request repeats has one entry for each value. Every value is marked
261    /// sensitive, so `Debug` output of the map does not show it. Forward only the
262    /// headers of [`headers`](Self::headers) to other services.
263    pub fn request_headers(&self) -> &HeaderMap {
264        &self.inner.request_headers
265    }
266}
267
268impl RequestContext {
269    /// The registry of background work of the app that received this invocation.
270    /// Work tracked here makes the app report `HealthyBusy`. See [`crate::tasks`].
271    pub fn tasks(&self) -> &AsyncTasks {
272        &self.inner.tasks
273    }
274}
275
276impl fmt::Debug for RequestContext {
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        f.debug_struct("RequestContext")
279            .field("session_id", &self.inner.session_id)
280            .field("request_id", &self.inner.request_id)
281            .field("workload_access_token", &self.inner.workload_access_token)
282            .field("oauth2_callback_url", &self.inner.oauth2_callback_url.as_ref().map(|_| "<set>"))
283            .field(
284                "workload_identity_context",
285                &self.inner.workload_identity_contexts.get(&self.inner.session_id).map(|_| "<set>"),
286            )
287            .field("headers", &self.inner.headers.keys().map(HeaderName::as_str).collect::<Vec<_>>())
288            .finish()
289    }
290}
291
292/// Builds a [`RequestContext`]. Create one with [`RequestContext::builder`].
293#[must_use]
294pub struct RequestContextBuilder {
295    inner: Inner,
296}
297
298impl RequestContextBuilder {
299    /// Sets the request ID. The default is a new UUID.
300    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
301        self.inner.request_id = request_id.into();
302        self
303    }
304
305    /// Sets the workload access token.
306    pub fn workload_access_token(mut self, token: WorkloadAccessToken) -> Self {
307        self.inner.workload_access_token = Some(token);
308        self
309    }
310
311    /// Sets the OAuth2 callback URL.
312    pub fn oauth2_callback_url(mut self, url: impl Into<String>) -> Self {
313        self.inner.oauth2_callback_url = Some(url.into());
314        self
315    }
316
317    /// Sets the encrypted workload identity context of the session. The runtime
318    /// server reads it from the
319    /// `X-Amzn-Bedrock-AgentCore-Runtime-Encrypted-Workload-Identity-Context` header
320    /// and keeps it for later invocations of the session. It is not in
321    /// [`RequestContext::headers`] and `Debug` does not show it.
322    pub fn workload_identity_context(self, context: impl Into<String>) -> Self {
323        self.inner.workload_identity_contexts.record(&self.inner.session_id, context.into());
324        self
325    }
326
327    /// Sets the store that the contexts of all invocations of an app share.
328    #[cfg(feature = "runtime")]
329    pub(crate) fn workload_identity_contexts(mut self, contexts: WorkloadIdentityContexts) -> Self {
330        self.inner.workload_identity_contexts = contexts;
331        self
332    }
333
334    /// Adds one entry to [`RequestContext::headers`]. The builder applies no filter.
335    ///
336    /// The value is marked sensitive, so its `Debug` output does not show it.
337    pub fn header(mut self, name: HeaderName, mut value: HeaderValue) -> Self {
338        value.set_sensitive(true);
339        self.inner.headers.append(name, value);
340        self
341    }
342
343    /// Adds one entry to [`RequestContext::request_headers`].
344    ///
345    /// The value is marked sensitive, so its `Debug` output does not show it.
346    pub fn request_header(mut self, name: HeaderName, mut value: HeaderValue) -> Self {
347        value.set_sensitive(true);
348        self.inner.request_headers.append(name, value);
349        self
350    }
351
352    /// Sets the registry returned by [`RequestContext::tasks`]. The default is a new
353    /// empty registry.
354    pub fn tasks(mut self, tasks: AsyncTasks) -> Self {
355        self.inner.tasks = tasks;
356        self
357    }
358
359    /// Builds the context.
360    pub fn build(mut self) -> RequestContext {
361        if self.inner.request_id.is_empty() {
362            self.inner.request_id = uuid::Uuid::new_v4().to_string();
363        }
364        RequestContext { inner: Arc::new(self.inner) }
365    }
366}
367
368impl fmt::Debug for RequestContextBuilder {
369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370        f.debug_struct("RequestContextBuilder").finish_non_exhaustive()
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    fn session() -> Option<String> {
379        current().map(|ctx| ctx.session_id().to_owned())
380    }
381
382    #[tokio::test]
383    async fn ambient_context_follows_scopes_and_not_unscoped_tasks() {
384        assert_eq!(session(), None, "outside any scope");
385        let outer = RequestContext::builder("outer").build();
386        let inner = RequestContext::builder("inner").build();
387
388        scope(outer.clone(), async {
389            assert_eq!(session().as_deref(), Some("outer"));
390            scope(inner, async { assert_eq!(session().as_deref(), Some("inner")) }).await;
391            assert_eq!(session().as_deref(), Some("outer"), "the outer context is back after a nested scope");
392
393            let unscoped = tokio::spawn(async { session() });
394            let scoped = tokio::spawn(scope(outer.clone(), async { session() }));
395            assert_eq!(unscoped.await.unwrap(), None, "a spawned task does not inherit the context");
396            assert_eq!(scoped.await.unwrap().as_deref(), Some("outer"));
397        })
398        .await;
399        assert_eq!(session(), None, "after the scope");
400    }
401
402    /// Records the ambient session when it is dropped.
403    struct RecordsOnDrop(std::sync::Arc<std::sync::Mutex<Option<String>>>);
404
405    impl Drop for RecordsOnDrop {
406        fn drop(&mut self) {
407            *self.0.lock().unwrap() = Some(session().unwrap_or_else(|| "no context".to_owned()));
408        }
409    }
410
411    #[tokio::test]
412    async fn scoped_future_is_dropped_within_its_context_even_when_it_was_never_polled() {
413        let ctx = RequestContext::builder("dropped").build();
414        // Dropped directly, and dropped by the runtime when its task is aborted. This
415        // runtime has one thread and the test does not yield before the abort.
416        for spawned in [false, true] {
417            let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
418            let guard = RecordsOnDrop(seen.clone());
419            let scoped = scope(ctx.clone(), async move {
420                let _guard = guard;
421            });
422            if spawned {
423                let task = tokio::spawn(scoped);
424                task.abort();
425                assert!(task.await.unwrap_err().is_cancelled());
426            } else {
427                drop(scoped);
428            }
429            assert_eq!(seen.lock().unwrap().as_deref(), Some("dropped"), "spawned: {spawned}");
430        }
431    }
432
433    #[tokio::test]
434    async fn owned_token_accessor_needs_a_nonempty_token_in_the_ambient_context() {
435        let with = |token: Option<&str>| {
436            let mut builder = RequestContext::builder("s");
437            if let Some(token) = token {
438                builder = builder.workload_access_token(WorkloadAccessToken::new(token));
439            }
440            scope(builder.build(), async { workload_access_token() })
441        };
442        assert_eq!(with(Some("SECRET-TOKEN")).await.unwrap().expose(), "SECRET-TOKEN");
443
444        // Outside a context, without a token, and with the empty token of a hand-built context.
445        let (outside, carried_none) = ("this call ran outside a request context", "the invocation carried none");
446        let missing = [
447            (workload_access_token(), outside),
448            (with(None).await, carried_none),
449            (with(Some("")).await, carried_none),
450        ];
451        for (missing, cause) in missing {
452            let error = missing.unwrap_err();
453            assert_eq!(error.kind(), ErrorKind::MissingWorkloadToken);
454            assert!(error.to_string().contains(cause), "{error}");
455        }
456        // The borrowed getter still returns the empty token as it was given.
457        let ctx = RequestContext::builder("s").workload_access_token(WorkloadAccessToken::new("")).build();
458        assert_eq!(ctx.workload_access_token().map(WorkloadAccessToken::expose), Some(""));
459    }
460
461    #[test]
462    fn built_context_has_a_request_id_and_hides_secrets_in_debug_output() {
463        let ctx = RequestContext::builder("s")
464            .workload_access_token(WorkloadAccessToken::new("SECRET-TOKEN"))
465            .oauth2_callback_url("https://secret.example/callback")
466            // The header types are reachable through the crate's re-export of `http`.
467            .header(crate::http::header::AUTHORIZATION, crate::http::HeaderValue::from_static("SECRET-AUTH"))
468            .build();
469        assert_eq!(ctx.request_id().parse::<uuid::Uuid>().unwrap().get_version_num(), 4);
470        assert_eq!(ctx.workload_access_token().unwrap().expose(), "SECRET-TOKEN");
471        assert_eq!(ctx.oauth2_callback_url(), Some("https://secret.example/callback"));
472        assert_eq!(RequestContext::builder("s").request_id("given").build().request_id(), "given");
473
474        let authorization = ctx.headers().get(http::header::AUTHORIZATION).unwrap();
475        assert_eq!(authorization, "SECRET-AUTH");
476        let debug = format!("{ctx:?} {:?} {:?} {authorization:?}", ctx.workload_access_token(), ctx.headers());
477        assert!(debug.contains("authorization") && debug.contains("session_id: \"s\""), "{debug}");
478        assert!(!debug.to_lowercase().contains("secret"), "{debug}");
479    }
480}