1use super::rpc::{SendStreamingMessageResponse, StreamingEvent, TaskPushNotificationConfig};
7use reqwest::Client;
8use std::time::Duration;
9use tracing::{debug, warn};
10use url::{Host, Url};
11
12pub(crate) fn parse_webhook_url(raw_url: &str) -> Result<Url, String> {
17 let url = Url::parse(raw_url).map_err(|error| format!("Webhook URL must be a valid absolute URL: {error}"))?;
18
19 if url.username() != "" || url.password().is_some() {
20 return Err("Webhook URL must not contain credentials".to_string());
21 }
22 if url.fragment().is_some() {
23 return Err("Webhook URL must not contain a fragment".to_string());
24 }
25
26 let is_loopback = matches!(
27 url.host(),
28 Some(Host::Domain(host)) if host.eq_ignore_ascii_case("localhost")
29 ) || matches!(url.host(), Some(Host::Ipv4(address)) if address.is_loopback())
30 || matches!(url.host(), Some(Host::Ipv6(address)) if address.is_loopback());
31
32 match url.scheme() {
33 "https" => Ok(url),
34 "http" if is_loopback => Ok(url),
35 "http" => Err("Webhook URL must use HTTPS unless it targets localhost".to_string()),
36 _ => Err("Webhook URL must use HTTPS or HTTP localhost".to_string()),
37 }
38}
39
40const WEBHOOK_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
42const WEBHOOK_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
44const WEBHOOK_MAX_RETRY_DELAY_MS: u64 = 30_000;
46
47#[derive(Debug, Clone)]
49pub struct WebhookNotifier {
50 client: Option<Client>,
51 max_retries: u32,
52 retry_delay_ms: u64,
53}
54
55impl Default for WebhookNotifier {
56 fn default() -> Self {
57 Self::new()
58 }
59}
60
61impl WebhookNotifier {
62 fn build_http_client() -> Option<Client> {
63 match Client::builder()
64 .timeout(WEBHOOK_REQUEST_TIMEOUT)
65 .connect_timeout(WEBHOOK_CONNECT_TIMEOUT)
66 .redirect(reqwest::redirect::Policy::none())
67 .build()
68 {
69 Ok(client) => Some(client),
70 Err(error) => {
71 warn!(error = %error, "Failed to configure webhook HTTP client; webhook delivery disabled");
72 None
73 }
74 }
75 }
76
77 pub(crate) fn new() -> Self {
79 Self {
80 client: Self::build_http_client(),
81 max_retries: 3,
82 retry_delay_ms: 1000,
83 }
84 }
85
86 fn with_settings(max_retries: u32, retry_delay_ms: u64) -> Self {
88 Self {
89 client: Self::build_http_client(),
90 max_retries,
91 retry_delay_ms,
92 }
93 }
94
95 pub(crate) async fn send_event(
97 &self,
98 config: &TaskPushNotificationConfig,
99 event: StreamingEvent,
100 ) -> Result<(), WebhookError> {
101 let response = SendStreamingMessageResponse { event };
102 let json = serde_json::to_string(&response).map_err(|e| WebhookError::Serialization(e.to_string()))?;
103 let url = parse_webhook_url(&config.url).map_err(WebhookError::InvalidUrl)?;
104
105 self.send_with_retry(&url, &json, config.authentication.as_deref()).await
106 }
107
108 fn retry_delay(&self, attempt: u32) -> Duration {
117 let exponent = attempt.saturating_sub(1);
118 let backoff_ms = self
119 .retry_delay_ms
120 .saturating_mul(2_u64.saturating_pow(exponent))
121 .min(WEBHOOK_MAX_RETRY_DELAY_MS);
122 let jitter_ms = (u64::from(exponent) * 31) % (backoff_ms / 4).saturating_add(1);
123 Duration::from_millis(backoff_ms.saturating_add(jitter_ms))
124 }
125
126 async fn send_with_retry(&self, url: &Url, json: &str, auth: Option<&str>) -> Result<(), WebhookError> {
128 let mut last_error = None;
129
130 for attempt in 0..=self.max_retries {
131 if attempt > 0 {
132 let delay = self.retry_delay(attempt); debug!("Retrying webhook delivery after {:?} (attempt {})", delay, attempt);
134 tokio::time::sleep(delay).await;
135 }
136
137 match self.send_request(url, json, auth).await {
138 Ok(()) => {
139 debug!("Webhook delivered successfully");
140 return Ok(());
141 }
142 Err(e) => {
143 warn!("Webhook delivery attempt {} failed: {}", attempt + 1, e);
144 if !is_retryable_webhook_error(&e) {
145 return Err(e);
146 }
147 last_error = Some(e);
148 }
149 }
150 }
151
152 Err(last_error.unwrap_or(WebhookError::Unknown))
153 }
154
155 async fn send_request(&self, url: &Url, json: &str, auth: Option<&str>) -> Result<(), WebhookError> {
157 let Some(client) = self.client.as_ref() else {
158 return Err(WebhookError::ClientUnavailable);
159 };
160
161 let mut request = client
162 .post(url.clone())
163 .header("Content-Type", "application/json")
164 .header("User-Agent", "VT Code-A2A/1.0");
165
166 if let Some(auth_header) = auth {
167 request = request.header("Authorization", auth_header);
168 }
169
170 let response = request
171 .body(json.to_string())
172 .send()
173 .await
174 .map_err(|e| WebhookError::Network(e.to_string()))?;
175
176 if response.status().is_success() {
177 Ok(())
178 } else {
179 Err(WebhookError::HttpError(response.status().as_u16()))
180 }
181 }
182}
183
184#[must_use]
188fn is_retryable_webhook_error(error: &WebhookError) -> bool {
189 match error {
190 WebhookError::Network(_) => true,
191 WebhookError::HttpError(status) => matches!(status, 429 | 500..=599),
192 WebhookError::Serialization(_)
193 | WebhookError::InvalidUrl(_)
194 | WebhookError::ClientUnavailable
195 | WebhookError::Unknown => false,
196 }
197}
198
199#[derive(Debug, Clone, thiserror::Error)]
201pub enum WebhookError {
202 #[error("Network error: {0}")]
204 Network(String),
205 #[error("HTTP error: {0}")]
207 HttpError(u16),
208 #[error("Serialization error: {0}")]
210 Serialization(String),
211 #[error("Invalid webhook URL: {0}")]
213 InvalidUrl(String),
214 #[error("Webhook HTTP client is unavailable")]
216 ClientUnavailable,
217 #[error("Unknown error")]
219 Unknown,
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225 use crate::types::{TaskState, TaskStatus};
226
227 #[test]
228 fn test_webhook_notifier_creation() {
229 let notifier = WebhookNotifier::new();
230 assert_eq!(notifier.max_retries, 3);
231 assert_eq!(notifier.retry_delay_ms, 1000);
232 }
233
234 #[test]
235 fn test_webhook_notifier_with_settings() {
236 let notifier = WebhookNotifier::with_settings(5, 2000);
237 assert_eq!(notifier.max_retries, 5);
238 assert_eq!(notifier.retry_delay_ms, 2000);
239 }
240
241 #[test]
242 fn test_webhook_retry_delay_doubles_and_saturates() {
243 let notifier = WebhookNotifier::with_settings(3, 1_000);
244 assert_eq!(notifier.retry_delay(1), Duration::from_millis(1_000));
246 assert_eq!(notifier.retry_delay(2), Duration::from_millis(2_031));
247 assert_eq!(notifier.retry_delay(3), Duration::from_millis(4_062));
248 assert_eq!(notifier.retry_delay(6), Duration::from_millis(30_155));
250 assert_eq!(notifier.retry_delay(3), notifier.retry_delay(3));
253 for attempt in [7, 100, u32::MAX] {
254 let delay = notifier.retry_delay(attempt);
255 assert!(
256 (Duration::from_millis(30_000)..=Duration::from_millis(37_500)).contains(&delay),
257 "attempt {attempt} delay {delay:?} escapes the 30s cap + jitter bound"
258 );
259 }
260 }
261
262 #[test]
263 fn webhook_retries_only_transient_failures() {
264 assert!(is_retryable_webhook_error(&WebhookError::Network("connection reset".to_string())));
265 for status in [429, 500, 502, 503, 504] {
268 assert!(is_retryable_webhook_error(&WebhookError::HttpError(status)), "HTTP {status} must retry");
269 }
270 for status in [400, 401, 403, 404] {
271 assert!(!is_retryable_webhook_error(&WebhookError::HttpError(status)), "HTTP {status} must fail fast");
272 }
273 assert!(!is_retryable_webhook_error(&WebhookError::Serialization("bad json".to_string())));
274 assert!(!is_retryable_webhook_error(&WebhookError::InvalidUrl("ftp://example.test/hook".to_string())));
275 assert!(!is_retryable_webhook_error(&WebhookError::ClientUnavailable));
276 assert!(!is_retryable_webhook_error(&WebhookError::Unknown));
277 }
278
279 #[test]
280 fn test_parse_webhook_url_requires_safe_scheme_and_host() {
281 for url in [
282 "https://example.com/webhook",
283 "http://localhost/webhook",
284 "http://127.0.0.1:8080/webhook",
285 "http://[::1]:8080/webhook",
286 ] {
287 assert!(parse_webhook_url(url).is_ok(), "URL should be accepted: {url}");
288 }
289
290 for url in [
291 "http://localhost.evil.example/webhook",
292 "http://localhost@evil.example/webhook",
293 "http://example.com/webhook",
294 "ftp://example.com/webhook",
295 "https://user:password@example.com/webhook",
296 "https://example.com/webhook#fragment",
297 ] {
298 assert!(parse_webhook_url(url).is_err(), "URL should be rejected: {url}");
299 }
300 }
301
302 #[tokio::test]
303 async fn test_webhook_error_display() {
304 let err = WebhookError::Network("Connection refused".to_string());
305 assert!(err.to_string().contains("Network error"));
306
307 let err = WebhookError::HttpError(404);
308 assert!(err.to_string().contains("404"));
309 }
310
311 #[tokio::test]
312 async fn test_send_event_serialization() {
313 let notifier = WebhookNotifier::new();
314 let config = TaskPushNotificationConfig {
315 task_id: "task-1".to_string(),
316 url: "https://example.com/webhook".to_string(),
317 authentication: None,
318 };
319
320 let event = StreamingEvent::TaskStatus {
321 task_id: "task-1".to_string(),
322 context_id: None,
323 status: TaskStatus::new(TaskState::Completed),
324 kind: "status-update".to_string(),
325 r#final: true,
326 };
327
328 let result = notifier.send_event(&config, event).await;
331 assert!(result.is_err());
332
333 if let Err(WebhookError::Serialization(_)) = result {
334 panic!("Unexpected serialization error");
335 }
336 }
337
338 #[tokio::test]
339 async fn test_send_event_rejects_invalid_url_before_network_access() {
340 let notifier = WebhookNotifier::new();
341 let config = TaskPushNotificationConfig {
342 task_id: "task-1".to_string(),
343 url: "http://localhost.evil.example/webhook".to_string(),
344 authentication: None,
345 };
346 let event = StreamingEvent::Unknown;
347
348 let result = notifier.send_event(&config, event).await;
349 assert!(matches!(result, Err(WebhookError::InvalidUrl(_))));
350 }
351
352 #[tokio::test]
353 async fn test_webhook_client_does_not_follow_redirects() {
354 use tokio::io::{AsyncReadExt, AsyncWriteExt};
355 use tokio::net::TcpListener;
356
357 let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind test listener");
358 let address = listener.local_addr().expect("read test listener address");
359 let server = tokio::spawn(async move {
360 let (mut socket, _) = listener.accept().await.expect("accept initial webhook");
361 let mut request = [0; 1024];
362 let _ignored = socket.read(&mut request).await.expect("read initial webhook");
363 let redirect = format!(
364 "HTTP/1.1 302 Found\r\nLocation: http://{address}/redirect-target\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
365 );
366 socket.write_all(redirect.as_bytes()).await.expect("send redirect");
367
368 match tokio::time::timeout(Duration::from_millis(250), listener.accept()).await {
369 Ok(Ok((mut redirected_socket, _))) => {
370 let mut request = [0; 1024];
371 let _ignored = redirected_socket.read(&mut request).await.expect("read redirected webhook");
372 let response = b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
373 redirected_socket.write_all(response).await.expect("send redirected response");
374 true
375 }
376 Ok(Err(_)) | Err(_) => false,
377 }
378 });
379
380 let notifier = WebhookNotifier::with_settings(0, 0);
381 let config = TaskPushNotificationConfig {
382 task_id: "task-1".to_string(),
383 url: format!("http://{address}/hook"),
384 authentication: None,
385 };
386 let result = notifier.send_event(&config, StreamingEvent::Unknown).await;
387 assert!(matches!(result, Err(WebhookError::HttpError(302))));
388 assert!(!server.await.expect("join test server"));
389 }
390}