Skip to main content

fusion_stack/
webhooks.rs

1//! Webhooks, as the PHP package sends them: endpoints subscribe to event types (with patterns such
2//! as `order.*`) and are pinned to a version, events are recorded as one delivery per subscribed
3//! endpoint, and a queued job posts each delivery, signed with the endpoint's secret, in the
4//! endpoint's version. Failed deliveries are retried after the configured delays, and an endpoint
5//! whose deliveries fail too many times in a row is disabled.
6//!
7//! Receivers check `Webhook-Signature` with [`Signer::verify`]; it is `t=<unix time>,v1=<hex>`,
8//! where the hex is an HMAC-SHA256 of `<unix time>.<body>` with the endpoint's secret.
9
10use hmac::{Hmac, KeyInit, Mac};
11use sha2::Sha256;
12
13/// Signs and checks webhook bodies.
14pub struct Signer;
15
16impl Signer {
17    /// The request header that carries the signature.
18    pub const HEADER: &'static str = "Webhook-Signature";
19
20    /// The signature of `body` with `secret`, made at `timestamp` (unix seconds).
21    #[must_use]
22    pub fn sign(body: &str, secret: &str, timestamp: i64) -> String {
23        format!("t={timestamp},v1={}", hash(body, secret, timestamp))
24    }
25
26    /// Whether `header` is a valid signature of `body` with `secret`, made within `tolerance`
27    /// seconds of `now`. Any of several `v1` signatures may match, so a sender can sign with an
28    /// old and a new secret while receivers switch.
29    #[must_use]
30    pub fn verify(
31        body: &str,
32        header: Option<&str>,
33        secret: &str,
34        tolerance: i64,
35        now: i64,
36    ) -> bool {
37        let mut timestamp = None;
38        let mut signatures = Vec::new();
39        for part in header.unwrap_or_default().split(',') {
40            let (key, value) = part.trim().split_once('=').unwrap_or((part.trim(), ""));
41            if key == "t" && !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
42                timestamp = value.parse::<i64>().ok();
43            } else if key == "v1" && !value.is_empty() {
44                signatures.push(value);
45            }
46        }
47        let Some(timestamp) = timestamp.filter(|timestamp| (now - timestamp).abs() <= tolerance)
48        else {
49            return false;
50        };
51        let expected = hash(body, secret, timestamp);
52        signatures
53            .iter()
54            .any(|signature| constant_time_eq(expected.as_bytes(), signature.as_bytes()))
55    }
56}
57
58fn hash(body: &str, secret: &str, timestamp: i64) -> String {
59    let mut mac =
60        Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes keys of any length");
61    mac.update(format!("{timestamp}.{body}").as_bytes());
62    mac.finalize()
63        .into_bytes()
64        .iter()
65        .map(|byte| format!("{byte:02x}"))
66        .collect()
67}
68
69fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
70    a.len() == b.len() && a.iter().zip(b).fold(0, |diff, (x, y)| diff | (x ^ y)) == 0
71}
72
73#[cfg(feature = "database")]
74pub use self::store::*;
75
76#[cfg(feature = "database")]
77mod store {
78    use std::time::Instant;
79
80    use laravel::db::{self, col, values};
81    use laravel::http::client;
82    use laravel::prelude::ToSpan;
83    use laravel::queue::{Attempt, Queueable, job};
84    use serde_json::{Map, Value};
85
86    use crate::query::Row;
87    use crate::{State, glob, time, versioning};
88
89    /// The prefix of endpoint secrets.
90    pub const SECRET_PREFIX: &str = "whsec_";
91
92    /// A delivery waiting for its first or next attempt.
93    pub const PENDING: &str = "pending";
94    /// A delivery the endpoint accepted.
95    pub const DELIVERED: &str = "delivered";
96    /// A delivery that ran out of attempts.
97    pub const FAILED: &str = "failed";
98
99    /// An event to send to the endpoints that subscribe to its type.
100    #[derive(Debug, Clone)]
101    pub struct Event {
102        kind: String,
103        document: Value,
104        owner: Option<(String, i64)>,
105    }
106
107    impl Event {
108        /// An event of type `kind`, such as `order.created`, carrying a JSON:API document's `data`
109        /// and `included`, such as one from [`ApiQuery::document`](crate::query::ApiQuery::document).
110        #[must_use]
111        pub fn new(kind: impl Into<String>, document: Value) -> Self {
112            Self {
113                kind: kind.into(),
114                document,
115                owner: None,
116            }
117        }
118
119        /// Sends the event only to the endpoints of one owner, such as the order's team, by its
120        /// morph type and ID. Without an owner, every subscribed endpoint gets it.
121        #[must_use]
122        pub fn owner(mut self, kind: impl Into<String>, id: i64) -> Self {
123            self.owner = Some((kind.into(), id));
124            self
125        }
126
127        /// Records a delivery for each active endpoint that subscribes to the event, and queues
128        /// them. Returns the deliveries' IDs.
129        ///
130        /// # Errors
131        ///
132        /// When the tables can't be read or written, or a job can't be queued.
133        pub async fn dispatch(self) -> laravel::Result<Vec<i64>> {
134            let mut query = db::table("webhook_endpoints")
135                .select(["id", "events"])
136                .filter(col("active").eq(true));
137            if let Some((kind, id)) = &self.owner {
138                query = query
139                    .filter(col("owner_type").eq(kind.clone()))
140                    .filter(col("owner_id").eq(*id));
141            }
142            let rows: Vec<Row> = query.get().await?;
143            let endpoints: Vec<i64> = rows
144                .into_iter()
145                .filter(|row| subscribes_to(&row.0, &self.kind))
146                .filter_map(|row| row.0.get("id").and_then(Value::as_i64))
147                .collect();
148            if endpoints.is_empty() {
149                return Ok(Vec::new());
150            }
151
152            let mut payload = Map::new();
153            let event_id = format!("evt_{}", ulid::Ulid::new().to_string().to_lowercase());
154            payload.insert("id".into(), Value::String(event_id.clone()));
155            payload.insert("type".into(), Value::String(self.kind.clone()));
156            payload.insert("created_at".into(), Value::String(time::atom(time::now())));
157            for member in ["data", "included"] {
158                if let Some(value) = self.document.get(member).filter(|value| !value.is_null()) {
159                    payload.insert(member.into(), value.clone());
160                }
161            }
162            let payload = Value::Object(payload).to_string();
163
164            let settings = settings();
165            let mut deliveries = Vec::new();
166            for endpoint in endpoints {
167                let now = laravel::now().timestamp();
168                let id = db::table("webhook_deliveries")
169                    .insert_get_id(
170                        values! {
171                            webhook_endpoint_id: endpoint,
172                            event_id: event_id.clone(),
173                            event_type: self.kind.clone(),
174                            payload: payload.clone(),
175                            status: PENDING,
176                            attempts: 0_i64,
177                            created_at: now,
178                            updated_at: now,
179                        },
180                        "id",
181                    )
182                    .await?;
183                let mut job = DeliverWebhook { delivery_id: id }.dispatch();
184                if let Some(connection) = &settings.connection {
185                    job = job.on_connection(connection);
186                }
187                if let Some(queue) = &settings.queue {
188                    job = job.on_queue(queue);
189                }
190                job.await?;
191                deliveries.push(id);
192            }
193            Ok(deliveries)
194        }
195    }
196
197    fn subscribes_to(endpoint: &Map<String, Value>, kind: &str) -> bool {
198        endpoint
199            .get("events")
200            .and_then(Value::as_str)
201            .and_then(|events| serde_json::from_str::<Vec<String>>(events).ok())
202            .unwrap_or_default()
203            .iter()
204            .any(|pattern| glob(pattern, kind))
205    }
206
207    /// `api.webhooks` in the PHP package.
208    #[derive(Debug, Clone)]
209    pub(crate) struct Settings {
210        pub(crate) connection: Option<String>,
211        pub(crate) queue: Option<String>,
212        pub(crate) timeout: u64,
213        pub(crate) backoff: Vec<u64>,
214        pub(crate) disable_after: Option<i64>,
215    }
216
217    impl Default for Settings {
218        fn default() -> Self {
219            Self {
220                connection: None,
221                queue: None,
222                timeout: 10,
223                backoff: vec![60, 300, 1800, 3600, 10_800, 21_600, 43_200],
224                disable_after: Some(5),
225            }
226        }
227    }
228
229    fn state() -> Option<&'static State> {
230        crate::STATE.get().map(AsRef::as_ref)
231    }
232
233    fn settings() -> Settings {
234        state()
235            .map(|state| state.config.webhooks.clone())
236            .unwrap_or_default()
237    }
238
239    /// Registers an endpoint with a new secret, subscribed to `events` (such as `["order.*"]`).
240    /// It is pinned to `version`, or to the latest version when versioning is on, so later
241    /// breaking changes never reach it until it is upgraded. Returns its ID.
242    ///
243    /// # Errors
244    ///
245    /// When the secret can't be encrypted (check `APP_KEY`) or the endpoint can't be written.
246    pub async fn register(
247        url: &str,
248        events: &[&str],
249        version: Option<&str>,
250        description: Option<&str>,
251    ) -> laravel::Result<i64> {
252        let version = version.map(str::to_owned).or_else(|| {
253            state()
254                .and_then(|state| state.registry.as_ref())
255                .map(|registry| registry.latest.to_string())
256        });
257        let secret = new_secret();
258        let now = laravel::now().timestamp();
259        db::table("webhook_endpoints")
260            .insert_get_id(
261                values! {
262                    url: url,
263                    description: description.map(str::to_owned),
264                    secret: laravel::crypt::encrypt_string(&secret)?,
265                    events: serde_json::to_string(events).unwrap_or_default(),
266                    version: version,
267                    active: true,
268                    consecutive_failures: 0_i64,
269                    created_at: now,
270                    updated_at: now,
271                },
272                "id",
273            )
274            .await
275    }
276
277    fn new_secret() -> String {
278        format!("{SECRET_PREFIX}{}", laravel::str::random(32))
279    }
280
281    /// An endpoint's secret, for a receiver that checks signatures.
282    ///
283    /// # Errors
284    ///
285    /// When there is no such endpoint, or its secret can't be decrypted.
286    pub async fn secret(endpoint: i64) -> laravel::Result<String> {
287        let row: Option<Row> = db::table("webhook_endpoints")
288            .select(["secret"])
289            .filter(col("id").eq(endpoint))
290            .first()
291            .await?;
292        let encrypted = row
293            .and_then(|row| {
294                row.0
295                    .get("secret")
296                    .and_then(Value::as_str)
297                    .map(str::to_owned)
298            })
299            .ok_or_else(|| laravel::Error::msg(format!("No webhook endpoint [{endpoint}].")))?;
300        laravel::crypt::decrypt_string(&encrypted)
301    }
302
303    /// Replaces an endpoint's secret, such as after a leak, and returns the new one. Receivers
304    /// must switch to it.
305    ///
306    /// # Errors
307    ///
308    /// When the endpoint can't be written.
309    pub async fn rotate_secret(endpoint: i64) -> laravel::Result<String> {
310        let secret = new_secret();
311        db::table("webhook_endpoints")
312            .filter(col("id").eq(endpoint))
313            .update(values! {
314                secret: laravel::crypt::encrypt_string(&secret)?,
315                updated_at: laravel::now().timestamp(),
316            })
317            .await?;
318        Ok(secret)
319    }
320
321    /// Turns an endpoint back on, such as after it was disabled for failing, with a clean slate.
322    ///
323    /// # Errors
324    ///
325    /// When the endpoint can't be written.
326    pub async fn enable(endpoint: i64) -> laravel::Result<()> {
327        db::table("webhook_endpoints")
328            .filter(col("id").eq(endpoint))
329            .update(values! {
330                active: true,
331                consecutive_failures: 0_i64,
332                disabled_at: None::<String>,
333                updated_at: laravel::now().timestamp(),
334            })
335            .await?;
336        Ok(())
337    }
338
339    /// Posts one delivery to its endpoint.
340    #[derive(Queueable)]
341    pub struct DeliverWebhook {
342        pub delivery_id: i64,
343    }
344
345    // Retries come from `api.webhooks.backoff` and the delivery's own attempt count, so the job
346    // allows as many attempts as a week of releases may need.
347    #[job(name = "fusion-stack.deliver-webhook", retry_for = 7.days())]
348    impl DeliverWebhook {
349        async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
350            deliver(self.delivery_id, attempt).await
351        }
352    }
353
354    fn int(row: &Map<String, Value>, key: &str) -> i64 {
355        match row.get(key) {
356            Some(Value::Bool(value)) => i64::from(*value),
357            Some(value) => value.as_i64().unwrap_or_default(),
358            None => 0,
359        }
360    }
361
362    fn text(row: &Map<String, Value>, key: &str) -> Option<String> {
363        row.get(key).and_then(Value::as_str).map(str::to_owned)
364    }
365
366    async fn deliver(delivery_id: i64, attempt: &Attempt) -> laravel::Result<()> {
367        let delivery: Option<Row> = db::table("webhook_deliveries")
368            .filter(col("id").eq(delivery_id))
369            .first()
370            .await?;
371        let Some(Row(delivery)) = delivery else {
372            return Ok(());
373        };
374        if text(&delivery, "status").as_deref() == Some(DELIVERED) {
375            return Ok(());
376        }
377        let endpoint_id = int(&delivery, "webhook_endpoint_id");
378        let endpoint: Option<Row> = db::table("webhook_endpoints")
379            .filter(col("id").eq(endpoint_id))
380            .first()
381            .await?;
382        let Some(Row(endpoint)) = endpoint else {
383            return Ok(());
384        };
385
386        if int(&endpoint, "active") == 0 {
387            update_delivery(
388                delivery_id,
389                values! { status: FAILED, error: "The endpoint is disabled.", updated_at: laravel::now().timestamp() },
390            )
391            .await?;
392            return Ok(());
393        }
394
395        let settings = settings();
396        let kind = text(&delivery, "event_type").unwrap_or_default();
397        let stored: Value = text(&delivery, "payload")
398            .and_then(|payload| serde_json::from_str(&payload).ok())
399            .unwrap_or(Value::Null);
400        let body = payload(stored, text(&endpoint, "version").as_deref(), &kind).to_string();
401        let secret =
402            laravel::crypt::decrypt_string(&text(&endpoint, "secret").unwrap_or_default())?;
403        let url = text(&endpoint, "url").unwrap_or_default();
404        let event_id = text(&delivery, "event_id").unwrap_or_default();
405
406        let started = Instant::now();
407        let sent = client::post(url.as_str())
408            .header("Webhook-Id", event_id.as_str())
409            .header(
410                super::Signer::HEADER,
411                super::Signer::sign(&body, &secret, time::now()),
412            )
413            .header("User-Agent", "Fusion Stack Webhooks")
414            .body(body, "application/json")
415            .timeout(i64::try_from(settings.timeout).unwrap_or(10).seconds())
416            .await;
417        let (status, error) = match sent {
418            Ok(response) if response.successful() => (Some(response.status().as_u16()), None),
419            Ok(response) => {
420                let status = response.status().as_u16();
421                (
422                    Some(status),
423                    Some(format!("The endpoint responded with {status}.")),
424                )
425            }
426            Err(error) => (None, Some(error.to_string())),
427        };
428
429        let attempts = int(&delivery, "attempts") + 1;
430        // The sync connection runs jobs inline and cannot delay them, so it gets no retries.
431        let retry_in = if error.is_none() || attempt.connection() == "sync" {
432            None
433        } else {
434            usize::try_from(attempts - 1)
435                .ok()
436                .and_then(|index| settings.backoff.get(index))
437                .copied()
438        };
439        let status_text = match (&error, retry_in) {
440            (None, _) => DELIVERED,
441            (Some(_), Some(_)) => PENDING,
442            (Some(_), None) => FAILED,
443        };
444        let now = laravel::now().timestamp();
445        update_delivery(
446            delivery_id,
447            values! {
448                status: status_text,
449                attempts: attempts,
450                response_status: status.map(i64::from),
451                duration_ms: i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX),
452                error: error.as_ref().map(|error| error.chars().take(1000).collect::<String>()),
453                delivered_at: error.is_none().then_some(now),
454                updated_at: now,
455            },
456        )
457        .await?;
458
459        match (error, retry_in) {
460            (None, _) => {
461                if int(&endpoint, "consecutive_failures") > 0 {
462                    db::table("webhook_endpoints")
463                        .filter(col("id").eq(endpoint_id))
464                        .update(values! { consecutive_failures: 0_i64 })
465                        .await?;
466                }
467            }
468            (Some(_), Some(delay)) => {
469                attempt.release(i64::try_from(delay).unwrap_or(i64::MAX).seconds());
470            }
471            (Some(_), None) => count_failure(&endpoint, endpoint_id, &settings).await?,
472        }
473        Ok(())
474    }
475
476    async fn update_delivery(id: i64, values: db::Values) -> laravel::Result<()> {
477        db::table("webhook_deliveries")
478            .filter(col("id").eq(id))
479            .update(values)
480            .await?;
481        Ok(())
482    }
483
484    /// Disables the endpoint when too many deliveries in a row have failed.
485    async fn count_failure(
486        endpoint: &Map<String, Value>,
487        id: i64,
488        settings: &Settings,
489    ) -> laravel::Result<()> {
490        let failures = int(endpoint, "consecutive_failures") + 1;
491        let disable = settings
492            .disable_after
493            .is_some_and(|limit| limit >= 1 && failures >= limit);
494        let now = laravel::now().timestamp();
495        let query = db::table("webhook_endpoints").filter(col("id").eq(id));
496        if disable {
497            query
498                .update(values! { consecutive_failures: failures, active: false, disabled_at: now, updated_at: now })
499                .await?;
500        } else {
501            query
502                .update(values! { consecutive_failures: failures })
503                .await?;
504        }
505        Ok(())
506    }
507
508    /// The delivery's payload in the endpoint's version: `data` and `included` pass through the
509    /// version changes newer than it, as a response would. Changes can target an event type as
510    /// the route `webhooks.order.created`.
511    pub(crate) fn payload(stored: Value, version: Option<&str>, kind: &str) -> Value {
512        let Some(registry) = state().and_then(|state| state.registry.as_ref()) else {
513            return stored;
514        };
515        let version = registry
516            .resolve(version, time::now())
517            .unwrap_or_else(|_| registry.default.clone());
518        let Value::Object(stored) = stored else {
519            return stored;
520        };
521        let mut document = Map::new();
522        let mut payload = Map::new();
523        for (key, value) in stored {
524            if key == "data" || key == "included" {
525                document.insert(key, value);
526            } else {
527                payload.insert(key, value);
528            }
529        }
530        let mut document = Value::Object(document);
531        let route = format!("webhooks.{kind}");
532        let types = versioning::document::types(&document);
533        for change in registry.changes_after(&version, None).iter().rev() {
534            if versioning::applies_to(change.as_ref(), &types, &route) {
535                change.transform_response(&mut document);
536            }
537        }
538        payload.insert("api_version".into(), Value::String(version.to_string()));
539        if let Value::Object(document) = document {
540            payload.extend(document);
541        }
542        Value::Object(payload)
543    }
544}
545
546#[cfg(test)]
547mod tests {
548    use super::Signer;
549
550    #[test]
551    fn signatures_verify_within_the_tolerance() {
552        let header = Signer::sign("{\"a\":1}", "whsec_x", 1_000);
553        assert!(header.starts_with("t=1000,v1="));
554        assert!(Signer::verify(
555            "{\"a\":1}",
556            Some(&header),
557            "whsec_x",
558            300,
559            1_200
560        ));
561        assert!(!Signer::verify(
562            "{\"a\":1}",
563            Some(&header),
564            "whsec_x",
565            300,
566            1_301
567        ));
568        assert!(!Signer::verify(
569            "{\"a\":2}",
570            Some(&header),
571            "whsec_x",
572            300,
573            1_000
574        ));
575        assert!(!Signer::verify(
576            "{\"a\":1}",
577            Some(&header),
578            "whsec_y",
579            300,
580            1_000
581        ));
582        // A second, older secret's signature alongside the current one still verifies.
583        let old = Signer::sign("{\"a\":1}", "whsec_old", 1_000);
584        let both = format!("{header},{}", old.split_once(',').unwrap_or_default().1);
585        assert!(Signer::verify(
586            "{\"a\":1}",
587            Some(&both),
588            "whsec_old",
589            300,
590            1_000
591        ));
592        assert!(!Signer::verify("{\"a\":1}", None, "whsec_x", 300, 1_000));
593    }
594
595    #[test]
596    fn signatures_match_php_hash_hmac() {
597        // php -r 'echo hash_hmac("sha256", "1700000000.{}", "whsec_test");'
598        assert_eq!(
599            Signer::sign("{}", "whsec_test", 1_700_000_000),
600            "t=1700000000,v1=35495024f4ef3f94e5a93e22221544c4b75e9a42300cd965ab81cb85cd994e91"
601        );
602    }
603}