adk-server 0.9.1

HTTP server and A2A protocol for Rust Agent Development Kit (ADK-Rust) agents
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
//! Bearer token authentication interceptor for A2A requests.
//!
//! This module provides a [`BearerAuthInterceptor`] that validates bearer tokens
//! from the `Authorization` header (stored in `ctx.metadata["authorization"]`).
//! It delegates token validation to a user-provided [`TokenValidator`] implementation.
//!
//! # Architecture
//!
//! The interceptor extracts the bearer token from the `authorization` metadata entry,
//! strips the `"Bearer "` prefix, and passes the raw token to the validator. On success,
//! the validator returns an optional `caller_id` that is set on the delegation context.
//! On failure, the request is rejected with a JSON-RPC error.
//!
//! # Example
//!
//! ```rust
//! use adk_server::a2a::interceptor::{
//!     A2aDelegationContext, A2aError, A2aInterceptor, InterceptorChain, InterceptorDecision,
//! };
//! use adk_server::a2a::bearer_auth::{BearerAuthInterceptor, TokenValidator};
//! use async_trait::async_trait;
//! use std::sync::Arc;
//!
//! struct MyValidator;
//!
//! #[async_trait]
//! impl TokenValidator for MyValidator {
//!     async fn validate_token(&self, token: &str) -> Result<Option<String>, A2aError> {
//!         if token == "valid-token-123" {
//!             Ok(Some("user-42".to_string()))
//!         } else {
//!             Err(A2aError::rejected(-32001, "invalid token"))
//!         }
//!     }
//! }
//!
//! # tokio_test::block_on(async {
//! let interceptor = BearerAuthInterceptor::new(Arc::new(MyValidator));
//! let chain = InterceptorChain::new().add(interceptor);
//!
//! let mut ctx = A2aDelegationContext {
//!     method: "tasks/send".to_string(),
//!     params: serde_json::json!({}),
//!     caller_id: None,
//!     metadata: std::collections::HashMap::from([
//!         ("authorization".to_string(), "Bearer valid-token-123".to_string()),
//!     ]),
//! };
//!
//! let decision = chain.run_before(&mut ctx).await.unwrap();
//! assert!(matches!(decision, InterceptorDecision::Continue));
//! assert_eq!(ctx.caller_id.as_deref(), Some("user-42"));
//! # });
//! ```

use std::sync::Arc;

use async_trait::async_trait;

use super::interceptor::{A2aDelegationContext, A2aError, A2aInterceptor, InterceptorDecision};

/// Trait for validating bearer tokens extracted from the Authorization header.
///
/// Implementations perform the actual token verification (e.g., JWT signature check,
/// database lookup, or external auth service call) and return an optional caller
/// identity on success.
///
/// # Example
///
/// ```rust
/// use adk_server::a2a::bearer_auth::TokenValidator;
/// use adk_server::a2a::interceptor::A2aError;
/// use async_trait::async_trait;
///
/// struct StaticValidator {
///     expected: String,
/// }
///
/// #[async_trait]
/// impl TokenValidator for StaticValidator {
///     async fn validate_token(&self, token: &str) -> Result<Option<String>, A2aError> {
///         if token == self.expected {
///             Ok(Some("authenticated-user".to_string()))
///         } else {
///             Err(A2aError::rejected(-32001, "invalid bearer token"))
///         }
///     }
/// }
/// ```
#[async_trait]
pub trait TokenValidator: Send + Sync {
    /// Validates the given bearer token.
    ///
    /// # Arguments
    ///
    /// * `token` - The raw bearer token (without the `"Bearer "` prefix).
    ///
    /// # Returns
    ///
    /// * `Ok(Some(caller_id))` — Token is valid; the returned string identifies the caller.
    /// * `Ok(None)` — Token is valid but no caller identity is available.
    /// * `Err(A2aError)` — Token is invalid or validation failed.
    async fn validate_token(&self, token: &str) -> Result<Option<String>, A2aError>;
}

/// A2A interceptor that validates bearer tokens in the Authorization header.
///
/// Extracts the bearer token from `ctx.metadata["authorization"]`, validates it
/// using the provided [`TokenValidator`], and sets `ctx.caller_id` on success.
/// Rejects the request if no token is present or if validation fails.
///
/// # Example
///
/// ```rust
/// use adk_server::a2a::bearer_auth::{BearerAuthInterceptor, TokenValidator};
/// use adk_server::a2a::interceptor::{
///     A2aDelegationContext, A2aError, A2aInterceptor, InterceptorChain, InterceptorDecision,
/// };
/// use async_trait::async_trait;
/// use std::sync::Arc;
///
/// struct AlwaysValid;
///
/// #[async_trait]
/// impl TokenValidator for AlwaysValid {
///     async fn validate_token(&self, _token: &str) -> Result<Option<String>, A2aError> {
///         Ok(Some("anonymous".to_string()))
///     }
/// }
///
/// # tokio_test::block_on(async {
/// let interceptor = BearerAuthInterceptor::new(Arc::new(AlwaysValid));
///
/// let mut ctx = A2aDelegationContext {
///     method: "tasks/send".to_string(),
///     params: serde_json::json!({}),
///     caller_id: None,
///     metadata: std::collections::HashMap::from([
///         ("authorization".to_string(), "Bearer my-token".to_string()),
///     ]),
/// };
///
/// let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
/// assert!(matches!(decision, InterceptorDecision::Continue));
/// assert_eq!(ctx.caller_id.as_deref(), Some("anonymous"));
/// # });
/// ```
#[derive(Clone)]
pub struct BearerAuthInterceptor {
    /// The token validator used to verify bearer tokens.
    pub validator: Arc<dyn TokenValidator>,
}

impl BearerAuthInterceptor {
    /// Creates a new `BearerAuthInterceptor` with the given token validator.
    ///
    /// # Arguments
    ///
    /// * `validator` - An implementation of [`TokenValidator`] wrapped in an `Arc`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_server::a2a::bearer_auth::{BearerAuthInterceptor, TokenValidator};
    /// use adk_server::a2a::interceptor::A2aError;
    /// use async_trait::async_trait;
    /// use std::sync::Arc;
    ///
    /// struct MyValidator;
    ///
    /// #[async_trait]
    /// impl TokenValidator for MyValidator {
    ///     async fn validate_token(&self, _token: &str) -> Result<Option<String>, A2aError> {
    ///         Ok(None)
    ///     }
    /// }
    ///
    /// let interceptor = BearerAuthInterceptor::new(Arc::new(MyValidator));
    /// ```
    pub fn new(validator: Arc<dyn TokenValidator>) -> Self {
        Self { validator }
    }

    /// Extracts the bearer token from the authorization header value.
    ///
    /// Returns `None` if the value does not start with `"Bearer "` (case-insensitive prefix).
    fn extract_bearer_token(auth_value: &str) -> Option<&str> {
        let trimmed = auth_value.trim();
        if trimmed.len() > 7 && trimmed[..7].eq_ignore_ascii_case("bearer ") {
            Some(&trimmed[7..])
        } else {
            None
        }
    }
}

#[async_trait]
impl A2aInterceptor for BearerAuthInterceptor {
    /// Validates the bearer token from `ctx.metadata["authorization"]`.
    ///
    /// On success, sets `ctx.caller_id` to the identity returned by the validator.
    /// On failure (missing header, malformed token, or validation error), rejects
    /// the request with a JSON-RPC error code `-32001`.
    async fn before_delegation(
        &self,
        ctx: &mut A2aDelegationContext,
    ) -> Result<InterceptorDecision, A2aError> {
        let auth_header = match ctx.metadata.get("authorization") {
            Some(value) => value.clone(),
            None => {
                return Ok(InterceptorDecision::Reject {
                    code: -32001,
                    message: "missing authorization header".to_string(),
                });
            }
        };

        let token = match Self::extract_bearer_token(&auth_header) {
            Some(t) => t,
            None => {
                return Ok(InterceptorDecision::Reject {
                    code: -32001,
                    message: "invalid authorization header: expected Bearer scheme".to_string(),
                });
            }
        };

        match self.validator.validate_token(token).await {
            Ok(caller_id) => {
                ctx.caller_id = caller_id;
                Ok(InterceptorDecision::Continue)
            }
            Err(err) => Ok(InterceptorDecision::Reject {
                code: err.code().unwrap_or(-32001),
                message: err.to_string(),
            }),
        }
    }

    /// No-op for the bearer auth interceptor. Authentication is handled entirely
    /// in `before_delegation`.
    async fn after_delegation(
        &self,
        _ctx: &A2aDelegationContext,
        _response: &mut serde_json::Value,
    ) -> Result<(), A2aError> {
        Ok(())
    }
}

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

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

    struct AcceptAllValidator;

    #[async_trait]
    impl TokenValidator for AcceptAllValidator {
        async fn validate_token(&self, _token: &str) -> Result<Option<String>, A2aError> {
            Ok(Some("test-user".to_string()))
        }
    }

    struct RejectAllValidator;

    #[async_trait]
    impl TokenValidator for RejectAllValidator {
        async fn validate_token(&self, _token: &str) -> Result<Option<String>, A2aError> {
            Err(A2aError::rejected(-32001, "token rejected"))
        }
    }

    struct NoCaller;

    #[async_trait]
    impl TokenValidator for NoCaller {
        async fn validate_token(&self, _token: &str) -> Result<Option<String>, A2aError> {
            Ok(None)
        }
    }

    fn make_ctx_with_auth(auth: &str) -> A2aDelegationContext {
        A2aDelegationContext {
            method: "tasks/send".to_string(),
            params: serde_json::json!({}),
            caller_id: None,
            metadata: HashMap::from([("authorization".to_string(), auth.to_string())]),
        }
    }

    fn make_ctx_no_auth() -> A2aDelegationContext {
        A2aDelegationContext {
            method: "tasks/send".to_string(),
            params: serde_json::json!({}),
            caller_id: None,
            metadata: HashMap::new(),
        }
    }

    #[tokio::test]
    async fn test_valid_bearer_token_sets_caller_id() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(AcceptAllValidator));
        let mut ctx = make_ctx_with_auth("Bearer my-secret-token");

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        assert!(matches!(decision, InterceptorDecision::Continue));
        assert_eq!(ctx.caller_id.as_deref(), Some("test-user"));
    }

    #[tokio::test]
    async fn test_valid_bearer_token_no_caller_id() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(NoCaller));
        let mut ctx = make_ctx_with_auth("Bearer some-token");

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        assert!(matches!(decision, InterceptorDecision::Continue));
        assert_eq!(ctx.caller_id, None);
    }

    #[tokio::test]
    async fn test_missing_authorization_header_rejects() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(AcceptAllValidator));
        let mut ctx = make_ctx_no_auth();

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        match decision {
            InterceptorDecision::Reject { code, message } => {
                assert_eq!(code, -32001);
                assert!(message.contains("missing authorization header"));
            }
            _ => panic!("expected Reject"),
        }
    }

    #[tokio::test]
    async fn test_non_bearer_scheme_rejects() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(AcceptAllValidator));
        let mut ctx = make_ctx_with_auth("Basic dXNlcjpwYXNz");

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        match decision {
            InterceptorDecision::Reject { code, message } => {
                assert_eq!(code, -32001);
                assert!(message.contains("expected Bearer scheme"));
            }
            _ => panic!("expected Reject"),
        }
    }

    #[tokio::test]
    async fn test_invalid_token_rejects() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(RejectAllValidator));
        let mut ctx = make_ctx_with_auth("Bearer bad-token");

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        match decision {
            InterceptorDecision::Reject { code, message } => {
                assert_eq!(code, -32001);
                assert!(message.contains("token rejected"));
            }
            _ => panic!("expected Reject"),
        }
    }

    #[tokio::test]
    async fn test_bearer_prefix_case_insensitive() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(AcceptAllValidator));
        let mut ctx = make_ctx_with_auth("BEARER my-token");

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        assert!(matches!(decision, InterceptorDecision::Continue));
        assert_eq!(ctx.caller_id.as_deref(), Some("test-user"));
    }

    #[tokio::test]
    async fn test_bearer_prefix_with_leading_whitespace() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(AcceptAllValidator));
        let mut ctx = make_ctx_with_auth("  Bearer my-token");

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        assert!(matches!(decision, InterceptorDecision::Continue));
        assert_eq!(ctx.caller_id.as_deref(), Some("test-user"));
    }

    #[tokio::test]
    async fn test_after_delegation_is_noop() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(AcceptAllValidator));
        let ctx = A2aDelegationContext {
            method: "tasks/send".to_string(),
            params: serde_json::json!({}),
            caller_id: Some("user".to_string()),
            metadata: HashMap::new(),
        };
        let mut response = serde_json::json!({"result": "ok"});

        let result = interceptor.after_delegation(&ctx, &mut response).await;
        assert!(result.is_ok());
        assert_eq!(response, serde_json::json!({"result": "ok"}));
    }

    #[tokio::test]
    async fn test_empty_bearer_value_rejects() {
        let interceptor = BearerAuthInterceptor::new(Arc::new(AcceptAllValidator));
        let mut ctx = make_ctx_with_auth("Bearer");

        let decision = interceptor.before_delegation(&mut ctx).await.unwrap();
        match decision {
            InterceptorDecision::Reject { code, message } => {
                assert_eq!(code, -32001);
                assert!(message.contains("expected Bearer scheme"));
            }
            _ => panic!("expected Reject"),
        }
    }
}