1use crate::{
9 client::{CallResponse, Error, One, PATH_SEGMENT},
10 transport::types::WebhookSubscriptionView
11};
12use chrono::{DateTime, Utc};
13use hmac::{Hmac, KeyInit, Mac};
14use percent_encoding::utf8_percent_encode;
15use secrecy::{ExposeSecret, SecretString};
16use serde::de::DeserializeOwned;
17use serde_json::{Value, from_value, json};
18use sha2::Sha256;
19use std::{collections::HashMap, error::Error as StdError, future::ready, pin::Pin, time::Duration};
20use uuid::Uuid;
21
22type HmacSha256 = Hmac<Sha256>;
23
24pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<(), WebhookError>> + Send>>;
27
28type Handler = Box<dyn Fn(Delivery) -> HandlerFuture + Send + Sync>;
29
30pub trait WebhookHandlerOutput {
36 #[doc(hidden)]
37 fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>>;
38}
39
40impl WebhookHandlerOutput for () {
41 fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>> {
42 Ok(())
43 }
44}
45
46impl<E> WebhookHandlerOutput for Result<(), E>
47where
48 E: StdError + Send + Sync + 'static
49{
50 fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>> {
51 self.map_err(|error| Box::new(error) as Box<dyn StdError + Send + Sync>)
52 }
53}
54
55const SIGNATURE_PREFIX: &str = "sha256=";
56const SUBSCRIPTIONS_BY_KEY_PATH: &str = "/v1/webhooks/subscriptions/by-key/";
57const TEST_METADATA_FIELD: &str = "test";
58
59#[derive(Debug, thiserror::Error)]
64#[non_exhaustive]
65pub enum WebhookError {
66 #[error("webhook signature header is missing or malformed")]
68 MalformedSignature,
69 #[error("webhook signature verification failed")]
71 InvalidSignature,
72 #[error("webhook event is older than the configured {max_age_secs}s maximum age")]
75 Expired { max_age_secs: u64 },
76 #[error("failed to parse webhook payload: {0}")]
79 Parse(#[from] serde_json::Error),
80 #[error("webhook handler failed: {0}")]
82 Handler(#[source] Box<dyn StdError + Send + Sync>),
83 #[error(transparent)]
85 Api(#[from] Error)
86}
87
88#[derive(Clone, Debug)]
94pub struct Delivery<P = Value> {
95 event: String,
96 id: Uuid,
97 timestamp: DateTime<Utc>,
98 payload: P,
99 metadata: Option<Value>
100}
101
102impl<P> Delivery<P> {
103 pub fn event_type(&self) -> Option<WebhookEventType> {
107 WebhookEventType::parse(&self.event)
108 }
109
110 pub fn event(&self) -> &str {
112 &self.event
113 }
114
115 pub fn id(&self) -> Uuid {
118 self.id
119 }
120
121 pub fn timestamp(&self) -> DateTime<Utc> {
123 self.timestamp
124 }
125
126 pub fn payload(&self) -> &P {
128 &self.payload
129 }
130
131 pub fn metadata(&self) -> Option<&Value> {
135 self.metadata.as_ref()
136 }
137}
138
139impl Delivery {
140 pub fn connection_key(&self) -> Result<Option<String>, serde_json::Error> {
147 if self.is_test() {
148 return Ok(None);
149 }
150 match self.event_type() {
151 Some(event) => event.connection_key_of(&self.payload),
152 None => Ok(None)
153 }
154 }
155
156 pub fn is_test(&self) -> bool {
163 self.metadata
164 .as_ref()
165 .and_then(|metadata| metadata.get(TEST_METADATA_FIELD))
166 .and_then(Value::as_bool)
167 .unwrap_or(false)
168 }
169
170 fn retype<P: DeserializeOwned>(&self) -> Result<Delivery<P>, serde_json::Error> {
172 Ok(Delivery {
173 event: self.event.clone(),
174 id: self.id,
175 timestamp: self.timestamp,
176 payload: from_value(self.payload.clone())?,
177 metadata: self.metadata.clone()
178 })
179 }
180}
181
182#[derive(Deserialize)]
184struct RawDelivery {
185 event: String,
186 event_id: Uuid,
187 timestamp: DateTime<Utc>,
188 payload: Value,
189 metadata: Option<Value>
190}
191
192struct Registered {
194 connection: Option<String>,
195 run: Handler
196}
197
198impl Registered {
199 fn accepts(&self, delivery: &Delivery) -> Result<bool, WebhookError> {
202 match &self.connection {
203 None => Ok(true),
204 Some(key) => Ok(delivery.connection_key()?.as_deref() == Some(key.as_str()))
205 }
206 }
207
208 async fn run_if_accepted(&self, delivery: &Delivery) -> Result<(), WebhookError> {
210 if self.accepts(delivery)? {
211 (self.run)(delivery.clone()).await?;
212 }
213 Ok(())
214 }
215}
216
217pub struct Webhooks {
223 client: One,
224 secret: SecretString,
225 tolerance: Option<Duration>,
226 handlers: HashMap<WebhookEventType, Vec<Registered>>,
227 any: Vec<Registered>
228}
229
230impl Webhooks {
231 pub(crate) fn new(client: One, secret: SecretString) -> Self {
232 Self {
233 client,
234 secret,
235 tolerance: None,
236 handlers: HashMap::new(),
237 any: Vec::new()
238 }
239 }
240
241 pub fn max_event_age(mut self, max_age: Duration) -> Self {
254 self.tolerance = Some(max_age);
255 self
256 }
257
258 pub fn connection<F>(mut self, key: impl Into<String>, block: F) -> Self
265 where
266 F: FnOnce(ConnectionWebhooks) -> ConnectionWebhooks
267 {
268 let scope = block(ConnectionWebhooks {
269 key: key.into(),
270 handlers: HashMap::new(),
271 any: Vec::new()
272 });
273 for (event, handlers) in scope.handlers {
274 self.handlers.entry(event).or_default().extend(handlers);
275 }
276 self.any.extend(scope.any);
277 self
278 }
279
280 pub fn on_any<F, Fut, Output>(mut self, handler: F) -> Self
291 where
292 F: Fn(Delivery) -> Fut + Send + Sync + 'static,
293 Fut: Future<Output = Output> + Send + 'static,
294 Output: WebhookHandlerOutput + Send + 'static
295 {
296 self.any.push(Registered {
297 connection: None,
298 run: Box::new(move |delivery| {
299 let work = handler(delivery);
300 Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
301 })
302 });
303 self
304 }
305
306 pub(crate) fn register<P, F, Fut, Output>(
309 mut self,
310 event: WebhookEventType,
311 connection: Option<String>,
312 handler: F
313 ) -> Self
314 where
315 P: DeserializeOwned + Send + 'static,
316 F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
317 Fut: Future<Output = Output> + Send + 'static,
318 Output: WebhookHandlerOutput + Send + 'static
319 {
320 self.handlers
321 .entry(event)
322 .or_default()
323 .push(typed_handler(connection, handler));
324 self
325 }
326
327 pub fn events(&self) -> Vec<WebhookEventType> {
337 if self.any.iter().any(|handler| handler.connection.is_none()) {
338 return WebhookEventType::ALL.to_vec();
339 }
340
341 let mut events: Vec<WebhookEventType> = self.handlers.keys().copied().collect();
342 if !self.any.is_empty() {
343 events.extend(WebhookEventType::CONNECTION_SCOPED);
344 }
345 events.sort();
346 events.dedup();
347 events
348 }
349
350 pub fn verify(&self, raw_body: &[u8], signature: &str) -> Result<Delivery, WebhookError> {
353 Self::verify_with(&self.secret, self.tolerance, raw_body, signature)
354 }
355
356 pub fn verify_with(
364 secret: &SecretString,
365 tolerance: Option<Duration>,
366 raw_body: &[u8],
367 signature: &str
368 ) -> Result<Delivery, WebhookError> {
369 let hex_sig = signature
370 .strip_prefix(SIGNATURE_PREFIX)
371 .ok_or(WebhookError::MalformedSignature)?;
372 let expected = hex::decode(hex_sig).map_err(|_| WebhookError::MalformedSignature)?;
373
374 let mut mac = HmacSha256::new_from_slice(secret.expose_secret().as_bytes())
375 .map_err(|_| WebhookError::InvalidSignature)?;
376 mac.update(raw_body);
377 mac.verify_slice(&expected)
378 .map_err(|_| WebhookError::InvalidSignature)?;
379
380 let raw: RawDelivery = serde_json::from_slice(raw_body)?;
381 if let Some(max_age) = tolerance {
382 let age = Utc::now().signed_duration_since(raw.timestamp).abs();
383 if age.to_std().is_ok_and(|age| age > max_age) {
384 return Err(WebhookError::Expired {
385 max_age_secs: max_age.as_secs()
386 });
387 }
388 }
389
390 Ok(Delivery {
391 event: raw.event,
392 id: raw.event_id,
393 timestamp: raw.timestamp,
394 payload: raw.payload,
395 metadata: raw.metadata
396 })
397 }
398
399 pub async fn handle(&self, raw_body: &[u8], signature: &str) -> Result<Delivery, WebhookError> {
405 let delivery = self.verify(raw_body, signature)?;
406
407 let mut failure = None;
408
409 if !delivery.is_test()
410 && let Some(event) = delivery.event_type()
411 && let Some(handlers) = self.handlers.get(&event)
412 {
413 for handler in handlers {
414 if let Err(error) = handler.run_if_accepted(&delivery).await {
415 failure.get_or_insert(error);
416 }
417 }
418 }
419 for handler in &self.any {
420 if let Err(error) = handler.run_if_accepted(&delivery).await {
421 failure.get_or_insert(error);
422 }
423 }
424
425 match failure {
426 Some(error) => Err(error),
427 None => Ok(delivery)
428 }
429 }
430
431 pub async fn listen(
439 &self,
440 key: impl AsRef<str>,
441 url: impl AsRef<str>
442 ) -> Result<WebhookSubscriptionView, WebhookError> {
443 let events: Vec<&str> = self.events().iter().map(|event| event.as_str()).collect();
444 let response = Self::register_listener(&self.client, key.as_ref(), url.as_ref(), &events, &self.secret).await?;
445 Ok(response.output()?)
446 }
447
448 pub async fn register_listener(
455 client: &One,
456 key: &str,
457 url: &str,
458 events: &[&str],
459 secret: &SecretString
460 ) -> Result<CallResponse<WebhookSubscriptionView>, WebhookError> {
461 let path = format!("{SUBSCRIPTIONS_BY_KEY_PATH}{}", utf8_percent_encode(key, PATH_SEGMENT));
462 let body = json!({ "url": url, "events": events, "secret": secret.expose_secret() });
463 Ok(client.put_json_response(&path, &body).await?)
464 }
465}
466
467pub struct ConnectionWebhooks {
471 key: String,
472 handlers: HashMap<WebhookEventType, Vec<Registered>>,
473 any: Vec<Registered>
474}
475
476impl ConnectionWebhooks {
477 pub fn on_any<F, Fut, Output>(mut self, handler: F) -> Self
479 where
480 F: Fn(Delivery) -> Fut + Send + Sync + 'static,
481 Fut: Future<Output = Output> + Send + 'static,
482 Output: WebhookHandlerOutput + Send + 'static
483 {
484 self.any.push(Registered {
485 connection: Some(self.key.clone()),
486 run: Box::new(move |delivery| {
487 let work = handler(delivery);
488 Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
489 })
490 });
491 self
492 }
493
494 pub(crate) fn register<P, F, Fut, Output>(mut self, event: WebhookEventType, handler: F) -> Self
497 where
498 P: DeserializeOwned + Send + 'static,
499 F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
500 Fut: Future<Output = Output> + Send + 'static,
501 Output: WebhookHandlerOutput + Send + 'static
502 {
503 let connection = Some(self.key.clone());
504 self.handlers
505 .entry(event)
506 .or_default()
507 .push(typed_handler(connection, handler));
508 self
509 }
510}
511
512fn typed_handler<P, F, Fut, Output>(connection: Option<String>, handler: F) -> Registered
520where
521 P: DeserializeOwned + Send + 'static,
522 F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
523 Fut: Future<Output = Output> + Send + 'static,
524 Output: WebhookHandlerOutput + Send + 'static
525{
526 Registered {
527 connection,
528 run: Box::new(move |delivery| match delivery.retype::<P>() {
529 Ok(typed) => {
530 let work = handler(typed);
531 Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
532 }
533 Err(error) => Box::pin(ready(Err(WebhookError::Parse(error))))
534 })
535 }
536}
537
538include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/generated/webhooks_generated.rs"));
539
540#[cfg(test)]
541mod tests {
542 use std::{
543 future::ready,
544 io::Error as IoError,
545 sync::{
546 Arc,
547 atomic::{AtomicBool, Ordering}
548 }
549 };
550
551 use chrono::Utc;
552 use hmac::{KeyInit, Mac};
553 use secrecy::SecretString;
554 use serde_json::json;
555 use uuid::Uuid;
556
557 use super::{Delivery, HmacSha256, Registered, WebhookError, Webhooks};
558 use crate::One;
559
560 #[tokio::test]
561 async fn test_webhooks_handle_propagates_first_handler_failure_after_dispatching_all_handlers() {
562 let secret = "handler-secret";
563 let raw_body = serde_json::to_vec(&json!({
564 "event": "future.event",
565 "event_id": Uuid::nil(),
566 "timestamp": Utc::now(),
567 "payload": {},
568 "metadata": null
569 }))
570 .expect("delivery serializes");
571 let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts the secret");
572 mac.update(&raw_body);
573 let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes()));
574 let second_ran = Arc::new(AtomicBool::new(false));
575 let second_handler = Arc::clone(&second_ran);
576 let webhooks = Webhooks::new(
577 One::builder().secret("api-secret").build().expect("client builds"),
578 SecretString::from(secret.to_string())
579 )
580 .on_any(|_| async { Err::<(), _>(IoError::other("first failure")) })
581 .on_any(move |_| {
582 let second_handler = Arc::clone(&second_handler);
583 async move {
584 second_handler.store(true, Ordering::SeqCst);
585 }
586 });
587
588 let error = webhooks
589 .handle(&raw_body, &signature)
590 .await
591 .expect_err("handler failure propagates");
592
593 assert!(second_ran.load(Ordering::SeqCst));
594 match error {
595 WebhookError::Handler(source) => assert_eq!(source.to_string(), "first failure"),
596 other => panic!("unexpected webhook error: {other}")
597 }
598 }
599
600 #[test]
601 fn test_webhooks_scoped_handler_preserves_connection_decode_errors() {
602 let delivery = Delivery {
603 event: "connection.created".to_string(),
604 id: Uuid::nil(),
605 timestamp: Utc::now(),
606 payload: json!({ "key": 42 }),
607 metadata: None
608 };
609 let handler = Registered {
610 connection: Some("primary".to_string()),
611 run: Box::new(|_| Box::pin(ready(Ok(()))))
612 };
613
614 assert!(matches!(handler.accepts(&delivery), Err(WebhookError::Parse(_))));
615 }
616
617 #[test]
618 fn test_webhooks_test_delivery_skips_connection_payload_decode() {
619 let delivery = Delivery {
620 event: "connection.created".to_string(),
621 id: Uuid::nil(),
622 timestamp: Utc::now(),
623 payload: json!({ "test": true }),
624 metadata: Some(json!({ "test": true }))
625 };
626
627 assert_eq!(delivery.connection_key().expect("test delivery is accepted"), None);
628 }
629}