1use 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#[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
47pub fn scope<F: Future>(ctx: RequestContext, future: F) -> impl Future<Output = F::Output> {
54 CURRENT.scope(ctx, future)
57}
58
59#[cfg(feature = "runtime")]
62pub(crate) fn sync_scope<R>(ctx: RequestContext, f: impl FnOnce() -> R) -> R {
63 CURRENT.sync_scope(ctx, f)
64}
65
66pub fn current() -> Option<RequestContext> {
71 CURRENT.try_with(Clone::clone).ok()
72}
73
74pub 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
92pub(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#[derive(Clone, PartialEq, Eq)]
113pub struct WorkloadAccessToken(String);
114
115impl WorkloadAccessToken {
116 pub fn new(token: impl Into<String>) -> Self {
118 Self(token.into())
119 }
120
121 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#[derive(Clone, Default)]
137pub(crate) struct WorkloadIdentityContexts(Arc<Mutex<Vec<(String, String)>>>);
138
139impl WorkloadIdentityContexts {
140 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#[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 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 pub fn session_id(&self) -> &str {
203 &self.inner.session_id
204 }
205
206 pub fn request_id(&self) -> &str {
214 &self.inner.request_id
215 }
216
217 pub fn workload_access_token(&self) -> Option<&WorkloadAccessToken> {
222 self.inner.workload_access_token.as_ref()
223 }
224
225 pub fn oauth2_callback_url(&self) -> Option<&str> {
233 self.inner.oauth2_callback_url.as_deref()
234 }
235
236 #[cfg(feature = "identity")]
240 pub(crate) fn workload_identity_contexts(&self) -> &WorkloadIdentityContexts {
241 &self.inner.workload_identity_contexts
242 }
243
244 pub fn headers(&self) -> &HeaderMap {
252 &self.inner.headers
253 }
254
255 pub fn request_headers(&self) -> &HeaderMap {
264 &self.inner.request_headers
265 }
266}
267
268impl RequestContext {
269 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#[must_use]
294pub struct RequestContextBuilder {
295 inner: Inner,
296}
297
298impl RequestContextBuilder {
299 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 pub fn workload_access_token(mut self, token: WorkloadAccessToken) -> Self {
307 self.inner.workload_access_token = Some(token);
308 self
309 }
310
311 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 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 #[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 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 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 pub fn tasks(mut self, tasks: AsyncTasks) -> Self {
355 self.inner.tasks = tasks;
356 self
357 }
358
359 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 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 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 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 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 .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}