Skip to main content

adk_server/a2a/v1/
push.rs

1//! A2A v1.0.0 push notification sender.
2//!
3//! Defines the [`PushNotificationSender`] trait for delivering task updates
4//! to client-registered webhook endpoints. Includes [`HttpPushNotificationSender`]
5//! with retry logic and SSRF validation, and [`NoOpPushNotificationSender`] for
6//! development and testing.
7
8use 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
20/// Maximum number of retry attempts for webhook delivery.
21const MAX_RETRIES: u32 = 3;
22
23/// Delay in seconds for each retry attempt (exponential backoff).
24const RETRY_DELAYS: &[u64] = &[1, 2, 4];
25
26/// Upper bound on one webhook delivery attempt, from connect to response.
27const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10);
28
29/// Upper bound on establishing the connection for one delivery attempt.
30const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
31
32/// A client under `policy` that follows no redirect and bounds each attempt.
33fn 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
44/// The client of a sender.
45enum PushClient {
46    /// [`HttpPushNotificationSender::new`]'s: public addresses only, checked when it connects
47    /// as well as on the URL, or why it could not be built.
48    Guarded(Result<adk_core::egress::GuardedClient, String>),
49    /// A caller's own, from [`HttpPushNotificationSender::with_client`].
50    Custom(reqwest::Client),
51}
52
53/// Async trait for delivering push notifications to webhook endpoints.
54///
55/// Implementations must be `Send + Sync` for use across async boundaries.
56#[async_trait]
57pub trait PushNotificationSender: Send + Sync {
58    /// Delivers a task status update to the configured webhook.
59    async fn send_status_update(
60        &self,
61        url: &str,
62        event: &TaskStatusUpdateEvent,
63        config: &TaskPushNotificationConfig,
64    ) -> Result<(), A2aError>;
65
66    /// Delivers a task artifact update to the configured webhook.
67    async fn send_artifact_update(
68        &self,
69        url: &str,
70        event: &TaskArtifactUpdateEvent,
71        config: &TaskPushNotificationConfig,
72    ) -> Result<(), A2aError>;
73
74    /// Delivers one of a task's updates to `config`, as the [`StreamResponse`] a streaming
75    /// client receives (`{"statusUpdate": …}` or `{"artifactUpdate": …}`).
76    ///
77    /// The default implementation calls [`send_status_update`](Self::send_status_update) or
78    /// [`send_artifact_update`](Self::send_artifact_update) with the bare event, so a
79    /// sender written for those keeps working.
80    ///
81    /// # Errors
82    ///
83    /// Returns an error if the update could not be delivered.
84    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
101/// No-op push notification sender for development and testing.
102///
103/// All delivery attempts succeed immediately without sending any HTTP requests.
104/// The `Authorization` header for a push config's authentication: `Bearer` or `Basic`
105/// with its credentials, as A2A push senders send it. No header for another scheme, or
106/// without credentials.
107fn 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
142/// HTTP-based push notification sender with retry and SSRF validation.
143///
144/// POSTs JSON payloads to webhook URLs. Retries up to 3 times with exponential backoff
145/// (1s, 2s, 4s) on failure. Validates webhook URLs with [`validate_webhook_url`] before
146/// every delivery (SSRF prevention), and [`new`](Self::new)'s client checks every address a
147/// webhook's host resolves to when it connects, so a name pointed at an internal address is
148/// refused too.
149pub struct HttpPushNotificationSender {
150    client: PushClient,
151}
152
153impl HttpPushNotificationSender {
154    /// Creates a new sender whose client reaches public addresses only — the URL's and every
155    /// address its host resolves to — follows no redirect, ignores proxy settings, gives up
156    /// on an attempt after 10 seconds and on a connection after 5 seconds. When that client
157    /// cannot be built, every delivery fails; no unguarded client is used in its place.
158    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    /// Creates a new sender with a custom `reqwest::Client`.
164    ///
165    /// The client should disable redirects (`reqwest::redirect::Policy::none()`)
166    /// and set a timeout: URL validation covers the registered URL only, so a
167    /// followed redirect, or a host name resolving to an internal address, can reach an
168    /// address the validation would have refused. [`new`](Self::new)'s client checks both.
169    pub fn with_client(client: reqwest::Client) -> Self {
170        Self { client: PushClient::Custom(client) }
171    }
172
173    /// Sends a JSON payload to the given URL with retry logic.
174    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            // Add notification token if configured
199            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
273/// Validates a webhook URL to prevent SSRF attacks.
274///
275/// Rejects URLs whose host is a literal address of any class but
276/// [`AddressClass::Public`](adk_core::egress::AddressClass::Public) — loopback, private,
277/// link-local, cloud metadata, reserved, and IPv6 forms embedding such an IPv4 address — or a
278/// `localhost` name.
279///
280/// The URL parser normalizes alternative IPv4 spellings (`0x7f.1`, `2130706433`)
281/// before the check. Host names other than `localhost` are not resolved here;
282/// put the sender behind an egress proxy when webhook hosts are untrusted.
283///
284/// # Example
285///
286/// ```rust
287/// use adk_server::a2a::v1::push::validate_webhook_url;
288///
289/// assert!(validate_webhook_url("https://hooks.example.com/a2a").is_ok());
290/// assert!(validate_webhook_url("http://169.254.169.254/latest/meta-data").is_err());
291/// ```
292///
293/// # Errors
294///
295/// Returns `A2aError::InvalidParams` for an unparseable URL, a URL without a host,
296/// or a host in one of the ranges above.
297pub 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    // IPv6 hosts are serialized in brackets, e.g. `[::1]`.
306    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        // 172.15.x.x is NOT private
386        assert!(validate_webhook_url("https://172.15.0.1/webhook").is_ok());
387        // 172.32.x.x is NOT private
388        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        // 192.169.x.x is NOT private
396        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    /// Every form here reaches a host-local, internal, or metadata address.
426    #[test]
427    fn test_validate_rejects_every_non_public_form() {
428        let blocked = [
429            // 0.0.0.0/8 — routes to the local host on most stacks
430            "http://0.0.0.0/hook",
431            "http://0.1.2.3/hook",
432            // 169.254.0.0/16 — link-local, including cloud metadata
433            "http://169.254.169.254/latest/meta-data",
434            "http://169.254.0.1/hook",
435            // 100.64.0.0/10 — carrier-grade NAT shared space
436            "http://100.64.0.1/hook",
437            "http://100.127.255.254/hook",
438            // Multicast and broadcast
439            "http://224.0.0.1/hook",
440            "http://255.255.255.255/hook",
441            // Alternative IPv4 spellings the URL parser normalizes
442            "http://2130706433/hook",
443            "http://0x7f.1/hook",
444            "http://0177.0.0.1/hook",
445            // IPv6 unspecified, unique-local (fc00::/7), link-local (fe80::/10), site-local
446            "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            // IPv4-mapped, IPv4-compatible, and NAT64 forms of blocked IPv4 ranges
454            "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            // localhost names
461            "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        // The redirect target stands in for an internal service; nothing may connect to it.
492        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        // The sender's client configuration, with loopback admitted to reach the test server.
510        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    // ── Push notification auth header tests ───────────────────────────────
533
534    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}