Skip to main content

glacier/webhooks/
mod.rs

1//! Receiving webhooks: verify the sender's signature, store the event
2//! once, answer `200` at once, and handle it in a job, as pay does, but
3//! with every event kept for replay and deduplicated on its provider's id.
4//!
5//! ```ignore
6//! App::new().webhooks(
7//!     Webhooks::new().provider(
8//!         Stripe::new(&[&std::env::var("STRIPE_SIGNING_SECRET")?])
9//!             .on("checkout.session.completed", |event: Event| async move {
10//!                 let session = event.payload()["data"]["object"].clone();
11//!                 // … sync from Stripe, upsert …
12//!                 Ok(())
13//!             }),
14//!     ),
15//! )
16//! // routes: post "/webhooks/:provider" => glacier::webhooks::receive
17//! ```
18//!
19//! The table comes from a migration: `glacier::webhooks::create_table(s)`.
20//! Only events something handles are stored; others are answered `200`
21//! and forgotten. A delivery the provider repeats is stored once and
22//! handled once; within a handler, [`Event::once`] keeps a side effect
23//! (an email, a charge) from happening twice if the handler is retried.
24
25mod verify;
26
27use std::collections::HashMap;
28use std::future::Future;
29use std::pin::Pin;
30use std::sync::{Arc, RwLock};
31
32use http::{HeaderMap, StatusCode};
33use serde::{Deserialize, Serialize};
34
35pub use self::verify::{
36    GitHub, Hmac, HmacProvider, LemonSqueezy, Paddle, Shopify, Stripe, sign_hex,
37};
38use crate::context::Context;
39use crate::db::migration::Schema;
40use crate::db::{self, Sql, Timestamp, Value};
41use crate::error::{Error, Result};
42use crate::jobs::Job;
43use crate::response::Response;
44
45const TABLE: &str = "webhook_events";
46const ONCE_TABLE: &str = "webhook_effects";
47
48/// The tables, for a migration's `up`.
49pub fn create_table(s: &mut Schema) {
50    s.create_table(TABLE, |t| {
51        t.string("provider").not_null();
52        t.string("event_id").not_null();
53        t.string("event_type").not_null();
54        t.text("body").not_null();
55        t.string("status").not_null().default("received");
56        t.integer("attempts").not_null().default(0);
57        t.text("last_error");
58        t.timestamp("processed_at");
59        t.timestamps();
60    });
61    s.add_unique_index(TABLE, &["provider", "event_id"]);
62    s.add_index(TABLE, &["status"]);
63    s.create_table(ONCE_TABLE, |t| {
64        t.string("key").not_null().unique();
65        t.timestamps();
66    });
67}
68
69/// A stored event, as its handler gets it.
70#[derive(Debug, Clone)]
71pub struct Event {
72    /// The row's id in `webhook_events`.
73    pub id: i64,
74    pub provider: String,
75    /// The provider's id for it: `evt_1…` from Stripe.
76    pub event_id: String,
77    /// `checkout.session.completed`, `push`, …
78    pub event_type: String,
79    /// The body as the provider sent it.
80    pub body: String,
81}
82
83impl Event {
84    /// The body as JSON (`Null` if it isn't).
85    pub fn payload(&self) -> serde_json::Value {
86        serde_json::from_str(&self.body).unwrap_or_default()
87    }
88
89    /// The body as a type of the app's own.
90    ///
91    /// # Errors
92    ///
93    /// When the body doesn't fit it.
94    pub fn parse<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
95        serde_json::from_str(&self.body)
96            .map_err(|e| Error::internal(format!("{} event {}: {e}", self.provider, self.event_id)))
97    }
98
99    /// Runs `effect` once for this event and `name`, however often the
100    /// handler runs: a retried handler doesn't email or charge twice. The
101    /// effect is recorded in the same transaction as its writes, when it
102    /// succeeds; returns whether it ran this time. Its value, such as
103    /// `deliver_later`'s job id, is dropped.
104    ///
105    /// # Errors
106    ///
107    /// The effect's own error, which leaves it to run on the next try.
108    pub async fn once<F, T>(&self, name: &str, effect: F) -> Result<bool>
109    where
110        F: Future<Output = Result<T>>,
111    {
112        let key = format!("{}:{}:{name}", self.provider, self.event_id);
113        db::transaction(async {
114            let now = crate::time::now();
115            let mut sql = Sql::new();
116            sql.push(&format!(
117                "INSERT INTO {ONCE_TABLE} (key, inserted_at, updated_at) VALUES ("
118            ));
119            sql.push_value(Value::Text(key.clone()));
120            sql.push(", ");
121            sql.push_value(Value::Timestamp(now));
122            sql.push(", ");
123            sql.push_value(Value::Timestamp(now));
124            sql.push(") ON CONFLICT (key) DO NOTHING");
125            if db::current()?.execute(&sql).await? == 0 {
126                return Ok(false);
127            }
128            effect.await?;
129            Ok(true)
130        })
131        .await
132    }
133}
134
135type Handler = Arc<dyn Fn(Event) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync>;
136
137/// Checks that a request came from the provider, and names the event.
138pub trait Verify: Send + Sync + 'static {
139    /// `Ok` when the signature is good.
140    ///
141    /// # Errors
142    ///
143    /// Why it isn't, for the log (the sender only sees `400`).
144    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()>;
145
146    /// The provider's id and type for the event in the request.
147    ///
148    /// # Errors
149    ///
150    /// When the request doesn't say.
151    fn identify(&self, headers: &HeaderMap, body: &[u8]) -> Result<(String, String)>;
152}
153
154/// One provider: how its requests are verified, and its event handlers.
155pub struct Provider {
156    name: String,
157    verify: Box<dyn Verify>,
158    handlers: HashMap<String, Handler>,
159}
160
161impl Provider {
162    /// A provider called `name` (the `:provider` in its URL), verified by
163    /// `verify`. The built-in ones are made with `Stripe::new(…)` and so on.
164    pub fn new(name: &str, verify: impl Verify) -> Self {
165        Self {
166            name: name.to_owned(),
167            verify: Box::new(verify),
168            handlers: HashMap::new(),
169        }
170    }
171
172    /// Handles events of `event_type` (`"*"` for any not handled
173    /// otherwise). The handler runs in a job, retried if it fails.
174    #[must_use]
175    pub fn on<F, Fut>(mut self, event_type: &str, handler: F) -> Self
176    where
177        F: Fn(Event) -> Fut + Send + Sync + 'static,
178        Fut: Future<Output = Result<()>> + Send + 'static,
179    {
180        let handler: Handler = Arc::new(move |event| Box::pin(handler(event)));
181        self.handlers.insert(event_type.to_owned(), handler);
182        self
183    }
184
185    fn handler(&self, event_type: &str) -> Option<&Handler> {
186        self.handlers
187            .get(event_type)
188            .or_else(|| self.handlers.get("*"))
189    }
190}
191
192/// The app's webhook providers, for `App::webhooks`.
193#[derive(Clone, Default)]
194pub struct Webhooks(Arc<HashMap<String, Provider>>);
195
196impl Webhooks {
197    pub fn new() -> Self {
198        Self::default()
199    }
200
201    /// Adds a provider; its name is the `:provider` in the URL.
202    #[must_use]
203    pub fn provider(mut self, provider: Provider) -> Self {
204        Arc::get_mut(&mut self.0)
205            .expect("Webhooks is built before the app starts")
206            .insert(provider.name.clone(), provider);
207        self
208    }
209
210    /// Queues stored event `id` to be handled again, whatever happened
211    /// last time: `glacier webhooks replay ID`. `false` if there's no
212    /// such event.
213    pub async fn replay(id: i64) -> Result<bool> {
214        let mut sql = Sql::new();
215        sql.push(&format!(
216            "UPDATE {TABLE} SET status = 'received', last_error = NULL, updated_at = "
217        ));
218        sql.push_value(Value::Timestamp(crate::time::now()));
219        sql.push(" WHERE id = ");
220        sql.push_value(Value::Int(id));
221        if db::current()?.execute(&sql).await? == 0 {
222            return Ok(false);
223        }
224        HandleWebhook { id }.enqueue().await?;
225        Ok(true)
226    }
227}
228
229/// Deletes events handled more than `age` ago, and `once` records as
230/// old, keeping events not yet handled or failed; how many events it
231/// deleted. Run
232/// it from the jobs scheduler:
233/// `Jobs::new().prune_with("webhook_events", || glacier::webhooks::prune(30.days()))`.
234pub async fn prune(age: chrono::TimeDelta) -> Result<u64> {
235    let before = crate::time::now() - age;
236    let mut sql = Sql::new();
237    sql.push(&format!(
238        "DELETE FROM {TABLE} WHERE status = 'processed' AND processed_at < "
239    ));
240    sql.push_value(Value::Timestamp(before));
241    let deleted = db::current()?.execute(&sql).await?;
242    let mut sql = Sql::new();
243    sql.push(&format!("DELETE FROM {ONCE_TABLE} WHERE inserted_at < "));
244    sql.push_value(Value::Timestamp(before));
245    db::current()?.execute(&sql).await?;
246    Ok(deleted)
247}
248
249static INSTALLED: RwLock<Option<Webhooks>> = RwLock::new(None);
250
251tokio::task_local! {
252    /// A test's own providers, from `#[glacier::test]`.
253    static TEST_SLOT: Arc<RwLock<Option<Webhooks>>>;
254}
255
256/// Runs `fut` with a providers slot of its own. `#[glacier::test]` does this.
257#[doc(hidden)]
258pub async fn with_test_slot<F: Future>(fut: F) -> F::Output {
259    TEST_SLOT.scope(Arc::default(), fut).await
260}
261
262/// Makes the providers the ones requests and jobs use (in a test, the
263/// test's). `App::webhooks` calls it.
264pub(crate) fn install(webhooks: Webhooks) {
265    let in_test = TEST_SLOT
266        .try_with(|slot| *slot.write().unwrap_or_else(|e| e.into_inner()) = Some(webhooks.clone()))
267        .is_ok();
268    if !in_test {
269        *INSTALLED.write().unwrap_or_else(|e| e.into_inner()) = Some(webhooks);
270    }
271}
272
273fn installed() -> Option<Webhooks> {
274    TEST_SLOT
275        .try_with(|slot| slot.read().unwrap_or_else(|e| e.into_inner()).clone())
276        .ok()
277        .flatten()
278        .or_else(|| INSTALLED.read().unwrap_or_else(|e| e.into_inner()).clone())
279}
280
281/// The action for `post "/webhooks/:provider"`: verifies the request,
282/// stores the event once, queues its handling, and answers `200`. A
283/// request that fails verification is answered `400`; an event nothing
284/// handles, `200` without being stored.
285pub async fn receive(ctx: Context) -> Result<Response> {
286    let name = ctx.param("provider").unwrap_or_default().to_owned();
287    let webhooks = installed().unwrap_or_default();
288    let provider = webhooks.0.get(&name).ok_or_else(Error::not_found)?;
289    let (headers, body) = (ctx.headers(), ctx.body());
290    if let Err(err) = provider.verify.verify(headers, body) {
291        tracing::warn!(target: "glacier::webhooks", provider = %name, "rejected: {}", err.message());
292        return Ok(Response::text("invalid signature").with_status(StatusCode::BAD_REQUEST));
293    }
294    let (event_id, event_type) = provider.verify.identify(headers, body)?;
295    if provider.handler(&event_type).is_none() {
296        return Ok(Response::text("ignored"));
297    }
298    let body = String::from_utf8_lossy(body).into_owned();
299    db::transaction(async {
300        let now = crate::time::now();
301        let mut sql = Sql::new();
302        sql.push(&format!(
303            "INSERT INTO {TABLE} (provider, event_id, event_type, body, status, attempts, inserted_at, updated_at) VALUES ("
304        ));
305        let values = [
306            Value::Text(name.clone()),
307            Value::Text(event_id.clone()),
308            Value::Text(event_type.clone()),
309            Value::Text(body),
310            Value::Text("received".to_owned()),
311            Value::Int(0),
312            Value::Timestamp(now),
313            Value::Timestamp(now),
314        ];
315        for (i, value) in values.into_iter().enumerate() {
316            if i > 0 {
317                sql.push(", ");
318            }
319            sql.push_value(value);
320        }
321        sql.push(") ON CONFLICT (provider, event_id) DO NOTHING RETURNING id");
322        let rows = db::current()?.fetch_all(&sql).await?;
323        // Already stored: the provider sent it again.
324        if let Some(row) = rows.first() {
325            let id = row.get::<i64>("id").or_else(|_| row.get::<i32>("id").map(i64::from))?;
326            HandleWebhook { id }.enqueue().await?;
327        }
328        Ok(())
329    })
330    .await?;
331    Ok(Response::text("ok"))
332}
333
334/// The job that hands a stored event to its handler.
335#[derive(Serialize, Deserialize)]
336pub struct HandleWebhook {
337    pub id: i64,
338}
339
340impl Job for HandleWebhook {
341    const NAME: &'static str = "glacier_handle_webhook";
342    const QUEUE: &'static str = "webhooks";
343    const MAX_ATTEMPTS: i32 = 8;
344
345    async fn perform(self) -> Result<()> {
346        let mut sql = Sql::new();
347        sql.push(&format!(
348            "SELECT id, provider, event_id, event_type, body, status, attempts FROM {TABLE} WHERE id = "
349        ));
350        sql.push_value(Value::Int(self.id));
351        let rows = db::current()?.fetch_all(&sql).await?;
352        let Some(row) = rows.first() else {
353            return Ok(());
354        };
355        let status: String = row.get("status")?;
356        if status == "processed" {
357            return Ok(());
358        }
359        let event = Event {
360            id: self.id,
361            provider: row.get("provider")?,
362            event_id: row.get("event_id")?,
363            event_type: row.get("event_type")?,
364            body: row.get("body")?,
365        };
366        let attempts: i32 = row
367            .get::<i32>("attempts")
368            .or_else(|_| row.get::<i64>("attempts").map(|n| n as i32))?;
369        let handler = installed().and_then(|webhooks| {
370            webhooks
371                .0
372                .get(&event.provider)?
373                .handler(&event.event_type)
374                .cloned()
375        });
376        let outcome = match handler {
377            // Webhooks act for no user: the provider sent them.
378            Some(handler) => {
379                let span = tracing::info_span!(
380                    target: "glacier::webhooks",
381                    "glacier.webhook",
382                    otel.name = %format!("{} {}", event.provider, event.event_type),
383                    otel.kind = "consumer",
384                    webhook.provider = %event.provider,
385                    webhook.event_id = %event.event_id,
386                    webhook.event_type = %event.event_type,
387                );
388                tracing::Instrument::instrument(
389                    crate::access::unscoped("webhook", handler(event)),
390                    span,
391                )
392                .await
393            }
394            None => Err(Error::internal("no handler for this event any more")),
395        };
396        let (status, error, processed) = match &outcome {
397            Ok(()) => ("processed", None, Some(crate::time::now())),
398            Err(err) => ("failed", Some(err.to_string()), None),
399        };
400        mark(self.id, status, attempts + 1, error, processed).await?;
401        outcome
402    }
403}
404
405async fn mark(
406    id: i64,
407    status: &str,
408    attempts: i32,
409    error: Option<String>,
410    processed: Option<Timestamp>,
411) -> Result<()> {
412    let mut sql = Sql::new();
413    sql.push(&format!("UPDATE {TABLE} SET status = "));
414    sql.push_value(Value::Text(status.to_owned()));
415    sql.push(", attempts = ");
416    sql.push_value(Value::Int(i64::from(attempts)));
417    sql.push(", last_error = ");
418    sql.push_value(error.map_or(Value::Null, Value::Text));
419    sql.push(", processed_at = ");
420    sql.push_value(processed.map_or(Value::Null, Value::Timestamp));
421    sql.push(", updated_at = ");
422    sql.push_value(Value::Timestamp(crate::time::now()));
423    sql.push(" WHERE id = ");
424    sql.push_value(Value::Int(id));
425    db::current()?.execute(&sql).await?;
426    Ok(())
427}