1use std::future::Future;
18use std::net::SocketAddr;
19use std::pin::Pin;
20
21use super::pinning::host_from_url;
22use super::request::{Attempt, Prepared, judge};
23use a2a_protocol_types::error::{A2aError, A2aResult};
24use a2a_protocol_types::events::StreamResponse;
25use a2a_protocol_types::push::TaskPushNotificationConfig;
26
27pub(crate) type PushHttpClient = crate::net::client::HttpsClient;
32
33#[cfg(feature = "tls-rustls")]
38pub(crate) fn build_push_https_client(tls_config: &rustls::ClientConfig) -> PushHttpClient {
39 crate::net::client::HttpsClient::new(tls_config)
40}
41
42#[cfg(test)]
45pub(crate) fn push_client_with_rules(
46 rules: std::sync::Arc<hyper_util::client::proxy::matcher::Matcher>,
47) -> PushHttpClient {
48 #[cfg(not(feature = "tls-rustls"))]
49 {
50 crate::net::client::HttpsClient::plain_with_rules(rules)
51 }
52 #[cfg(feature = "tls-rustls")]
53 {
54 crate::net::client::HttpsClient::with_rules(&crate::net::roots::default_tls_config(), rules)
55 }
56}
57
58pub(crate) fn build_push_http_client() -> PushHttpClient {
61 #[cfg(not(feature = "tls-rustls"))]
64 {
65 crate::net::client::HttpsClient::plain()
66 }
67 #[cfg(feature = "tls-rustls")]
68 {
69 build_push_https_client(&crate::net::roots::default_tls_config())
70 }
71}
72
73pub trait PushSender: Send + Sync + 'static {
95 fn send<'a>(
101 &'a self,
102 url: &'a str,
103 event: &'a StreamResponse,
104 config: &'a TaskPushNotificationConfig,
105 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>>;
106
107 fn allows_private_urls(&self) -> bool {
113 false
114 }
115
116 fn allows_webhook_url(&self, _url: &str) -> bool {
121 true
122 }
123
124 fn requires_https(&self) -> bool {
129 false
130 }
131
132 fn max_delivery_duration(&self) -> Option<std::time::Duration> {
155 None
156 }
157}
158
159const DEFAULT_PUSH_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
167
168const DEFAULT_DNS_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
171
172#[derive(Debug, Clone)]
193#[non_exhaustive]
194pub struct PushRetryPolicy {
195 pub max_attempts: usize,
197 pub backoff: Vec<std::time::Duration>,
202}
203
204impl Default for PushRetryPolicy {
205 fn default() -> Self {
206 Self {
207 max_attempts: 3,
208 backoff: vec![
209 std::time::Duration::from_secs(1),
210 std::time::Duration::from_secs(2),
211 ],
212 }
213 }
214}
215
216impl PushRetryPolicy {
217 #[must_use]
221 pub const fn with_max_attempts(mut self, max: usize) -> Self {
222 self.max_attempts = if max == 0 { 1 } else { max };
223 self
224 }
225
226 #[must_use]
228 pub fn with_backoff(mut self, backoff: Vec<std::time::Duration>) -> Self {
229 self.backoff = backoff;
230 self
231 }
232}
233
234#[derive(Debug)]
281pub struct HttpPushSender {
282 client: PushHttpClient,
283 request_timeout: std::time::Duration,
284 retry_policy: PushRetryPolicy,
285 dns_timeout: std::time::Duration,
287 allow_private_urls: bool,
289 allowed_hosts: Option<Vec<String>>,
291 https_only: bool,
293 proxy_resolved_names: bool,
296}
297
298impl Default for HttpPushSender {
299 fn default() -> Self {
300 Self::new()
301 }
302}
303
304impl HttpPushSender {
305 #[must_use]
308 pub fn new() -> Self {
309 Self::with_timeout(DEFAULT_PUSH_REQUEST_TIMEOUT)
310 }
311
312 #[must_use]
314 pub fn with_timeout(request_timeout: std::time::Duration) -> Self {
315 let client = build_push_http_client();
316 Self {
317 client,
318 request_timeout,
319 retry_policy: PushRetryPolicy::default(),
320 dns_timeout: DEFAULT_DNS_LOOKUP_TIMEOUT,
321 allow_private_urls: false,
322 allowed_hosts: None,
323 https_only: false,
324 proxy_resolved_names: false,
325 }
326 }
327
328 #[cfg(feature = "tls-rustls")]
339 #[must_use]
340 #[allow(clippy::needless_pass_by_value)]
343 pub fn with_tls_config(tls_config: rustls::ClientConfig) -> Self {
344 Self {
345 client: build_push_https_client(&tls_config),
346 request_timeout: DEFAULT_PUSH_REQUEST_TIMEOUT,
347 retry_policy: PushRetryPolicy::default(),
348 dns_timeout: DEFAULT_DNS_LOOKUP_TIMEOUT,
349 allow_private_urls: false,
350 allowed_hosts: None,
351 https_only: false,
352 proxy_resolved_names: false,
353 }
354 }
355
356 #[must_use]
367 pub const fn with_dns_timeout(mut self, timeout: std::time::Duration) -> Self {
368 self.dns_timeout = timeout;
369 self
370 }
371
372 #[must_use]
374 pub fn with_retry_policy(mut self, policy: PushRetryPolicy) -> Self {
375 self.retry_policy = policy;
376 self
377 }
378
379 #[must_use]
384 pub const fn allow_private_urls(mut self) -> Self {
385 self.allow_private_urls = true;
386 self
387 }
388
389 #[must_use]
396 pub fn with_allowed_hosts<I, S>(mut self, hosts: I) -> Self
397 where
398 I: IntoIterator<Item = S>,
399 S: AsRef<str>,
400 {
401 self.allowed_hosts = Some(
402 hosts
403 .into_iter()
404 .map(|h| h.as_ref().to_ascii_lowercase())
405 .collect(),
406 );
407 self
408 }
409
410 #[must_use]
416 pub const fn https_only(mut self) -> Self {
417 self.https_only = true;
418 self
419 }
420
421 #[must_use]
442 pub const fn with_proxy_resolved_names(mut self) -> Self {
443 self.proxy_resolved_names = true;
444 self
445 }
446
447 async fn preflight(&self, url: &str) -> A2aResult<Option<Vec<SocketAddr>>> {
450 let proxied = url
451 .parse::<hyper::Uri>()
452 .is_ok_and(|uri| self.client.proxied(&uri));
453 preflight_with(
454 url,
455 self.dns_timeout,
456 proxied,
457 self.proxy_resolved_names,
458 crate::url_guard::system_lookup,
459 )
460 .await
461 }
462
463 fn host_allowed(&self, url: &str) -> bool {
464 let Some(allowed) = &self.allowed_hosts else {
465 return true;
466 };
467 url.parse::<hyper::Uri>()
468 .ok()
469 .and_then(|uri| uri.host().map(str::to_ascii_lowercase))
470 .is_some_and(|host| allowed.contains(&host))
471 }
472}
473
474pub(crate) fn is_https_url(url: &str) -> bool {
476 url.split_once("://")
477 .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("https"))
478}
479
480pub(crate) fn validate_webhook_url(url: &str) -> A2aResult<()> {
487 crate::url_guard::check(url, "webhook URL")
488}
489
490pub(crate) async fn preflight_with<F, Fut>(
498 url: &str,
499 dns_timeout: std::time::Duration,
500 proxied: bool,
501 proxy_resolved_names: bool,
502 resolve: F,
503) -> A2aResult<Option<Vec<SocketAddr>>>
504where
505 F: FnOnce(String) -> Fut,
506 Fut: std::future::Future<Output = std::io::Result<Vec<SocketAddr>>>,
507{
508 if !proxied {
509 return crate::url_guard::resolve_with(url, "webhook URL", dns_timeout, resolve).await;
510 }
511 let looked_up = std::sync::atomic::AtomicBool::new(false);
516 let answered = std::sync::atomic::AtomicBool::new(false);
517 let watched = |addr: String| {
518 let (looked_up, answered) = (&looked_up, &answered);
519 looked_up.store(true, std::sync::atomic::Ordering::SeqCst);
520 let lookup = resolve(addr);
521 async move {
522 let found = lookup.await;
523 if found.as_ref().is_ok_and(|addrs| !addrs.is_empty()) {
524 answered.store(true, std::sync::atomic::Ordering::SeqCst);
525 }
526 found
527 }
528 };
529 let checked = crate::url_guard::resolve_with(url, "webhook URL", dns_timeout, watched).await;
530 let unanswered = looked_up.load(std::sync::atomic::Ordering::SeqCst)
531 && !answered.load(std::sync::atomic::Ordering::SeqCst);
532 match checked {
533 Err(_) if unanswered && proxy_resolved_names => Ok(None),
534 Err(err) if unanswered => Err(A2aError::invalid_params(format!(
535 "{}; a proxy carries this webhook, and HttpPushSender::with_proxy_resolved_names \
536 lets it resolve names this process cannot (ADR 0043)",
537 err.message
538 ))),
539 other => other,
540 }
541}
542
543#[cfg(test)]
545async fn validate_webhook_url_with_resolver<F, Fut>(
546 url: &str,
547 dns_timeout: std::time::Duration,
548 resolve: F,
549) -> A2aResult<Option<Vec<SocketAddr>>>
550where
551 F: FnOnce(String) -> Fut,
552 Fut: std::future::Future<Output = std::io::Result<Vec<SocketAddr>>>,
553{
554 crate::url_guard::resolve_with(url, "webhook URL", dns_timeout, resolve).await
555}
556
557#[cfg(test)]
558use crate::url_guard::{embedded_ipv4, is_private_v4, parse_numeric_ipv4, webhook_port};
559#[cfg(test)]
560use std::net::Ipv4Addr;
561
562#[cfg(test)]
566pub(crate) async fn validate_webhook_url_with_dns(
567 url: &str,
568 dns_timeout: std::time::Duration,
569) -> A2aResult<Option<Vec<SocketAddr>>> {
570 crate::url_guard::resolve(url, "webhook URL", dns_timeout).await
571}
572
573pub(super) fn validate_header_value(value: &str, name: &str) -> A2aResult<()> {
575 if value.contains('\r') || value.contains('\n') {
576 return Err(A2aError::invalid_params(format!(
577 "{name} contains invalid characters (CR/LF)"
578 )));
579 }
580 Ok(())
581}
582
583pub(super) fn authorization_header(
599 config: &TaskPushNotificationConfig,
600) -> A2aResult<Option<String>> {
601 let Some(auth) = config.authentication.as_ref() else {
602 return Ok(None);
603 };
604 let prefix = if auth.scheme.eq_ignore_ascii_case("bearer") {
605 "Bearer"
606 } else if auth.scheme.eq_ignore_ascii_case("basic") {
607 "Basic"
608 } else {
609 trace_warn!(
610 scheme = auth.scheme.as_str(),
611 "unknown push authentication scheme; not delivering"
612 );
613 return Err(A2aError::invalid_params(format!(
614 "push config authentication scheme {:?} is not one this sender can send \
615 (Bearer or Basic); not delivering without the credentials the config \
616 specifies (spec §13.2)",
617 auth.scheme
618 )));
619 };
620 let credentials = auth
621 .credentials
622 .as_deref()
623 .filter(|c| !c.trim().is_empty())
624 .ok_or_else(|| {
625 trace_warn!(
626 scheme = auth.scheme.as_str(),
627 "push authentication scheme has no credentials; not delivering"
628 );
629 A2aError::invalid_params(format!(
630 "push config authentication scheme {prefix} has no credentials; not \
631 delivering without the credentials the config specifies (spec §13.2)"
632 ))
633 })?;
634 Ok(Some(format!("{prefix} {credentials}")))
635}
636
637#[allow(clippy::manual_async_fn, clippy::too_many_lines)]
638impl PushSender for HttpPushSender {
639 fn max_delivery_duration(&self) -> Option<std::time::Duration> {
645 let attempts = self.retry_policy.max_attempts.max(1);
646 if attempts == 0 {
647 return Some(std::time::Duration::ZERO);
648 }
649 let mut total = self
652 .request_timeout
653 .saturating_mul(u32::try_from(attempts).unwrap_or(u32::MAX))
654 .saturating_add(self.dns_timeout);
655 for attempt in 0..attempts.saturating_sub(1) {
656 if let Some(delay) = self
657 .retry_policy
658 .backoff
659 .get(attempt)
660 .or_else(|| self.retry_policy.backoff.last())
661 {
662 total = total.saturating_add(*delay);
663 }
664 }
665 Some(total)
666 }
667
668 fn allows_private_urls(&self) -> bool {
669 self.allow_private_urls
670 }
671
672 fn allows_webhook_url(&self, url: &str) -> bool {
673 self.host_allowed(url)
674 }
675
676 fn requires_https(&self) -> bool {
677 self.https_only
678 }
679
680 fn send<'a>(
681 &'a self,
682 url: &'a str,
683 event: &'a StreamResponse,
684 config: &'a TaskPushNotificationConfig,
685 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
686 Box::pin(async move {
687 let target = super::webhook::origin_for_log(url);
690 let _ = ⌖
691 trace_info!(target = %target, "delivering push notification");
692
693 if !self.host_allowed(url) {
694 return Err(A2aError::invalid_params(format!(
695 "webhook host of {target} is not in this sender's allowlist"
696 )));
697 }
698
699 let is_https = is_https_url(url);
700 if self.https_only && !is_https {
701 return Err(A2aError::invalid_params(format!(
702 "{target} is not an https:// webhook, and this sender delivers only to https"
703 )));
704 }
705
706 #[cfg(not(feature = "tls-rustls"))]
712 if is_https {
713 return Err(A2aError::internal(
714 "this build of HttpPushSender delivers over HTTP only and cannot reach an \
715 https:// webhook; enable the `tls-rustls` feature (on by default in \
716 a2a-protocol-sdk) or supply a TLS-capable PushSender implementation",
717 ));
718 }
719
720 let validated = if self.allow_private_urls {
725 None
726 } else {
727 self.preflight(url).await?
728 };
729
730 let addresses: Vec<std::net::IpAddr> = validated.as_ref().map_or_else(
734 || super::gate::literal_ip(url).into_iter().collect(),
735 |addrs| addrs.iter().map(SocketAddr::ip).collect(),
736 );
737 let _address_hold = super::gate::admission::hold_addresses(&addresses).await;
738
739 self.deliver(url, event, config, validated).await
740 })
741 }
742}
743
744impl HttpPushSender {
745 pub(crate) async fn deliver(
750 &self,
751 url: &str,
752 event: &StreamResponse,
753 config: &TaskPushNotificationConfig,
754 validated: Option<Vec<SocketAddr>>,
755 ) -> A2aResult<()> {
756 let target = super::webhook::origin_for_log(url);
757 let _ = ⌖
758
759 let _pin = match validated {
768 Some(addrs) => Some(self.client.pin(&host_from_url(url)?, addrs)),
769 None => None,
770 };
771
772 let prepared = Prepared::new(config, event)?;
773
774 let mut last_err = String::new();
775
776 let attempts = self.retry_policy.max_attempts.max(1);
779 for attempt in 0..attempts {
780 let mut req = prepared.request(url, None, None)?;
781
782 let span = crate::rpc_span::WebhookSpan::open(url, attempt);
785 span.inject(req.headers_mut());
786 let request_result = span
787 .run(tokio::time::timeout(
788 self.request_timeout,
789 self.client.request(req),
790 ))
791 .await;
792
793 match judge(&target, attempt, self.request_timeout, request_result) {
794 Attempt::Delivered => return Ok(()),
795 Attempt::Rejected { why, status } => {
796 return Err(super::health::rejected(why, status));
797 }
798 Attempt::Retry(why) => last_err = why,
799 }
800
801 if attempt + 1 < attempts {
805 let delay = self
806 .retry_policy
807 .backoff
808 .get(attempt)
809 .or_else(|| self.retry_policy.backoff.last());
810 if let Some(delay) = delay {
811 tokio::time::sleep(*delay).await;
812 }
813 }
814 }
815
816 Err(A2aError::internal(last_err))
817 }
818}
819
820#[cfg(test)]
823#[path = "sender_pin_tests.rs"]
824mod pin_tests;
825
826#[cfg(test)]
827#[path = "sender_proxy_tests.rs"]
828mod proxy_tests;
829
830#[cfg(test)]
831#[path = "sender_proxy_hint_tests.rs"]
832mod proxy_hint_tests;
833
834#[cfg(test)]
835mod tests {
836 use super::*;
837
838 #[test]
842 fn a_sender_that_does_not_report_a_schedule_reports_none() {
843 struct SaysNothing;
844 impl PushSender for SaysNothing {
845 fn send<'a>(
846 &'a self,
847 _url: &'a str,
848 _event: &'a StreamResponse,
849 _config: &'a TaskPushNotificationConfig,
850 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
851 Box::pin(async { Ok(()) })
852 }
853 }
854 assert_eq!(SaysNothing.max_delivery_duration(), None);
855 }
856
857 #[test]
859 fn push_retry_policy_with_max_attempts() {
860 let policy = PushRetryPolicy::default().with_max_attempts(5);
861 assert_eq!(policy.max_attempts, 5);
862 assert_eq!(policy.backoff.len(), 2);
864 }
865
866 #[test]
868 fn push_retry_policy_with_backoff() {
869 let backoff = vec![
870 std::time::Duration::from_millis(100),
871 std::time::Duration::from_millis(500),
872 std::time::Duration::from_secs(1),
873 ];
874 let policy = PushRetryPolicy::default().with_backoff(backoff.clone());
875 assert_eq!(policy.backoff, backoff);
876 assert_eq!(policy.max_attempts, 3);
878 }
879
880 #[test]
882 fn http_push_sender_with_retry_policy() {
883 let policy = PushRetryPolicy::default().with_max_attempts(10);
884 let sender = HttpPushSender::new().with_retry_policy(policy);
885 assert_eq!(sender.retry_policy.max_attempts, 10);
886 }
887
888 #[test]
890 fn rejects_url_without_host() {
891 assert!(validate_webhook_url("http:///path").is_err());
892 }
893
894 #[test]
896 fn http_push_sender_allow_private_urls() {
897 let sender = HttpPushSender::new().allow_private_urls();
898 assert!(sender.allow_private_urls);
899 }
900
901 #[test]
903 fn http_push_sender_default() {
904 let sender = HttpPushSender::default();
905 assert_eq!(sender.request_timeout, DEFAULT_PUSH_REQUEST_TIMEOUT);
906 assert!(!sender.allow_private_urls);
907 }
908
909 #[test]
911 fn push_retry_policy_default() {
912 let policy = PushRetryPolicy::default();
913 assert_eq!(policy.max_attempts, 3);
914 assert_eq!(policy.backoff.len(), 2);
915 assert_eq!(policy.backoff[0], std::time::Duration::from_secs(1));
916 assert_eq!(policy.backoff[1], std::time::Duration::from_secs(2));
917 }
918
919 #[test]
920 fn rejects_loopback_ipv4() {
921 assert!(validate_webhook_url("http://127.0.0.1:8080/webhook").is_err());
922 }
923
924 #[test]
925 fn rejects_private_10_range() {
926 assert!(validate_webhook_url("http://10.0.0.1/webhook").is_err());
927 }
928
929 #[test]
930 fn rejects_private_172_range() {
931 assert!(validate_webhook_url("http://172.16.0.1/webhook").is_err());
932 }
933
934 #[test]
935 fn rejects_private_192_168_range() {
936 assert!(validate_webhook_url("http://192.168.1.1/webhook").is_err());
937 }
938
939 #[test]
940 fn rejects_link_local() {
941 assert!(validate_webhook_url("http://169.254.169.254/latest").is_err());
942 }
943
944 #[test]
945 fn parse_numeric_ipv4_matches_the_resolver() {
946 let v4 = |s: &str| s.parse::<Ipv4Addr>().unwrap();
947 assert_eq!(
949 parse_numeric_ipv4("2852039166"),
950 Some(v4("169.254.169.254"))
951 ); assert_eq!(
953 parse_numeric_ipv4("0xA9FEA9FE"),
954 Some(v4("169.254.169.254"))
955 ); assert_eq!(
957 parse_numeric_ipv4("0xa9fea9fe"),
958 Some(v4("169.254.169.254"))
959 ); assert_eq!(
961 parse_numeric_ipv4("0251.0376.0251.0376"),
962 Some(v4("169.254.169.254")) );
964 assert_eq!(parse_numeric_ipv4("2130706433"), Some(v4("127.0.0.1"))); assert_eq!(parse_numeric_ipv4("127.1"), Some(v4("127.0.0.1"))); assert_eq!(parse_numeric_ipv4("0x7f.0.0.1"), Some(v4("127.0.0.1"))); assert_eq!(parse_numeric_ipv4("134744072"), Some(v4("8.8.8.8")));
971 assert_eq!(parse_numeric_ipv4("example.com"), None);
973 assert_eq!(parse_numeric_ipv4("printer.local"), None);
974 assert_eq!(parse_numeric_ipv4("256.1.1.1"), None); assert_eq!(parse_numeric_ipv4("1.2.3.4.5"), None); assert_eq!(parse_numeric_ipv4("99999999999999999999"), None); assert_eq!(parse_numeric_ipv4("0x"), None); assert_eq!(parse_numeric_ipv4("1e10"), None); }
980
981 #[test]
990 fn parse_numeric_ipv4_packs_every_part_count_exactly() {
991 let v4 = |s: &str| s.parse::<Ipv4Addr>().unwrap();
992
993 assert_eq!(parse_numeric_ipv4("1"), Some(v4("0.0.0.1")));
995 assert_eq!(parse_numeric_ipv4("1.2"), Some(v4("1.0.0.2")));
996 assert_eq!(parse_numeric_ipv4("1.2.3"), Some(v4("1.2.0.3")));
997 assert_eq!(parse_numeric_ipv4("1.2.3.4"), Some(v4("1.2.3.4")));
998 assert_eq!(parse_numeric_ipv4("0177.0.0.01"), Some(v4("127.0.0.1")));
999
1000 assert_eq!(
1003 parse_numeric_ipv4("4294967295"),
1004 Some(v4("255.255.255.255"))
1005 );
1006 assert_eq!(parse_numeric_ipv4("4294967296"), None);
1007 assert_eq!(parse_numeric_ipv4("1.16777215"), Some(v4("1.255.255.255")));
1008 assert_eq!(parse_numeric_ipv4("1.16777216"), None);
1009 assert_eq!(parse_numeric_ipv4("1.2.65535"), Some(v4("1.2.255.255")));
1010 assert_eq!(parse_numeric_ipv4("1.2.65536"), None);
1011 assert_eq!(parse_numeric_ipv4("1.2.3.255"), Some(v4("1.2.3.255")));
1012 assert_eq!(parse_numeric_ipv4("1.2.3.256"), None);
1013
1014 assert_eq!(parse_numeric_ipv4("255.1"), Some(v4("255.0.0.1")));
1016 assert_eq!(parse_numeric_ipv4("256.1"), None);
1017 assert_eq!(parse_numeric_ipv4("1.255.1"), Some(v4("1.255.0.1")));
1018 assert_eq!(parse_numeric_ipv4("1.256.1"), None);
1019 assert_eq!(parse_numeric_ipv4("1.2.255.1"), Some(v4("1.2.255.1")));
1020 assert_eq!(parse_numeric_ipv4("1.2.256.1"), None);
1021
1022 assert_eq!(parse_numeric_ipv4("1.2.3.4.5"), None);
1025 assert_eq!(parse_numeric_ipv4("1.2.3.4.5.6"), None);
1026
1027 assert_eq!(parse_numeric_ipv4(""), None);
1029 assert_eq!(parse_numeric_ipv4("."), None);
1030 assert_eq!(parse_numeric_ipv4("1..2"), None);
1031 assert_eq!(parse_numeric_ipv4("1.2."), None);
1032 assert_eq!(parse_numeric_ipv4("-1"), None);
1033 assert_eq!(parse_numeric_ipv4("1.-1"), None);
1034 }
1035
1036 #[test]
1037 fn rejects_decimal_integer_metadata() {
1038 assert!(validate_webhook_url("http://2852039166/latest/meta-data").is_err());
1041 }
1042
1043 #[test]
1044 fn rejects_hex_integer_metadata() {
1045 assert!(validate_webhook_url("http://0xA9FEA9FE/latest").is_err());
1046 }
1047
1048 #[test]
1049 fn rejects_octal_dotted_metadata() {
1050 assert!(validate_webhook_url("http://0251.0376.0251.0376/latest").is_err());
1051 }
1052
1053 #[test]
1054 fn rejects_packed_short_form_loopback() {
1055 assert!(validate_webhook_url("http://2130706433/webhook").is_err()); assert!(validate_webhook_url("http://127.1/webhook").is_err()); assert!(validate_webhook_url("http://0x7f.0.0.1/webhook").is_err());
1058 }
1059
1060 #[test]
1061 fn accepts_public_numeric_ip() {
1062 assert!(validate_webhook_url("http://134744072/webhook").is_ok());
1065 }
1066
1067 #[test]
1068 fn max_delivery_duration_matches_the_retry_loop_it_describes() {
1069 use std::time::Duration;
1070
1071 let sender = HttpPushSender::new();
1073 assert_eq!(
1074 sender.max_delivery_duration(),
1075 Some(Duration::from_secs(5 + 10 + 1 + 10 + 2 + 10)),
1076 "the default schedule is 38 seconds: 5 of DNS, then 33 of requests and backoff"
1077 );
1078
1079 let one = HttpPushSender::with_timeout(Duration::from_secs(7))
1081 .with_retry_policy(PushRetryPolicy::default().with_max_attempts(1))
1082 .with_dns_timeout(Duration::from_secs(1));
1083 assert_eq!(
1084 one.max_delivery_duration(),
1085 Some(Duration::from_secs(1 + 7))
1086 );
1087
1088 let many = HttpPushSender::with_timeout(Duration::from_secs(1))
1091 .with_retry_policy(
1092 PushRetryPolicy::default().with_max_attempts(5), )
1094 .with_dns_timeout(Duration::ZERO);
1095 assert_eq!(
1096 many.max_delivery_duration(),
1097 Some(Duration::from_secs(5 + 1 + 2 + 2 + 2)),
1098 "backoff falls back to its last entry, as `send` does"
1099 );
1100 }
1101
1102 #[test]
1111 fn the_default_schedule_starts_every_attempt_inside_the_default_bound() {
1112 use crate::handler::HandlerLimits;
1113 use std::time::Duration;
1114
1115 let ten = Duration::from_secs(10);
1116 let thirty = Duration::from_secs(30);
1117 assert!((ten..=thirty).contains(&DEFAULT_PUSH_REQUEST_TIMEOUT));
1118 let allowed = HandlerLimits::default().push_delivery_timeout;
1119 assert!((ten..=thirty).contains(&allowed));
1120
1121 let policy = PushRetryPolicy::default();
1124 let mut starts = Vec::new();
1125 let mut at = DEFAULT_DNS_LOOKUP_TIMEOUT;
1126 for i in 0..policy.max_attempts {
1127 starts.push(at);
1128 at += DEFAULT_PUSH_REQUEST_TIMEOUT;
1129 if let Some(d) = policy.backoff.get(i).or_else(|| policy.backoff.last()) {
1130 at += *d;
1131 }
1132 }
1133 assert_eq!(
1134 starts,
1135 [5, 16, 28].map(Duration::from_secs),
1136 "every attempt starts inside the {allowed:?} bound"
1137 );
1138 assert!(starts.iter().all(|s| *s < allowed));
1139 let finished = starts
1140 .iter()
1141 .filter(|s| **s + DEFAULT_PUSH_REQUEST_TIMEOUT <= allowed)
1142 .count();
1143 assert_eq!(finished, 2, "the first two attempts always finish");
1144
1145 let wanted = HttpPushSender::new()
1148 .max_delivery_duration()
1149 .expect("HttpPushSender reports its schedule");
1150 assert_eq!(wanted, Duration::from_secs(38));
1151 assert!(wanted > allowed);
1152 }
1153
1154 #[test]
1155 fn rejects_localhost() {
1156 assert!(validate_webhook_url("http://localhost:8080/webhook").is_err());
1157 }
1158
1159 #[test]
1160 fn rejects_dot_local() {
1161 assert!(validate_webhook_url("http://myservice.local/webhook").is_err());
1162 }
1163
1164 #[test]
1165 fn rejects_dot_internal() {
1166 assert!(validate_webhook_url("http://metadata.internal/webhook").is_err());
1167 }
1168
1169 #[test]
1170 fn rejects_ipv6_loopback() {
1171 assert!(validate_webhook_url("http://[::1]:8080/webhook").is_err());
1172 }
1173
1174 #[test]
1181 fn rejects_ipv4_mapped_loopback() {
1182 assert!(validate_webhook_url("http://[::ffff:127.0.0.1]:8080/webhook").is_err());
1183 }
1184
1185 #[test]
1186 fn rejects_ipv4_mapped_metadata() {
1187 assert!(validate_webhook_url("http://[::ffff:169.254.169.254]/latest/meta-data").is_err());
1188 }
1189
1190 #[test]
1191 fn rejects_ipv4_mapped_private() {
1192 assert!(validate_webhook_url("http://[::ffff:10.0.0.1]/webhook").is_err());
1193 assert!(validate_webhook_url("http://[::ffff:192.168.1.1]/webhook").is_err());
1194 }
1195
1196 #[test]
1197 fn rejects_ipv4_compatible_loopback() {
1198 assert!(validate_webhook_url("http://[::127.0.0.1]/webhook").is_err());
1200 }
1201
1202 #[test]
1203 fn rejects_nat64_wellknown_prefix_to_private() {
1204 assert!(validate_webhook_url("http://[64:ff9b::a9fe:a9fe]/latest").is_err());
1206 }
1207
1208 #[test]
1209 fn accepts_ipv4_mapped_public() {
1210 assert!(validate_webhook_url("http://[::ffff:203.0.113.1]/webhook").is_ok());
1212 }
1213
1214 #[test]
1222 fn is_private_v4_cgnat_boundary() {
1223 assert!(is_private_v4("100.64.0.1".parse().unwrap()));
1225 assert!(is_private_v4("100.127.255.255".parse().unwrap())); assert!(!is_private_v4("100.0.0.1".parse().unwrap())); assert!(!is_private_v4("100.128.0.1".parse().unwrap())); assert!(!is_private_v4("5.64.0.1".parse().unwrap()));
1231 }
1232
1233 #[test]
1234 fn embedded_ipv4_recovers_only_the_v4_bearing_forms() {
1235 let v6 = |s: &str| s.parse::<std::net::Ipv6Addr>().unwrap();
1236 let v4 = |s: &str| Some(s.parse::<std::net::Ipv4Addr>().unwrap());
1237
1238 assert_eq!(embedded_ipv4(v6("::ffff:127.0.0.1")), v4("127.0.0.1"));
1240 assert_eq!(
1241 embedded_ipv4(v6("64:ff9b::a9fe:a9fe")),
1242 v4("169.254.169.254")
1243 );
1244 assert_eq!(embedded_ipv4(v6("::2")), v4("0.0.0.2"));
1247 assert_eq!(embedded_ipv4(v6("::")), None);
1248 assert_eq!(embedded_ipv4(v6("::1")), None);
1249 assert_eq!(embedded_ipv4(v6("2606:4700::1111")), None);
1251 }
1252
1253 #[test]
1254 fn accepts_public_url() {
1255 assert!(validate_webhook_url("https://example.com/webhook").is_ok());
1256 }
1257
1258 #[test]
1259 fn accepts_public_ip() {
1260 assert!(validate_webhook_url("https://203.0.113.1/webhook").is_ok());
1261 }
1262
1263 #[test]
1264 fn rejects_header_with_crlf() {
1265 assert!(validate_header_value("token\r\nX-Injected: value", "test").is_err());
1266 }
1267
1268 #[test]
1269 fn rejects_header_with_cr() {
1270 assert!(validate_header_value("token\rvalue", "test").is_err());
1271 }
1272
1273 #[test]
1274 fn rejects_header_with_lf() {
1275 assert!(validate_header_value("token\nvalue", "test").is_err());
1276 }
1277
1278 #[test]
1279 fn accepts_clean_header_value() {
1280 assert!(validate_header_value("Bearer abc123+/=", "test").is_ok());
1281 }
1282
1283 #[test]
1284 fn rejects_url_without_scheme() {
1285 assert!(validate_webhook_url("example.com/webhook").is_err());
1286 }
1287
1288 #[test]
1289 fn rejects_ftp_scheme() {
1290 assert!(validate_webhook_url("ftp://example.com/webhook").is_err());
1291 }
1292
1293 #[test]
1294 fn rejects_file_scheme() {
1295 assert!(validate_webhook_url("file:///etc/passwd").is_err());
1296 }
1297
1298 #[test]
1299 fn accepts_http_scheme() {
1300 assert!(validate_webhook_url("http://example.com/webhook").is_ok());
1301 }
1302
1303 #[test]
1304 fn rejects_cgnat_range() {
1305 assert!(validate_webhook_url("http://100.64.0.1/webhook").is_err());
1306 }
1307
1308 #[test]
1309 fn rejects_unspecified_ipv4() {
1310 assert!(validate_webhook_url("http://0.0.0.0/webhook").is_err());
1311 }
1312
1313 #[test]
1314 fn rejects_ipv6_unique_local() {
1315 assert!(validate_webhook_url("http://[fc00::1]:8080/webhook").is_err());
1316 }
1317
1318 #[test]
1319 fn rejects_ipv6_link_local() {
1320 assert!(validate_webhook_url("http://[fe80::1]:8080/webhook").is_err());
1321 }
1322
1323 async fn validate_webhook_url_with_dns_default(
1326 url: &str,
1327 ) -> A2aResult<Option<Vec<SocketAddr>>> {
1328 validate_webhook_url_with_dns(url, DEFAULT_DNS_LOOKUP_TIMEOUT).await
1329 }
1330
1331 #[tokio::test(start_paused = true)]
1336 async fn a_hung_resolver_is_bounded_by_the_dns_timeout() {
1337 let started = tokio::time::Instant::now();
1338 let err = validate_webhook_url_with_resolver(
1339 "https://webhook.example/hook",
1340 std::time::Duration::from_secs(3),
1341 |_addr| std::future::pending::<std::io::Result<Vec<SocketAddr>>>(),
1342 )
1343 .await
1344 .expect_err("a lookup that never returns must not hold the delivery");
1345 assert_eq!(started.elapsed(), std::time::Duration::from_secs(3));
1346 assert!(
1347 err.message.contains("resolution timed out after 3s")
1348 && err.message.contains("webhook.example"),
1349 "got: {}",
1350 err.message
1351 );
1352 }
1353
1354 #[tokio::test]
1358 async fn the_resolver_seam_checks_and_pins_what_it_is_given() {
1359 let private = validate_webhook_url_with_resolver(
1360 "http://webhook.example/hook",
1361 std::time::Duration::from_secs(1),
1362 |_addr| async { Ok(vec!["10.0.0.7:80".parse().unwrap()]) },
1363 )
1364 .await
1365 .expect_err("a private answer is refused");
1366 assert!(
1367 private.message.contains("private/loopback"),
1368 "got: {}",
1369 private.message
1370 );
1371
1372 let pinned = validate_webhook_url_with_resolver(
1373 "http://webhook.example/hook",
1374 std::time::Duration::from_secs(1),
1375 |addr| async move {
1376 assert_eq!(
1377 addr, "webhook.example:80",
1378 "the lookup carries the scheme's port"
1379 );
1380 Ok(vec!["203.0.113.9:80".parse().unwrap()])
1381 },
1382 )
1383 .await
1384 .expect("a public answer is accepted");
1385 assert_eq!(pinned, Some(vec!["203.0.113.9:80".parse().unwrap()]));
1386 }
1387
1388 #[tokio::test]
1391 async fn dns_rejects_loopback_ip_literal() {
1392 let result = validate_webhook_url_with_dns_default("http://127.0.0.1:8080/webhook").await;
1394 assert!(result.is_err(), "loopback IP should be rejected");
1395 }
1396
1397 #[tokio::test]
1398 async fn dns_rejects_private_ip_literal() {
1399 let result = validate_webhook_url_with_dns_default("http://10.0.0.1/webhook").await;
1400 assert!(result.is_err(), "private IP should be rejected");
1401 }
1402
1403 #[tokio::test]
1404 async fn dns_rejects_localhost_hostname() {
1405 let result = validate_webhook_url_with_dns_default("http://localhost:8080/webhook").await;
1407 assert!(result.is_err(), "localhost should be rejected");
1408 }
1409
1410 #[tokio::test]
1411 async fn dns_rejects_invalid_scheme() {
1412 let result = validate_webhook_url_with_dns_default("ftp://example.com/webhook").await;
1413 assert!(result.is_err(), "ftp scheme should be rejected");
1414 }
1415
1416 #[tokio::test]
1417 async fn dns_rejects_missing_host() {
1418 let result = validate_webhook_url_with_dns_default("http:///path").await;
1419 assert!(result.is_err(), "missing host should be rejected");
1420 }
1421
1422 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1423 async fn dns_rejects_unresolvable_hostname() {
1424 let (tx, rx) = tokio::sync::oneshot::channel();
1427 std::thread::spawn(move || {
1428 let rt = tokio::runtime::Builder::new_current_thread()
1429 .enable_all()
1430 .build()
1431 .unwrap();
1432 let result = rt.block_on(validate_webhook_url_with_dns_default(
1433 "https://this-hostname-definitely-does-not-exist-a2a-test.invalid/webhook",
1434 ));
1435 let _ = tx.send(result);
1436 });
1437 match tokio::time::timeout(std::time::Duration::from_secs(5), rx).await {
1438 Ok(Ok(result)) => {
1439 assert!(result.is_err(), "unresolvable hostname should be rejected");
1440 }
1441 Ok(Err(_)) => panic!("sender dropped without sending"),
1442 Err(_elapsed) => {
1443 }
1445 }
1446 }
1447
1448 #[tokio::test]
1449 async fn dns_accepts_ip_literal_public() {
1450 let result = validate_webhook_url_with_dns_default("https://203.0.113.1/webhook").await;
1453 assert!(
1454 matches!(result, Ok(None)),
1455 "public IP literal should be accepted with no pinning (got {result:?})",
1456 );
1457 }
1458
1459 fn dummy_event() -> StreamResponse {
1462 use a2a_protocol_types::events::TaskStatusUpdateEvent;
1463 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
1464 StreamResponse::StatusUpdate(TaskStatusUpdateEvent::new(
1465 TaskId::new("t1"),
1466 ContextId::new("c1"),
1467 TaskStatus::with_timestamp(TaskState::Working),
1468 ))
1469 }
1470
1471 fn dummy_config(url: &str) -> TaskPushNotificationConfig {
1472 TaskPushNotificationConfig::new("t1".to_owned(), url.to_owned()).with_id("cfg".to_owned())
1473 }
1474
1475 #[cfg(not(feature = "tls-rustls"))]
1478 #[tokio::test]
1479 async fn https_without_tls_feature_fails_fast() {
1480 let sender = HttpPushSender::new();
1481 let event = dummy_event();
1482 let config = dummy_config("https://example.com/webhook");
1483 let err = sender
1484 .send(&config.url, &event, &config)
1485 .await
1486 .expect_err("https must fail fast without the tls-rustls feature");
1487 assert!(
1488 err.to_string().contains("HTTP only"),
1489 "expected the HTTP-only error, got: {err}"
1490 );
1491 }
1492
1493 #[cfg(feature = "tls-rustls")]
1497 #[tokio::test]
1498 async fn https_with_tls_feature_still_enforces_ssrf() {
1499 let sender = HttpPushSender::new();
1500 let event = dummy_event();
1501 let config = dummy_config("https://127.0.0.1:8443/webhook");
1502 let err = sender
1503 .send(&config.url, &event, &config)
1504 .await
1505 .expect_err("https to a loopback address must be rejected by SSRF");
1506 let msg = err.to_string();
1507 assert!(
1508 msg.contains("private/loopback") || msg.contains("loopback"),
1509 "expected an SSRF rejection (not the HTTP-only error), got: {msg}"
1510 );
1511 }
1512}
1513
1514#[cfg(test)]
1515mod port_tests {
1516 use super::webhook_port;
1517
1518 #[test]
1522 fn scheme_defaults_are_not_swapped() {
1523 let port = |u: &str| webhook_port(&u.parse::<hyper::Uri>().expect("uri"));
1524
1525 assert_eq!(
1526 port("https://example.com/hook"),
1527 443,
1528 "https defaults to 443"
1529 );
1530 assert_eq!(port("http://example.com/hook"), 80, "http defaults to 80");
1531 assert_eq!(port("https://example.com:8443/hook"), 8443);
1534 assert_eq!(port("http://example.com:8080/hook"), 8080);
1535 }
1536}