1use std::net::IpAddr;
9use std::time::Duration;
10
11use adk_core::egress::is_non_public;
12use async_trait::async_trait;
13use serde::Serialize;
14
15use a2a_protocol_types::TaskPushNotificationConfig;
16use a2a_protocol_types::events::{StreamResponse, TaskArtifactUpdateEvent, TaskStatusUpdateEvent};
17
18use super::error::A2aError;
19
20const MAX_RETRIES: u32 = 3;
22
23const RETRY_DELAYS: &[u64] = &[1, 2, 4];
25
26const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10);
28
29const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
31
32fn guarded_client(
34 policy: adk_core::egress::EgressPolicy,
35) -> Result<adk_core::egress::GuardedClient, String> {
36 adk_core::egress::GuardedClient::builder(policy)
37 .timeout(DELIVERY_TIMEOUT)
38 .connect_timeout(CONNECT_TIMEOUT)
39 .redirects(0)
40 .build()
41 .map_err(|error| error.to_string())
42}
43
44enum PushClient {
46 Guarded(Result<adk_core::egress::GuardedClient, String>),
49 Custom(reqwest::Client),
51}
52
53#[async_trait]
57pub trait PushNotificationSender: Send + Sync {
58 async fn send_status_update(
60 &self,
61 url: &str,
62 event: &TaskStatusUpdateEvent,
63 config: &TaskPushNotificationConfig,
64 ) -> Result<(), A2aError>;
65
66 async fn send_artifact_update(
68 &self,
69 url: &str,
70 event: &TaskArtifactUpdateEvent,
71 config: &TaskPushNotificationConfig,
72 ) -> Result<(), A2aError>;
73
74 async fn send_update(
85 &self,
86 update: &StreamResponse,
87 config: &TaskPushNotificationConfig,
88 ) -> Result<(), A2aError> {
89 match update {
90 StreamResponse::StatusUpdate(event) => {
91 self.send_status_update(&config.url, event, config).await
92 }
93 StreamResponse::ArtifactUpdate(event) => {
94 self.send_artifact_update(&config.url, event, config).await
95 }
96 _ => Ok(()),
97 }
98 }
99}
100
101fn authorization_header(auth: &a2a_protocol_types::push::AuthenticationInfo) -> Option<String> {
108 let credentials = auth.credentials.as_deref()?;
109 let scheme = if auth.scheme.eq_ignore_ascii_case("bearer") {
110 "Bearer"
111 } else if auth.scheme.eq_ignore_ascii_case("basic") {
112 "Basic"
113 } else {
114 return None;
115 };
116 Some(format!("{scheme} {credentials}"))
117}
118
119pub struct NoOpPushNotificationSender;
120
121#[async_trait]
122impl PushNotificationSender for NoOpPushNotificationSender {
123 async fn send_status_update(
124 &self,
125 _url: &str,
126 _event: &TaskStatusUpdateEvent,
127 _config: &TaskPushNotificationConfig,
128 ) -> Result<(), A2aError> {
129 Ok(())
130 }
131
132 async fn send_artifact_update(
133 &self,
134 _url: &str,
135 _event: &TaskArtifactUpdateEvent,
136 _config: &TaskPushNotificationConfig,
137 ) -> Result<(), A2aError> {
138 Ok(())
139 }
140}
141
142pub struct HttpPushNotificationSender {
150 client: PushClient,
151}
152
153impl HttpPushNotificationSender {
154 pub fn new() -> Self {
159 let public = adk_core::egress::EgressPolicy::public_only().with_plain_http();
160 Self { client: PushClient::Guarded(guarded_client(public)) }
161 }
162
163 pub fn with_client(client: reqwest::Client) -> Self {
170 Self { client: PushClient::Custom(client) }
171 }
172
173 async fn send_with_retry(
175 &self,
176 url: &str,
177 body: &impl Serialize,
178 config: &TaskPushNotificationConfig,
179 ) -> Result<(), A2aError> {
180 validate_webhook_url(url)?;
181
182 for attempt in 0..=MAX_RETRIES {
183 let request = match &self.client {
184 PushClient::Guarded(Ok(client)) => client.post(url).map_err(|denial| {
185 A2aError::InvalidParams { message: format!("webhook URL refused: {denial}") }
186 })?,
187 PushClient::Guarded(Err(reason)) => {
188 return Err(A2aError::PushDeliveryFailed { message: reason.clone() });
189 }
190 PushClient::Custom(client) => client.post(url),
191 };
192 let mut request = request.json(body);
193
194 if let Some(value) = config.authentication.as_ref().and_then(authorization_header) {
195 request = request.header("Authorization", value);
196 }
197
198 if let Some(ref token) = config.token {
200 request = request.header("a2a-notification-token", token);
201 }
202
203 match request.send().await {
204 Ok(resp) if resp.status().is_success() => return Ok(()),
205 Ok(resp) => {
206 tracing::warn!(
207 attempt,
208 status = %resp.status(),
209 url,
210 "push notification delivery received non-success status"
211 );
212 }
213 Err(e) => {
214 tracing::warn!(
215 attempt,
216 error = %e,
217 url,
218 "push notification delivery request failed"
219 );
220 }
221 }
222 if attempt < MAX_RETRIES {
223 tokio::time::sleep(Duration::from_secs(RETRY_DELAYS[attempt as usize])).await;
224 }
225 }
226
227 tracing::error!(
228 retries = MAX_RETRIES,
229 url,
230 "push notification delivery failed after all retries"
231 );
232 Err(A2aError::PushDeliveryFailed {
233 message: format!("delivery failed after {MAX_RETRIES} retries"),
234 })
235 }
236}
237
238impl Default for HttpPushNotificationSender {
239 fn default() -> Self {
240 Self::new()
241 }
242}
243
244#[async_trait]
245impl PushNotificationSender for HttpPushNotificationSender {
246 async fn send_status_update(
247 &self,
248 url: &str,
249 event: &TaskStatusUpdateEvent,
250 config: &TaskPushNotificationConfig,
251 ) -> Result<(), A2aError> {
252 self.send_with_retry(url, event, config).await
253 }
254
255 async fn send_artifact_update(
256 &self,
257 url: &str,
258 event: &TaskArtifactUpdateEvent,
259 config: &TaskPushNotificationConfig,
260 ) -> Result<(), A2aError> {
261 self.send_with_retry(url, event, config).await
262 }
263
264 async fn send_update(
265 &self,
266 update: &StreamResponse,
267 config: &TaskPushNotificationConfig,
268 ) -> Result<(), A2aError> {
269 self.send_with_retry(&config.url, update, config).await
270 }
271}
272
273pub fn validate_webhook_url(url: &str) -> Result<(), A2aError> {
298 let parsed = reqwest::Url::parse(url)
299 .map_err(|e| A2aError::InvalidParams { message: format!("invalid webhook URL: {e}") })?;
300
301 let host = parsed.host_str().ok_or_else(|| A2aError::InvalidParams {
302 message: "webhook URL has no host".to_string(),
303 })?;
304
305 let unbracketed = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
307 if let Ok(ip) = unbracketed.parse::<IpAddr>() {
308 if is_non_public(ip) {
309 return Err(A2aError::InvalidParams {
310 message: format!("webhook URL must not target a non-public address: {ip}"),
311 });
312 }
313 return Ok(());
314 }
315
316 let name = host.trim_end_matches('.').to_ascii_lowercase();
317 if name == "localhost" || name.ends_with(".localhost") {
318 return Err(A2aError::InvalidParams {
319 message: "webhook URL must not target localhost".to_string(),
320 });
321 }
322
323 Ok(())
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329 use a2a_protocol_types::{AuthenticationInfo, TaskPushNotificationConfig};
330
331 #[test]
332 fn authorization_follows_the_configs_scheme() {
333 let auth = |scheme: &str, credentials: Option<&str>| AuthenticationInfo {
334 scheme: scheme.to_string(),
335 credentials: credentials.map(str::to_owned),
336 };
337 assert_eq!(authorization_header(&auth("Bearer", Some("t"))).as_deref(), Some("Bearer t"));
338 assert_eq!(
339 authorization_header(&auth("basic", Some("dTpw"))).as_deref(),
340 Some("Basic dTpw")
341 );
342 assert_eq!(authorization_header(&auth("ApiKey", Some("k"))), None);
343 assert_eq!(authorization_header(&auth("Bearer", None)), None);
344 }
345
346 #[test]
347 fn a_pushed_update_is_the_stream_response_a_streaming_client_gets() {
348 let event = TaskStatusUpdateEvent {
349 task_id: a2a_protocol_types::TaskId::new("t"),
350 context_id: a2a_protocol_types::ContextId::new("c"),
351 status: a2a_protocol_types::TaskStatus::with_timestamp(
352 a2a_protocol_types::TaskState::Working,
353 ),
354 metadata: None,
355 };
356 let body = serde_json::to_value(StreamResponse::StatusUpdate(event)).unwrap();
357 assert!(body.get("statusUpdate").is_some(), "{body}");
358 }
359
360 #[test]
361 fn test_validate_public_ip_accepted() {
362 assert!(validate_webhook_url("https://8.8.8.8/webhook").is_ok());
363 assert!(validate_webhook_url("https://1.2.3.4:8080/hook").is_ok());
364 assert!(validate_webhook_url("https://203.0.113.1/callback").is_ok());
365 }
366
367 #[test]
368 fn test_validate_public_domain_accepted() {
369 assert!(validate_webhook_url("https://example.com/webhook").is_ok());
370 assert!(validate_webhook_url("https://hooks.slack.com/services/abc").is_ok());
371 assert!(validate_webhook_url("https://api.github.com/hooks").is_ok());
372 }
373
374 #[test]
375 fn test_validate_private_10_rejected() {
376 assert!(validate_webhook_url("https://10.0.0.1/webhook").is_err());
377 assert!(validate_webhook_url("https://10.255.255.255/webhook").is_err());
378 assert!(validate_webhook_url("https://10.1.2.3:8080/hook").is_err());
379 }
380
381 #[test]
382 fn test_validate_private_172_rejected() {
383 assert!(validate_webhook_url("https://172.16.0.1/webhook").is_err());
384 assert!(validate_webhook_url("https://172.31.255.255/webhook").is_err());
385 assert!(validate_webhook_url("https://172.15.0.1/webhook").is_ok());
387 assert!(validate_webhook_url("https://172.32.0.1/webhook").is_ok());
389 }
390
391 #[test]
392 fn test_validate_private_192_168_rejected() {
393 assert!(validate_webhook_url("https://192.168.0.1/webhook").is_err());
394 assert!(validate_webhook_url("https://192.168.255.255/webhook").is_err());
395 assert!(validate_webhook_url("https://192.169.0.1/webhook").is_ok());
397 }
398
399 #[test]
400 fn test_validate_loopback_ipv4_rejected() {
401 assert!(validate_webhook_url("https://127.0.0.1/webhook").is_err());
402 assert!(validate_webhook_url("https://127.0.0.2/webhook").is_err());
403 assert!(validate_webhook_url("https://127.255.255.255/webhook").is_err());
404 }
405
406 #[test]
407 fn test_validate_loopback_ipv6_rejected() {
408 assert!(validate_webhook_url("https://[::1]/webhook").is_err());
409 }
410
411 #[test]
412 fn test_validate_localhost_rejected() {
413 assert!(validate_webhook_url("https://localhost/webhook").is_err());
414 assert!(validate_webhook_url("https://localhost:8080/webhook").is_err());
415 assert!(validate_webhook_url("https://LOCALHOST/webhook").is_err());
416 }
417
418 #[test]
419 fn test_validate_invalid_url_rejected() {
420 assert!(validate_webhook_url("not-a-url").is_err());
421 assert!(validate_webhook_url("").is_err());
422 assert!(validate_webhook_url("://missing-scheme").is_err());
423 }
424
425 #[test]
427 fn test_validate_rejects_every_non_public_form() {
428 let blocked = [
429 "http://0.0.0.0/hook",
431 "http://0.1.2.3/hook",
432 "http://169.254.169.254/latest/meta-data",
434 "http://169.254.0.1/hook",
435 "http://100.64.0.1/hook",
437 "http://100.127.255.254/hook",
438 "http://224.0.0.1/hook",
440 "http://255.255.255.255/hook",
441 "http://2130706433/hook",
443 "http://0x7f.1/hook",
444 "http://0177.0.0.1/hook",
445 "http://[::]/hook",
447 "http://[fc00::1]/hook",
448 "http://[fd12:3456:789a::1]/hook",
449 "http://[fe80::1]/hook",
450 "http://[febf::1]/hook",
451 "http://[fec0::1]/hook",
452 "http://[ff02::1]/hook",
453 "http://[::ffff:127.0.0.1]/hook",
455 "http://[::ffff:169.254.169.254]/hook",
456 "http://[::ffff:10.0.0.1]/hook",
457 "http://[::ffff:7f00:1]/hook",
458 "http://[::127.0.0.1]/hook",
459 "http://[64:ff9b::a9fe:a9fe]/hook",
460 "http://localhost./hook",
462 "http://api.localhost/hook",
463 ];
464 for url in blocked {
465 assert!(validate_webhook_url(url).is_err(), "{url} must be rejected");
466 }
467 }
468
469 #[test]
470 fn test_validate_accepts_public_neighbours_of_blocked_ranges() {
471 let allowed = [
472 "http://100.63.255.255/hook",
473 "http://100.128.0.1/hook",
474 "http://169.253.0.1/hook",
475 "http://1.0.0.1/hook",
476 "http://[2001:4860:4860::8888]/hook",
477 "http://[::ffff:8.8.8.8]/hook",
478 "http://[64:ff9b::808:808]/hook",
479 "http://[fbff::1]/hook",
480 "https://notlocalhost.example/hook",
481 ];
482 for url in allowed {
483 assert!(validate_webhook_url(url).is_ok(), "{url} must be accepted");
484 }
485 }
486
487 #[tokio::test]
488 async fn test_push_client_does_not_follow_redirects() {
489 use std::io::{Read, Write};
490
491 let target = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
493 target.set_nonblocking(true).unwrap();
494 let target_addr = target.local_addr().unwrap();
495
496 let redirector = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
497 let redirector_addr = redirector.local_addr().unwrap();
498 let server = std::thread::spawn(move || {
499 let (mut stream, _) = redirector.accept().unwrap();
500 let mut request = [0u8; 4096];
501 let _ = stream.read(&mut request);
502 let response = format!(
503 "HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{target_addr}/internal\r\n\
504 Content-Length: 0\r\nConnection: close\r\n\r\n"
505 );
506 stream.write_all(response.as_bytes()).unwrap();
507 });
508
509 let client =
511 guarded_client(adk_core::egress::EgressPolicy::allow_private_networks()).unwrap();
512 let response = tokio::time::timeout(
513 Duration::from_secs(5),
514 client
515 .post(&format!("http://{redirector_addr}/hook"))
516 .unwrap()
517 .json(&serde_json::json!({}))
518 .send(),
519 )
520 .await
521 .expect("the redirect must not be followed to a target that never answers")
522 .unwrap();
523 server.join().unwrap();
524
525 assert_eq!(response.status(), reqwest::StatusCode::TEMPORARY_REDIRECT);
526 assert!(
527 matches!(target.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock),
528 "the redirect target must never be contacted"
529 );
530 }
531
532 fn make_status_event() -> TaskStatusUpdateEvent {
535 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
536 TaskStatusUpdateEvent {
537 task_id: TaskId("task-1".to_string()),
538 context_id: ContextId("ctx-1".to_string()),
539 status: TaskStatus::new(TaskState::Working),
540 metadata: None,
541 }
542 }
543
544 fn make_artifact_event() -> TaskArtifactUpdateEvent {
545 use a2a_protocol_types::artifact::{Artifact, ArtifactId};
546 use a2a_protocol_types::task::{ContextId, TaskId};
547 TaskArtifactUpdateEvent {
548 task_id: TaskId("task-1".to_string()),
549 context_id: ContextId("ctx-1".to_string()),
550 artifact: Artifact {
551 id: ArtifactId::new("art-1"),
552 name: None,
553 description: None,
554 parts: vec![],
555 metadata: None,
556 extensions: None,
557 },
558 metadata: None,
559 append: None,
560 last_chunk: None,
561 }
562 }
563
564 #[tokio::test]
565 async fn test_noop_sender_accepts_config_with_neither() {
566 let sender = NoOpPushNotificationSender;
567 let config = TaskPushNotificationConfig::new("task-1", "https://example.com/hook");
568 let event = make_status_event();
569 assert!(
570 sender.send_status_update("https://example.com/hook", &event, &config).await.is_ok()
571 );
572 }
573
574 #[tokio::test]
575 async fn test_noop_sender_accepts_config_with_bearer_only() {
576 let sender = NoOpPushNotificationSender;
577 let mut config = TaskPushNotificationConfig::new("task-1", "https://example.com/hook");
578 config.authentication = Some(AuthenticationInfo {
579 scheme: "bearer".to_string(),
580 credentials: Some("my-token".to_string()),
581 });
582 let event = make_status_event();
583 assert!(
584 sender.send_status_update("https://example.com/hook", &event, &config).await.is_ok()
585 );
586 }
587
588 #[tokio::test]
589 async fn test_noop_sender_accepts_config_with_token_only() {
590 let sender = NoOpPushNotificationSender;
591 let mut config = TaskPushNotificationConfig::new("task-1", "https://example.com/hook");
592 config.token = Some("notification-secret".to_string());
593 let event = make_artifact_event();
594 assert!(
595 sender.send_artifact_update("https://example.com/hook", &event, &config).await.is_ok()
596 );
597 }
598
599 #[tokio::test]
600 async fn test_noop_sender_accepts_config_with_both() {
601 let sender = NoOpPushNotificationSender;
602 let mut config = TaskPushNotificationConfig::new("task-1", "https://example.com/hook");
603 config.authentication = Some(AuthenticationInfo {
604 scheme: "bearer".to_string(),
605 credentials: Some("my-token".to_string()),
606 });
607 config.token = Some("notification-secret".to_string());
608 let event = make_status_event();
609 assert!(
610 sender.send_status_update("https://example.com/hook", &event, &config).await.is_ok()
611 );
612 }
613}