1use std::{
12 collections::HashSet,
13 fmt,
14 pin::Pin,
15 sync::Arc,
16 time::{Duration, SystemTime},
17};
18
19use a2a as wire;
20use a2a_server::{RequestHandler, ServiceParams};
21use async_trait::async_trait;
22use axum::{
23 Json, Router,
24 body::Body,
25 extract::{DefaultBodyLimit, Request, State},
26 http::{
27 HeaderMap, HeaderValue, Method, Response, StatusCode,
28 header::{
29 ACCESS_CONTROL_ALLOW_ORIGIN, AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, ETAG, HOST,
30 IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED, RETRY_AFTER, VARY, WWW_AUTHENTICATE,
31 },
32 },
33 middleware::{self, Next},
34 response::IntoResponse,
35 routing::get,
36};
37use futures_core::Stream;
38use futures_util::StreamExt as _;
39use http_body_util::{BodyExt as _, Limited};
40use serde::{Serialize, de::DeserializeOwned};
41use sha2::{Digest as _, Sha256};
42use stateknot_core::{BoxFuture, PrincipalIdentity, TenantId};
43use thiserror::Error;
44use tokio::sync::{OwnedSemaphorePermit, Semaphore};
45use tokio_util::sync::CancellationToken;
46
47use crate::{
48 A2A_AGENT_CARD_PATH, A2A_PROTOCOL_VERSION_1_0, A2aAgentCard, A2aCancelTaskRequest,
49 A2aContractError, A2aDeletePushConfigRequest, A2aGetPushConfigRequest, A2aGetTaskRequest,
50 A2aListPushConfigsRequest, A2aListTasksRequest, A2aPushConfig, A2aPushConfigPage, A2aSecret,
51 A2aSendMessageRequest, A2aSendMessageResponse, A2aStreamEvent, A2aSubscribeTaskRequest,
52 A2aTask, A2aTaskPage,
53};
54
55const A2A_VERSION_HEADER: &str = "a2a-version";
56const A2A_EXTENSIONS_HEADER: &str = "a2a-extensions";
57const DEFAULT_REST_PREFIX: &str = "/a2a/rest";
58const DEFAULT_JSONRPC_PATH: &str = "/a2a/jsonrpc";
59const MAX_BEARER_BYTES: usize = 16 * 1024;
60const MAX_EXTENSION_HEADER_BYTES: usize = 16 * 1024;
61const MAX_NEGOTIATED_EXTENSIONS: usize = 64;
62
63tokio::task_local! {
64 static A2A_REQUEST_PRINCIPAL: A2aServerPrincipal;
65}
66
67#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
69#[non_exhaustive]
70pub enum A2aServerOperation {
71 SendMessage,
73 SendStreamingMessage,
75 GetTask,
77 ListTasks,
79 CancelTask,
81 SubscribeToTask,
83 CreatePushConfig,
85 GetPushConfig,
87 ListPushConfigs,
89 DeletePushConfig,
91 GetExtendedAgentCard,
93}
94
95#[derive(Clone, Debug, Eq, PartialEq)]
97pub struct A2aServerPrincipal {
98 tenant: TenantId,
99 identity: PrincipalIdentity,
100 scopes: Arc<[Box<str>]>,
101}
102
103impl A2aServerPrincipal {
104 pub const MAX_SCOPES: usize = 128;
106 pub const MAX_SCOPE_BYTES: usize = 256;
108
109 pub fn new(
111 tenant: TenantId,
112 identity: PrincipalIdentity,
113 scopes: impl IntoIterator<Item = impl Into<String>>,
114 ) -> Result<Self, A2aServerPrincipalError> {
115 let mut scopes = scopes.into_iter().map(Into::into).collect::<Vec<_>>();
116 if scopes.len() > Self::MAX_SCOPES {
117 return Err(A2aServerPrincipalError::TooManyScopes);
118 }
119 for scope in &scopes {
120 if scope.is_empty()
121 || scope.len() > Self::MAX_SCOPE_BYTES
122 || scope
123 .bytes()
124 .any(|byte| !matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~'))
125 {
126 return Err(A2aServerPrincipalError::InvalidScope);
127 }
128 }
129 scopes.sort_unstable();
130 if scopes.windows(2).any(|pair| pair[0] == pair[1]) {
131 return Err(A2aServerPrincipalError::DuplicateScope);
132 }
133 Ok(Self {
134 tenant,
135 identity,
136 scopes: scopes
137 .into_iter()
138 .map(String::into_boxed_str)
139 .collect::<Vec<_>>()
140 .into(),
141 })
142 }
143
144 #[must_use]
146 pub const fn tenant(&self) -> &TenantId {
147 &self.tenant
148 }
149
150 #[must_use]
152 pub const fn identity(&self) -> &PrincipalIdentity {
153 &self.identity
154 }
155
156 pub fn scopes(&self) -> impl ExactSizeIterator<Item = &str> {
158 self.scopes.iter().map(AsRef::as_ref)
159 }
160
161 #[must_use]
163 pub fn has_scope(&self, value: &str) -> bool {
164 self.scopes
165 .binary_search_by(|candidate| candidate.as_ref().cmp(value))
166 .is_ok()
167 }
168}
169
170#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
172#[non_exhaustive]
173pub enum A2aServerPrincipalError {
174 #[error("too many A2A principal scopes")]
176 TooManyScopes,
177 #[error("invalid A2A principal scope")]
179 InvalidScope,
180 #[error("duplicate A2A principal scope")]
182 DuplicateScope,
183}
184
185pub struct A2aServerAuthenticationRequest {
187 bearer: Option<A2aSecret>,
188 method: Method,
189 path: Box<str>,
190}
191
192impl A2aServerAuthenticationRequest {
193 #[must_use]
195 pub const fn bearer(&self) -> Option<&A2aSecret> {
196 self.bearer.as_ref()
197 }
198
199 #[must_use]
201 pub const fn method(&self) -> &Method {
202 &self.method
203 }
204
205 #[must_use]
208 pub fn path(&self) -> &str {
209 &self.path
210 }
211}
212
213impl fmt::Debug for A2aServerAuthenticationRequest {
214 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
215 formatter
216 .debug_struct("A2aServerAuthenticationRequest")
217 .field("bearer", &self.bearer.as_ref().map(|_| "[REDACTED]"))
218 .field("method", &self.method)
219 .field("path", &self.path)
220 .finish()
221 }
222}
223
224#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
226#[non_exhaustive]
227pub enum A2aServerAuthenticationError {
228 #[error("A2A credential is invalid")]
231 InvalidCredential,
232 #[error("A2A access is forbidden")]
234 Forbidden,
235 #[error("A2A authentication is unavailable")]
237 Unavailable,
238}
239
240pub trait A2aServerAuthenticator: Send + Sync + 'static {
242 fn authenticate(
245 &self,
246 request: A2aServerAuthenticationRequest,
247 ) -> BoxFuture<'_, Result<A2aServerPrincipal, A2aServerAuthenticationError>>;
248}
249
250#[derive(Clone, Debug)]
252pub struct A2aServerAuthorizationRequest {
253 principal: A2aServerPrincipal,
254 operation: A2aServerOperation,
255 task_id: Option<Box<str>>,
256 config_id: Option<Box<str>>,
257}
258
259impl A2aServerAuthorizationRequest {
260 #[must_use]
262 pub const fn principal(&self) -> &A2aServerPrincipal {
263 &self.principal
264 }
265
266 #[must_use]
268 pub const fn operation(&self) -> A2aServerOperation {
269 self.operation
270 }
271
272 #[must_use]
274 pub fn task_id(&self) -> Option<&str> {
275 self.task_id.as_deref()
276 }
277
278 #[must_use]
280 pub fn config_id(&self) -> Option<&str> {
281 self.config_id.as_deref()
282 }
283}
284
285#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
288#[non_exhaustive]
289pub enum A2aServerAuthorizationError {
290 #[error("A2A operation is forbidden")]
292 Forbidden,
293 #[error("A2A authorization is unavailable")]
295 Unavailable,
296}
297
298pub trait A2aServerAuthorizer: Send + Sync + 'static {
300 fn authorize(
303 &self,
304 request: A2aServerAuthorizationRequest,
305 ) -> BoxFuture<'_, Result<(), A2aServerAuthorizationError>>;
306}
307
308#[derive(Clone, Debug)]
311pub struct A2aServerAdmissionRequest {
312 principal: A2aServerPrincipal,
313 operation: A2aServerOperation,
314}
315
316impl A2aServerAdmissionRequest {
317 #[must_use]
319 pub const fn principal(&self) -> &A2aServerPrincipal {
320 &self.principal
321 }
322
323 #[must_use]
325 pub const fn operation(&self) -> A2aServerOperation {
326 self.operation
327 }
328}
329
330#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
332#[non_exhaustive]
333pub enum A2aServerAdmissionError {
334 #[error("A2A request is rate limited")]
336 Rejected,
337 #[error("A2A admission is unavailable")]
339 Unavailable,
340}
341
342pub trait A2aServerAdmissionControl: Send + Sync + 'static {
344 fn admit(
346 &self,
347 request: A2aServerAdmissionRequest,
348 ) -> BoxFuture<'_, Result<(), A2aServerAdmissionError>>;
349}
350
351#[derive(Clone, Copy, Debug, Default)]
354pub struct AllowA2aServerAuthorization;
355
356impl A2aServerAuthorizer for AllowA2aServerAuthorization {
357 fn authorize(
358 &self,
359 _request: A2aServerAuthorizationRequest,
360 ) -> BoxFuture<'_, Result<(), A2aServerAuthorizationError>> {
361 Box::pin(async { Ok(()) })
362 }
363}
364
365#[derive(Clone, Copy, Debug, Default)]
368pub struct AllowA2aServerAdmission;
369
370impl A2aServerAdmissionControl for AllowA2aServerAdmission {
371 fn admit(
372 &self,
373 _request: A2aServerAdmissionRequest,
374 ) -> BoxFuture<'_, Result<(), A2aServerAdmissionError>> {
375 Box::pin(async { Ok(()) })
376 }
377}
378
379#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
381pub struct A2aTaskServiceCapabilities {
382 pub streaming: bool,
384 pub push_notifications: bool,
386 pub extended_agent_card: bool,
388}
389
390#[derive(Clone, Debug)]
392pub struct A2aRequestContext {
393 principal: A2aServerPrincipal,
394 extensions: Arc<[Box<str>]>,
395}
396
397impl A2aRequestContext {
398 #[must_use]
400 pub const fn principal(&self) -> &A2aServerPrincipal {
401 &self.principal
402 }
403
404 pub fn negotiated_extensions(&self) -> impl ExactSizeIterator<Item = &str> {
407 self.extensions.iter().map(AsRef::as_ref)
408 }
409}
410
411#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
413#[non_exhaustive]
414pub enum A2aTaskServiceError {
415 #[error("A2A task was not found")]
417 TaskNotFound,
418 #[error("A2A task cannot be canceled")]
420 TaskNotCancelable,
421 #[error("A2A push notifications are not supported")]
423 PushNotificationsNotSupported,
424 #[error("A2A operation is not supported")]
426 UnsupportedOperation,
427 #[error("A2A content type is not supported")]
429 ContentTypeNotSupported,
430 #[error("A2A agent response is invalid")]
432 InvalidAgentResponse,
433 #[error("A2A extended Agent Card is not configured")]
435 ExtendedCardNotConfigured,
436 #[error("required A2A extension was not negotiated")]
438 ExtensionSupportRequired,
439 #[error("A2A request is invalid")]
441 InvalidRequest,
442 #[error("A2A service is unavailable")]
444 Unavailable,
445}
446
447pub type A2aEventStream =
450 Pin<Box<dyn Stream<Item = Result<A2aStreamEvent, A2aTaskServiceError>> + Send + 'static>>;
451
452pub trait A2aTaskService: Send + Sync + 'static {
459 fn capabilities(&self) -> A2aTaskServiceCapabilities;
461
462 fn send_message(
464 &self,
465 context: A2aRequestContext,
466 request: A2aSendMessageRequest,
467 ) -> BoxFuture<'_, Result<A2aSendMessageResponse, A2aTaskServiceError>>;
468
469 fn send_streaming_message(
471 &self,
472 context: A2aRequestContext,
473 request: A2aSendMessageRequest,
474 ) -> BoxFuture<'_, Result<A2aEventStream, A2aTaskServiceError>>;
475
476 fn get_task(
478 &self,
479 context: A2aRequestContext,
480 request: A2aGetTaskRequest,
481 ) -> BoxFuture<'_, Result<A2aTask, A2aTaskServiceError>>;
482
483 fn list_tasks(
485 &self,
486 context: A2aRequestContext,
487 request: A2aListTasksRequest,
488 ) -> BoxFuture<'_, Result<A2aTaskPage, A2aTaskServiceError>>;
489
490 fn cancel_task(
492 &self,
493 context: A2aRequestContext,
494 request: A2aCancelTaskRequest,
495 ) -> BoxFuture<'_, Result<A2aTask, A2aTaskServiceError>>;
496
497 fn subscribe_to_task(
499 &self,
500 context: A2aRequestContext,
501 request: A2aSubscribeTaskRequest,
502 ) -> BoxFuture<'_, Result<A2aEventStream, A2aTaskServiceError>>;
503
504 fn create_push_config(
506 &self,
507 context: A2aRequestContext,
508 config: A2aPushConfig,
509 ) -> BoxFuture<'_, Result<A2aPushConfig, A2aTaskServiceError>>;
510
511 fn get_push_config(
513 &self,
514 context: A2aRequestContext,
515 request: A2aGetPushConfigRequest,
516 ) -> BoxFuture<'_, Result<A2aPushConfig, A2aTaskServiceError>>;
517
518 fn list_push_configs(
520 &self,
521 context: A2aRequestContext,
522 request: A2aListPushConfigsRequest,
523 ) -> BoxFuture<'_, Result<A2aPushConfigPage, A2aTaskServiceError>>;
524
525 fn delete_push_config(
527 &self,
528 context: A2aRequestContext,
529 request: A2aDeletePushConfigRequest,
530 ) -> BoxFuture<'_, Result<(), A2aTaskServiceError>>;
531
532 fn get_extended_agent_card(
534 &self,
535 context: A2aRequestContext,
536 ) -> BoxFuture<'_, Result<A2aAgentCard, A2aTaskServiceError>>;
537}
538
539#[derive(Clone, Debug)]
541pub struct A2aServerHttpOptions {
542 rest_prefix: Box<str>,
543 jsonrpc_path: Box<str>,
544 allowed_authorities: Arc<[Box<str>]>,
545 allowed_origins: Arc<[Box<str>]>,
546 maximum_body_bytes: usize,
547 maximum_response_body_bytes: usize,
548 maximum_in_flight_requests: usize,
549 maximum_in_flight_operations: usize,
550 request_timeout: Duration,
551 stream_idle_timeout: Duration,
552 maximum_stream_events: u32,
553 card_max_age: Duration,
554 bearer_challenge: Option<Box<str>>,
555}
556
557impl A2aServerHttpOptions {
558 #[must_use]
561 pub fn new() -> Self {
562 Self {
563 rest_prefix: DEFAULT_REST_PREFIX.into(),
564 jsonrpc_path: DEFAULT_JSONRPC_PATH.into(),
565 allowed_authorities: Arc::from([]),
566 allowed_origins: Arc::from([]),
567 maximum_body_bytes: 1024 * 1024,
568 maximum_response_body_bytes: 8 * 1024 * 1024,
569 maximum_in_flight_requests: 1024,
570 maximum_in_flight_operations: 512,
571 request_timeout: Duration::from_secs(30),
572 stream_idle_timeout: Duration::from_secs(60),
573 maximum_stream_events: 16_384,
574 card_max_age: Duration::from_secs(300),
575 bearer_challenge: None,
576 }
577 }
578
579 pub fn with_paths(
581 mut self,
582 rest_prefix: impl Into<String>,
583 jsonrpc_path: impl Into<String>,
584 ) -> Result<Self, A2aServerHttpOptionsError> {
585 self.rest_prefix = validate_mount_path(rest_prefix.into())?;
586 self.jsonrpc_path = validate_mount_path(jsonrpc_path.into())?;
587 if self.rest_prefix == self.jsonrpc_path {
588 return Err(A2aServerHttpOptionsError::DuplicatePaths);
589 }
590 Ok(self)
591 }
592
593 pub fn with_allowed_authorities(
596 mut self,
597 authorities: impl IntoIterator<Item = impl Into<String>>,
598 ) -> Result<Self, A2aServerHttpOptionsError> {
599 let mut values = authorities.into_iter().map(Into::into).collect::<Vec<_>>();
600 if values.is_empty() || values.len() > 64 {
601 return Err(A2aServerHttpOptionsError::InvalidAuthorities);
602 }
603 for value in &mut values {
604 if value.trim() != value
605 || value.is_empty()
606 || value.len() > 512
607 || value.contains('/')
608 || value.contains('@')
609 {
610 return Err(A2aServerHttpOptionsError::InvalidAuthorities);
611 }
612 value.make_ascii_lowercase();
613 }
614 values.sort_unstable();
615 values.dedup();
616 self.allowed_authorities = values
617 .into_iter()
618 .map(String::into_boxed_str)
619 .collect::<Vec<_>>()
620 .into();
621 Ok(self)
622 }
623
624 pub fn with_allowed_origins(
627 mut self,
628 origins: impl IntoIterator<Item = impl Into<String>>,
629 ) -> Result<Self, A2aServerHttpOptionsError> {
630 let mut values = origins.into_iter().map(Into::into).collect::<Vec<_>>();
631 if values.len() > 64 {
632 return Err(A2aServerHttpOptionsError::InvalidOrigins);
633 }
634 for value in &values {
635 let url = reqwest::Url::parse(value)
636 .map_err(|_| A2aServerHttpOptionsError::InvalidOrigins)?;
637 if url.host_str().is_none()
638 || url.path() != "/"
639 || url.query().is_some()
640 || url.fragment().is_some()
641 || url.username() != ""
642 || url.password().is_some()
643 {
644 return Err(A2aServerHttpOptionsError::InvalidOrigins);
645 }
646 }
647 values.sort_unstable();
648 values.dedup();
649 self.allowed_origins = values
650 .into_iter()
651 .map(String::into_boxed_str)
652 .collect::<Vec<_>>()
653 .into();
654 Ok(self)
655 }
656
657 pub fn with_limits(
659 mut self,
660 maximum_body_bytes: usize,
661 maximum_in_flight_requests: usize,
662 maximum_in_flight_operations: usize,
663 ) -> Result<Self, A2aServerHttpOptionsError> {
664 if !(1024..=16 * 1024 * 1024).contains(&maximum_body_bytes)
665 || maximum_in_flight_requests == 0
666 || maximum_in_flight_requests > 65_536
667 || maximum_in_flight_operations == 0
668 || maximum_in_flight_operations > maximum_in_flight_requests
669 {
670 return Err(A2aServerHttpOptionsError::InvalidLimits);
671 }
672 self.maximum_body_bytes = maximum_body_bytes;
673 self.maximum_in_flight_requests = maximum_in_flight_requests;
674 self.maximum_in_flight_operations = maximum_in_flight_operations;
675 Ok(self)
676 }
677
678 pub fn with_maximum_response_body_bytes(
682 mut self,
683 value: usize,
684 ) -> Result<Self, A2aServerHttpOptionsError> {
685 if !(1024..=64 * 1024 * 1024).contains(&value) {
686 return Err(A2aServerHttpOptionsError::InvalidLimits);
687 }
688 self.maximum_response_body_bytes = value;
689 Ok(self)
690 }
691
692 pub fn with_timeouts(
694 mut self,
695 request_timeout: Duration,
696 stream_idle_timeout: Duration,
697 ) -> Result<Self, A2aServerHttpOptionsError> {
698 if request_timeout < Duration::from_millis(10)
699 || request_timeout > Duration::from_secs(300)
700 || stream_idle_timeout < Duration::from_secs(1)
701 || stream_idle_timeout > Duration::from_secs(3600)
702 {
703 return Err(A2aServerHttpOptionsError::InvalidTimeouts);
704 }
705 self.request_timeout = request_timeout;
706 self.stream_idle_timeout = stream_idle_timeout;
707 Ok(self)
708 }
709
710 pub fn with_maximum_stream_events(
712 mut self,
713 value: u32,
714 ) -> Result<Self, A2aServerHttpOptionsError> {
715 if value == 0 || value > 1_000_000 {
716 return Err(A2aServerHttpOptionsError::InvalidLimits);
717 }
718 self.maximum_stream_events = value;
719 Ok(self)
720 }
721
722 pub fn with_card_max_age(mut self, value: Duration) -> Result<Self, A2aServerHttpOptionsError> {
724 if value > Duration::from_secs(86_400) {
725 return Err(A2aServerHttpOptionsError::InvalidCardCache);
726 }
727 self.card_max_age = value;
728 Ok(self)
729 }
730
731 pub fn with_bearer_challenge(
734 mut self,
735 value: impl Into<String>,
736 ) -> Result<Self, A2aServerHttpOptionsError> {
737 let value = value.into();
738 let header = HeaderValue::from_str(&value)
739 .map_err(|_| A2aServerHttpOptionsError::InvalidBearerChallenge)?;
740 if !value.starts_with("Bearer ") || header.as_bytes().len() > 1024 {
741 return Err(A2aServerHttpOptionsError::InvalidBearerChallenge);
742 }
743 self.bearer_challenge = Some(value.into_boxed_str());
744 Ok(self)
745 }
746}
747
748impl Default for A2aServerHttpOptions {
749 fn default() -> Self {
750 Self::new()
751 }
752}
753
754#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
756#[non_exhaustive]
757pub enum A2aServerHttpOptionsError {
758 #[error("invalid A2A mount path")]
760 InvalidPath,
761 #[error("A2A REST and JSON-RPC paths must differ")]
763 DuplicatePaths,
764 #[error("invalid A2A Host authority allowlist")]
766 InvalidAuthorities,
767 #[error("invalid A2A Origin allowlist")]
769 InvalidOrigins,
770 #[error("invalid A2A HTTP limits")]
772 InvalidLimits,
773 #[error("invalid A2A timeouts")]
775 InvalidTimeouts,
776 #[error("invalid Agent Card cache lifetime")]
778 InvalidCardCache,
779 #[error("invalid A2A Bearer challenge")]
781 InvalidBearerChallenge,
782}
783
784fn validate_mount_path(value: String) -> Result<Box<str>, A2aServerHttpOptionsError> {
785 if value.len() < 2
786 || value.len() > 256
787 || !value.starts_with('/')
788 || value.ends_with('/')
789 || value.contains("//")
790 || value.contains('?')
791 || value.contains('#')
792 || value
793 .split('/')
794 .any(|segment| matches!(segment, "." | ".."))
795 {
796 return Err(A2aServerHttpOptionsError::InvalidPath);
797 }
798 Ok(value.into_boxed_str())
799}
800
801#[derive(Debug, Error)]
803#[non_exhaustive]
804pub enum A2aServerBuildError {
805 #[error("A2A server requires at least one exact allowed Host authority")]
807 MissingAllowedAuthority,
808 #[error("A2A Agent Card capabilities do not match the task service")]
810 CapabilityMismatch,
811 #[error("A2A Agent Card interfaces do not match mounted bindings")]
814 InterfaceMismatch,
815 #[error("A2A Agent Card serialization failed")]
817 InvalidAgentCard(#[source] A2aContractError),
818}
819
820pub struct A2aServer {
822 router: Router,
823 shutdown: CancellationToken,
824}
825
826impl A2aServer {
827 pub fn new(
829 card: A2aAgentCard,
830 authenticator: impl A2aServerAuthenticator,
831 authorizer: impl A2aServerAuthorizer,
832 admission: impl A2aServerAdmissionControl,
833 service: impl A2aTaskService,
834 options: A2aServerHttpOptions,
835 shutdown: CancellationToken,
836 ) -> Result<Self, A2aServerBuildError> {
837 if options.allowed_authorities.is_empty() {
838 return Err(A2aServerBuildError::MissingAllowedAuthority);
839 }
840 let card_capabilities = card.capabilities();
841 let service_capabilities = service.capabilities();
842 if card_capabilities.supports_streaming() != service_capabilities.streaming
843 || card_capabilities.supports_push_notifications()
844 != service_capabilities.push_notifications
845 || card_capabilities.supports_extended_agent_card()
846 != service_capabilities.extended_agent_card
847 {
848 return Err(A2aServerBuildError::CapabilityMismatch);
849 }
850 validate_advertised_interfaces(&card, &options)?;
851
852 let card_json = card
853 .to_json()
854 .map_err(A2aServerBuildError::InvalidAgentCard)?;
855 let card_bytes = serde_json::to_vec(&card_json).map_err(|_| {
856 A2aServerBuildError::InvalidAgentCard(A2aContractError::InvalidJson {
857 field: "Agent Card",
858 })
859 })?;
860 let card_state = Arc::new(AgentCardState::new(
861 card_json,
862 &card_bytes,
863 options.card_max_age,
864 ));
865 let task_handler = Arc::new(A2aSdkRequestHandler {
866 card,
867 authorizer: Arc::new(authorizer),
868 admission: Arc::new(admission),
869 service: Arc::new(service),
870 operation_slots: Arc::new(Semaphore::new(options.maximum_in_flight_operations)),
871 request_timeout: options.request_timeout,
872 stream_idle_timeout: options.stream_idle_timeout,
873 maximum_stream_events: options.maximum_stream_events,
874 shutdown: shutdown.clone(),
875 });
876
877 let rest = a2a_server::rest::rest_router(Arc::clone(&task_handler));
878 let jsonrpc = a2a_server::jsonrpc::jsonrpc_router(task_handler);
879 let router = Router::new()
880 .route(A2A_AGENT_CARD_PATH, get(serve_agent_card))
881 .with_state(card_state)
882 .nest(options.rest_prefix.as_ref(), rest)
883 .nest_service(options.jsonrpc_path.as_ref(), jsonrpc)
888 .layer(DefaultBodyLimit::max(options.maximum_body_bytes))
889 .layer(middleware::from_fn_with_state(
890 Arc::new(A2aBoundaryState {
891 authenticator: Arc::new(authenticator),
892 request_slots: Arc::new(Semaphore::new(options.maximum_in_flight_requests)),
893 options,
894 shutdown: shutdown.clone(),
895 }),
896 enforce_boundary,
897 ));
898
899 Ok(Self { router, shutdown })
900 }
901
902 pub fn router(&self) -> Router {
904 self.router.clone()
905 }
906
907 pub fn shutdown(&self) {
910 self.shutdown.cancel();
911 }
912}
913
914fn validate_advertised_interfaces(
915 card: &A2aAgentCard,
916 options: &A2aServerHttpOptions,
917) -> Result<(), A2aServerBuildError> {
918 let mut rest = false;
919 let mut jsonrpc = false;
920 for interface in card.interfaces() {
921 let Ok(url) = reqwest::Url::parse(interface.url()) else {
922 return Err(A2aServerBuildError::InterfaceMismatch);
923 };
924 match interface.binding() {
925 crate::A2aBinding::HttpJson if url.path() == options.rest_prefix.as_ref() => {
926 rest = true;
927 }
928 crate::A2aBinding::JsonRpc if url.path() == options.jsonrpc_path.as_ref() => {
929 jsonrpc = true;
930 }
931 _ => return Err(A2aServerBuildError::InterfaceMismatch),
932 }
933 }
934 if rest && jsonrpc {
935 Ok(())
936 } else {
937 Err(A2aServerBuildError::InterfaceMismatch)
938 }
939}
940
941struct AgentCardState {
942 value: Json<serde_json::Value>,
943 etag: HeaderValue,
944 last_modified: HeaderValue,
945 modified_at: SystemTime,
946 cache_control: HeaderValue,
947}
948
949impl AgentCardState {
950 fn new(value: serde_json::Value, bytes: &[u8], max_age: Duration) -> Self {
951 let hash = Sha256::digest(bytes);
952 let etag = format!("\"{}\"", hex_digest(&hash));
953 let modified_at = SystemTime::now()
957 .duration_since(SystemTime::UNIX_EPOCH)
958 .map_or(SystemTime::UNIX_EPOCH, |elapsed| {
959 SystemTime::UNIX_EPOCH + Duration::from_secs(elapsed.as_secs())
960 });
961 Self {
962 value: Json(value),
963 etag: HeaderValue::from_str(&etag).expect("SHA-256 ETag is a valid header"),
964 last_modified: HeaderValue::from_str(&httpdate::fmt_http_date(modified_at))
965 .expect("HTTP date is a valid header"),
966 modified_at,
967 cache_control: HeaderValue::from_str(&format!(
968 "public, max-age={}, must-revalidate",
969 max_age.as_secs()
970 ))
971 .expect("bounded max-age is a valid header"),
972 }
973 }
974}
975
976fn hex_digest(bytes: &[u8]) -> String {
977 use std::fmt::Write as _;
978 let mut value = String::with_capacity(bytes.len() * 2);
979 for byte in bytes {
980 let _ = write!(value, "{byte:02x}");
981 }
982 value
983}
984
985async fn serve_agent_card(
986 State(state): State<Arc<AgentCardState>>,
987 headers: HeaderMap,
988) -> Response<Body> {
989 let not_modified = headers
990 .get(IF_NONE_MATCH)
991 .is_some_and(|value| value == state.etag)
992 || headers
993 .get(IF_MODIFIED_SINCE)
994 .and_then(|value| value.to_str().ok())
995 .and_then(|value| httpdate::parse_http_date(value).ok())
996 .is_some_and(|value| value >= state.modified_at);
997
998 let mut response = if not_modified {
999 StatusCode::NOT_MODIFIED.into_response()
1000 } else {
1001 state.value.clone().into_response()
1002 };
1003 response.headers_mut().insert(ETAG, state.etag.clone());
1004 response
1005 .headers_mut()
1006 .insert(LAST_MODIFIED, state.last_modified.clone());
1007 response
1008 .headers_mut()
1009 .insert(CACHE_CONTROL, state.cache_control.clone());
1010 response
1011}
1012
1013struct A2aBoundaryState {
1014 authenticator: Arc<dyn A2aServerAuthenticator>,
1015 request_slots: Arc<Semaphore>,
1016 options: A2aServerHttpOptions,
1017 shutdown: CancellationToken,
1018}
1019
1020async fn enforce_boundary(
1021 State(state): State<Arc<A2aBoundaryState>>,
1022 request: Request,
1023 next: Next,
1024) -> Response<Body> {
1025 if state.shutdown.is_cancelled() {
1026 return plain_response(StatusCode::SERVICE_UNAVAILABLE, "service unavailable");
1027 }
1028 if !allowed_host(request.headers(), &state.options.allowed_authorities) {
1029 return plain_response(StatusCode::MISDIRECTED_REQUEST, "misdirected request");
1030 }
1031 let Ok(origin) = allowed_origin(request.headers(), &state.options.allowed_origins) else {
1032 return plain_response(StatusCode::FORBIDDEN, "origin forbidden");
1033 };
1034 if !canonical_path(request.uri().path(), &state.options) {
1035 return plain_response(StatusCode::NOT_FOUND, "not found");
1036 }
1037 if request.uri().path() != A2A_AGENT_CARD_PATH && !valid_content_type(&request) {
1038 if request
1039 .uri()
1040 .path()
1041 .starts_with(state.options.rest_prefix.as_ref())
1042 {
1043 return rest_protocol_error(
1044 StatusCode::UNSUPPORTED_MEDIA_TYPE,
1045 "INVALID_ARGUMENT",
1046 "incompatible content types",
1047 "CONTENT_TYPE_NOT_SUPPORTED",
1048 );
1049 }
1050 return plain_response(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported media type");
1051 }
1052
1053 let Ok(permit) = Arc::clone(&state.request_slots).try_acquire_owned() else {
1054 let mut response = plain_response(StatusCode::TOO_MANY_REQUESTS, "overloaded");
1055 response
1056 .headers_mut()
1057 .insert(RETRY_AFTER, HeaderValue::from_static("1"));
1058 return response;
1059 };
1060
1061 if request.uri().path() == A2A_AGENT_CARD_PATH {
1062 let mut response = next.run(request).await;
1063 drop(permit);
1064 apply_origin_header(&mut response, origin);
1065 return response;
1066 }
1067
1068 let Ok(authentication) = authentication_request(&request) else {
1069 return authentication_response(
1070 A2aServerAuthenticationError::InvalidCredential,
1071 state.options.bearer_challenge.as_deref(),
1072 );
1073 };
1074 let principal = match tokio::time::timeout(
1075 state.options.request_timeout,
1076 state.authenticator.authenticate(authentication),
1077 )
1078 .await
1079 {
1080 Ok(Ok(principal)) => principal,
1081 Ok(Err(error)) => {
1082 return authentication_response(error, state.options.bearer_challenge.as_deref());
1083 }
1084 Err(_) => {
1085 return authentication_response(
1086 A2aServerAuthenticationError::Unavailable,
1087 state.options.bearer_challenge.as_deref(),
1088 );
1089 }
1090 };
1091
1092 let is_rest = request
1093 .uri()
1094 .path()
1095 .starts_with(state.options.rest_prefix.as_ref());
1096 let request = match canonicalize_request_payload(
1097 request,
1098 state.options.rest_prefix.as_ref(),
1099 state.options.jsonrpc_path.as_ref(),
1100 state.options.maximum_body_bytes,
1101 )
1102 .await
1103 {
1104 Ok(request) => request,
1105 Err(response) => return response,
1106 };
1107 let mut response = A2A_REQUEST_PRINCIPAL
1108 .scope(principal, next.run(request))
1109 .await;
1110 drop(permit);
1111 response =
1112 normalize_protocol_response(response, is_rest, state.options.maximum_response_body_bytes)
1113 .await;
1114 apply_origin_header(&mut response, origin);
1115 response
1116}
1117
1118async fn canonicalize_request_payload(
1119 request: Request,
1120 rest_prefix: &str,
1121 jsonrpc_path: &str,
1122 maximum_bytes: usize,
1123) -> Result<Request, Response<Body>> {
1124 if request.method() != Method::POST {
1125 return Ok(request);
1126 }
1127 let path = request.uri().path();
1128 let rest_send = matches!(
1129 path.strip_prefix(rest_prefix),
1130 Some("/message:send" | "/message:stream")
1131 );
1132 let jsonrpc = path == jsonrpc_path
1133 || path
1134 .strip_suffix('/')
1135 .is_some_and(|value| value == jsonrpc_path);
1136 if !rest_send && !jsonrpc {
1137 return Ok(request);
1138 }
1139
1140 let (mut parts, body) = request.into_parts();
1141 let collected = Limited::new(body, maximum_bytes)
1142 .collect()
1143 .await
1144 .map_err(|_| {
1145 if rest_send {
1146 rest_protocol_error(
1147 StatusCode::PAYLOAD_TOO_LARGE,
1148 "RESOURCE_EXHAUSTED",
1149 "A2A request exceeds the configured boundary",
1150 "INVALID_REQUEST",
1151 )
1152 } else {
1153 plain_response(StatusCode::PAYLOAD_TOO_LARGE, "request body is too large")
1154 }
1155 })?;
1156 let bytes = collected.to_bytes();
1157 let normalized = if jsonrpc {
1158 canonicalize_jsonrpc_request(&bytes).map_err(|error| match error {
1159 JsonRpcPayloadError::Parse => jsonrpc_protocol_error(-32700, "Parse error"),
1160 JsonRpcPayloadError::InvalidRequest => {
1161 jsonrpc_protocol_error(-32600, "Invalid Request")
1162 }
1163 })?
1164 } else {
1165 canonicalize_native::<wire::SendMessageRequest>(&bytes).unwrap_or_else(|| bytes.to_vec())
1166 };
1167 parts.headers.remove(axum::http::header::CONTENT_LENGTH);
1168 Ok(Request::from_parts(parts, Body::from(normalized)))
1169}
1170
1171#[derive(Clone, Copy)]
1172enum JsonRpcPayloadError {
1173 Parse,
1174 InvalidRequest,
1175}
1176
1177fn canonicalize_jsonrpc_request(bytes: &[u8]) -> Result<Vec<u8>, JsonRpcPayloadError> {
1178 let value = serde_json::from_slice::<serde_json::Value>(bytes)
1179 .map_err(|_| JsonRpcPayloadError::Parse)?;
1180 let mut request = serde_json::from_value::<wire::JsonRpcRequest>(value)
1181 .map_err(|_| JsonRpcPayloadError::InvalidRequest)?;
1182 if let Some(params) = request.params.take() {
1183 request.params = Some(match request.method.as_str() {
1184 wire::methods::SEND_MESSAGE | wire::methods::SEND_STREAMING_MESSAGE => {
1185 canonicalize_value::<wire::SendMessageRequest>(params)
1186 }
1187 wire::methods::GET_TASK => canonicalize_value::<wire::GetTaskRequest>(params),
1188 wire::methods::LIST_TASKS => canonicalize_value::<wire::ListTasksRequest>(params),
1189 wire::methods::CANCEL_TASK => canonicalize_value::<wire::CancelTaskRequest>(params),
1190 wire::methods::SUBSCRIBE_TO_TASK => {
1191 canonicalize_value::<wire::SubscribeToTaskRequest>(params)
1192 }
1193 wire::methods::CREATE_PUSH_CONFIG => {
1194 canonicalize_value::<wire::TaskPushNotificationConfig>(params)
1195 }
1196 wire::methods::GET_PUSH_CONFIG => {
1197 canonicalize_value::<wire::GetTaskPushNotificationConfigRequest>(params)
1198 }
1199 wire::methods::LIST_PUSH_CONFIGS => {
1200 canonicalize_value::<wire::ListTaskPushNotificationConfigsRequest>(params)
1201 }
1202 wire::methods::DELETE_PUSH_CONFIG => {
1203 canonicalize_value::<wire::DeleteTaskPushNotificationConfigRequest>(params)
1204 }
1205 wire::methods::GET_EXTENDED_AGENT_CARD => {
1206 canonicalize_value::<wire::GetExtendedAgentCardRequest>(params)
1207 }
1208 _ => params,
1209 });
1210 }
1211 serde_json::to_vec(&request).map_err(|_| JsonRpcPayloadError::InvalidRequest)
1212}
1213
1214fn canonicalize_native<T>(bytes: &[u8]) -> Option<Vec<u8>>
1215where
1216 T: DeserializeOwned + Serialize,
1217{
1218 let value = serde_json::from_slice::<T>(bytes).ok()?;
1219 serde_json::to_vec(&value).ok()
1220}
1221
1222fn canonicalize_value<T>(value: serde_json::Value) -> serde_json::Value
1223where
1224 T: DeserializeOwned + Serialize,
1225{
1226 serde_json::from_value::<T>(value.clone())
1227 .and_then(serde_json::to_value)
1228 .unwrap_or(value)
1229}
1230
1231async fn normalize_protocol_response(
1232 response: Response<Body>,
1233 is_rest: bool,
1234 maximum_bytes: usize,
1235) -> Response<Body> {
1236 let is_json = response
1237 .headers()
1238 .get(CONTENT_TYPE)
1239 .and_then(|value| value.to_str().ok())
1240 .is_some_and(|value| value.to_ascii_lowercase().contains("application/json"));
1241 if !is_json {
1242 return response;
1243 }
1244
1245 let (mut parts, body) = response.into_parts();
1246 let Ok(collected) = Limited::new(body, maximum_bytes).collect().await else {
1247 return rest_protocol_error(
1248 StatusCode::BAD_GATEWAY,
1249 "INTERNAL",
1250 "A2A response exceeds the configured boundary",
1251 "INVALID_AGENT_RESPONSE",
1252 );
1253 };
1254 let Ok(mut value) = serde_json::from_slice::<serde_json::Value>(&collected.to_bytes()) else {
1255 return rest_protocol_error(
1256 StatusCode::BAD_GATEWAY,
1257 "INTERNAL",
1258 "A2A response is not valid JSON",
1259 "INVALID_AGENT_RESPONSE",
1260 );
1261 };
1262
1263 normalize_utc_timestamps(&mut value);
1264 if is_rest {
1265 normalize_rest_error_status(&mut parts.status, &mut value);
1266 }
1267 let Ok(bytes) = serde_json::to_vec(&value) else {
1268 return rest_protocol_error(
1269 StatusCode::BAD_GATEWAY,
1270 "INTERNAL",
1271 "A2A response could not be serialized",
1272 "INVALID_AGENT_RESPONSE",
1273 );
1274 };
1275 parts.headers.remove(axum::http::header::CONTENT_LENGTH);
1276 Response::from_parts(parts, Body::from(bytes))
1277}
1278
1279fn normalize_utc_timestamps(value: &mut serde_json::Value) {
1280 match value {
1281 serde_json::Value::Object(fields) => {
1282 for (name, value) in fields {
1283 if matches!(
1284 name.as_str(),
1285 "timestamp" | "createdAt" | "updatedAt" | "statusTimestamp"
1286 ) {
1287 if let serde_json::Value::String(timestamp) = value {
1288 if let Some(prefix) = timestamp.strip_suffix("+00:00") {
1289 *timestamp = format!("{prefix}Z");
1290 }
1291 }
1292 } else {
1293 normalize_utc_timestamps(value);
1294 }
1295 }
1296 }
1297 serde_json::Value::Array(values) => {
1298 for value in values {
1299 normalize_utc_timestamps(value);
1300 }
1301 }
1302 _ => {}
1303 }
1304}
1305
1306fn normalize_rest_error_status(status: &mut StatusCode, value: &mut serde_json::Value) {
1307 let Some(error) = value
1308 .get_mut("error")
1309 .and_then(serde_json::Value::as_object_mut)
1310 else {
1311 return;
1312 };
1313 let reason = error
1314 .get("details")
1315 .and_then(serde_json::Value::as_array)
1316 .and_then(|details| {
1317 details
1318 .iter()
1319 .find_map(|detail| detail.get("reason").and_then(serde_json::Value::as_str))
1320 });
1321 let Some((http_status, canonical_status)) = reason.and_then(rest_error_mapping) else {
1322 return;
1323 };
1324 *status = http_status;
1325 error.insert(
1326 "code".to_string(),
1327 serde_json::Value::from(http_status.as_u16()),
1328 );
1329 error.insert(
1330 "status".to_string(),
1331 serde_json::Value::from(canonical_status),
1332 );
1333}
1334
1335fn rest_error_mapping(reason: &str) -> Option<(StatusCode, &'static str)> {
1336 match reason {
1337 "TASK_NOT_FOUND" | "METHOD_NOT_FOUND" => Some((StatusCode::NOT_FOUND, "NOT_FOUND")),
1338 "TASK_NOT_CANCELABLE" => Some((StatusCode::CONFLICT, "FAILED_PRECONDITION")),
1339 "PUSH_NOTIFICATION_NOT_SUPPORTED" | "UNSUPPORTED_OPERATION" | "VERSION_NOT_SUPPORTED" => {
1340 Some((StatusCode::BAD_REQUEST, "UNIMPLEMENTED"))
1341 }
1342 "CONTENT_TYPE_NOT_SUPPORTED" => {
1343 Some((StatusCode::UNSUPPORTED_MEDIA_TYPE, "INVALID_ARGUMENT"))
1344 }
1345 "INVALID_AGENT_RESPONSE" => Some((StatusCode::BAD_GATEWAY, "INTERNAL")),
1346 "EXTENDED_AGENT_CARD_NOT_CONFIGURED" | "EXTENSION_SUPPORT_REQUIRED" => {
1347 Some((StatusCode::BAD_REQUEST, "FAILED_PRECONDITION"))
1348 }
1349 "INVALID_REQUEST" | "INVALID_PARAMS" | "PARSE_ERROR" => {
1350 Some((StatusCode::BAD_REQUEST, "INVALID_ARGUMENT"))
1351 }
1352 "INTERNAL_ERROR" => Some((StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL")),
1353 _ => None,
1354 }
1355}
1356
1357fn rest_protocol_error(
1358 status: StatusCode,
1359 canonical_status: &'static str,
1360 message: &'static str,
1361 reason: &'static str,
1362) -> Response<Body> {
1363 (
1364 status,
1365 Json(serde_json::json!({
1366 "error": {
1367 "code": status.as_u16(),
1368 "status": canonical_status,
1369 "message": message,
1370 "details": [{
1371 "@type": "type.googleapis.com/google.rpc.ErrorInfo",
1372 "reason": reason,
1373 "domain": "a2a-protocol.org",
1374 "metadata": {}
1375 }]
1376 }
1377 })),
1378 )
1379 .into_response()
1380}
1381
1382fn jsonrpc_protocol_error(code: i32, message: &'static str) -> Response<Body> {
1383 (
1384 StatusCode::OK,
1385 Json(serde_json::json!({
1386 "jsonrpc": "2.0",
1387 "id": null,
1388 "error": {
1389 "code": code,
1390 "message": message
1391 }
1392 })),
1393 )
1394 .into_response()
1395}
1396
1397fn authentication_request(request: &Request) -> Result<A2aServerAuthenticationRequest, ()> {
1398 let values = request.headers().get_all(AUTHORIZATION);
1399 let mut iter = values.iter();
1400 let first = iter.next();
1401 if iter.next().is_some() {
1402 return Err(());
1403 }
1404 let bearer = first
1405 .map(|value| {
1406 let value = value.to_str().map_err(|_| ())?;
1407 let credential = value.strip_prefix("Bearer ").ok_or(())?;
1408 if credential.is_empty() || credential.len() > MAX_BEARER_BYTES {
1409 return Err(());
1410 }
1411 A2aSecret::new(credential.to_string()).map_err(|_| ())
1412 })
1413 .transpose()?;
1414 Ok(A2aServerAuthenticationRequest {
1415 bearer,
1416 method: request.method().clone(),
1417 path: request.uri().path().into(),
1418 })
1419}
1420
1421fn authentication_response(
1422 error: A2aServerAuthenticationError,
1423 challenge: Option<&str>,
1424) -> Response<Body> {
1425 let status = match error {
1426 A2aServerAuthenticationError::InvalidCredential => StatusCode::UNAUTHORIZED,
1427 A2aServerAuthenticationError::Forbidden => StatusCode::FORBIDDEN,
1428 A2aServerAuthenticationError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
1429 };
1430 let mut response = plain_response(status, error.to_string());
1431 if status == StatusCode::UNAUTHORIZED {
1432 if let Some(challenge) = challenge.and_then(|value| HeaderValue::from_str(value).ok()) {
1433 response.headers_mut().insert(WWW_AUTHENTICATE, challenge);
1434 }
1435 }
1436 response
1437}
1438
1439fn plain_response(status: StatusCode, message: impl Into<String>) -> Response<Body> {
1440 let mut response = Response::new(Body::from(message.into()));
1441 *response.status_mut() = status;
1442 response.headers_mut().insert(
1443 CONTENT_TYPE,
1444 HeaderValue::from_static("text/plain; charset=utf-8"),
1445 );
1446 response
1447}
1448
1449fn allowed_host(headers: &HeaderMap, allowed: &[Box<str>]) -> bool {
1450 let values = headers.get_all(HOST);
1451 let mut iter = values.iter();
1452 let Some(first) = iter.next().and_then(|value| value.to_str().ok()) else {
1453 return false;
1454 };
1455 if iter.next().is_some() {
1456 return false;
1457 }
1458 let candidate = first.to_ascii_lowercase();
1459 allowed
1460 .binary_search_by(|value| value.as_ref().cmp(&candidate))
1461 .is_ok()
1462}
1463
1464fn allowed_origin(headers: &HeaderMap, allowed: &[Box<str>]) -> Result<Option<HeaderValue>, ()> {
1465 let values = headers.get_all(axum::http::header::ORIGIN);
1466 let mut iter = values.iter();
1467 let Some(first) = iter.next() else {
1468 return Ok(None);
1469 };
1470 if iter.next().is_some() {
1471 return Err(());
1472 }
1473 let text = first.to_str().map_err(|_| ())?;
1474 if allowed.iter().any(|value| value.as_ref() == text) {
1475 Ok(Some(first.clone()))
1476 } else {
1477 Err(())
1478 }
1479}
1480
1481fn apply_origin_header(response: &mut Response<Body>, origin: Option<HeaderValue>) {
1482 if let Some(origin) = origin {
1483 response
1484 .headers_mut()
1485 .insert(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
1486 response
1487 .headers_mut()
1488 .insert(VARY, HeaderValue::from_static("Origin"));
1489 }
1490}
1491
1492fn valid_content_type(request: &Request) -> bool {
1493 if matches!(*request.method(), Method::GET | Method::DELETE) {
1494 return true;
1495 }
1496 let values = request.headers().get_all(CONTENT_TYPE);
1497 let mut iter = values.iter();
1498 let Some(value) = iter.next().and_then(|value| value.to_str().ok()) else {
1499 return false;
1500 };
1501 if iter.next().is_some() {
1502 return false;
1503 }
1504 value.parse::<mime::Mime>().is_ok_and(|value| {
1505 (value.type_() == mime::APPLICATION && value.subtype() == mime::JSON)
1506 || value.essence_str() == "application/a2a+json"
1507 })
1508}
1509
1510fn canonical_path(path: &str, options: &A2aServerHttpOptions) -> bool {
1511 if path == A2A_AGENT_CARD_PATH
1512 || path == options.jsonrpc_path.as_ref()
1513 || path
1514 .strip_suffix('/')
1515 .is_some_and(|value| value == options.jsonrpc_path.as_ref())
1516 {
1517 return true;
1518 }
1519 let Some(suffix) = path.strip_prefix(options.rest_prefix.as_ref()) else {
1520 return false;
1521 };
1522 if matches!(
1523 suffix,
1524 "/message:send" | "/message:stream" | "/tasks" | "/extendedAgentCard"
1525 ) {
1526 return true;
1527 }
1528 let Some(task_suffix) = suffix.strip_prefix("/tasks/") else {
1529 return false;
1530 };
1531 if task_suffix.is_empty() || task_suffix.contains("//") {
1532 return false;
1533 }
1534 if let Some(task_id) = task_suffix.strip_suffix(":cancel") {
1535 return valid_path_segment(task_id);
1536 }
1537 if let Some(task_id) = task_suffix.strip_suffix(":subscribe") {
1538 return valid_path_segment(task_id);
1539 }
1540 if let Some((task_id, config_suffix)) = task_suffix.split_once("/pushNotificationConfigs") {
1541 return valid_path_segment(task_id)
1542 && (config_suffix.is_empty()
1543 || config_suffix
1544 .strip_prefix('/')
1545 .is_some_and(valid_path_segment));
1546 }
1547 valid_path_segment(task_suffix)
1548}
1549
1550fn valid_path_segment(value: &str) -> bool {
1551 !value.is_empty() && value.len() <= 1536 && !value.contains('/') && !matches!(value, "." | "..")
1552}
1553
1554struct A2aSdkRequestHandler {
1555 card: A2aAgentCard,
1556 authorizer: Arc<dyn A2aServerAuthorizer>,
1557 admission: Arc<dyn A2aServerAdmissionControl>,
1558 service: Arc<dyn A2aTaskService>,
1559 operation_slots: Arc<Semaphore>,
1560 request_timeout: Duration,
1561 stream_idle_timeout: Duration,
1562 maximum_stream_events: u32,
1563 shutdown: CancellationToken,
1564}
1565
1566impl A2aSdkRequestHandler {
1567 async fn prepare(
1568 &self,
1569 params: &ServiceParams,
1570 operation: A2aServerOperation,
1571 task_id: Option<&str>,
1572 config_id: Option<&str>,
1573 ) -> Result<(A2aRequestContext, OwnedSemaphorePermit), wire::A2AError> {
1574 let principal = A2A_REQUEST_PRINCIPAL
1575 .try_with(Clone::clone)
1576 .map_err(|_| wire::A2AError::internal("request authentication context is absent"))?;
1577 let extensions = negotiate_extensions(params, &self.card)?;
1578 let capabilities = self.card.capabilities();
1579 match operation {
1580 A2aServerOperation::SendStreamingMessage | A2aServerOperation::SubscribeToTask
1581 if !capabilities.supports_streaming() =>
1582 {
1583 return Err(wire::A2AError::unsupported_operation(
1584 "A2A streaming is not supported",
1585 ));
1586 }
1587 A2aServerOperation::CreatePushConfig
1588 | A2aServerOperation::GetPushConfig
1589 | A2aServerOperation::ListPushConfigs
1590 | A2aServerOperation::DeletePushConfig
1591 if !capabilities.supports_push_notifications() =>
1592 {
1593 return Err(wire::A2AError::push_notification_not_supported());
1594 }
1595 A2aServerOperation::GetExtendedAgentCard
1596 if !capabilities.supports_extended_agent_card() =>
1597 {
1598 return Err(wire::A2AError::unsupported_operation(
1599 "A2A extended Agent Card is not supported",
1600 ));
1601 }
1602 _ => {}
1603 }
1604 self.authorizer
1605 .authorize(A2aServerAuthorizationRequest {
1606 principal: principal.clone(),
1607 operation,
1608 task_id: task_id.map(Into::into),
1609 config_id: config_id.map(Into::into),
1610 })
1611 .await
1612 .map_err(map_authorization_error)?;
1613 self.admission
1614 .admit(A2aServerAdmissionRequest {
1615 principal: principal.clone(),
1616 operation,
1617 })
1618 .await
1619 .map_err(map_admission_error)?;
1620 let permit = Arc::clone(&self.operation_slots)
1621 .try_acquire_owned()
1622 .map_err(|_| wire::A2AError::internal("A2A service is overloaded"))?;
1623 Ok((
1624 A2aRequestContext {
1625 principal,
1626 extensions: extensions
1627 .into_iter()
1628 .map(String::into_boxed_str)
1629 .collect::<Vec<_>>()
1630 .into(),
1631 },
1632 permit,
1633 ))
1634 }
1635
1636 async fn unary<T>(
1637 &self,
1638 future: impl std::future::Future<Output = Result<T, A2aTaskServiceError>>,
1639 _permit: OwnedSemaphorePermit,
1640 ) -> Result<T, wire::A2AError> {
1641 tokio::select! {
1642 () = self.shutdown.cancelled() => Err(wire::A2AError::internal("A2A service is shutting down")),
1643 result = tokio::time::timeout(self.request_timeout, future) => {
1644 match result {
1645 Ok(result) => result.map_err(map_service_error),
1646 Err(_) => Err(wire::A2AError::internal("A2A operation timed out")),
1647 }
1648 }
1649 }
1650 }
1651
1652 async fn stream(
1653 &self,
1654 future: impl std::future::Future<Output = Result<A2aEventStream, A2aTaskServiceError>>,
1655 permit: OwnedSemaphorePermit,
1656 ) -> Result<
1657 futures_util::stream::BoxStream<'static, Result<wire::StreamResponse, wire::A2AError>>,
1658 wire::A2AError,
1659 > {
1660 let stream = tokio::select! {
1661 () = self.shutdown.cancelled() => {
1662 return Err(wire::A2AError::internal("A2A service is shutting down"));
1663 }
1664 result = tokio::time::timeout(self.request_timeout, future) => {
1665 match result {
1666 Ok(result) => result.map_err(map_service_error)?,
1667 Err(_) => return Err(wire::A2AError::internal("A2A operation timed out")),
1668 }
1669 }
1670 };
1671 Ok(self.bounded_stream(stream, permit))
1675 }
1676
1677 fn bounded_stream(
1678 &self,
1679 stream: A2aEventStream,
1680 permit: OwnedSemaphorePermit,
1681 ) -> futures_util::stream::BoxStream<'static, Result<wire::StreamResponse, wire::A2AError>>
1682 {
1683 struct StreamState {
1684 stream: A2aEventStream,
1685 _permit: OwnedSemaphorePermit,
1686 shutdown: CancellationToken,
1687 idle_timeout: Duration,
1688 remaining: u32,
1689 terminal_seen: bool,
1690 }
1691
1692 Box::pin(futures_util::stream::unfold(
1693 StreamState {
1694 stream,
1695 _permit: permit,
1696 shutdown: self.shutdown.clone(),
1697 idle_timeout: self.stream_idle_timeout,
1698 remaining: self.maximum_stream_events,
1699 terminal_seen: false,
1700 },
1701 |mut state| async move {
1702 if state.terminal_seen {
1703 return None;
1704 }
1705 if state.remaining == 0 {
1706 return Some((
1707 Err(wire::A2AError::internal("A2A stream event limit reached")),
1708 StreamState {
1709 terminal_seen: true,
1710 ..state
1711 },
1712 ));
1713 }
1714 let next = tokio::select! {
1715 () = state.shutdown.cancelled() => {
1716 return Some((
1717 Err(wire::A2AError::internal("A2A service is shutting down")),
1718 StreamState { terminal_seen: true, ..state },
1719 ));
1720 }
1721 next = tokio::time::timeout(state.idle_timeout, state.stream.next()) => next,
1722 };
1723 match next {
1724 Err(_) => Some((
1725 Err(wire::A2AError::internal("A2A stream idle timeout")),
1726 StreamState {
1727 terminal_seen: true,
1728 ..state
1729 },
1730 )),
1731 Ok(None) => None,
1732 Ok(Some(Err(error))) => Some((
1733 Err(map_service_error(error)),
1734 StreamState {
1735 terminal_seen: true,
1736 ..state
1737 },
1738 )),
1739 Ok(Some(Ok(event))) => {
1740 state.remaining -= 1;
1741 state.terminal_seen = event.is_terminal();
1742 Some((Ok(event.into_wire()), state))
1743 }
1744 }
1745 },
1746 ))
1747 }
1748}
1749
1750fn negotiate_extensions(
1751 params: &ServiceParams,
1752 card: &A2aAgentCard,
1753) -> Result<Vec<String>, wire::A2AError> {
1754 validate_version(params)?;
1755 let mut requested = Vec::new();
1756 if let Some(values) = params.get(A2A_EXTENSIONS_HEADER) {
1757 let encoded_size = values.iter().map(String::len).sum::<usize>();
1758 if encoded_size > MAX_EXTENSION_HEADER_BYTES {
1759 return Err(wire::A2AError::invalid_request(
1760 "A2A-Extensions header is too large",
1761 ));
1762 }
1763 for value in values {
1764 for extension in value.split(',') {
1765 let extension = extension.trim();
1766 if extension.is_empty() {
1767 continue;
1768 }
1769 if reqwest::Url::parse(extension).is_err() {
1770 return Err(wire::A2AError::invalid_request(
1771 "A2A-Extensions contains an invalid URI",
1772 ));
1773 }
1774 requested.push(extension.to_string());
1775 if requested.len() > MAX_NEGOTIATED_EXTENSIONS {
1776 return Err(wire::A2AError::invalid_request(
1777 "too many A2A extensions requested",
1778 ));
1779 }
1780 }
1781 }
1782 }
1783 requested.sort_unstable();
1784 requested.dedup();
1785
1786 let declared = card.capabilities().extensions().to_vec();
1787 let supported = declared
1788 .iter()
1789 .map(crate::A2aAgentExtension::uri)
1790 .collect::<HashSet<_>>();
1791 for extension in &declared {
1792 if extension.is_required() && !requested.iter().any(|value| value == extension.uri()) {
1793 return Err(wire::A2AError::new(
1794 wire::error_code::EXTENSION_SUPPORT_REQUIRED,
1795 "required A2A extension was not requested",
1796 ));
1797 }
1798 }
1799 requested.retain(|extension| supported.contains(extension.as_str()));
1800 Ok(requested)
1801}
1802
1803fn validate_version(params: &ServiceParams) -> Result<(), wire::A2AError> {
1804 let Some(values) = params.get(A2A_VERSION_HEADER) else {
1805 return Ok(());
1806 };
1807 if values.len() != 1 {
1808 return Err(wire::A2AError::invalid_request(
1809 "A2A-Version must appear at most once",
1810 ));
1811 }
1812 let version = values[0].trim();
1813 if version.is_empty() || version == A2A_PROTOCOL_VERSION_1_0 {
1814 Ok(())
1815 } else {
1816 Err(wire::A2AError::version_not_supported(version))
1817 }
1818}
1819
1820fn contract_error(_: A2aContractError) -> wire::A2AError {
1821 wire::A2AError::invalid_params("A2A payload violates bounded contract")
1822}
1823
1824fn map_authorization_error(error: A2aServerAuthorizationError) -> wire::A2AError {
1825 match error {
1826 A2aServerAuthorizationError::Forbidden => {
1827 wire::A2AError::task_not_found("authorized resource")
1828 }
1829 A2aServerAuthorizationError::Unavailable => {
1830 wire::A2AError::internal("A2A authorization is unavailable")
1831 }
1832 }
1833}
1834
1835fn map_admission_error(error: A2aServerAdmissionError) -> wire::A2AError {
1836 match error {
1837 A2aServerAdmissionError::Rejected => {
1838 wire::A2AError::internal("A2A request is rate limited")
1839 }
1840 A2aServerAdmissionError::Unavailable => {
1841 wire::A2AError::internal("A2A admission is unavailable")
1842 }
1843 }
1844}
1845
1846fn map_service_error(error: A2aTaskServiceError) -> wire::A2AError {
1847 match error {
1848 A2aTaskServiceError::TaskNotFound => wire::A2AError::task_not_found("task"),
1849 A2aTaskServiceError::TaskNotCancelable => wire::A2AError::task_not_cancelable("task"),
1850 A2aTaskServiceError::PushNotificationsNotSupported => {
1851 wire::A2AError::push_notification_not_supported()
1852 }
1853 A2aTaskServiceError::UnsupportedOperation => {
1854 wire::A2AError::unsupported_operation("A2A operation is not supported")
1855 }
1856 A2aTaskServiceError::ContentTypeNotSupported => {
1857 wire::A2AError::content_type_not_supported()
1858 }
1859 A2aTaskServiceError::InvalidAgentResponse => wire::A2AError::invalid_agent_response(),
1860 A2aTaskServiceError::ExtendedCardNotConfigured => wire::A2AError::new(
1861 wire::error_code::EXTENDED_CARD_NOT_CONFIGURED,
1862 "extended Agent Card is not configured",
1863 ),
1864 A2aTaskServiceError::ExtensionSupportRequired => wire::A2AError::new(
1865 wire::error_code::EXTENSION_SUPPORT_REQUIRED,
1866 "required A2A extension is not supported",
1867 ),
1868 A2aTaskServiceError::InvalidRequest => {
1869 wire::A2AError::invalid_params("A2A request is invalid")
1870 }
1871 A2aTaskServiceError::Unavailable => wire::A2AError::internal("A2A service is unavailable"),
1872 }
1873}
1874
1875#[async_trait]
1876impl RequestHandler for A2aSdkRequestHandler {
1877 async fn send_message(
1878 &self,
1879 params: &ServiceParams,
1880 request: wire::SendMessageRequest,
1881 ) -> Result<wire::SendMessageResponse, wire::A2AError> {
1882 let task_hint = request.message.task_id.clone();
1883 let request = A2aSendMessageRequest::try_from_wire(request).map_err(contract_error)?;
1884 let (context, permit) = self
1885 .prepare(
1886 params,
1887 A2aServerOperation::SendMessage,
1888 task_hint.as_deref(),
1889 None,
1890 )
1891 .await?;
1892 let response = self
1893 .unary(self.service.send_message(context, request), permit)
1894 .await?;
1895 Ok(response.into_wire())
1896 }
1897
1898 async fn send_streaming_message(
1899 &self,
1900 params: &ServiceParams,
1901 request: wire::SendMessageRequest,
1902 ) -> Result<
1903 futures_util::stream::BoxStream<'static, Result<wire::StreamResponse, wire::A2AError>>,
1904 wire::A2AError,
1905 > {
1906 let task_hint = request.message.task_id.clone();
1907 let request = A2aSendMessageRequest::try_from_wire(request).map_err(contract_error)?;
1908 let (context, permit) = self
1909 .prepare(
1910 params,
1911 A2aServerOperation::SendStreamingMessage,
1912 task_hint.as_deref(),
1913 None,
1914 )
1915 .await?;
1916 self.stream(
1917 self.service.send_streaming_message(context, request),
1918 permit,
1919 )
1920 .await
1921 }
1922
1923 async fn get_task(
1924 &self,
1925 params: &ServiceParams,
1926 request: wire::GetTaskRequest,
1927 ) -> Result<wire::Task, wire::A2AError> {
1928 let task_id = request.id.clone();
1929 let request = A2aGetTaskRequest::try_from_wire(request).map_err(contract_error)?;
1930 let (context, permit) = self
1931 .prepare(params, A2aServerOperation::GetTask, Some(&task_id), None)
1932 .await?;
1933 let task = self
1934 .unary(self.service.get_task(context, request), permit)
1935 .await?;
1936 Ok(task.into_wire())
1937 }
1938
1939 async fn list_tasks(
1940 &self,
1941 params: &ServiceParams,
1942 request: wire::ListTasksRequest,
1943 ) -> Result<wire::ListTasksResponse, wire::A2AError> {
1944 let request = A2aListTasksRequest::try_from_wire(request).map_err(contract_error)?;
1945 let (context, permit) = self
1946 .prepare(params, A2aServerOperation::ListTasks, None, None)
1947 .await?;
1948 let page = self
1949 .unary(self.service.list_tasks(context, request), permit)
1950 .await?;
1951 page.into_wire().map_err(contract_error)
1952 }
1953
1954 async fn cancel_task(
1955 &self,
1956 params: &ServiceParams,
1957 request: wire::CancelTaskRequest,
1958 ) -> Result<wire::Task, wire::A2AError> {
1959 let task_id = request.id.clone();
1960 let request = A2aCancelTaskRequest::try_from_wire(request).map_err(contract_error)?;
1961 let (context, permit) = self
1962 .prepare(params, A2aServerOperation::CancelTask, Some(&task_id), None)
1963 .await?;
1964 let task = self
1965 .unary(self.service.cancel_task(context, request), permit)
1966 .await?;
1967 Ok(task.into_wire())
1968 }
1969
1970 async fn subscribe_to_task(
1971 &self,
1972 params: &ServiceParams,
1973 request: wire::SubscribeToTaskRequest,
1974 ) -> Result<
1975 futures_util::stream::BoxStream<'static, Result<wire::StreamResponse, wire::A2AError>>,
1976 wire::A2AError,
1977 > {
1978 let task_id = request.id.clone();
1979 let request = A2aSubscribeTaskRequest::try_from_wire(request).map_err(contract_error)?;
1980 let (context, permit) = self
1981 .prepare(
1982 params,
1983 A2aServerOperation::SubscribeToTask,
1984 Some(&task_id),
1985 None,
1986 )
1987 .await?;
1988 self.stream(self.service.subscribe_to_task(context, request), permit)
1989 .await
1990 }
1991
1992 async fn create_push_config(
1993 &self,
1994 params: &ServiceParams,
1995 request: wire::TaskPushNotificationConfig,
1996 ) -> Result<wire::TaskPushNotificationConfig, wire::A2AError> {
1997 let task_hint = (!request.task_id.is_empty()).then_some(request.task_id.clone());
1998 let request = A2aPushConfig::try_from_wire(request).map_err(contract_error)?;
1999 let (context, permit) = self
2000 .prepare(
2001 params,
2002 A2aServerOperation::CreatePushConfig,
2003 task_hint.as_deref(),
2004 None,
2005 )
2006 .await?;
2007 let config = self
2008 .unary(self.service.create_push_config(context, request), permit)
2009 .await?;
2010 Ok(config.into_wire())
2011 }
2012
2013 async fn get_push_config(
2014 &self,
2015 params: &ServiceParams,
2016 request: wire::GetTaskPushNotificationConfigRequest,
2017 ) -> Result<wire::TaskPushNotificationConfig, wire::A2AError> {
2018 let task_id = request.task_id.clone();
2019 let config_id = request.id.clone();
2020 let request = A2aGetPushConfigRequest::try_from_wire(request).map_err(contract_error)?;
2021 let (context, permit) = self
2022 .prepare(
2023 params,
2024 A2aServerOperation::GetPushConfig,
2025 Some(&task_id),
2026 Some(&config_id),
2027 )
2028 .await?;
2029 let config = self
2030 .unary(self.service.get_push_config(context, request), permit)
2031 .await?;
2032 Ok(config.into_wire())
2033 }
2034
2035 async fn list_push_configs(
2036 &self,
2037 params: &ServiceParams,
2038 request: wire::ListTaskPushNotificationConfigsRequest,
2039 ) -> Result<wire::ListTaskPushNotificationConfigsResponse, wire::A2AError> {
2040 let task_id = request.task_id.clone();
2041 let request = A2aListPushConfigsRequest::try_from_wire(request).map_err(contract_error)?;
2042 let (context, permit) = self
2043 .prepare(
2044 params,
2045 A2aServerOperation::ListPushConfigs,
2046 Some(&task_id),
2047 None,
2048 )
2049 .await?;
2050 let page = self
2051 .unary(self.service.list_push_configs(context, request), permit)
2052 .await?;
2053 Ok(page.into_wire())
2054 }
2055
2056 async fn delete_push_config(
2057 &self,
2058 params: &ServiceParams,
2059 request: wire::DeleteTaskPushNotificationConfigRequest,
2060 ) -> Result<(), wire::A2AError> {
2061 if request.tenant.is_some() {
2062 return Err(contract_error(A2aContractError::Unsupported {
2063 field: "request tenant override",
2064 value: "tenant".to_string(),
2065 }));
2066 }
2067 let task_id = request.task_id.clone();
2068 let config_id = request.id.clone();
2069 let request =
2070 A2aDeletePushConfigRequest::new(request.task_id, request.id).map_err(contract_error)?;
2071 let (context, permit) = self
2072 .prepare(
2073 params,
2074 A2aServerOperation::DeletePushConfig,
2075 Some(&task_id),
2076 Some(&config_id),
2077 )
2078 .await?;
2079 self.unary(self.service.delete_push_config(context, request), permit)
2080 .await
2081 }
2082
2083 async fn get_extended_agent_card(
2084 &self,
2085 params: &ServiceParams,
2086 request: wire::GetExtendedAgentCardRequest,
2087 ) -> Result<wire::AgentCard, wire::A2AError> {
2088 if request.tenant.is_some() {
2089 return Err(contract_error(A2aContractError::Unsupported {
2090 field: "request tenant override",
2091 value: "tenant".to_string(),
2092 }));
2093 }
2094 let (context, permit) = self
2095 .prepare(params, A2aServerOperation::GetExtendedAgentCard, None, None)
2096 .await?;
2097 let card = self
2098 .unary(self.service.get_extended_agent_card(context), permit)
2099 .await?;
2100 Ok(card.into_wire())
2101 }
2102}
2103
2104#[cfg(test)]
2105mod tests {
2106 use super::*;
2107 use crate::{
2108 A2aAgentCapabilities, A2aAgentInterface, A2aAgentSkill, A2aBinding, A2aMessage,
2109 A2aMessageRole, A2aPart, A2aTaskState, A2aTaskStatus,
2110 };
2111 use axum::body::Body;
2112 use stateknot_core::{IssuerId, SubjectId};
2113 use tower_service::Service;
2114
2115 #[derive(Clone)]
2116 struct TestAuthenticator;
2117
2118 impl A2aServerAuthenticator for TestAuthenticator {
2119 fn authenticate(
2120 &self,
2121 request: A2aServerAuthenticationRequest,
2122 ) -> BoxFuture<'_, Result<A2aServerPrincipal, A2aServerAuthenticationError>> {
2123 Box::pin(async move {
2124 if request
2125 .bearer()
2126 .is_none_or(|value| value.expose_secret() != "token")
2127 {
2128 return Err(A2aServerAuthenticationError::InvalidCredential);
2129 }
2130 Ok(A2aServerPrincipal::new(
2131 TenantId::new("tenant-a").unwrap(),
2132 PrincipalIdentity::new(
2133 IssuerId::new("https://issuer.example").unwrap(),
2134 SubjectId::new("caller").unwrap(),
2135 ),
2136 ["a2a.invoke"],
2137 )
2138 .unwrap())
2139 })
2140 }
2141 }
2142
2143 struct TestService;
2144
2145 impl A2aTaskService for TestService {
2146 fn capabilities(&self) -> A2aTaskServiceCapabilities {
2147 A2aTaskServiceCapabilities::default()
2148 }
2149
2150 fn send_message(
2151 &self,
2152 _context: A2aRequestContext,
2153 request: A2aSendMessageRequest,
2154 ) -> BoxFuture<'_, Result<A2aSendMessageResponse, A2aTaskServiceError>> {
2155 Box::pin(async move {
2156 let response = A2aMessage::new(
2157 "response-1",
2158 A2aMessageRole::Agent,
2159 vec![
2160 A2aPart::text(format!("echo:{}", request.message().message_id())).unwrap(),
2161 ],
2162 )
2163 .unwrap();
2164 Ok(A2aSendMessageResponse::Message(response))
2165 })
2166 }
2167
2168 fn send_streaming_message(
2169 &self,
2170 _context: A2aRequestContext,
2171 _request: A2aSendMessageRequest,
2172 ) -> BoxFuture<'_, Result<A2aEventStream, A2aTaskServiceError>> {
2173 Box::pin(async { Err(A2aTaskServiceError::UnsupportedOperation) })
2174 }
2175
2176 fn get_task(
2177 &self,
2178 _context: A2aRequestContext,
2179 _request: A2aGetTaskRequest,
2180 ) -> BoxFuture<'_, Result<A2aTask, A2aTaskServiceError>> {
2181 Box::pin(async { Err(A2aTaskServiceError::TaskNotFound) })
2182 }
2183
2184 fn list_tasks(
2185 &self,
2186 _context: A2aRequestContext,
2187 _request: A2aListTasksRequest,
2188 ) -> BoxFuture<'_, Result<A2aTaskPage, A2aTaskServiceError>> {
2189 Box::pin(async {
2190 A2aTaskPage::new(Vec::new(), None, A2aListTasksRequest::DEFAULT_PAGE_SIZE, 0)
2191 .map_err(|_| A2aTaskServiceError::InvalidAgentResponse)
2192 })
2193 }
2194
2195 fn cancel_task(
2196 &self,
2197 _context: A2aRequestContext,
2198 _request: A2aCancelTaskRequest,
2199 ) -> BoxFuture<'_, Result<A2aTask, A2aTaskServiceError>> {
2200 Box::pin(async { Err(A2aTaskServiceError::TaskNotFound) })
2201 }
2202
2203 fn subscribe_to_task(
2204 &self,
2205 _context: A2aRequestContext,
2206 _request: A2aSubscribeTaskRequest,
2207 ) -> BoxFuture<'_, Result<A2aEventStream, A2aTaskServiceError>> {
2208 Box::pin(async { Err(A2aTaskServiceError::UnsupportedOperation) })
2209 }
2210
2211 fn create_push_config(
2212 &self,
2213 _context: A2aRequestContext,
2214 _config: A2aPushConfig,
2215 ) -> BoxFuture<'_, Result<A2aPushConfig, A2aTaskServiceError>> {
2216 Box::pin(async { Err(A2aTaskServiceError::PushNotificationsNotSupported) })
2217 }
2218
2219 fn get_push_config(
2220 &self,
2221 _context: A2aRequestContext,
2222 _request: A2aGetPushConfigRequest,
2223 ) -> BoxFuture<'_, Result<A2aPushConfig, A2aTaskServiceError>> {
2224 Box::pin(async { Err(A2aTaskServiceError::PushNotificationsNotSupported) })
2225 }
2226
2227 fn list_push_configs(
2228 &self,
2229 _context: A2aRequestContext,
2230 _request: A2aListPushConfigsRequest,
2231 ) -> BoxFuture<'_, Result<A2aPushConfigPage, A2aTaskServiceError>> {
2232 Box::pin(async { Err(A2aTaskServiceError::PushNotificationsNotSupported) })
2233 }
2234
2235 fn delete_push_config(
2236 &self,
2237 _context: A2aRequestContext,
2238 _request: A2aDeletePushConfigRequest,
2239 ) -> BoxFuture<'_, Result<(), A2aTaskServiceError>> {
2240 Box::pin(async { Err(A2aTaskServiceError::PushNotificationsNotSupported) })
2241 }
2242
2243 fn get_extended_agent_card(
2244 &self,
2245 _context: A2aRequestContext,
2246 ) -> BoxFuture<'_, Result<A2aAgentCard, A2aTaskServiceError>> {
2247 Box::pin(async { Err(A2aTaskServiceError::ExtendedCardNotConfigured) })
2248 }
2249 }
2250
2251 fn card() -> A2aAgentCard {
2252 A2aAgentCard::builder("Test", "Test A2A agent", "0.0.0")
2253 .unwrap()
2254 .capabilities(A2aAgentCapabilities::new())
2255 .interface(
2256 A2aAgentInterface::new("https://agent.example/a2a/rest", A2aBinding::HttpJson)
2257 .unwrap(),
2258 )
2259 .unwrap()
2260 .interface(
2261 A2aAgentInterface::new("https://agent.example/a2a/jsonrpc", A2aBinding::JsonRpc)
2262 .unwrap(),
2263 )
2264 .unwrap()
2265 .default_input_modes(vec!["text/plain".to_string()])
2266 .unwrap()
2267 .default_output_modes(vec!["text/plain".to_string()])
2268 .unwrap()
2269 .skill(
2270 A2aAgentSkill::new(
2271 "echo",
2272 "Echo",
2273 "Echoes a bounded message.",
2274 vec!["test".to_string()],
2275 )
2276 .unwrap(),
2277 )
2278 .unwrap()
2279 .build()
2280 .unwrap()
2281 }
2282
2283 fn server() -> A2aServer {
2284 A2aServer::new(
2285 card(),
2286 TestAuthenticator,
2287 AllowA2aServerAuthorization,
2288 AllowA2aServerAdmission,
2289 TestService,
2290 A2aServerHttpOptions::new()
2291 .with_allowed_authorities(["agent.example"])
2292 .unwrap()
2293 .with_bearer_challenge("Bearer realm=\"stateknot\"")
2294 .unwrap(),
2295 CancellationToken::new(),
2296 )
2297 .unwrap()
2298 }
2299
2300 #[tokio::test]
2301 async fn authenticates_before_jsonrpc_dispatch() {
2302 let mut router = server().router();
2303 let request = Request::builder()
2304 .method(Method::POST)
2305 .uri("/a2a/jsonrpc")
2306 .header(HOST, "agent.example")
2307 .header(CONTENT_TYPE, "application/json")
2308 .body(Body::from("not json"))
2309 .unwrap();
2310 let response = router.call(request).await.unwrap();
2311 assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
2312 assert!(response.headers().contains_key(WWW_AUTHENTICATE));
2313 }
2314
2315 #[tokio::test]
2316 async fn serves_cacheable_card_and_rejects_legacy_routes() {
2317 let mut router = server().router();
2318 let response = router
2319 .call(
2320 Request::builder()
2321 .uri(A2A_AGENT_CARD_PATH)
2322 .header(HOST, "agent.example")
2323 .body(Body::empty())
2324 .unwrap(),
2325 )
2326 .await
2327 .unwrap();
2328 assert_eq!(response.status(), StatusCode::OK);
2329 assert!(response.headers().contains_key(ETAG));
2330 let last_modified = response.headers()[LAST_MODIFIED].clone();
2331 assert!(response.headers().contains_key(CACHE_CONTROL));
2332
2333 let response = router
2334 .call(
2335 Request::builder()
2336 .uri(A2A_AGENT_CARD_PATH)
2337 .header(HOST, "agent.example")
2338 .header(IF_MODIFIED_SINCE, last_modified)
2339 .body(Body::empty())
2340 .unwrap(),
2341 )
2342 .await
2343 .unwrap();
2344 assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
2345
2346 let response = router
2347 .call(
2348 Request::builder()
2349 .method(Method::POST)
2350 .uri("/a2a/rest/message/send")
2351 .header(HOST, "agent.example")
2352 .header(CONTENT_TYPE, "application/json")
2353 .header(AUTHORIZATION, "Bearer token")
2354 .body(Body::from("{}"))
2355 .unwrap(),
2356 )
2357 .await
2358 .unwrap();
2359 assert_eq!(response.status(), StatusCode::NOT_FOUND);
2360 }
2361
2362 #[tokio::test]
2363 async fn serves_base_url_clients_at_the_jsonrpc_slash_form() {
2364 let mut router = server().router();
2365 let response = router
2366 .call(
2367 Request::builder()
2368 .method(Method::POST)
2369 .uri("/a2a/jsonrpc/")
2370 .header(HOST, "agent.example")
2371 .header(CONTENT_TYPE, "application/json")
2372 .header(AUTHORIZATION, "Bearer token")
2373 .body(Body::from("{}"))
2374 .unwrap(),
2375 )
2376 .await
2377 .unwrap();
2378 assert_eq!(response.status(), StatusCode::OK);
2379 assert_eq!(
2380 response.headers()[CONTENT_TYPE],
2381 HeaderValue::from_static("application/json")
2382 );
2383 let body = response.into_body().collect().await.unwrap().to_bytes();
2384 let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2385 assert_eq!(value["error"]["code"], -32600);
2386 assert_eq!(value["id"], serde_json::Value::Null);
2387 }
2388
2389 #[tokio::test]
2390 async fn returns_jsonrpc_parse_error_after_authentication() {
2391 let mut router = server().router();
2392 let response = router
2393 .call(
2394 Request::builder()
2395 .method(Method::POST)
2396 .uri("/a2a/jsonrpc")
2397 .header(HOST, "agent.example")
2398 .header(CONTENT_TYPE, "application/json")
2399 .header(AUTHORIZATION, "Bearer token")
2400 .body(Body::from("{"))
2401 .unwrap(),
2402 )
2403 .await
2404 .unwrap();
2405 assert_eq!(response.status(), StatusCode::OK);
2406 let body = response.into_body().collect().await.unwrap().to_bytes();
2407 let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2408 assert_eq!(value["error"]["code"], -32700);
2409 assert_eq!(value["id"], serde_json::Value::Null);
2410 }
2411
2412 #[tokio::test]
2413 async fn rejects_rest_media_type_with_aip193_error() {
2414 let mut router = server().router();
2415 let response = router
2416 .call(
2417 Request::builder()
2418 .method(Method::POST)
2419 .uri("/a2a/rest/message:send")
2420 .header(HOST, "agent.example")
2421 .header(CONTENT_TYPE, "text/plain")
2422 .body(Body::from("{}"))
2423 .unwrap(),
2424 )
2425 .await
2426 .unwrap();
2427 assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
2428 let body = response.into_body().collect().await.unwrap().to_bytes();
2429 let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2430 assert_eq!(value["error"]["code"], 415);
2431 assert_eq!(
2432 value["error"]["details"][0]["reason"],
2433 "CONTENT_TYPE_NOT_SUPPORTED"
2434 );
2435 }
2436
2437 #[tokio::test]
2438 async fn dispatches_bounded_rest_message() {
2439 let mut router = server().router();
2440 let body = serde_json::json!({
2441 "message": {
2442 "messageId": "message-1",
2443 "role": "ROLE_USER",
2444 "parts": [{"text": "hello"}]
2445 }
2446 });
2447 let response = router
2448 .call(
2449 Request::builder()
2450 .method(Method::POST)
2451 .uri("/a2a/rest/message:send")
2452 .header(HOST, "agent.example")
2453 .header(CONTENT_TYPE, "application/a2a+json")
2454 .header(AUTHORIZATION, "Bearer token")
2455 .header(A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION_1_0)
2456 .body(Body::from(serde_json::to_vec(&body).unwrap()))
2457 .unwrap(),
2458 )
2459 .await
2460 .unwrap();
2461 assert_eq!(response.status(), StatusCode::OK);
2462 let body = response.into_body().collect().await.unwrap().to_bytes();
2463 let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2464 assert_eq!(value["message"]["parts"][0]["text"], "echo:message-1");
2465 }
2466
2467 #[tokio::test]
2468 async fn ignores_unknown_fields_for_forward_compatibility() {
2469 let mut router = server().router();
2470 let params = serde_json::json!({
2471 "message": {
2472 "messageId": "message-with-future-fields",
2473 "role": "ROLE_USER",
2474 "parts": [{"text": "hello", "futurePartField": true}],
2475 "futureMessageField": "ignored"
2476 },
2477 "futureRequestField": 42
2478 });
2479
2480 let jsonrpc = serde_json::json!({
2481 "jsonrpc": "2.0",
2482 "id": 1,
2483 "method": "SendMessage",
2484 "params": params
2485 });
2486 let response = router
2487 .call(
2488 Request::builder()
2489 .method(Method::POST)
2490 .uri("/a2a/jsonrpc/")
2491 .header(HOST, "agent.example")
2492 .header(CONTENT_TYPE, "application/json")
2493 .header(AUTHORIZATION, "Bearer token")
2494 .header(A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION_1_0)
2495 .body(Body::from(serde_json::to_vec(&jsonrpc).unwrap()))
2496 .unwrap(),
2497 )
2498 .await
2499 .unwrap();
2500 assert_eq!(response.status(), StatusCode::OK);
2501 let body = response.into_body().collect().await.unwrap().to_bytes();
2502 let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2503 assert!(value.get("error").is_none(), "{value}");
2504
2505 let response = router
2506 .call(
2507 Request::builder()
2508 .method(Method::POST)
2509 .uri("/a2a/rest/message:send")
2510 .header(HOST, "agent.example")
2511 .header(CONTENT_TYPE, "application/a2a+json")
2512 .header(AUTHORIZATION, "Bearer token")
2513 .header(A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION_1_0)
2514 .body(Body::from(serde_json::to_vec(¶ms).unwrap()))
2515 .unwrap(),
2516 )
2517 .await
2518 .unwrap();
2519 assert_eq!(response.status(), StatusCode::OK);
2520 let body = response.into_body().collect().await.unwrap().to_bytes();
2521 let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2522 assert_eq!(
2523 value["message"]["parts"][0]["text"],
2524 "echo:message-with-future-fields"
2525 );
2526 }
2527
2528 #[test]
2529 fn task_status_construction_stays_independent() {
2530 let status = A2aTaskStatus::new(A2aTaskState::Completed, None, None).unwrap();
2531 assert_eq!(status.state(), A2aTaskState::Completed);
2532 }
2533
2534 #[test]
2535 fn normalizes_sdk_rest_statuses_and_utc_timestamps() {
2536 let mut status = StatusCode::BAD_REQUEST;
2537 let mut value = serde_json::json!({
2538 "error": {
2539 "code": 400,
2540 "status": "FAILED_PRECONDITION",
2541 "details": [{
2542 "reason": "TASK_NOT_CANCELABLE",
2543 "metadata": {"timestamp": "2026-09-03T02:35:41.624133+00:00"}
2544 }]
2545 }
2546 });
2547 normalize_utc_timestamps(&mut value);
2548 normalize_rest_error_status(&mut status, &mut value);
2549 assert_eq!(status, StatusCode::CONFLICT);
2550 assert_eq!(value["error"]["code"], 409);
2551 assert_eq!(
2552 value["error"]["details"][0]["metadata"]["timestamp"],
2553 "2026-09-03T02:35:41.624133Z"
2554 );
2555 }
2556}