adk_core/request_context.rs
1use std::collections::HashMap;
2
3/// Identity and authorization context extracted from an HTTP request.
4///
5/// This struct carries authenticated identity fields (user_id, scopes, metadata)
6/// that flow from the server's auth middleware into the agent invocation context.
7/// It lives in `adk-core` so that both `adk-server` (which produces it) and
8/// `adk-runner` (which consumes it) can reference it without circular dependencies.
9///
10/// # Example
11///
12/// ```rust
13/// use adk_core::RequestContext;
14///
15/// let ctx = RequestContext {
16/// user_id: "user-123".to_string(),
17/// scopes: vec!["read".to_string(), "write".to_string()],
18/// metadata: [("tenant".to_string(), "acme".to_string())].into(),
19/// };
20/// assert_eq!(ctx.user_id, "user-123");
21/// assert_eq!(ctx.scopes.len(), 2);
22/// ```
23#[derive(Debug, Clone)]
24pub struct RequestContext {
25 /// Authenticated user ID (e.g. from JWT `sub` or `email` claim).
26 pub user_id: String,
27 /// Granted scopes (e.g. from JWT `scope` or `scp` claim).
28 pub scopes: Vec<String>,
29 /// Additional metadata for custom middleware use.
30 pub metadata: HashMap<String, String>,
31}
32
33/// Extracts authenticated identity from HTTP request headers.
34///
35/// Implementations typically parse a Bearer token from the `Authorization`
36/// header, validate it, and map claims to a [`RequestContext`]. `adk-server`
37/// re-exports it as `adk_server::auth_bridge::RequestContextExtractor`.
38///
39/// # Example
40///
41/// ```rust
42/// use adk_core::RequestContext;
43/// use adk_core::request_context::{RequestContextError, RequestContextExtractor};
44///
45/// struct Header;
46///
47/// #[async_trait::async_trait]
48/// impl RequestContextExtractor for Header {
49/// async fn extract(
50/// &self,
51/// parts: &http::request::Parts,
52/// ) -> Result<RequestContext, RequestContextError> {
53/// let user = parts
54/// .headers
55/// .get("x-user")
56/// .and_then(|value| value.to_str().ok())
57/// .ok_or(RequestContextError::MissingAuth)?;
58/// Ok(RequestContext { user_id: user.to_string(), scopes: vec![], metadata: Default::default() })
59/// }
60/// }
61/// ```
62#[cfg(feature = "auth-bridge")]
63#[async_trait::async_trait]
64pub trait RequestContextExtractor: Send + Sync {
65 /// Extract identity from the request parts (headers, URI, etc.).
66 async fn extract(
67 &self,
68 parts: &http::request::Parts,
69 ) -> Result<RequestContext, RequestContextError>;
70}
71
72/// Errors that can occur during request context extraction.
73#[cfg(feature = "auth-bridge")]
74#[derive(Debug, thiserror::Error)]
75pub enum RequestContextError {
76 /// The `Authorization` header is missing from the request.
77 #[error("missing authorization header")]
78 MissingAuth,
79 /// The token was present but failed validation.
80 #[error("invalid token: {0}")]
81 InvalidToken(String),
82 /// An internal error occurred during extraction.
83 #[error("extraction failed: {0}")]
84 ExtractionFailed(String),
85}