Skip to main content

one/
webhooks.rs

1//! Receiving-side webhook support: verify a delivery, dispatch it to typed
2//! handlers, and register the listener with One idempotently.
3//!
4//! The event catalog and the per-event handler methods are generated at build
5//! time from the committed SDK spec, so a new server event reaches this API by
6//! regenerating rather than by a hand edit.
7
8use 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
24/// A handler's returned work, boxed so handlers of different concrete future
25/// types share one registry.
26pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<(), WebhookError>> + Send>>;
27
28type Handler = Box<dyn Fn(Delivery) -> HandlerFuture + Send + Sync>;
29
30/// A webhook handler's completion value.
31///
32/// Returning `()` acknowledges successful processing. Returning a fallible
33/// result propagates its error from [`Webhooks::handle`] so the receiver can
34/// answer non-2xx and request a retry.
35pub 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/// Failures from verifying, parsing, or registering a webhook.
60///
61/// `#[non_exhaustive]`: new variants may be added in future releases, so
62/// downstream `match` statements must include a `_ =>` arm.
63#[derive(Debug, thiserror::Error)]
64#[non_exhaustive]
65pub enum WebhookError {
66    /// The signature header was absent, or not a `sha256=<hex>` value.
67    #[error("webhook signature header is missing or malformed")]
68    MalformedSignature,
69    /// The signature did not match the body under the configured secret.
70    #[error("webhook signature verification failed")]
71    InvalidSignature,
72    /// The event is older than the configured maximum age. Only returned when
73    /// [`Webhooks::max_event_age`] is set.
74    #[error("webhook event is older than the configured {max_age_secs}s maximum age")]
75    Expired { max_age_secs: u64 },
76    /// The body verified but was not a well-formed delivery, or its payload did
77    /// not match the type its event declares.
78    #[error("failed to parse webhook payload: {0}")]
79    Parse(#[from] serde_json::Error),
80    /// A registered handler failed while processing the delivery.
81    #[error("webhook handler failed: {0}")]
82    Handler(#[source] Box<dyn StdError + Send + Sync>),
83    /// Registering the listener with One failed.
84    #[error(transparent)]
85    Api(#[from] Error)
86}
87
88/// A verified delivery, with the payload still typed as raw JSON.
89///
90/// Typed handlers receive [`Delivery`] with the payload already decoded into
91/// the event's own type; [`Webhooks::on_any`] and [`Webhooks::verify`] hand
92/// back this untyped form because the event is only known at runtime.
93#[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    /// The event type as a known variant, or `None` for an event this SDK
104    /// build does not recognize - a subscription edited outside the SDK can
105    /// carry one.
106    pub fn event_type(&self) -> Option<WebhookEventType> {
107        WebhookEventType::parse(&self.event)
108    }
109
110    /// The raw on-the-wire event string, present even for unknown types.
111    pub fn event(&self) -> &str {
112        &self.event
113    }
114
115    /// Stable delivery id, identical on every retry. Deduplicate on this:
116    /// delivery is at-least-once.
117    pub fn id(&self) -> Uuid {
118        self.id
119    }
120
121    /// When One emitted the event.
122    pub fn timestamp(&self) -> DateTime<Utc> {
123        self.timestamp
124    }
125
126    /// The event-specific payload.
127    pub fn payload(&self) -> &P {
128        &self.payload
129    }
130
131    /// Metadata recorded on the event when it was captured, if any. This is the
132    /// event's own metadata - a subscription's `metadata` field is not echoed
133    /// back on delivery.
134    pub fn metadata(&self) -> Option<&Value> {
135        self.metadata.as_ref()
136    }
137}
138
139impl Delivery {
140    /// The connection key this delivery concerns, for the events that carry
141    /// one. `None` for account-level events (`project.*`, `organization.*`,
142    /// `member.*`) and for an `oauth.failed` that fired before the connection
143    /// existed. Every known event is decoded first, so a payload that does not
144    /// match its declared type returns a decode error even when it has no
145    /// connection key.
146    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    /// Whether this is a test delivery from the dashboard's "send test" action.
157    ///
158    /// A test delivery reuses a real event name but carries a synthetic
159    /// payload, so it cannot decode into that event's type. Typed handlers are
160    /// skipped for it and only [`Webhooks::on_any`] runs - otherwise every test
161    /// send would fail to decode and be retried forever.
162    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    /// Re-decodes the payload into the event's own type.
171    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/// What the server puts on the wire, mapped into [`Delivery`].
183#[derive(Deserialize)]
184struct RawDelivery {
185    event:     String,
186    event_id:  Uuid,
187    timestamp: DateTime<Utc>,
188    payload:   Value,
189    metadata:  Option<Value>
190}
191
192/// A handler plus the connection it was scoped to, if any.
193struct Registered {
194    connection: Option<String>,
195    run:        Handler
196}
197
198impl Registered {
199    /// Whether this handler should see `delivery`. An unscoped handler sees
200    /// everything; a scoped one only deliveries carrying its connection key.
201    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    /// Runs this handler when its connection scope accepts the delivery.
209    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
217/// A registry of typed webhook handlers plus the listener registration that
218/// makes One send them.
219///
220/// Built fluently; every per-event method is generated from the SDK spec's
221/// event catalog.
222pub 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    /// Rejects deliveries whose event is older than `max_age`.
242    ///
243    /// **Off by default, and not replay protection.** The signed timestamp is
244    /// when the *event* occurred, not when this attempt was sent: the server
245    /// retries on a `30 * (2^n - 1)` second backoff over five attempts, and a
246    /// backed-up delivery queue can push an authentic first attempt arbitrarily
247    /// far past the event. Any window therefore rejects genuine deliveries once
248    /// the server is behind, which is exactly when you least want to drop them.
249    ///
250    /// Deduplicate on [`Delivery::id`] instead - it is stable across retries.
251    /// Real replay protection needs a per-attempt signed timestamp, which is a
252    /// server-side signing change.
253    pub fn max_event_age(mut self, max_age: Duration) -> Self {
254        self.tolerance = Some(max_age);
255        self
256    }
257
258    /// Registers handlers scoped to one connection: they fire only for
259    /// deliveries carrying that connection's key.
260    ///
261    /// The block form keeps the scope lexical, so a reader never has to scan
262    /// backwards to work out which connection a handler belongs to, and only
263    /// the connection-carrying events are offered inside it.
264    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    /// Registers a handler fired for every verified delivery, whatever its
281    /// event type. Runs after event-specific handlers.
282    ///
283    /// "Every" means every event in this SDK build's catalog, which is what
284    /// [`Webhooks::listen`] subscribes to. An event the server adds after this
285    /// build was released is not in that list and will not be delivered, so
286    /// regenerate the SDK to pick up new events. A delivery for an unrecognized
287    /// type still verifies and reaches this handler with
288    /// [`Delivery::event_type`] as `None` - that path exists for a subscription
289    /// edited outside the SDK, not as forward compatibility.
290    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    /// Registers a typed handler for `event`. The generated per-event methods
307    /// are thin wrappers over this.
308    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    /// The event types [`Webhooks::listen`] subscribes to.
328    ///
329    /// An unscoped catch-all subscribes to this build's whole catalog. The
330    /// server matches exact event strings, so an event added after this build
331    /// was released is not covered - see [`Webhooks::on_any`].
332    ///
333    /// A catch-all scoped to a connection adds only the connection-carrying
334    /// events. The server cannot filter by connection, so subscribing to
335    /// account-level events would just ship deliveries `accepts` discards.
336    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    /// Verifies the signature and parses the body without dispatching. Use it
351    /// when you want to route deliveries yourself.
352    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    /// Verifies a delivery without a registry, for callers that hold only the
357    /// signing secret. The language bindings route through this so signature
358    /// checking, the replay window, and its default all have exactly one
359    /// implementation.
360    ///
361    /// `tolerance` of `None` performs no age check, which is the default - see
362    /// [`Webhooks::max_event_age`] for why.
363    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    /// Verifies, parses, and dispatches a delivery to every handler registered
400    /// for its event type, then to the catch-all handlers.
401    ///
402    /// Handlers run sequentially, so one that panics or hangs blocks the rest.
403    /// Returns the delivery so callers can log it after dispatch.
404    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    /// Registers this listener with One under the stable name `key`, pointing
432    /// at `url` and subscribing to exactly the events handlers were attached
433    /// for.
434    ///
435    /// Idempotent: calling it on every boot reconciles the one listener named
436    /// `key` rather than accumulating duplicates, so `url` and the event set
437    /// can change freely between runs.
438    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    /// Performs the listener upsert against the API.
449    ///
450    /// The route, the request shape, and the percent-encoding of `key` live
451    /// here only - the language bindings call this rather than rebuilding the
452    /// request, so there is one definition of what registering a listener
453    /// means. The raw response metadata is retained for language bindings.
454    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
467/// Handlers scoped to a single connection. Only the events that carry a
468/// connection are offered here, so a scoped handler can never be one that could
469/// not fire.
470pub struct ConnectionWebhooks {
471    key:      String,
472    handlers: HashMap<WebhookEventType, Vec<Registered>>,
473    any:      Vec<Registered>
474}
475
476impl ConnectionWebhooks {
477    /// Registers a handler for every event concerning this connection.
478    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    /// Registers a typed handler scoped to this connection. The generated
495    /// per-event methods are thin wrappers over this.
496    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
512/// Wraps a typed handler into the registry's untyped shape, decoding the
513/// payload on the way in.
514///
515/// A payload that does not match the type its event declares surfaces as
516/// [`WebhookError::Parse`] rather than being skipped: that is what lets the
517/// caller answer non-2xx, so the server retries instead of the delivery being
518/// silently lost.
519fn 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}