Skip to main content

adk_awp/
events.rs

1//! AWP event subscription system with signed webhook delivery.
2//!
3//! [`InMemoryEventSubscriptionService`] delivers every matching event over HTTP through
4//! [`WebhookDelivery`]: [Standard Webhooks](adk_core::webhook) signatures keyed with the
5//! subscription's secret bytes, the event id as the stable `webhook-id`, retries with
6//! exponential backoff and jitter, a dead-letter sink, and an egress guard that refuses
7//! internal destinations.
8
9use std::sync::Arc;
10
11use adk_core::egress::EgressPolicy;
12use adk_core::webhook::WebhookSecret;
13use adk_core::webhook_delivery::{
14    DeliveryReport, WebhookDelivery, WebhookEndpoint, WebhookMessage,
15};
16use async_trait::async_trait;
17use awp_types::AwpError;
18use chrono::{DateTime, Utc};
19use dashmap::DashMap;
20use hmac::{Hmac, Mac};
21use serde::{Deserialize, Serialize};
22use sha2::Sha256;
23use uuid::Uuid;
24
25type HmacSha256 = Hmac<Sha256>;
26
27/// An AWP event to be delivered to subscribers.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30pub struct AwpEvent {
31    /// Unique event identifier.
32    pub id: Uuid,
33    /// Event type (e.g. `"health.changed"`, `"consent.captured"`).
34    pub event_type: String,
35    /// When the event occurred.
36    pub timestamp: DateTime<Utc>,
37    /// Event payload.
38    pub payload: serde_json::Value,
39}
40
41/// A webhook subscription for AWP events.
42///
43/// The HMAC secret never leaves this process: it is skipped on serialization and redacted in
44/// `Debug`. Listing subscriptions previously returned every subscriber's signing secret in the
45/// response body, which let anyone who could read the list forge signed deliveries to that
46/// endpoint.
47#[derive(Clone, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub struct EventSubscription {
50    /// Unique subscription identifier.
51    pub id: Uuid,
52    /// Human-readable subscriber name.
53    pub subscriber: String,
54    /// URL to POST events to.
55    pub callback_url: String,
56    /// Event types this subscription listens for.
57    pub event_types: Vec<String>,
58    /// Shared secret for HMAC-SHA256 signing.
59    ///
60    /// Skipped on serialization so it cannot reach an HTTP response. Deserialization still
61    /// accepts it, defaulting to empty, so a stored subscription can be loaded.
62    #[serde(skip_serializing, default)]
63    pub secret: String,
64}
65
66impl std::fmt::Debug for EventSubscription {
67    /// Redacts the signing secret.
68    ///
69    /// The derived implementation printed it, so any `tracing` call that captured a
70    /// subscription would have written a live credential to the logs.
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("EventSubscription")
73            .field("id", &self.id)
74            .field("subscriber", &self.subscriber)
75            .field("callback_url", &self.callback_url)
76            .field("event_types", &self.event_types)
77            .field("secret", &"<redacted>")
78            .finish()
79    }
80}
81
82impl EventSubscription {
83    /// Validates the bounded subscription fields accepted by the built-in service.
84    ///
85    /// Callback URLs require HTTPS and must not name a loopback, private, link-local,
86    /// cloud metadata or other non-public address; see [`EgressPolicy`].
87    ///
88    /// # Errors
89    ///
90    /// Returns [`AwpError::InvalidRequest`] when a field is missing, oversized,
91    /// insecure, or malformed.
92    pub fn validate(&self) -> Result<(), AwpError> {
93        self.validate_with(&EgressPolicy::default())
94    }
95
96    /// Validates the subscription against the destinations `egress` allows.
97    ///
98    /// # Errors
99    ///
100    /// Same as [`validate`](Self::validate).
101    pub fn validate_with(&self, egress: &EgressPolicy) -> Result<(), AwpError> {
102        if self.subscriber.trim().is_empty() || self.subscriber.len() > 256 {
103            return Err(AwpError::InvalidRequest(
104                "subscriber must contain 1 to 256 bytes".to_string(),
105            ));
106        }
107        if self.callback_url.len() > 2_048 {
108            return Err(AwpError::InvalidRequest(
109                "callbackUrl must not exceed 2048 bytes".to_string(),
110            ));
111        }
112        let callback = self.callback_url.parse::<http::Uri>().map_err(|_| {
113            AwpError::InvalidRequest("callbackUrl must be a valid absolute HTTPS URL".to_string())
114        })?;
115        let scheme_allowed = callback.scheme_str() == Some("https")
116            || (egress.allows_plain_http() && callback.scheme_str() == Some("http"));
117        if !scheme_allowed || callback.authority().is_none() {
118            return Err(AwpError::InvalidRequest(
119                "callbackUrl must be a valid absolute HTTPS URL".to_string(),
120            ));
121        }
122        egress
123            .check_url(&self.callback_url)
124            .map_err(|reason| AwpError::InvalidRequest(format!("callbackUrl refused: {reason}")))?;
125        if self.event_types.len() > 64 {
126            return Err(AwpError::InvalidRequest(
127                "eventTypes must not contain more than 64 entries".to_string(),
128            ));
129        }
130        if self
131            .event_types
132            .iter()
133            .any(|event_type| event_type.trim().is_empty() || event_type.len() > 128)
134        {
135            return Err(AwpError::InvalidRequest(
136                "each eventTypes entry must contain 1 to 128 bytes".to_string(),
137            ));
138        }
139        if self.secret.len() < 32 || self.secret.len() > 4_096 {
140            return Err(AwpError::InvalidRequest(
141                "secret must contain 32 to 4096 bytes".to_string(),
142            ));
143        }
144
145        Ok(())
146    }
147}
148
149/// Trait for managing event subscriptions and delivering events.
150#[async_trait]
151pub trait EventSubscriptionService: Send + Sync {
152    /// Create a new subscription, returning its ID.
153    async fn create(&self, subscription: EventSubscription) -> Result<Uuid, AwpError>;
154
155    /// Get a subscription by ID.
156    async fn get(&self, id: Uuid) -> Result<Option<EventSubscription>, AwpError>;
157
158    /// List all subscriptions.
159    async fn list(&self) -> Result<Vec<EventSubscription>, AwpError>;
160
161    /// Delete a subscription by ID.
162    async fn delete(&self, id: Uuid) -> Result<(), AwpError>;
163
164    /// Deliver an event to all matching subscribers.
165    async fn deliver(&self, event: AwpEvent) -> Result<(), AwpError>;
166}
167
168/// In-memory event subscription service backed by [`DashMap`] that delivers over HTTP.
169///
170/// [`deliver`](EventSubscriptionService::deliver) starts one background delivery per
171/// matching subscription and returns at once, so a health transition never waits on a
172/// slow subscriber. [`deliver_and_wait`](Self::deliver_and_wait) waits for the reports.
173/// Receivers verify deliveries with Standard Webhooks, using the subscription secret's
174/// bytes as the key (its `whsec_` form is `WebhookSecret::from_bytes(secret).to_whsec()`).
175///
176/// # Example
177///
178/// ```rust
179/// use std::sync::Arc;
180/// use adk_awp::InMemoryEventSubscriptionService;
181/// use adk_core::webhook_delivery::{InMemoryDeadLetterSink, RetryPolicy, WebhookDelivery};
182///
183/// let dead_letters = Arc::new(InMemoryDeadLetterSink::new());
184/// let service = InMemoryEventSubscriptionService::new().with_delivery(
185///     WebhookDelivery::new()
186///         .with_retry_policy(RetryPolicy::default().with_max_attempts(8))
187///         .with_dead_letter_sink(dead_letters),
188/// );
189/// # let _ = service;
190/// ```
191pub struct InMemoryEventSubscriptionService {
192    subscriptions: DashMap<Uuid, EventSubscription>,
193    delivery: Arc<WebhookDelivery>,
194}
195
196impl InMemoryEventSubscriptionService {
197    /// Create a new empty event subscription service with the default [`WebhookDelivery`].
198    pub fn new() -> Self {
199        Self { subscriptions: DashMap::new(), delivery: Arc::new(WebhookDelivery::new()) }
200    }
201
202    /// Delivers through `delivery`, for a custom retry policy, dead-letter sink, or egress policy.
203    pub fn with_delivery(mut self, delivery: WebhookDelivery) -> Self {
204        self.delivery = Arc::new(delivery);
205        self
206    }
207
208    /// The signed messages for `event`, one per matching subscription.
209    fn deliveries(
210        &self,
211        event: &AwpEvent,
212    ) -> Result<Vec<(Uuid, WebhookEndpoint, WebhookMessage)>, AwpError> {
213        let message = WebhookMessage::json(event.id.to_string(), event)
214            .map_err(|e| AwpError::InternalError(format!("event serialization failed: {e}")))?;
215        let mut deliveries = Vec::new();
216        for entry in self.subscriptions.iter() {
217            let sub = entry.value();
218            if !sub.event_types.is_empty()
219                && !sub.event_types.iter().any(|t| t == &event.event_type || t == "*")
220            {
221                continue;
222            }
223            let Ok(secret) = WebhookSecret::from_bytes(sub.secret.as_bytes().to_vec()) else {
224                tracing::warn!(subscription.id = %sub.id, "subscription has no signing secret; skipped");
225                continue;
226            };
227            deliveries.push((
228                sub.id,
229                WebhookEndpoint::new(&sub.callback_url, secret),
230                message.clone(),
231            ));
232        }
233        Ok(deliveries)
234    }
235
236    /// Delivers `event` to every matching subscription and waits for each report.
237    ///
238    /// # Errors
239    ///
240    /// Returns [`AwpError::InternalError`] when the event cannot be serialized.
241    pub async fn deliver_and_wait(
242        &self,
243        event: AwpEvent,
244    ) -> Result<Vec<(Uuid, DeliveryReport)>, AwpError> {
245        let deliveries = self.deliveries(&event)?;
246        let mut reports = Vec::with_capacity(deliveries.len());
247        for (id, endpoint, message) in deliveries {
248            reports.push((id, self.delivery.deliver(&endpoint, &message).await));
249        }
250        Ok(reports)
251    }
252}
253
254impl Default for InMemoryEventSubscriptionService {
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260#[async_trait]
261impl EventSubscriptionService for InMemoryEventSubscriptionService {
262    async fn create(&self, subscription: EventSubscription) -> Result<Uuid, AwpError> {
263        subscription.validate_with(self.delivery.egress_policy())?;
264        let id = subscription.id;
265        self.subscriptions.insert(id, subscription);
266        Ok(id)
267    }
268
269    async fn get(&self, id: Uuid) -> Result<Option<EventSubscription>, AwpError> {
270        Ok(self.subscriptions.get(&id).map(|e| e.value().clone()))
271    }
272
273    async fn list(&self) -> Result<Vec<EventSubscription>, AwpError> {
274        Ok(self.subscriptions.iter().map(|e| e.value().clone()).collect())
275    }
276
277    async fn delete(&self, id: Uuid) -> Result<(), AwpError> {
278        self.subscriptions.remove(&id);
279        Ok(())
280    }
281
282    async fn deliver(&self, event: AwpEvent) -> Result<(), AwpError> {
283        for (subscription_id, endpoint, message) in self.deliveries(&event)? {
284            let delivery = Arc::clone(&self.delivery);
285            let event_type = event.event_type.clone();
286            tokio::spawn(async move {
287                let report = delivery.deliver(&endpoint, &message).await;
288                tracing::debug!(
289                    subscription.id = %subscription_id,
290                    event.r#type = %event_type,
291                    delivered = report.is_delivered(),
292                    "awp event delivery finished"
293                );
294            });
295        }
296        Ok(())
297    }
298}
299
300/// Compute HMAC-SHA256 of a payload with the given secret.
301///
302/// Returns the signature in `sha256={hex_digest}` format. Deliveries from
303/// [`InMemoryEventSubscriptionService`] carry Standard Webhooks signatures instead;
304/// this helper remains for receivers of the older format and is deprecated (spec 3.5
305/// §10 X5).
306#[deprecated(
307    since = "3.0.0",
308    note = "AWP deliveries carry Standard Webhooks signatures; verify them with `adk_core::webhook::WebhookVerifier`"
309)]
310pub fn sign_payload(payload: &[u8], secret: &str) -> String {
311    let mut mac =
312        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
313    mac.update(payload);
314    let result = mac.finalize();
315    format!("sha256={}", hex::encode(result.into_bytes()))
316}
317
318/// Verify an HMAC-SHA256 signature against a payload and secret.
319///
320/// The `signature` should be in `sha256={hex_digest}` format. Deprecated with
321/// [`sign_payload`] (spec 3.5 §10 X5).
322#[deprecated(
323    since = "3.0.0",
324    note = "AWP deliveries carry Standard Webhooks signatures; verify them with `adk_core::webhook::WebhookVerifier`"
325)]
326pub fn verify_signature(payload: &[u8], secret: &str, signature: &str) -> bool {
327    // Constant-time comparison via the hmac crate
328    let mut mac =
329        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
330    mac.update(payload);
331
332    if let Some(hex_sig) = signature.strip_prefix("sha256=")
333        && let Ok(sig_bytes) = hex::decode(hex_sig)
334    {
335        return mac.verify_slice(&sig_bytes).is_ok();
336    }
337    false
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    fn sample_subscription(event_types: Vec<String>) -> EventSubscription {
345        EventSubscription {
346            id: Uuid::now_v7(),
347            subscriber: "test-subscriber".to_string(),
348            callback_url: "https://example.com/webhook".to_string(),
349            event_types,
350            secret: "test-secret-key-32-bytes-minimum!!".to_string(),
351        }
352    }
353
354    fn sample_event() -> AwpEvent {
355        AwpEvent {
356            id: Uuid::now_v7(),
357            event_type: "health.changed".to_string(),
358            timestamp: Utc::now(),
359            payload: serde_json::json!({"state": "degrading"}),
360        }
361    }
362
363    #[test]
364    fn test_subscription_validation_accepts_bounded_https_destination() {
365        assert!(sample_subscription(vec!["health.changed".to_string()]).validate().is_ok());
366    }
367
368    #[test]
369    fn test_subscription_validation_rejects_insecure_destination() {
370        let mut subscription = sample_subscription(vec![]);
371        subscription.callback_url = "http://example.com/webhook".to_string();
372        assert!(subscription.validate().is_err());
373    }
374
375    #[test]
376    fn test_subscription_validation_rejects_short_signing_secret() {
377        let mut subscription = sample_subscription(vec![]);
378        subscription.secret = "short".to_string();
379        assert!(subscription.validate().is_err());
380    }
381
382    #[tokio::test]
383    async fn test_create_and_get() {
384        let svc = InMemoryEventSubscriptionService::new();
385        let sub = sample_subscription(vec!["health.changed".to_string()]);
386        let id = sub.id;
387        svc.create(sub).await.unwrap();
388
389        let retrieved = svc.get(id).await.unwrap().unwrap();
390        assert_eq!(retrieved.subscriber, "test-subscriber");
391    }
392
393    #[tokio::test]
394    async fn test_get_nonexistent() {
395        let svc = InMemoryEventSubscriptionService::new();
396        assert!(svc.get(Uuid::now_v7()).await.unwrap().is_none());
397    }
398
399    #[tokio::test]
400    async fn test_list() {
401        let svc = InMemoryEventSubscriptionService::new();
402        svc.create(sample_subscription(vec![])).await.unwrap();
403        svc.create(sample_subscription(vec![])).await.unwrap();
404
405        let list = svc.list().await.unwrap();
406        assert_eq!(list.len(), 2);
407    }
408
409    #[tokio::test]
410    async fn test_delete() {
411        let svc = InMemoryEventSubscriptionService::new();
412        let sub = sample_subscription(vec![]);
413        let id = sub.id;
414        svc.create(sub).await.unwrap();
415        assert!(svc.get(id).await.unwrap().is_some());
416
417        svc.delete(id).await.unwrap();
418        assert!(svc.get(id).await.unwrap().is_none());
419    }
420
421    #[tokio::test]
422    async fn test_deliver_matching_event() {
423        let svc = InMemoryEventSubscriptionService::new();
424        svc.create(sample_subscription(vec!["health.changed".to_string()])).await.unwrap();
425        // Should not error — just logs
426        svc.deliver(sample_event()).await.unwrap();
427    }
428
429    #[tokio::test]
430    async fn test_deliver_wildcard_subscription() {
431        let svc = InMemoryEventSubscriptionService::new();
432        svc.create(sample_subscription(vec!["*".to_string()])).await.unwrap();
433        svc.deliver(sample_event()).await.unwrap();
434    }
435
436    #[tokio::test]
437    async fn test_deliver_non_matching_event() {
438        let svc = InMemoryEventSubscriptionService::new();
439        svc.create(sample_subscription(vec!["consent.captured".to_string()])).await.unwrap();
440        // health.changed doesn't match consent.captured — should still succeed (no delivery)
441        svc.deliver(sample_event()).await.unwrap();
442    }
443
444    // The deprecated legacy pair stays tested until it is removed (spec 3.5 §10 X5).
445    #[test]
446    #[allow(deprecated)]
447    fn test_sign_payload() {
448        let payload = b"hello world";
449        let sig = sign_payload(payload, "secret");
450        assert!(sig.starts_with("sha256="));
451        assert_eq!(sig.len(), 7 + 64); // "sha256=" + 64 hex chars
452    }
453
454    #[test]
455    #[allow(deprecated)]
456    fn test_verify_signature_valid() {
457        let payload = b"test payload";
458        let secret = "my-secret";
459        let sig = sign_payload(payload, secret);
460        assert!(verify_signature(payload, secret, &sig));
461    }
462
463    #[test]
464    #[allow(deprecated)]
465    fn test_verify_signature_wrong_payload() {
466        let secret = "my-secret";
467        let sig = sign_payload(b"original", secret);
468        assert!(!verify_signature(b"tampered", secret, &sig));
469    }
470
471    #[test]
472    #[allow(deprecated)]
473    fn test_verify_signature_wrong_secret() {
474        let payload = b"test payload";
475        let sig = sign_payload(payload, "secret1");
476        assert!(!verify_signature(payload, "secret2", &sig));
477    }
478
479    #[test]
480    #[allow(deprecated)]
481    fn test_verify_signature_invalid_format() {
482        assert!(!verify_signature(b"payload", "secret", "not-a-signature"));
483    }
484
485    #[test]
486    #[allow(deprecated)]
487    fn test_verify_signature_invalid_hex() {
488        assert!(!verify_signature(b"payload", "secret", "sha256=not-hex"));
489    }
490
491    #[test]
492    fn test_event_serialization_round_trip() {
493        let event = sample_event();
494        let json = serde_json::to_string(&event).unwrap();
495        let parsed: AwpEvent = serde_json::from_str(&json).unwrap();
496        assert_eq!(event.id, parsed.id);
497        assert_eq!(event.event_type, parsed.event_type);
498    }
499
500    #[test]
501    fn test_subscription_serialization_round_trip() {
502        let sub = sample_subscription(vec!["health.changed".to_string()]);
503        let json = serde_json::to_string(&sub).unwrap();
504        let parsed: EventSubscription = serde_json::from_str(&json).unwrap();
505        assert_eq!(sub.id, parsed.id);
506        assert_eq!(sub.subscriber, parsed.subscriber);
507    }
508
509    #[test]
510    fn test_subscription_validation_rejects_internal_destinations() {
511        for url in
512            ["https://169.254.169.254/latest", "https://127.0.0.1/hook", "https://localhost/hook"]
513        {
514            let mut subscription = sample_subscription(vec![]);
515            subscription.callback_url = url.to_string();
516            assert!(subscription.validate().is_err(), "{url}");
517        }
518    }
519
520    type Captured = Arc<std::sync::Mutex<Vec<(axum::http::HeaderMap, bytes::Bytes)>>>;
521
522    /// A local receiver that answers every delivery with `status`.
523    async fn receiver(status: u16) -> (String, Captured) {
524        let captured: Captured = Arc::default();
525        let log = captured.clone();
526        let app = axum::Router::new().route(
527            "/hook",
528            axum::routing::post(move |headers: axum::http::HeaderMap, body: bytes::Bytes| {
529                let log = log.clone();
530                async move {
531                    log.lock().unwrap().push((headers, body));
532                    axum::http::StatusCode::from_u16(status).unwrap()
533                }
534            }),
535        );
536        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
537        let url = format!("http://{}/hook", listener.local_addr().unwrap());
538        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
539        (url, captured)
540    }
541
542    fn local_service(max_attempts: u32) -> InMemoryEventSubscriptionService {
543        use adk_core::webhook_delivery::RetryPolicy;
544        InMemoryEventSubscriptionService::new().with_delivery(
545            WebhookDelivery::new()
546                .with_retry_policy(
547                    RetryPolicy::default()
548                        .with_max_attempts(max_attempts)
549                        .with_initial_backoff(std::time::Duration::from_millis(5))
550                        .with_max_backoff(std::time::Duration::from_millis(20)),
551                )
552                .with_egress_policy(EgressPolicy::allow_private_networks()),
553        )
554    }
555
556    #[tokio::test]
557    async fn test_events_are_delivered_with_standard_webhooks_signatures() {
558        use adk_core::webhook::{WebhookHeaders, WebhookVerifier};
559        let (url, captured) = receiver(200).await;
560        let svc = local_service(3);
561        let mut sub = sample_subscription(vec!["health.changed".to_string()]);
562        sub.callback_url = url;
563        svc.create(sub.clone()).await.unwrap();
564        let event = sample_event();
565
566        let reports = svc.deliver_and_wait(event.clone()).await.unwrap();
567        assert_eq!(reports, vec![(sub.id, DeliveryReport::Delivered { attempts: 1, status: 200 })]);
568
569        let (headers, body) = captured.lock().unwrap()[0].clone();
570        assert_eq!(headers["webhook-id"], event.id.to_string());
571        // Deliveries carry only Standard Webhooks signatures; the deprecated `sha256=` pair
572        // (spec 3.5 §10 X5) cannot verify one.
573        #[allow(deprecated)]
574        let legacy =
575            verify_signature(&body, &sub.secret, headers["webhook-signature"].to_str().unwrap());
576        assert!(!legacy);
577        let parsed =
578            WebhookHeaders::from_lookup(|name| headers.get(name).and_then(|v| v.to_str().ok()))
579                .unwrap();
580        let verifier =
581            WebhookVerifier::new(WebhookSecret::from_bytes(sub.secret.into_bytes()).unwrap());
582        verifier.verify(&parsed, &body).expect("signed with the subscription secret");
583        let delivered: AwpEvent = serde_json::from_slice(&body).unwrap();
584        assert_eq!(delivered.id, event.id);
585    }
586
587    #[tokio::test]
588    async fn test_failing_subscribers_are_retried_then_dead_lettered() {
589        let (url, captured) = receiver(503).await;
590        let svc = local_service(2);
591        let mut sub = sample_subscription(vec![]);
592        sub.callback_url = url;
593        svc.create(sub).await.unwrap();
594        let reports = svc.deliver_and_wait(sample_event()).await.unwrap();
595        assert!(
596            matches!(&reports[0].1, DeliveryReport::DeadLettered(letter) if letter.attempts == 2)
597        );
598        assert_eq!(captured.lock().unwrap().len(), 2);
599    }
600
601    #[tokio::test]
602    async fn test_deliver_returns_before_the_delivery_finishes() {
603        let (url, captured) = receiver(200).await;
604        let svc = local_service(1);
605        let mut sub = sample_subscription(vec![]);
606        sub.callback_url = url;
607        svc.create(sub).await.unwrap();
608        svc.deliver(sample_event()).await.unwrap();
609        for _ in 0..100 {
610            if !captured.lock().unwrap().is_empty() {
611                return;
612            }
613            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
614        }
615        panic!("the background delivery never arrived");
616    }
617}