Skip to main content

vtcode_a2a/
server.rs

1//! A2A HTTP Server using axum
2//!
3//! Provides HTTP endpoints for the A2A Protocol, enabling VT Code to operate as an A2A agent.
4//! The server exposes:
5//! - Agent discovery via `/.well-known/agent-card.json`
6//! - RPC endpoints at `/a2a` for message sending and task management
7//! - Streaming endpoint at `/a2a/stream` for real-time updates via Server-Sent Events
8
9use crate::WebhookNotifier;
10use crate::agent_card::AgentCard;
11use crate::errors::{A2aError, A2aErrorCode, A2aResult};
12use crate::rpc::{
13    JSONRPC_VERSION, JsonRpcError, JsonRpcRequest, JsonRpcResponse, ListTasksParams, METHOD_MESSAGE_SEND,
14    METHOD_MESSAGE_STREAM, METHOD_TASKS_CANCEL, METHOD_TASKS_GET, METHOD_TASKS_LIST, METHOD_TASKS_PUSH_CONFIG_GET,
15    METHOD_TASKS_PUSH_CONFIG_SET, MessageSendParams, SendStreamingMessageResponse, StreamingEvent, TaskIdParams,
16    TaskQueryParams,
17};
18use crate::task_manager::TaskManager;
19use crate::types::TaskState;
20use axum::{
21    Json, Router,
22    extract::{Request, State},
23    http::{
24        HeaderMap, HeaderValue, Method, StatusCode,
25        header::{AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE},
26    },
27    middleware::{self, Next},
28    response::{
29        IntoResponse, Response,
30        sse::{Event, Sse},
31    },
32    routing::post,
33};
34use serde_json::{Value, json};
35use std::fmt;
36use std::future::Future;
37use std::net::SocketAddr;
38use std::sync::Arc;
39use std::time::Duration;
40use tower_http::cors::CorsLayer;
41use uuid::Uuid;
42
43/// Bearer token used to protect the A2A RPC and streaming endpoints.
44#[derive(Clone)]
45struct AuthToken(Arc<str>);
46
47impl fmt::Debug for AuthToken {
48    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49        formatter.write_str("AuthToken(REDACTED)")
50    }
51}
52
53impl AuthToken {
54    fn generated() -> Self {
55        Self(Arc::from(Uuid::new_v4().to_string()))
56    }
57
58    fn from_value(value: String) -> anyhow::Result<Self> {
59        if value.is_empty() || !value.is_ascii() || value.chars().any(char::is_whitespace) {
60            anyhow::bail!("A2A authentication token must be non-empty ASCII text without whitespace");
61        }
62
63        Ok(Self(Arc::from(value)))
64    }
65
66    fn as_str(&self) -> &str {
67        &self.0
68    }
69
70    fn matches(&self, presented: &str) -> bool {
71        let expected = self.0.as_bytes();
72        let presented = presented.as_bytes();
73        // Branch-free OR-reduction over iterators (no per-byte bounds checks).
74        // LLVM can auto-vectorize this shape; the indexed `.get(i)` form cannot
75        // prove in-bounds and stays scalar. All bytes are still visited so the
76        // comparison remains constant-time with no early exit.
77        let common_len = expected.len().min(presented.len());
78        let (expected_common, expected_tail) = expected.split_at(common_len);
79        let (presented_common, presented_tail) = presented.split_at(common_len);
80        let mut difference = expected.len() ^ presented.len();
81        difference |= expected_common
82            .iter()
83            .zip(presented_common.iter())
84            .fold(0_usize, |acc, (&a, &b)| acc | usize::from(a ^ b));
85        difference |= expected_tail.iter().fold(0_usize, |acc, &b| acc | usize::from(b));
86        difference |= presented_tail.iter().fold(0_usize, |acc, &b| acc | usize::from(b));
87
88        difference == 0
89    }
90}
91
92// ============================================================================
93// Server State
94// ============================================================================
95
96/// A2A Server State containing shared resources
97#[derive(Debug, Clone)]
98pub struct A2aServerState {
99    /// Task manager for handling task lifecycle
100    task_manager: Arc<TaskManager>,
101    /// Agent card for discovery
102    agent_card: Arc<AgentCard>,
103    /// Broadcast channel for streaming events
104    event_tx: Arc<tokio::sync::broadcast::Sender<StreamingEvent>>,
105    /// Webhook notifier for push notifications
106    webhook_notifier: Arc<WebhookNotifier>,
107    /// Bearer token required by the RPC and streaming endpoints
108    auth_token: AuthToken,
109}
110
111impl A2aServerState {
112    /// Create a new server state
113    pub fn new(task_manager: TaskManager, agent_card: AgentCard) -> Self {
114        Self::from_auth_token(task_manager, agent_card, AuthToken::generated())
115    }
116
117    /// Create a new server state with a caller-supplied bearer token.
118    pub fn new_with_auth_token(
119        task_manager: TaskManager,
120        agent_card: AgentCard,
121        auth_token: impl Into<String>,
122    ) -> anyhow::Result<Self> {
123        let auth_token = AuthToken::from_value(auth_token.into())?;
124        Ok(Self::from_auth_token(task_manager, agent_card, auth_token))
125    }
126
127    fn from_auth_token(task_manager: TaskManager, agent_card: AgentCard, auth_token: AuthToken) -> Self {
128        let (event_tx, _) = tokio::sync::broadcast::channel(100);
129        Self {
130            task_manager: Arc::new(task_manager),
131            agent_card: Arc::new(agent_card.with_bearer_auth()),
132            event_tx: Arc::new(event_tx),
133            webhook_notifier: Arc::new(WebhookNotifier::new()),
134            auth_token,
135        }
136    }
137
138    /// Return the bearer token clients must use for protected endpoints.
139    pub fn auth_token(&self) -> &str {
140        self.auth_token.as_str()
141    }
142
143    /// Create a server state with default settings for VT Code
144    fn vtcode_default(base_url: impl Into<String>) -> Self {
145        Self::new(TaskManager::new(), AgentCard::vtcode_default(base_url))
146    }
147}
148
149// ============================================================================
150// Router Creation
151// ============================================================================
152
153/// Create the A2A HTTP router
154pub fn create_router(state: A2aServerState) -> Router {
155    let protected_routes = Router::new()
156        .route("/a2a", post(handle_rpc))
157        .route("/a2a/stream", post(handle_stream))
158        .layer(middleware::from_fn_with_state(state.clone(), require_bearer_auth));
159
160    Router::new()
161        .route("/.well-known/agent-card.json", axum::routing::get(get_agent_card))
162        .merge(protected_routes)
163        .with_state(state)
164        // Cross-origin access is disabled by default. A deployment that needs
165        // browser clients must add an explicit origin allowlist at its edge.
166        .layer(
167            CorsLayer::new()
168                .allow_methods([Method::POST])
169                .allow_headers([AUTHORIZATION, CONTENT_TYPE]),
170        )
171}
172
173async fn require_bearer_auth(State(state): State<A2aServerState>, request: Request, next: Next) -> Response {
174    if has_valid_bearer_auth(&state, request.headers()) {
175        next.run(request).await
176    } else {
177        let mut response = (
178            StatusCode::UNAUTHORIZED,
179            Json(JsonRpcResponse::error(JsonRpcError::new(-32600, "Authentication required"), Value::Null)),
180        )
181            .into_response();
182        drop(
183            response
184                .headers_mut()
185                .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")),
186        );
187        response
188    }
189}
190
191fn has_valid_bearer_auth(state: &A2aServerState, headers: &HeaderMap) -> bool {
192    if headers.get_all(AUTHORIZATION).iter().count() != 1 {
193        return false;
194    }
195
196    let Some(value) = headers.get(AUTHORIZATION).and_then(|value| value.to_str().ok()) else {
197        return false;
198    };
199
200    let Some((scheme, token)) = value.split_once(' ') else {
201        return false;
202    };
203
204    scheme.eq_ignore_ascii_case("Bearer")
205        && !token.is_empty()
206        && !token.chars().any(char::is_whitespace)
207        && state.auth_token.matches(token)
208}
209
210// ============================================================================
211// Handlers
212// ============================================================================
213
214/// Get agent card for discovery
215async fn get_agent_card(State(state): State<A2aServerState>) -> Json<AgentCard> {
216    Json(state.agent_card.as_ref().clone())
217}
218
219/// Handle JSON-RPC requests
220async fn handle_rpc(
221    State(state): State<A2aServerState>,
222    Json(request): Json<JsonRpcRequest>,
223) -> Result<Json<JsonRpcResponse>, A2aErrorResponse> {
224    // Validate request
225    if request.jsonrpc != JSONRPC_VERSION {
226        return Err(A2aErrorResponse::invalid_request("Invalid JSON-RPC version", request.id));
227    }
228
229    // Dispatch to method handler
230    let result = match request.method.as_str() {
231        METHOD_MESSAGE_SEND => handle_message_send(&state, request.params, request.id.clone()).await,
232        METHOD_MESSAGE_STREAM => handle_message_stream(&state, request.params, request.id.clone()).await,
233        METHOD_TASKS_GET => handle_tasks_get(&state, request.params, request.id.clone()).await,
234        METHOD_TASKS_LIST => handle_tasks_list(&state, request.params, request.id.clone()).await,
235        METHOD_TASKS_CANCEL => handle_tasks_cancel(&state, request.params, request.id.clone()).await,
236        METHOD_TASKS_PUSH_CONFIG_SET => handle_push_config_set(&state, request.params, request.id.clone()).await,
237        METHOD_TASKS_PUSH_CONFIG_GET => handle_push_config_get(&state, request.params, request.id.clone()).await,
238        _ => {
239            return Err(A2aErrorResponse::method_not_found(&request.method, request.id));
240        }
241    };
242
243    match result {
244        Ok(result_value) => Ok(Json(JsonRpcResponse::success(result_value, request.id))),
245        Err(err) => Err(A2aErrorResponse::from_error(err, request.id)),
246    }
247}
248
249/// Spawn a best-effort webhook delivery task.
250///
251/// Documented detached: the delivery is bounded (10s client timeout, max 3
252/// retries with backoff in `WebhookNotifier`), self-terminating, and its
253/// outcome is observable via `tracing::warn` on failure. Detachment is safe
254/// because webhook delivery must never block the SSE stream or agent turn;
255/// see "Task Extent, Error Propagation, and Cancel-Safety" in
256/// `docs/guides/async-architecture.md`.
257fn spawn_webhook_delivery(
258    notifier: Arc<WebhookNotifier>,
259    task_manager: Arc<TaskManager>,
260    task_id: String,
261    event: StreamingEvent,
262) {
263    drop(tokio::spawn(async move {
264        let Some(cfg) = task_manager.get_webhook_config(&task_id).await else {
265            return;
266        };
267        if let Err(error) = notifier.send_event(&cfg, event).await {
268            tracing::warn!(task_id = %task_id, error = %error, "A2A webhook delivery failed");
269        }
270    }));
271}
272
273/// Handle Server-Sent Events streaming
274async fn handle_stream(State(state): State<A2aServerState>, Json(request): Json<JsonRpcRequest>) -> impl IntoResponse {
275    if request.jsonrpc != JSONRPC_VERSION {
276        return Err(A2aErrorResponse::invalid_request("Invalid JSON-RPC version", request.id.clone()));
277    }
278
279    if request.method != METHOD_MESSAGE_STREAM {
280        return Err(A2aErrorResponse::method_not_found(&request.method, request.id.clone()));
281    }
282
283    // Parse params
284    let params: MessageSendParams = serde_json::from_value(request.params.unwrap_or_default())
285        .map_err(|_e| A2aErrorResponse::invalid_request("Invalid message/stream params", request.id.clone()))?;
286
287    // Create or get task
288    let task_id = if let Some(task_id) = params.task_id.clone() {
289        task_id
290    } else {
291        let task = state.task_manager.create_task(params.context_id.clone()).await;
292        task.id.clone()
293    };
294
295    // Add initial message
296    drop(
297        state
298            .task_manager
299            .add_message(&task_id, params.message.clone())
300            .await
301            .map_err(|e| A2aErrorResponse::from_error(e, request.id.clone()))?,
302    );
303
304    // Subscribe to broadcast channel
305    let mut rx = state.event_tx.subscribe();
306    let task_id_clone = task_id.clone();
307    let context_id = params.context_id.clone();
308    let notifier = state.webhook_notifier.clone();
309    let task_manager = state.task_manager.clone();
310
311    // Create stream from broadcast receiver using async_stream
312    let stream = async_stream::stream! {
313        while let Ok(event) = rx.recv().await {
314            // Filter events for this task/context
315            let matches = match &event {
316                StreamingEvent::Message { context_id: ctx, .. } => {
317                    context_id.as_ref() == ctx.as_ref()
318                }
319                StreamingEvent::TaskStatus { task_id: tid, .. } => tid == &task_id_clone,
320                StreamingEvent::TaskArtifact { task_id: tid, .. } => tid == &task_id_clone,
321                _ => false,
322            };
323
324            if matches {
325                spawn_webhook_delivery(notifier.clone(), task_manager.clone(), task_id_clone.clone(), event.clone());
326
327                let is_final = event.is_final();
328                let json = serde_json::to_string(&SendStreamingMessageResponse { event })
329                    .unwrap_or_default();
330                yield Ok::<_, !>(Event::default().data(json));
331
332                if is_final {
333                    break;
334                }
335            }
336        }
337    };
338
339    // Start background task to process and emit events.
340    // Documented detached: bounded demo pipeline (~600ms of sleeps plus
341    // channel sends), terminated by completion, with outcomes fanned out over
342    // the broadcast channel; webhook legs use `spawn_webhook_delivery`.
343    let state_clone = state.clone();
344    let task_id_clone = task_id.clone();
345    drop(tokio::spawn(async move {
346        // Simulate agent processing
347        tokio::time::sleep(Duration::from_millis(100)).await;
348
349        // Update task to working
350        drop(
351            state_clone
352                .task_manager
353                .update_status(&task_id_clone, TaskState::Working, None)
354                .await,
355        );
356
357        // Send status update event
358        let status_event = StreamingEvent::TaskStatus {
359            task_id: task_id_clone.clone(),
360            context_id: params.context_id.clone(),
361            status: crate::types::TaskStatus::new(TaskState::Working),
362            kind: "status-update".to_string(),
363            r#final: false,
364        };
365        drop(state_clone.event_tx.send(status_event.clone()));
366
367        spawn_webhook_delivery(
368            state_clone.webhook_notifier.clone(),
369            state_clone.task_manager.clone(),
370            task_id_clone.clone(),
371            status_event,
372        );
373
374        // Simulate generating a response message
375        tokio::time::sleep(Duration::from_millis(200)).await;
376        let response_msg = crate::types::Message::agent_text("Processing your request...");
377        let message_event = StreamingEvent::Message {
378            message: response_msg,
379            context_id: params.context_id.clone(),
380            kind: "streaming-response".to_string(),
381            r#final: false,
382        };
383        drop(state_clone.event_tx.send(message_event.clone()));
384
385        spawn_webhook_delivery(
386            state_clone.webhook_notifier.clone(),
387            state_clone.task_manager.clone(),
388            task_id_clone.clone(),
389            message_event,
390        );
391
392        // Complete the task
393        tokio::time::sleep(Duration::from_millis(300)).await;
394        drop(
395            state_clone
396                .task_manager
397                .update_status(&task_id_clone, TaskState::Completed, None)
398                .await,
399        );
400
401        // Send final status event
402        let final_status_event = StreamingEvent::TaskStatus {
403            task_id: task_id_clone,
404            context_id: params.context_id,
405            status: crate::types::TaskStatus::new(TaskState::Completed),
406            kind: "status-update".to_string(),
407            r#final: true,
408        };
409        drop(state_clone.event_tx.send(final_status_event.clone()));
410
411        spawn_webhook_delivery(
412            state_clone.webhook_notifier.clone(),
413            state_clone.task_manager.clone(),
414            final_status_event.task_id().unwrap_or_default().to_string(),
415            final_status_event,
416        );
417    }));
418
419    Ok(Sse::new(Box::pin(stream)).keep_alive(
420        axum::response::sse::KeepAlive::new()
421            .interval(Duration::from_secs(15))
422            .text("keep-alive"),
423    ))
424}
425
426// ============================================================================
427// RPC Method Handlers
428// ============================================================================
429
430/// Handle message/send RPC method
431async fn handle_message_send(state: &A2aServerState, params: Option<Value>, _id: Value) -> A2aResult<Value> {
432    let params: MessageSendParams = serde_json::from_value(params.unwrap_or_default())
433        .map_err(|_e| A2aError::rpc(A2aErrorCode::InvalidParams, "Invalid message/send params"))?;
434
435    // Create or get task
436    let task_id = if let Some(task_id) = params.task_id {
437        task_id
438    } else {
439        let task = state.task_manager.create_task(params.context_id).await;
440        task.id.clone()
441    };
442
443    // Add message to history
444    drop(state.task_manager.add_message(&task_id, params.message).await?);
445
446    // Update status to working
447    let task = state.task_manager.update_status(&task_id, TaskState::Working, None).await?;
448
449    // Return task as response
450    Ok(serde_json::to_value(task)?)
451}
452
453/// Handle tasks/pushNotificationConfig/set RPC method
454async fn handle_push_config_set(state: &A2aServerState, params: Option<Value>, _id: Value) -> A2aResult<Value> {
455    let config: crate::rpc::TaskPushNotificationConfig = serde_json::from_value(params.unwrap_or_default())
456        .map_err(|_e| A2aError::rpc(A2aErrorCode::InvalidParams, "Invalid pushNotificationConfig/set params"))?;
457
458    state.task_manager.set_webhook_config(config).await?;
459
460    Ok(json!({ "success": true }))
461}
462
463/// Handle tasks/pushNotificationConfig/get RPC method
464async fn handle_push_config_get(state: &A2aServerState, params: Option<Value>, _id: Value) -> A2aResult<Value> {
465    let params: TaskIdParams = serde_json::from_value(params.unwrap_or_default())
466        .map_err(|_e| A2aError::rpc(A2aErrorCode::InvalidParams, "Invalid pushNotificationConfig/get params"))?;
467
468    let config = state.task_manager.get_webhook_config(&params.id).await;
469
470    Ok(serde_json::to_value(config)?)
471}
472
473/// Handle message/stream RPC method
474fn handle_message_stream<'a>(
475    state: &'a A2aServerState,
476    params: Option<Value>,
477    id: Value,
478) -> impl Future<Output = A2aResult<Value>> + 'a {
479    // Same as message_send for now, but would support streaming
480    handle_message_send(state, params, id)
481}
482
483/// Handle tasks/get RPC method
484async fn handle_tasks_get(state: &A2aServerState, params: Option<Value>, _id: Value) -> A2aResult<Value> {
485    let params: TaskQueryParams = serde_json::from_value(params.unwrap_or_default())
486        .map_err(|_e| A2aError::rpc(A2aErrorCode::InvalidParams, "Invalid tasks/get params"))?;
487
488    let task = state
489        .task_manager
490        .get_task_or_error_with_history(&params.id, params.history_length.unwrap_or_default() as usize)
491        .await?;
492
493    Ok(serde_json::to_value(task)?)
494}
495
496/// Handle tasks/list RPC method
497async fn handle_tasks_list(state: &A2aServerState, params: Option<Value>, _id: Value) -> A2aResult<Value> {
498    let params = match params {
499        Some(params) => serde_json::from_value(params)
500            .map_err(|_e| A2aError::rpc(A2aErrorCode::InvalidParams, "Invalid tasks/list params"))?,
501        None => ListTasksParams::default(),
502    };
503
504    let result = state.task_manager.list_tasks(params).await;
505
506    Ok(serde_json::to_value(result)?)
507}
508
509/// Handle tasks/cancel RPC method
510async fn handle_tasks_cancel(state: &A2aServerState, params: Option<Value>, _id: Value) -> A2aResult<Value> {
511    let params: TaskIdParams = serde_json::from_value(params.unwrap_or_default())
512        .map_err(|_e| A2aError::rpc(A2aErrorCode::InvalidParams, "Invalid tasks/cancel params"))?;
513
514    let task = state.task_manager.cancel_task(&params.id).await?;
515
516    Ok(serde_json::to_value(task)?)
517}
518
519// ============================================================================
520// Error Response Handler
521// ============================================================================
522
523/// A2A error response for Axum
524pub struct A2aErrorResponse {
525    response: Box<JsonRpcResponse>,
526    status_code: StatusCode,
527}
528
529impl A2aErrorResponse {
530    /// Create a new error response
531    fn new(error: JsonRpcError, id: Value, status_code: StatusCode) -> Self {
532        Self {
533            response: Box::new(JsonRpcResponse::error(error, id)),
534            status_code,
535        }
536    }
537
538    /// Create an invalid request error response
539    fn invalid_request(message: &str, id: Value) -> Self {
540        Self::new(JsonRpcError::invalid_request(message), id, StatusCode::BAD_REQUEST)
541    }
542
543    /// Create a method not found error response
544    fn method_not_found(method: &str, id: Value) -> Self {
545        Self::new(JsonRpcError::method_not_found(method), id, StatusCode::NOT_FOUND)
546    }
547
548    /// Create an error response from an A2aError
549    fn from_error(error: A2aError, id: Value) -> Self {
550        let code: i32 = error.code().into();
551        let message = error.to_string();
552        let status_code = match &error {
553            A2aError::RpcError { code, .. } => match code {
554                A2aErrorCode::InvalidRequest | A2aErrorCode::InvalidParams | A2aErrorCode::JsonParseError => {
555                    StatusCode::BAD_REQUEST
556                }
557                A2aErrorCode::MethodNotFound => StatusCode::NOT_FOUND,
558                _ => StatusCode::INTERNAL_SERVER_ERROR,
559            },
560            A2aError::TaskNotFound(_) => StatusCode::NOT_FOUND,
561            A2aError::TaskNotCancelable(_) => StatusCode::UNPROCESSABLE_ENTITY,
562            A2aError::InvalidStateTransition { .. } => StatusCode::UNPROCESSABLE_ENTITY,
563            _ => StatusCode::INTERNAL_SERVER_ERROR,
564        };
565
566        Self::new(JsonRpcError::new(code, message), id, status_code)
567    }
568}
569
570impl IntoResponse for A2aErrorResponse {
571    fn into_response(self) -> Response {
572        (self.status_code, Json(*self.response)).into_response()
573    }
574}
575
576// ============================================================================
577// Server Startup
578// ============================================================================
579
580/// Run the A2A server
581pub async fn run(state: A2aServerState, addr: SocketAddr) -> anyhow::Result<()> {
582    let listener = tokio::net::TcpListener::bind(addr).await?;
583    tracing::info!("A2A server listening on {}", addr);
584    axum::serve(listener, create_router(state))
585        .with_graceful_shutdown(crate::shutdown_signal_logged("A2A"))
586        .await?;
587    Ok(())
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    #[test]
595    fn test_server_state_creation() {
596        let state = A2aServerState::vtcode_default("http://localhost:8080");
597        assert_eq!(state.agent_card.name, "vtcode-agent");
598    }
599
600    #[test]
601    fn test_error_response_task_not_found() {
602        use serde_json::json;
603        let err_response = A2aErrorResponse::from_error(A2aError::TaskNotFound("test-id".to_string()), json!(1));
604        assert_eq!(err_response.status_code, StatusCode::NOT_FOUND);
605    }
606
607    #[test]
608    fn test_error_response_task_not_cancelable() {
609        use serde_json::json;
610        let err = A2aError::TaskNotCancelable("Cannot cancel completed task".to_string());
611        let err_response = A2aErrorResponse::from_error(err, json!(1));
612        assert_eq!(err_response.status_code, StatusCode::UNPROCESSABLE_ENTITY);
613    }
614
615    #[test]
616    fn test_error_response_invalid_request() {
617        use serde_json::json;
618        let err_response = A2aErrorResponse::invalid_request("Invalid JSON", json!(1));
619        assert_eq!(err_response.status_code, StatusCode::BAD_REQUEST);
620    }
621
622    #[tokio::test]
623    async fn test_server_state_with_broadcast() {
624        let state = A2aServerState::vtcode_default("http://localhost:8080");
625
626        // Verify broadcast channel works
627        let mut rx = state.event_tx.subscribe();
628
629        // Send a test event
630        let test_event = StreamingEvent::Message {
631            message: super::super::types::Message::agent_text("Test"),
632            context_id: Some("test".to_string()),
633            kind: "streaming-response".to_string(),
634            r#final: false,
635        };
636
637        let _ignored = state.event_tx.send(test_event.clone()).expect("send event");
638
639        // Receive the event
640        let received = rx.recv().await.expect("receive event");
641        assert!(!received.is_final());
642    }
643
644    #[test]
645    fn test_server_state_debug_redacts_auth_token() {
646        let state = A2aServerState::new_with_auth_token(
647            TaskManager::new(),
648            AgentCard::vtcode_default("http://localhost:8080"),
649            "test-token",
650        )
651        .expect("valid auth token");
652
653        let debug = format!("{state:?}");
654        assert!(!debug.contains("test-token"));
655        assert!(debug.contains("REDACTED"));
656    }
657
658    #[test]
659    fn test_server_state_rejects_invalid_auth_token() {
660        let result = A2aServerState::new_with_auth_token(
661            TaskManager::new(),
662            AgentCard::vtcode_default("http://localhost:8080"),
663            " ",
664        );
665
666        assert!(result.is_err());
667    }
668
669    #[tokio::test]
670    async fn test_agent_card_is_public_and_advertises_authentication() {
671        use axum::{body::Body, http::Request};
672        use tower::ServiceExt;
673
674        let state = A2aServerState::new_with_auth_token(
675            TaskManager::new(),
676            AgentCard::vtcode_default("http://localhost:8080"),
677            "test-token",
678        )
679        .expect("valid auth token");
680        let app = create_router(state);
681
682        let response = app
683            .oneshot(
684                Request::builder()
685                    .uri("/.well-known/agent-card.json")
686                    .body(Body::empty())
687                    .expect("build request"),
688            )
689            .await
690            .expect("receive response");
691
692        assert_eq!(response.status(), StatusCode::OK);
693        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.expect("read body");
694        let card: Value = serde_json::from_slice(&body).expect("parse card");
695        assert_eq!(card["securitySchemes"]["bearerAuth"]["scheme"], "bearer");
696        assert_eq!(card["security"][0]["bearerAuth"], json!([]));
697    }
698
699    #[tokio::test]
700    async fn test_rpc_requires_bearer_auth_before_json_parsing() {
701        use axum::{body::Body, http::Request};
702        use tower::ServiceExt;
703
704        let state = A2aServerState::new_with_auth_token(
705            TaskManager::new(),
706            AgentCard::vtcode_default("http://localhost:8080"),
707            "test-token",
708        )
709        .expect("valid auth token");
710        let token = state.auth_token().to_string();
711        let app = create_router(state);
712
713        let unauthorized = app
714            .clone()
715            .oneshot(
716                Request::builder()
717                    .method("POST")
718                    .uri("/a2a")
719                    .header("content-type", "application/json")
720                    .body(Body::from("not-json"))
721                    .expect("build request"),
722            )
723            .await
724            .expect("receive response");
725        assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED);
726        assert_eq!(unauthorized.headers()[WWW_AUTHENTICATE], "Bearer");
727
728        let wrong_token = app
729            .clone()
730            .oneshot(
731                Request::builder()
732                    .method("POST")
733                    .uri("/a2a")
734                    .header("content-type", "application/json")
735                    .header(AUTHORIZATION, "Bearer wrong-token")
736                    .body(Body::from("{}"))
737                    .expect("build request"),
738            )
739            .await
740            .expect("receive response");
741        assert_eq!(wrong_token.status(), StatusCode::UNAUTHORIZED);
742
743        let stream_unauthorized = app
744            .clone()
745            .oneshot(
746                Request::builder()
747                    .method("POST")
748                    .uri("/a2a/stream")
749                    .header("content-type", "application/json")
750                    .body(Body::from("not-json"))
751                    .expect("build request"),
752            )
753            .await
754            .expect("receive response");
755        assert_eq!(stream_unauthorized.status(), StatusCode::UNAUTHORIZED);
756
757        let authenticated = app
758            .oneshot(
759                Request::builder()
760                    .method("POST")
761                    .uri("/a2a")
762                    .header("content-type", "application/json")
763                    .header(AUTHORIZATION, format!("Bearer {token}"))
764                    .body(Body::from(r#"{"jsonrpc":"2.0","method":"unknown","id":1}"#))
765                    .expect("build request"),
766            )
767            .await
768            .expect("receive response");
769        assert_eq!(authenticated.status(), StatusCode::NOT_FOUND);
770    }
771
772    #[tokio::test]
773    async fn test_duplicate_authorization_headers_are_rejected() {
774        use axum::{body::Body, http::Request};
775        use tower::ServiceExt;
776
777        let state = A2aServerState::new_with_auth_token(
778            TaskManager::new(),
779            AgentCard::vtcode_default("http://localhost:8080"),
780            "test-token",
781        )
782        .expect("valid auth token");
783        let app = create_router(state);
784        let mut request = Request::builder()
785            .method("POST")
786            .uri("/a2a")
787            .header("content-type", "application/json")
788            .body(Body::from("{}"))
789            .expect("build request");
790        let _ = request
791            .headers_mut()
792            .append(AUTHORIZATION, HeaderValue::from_static("Bearer test-token"));
793        let _ = request
794            .headers_mut()
795            .append(AUTHORIZATION, HeaderValue::from_static("Bearer test-token"));
796
797        let response = app.oneshot(request).await.expect("receive response");
798        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
799    }
800
801    #[tokio::test]
802    async fn test_rpc_does_not_allow_cross_origin_cors_access() {
803        use axum::{body::Body, http::Request};
804        use tower::ServiceExt;
805
806        let state = A2aServerState::new_with_auth_token(
807            TaskManager::new(),
808            AgentCard::vtcode_default("http://localhost:8080"),
809            "test-token",
810        )
811        .expect("valid auth token");
812        let app = create_router(state);
813
814        let response = app
815            .oneshot(
816                Request::builder()
817                    .method("POST")
818                    .uri("/a2a")
819                    .header("origin", "https://attacker.example")
820                    .body(Body::from("{}"))
821                    .expect("build request"),
822            )
823            .await
824            .expect("receive response");
825
826        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
827        assert!(response.headers().get("access-control-allow-origin").is_none());
828    }
829
830    #[tokio::test]
831    async fn test_task_history_limits_are_applied_by_rpc_handlers() {
832        use axum::{body::Body, http::Request};
833        use tower::ServiceExt;
834
835        let task_manager = TaskManager::new();
836        let task = task_manager.create_task(None).await;
837        drop(
838            task_manager
839                .add_message(&task.id, crate::types::Message::user_text("private message"))
840                .await
841                .expect("add message"),
842        );
843        let state = A2aServerState::new_with_auth_token(
844            task_manager,
845            AgentCard::vtcode_default("http://localhost:8080"),
846            "test-token",
847        )
848        .expect("valid auth token");
849        let app = create_router(state);
850
851        let request_body = |params| {
852            serde_json::to_vec(&json!({
853                "jsonrpc": "2.0",
854                "method": METHOD_TASKS_GET,
855                "params": params,
856                "id": 1,
857            }))
858            .expect("serialize request")
859        };
860        let response = app
861            .clone()
862            .oneshot(
863                Request::builder()
864                    .method("POST")
865                    .uri("/a2a")
866                    .header("content-type", "application/json")
867                    .header(AUTHORIZATION, "Bearer test-token")
868                    .body(Body::from(request_body(json!({"id": task.id}))))
869                    .expect("build request"),
870            )
871            .await
872            .expect("receive response");
873        assert_eq!(response.status(), StatusCode::OK);
874        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.expect("read body");
875        let body: Value = serde_json::from_slice(&body).expect("parse response");
876        assert!(body["result"].get("history").is_none());
877
878        let response = app
879            .clone()
880            .oneshot(
881                Request::builder()
882                    .method("POST")
883                    .uri("/a2a")
884                    .header("content-type", "application/json")
885                    .header(AUTHORIZATION, "Bearer test-token")
886                    .body(Body::from(request_body(json!({"id": task.id, "historyLength": 1}))))
887                    .expect("build request"),
888            )
889            .await
890            .expect("receive response");
891        assert_eq!(response.status(), StatusCode::OK);
892        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.expect("read body");
893        let body: Value = serde_json::from_slice(&body).expect("parse response");
894        assert_eq!(body["result"]["history"].as_array().map(Vec::len), Some(1));
895    }
896
897    #[tokio::test]
898    async fn test_malformed_task_list_params_are_rejected() {
899        use axum::{body::Body, http::Request};
900        use tower::ServiceExt;
901
902        let state = A2aServerState::new_with_auth_token(
903            TaskManager::new(),
904            AgentCard::vtcode_default("http://localhost:8080"),
905            "test-token",
906        )
907        .expect("valid auth token");
908        let app = create_router(state);
909        let response = app
910            .oneshot(
911                Request::builder()
912                    .method("POST")
913                    .uri("/a2a")
914                    .header("content-type", "application/json")
915                    .header(AUTHORIZATION, "Bearer test-token")
916                    .body(Body::from(r#"{"jsonrpc":"2.0","method":"tasks/list","params":[],"id":1}"#))
917                    .expect("build request"),
918            )
919            .await
920            .expect("receive response");
921
922        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
923    }
924}