Skip to main content

a2a_server/
middleware.rs

1// Copyright AGNTCY Contributors (https://github.com/agntcy)
2// Copyright A2A Contributors (https://github.com/a2aproject)
3// SPDX-License-Identifier: Apache-2.0
4use a2a::A2AError;
5use async_trait::async_trait;
6use axum::extract::Query;
7use axum::http::{HeaderMap, Uri};
8use serde_json::Value;
9use std::collections::HashMap;
10
11/// Service parameters — metadata from HTTP headers or gRPC metadata.
12pub type ServiceParams = HashMap<String, Vec<String>>;
13
14/// The major version this build implements (§3.6.2). Minor is accepted
15/// unconditionally since nothing here branches on it.
16const SUPPORTED_MAJOR_VERSION: u32 = 1;
17
18/// Mirrors a2acli's own `parse_protocol_version`: tolerant of a bare major,
19/// extra trailing components, and surrounding whitespace.
20fn parse_major_version(value: &str) -> Option<u32> {
21    value.trim().split('.').next()?.parse().ok()
22}
23
24/// §3.6.2: reject a request whose `A2A-Version` service parameter names an
25/// unsupported major version. §3.6.1/§3.6.2 both require an absent value
26/// to be interpreted as "0.3", not as "whatever this interface happens to
27/// serve" -- so it's rejected here exactly like any other unsupported
28/// version, rather than silently processed as this build's version.
29///
30/// Every protocol binding calls this before dispatching a request, since
31/// §3.6.2 applies to each interface the agent exposes.
32pub fn check_a2a_version(params: &ServiceParams) -> Result<(), A2AError> {
33    let requested = params
34        .get("a2a-version")
35        .and_then(|v| v.first())
36        .map(String::as_str)
37        .unwrap_or("0.3");
38    match parse_major_version(requested) {
39        Some(SUPPORTED_MAJOR_VERSION) => Ok(()),
40        _ => Err(A2AError::version_not_supported(requested)),
41    }
42}
43
44/// Build [`ServiceParams`] from an axum [`HeaderMap`].
45///
46/// Header names are normalized to lowercase (axum does this for us), values
47/// that aren't valid ASCII are silently skipped, and multi-valued headers
48/// produce a `Vec<String>` in insertion order.
49pub(crate) fn extract_service_params(headers: &HeaderMap) -> ServiceParams {
50    let mut params = ServiceParams::new();
51    for (name, value) in headers {
52        if let Ok(v) = value.to_str() {
53            params
54                .entry(name.as_str().to_owned())
55                .or_default()
56                .push(v.to_owned());
57        }
58    }
59    params
60}
61
62/// §3.6.1 lets a client send `A2A-Version` as a query parameter instead of a
63/// header, so the query form fills in when the header is absent. Every HTTP
64/// binding calls this before [`check_a2a_version`].
65pub(crate) fn add_query_version(params: &mut ServiceParams, uri: &Uri) {
66    if params.contains_key("a2a-version") {
67        return;
68    }
69    let from_query = Query::<HashMap<String, String>>::try_from_uri(uri)
70        .ok()
71        .and_then(|Query(query)| {
72            query
73                .into_iter()
74                .find(|(name, _)| name.eq_ignore_ascii_case(a2a::SVC_PARAM_VERSION))
75        });
76    if let Some((_, version)) = from_query {
77        params.insert("a2a-version".to_owned(), vec![version]);
78    }
79}
80
81/// Authenticated user information.
82#[derive(Debug, Clone)]
83pub struct User {
84    pub name: String,
85    pub authenticated: bool,
86    pub attributes: HashMap<String, Value>,
87}
88
89impl User {
90    pub fn authenticated(name: impl Into<String>) -> Self {
91        User {
92            name: name.into(),
93            authenticated: true,
94            attributes: HashMap::new(),
95        }
96    }
97}
98
99/// Context for a single request being processed.
100pub struct CallContext {
101    pub method: String,
102    pub service_params: ServiceParams,
103    pub tenant: Option<String>,
104    pub user: Option<User>,
105}
106
107impl CallContext {
108    pub fn new(method: impl Into<String>, params: ServiceParams) -> Self {
109        CallContext {
110            method: method.into(),
111            service_params: params,
112            tenant: None,
113            user: None,
114        }
115    }
116}
117
118/// Server-side interceptor for modifying requests and responses.
119#[async_trait]
120pub trait CallInterceptor: Send + Sync + 'static {
121    async fn before(&self, ctx: &mut CallContext, request: &Value) -> Result<(), A2AError> {
122        let _ = (ctx, request);
123        Ok(())
124    }
125
126    async fn after(
127        &self,
128        ctx: &CallContext,
129        result: &Result<Value, A2AError>,
130    ) -> Result<(), A2AError> {
131        let _ = (ctx, result);
132        Ok(())
133    }
134}
135
136/// Wraps a [`RequestHandler`](crate::RequestHandler) with interceptors.
137pub struct InterceptedHandler<H> {
138    pub handler: H,
139    pub interceptors: Vec<Box<dyn CallInterceptor>>,
140}
141
142impl<H> InterceptedHandler<H> {
143    pub fn new(handler: H) -> Self {
144        InterceptedHandler {
145            handler,
146            interceptors: Vec::new(),
147        }
148    }
149
150    pub fn with_interceptor(mut self, interceptor: impl CallInterceptor) -> Self {
151        self.interceptors.push(Box::new(interceptor));
152        self
153    }
154}
155
156/// Server-side logging interceptor.
157pub struct LoggingInterceptor;
158
159#[async_trait]
160impl CallInterceptor for LoggingInterceptor {
161    async fn before(&self, ctx: &mut CallContext, _request: &Value) -> Result<(), A2AError> {
162        tracing::info!(method = %ctx.method, "A2A server request");
163        Ok(())
164    }
165
166    async fn after(
167        &self,
168        ctx: &CallContext,
169        result: &Result<Value, A2AError>,
170    ) -> Result<(), A2AError> {
171        match result {
172            Ok(_) => tracing::info!(method = %ctx.method, "A2A server response"),
173            Err(e) => tracing::warn!(method = %ctx.method, error = %e, "A2A server error"),
174        }
175        Ok(())
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use axum::http::HeaderValue;
183
184    #[test]
185    fn test_extract_service_params_empty() {
186        let headers = HeaderMap::new();
187        let params = extract_service_params(&headers);
188        assert!(params.is_empty());
189    }
190
191    #[test]
192    fn test_extract_service_params_basic() {
193        let mut headers = HeaderMap::new();
194        headers.insert(
195            "authorization",
196            HeaderValue::from_static("Bearer token-abc"),
197        );
198        headers.insert("x-tenant-id", HeaderValue::from_static("acme"));
199
200        let params = extract_service_params(&headers);
201
202        assert_eq!(
203            params.get("authorization"),
204            Some(&vec!["Bearer token-abc".to_string()])
205        );
206        assert_eq!(params.get("x-tenant-id"), Some(&vec!["acme".to_string()]));
207    }
208
209    #[test]
210    fn test_extract_service_params_multi_value() {
211        let mut headers = HeaderMap::new();
212        headers.append("x-forwarded-for", HeaderValue::from_static("10.0.0.1"));
213        headers.append("x-forwarded-for", HeaderValue::from_static("10.0.0.2"));
214
215        let params = extract_service_params(&headers);
216
217        assert_eq!(
218            params.get("x-forwarded-for"),
219            Some(&vec!["10.0.0.1".to_string(), "10.0.0.2".to_string()]),
220        );
221    }
222
223    #[test]
224    fn test_extract_service_params_lowercases_names() {
225        let mut headers = HeaderMap::new();
226        // HeaderMap normalizes the name to lowercase regardless of casing here.
227        headers.insert("Authorization", HeaderValue::from_static("Bearer cased"));
228        let params = extract_service_params(&headers);
229        assert_eq!(
230            params.get("authorization"),
231            Some(&vec!["Bearer cased".to_string()])
232        );
233        assert!(!params.contains_key("Authorization"));
234    }
235
236    #[test]
237    fn test_extract_service_params_skips_non_ascii_values() {
238        let mut headers = HeaderMap::new();
239        headers.insert("x-ascii", HeaderValue::from_static("ok"));
240        headers.insert(
241            "x-binary",
242            HeaderValue::from_bytes(&[0xff, 0xfe, 0xfd]).unwrap(),
243        );
244
245        let params = extract_service_params(&headers);
246
247        assert_eq!(params.get("x-ascii"), Some(&vec!["ok".to_string()]));
248        assert!(
249            !params.contains_key("x-binary"),
250            "non-ASCII value should be skipped, not produce an empty entry"
251        );
252    }
253
254    #[test]
255    fn test_user_authenticated() {
256        let user = User::authenticated("alice");
257        assert_eq!(user.name, "alice");
258        assert!(user.authenticated);
259        assert!(user.attributes.is_empty());
260    }
261
262    #[test]
263    fn test_call_context_new() {
264        let params = ServiceParams::new();
265        let ctx = CallContext::new(a2a::jsonrpc::methods::SEND_MESSAGE, params);
266        assert_eq!(ctx.method, a2a::jsonrpc::methods::SEND_MESSAGE);
267        assert!(ctx.tenant.is_none());
268        assert!(ctx.user.is_none());
269    }
270
271    #[test]
272    fn test_intercepted_handler_new() {
273        let handler = "dummy";
274        let ih = InterceptedHandler::new(handler);
275        assert_eq!(ih.handler, "dummy");
276        assert!(ih.interceptors.is_empty());
277    }
278
279    #[test]
280    fn test_intercepted_handler_with_interceptor() {
281        let handler = "dummy";
282        let ih = InterceptedHandler::new(handler).with_interceptor(LoggingInterceptor);
283        assert_eq!(ih.interceptors.len(), 1);
284    }
285
286    struct NoopInterceptor;
287
288    #[async_trait]
289    impl CallInterceptor for NoopInterceptor {}
290
291    #[tokio::test]
292    async fn test_noop_interceptor_before() {
293        let interceptor = NoopInterceptor;
294        let mut ctx = CallContext::new("test", ServiceParams::new());
295        let result = interceptor.before(&mut ctx, &Value::Null).await;
296        assert!(result.is_ok());
297    }
298
299    #[tokio::test]
300    async fn test_noop_interceptor_after() {
301        let interceptor = NoopInterceptor;
302        let ctx = CallContext::new("test", ServiceParams::new());
303        let result = interceptor.after(&ctx, &Ok(Value::Null)).await;
304        assert!(result.is_ok());
305    }
306
307    #[tokio::test]
308    async fn test_logging_interceptor_before() {
309        let interceptor = LoggingInterceptor;
310        let mut ctx = CallContext::new(a2a::jsonrpc::methods::SEND_MESSAGE, ServiceParams::new());
311        let result = interceptor.before(&mut ctx, &Value::Null).await;
312        assert!(result.is_ok());
313    }
314
315    #[tokio::test]
316    async fn test_logging_interceptor_after_ok() {
317        let interceptor = LoggingInterceptor;
318        let ctx = CallContext::new(a2a::jsonrpc::methods::SEND_MESSAGE, ServiceParams::new());
319        let result = interceptor.after(&ctx, &Ok(Value::Null)).await;
320        assert!(result.is_ok());
321    }
322
323    #[tokio::test]
324    async fn test_logging_interceptor_after_err() {
325        let interceptor = LoggingInterceptor;
326        let ctx = CallContext::new(a2a::jsonrpc::methods::SEND_MESSAGE, ServiceParams::new());
327        let err: Result<Value, A2AError> = Err(A2AError::internal("boom"));
328        let result = interceptor.after(&ctx, &err).await;
329        assert!(result.is_ok());
330    }
331}