1use a2a::*;
5use reqwest::dns::{Addrs, Name, Resolve, Resolving};
6use std::net::SocketAddr;
7use std::sync::Arc;
8use std::time::Duration;
9
10pub struct HttpPushSender {
14 client: reqwest::Client,
15 fail_on_error: bool,
16 validate_urls: bool,
17}
18
19pub struct HttpPushSenderConfig {
21 pub timeout: Duration,
23 pub fail_on_error: bool,
25 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 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 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 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 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 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
171pub(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 let host = host.strip_suffix('.').unwrap_or(host);
192 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 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
228pub(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 let is_ula = (v6.segments()[0] & 0xfe00) == 0xfc00;
251 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
271fn connectable_addrs(addrs: impl Iterator<Item = SocketAddr>) -> Vec<SocketAddr> {
275 addrs.filter(|addr| !is_blocked_ip(addr.ip())).collect()
276}
277
278struct 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 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
316fn 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 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 assert!(result.is_ok()); }
475
476 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 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 for url in [
620 "http://2130706433/hook", "http://0x7f.0.0.1/hook", "http://127.1/hook", "http://127.0.0.1./hook", "http://[::ffff:127.0.0.1]/hook", ] {
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 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 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 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); let config = sample_config("http://127.0.0.1:1/callback");
697 let result = sender.send_push(&config, sample_status_update()).await;
698 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 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 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 let addrs: Vec<SocketAddr> = vec![
794 "127.0.0.1:443".parse().unwrap(), "10.0.0.5:443".parse().unwrap(), "169.254.169.254:80".parse().unwrap(), "93.184.216.34:443".parse().unwrap(), "[fc00::1]:443".parse().unwrap(), "[2606:4700::1111]:443".parse().unwrap(), ];
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 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 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 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 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}