1use anyhow::{anyhow, Context, Result};
6use reqwest::Client;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::net::IpAddr;
10use std::sync::Arc;
11use std::time::Duration;
12use tokio::sync::RwLock;
13use tracing::{debug, error, info, warn};
14
15const MAX_STORED_RESPONSE_BYTES: usize = 64 * 1024;
18
19fn is_disallowed_ip(ip: &IpAddr) -> bool {
23 match ip {
24 IpAddr::V4(v4) => {
25 v4.is_loopback()
26 || v4.is_private()
27 || v4.is_link_local() || v4.is_unspecified()
29 || v4.is_broadcast()
30 || v4.is_documentation()
31 || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64)
33 }
34 IpAddr::V6(v6) => {
35 v6.is_loopback()
36 || v6.is_unspecified()
37 || (v6.segments()[0] & 0xfe00) == 0xfc00
39 || (v6.segments()[0] & 0xffc0) == 0xfe80
41 || v6
43 .to_ipv4_mapped()
44 .map(|v4| is_disallowed_ip(&IpAddr::V4(v4)))
45 .unwrap_or(false)
46 }
47 }
48}
49
50async fn validate_webhook_target(url_str: &str) -> Result<()> {
57 let url = reqwest::Url::parse(url_str).context("invalid webhook URL")?;
58 match url.scheme() {
59 "http" | "https" => {}
60 other => return Err(anyhow!("webhook URL scheme '{other}' is not allowed")),
61 }
62 let host = url
63 .host_str()
64 .ok_or_else(|| anyhow!("webhook URL has no host"))?;
65 let host_lower = host.to_ascii_lowercase();
66 if host_lower == "localhost"
67 || host_lower.ends_with(".local")
68 || host_lower.ends_with(".internal")
69 || host_lower.ends_with(".localhost")
70 {
71 return Err(anyhow!("webhook host '{host}' is not allowed"));
72 }
73
74 if let Ok(ip) = host.parse::<IpAddr>() {
76 if is_disallowed_ip(&ip) {
77 return Err(anyhow!("webhook host '{host}' is a disallowed address"));
78 }
79 return Ok(());
80 }
81
82 let port = url.port_or_known_default().unwrap_or(0);
83 let addrs = tokio::net::lookup_host((host, port))
84 .await
85 .with_context(|| format!("failed to resolve webhook host '{host}'"))?;
86 let mut any = false;
87 for addr in addrs {
88 any = true;
89 if is_disallowed_ip(&addr.ip()) {
90 return Err(anyhow!(
91 "webhook host '{host}' resolves to a disallowed address {}",
92 addr.ip()
93 ));
94 }
95 }
96 if !any {
97 return Err(anyhow!("webhook host '{host}' did not resolve"));
98 }
99 Ok(())
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
104pub enum WebhookEvent {
105 MessageReceived,
107 MessageSent,
109 SessionCreated,
111 SessionEnded,
113 QueryExecuted,
115 ErrorOccurred,
117 Custom,
119}
120
121impl WebhookEvent {
122 pub fn as_str(&self) -> &str {
124 match self {
125 WebhookEvent::MessageReceived => "message.received",
126 WebhookEvent::MessageSent => "message.sent",
127 WebhookEvent::SessionCreated => "session.created",
128 WebhookEvent::SessionEnded => "session.ended",
129 WebhookEvent::QueryExecuted => "query.executed",
130 WebhookEvent::ErrorOccurred => "error.occurred",
131 WebhookEvent::Custom => "custom",
132 }
133 }
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct WebhookPayload {
139 pub event: String,
141 pub timestamp: chrono::DateTime<chrono::Utc>,
143 pub session_id: String,
145 pub data: serde_json::Value,
147 pub webhook_id: String,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct WebhookConfig {
154 pub id: String,
156 pub url: String,
158 pub events: Vec<WebhookEvent>,
160 pub headers: HashMap<String, String>,
162 pub secret: Option<String>,
164 pub timeout: Duration,
166 pub retry_policy: RetryPolicy,
168 pub enabled: bool,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct RetryPolicy {
175 pub max_retries: usize,
177 pub initial_backoff: Duration,
179 pub max_backoff: Duration,
181 pub backoff_multiplier: f64,
183}
184
185impl Default for RetryPolicy {
186 fn default() -> Self {
187 Self {
188 max_retries: 3,
189 initial_backoff: Duration::from_secs(1),
190 max_backoff: Duration::from_secs(60),
191 backoff_multiplier: 2.0,
192 }
193 }
194}
195
196impl Default for WebhookConfig {
197 fn default() -> Self {
198 Self {
199 id: uuid::Uuid::new_v4().to_string(),
200 url: String::new(),
201 events: vec![],
202 headers: HashMap::new(),
203 secret: None,
204 timeout: Duration::from_secs(30),
205 retry_policy: RetryPolicy::default(),
206 enabled: true,
207 }
208 }
209}
210
211#[derive(Debug, Clone)]
213pub struct WebhookDeliveryResult {
214 pub webhook_id: String,
216 pub success: bool,
218 pub status_code: Option<u16>,
220 pub response_body: Option<String>,
222 pub error: Option<String>,
224 pub attempts: usize,
226 pub duration: Duration,
228}
229
230pub struct WebhookManager {
232 webhooks: Arc<RwLock<HashMap<String, WebhookConfig>>>,
233 client: Client,
234 delivery_history: Arc<RwLock<Vec<WebhookDeliveryResult>>>,
235}
236
237impl WebhookManager {
238 pub fn new() -> Result<Self> {
240 let client = Client::builder()
241 .timeout(Duration::from_secs(30))
242 .redirect(reqwest::redirect::Policy::none())
245 .build()
246 .context("Failed to create HTTP client")?;
247
248 info!("Initialized webhook manager");
249
250 Ok(Self {
251 webhooks: Arc::new(RwLock::new(HashMap::new())),
252 client,
253 delivery_history: Arc::new(RwLock::new(Vec::new())),
254 })
255 }
256
257 pub async fn register(&self, config: WebhookConfig) -> Result<()> {
263 info!("Registering webhook: {} for URL: {}", config.id, config.url);
264
265 validate_webhook_target(&config.url)
266 .await
267 .with_context(|| format!("rejected webhook URL '{}'", config.url))?;
268
269 let mut webhooks = self.webhooks.write().await;
270 webhooks.insert(config.id.clone(), config);
271
272 Ok(())
273 }
274
275 pub async fn unregister(&self, webhook_id: &str) -> Result<()> {
277 info!("Unregistering webhook: {}", webhook_id);
278
279 let mut webhooks = self.webhooks.write().await;
280 webhooks.remove(webhook_id);
281
282 Ok(())
283 }
284
285 pub async fn trigger(
287 &self,
288 event: WebhookEvent,
289 session_id: String,
290 data: serde_json::Value,
291 ) -> Result<()> {
292 debug!(
293 "Triggering webhook event: {:?} for session: {}",
294 event, session_id
295 );
296
297 let webhooks = self.webhooks.read().await;
298
299 for webhook in webhooks.values() {
300 if !webhook.enabled {
301 continue;
302 }
303
304 if !webhook.events.contains(&event) {
305 continue;
306 }
307
308 let payload = WebhookPayload {
309 event: event.as_str().to_string(),
310 timestamp: chrono::Utc::now(),
311 session_id: session_id.clone(),
312 data: data.clone(),
313 webhook_id: webhook.id.clone(),
314 };
315
316 let webhook_clone = webhook.clone();
318 let client = self.client.clone();
319 let delivery_history = self.delivery_history.clone();
320
321 tokio::spawn(async move {
322 let result = Self::deliver_webhook(&client, &webhook_clone, &payload).await;
323
324 let mut history = delivery_history.write().await;
326 history.push(result);
327
328 if history.len() > 1000 {
330 history.remove(0);
331 }
332 });
333 }
334
335 Ok(())
336 }
337
338 async fn deliver_webhook(
340 client: &Client,
341 webhook: &WebhookConfig,
342 payload: &WebhookPayload,
343 ) -> WebhookDeliveryResult {
344 let start = std::time::Instant::now();
345 let mut attempts = 0;
346 let mut backoff = webhook.retry_policy.initial_backoff;
347
348 if let Err(e) = validate_webhook_target(&webhook.url).await {
351 error!("Blocked webhook delivery to {}: {}", webhook.url, e);
352 return WebhookDeliveryResult {
353 webhook_id: webhook.id.clone(),
354 success: false,
355 status_code: None,
356 response_body: None,
357 error: Some(format!("blocked by SSRF egress policy: {e}")),
358 attempts: 0,
359 duration: start.elapsed(),
360 };
361 }
362
363 loop {
364 attempts += 1;
365
366 debug!(
367 "Delivering webhook to {} (attempt {})",
368 webhook.url, attempts
369 );
370
371 let mut request = client
372 .post(&webhook.url)
373 .timeout(webhook.timeout)
374 .json(&payload);
375
376 for (key, value) in &webhook.headers {
378 request = request.header(key, value);
379 }
380
381 if let Some(ref secret) = webhook.secret {
383 let signature = Self::generate_signature(payload, secret);
384 request = request.header("X-Webhook-Signature", signature);
385 }
386
387 match request.send().await {
388 Ok(response) => {
389 let status = response.status();
390 let body = response.bytes().await.ok().map(|bytes| {
391 let capped = &bytes[..bytes.len().min(MAX_STORED_RESPONSE_BYTES)];
392 String::from_utf8_lossy(capped).into_owned()
393 });
394
395 if status.is_success() {
396 info!("Webhook delivered successfully to {}", webhook.url);
397
398 return WebhookDeliveryResult {
399 webhook_id: webhook.id.clone(),
400 success: true,
401 status_code: Some(status.as_u16()),
402 response_body: body,
403 error: None,
404 attempts,
405 duration: start.elapsed(),
406 };
407 } else {
408 warn!(
409 "Webhook delivery failed with status {}: {}",
410 status, webhook.url
411 );
412
413 if attempts >= webhook.retry_policy.max_retries {
414 return WebhookDeliveryResult {
415 webhook_id: webhook.id.clone(),
416 success: false,
417 status_code: Some(status.as_u16()),
418 response_body: body,
419 error: Some(format!("Failed with status {}", status)),
420 attempts,
421 duration: start.elapsed(),
422 };
423 }
424 }
425 }
426 Err(e) => {
427 error!("Webhook delivery error to {}: {}", webhook.url, e);
428
429 if attempts >= webhook.retry_policy.max_retries {
430 return WebhookDeliveryResult {
431 webhook_id: webhook.id.clone(),
432 success: false,
433 status_code: None,
434 response_body: None,
435 error: Some(e.to_string()),
436 attempts,
437 duration: start.elapsed(),
438 };
439 }
440 }
441 }
442
443 tokio::time::sleep(backoff).await;
445
446 backoff = Duration::from_secs_f64(
448 (backoff.as_secs_f64() * webhook.retry_policy.backoff_multiplier)
449 .min(webhook.retry_policy.max_backoff.as_secs_f64()),
450 );
451 }
452 }
453
454 fn generate_signature(payload: &WebhookPayload, secret: &str) -> String {
456 use hmac::{Hmac, KeyInit, Mac};
457 use sha2::Sha256;
458
459 type HmacSha256 = Hmac<Sha256>;
460
461 let payload_json = serde_json::to_string(payload).unwrap_or_default();
462
463 let mut mac =
464 HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC can take key of any size");
465 mac.update(payload_json.as_bytes());
466
467 let result = mac.finalize();
468 let hex_string = result
469 .into_bytes()
470 .iter()
471 .map(|b| format!("{:02x}", b))
472 .collect::<String>();
473 format!("sha256={}", hex_string)
474 }
475
476 pub async fn get_delivery_history(&self, limit: usize) -> Vec<WebhookDeliveryResult> {
478 let history = self.delivery_history.read().await;
479 history.iter().rev().take(limit).cloned().collect()
480 }
481
482 pub async fn get_statistics(&self) -> WebhookStatistics {
484 let history = self.delivery_history.read().await;
485
486 let total_deliveries = history.len();
487 let successful_deliveries = history.iter().filter(|d| d.success).count();
488 let failed_deliveries = total_deliveries - successful_deliveries;
489
490 let average_duration = if !history.is_empty() {
491 history.iter().map(|d| d.duration.as_millis()).sum::<u128>() / history.len() as u128
492 } else {
493 0
494 };
495
496 WebhookStatistics {
497 total_deliveries,
498 successful_deliveries,
499 failed_deliveries,
500 average_duration_ms: average_duration,
501 }
502 }
503
504 pub async fn list_webhooks(&self) -> Vec<WebhookConfig> {
506 let webhooks = self.webhooks.read().await;
507 webhooks.values().cloned().collect()
508 }
509}
510
511impl Default for WebhookManager {
512 fn default() -> Self {
513 Self::new().expect("Failed to create webhook manager")
514 }
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize)]
519pub struct WebhookStatistics {
520 pub total_deliveries: usize,
522 pub successful_deliveries: usize,
524 pub failed_deliveries: usize,
526 pub average_duration_ms: u128,
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533
534 #[tokio::test]
535 async fn test_webhook_registration() {
536 let manager = WebhookManager::new().expect("should succeed");
537
538 let config = WebhookConfig {
539 id: "test-webhook".to_string(),
540 url: "https://93.184.216.34/webhook".to_string(),
543 events: vec![WebhookEvent::MessageReceived],
544 ..Default::default()
545 };
546
547 manager.register(config).await.expect("should succeed");
548
549 let webhooks = manager.list_webhooks().await;
550 assert_eq!(webhooks.len(), 1);
551 assert_eq!(webhooks[0].id, "test-webhook");
552 }
553
554 #[tokio::test]
557 async fn regression_webhook_ssrf_internal_targets_rejected() {
558 let manager = WebhookManager::new().expect("should succeed");
559 for url in [
560 "http://127.0.0.1/hook",
561 "http://169.254.169.254/latest/meta-data/",
562 "http://10.0.0.5/hook",
563 "http://192.168.1.10/hook",
564 "http://localhost:8080/hook",
565 "https://[::1]/hook",
566 "ftp://93.184.216.34/hook",
567 ] {
568 let config = WebhookConfig {
569 id: format!("bad-{url}"),
570 url: url.to_string(),
571 events: vec![WebhookEvent::MessageReceived],
572 ..Default::default()
573 };
574 assert!(
575 manager.register(config).await.is_err(),
576 "internal/invalid target must be rejected: {url}"
577 );
578 }
579 assert!(manager.list_webhooks().await.is_empty());
580 }
581
582 #[test]
585 fn regression_is_disallowed_ip_classification() {
586 use std::net::IpAddr;
587 for ip in [
588 "127.0.0.1",
589 "10.1.2.3",
590 "192.168.0.1",
591 "172.16.5.5",
592 "169.254.169.254",
593 "100.64.0.1",
594 "0.0.0.0",
595 "::1",
596 "fe80::1",
597 "fc00::1",
598 ] {
599 assert!(
600 is_disallowed_ip(&ip.parse::<IpAddr>().expect("ip")),
601 "{ip} should be disallowed"
602 );
603 }
604 for ip in [
605 "93.184.216.34",
606 "8.8.8.8",
607 "1.1.1.1",
608 "2606:4700:4700::1111",
609 ] {
610 assert!(
611 !is_disallowed_ip(&ip.parse::<IpAddr>().expect("ip")),
612 "{ip} should be allowed"
613 );
614 }
615 }
616
617 #[tokio::test]
618 async fn test_webhook_event_names() {
619 assert_eq!(WebhookEvent::MessageReceived.as_str(), "message.received");
620 assert_eq!(WebhookEvent::SessionCreated.as_str(), "session.created");
621 }
622}