Skip to main content

oxirs_chat/
webhooks.rs

1//! Webhook System
2//!
3//! Provides webhook support for event notifications and integrations.
4
5use 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
15/// Maximum number of response body bytes retained in delivery history, to bound
16/// per-entry memory regardless of how large a webhook endpoint's response is.
17const MAX_STORED_RESPONSE_BYTES: usize = 64 * 1024;
18
19/// True if `ip` is an internal / non-routable address a webhook must never be
20/// allowed to target (SSRF egress guard: loopback, private, link-local incl. the
21/// cloud metadata endpoint, CGNAT, unspecified, ULA).
22fn 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() // covers 169.254.0.0/16 (metadata 169.254.169.254)
28                || v4.is_unspecified()
29                || v4.is_broadcast()
30                || v4.is_documentation()
31                // Carrier-grade NAT 100.64.0.0/10 (not covered by std helpers).
32                || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64)
33        }
34        IpAddr::V6(v6) => {
35            v6.is_loopback()
36                || v6.is_unspecified()
37                // Unique local addresses fc00::/7.
38                || (v6.segments()[0] & 0xfe00) == 0xfc00
39                // Link-local unicast fe80::/10.
40                || (v6.segments()[0] & 0xffc0) == 0xfe80
41                // IPv4-mapped addresses whose embedded v4 is disallowed.
42                || v6
43                    .to_ipv4_mapped()
44                    .map(|v4| is_disallowed_ip(&IpAddr::V4(v4)))
45                    .unwrap_or(false)
46        }
47    }
48}
49
50/// Validate a webhook target URL against the SSRF egress policy.
51///
52/// Rejects non-HTTP(S) schemes, obvious internal names, and any host that
53/// resolves to a loopback/private/link-local/metadata address. Resolution is
54/// performed here (at registration and again at delivery) so both a literal
55/// internal IP and a hostname pointing at one are caught.
56async 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 the host is an IP literal, check it directly; otherwise resolve it.
75    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/// Webhook event types
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
104pub enum WebhookEvent {
105    /// New message received
106    MessageReceived,
107    /// Message sent
108    MessageSent,
109    /// Session created
110    SessionCreated,
111    /// Session ended
112    SessionEnded,
113    /// Query executed
114    QueryExecuted,
115    /// Error occurred
116    ErrorOccurred,
117    /// Custom event
118    Custom,
119}
120
121impl WebhookEvent {
122    /// Get event name as string
123    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/// Webhook payload
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct WebhookPayload {
139    /// Event type
140    pub event: String,
141    /// Timestamp
142    pub timestamp: chrono::DateTime<chrono::Utc>,
143    /// Session ID
144    pub session_id: String,
145    /// Event data
146    pub data: serde_json::Value,
147    /// Webhook ID
148    pub webhook_id: String,
149}
150
151/// Webhook configuration
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct WebhookConfig {
154    /// Webhook ID
155    pub id: String,
156    /// Webhook URL
157    pub url: String,
158    /// Events to subscribe to
159    pub events: Vec<WebhookEvent>,
160    /// Custom headers
161    pub headers: HashMap<String, String>,
162    /// Secret for signature verification
163    pub secret: Option<String>,
164    /// Timeout duration
165    pub timeout: Duration,
166    /// Retry policy
167    pub retry_policy: RetryPolicy,
168    /// Is enabled
169    pub enabled: bool,
170}
171
172/// Retry policy for failed webhooks
173#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct RetryPolicy {
175    /// Maximum number of retries
176    pub max_retries: usize,
177    /// Initial backoff duration
178    pub initial_backoff: Duration,
179    /// Maximum backoff duration
180    pub max_backoff: Duration,
181    /// Backoff multiplier
182    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/// Webhook delivery result
212#[derive(Debug, Clone)]
213pub struct WebhookDeliveryResult {
214    /// Webhook ID
215    pub webhook_id: String,
216    /// Success status
217    pub success: bool,
218    /// Response status code
219    pub status_code: Option<u16>,
220    /// Response body
221    pub response_body: Option<String>,
222    /// Error message
223    pub error: Option<String>,
224    /// Delivery attempts
225    pub attempts: usize,
226    /// Delivery duration
227    pub duration: Duration,
228}
229
230/// Webhook manager
231pub struct WebhookManager {
232    webhooks: Arc<RwLock<HashMap<String, WebhookConfig>>>,
233    client: Client,
234    delivery_history: Arc<RwLock<Vec<WebhookDeliveryResult>>>,
235}
236
237impl WebhookManager {
238    /// Create a new webhook manager
239    pub fn new() -> Result<Self> {
240        let client = Client::builder()
241            .timeout(Duration::from_secs(30))
242            // Do not follow redirects: a 3xx to an internal host would bypass
243            // the SSRF egress checks performed against the original URL.
244            .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    /// Register a webhook.
258    ///
259    /// The target URL is validated against the SSRF egress policy (no
260    /// loopback/private/link-local/metadata hosts) and rejected fail-loud here
261    /// so an untrusted tenant cannot register an internal target.
262    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    /// Unregister a webhook
276    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    /// Trigger a webhook event
286    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            // Deliver webhook asynchronously
317            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                // Store delivery result
325                let mut history = delivery_history.write().await;
326                history.push(result);
327
328                // Keep only last 1000 deliveries
329                if history.len() > 1000 {
330                    history.remove(0);
331                }
332            });
333        }
334
335        Ok(())
336    }
337
338    /// Deliver a webhook with retry logic
339    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        // SSRF egress guard: re-validate the target at delivery time (defends
349        // against records mutated after registration and DNS-rebinding).
350        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            // Add custom headers
377            for (key, value) in &webhook.headers {
378                request = request.header(key, value);
379            }
380
381            // Add signature if secret is configured
382            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            // Wait before retry
444            tokio::time::sleep(backoff).await;
445
446            // Increase backoff
447            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    /// Generate HMAC signature for webhook payload
455    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    /// Get delivery history
477    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    /// Get webhook statistics
483    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    /// List all registered webhooks
505    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/// Webhook statistics
518#[derive(Debug, Clone, Serialize, Deserialize)]
519pub struct WebhookStatistics {
520    /// Total deliveries
521    pub total_deliveries: usize,
522    /// Successful deliveries
523    pub successful_deliveries: usize,
524    /// Failed deliveries
525    pub failed_deliveries: usize,
526    /// Average delivery duration (ms)
527    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            // Public routable IP literal — avoids requiring DNS in the test env
541            // while still passing the SSRF egress policy.
542            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    /// Regression: SSRF egress guard rejects internal webhook targets at
555    /// registration (loopback, private, and cloud-metadata addresses).
556    #[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    /// Regression: the IP egress classifier flags internal ranges and permits
583    /// public addresses.
584    #[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}