Skip to main content

a2a_server/push/
sender.rs

1// Copyright AGNTCY Contributors (https://github.com/agntcy)
2// Copyright A2A Contributors (https://github.com/a2aproject)
3// SPDX-License-Identifier: Apache-2.0
4use a2a::*;
5use reqwest::dns::{Addrs, Name, Resolve, Resolving};
6use std::net::SocketAddr;
7use std::sync::Arc;
8use std::time::Duration;
9
10/// HTTP push notification sender.
11///
12/// Sends A2A streaming events to a push notification endpoint over HTTP POST.
13pub struct HttpPushSender {
14    client: reqwest::Client,
15    fail_on_error: bool,
16    validate_urls: bool,
17}
18
19/// Configuration for [`HttpPushSender`].
20pub struct HttpPushSenderConfig {
21    /// HTTP request timeout (default: 30s).
22    pub timeout: Duration,
23    /// If true, push sending errors abort execution.
24    pub fail_on_error: bool,
25    /// If true (default), guard push URLs against SSRF. A string pre-check
26    /// (scheme must be http/https; host must not be a loopback, private,
27    /// link-local, multicast, unspecified, or cloud-metadata literal) fails
28    /// before any network activity. A connect-time resolver then drops any
29    /// resolved address in those ranges before dialing, so a hostname cannot
30    /// reach a blocked address through DNS (split-horizon, attacker-controlled
31    /// records, or rebinding). Redirects are re-screened per hop with the same
32    /// string check, and the sender uses no system proxy, since either path
33    /// would otherwise reach an address the guard never saw. Disable only when
34    /// pushing to local webhooks in trusted test environments; that turns off
35    /// the whole guard.
36    pub validate_urls: bool,
37}
38
39impl Default for HttpPushSenderConfig {
40    fn default() -> Self {
41        HttpPushSenderConfig {
42            timeout: Duration::from_secs(30),
43            fail_on_error: false,
44            validate_urls: true,
45        }
46    }
47}
48
49impl HttpPushSender {
50    pub fn new(config: Option<HttpPushSenderConfig>) -> Self {
51        let config = config.unwrap_or_default();
52        // When URL validation is on, the guard needs three things reqwest does
53        // not do by default, because each one is a way a request reaches an
54        // address the string check never saw:
55        //   - a resolver that screens every resolved address at connect time
56        //     (see SsrfGuardedResolver), since the string check cannot see
57        //     where a hostname actually resolves;
58        //   - a redirect policy that re-screens each hop with validate_push_url,
59        //     since a redirect to a blocked literal IP skips DNS entirely and so
60        //     never reaches the resolver, and the string check only ran on the
61        //     original URL;
62        //   - no system proxy, since a proxy would resolve and reach the target
63        //     itself, leaving only the proxy address screened.
64        // When validation is off (the single documented opt-out for local test
65        // webhooks), keep reqwest's defaults so loopback targets still work.
66        let mut builder = reqwest::Client::builder().timeout(config.timeout);
67        if config.validate_urls {
68            builder = builder
69                .dns_resolver(Arc::new(SsrfGuardedResolver))
70                .no_proxy()
71                .redirect(ssrf_guarded_redirect_policy());
72        }
73        let client = builder.build().expect("failed to create HTTP client");
74        HttpPushSender {
75            client,
76            fail_on_error: config.fail_on_error,
77            validate_urls: config.validate_urls,
78        }
79    }
80
81    /// Send an event to the push notification endpoint.
82    pub async fn send_push(
83        &self,
84        config: &TaskPushNotificationConfig,
85        event: StreamResponse,
86    ) -> Result<(), A2AError> {
87        if self.validate_urls {
88            validate_push_url(&config.url)?;
89        }
90
91        // Reject credentials containing CR/LF so they cannot inject
92        // additional headers into the outgoing request (BUG-34).
93        if let Some(ref token) = config.token {
94            if token.contains('\r') || token.contains('\n') {
95                return Err(A2AError::invalid_params(
96                    "push notification token must not contain CR/LF",
97                ));
98            }
99        }
100        if let Some(ref auth) = config.authentication {
101            if let Some(ref creds) = auth.credentials {
102                if creds.contains('\r') || creds.contains('\n') {
103                    return Err(A2AError::invalid_params(
104                        "push credentials must not contain CR/LF",
105                    ));
106                }
107                // The scheme opens the Authorization header, so it must be a
108                // single HTTP auth-scheme token (RFC 9110 §11.1).
109                if auth.scheme.is_empty()
110                    || auth
111                        .scheme
112                        .contains(|c: char| c.is_whitespace() || c.is_control())
113                {
114                    return Err(A2AError::invalid_params(
115                        "push authentication scheme must be a single token",
116                    ));
117                }
118            }
119        }
120
121        let body = match serde_json::to_vec(&event) {
122            Ok(b) => b,
123            Err(e) => return self.handle_error(format!("failed to serialize event: {e}")),
124        };
125
126        let mut request = self
127            .client
128            .post(&config.url)
129            .header("Content-Type", "application/json")
130            .body(body);
131
132        if let Some(ref token) = config.token {
133            request = request.header("A2A-Notification-Token", token);
134        }
135
136        if let Some(ref auth) = config.authentication {
137            if let Some(ref creds) = auth.credentials {
138                // Any IANA scheme is sent as configured (§4.3.3); the two
139                // common ones keep their canonical spelling.
140                let scheme = match auth.scheme.to_lowercase().as_str() {
141                    "bearer" => "Bearer",
142                    "basic" => "Basic",
143                    _ => auth.scheme.as_str(),
144                };
145                request = request.header("Authorization", format!("{scheme} {creds}"));
146            }
147        }
148
149        match request.send().await {
150            Ok(resp) => {
151                if !resp.status().is_success() {
152                    return self
153                        .handle_error(format!("push endpoint returned status: {}", resp.status()));
154                }
155                Ok(())
156            }
157            Err(e) => self.handle_error(format!("failed to send push notification: {e}")),
158        }
159    }
160
161    fn handle_error(&self, msg: String) -> Result<(), A2AError> {
162        if self.fail_on_error {
163            Err(crate::sanitized_internal_error(&msg))
164        } else {
165            tracing::error!("{}", msg);
166            Ok(())
167        }
168    }
169}
170
171/// Validate a push notification URL against SSRF targets (BUG-54).
172///
173/// The URL scheme must be http/https and the host must not resolve to a
174/// loopback, private, link-local, multicast, or unspecified address, nor to a
175/// well-known cloud metadata endpoint.
176pub(crate) fn validate_push_url(url: &str) -> Result<(), A2AError> {
177    let parsed = reqwest::Url::parse(url)
178        .map_err(|_| A2AError::invalid_params("invalid push notification URL"))?;
179
180    if parsed.scheme() != "http" && parsed.scheme() != "https" {
181        return Err(A2AError::invalid_params("push URL must be http or https"));
182    }
183
184    if let Some(host) = parsed.host_str() {
185        // A trailing dot is an equivalent fully-qualified form: "localhost."
186        // resolves exactly as "localhost" does. Normalise it away, or every
187        // hostname below is bypassed by appending one character. IP literals
188        // are unaffected either way -- Url::parse already strips the dot for
189        // those, which is why "127.0.0.1." was blocked and "localhost." was
190        // not.
191        let host = host.strip_suffix('.').unwrap_or(host);
192        // Block well-known loopback, metadata, and unspecified hosts.
193        let blocked = [
194            "127.0.0.1",
195            "localhost",
196            "::1",
197            "[::1]",
198            "169.254.169.254",
199            "metadata.google.internal",
200            "metadata.azure.com",
201            "metadata.goog",
202            "0.0.0.0",
203        ];
204        if blocked.contains(&host) {
205            return Err(A2AError::invalid_params("push URL targets blocked host"));
206        }
207        // Block IP literals in restricted ranges (loopback, RFC 1918
208        // private, link-local, ULA, unspecified, multicast). For IPv6 URLs
209        // the host serializes WITH brackets ("[fc00::1]"), which never
210        // parses as an IpAddr — strip them first or every range check
211        // below is silently skipped.
212        let host_unbracketed = host
213            .strip_prefix('[')
214            .and_then(|h| h.strip_suffix(']'))
215            .unwrap_or(host);
216        if let Ok(ip) = host_unbracketed.parse::<std::net::IpAddr>() {
217            if is_blocked_ip(ip) {
218                return Err(A2AError::invalid_params(
219                    "push URL targets private/loopback/link-local address",
220                ));
221            }
222        }
223    }
224
225    Ok(())
226}
227
228/// Whether `ip` is loopback, RFC 1918/ULA private, link-local, unspecified,
229/// or multicast -- the ranges a push URL must not target.
230///
231/// A standalone predicate rather than inline in `validate_push_url`, per
232/// #224's own scope: the connect-time guard it asks for needs to check the
233/// *resolved* address against these same ranges, and must reuse this rather
234/// than duplicate it. It is also what makes target 4 of #238's fuzz plan
235/// possible: fuzzing "does `validate_push_url` correctly extract an IP from
236/// an arbitrary URL and apply this predicate" needs the predicate itself to
237/// be callable as independent ground truth, not re-derived by the fuzz
238/// target and risking drifting out of sync with the real one.
239pub(crate) fn is_blocked_ip(ip: std::net::IpAddr) -> bool {
240    match ip {
241        std::net::IpAddr::V4(v4) => {
242            v4.is_loopback()
243                || v4.is_private()
244                || v4.is_link_local()
245                || v4.is_unspecified()
246                || v4.is_multicast()
247        }
248        std::net::IpAddr::V6(v6) => {
249            // fc00::/7 unique local addresses (IPv6 "private").
250            let is_ula = (v6.segments()[0] & 0xfe00) == 0xfc00;
251            // IPv4-mapped IPv6 literals (::ffff:a.b.c.d) must be checked
252            // against the IPv4 restrictions too, or they bypass the
253            // loopback/private/link-local checks above.
254            let mapped_v4_blocked = v6.to_ipv4_mapped().is_some_and(|v4| {
255                v4.is_loopback()
256                    || v4.is_private()
257                    || v4.is_link_local()
258                    || v4.is_unspecified()
259                    || v4.is_multicast()
260            });
261            v6.is_loopback()
262                || is_ula
263                || mapped_v4_blocked
264                || v6.is_unicast_link_local()
265                || v6.is_unspecified()
266                || v6.is_multicast()
267        }
268    }
269}
270
271/// Retain only the socket addresses safe to dial, dropping any whose IP
272/// [`is_blocked_ip`] rejects. Split out from [`SsrfGuardedResolver`] so the
273/// connect-time filter is unit-testable without performing real DNS.
274fn connectable_addrs(addrs: impl Iterator<Item = SocketAddr>) -> Vec<SocketAddr> {
275    addrs.filter(|addr| !is_blocked_ip(addr.ip())).collect()
276}
277
278/// A `reqwest` resolver that screens resolved addresses against
279/// [`is_blocked_ip`] before the socket is dialed (#224).
280///
281/// `validate_push_url` screens the URL *string*, but a hostname can still
282/// resolve to a loopback, private, or link-local address through split-horizon
283/// DNS, an attacker-controlled A record, or DNS rebinding. This resolver is the
284/// connect-time half of the guard: reqwest dials exactly the addresses returned
285/// here, so filtering them is not subject to a resolve-then-reconnect TOCTOU.
286/// Installed only when `validate_urls` is set.
287///
288/// This resolver only sees addresses reqwest resolves from a hostname. Two
289/// paths reach an address without hitting it, so [`HttpPushSender::new`] closes
290/// them alongside installing this resolver: a redirect to a blocked literal IP
291/// skips DNS entirely (handled by re-screening every redirect hop with
292/// `validate_push_url`), and a system proxy would resolve the target itself
293/// (handled by disabling the proxy). All three are gated on the same
294/// `validate_urls` flag.
295struct SsrfGuardedResolver;
296
297impl Resolve for SsrfGuardedResolver {
298    fn resolve(&self, name: Name) -> Resolving {
299        Box::pin(async move {
300            let host = name.as_str().to_owned();
301            // Port 0: reqwest replaces it with the request's port before
302            // dialing; only the resolved IP matters for the range check.
303            let resolved = tokio::net::lookup_host((host.as_str(), 0)).await?;
304            let allowed = connectable_addrs(resolved);
305            if allowed.is_empty() {
306                return Err(Box::<dyn std::error::Error + Send + Sync>::from(
307                    "push URL host resolves only to blocked (loopback, private, \
308                     link-local, or metadata) addresses",
309                ));
310            }
311            Ok(Box::new(allowed.into_iter()) as Addrs)
312        })
313    }
314}
315
316/// The redirect policy installed when `validate_urls` is set: re-screens
317/// each hop with [`validate_push_url`], since a redirect to a blocked
318/// literal IP skips DNS entirely and never reaches [`SsrfGuardedResolver`].
319///
320/// Split out from [`HttpPushSender::new`] so a test can attach it to a
321/// client on its own, without the resolver -- `reqwest::redirect::Attempt`
322/// has no public constructor, so driving a real HTTP redirect through this
323/// policy is the only way to exercise it.
324fn ssrf_guarded_redirect_policy() -> reqwest::redirect::Policy {
325    reqwest::redirect::Policy::custom(|attempt| {
326        if attempt.previous().len() >= 10 {
327            return attempt.stop();
328        }
329        if validate_push_url(attempt.url().as_str()).is_err() {
330            attempt.error("push URL redirect target is blocked")
331        } else {
332            attempt.follow()
333        }
334    })
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    use crate::test_util::install_crypto_provider;
342
343    #[test]
344    fn test_default_config() {
345        let config = HttpPushSenderConfig::default();
346        assert_eq!(config.timeout, Duration::from_secs(30));
347        assert!(!config.fail_on_error);
348        assert!(config.validate_urls);
349    }
350
351    #[test]
352    fn test_sender_new_default() {
353        install_crypto_provider();
354        let sender = HttpPushSender::new(None);
355        assert!(!sender.fail_on_error);
356        assert!(sender.validate_urls);
357    }
358
359    #[test]
360    fn test_sender_new_custom() {
361        install_crypto_provider();
362        let config = HttpPushSenderConfig {
363            timeout: Duration::from_secs(10),
364            fail_on_error: true,
365            validate_urls: false,
366        };
367        let sender = HttpPushSender::new(Some(config));
368        assert!(sender.fail_on_error);
369        assert!(!sender.validate_urls);
370    }
371
372    #[test]
373    fn test_handle_error_fail_on_error() {
374        install_crypto_provider();
375        let sender = HttpPushSender::new(Some(HttpPushSenderConfig {
376            timeout: Duration::from_secs(5),
377            fail_on_error: true,
378            validate_urls: true,
379        }));
380        let result = sender.handle_error("test error".to_string());
381        assert!(result.is_err());
382    }
383
384    #[test]
385    fn test_handle_error_ignore() {
386        install_crypto_provider();
387        let sender = HttpPushSender::new(None);
388        let result = sender.handle_error("test error".to_string());
389        assert!(result.is_ok());
390    }
391
392    fn sample_status_update() -> StreamResponse {
393        use a2a::event::*;
394        StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
395            task_id: "t1".into(),
396            context_id: "c1".into(),
397            status: TaskStatus {
398                state: TaskState::Working,
399                message: None,
400                timestamp: None,
401            },
402            metadata: None,
403        })
404    }
405
406    fn sample_config(url: &str) -> TaskPushNotificationConfig {
407        TaskPushNotificationConfig {
408            task_id: String::new(),
409            url: url.to_string(),
410            id: None,
411            token: None,
412            authentication: None,
413            tenant: None,
414        }
415    }
416
417    #[tokio::test]
418    async fn test_send_push_connection_refused_no_fail() {
419        install_crypto_provider();
420        let sender = HttpPushSender::new(Some(HttpPushSenderConfig {
421            validate_urls: false,
422            ..Default::default()
423        }));
424        let config = TaskPushNotificationConfig {
425            task_id: String::new(),
426            url: "http://127.0.0.1:1/callback".to_string(),
427            id: None,
428            token: Some("tok".to_string()),
429            authentication: Some(AuthenticationInfo {
430                scheme: "bearer".to_string(),
431                credentials: Some("secret".to_string()),
432            }),
433            tenant: None,
434        };
435        let result = sender.send_push(&config, sample_status_update()).await;
436        // Should be Ok because fail_on_error is false
437        assert!(result.is_ok());
438    }
439
440    #[tokio::test]
441    async fn test_send_push_connection_refused_fail() {
442        install_crypto_provider();
443        let sender = HttpPushSender::new(Some(HttpPushSenderConfig {
444            timeout: std::time::Duration::from_millis(100),
445            fail_on_error: true,
446            validate_urls: false,
447        }));
448        let config = sample_config("http://127.0.0.1:1/callback");
449        let result = sender.send_push(&config, sample_status_update()).await;
450        assert!(result.is_err());
451    }
452
453    #[tokio::test]
454    async fn test_send_push_with_basic_auth() {
455        install_crypto_provider();
456        let sender = HttpPushSender::new(Some(HttpPushSenderConfig {
457            validate_urls: false,
458            ..Default::default()
459        }));
460        let config = TaskPushNotificationConfig {
461            task_id: String::new(),
462            url: "http://127.0.0.1:1/callback".to_string(),
463            id: None,
464            token: None,
465            authentication: Some(AuthenticationInfo {
466                scheme: "basic".to_string(),
467                credentials: Some("dXNlcjpwYXNz".to_string()),
468            }),
469            tenant: None,
470        };
471        let result = sender.send_push(&config, sample_status_update()).await;
472        // Will fail to connect but exercises basic auth header path
473        assert!(result.is_ok()); // fail_on_error=false
474    }
475
476    /// Runs a webhook that records the Authorization header of each request.
477    async fn spawn_auth_recorder() -> (String, Arc<std::sync::Mutex<Vec<Option<String>>>>) {
478        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
479        let log = Arc::clone(&seen);
480        let app = axum::Router::new().route(
481            "/callback",
482            axum::routing::post(move |headers: axum::http::HeaderMap| {
483                let log = Arc::clone(&log);
484                async move {
485                    log.lock().unwrap().push(
486                        headers
487                            .get("authorization")
488                            .map(|value| value.to_str().unwrap().to_owned()),
489                    );
490                }
491            }),
492        );
493        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
494        let addr = listener.local_addr().unwrap();
495        tokio::spawn(async move { axum::serve(listener, app).await });
496        (format!("http://{addr}/callback"), seen)
497    }
498
499    #[tokio::test]
500    async fn test_send_push_sends_credentials_of_any_scheme() {
501        install_crypto_provider();
502        let sender = HttpPushSender::new(Some(HttpPushSenderConfig {
503            fail_on_error: true,
504            validate_urls: false,
505            ..Default::default()
506        }));
507        let (url, seen) = spawn_auth_recorder().await;
508        for (scheme, expected) in [
509            ("bearer", "Bearer tok"),
510            ("Basic", "Basic tok"),
511            ("DPoP", "DPoP tok"),
512        ] {
513            let config = TaskPushNotificationConfig {
514                authentication: Some(AuthenticationInfo {
515                    scheme: scheme.to_string(),
516                    credentials: Some("tok".to_string()),
517                }),
518                ..sample_config(&url)
519            };
520            sender
521                .send_push(&config, sample_status_update())
522                .await
523                .unwrap();
524            assert_eq!(
525                seen.lock().unwrap().last().unwrap().as_deref(),
526                Some(expected),
527                "scheme {scheme}"
528            );
529        }
530    }
531
532    #[tokio::test]
533    async fn test_send_push_rejects_a_scheme_that_is_not_one_token() {
534        install_crypto_provider();
535        let sender = HttpPushSender::new(None);
536        for scheme in ["", "Bearer x", "Bearer\r\nX-Injected: 1"] {
537            let config = TaskPushNotificationConfig {
538                authentication: Some(AuthenticationInfo {
539                    scheme: scheme.to_string(),
540                    credentials: Some("tok".to_string()),
541                }),
542                ..sample_config("https://example.com/callback")
543            };
544            let error = sender
545                .send_push(&config, sample_status_update())
546                .await
547                .unwrap_err();
548            assert_eq!(error.code, error_code::INVALID_PARAMS, "scheme {scheme:?}");
549        }
550    }
551
552    #[test]
553    fn test_validate_push_url_rejects_non_http_schemes() {
554        for url in [
555            "file:///etc/passwd",
556            "ftp://example.com/hook",
557            "gopher://example.com/",
558        ] {
559            let err = validate_push_url(url).unwrap_err();
560            assert_eq!(err.code, error_code::INVALID_PARAMS);
561        }
562    }
563
564    #[test]
565    fn test_validate_push_url_rejects_loopback() {
566        for url in [
567            "http://127.0.0.1:1/callback",
568            "http://localhost/callback",
569            "http://[::1]/callback",
570            "http://0.0.0.0/callback",
571        ] {
572            assert!(
573                validate_push_url(url).is_err(),
574                "expected {url} to be rejected"
575            );
576        }
577    }
578
579    #[test]
580    fn test_validate_push_url_rejects_private_and_link_local() {
581        for url in [
582            "http://10.0.0.1/callback",
583            "http://192.168.1.1/callback",
584            "http://172.16.0.1/callback",
585            "http://169.254.169.254/latest/meta-data/",
586            "http://169.254.1.1/callback",
587            "http://metadata.google.internal/callback",
588        ] {
589            assert!(
590                validate_push_url(url).is_err(),
591                "expected {url} to be rejected"
592            );
593        }
594    }
595
596    #[test]
597    fn test_validate_push_url_rejects_trailing_dot_hosts() {
598        // "localhost." is the fully-qualified spelling of "localhost" and
599        // resolves identically, so it must not slip past the host blocklist.
600        for url in [
601            "http://localhost./hook",
602            "http://LocalHost./hook",
603            "https://localhost./hook",
604            "http://metadata.google.internal./hook",
605            "http://metadata.azure.com./hook",
606        ] {
607            assert!(
608                validate_push_url(url).is_err(),
609                "{url} must be blocked, but was allowed"
610            );
611        }
612    }
613
614    #[test]
615    fn test_validate_push_url_rejects_alternate_ipv4_spellings() {
616        // These are blocked only because Url::parse normalises them to
617        // 127.0.0.1 before the range check sees them. Pin that, so the
618        // normalisation cannot be regressed away unnoticed.
619        for url in [
620            "http://2130706433/hook",         // decimal
621            "http://0x7f.0.0.1/hook",         // hex octet
622            "http://127.1/hook",              // short form
623            "http://127.0.0.1./hook",         // trailing dot on a literal
624            "http://[::ffff:127.0.0.1]/hook", // IPv4-mapped IPv6
625        ] {
626            assert!(
627                validate_push_url(url).is_err(),
628                "{url} must be blocked, but was allowed"
629            );
630        }
631    }
632
633    #[test]
634    fn test_is_blocked_ip_checks_every_range_through_an_ipv4_mapped_address() {
635        // is_blocked_ip's IPv4-mapped-IPv6 branch applies every IPv4
636        // predicate to the unwrapped address, not just is_loopback -- the
637        // existing ::ffff:127.0.0.1 test case above only exercises that
638        // first one, since a loopback address short-circuits the rest.
639        // Each of these is chosen to be false on every earlier predicate,
640        // so the run reaches its own line rather than returning early.
641        for (ip, why) in [
642            ("::ffff:169.254.1.1", "link-local"),
643            ("::ffff:0.0.0.0", "unspecified"),
644            ("::ffff:224.0.0.1", "multicast"),
645        ] {
646            let addr: std::net::IpAddr = ip.parse().unwrap();
647            assert!(is_blocked_ip(addr), "{ip} ({why}) should be blocked");
648        }
649
650        // And the mapped address is not blocked when the underlying IPv4
651        // address is none of these -- confirms the closure's result is
652        // actually load-bearing, not a predicate that always returns true.
653        let public: std::net::IpAddr = "::ffff:93.184.216.34".parse().unwrap();
654        assert!(
655            !is_blocked_ip(public),
656            "a public mapped address was blocked"
657        );
658    }
659
660    #[test]
661    fn test_validate_push_url_rejects_blocked_hosts_regardless_of_case() {
662        // Url::parse lowercases the host per the URL Standard before the
663        // blocklist ever sees it, so this holds independent of the
664        // trailing-dot case above -- pinned on its own rather than only as
665        // a side effect of that test.
666        for url in [
667            "http://LOCALHOST/hook",
668            "http://METADATA.GOOGLE.INTERNAL/hook",
669            "http://Metadata.Azure.Com/hook",
670        ] {
671            assert!(
672                validate_push_url(url).is_err(),
673                "{url} must be blocked, but was allowed"
674            );
675        }
676    }
677
678    #[test]
679    fn test_validate_push_url_accepts_public_urls() {
680        for url in [
681            "http://example.com/callback",
682            "https://example.com/callback",
683            "https://hooks.example.com/abc?x=1",
684        ] {
685            assert!(
686                validate_push_url(url).is_ok(),
687                "expected {url} to be accepted"
688            );
689        }
690    }
691
692    #[tokio::test]
693    async fn test_send_push_rejects_blocked_url_even_without_fail_on_error() {
694        install_crypto_provider();
695        let sender = HttpPushSender::new(None); // validate_urls = true
696        let config = sample_config("http://127.0.0.1:1/callback");
697        let result = sender.send_push(&config, sample_status_update()).await;
698        // Validation errors are always returned, regardless of fail_on_error.
699        assert!(result.is_err());
700        assert_eq!(result.unwrap_err().code, error_code::INVALID_PARAMS);
701    }
702
703    #[tokio::test]
704    async fn test_send_push_rejects_crlf_credentials() {
705        install_crypto_provider();
706        let sender = HttpPushSender::new(None);
707        let config = TaskPushNotificationConfig {
708            task_id: String::new(),
709            url: "https://example.com/callback".to_string(),
710            id: None,
711            token: None,
712            authentication: Some(AuthenticationInfo {
713                scheme: "bearer".to_string(),
714                credentials: Some("secret\r\nX-Injected: 1".to_string()),
715            }),
716            tenant: None,
717        };
718        let result = sender.send_push(&config, sample_status_update()).await;
719        assert!(result.is_err());
720        assert_eq!(result.unwrap_err().code, error_code::INVALID_PARAMS);
721    }
722
723    #[tokio::test]
724    async fn test_send_push_rejects_crlf_token() {
725        install_crypto_provider();
726        let sender = HttpPushSender::new(None);
727        let config = TaskPushNotificationConfig {
728            task_id: String::new(),
729            url: "https://example.com/callback".to_string(),
730            id: None,
731            token: Some("tok\nX-Injected: 1".to_string()),
732            authentication: None,
733            tenant: None,
734        };
735        let result = sender.send_push(&config, sample_status_update()).await;
736        assert!(result.is_err());
737        assert_eq!(result.unwrap_err().code, error_code::INVALID_PARAMS);
738    }
739
740    #[test]
741    fn test_validate_push_url_rejects_invalid_url() {
742        assert!(validate_push_url("not a url").is_err());
743        assert!(validate_push_url("").is_err());
744        // Empty authority fails URL parsing outright (EmptyHost).
745        assert!(validate_push_url("http://").is_err());
746    }
747
748    #[test]
749    fn test_validate_push_url_rejects_ipv6_restricted_ranges() {
750        for url in [
751            "http://[fc00::1]/cb",
752            "http://[fd12:3456:789a::1]/cb",
753            "http://[fe80::1]/cb",
754            "http://[ff02::1]/cb",
755            "http://[::]/cb",
756        ] {
757            let result = validate_push_url(url);
758            assert!(result.is_err(), "expected {url} to be rejected");
759            assert_eq!(result.unwrap_err().code, error_code::INVALID_PARAMS);
760        }
761    }
762
763    #[test]
764    fn test_validate_push_url_rejects_ipv4_mapped_ipv6() {
765        // ::ffff:a.b.c.d literals must inherit the IPv4 restrictions.
766        for url in [
767            "http://[::ffff:127.0.0.1]/cb",
768            "http://[::ffff:10.0.0.1]/cb",
769        ] {
770            let result = validate_push_url(url);
771            assert!(result.is_err(), "expected {url} to be rejected");
772            assert_eq!(result.unwrap_err().code, error_code::INVALID_PARAMS);
773        }
774    }
775
776    #[test]
777    fn test_validate_push_url_rejects_ipv4_multicast() {
778        let result = validate_push_url("http://224.0.0.1/cb");
779        assert!(result.is_err());
780        assert_eq!(result.unwrap_err().code, error_code::INVALID_PARAMS);
781    }
782
783    #[test]
784    fn test_validate_push_url_accepts_global_ipv6() {
785        assert!(validate_push_url("http://[2606:4700::1111]/cb").is_ok());
786    }
787
788    #[test]
789    fn test_connectable_addrs_drops_blocked_keeps_public() {
790        // The connect-time filter (#224) must drop every restricted resolved
791        // address and keep the routable ones, so a hostname that resolves to a
792        // mix cannot reach the blocked members.
793        let addrs: Vec<SocketAddr> = vec![
794            "127.0.0.1:443".parse().unwrap(),         // loopback
795            "10.0.0.5:443".parse().unwrap(),          // RFC 1918
796            "169.254.169.254:80".parse().unwrap(),    // link-local metadata
797            "93.184.216.34:443".parse().unwrap(),     // public v4
798            "[fc00::1]:443".parse().unwrap(),         // IPv6 ULA
799            "[2606:4700::1111]:443".parse().unwrap(), // public v6
800        ];
801        let ips: Vec<std::net::IpAddr> = connectable_addrs(addrs.into_iter())
802            .iter()
803            .map(|a| a.ip())
804            .collect();
805        assert_eq!(
806            ips,
807            vec![
808                "93.184.216.34".parse::<std::net::IpAddr>().unwrap(),
809                "2606:4700::1111".parse::<std::net::IpAddr>().unwrap(),
810            ]
811        );
812    }
813
814    #[test]
815    fn test_connectable_addrs_all_blocked_is_empty() {
816        let addrs: Vec<SocketAddr> = vec![
817            "127.0.0.1:443".parse().unwrap(),
818            "192.168.1.1:443".parse().unwrap(),
819        ];
820        assert!(connectable_addrs(addrs.into_iter()).is_empty());
821    }
822
823    #[tokio::test]
824    async fn test_ssrf_resolver_rejects_host_resolving_to_loopback() {
825        // A bare hostname that resolves only to loopback must be refused at
826        // connect time, even though the resolver never sees an IP literal.
827        // "localhost" resolves to 127.0.0.1 / ::1 without leaving the machine,
828        // so this is deterministic.
829        let name: Name = "localhost".parse().expect("localhost is a valid dns name");
830        let result = SsrfGuardedResolver.resolve(name).await;
831        assert!(
832            result.is_err(),
833            "a host resolving only to loopback must be refused at connect time"
834        );
835    }
836
837    #[test]
838    fn test_redirect_hop_check_rejects_blocked_targets() {
839        // The custom redirect policy re-runs validate_push_url on each hop, so a
840        // redirect to a blocked literal IP (which skips DNS and never reaches
841        // SsrfGuardedResolver) is refused, while a public hop follows. This pins
842        // the per-hop check the policy relies on.
843        assert!(validate_push_url("http://127.0.0.1/").is_err());
844        assert!(validate_push_url("http://169.254.169.254/latest/meta-data/").is_err());
845        assert!(validate_push_url("http://[::1]/").is_err());
846        assert!(validate_push_url("https://example.com/next").is_ok());
847    }
848
849    /// Runs a local server that redirects `/` to `location`, so a real
850    /// `reqwest::redirect::Attempt` reaches [`ssrf_guarded_redirect_policy`]
851    /// -- the type has no public constructor, so this is the only way to
852    /// drive it without faking reqwest's internals.
853    async fn spawn_redirect_server(location: String) -> String {
854        let app = axum::Router::new().route(
855            "/",
856            axum::routing::get(move || {
857                let location = location.clone();
858                async move { axum::response::Redirect::temporary(&location) }
859            }),
860        );
861        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
862        let addr = listener.local_addr().unwrap();
863        tokio::spawn(async move {
864            axum::serve(listener, app).await.unwrap();
865        });
866        format!("http://{addr}/")
867    }
868
869    #[tokio::test]
870    async fn test_redirect_policy_blocks_a_redirect_to_a_disallowed_target() {
871        let server_url =
872            spawn_redirect_server("http://169.254.169.254/latest/meta-data/".into()).await;
873        let client = reqwest::Client::builder()
874            .redirect(ssrf_guarded_redirect_policy())
875            .build()
876            .unwrap();
877        let err = client
878            .get(&server_url)
879            .send()
880            .await
881            .expect_err("a redirect to a blocked target must fail");
882        assert!(err.is_redirect(), "expected a redirect-policy error: {err}");
883    }
884
885    #[tokio::test]
886    async fn test_redirect_policy_rejects_a_self_redirect_loop_immediately() {
887        // A server that redirects to itself is a loopback target, so the
888        // per-hop block check (not the separate 10-hop cap, which nothing
889        // here can safely reach without a real allowed target to bounce
890        // through) is what stops it -- on the very first hop.
891        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
892        let addr = listener.local_addr().unwrap();
893        let self_url = format!("http://{addr}/");
894        let app = axum::Router::new().route(
895            "/",
896            axum::routing::get(move || {
897                let self_url = self_url.clone();
898                async move { axum::response::Redirect::temporary(&self_url) }
899            }),
900        );
901        tokio::spawn(async move {
902            axum::serve(listener, app).await.unwrap();
903        });
904
905        let client = reqwest::Client::builder()
906            .redirect(ssrf_guarded_redirect_policy())
907            .build()
908            .unwrap();
909        let err = client
910            .get(format!("http://{addr}/"))
911            .send()
912            .await
913            .expect_err("a loopback self-redirect must be refused, not followed");
914        assert!(err.is_redirect(), "expected a redirect-policy error: {err}");
915    }
916}