Skip to main content

adk_server/
auth_bridge.rs

1//! Auth middleware bridge for flowing authenticated identity into agent execution.
2//!
3//! This module defines the [`RequestContextExtractor`] trait that server operators
4//! implement to extract identity from HTTP requests, and the [`RequestContextError`]
5//! enum for extraction failures.
6//!
7//! The extracted [`RequestContext`] (re-exported from `adk-core`) carries user_id,
8//! scopes, and metadata into the `InvocationContext`, making scopes available
9//! to tools via `ToolContext::user_scopes()`.
10//!
11//! # Example
12//!
13//! ```rust,ignore
14//! use adk_server::auth_bridge::{RequestContextExtractor, RequestContextError};
15//! use adk_core::RequestContext;
16//! use async_trait::async_trait;
17//!
18//! struct MyExtractor;
19//!
20//! #[async_trait]
21//! impl RequestContextExtractor for MyExtractor {
22//!     async fn extract(
23//!         &self,
24//!         parts: &axum::http::request::Parts,
25//!     ) -> Result<RequestContext, RequestContextError> {
26//!         let auth = parts.headers
27//!             .get("authorization")
28//!             .and_then(|v| v.to_str().ok())
29//!             .ok_or(RequestContextError::MissingAuth)?;
30//!         // ... validate token, build RequestContext ...
31//!         # todo!()
32//!     }
33//! }
34//! ```
35
36pub use adk_core::RequestContext;
37pub use adk_core::request_context::{RequestContextError, RequestContextExtractor};
38use axum::extract::FromRequestParts;
39use axum::http::request::Parts;
40use std::convert::Infallible;
41
42/// The authenticated principal of a request, read from the request extensions.
43///
44/// The server's authentication layer stores the extracted identity as an
45/// `Option<RequestContext>` extension; middleware written outside this crate
46/// can also store a bare [`RequestContext`]. This extractor accepts either and
47/// never rejects: it yields `None` when no authentication ran, which is how a
48/// handler tells an unauthenticated deployment from an authenticated caller.
49///
50/// # Example
51///
52/// ```rust
53/// use adk_server::auth_bridge::AuthenticatedCaller;
54///
55/// async fn whoami(AuthenticatedCaller(caller): AuthenticatedCaller) -> String {
56///     caller.map_or_else(|| "anonymous".to_string(), |context| context.user_id)
57/// }
58///
59/// let _app: axum::Router = axum::Router::new().route("/whoami", axum::routing::get(whoami));
60/// ```
61#[derive(Debug, Clone, Default)]
62pub struct AuthenticatedCaller(pub Option<RequestContext>);
63
64impl AuthenticatedCaller {
65    /// Returns the authenticated user ID, or `None` when no authentication ran.
66    pub fn user_id(&self) -> Option<&str> {
67        self.0.as_ref().map(|context| context.user_id.as_str())
68    }
69}
70
71impl<S: Send + Sync> FromRequestParts<S> for AuthenticatedCaller {
72    type Rejection = Infallible;
73
74    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
75        let context = parts
76            .extensions
77            .get::<Option<RequestContext>>()
78            .cloned()
79            .flatten()
80            .or_else(|| parts.extensions.get::<RequestContext>().cloned());
81        Ok(Self(context))
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88
89    fn context(user_id: &str) -> RequestContext {
90        RequestContext {
91            user_id: user_id.to_string(),
92            scopes: vec![],
93            metadata: Default::default(),
94        }
95    }
96
97    async fn extract(parts: &mut Parts) -> Option<String> {
98        let caller = AuthenticatedCaller::from_request_parts(parts, &()).await.unwrap();
99        caller.user_id().map(str::to_string)
100    }
101
102    #[tokio::test]
103    async fn reads_the_auth_layer_extension() {
104        let (mut parts, ()) = axum::http::Request::new(()).into_parts();
105        parts.extensions.insert::<Option<RequestContext>>(Some(context("alice")));
106        assert_eq!(extract(&mut parts).await, Some("alice".to_string()));
107    }
108
109    #[tokio::test]
110    async fn reads_a_bare_request_context_extension() {
111        let (mut parts, ()) = axum::http::Request::new(()).into_parts();
112        parts.extensions.insert(context("bob"));
113        assert_eq!(extract(&mut parts).await, Some("bob".to_string()));
114    }
115
116    #[tokio::test]
117    async fn is_none_without_authentication() {
118        let (mut parts, ()) = axum::http::Request::new(()).into_parts();
119        assert_eq!(extract(&mut parts).await, None);
120        parts.extensions.insert::<Option<RequestContext>>(None);
121        assert_eq!(extract(&mut parts).await, None);
122    }
123}