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//!
10//! An endpoint's URL may come from a user, so a delivery is only sent to an address on the public
11//! internet ([`is_public`]) and redirects are not followed, unless
12//! [`Config::webhook_private_addresses`](crate::Config::webhook_private_addresses) allows it.
13
14use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
15
16use hmac::{Hmac, KeyInit, Mac};
17use sha2::Sha256;
18
19/// Signs and checks webhook bodies.
20pub struct Signer;
21
22impl Signer {
23    /// The request header that carries the signature.
24    pub const HEADER: &'static str = "Webhook-Signature";
25
26    /// The signature of `body` with `secret`, made at `timestamp` (unix seconds).
27    #[must_use]
28    pub fn sign(body: &str, secret: &str, timestamp: i64) -> String {
29        format!("t={timestamp},v1={}", hash(body, secret, timestamp))
30    }
31
32    /// Whether `header` is a valid signature of `body` with `secret`, made within `tolerance`
33    /// seconds of `now`. Any of several `v1` signatures may match, so a sender can sign with an
34    /// old and a new secret while receivers switch.
35    #[must_use]
36    pub fn verify(
37        body: &str,
38        header: Option<&str>,
39        secret: &str,
40        tolerance: i64,
41        now: i64,
42    ) -> bool {
43        let mut timestamp = None;
44        let mut signatures = Vec::new();
45        for part in header.unwrap_or_default().split(',') {
46            let (key, value) = part.trim().split_once('=').unwrap_or((part.trim(), ""));
47            if key == "t" && !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
48                timestamp = value.parse::<i64>().ok();
49            } else if key == "v1" && !value.is_empty() {
50                signatures.push(value);
51            }
52        }
53        let Some(timestamp) = timestamp.filter(|timestamp| (now - timestamp).abs() <= tolerance)
54        else {
55            return false;
56        };
57        let expected = hash(body, secret, timestamp);
58        signatures
59            .iter()
60            .any(|signature| constant_time_eq(expected.as_bytes(), signature.as_bytes()))
61    }
62}
63
64fn hash(body: &str, secret: &str, timestamp: i64) -> String {
65    let mut mac =
66        Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes keys of any length");
67    mac.update(format!("{timestamp}.{body}").as_bytes());
68    mac.finalize()
69        .into_bytes()
70        .iter()
71        .map(|byte| format!("{byte:02x}"))
72        .collect()
73}
74
75fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
76    a.len() == b.len() && a.iter().zip(b).fold(0, |diff, (x, y)| diff | (x ^ y)) == 0
77}
78
79/// Whether an IP address is on the public internet: globally reachable, as RFC 6890 lists them,
80/// which leaves out loopback, private networks and link-local addresses such as a cloud metadata
81/// service's. A NAT64 address counts as the IPv4 address it carries, which is where it connects.
82/// The same addresses as the PHP package's `PublicAddressHandler::isPublic`.
83#[must_use]
84pub fn is_public(address: IpAddr) -> bool {
85    match address {
86        IpAddr::V4(address) => is_public_v4(address),
87        IpAddr::V6(address) => is_public_v6(address),
88    }
89}
90
91fn is_public_v4(address: Ipv4Addr) -> bool {
92    let [a, b, c, _] = address.octets();
93    let special = a == 0
94        || a == 10
95        || (a == 100 && (64..=127).contains(&b))
96        || a == 127
97        || (a == 169 && b == 254)
98        || (a == 172 && (16..=31).contains(&b))
99        || (a == 192 && b == 0 && (c == 0 || c == 2))
100        || (a == 192 && b == 168)
101        || (a == 198 && (b == 18 || b == 19))
102        || (a == 198 && b == 51 && c == 100)
103        || (a == 203 && b == 0 && c == 113)
104        || a >= 240;
105    !special
106}
107
108fn is_public_v6(address: Ipv6Addr) -> bool {
109    let segments = address.segments();
110    // 64:ff9b::/96 carries an IPv4 address in its last four bytes; the rest of 64:ff9b::/32, such
111    // as 64:ff9b:1::/48, is for local use.
112    if segments[0] == 0x64 && segments[1] == 0xff9b {
113        let [.., a, b, c, d] = address.octets();
114        return segments[2..6] == [0; 4] && is_public_v4(Ipv4Addr::new(a, b, c, d));
115    }
116    let special = address.is_unspecified()
117        || address.is_loopback()
118        // IPv4-mapped addresses.
119        || segments[..6] == [0, 0, 0, 0, 0, 0xffff]
120        || segments[..4] == [0x100, 0, 0, 0]
121        // IETF protocol assignments (2001::/23), documentation and 6to4.
122        || (segments[0] == 0x2001 && segments[1] <= 0x1ff)
123        || (segments[0] == 0x2001 && segments[1] == 0xdb8)
124        || segments[0] == 0x2002
125        // Unique local and link-local.
126        || segments[0] & 0xfe00 == 0xfc00
127        || segments[0] & 0xffc0 == 0xfe80;
128    !special
129}
130
131#[cfg(feature = "database")]
132pub use self::store::*;
133
134#[cfg(feature = "database")]
135mod store {
136    use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
137    use std::time::Instant;
138
139    use laravel::db::{self, col, values};
140    use laravel::http::client;
141    use laravel::http::client::reqwest;
142    use laravel::prelude::ToSpan;
143    use laravel::queue::{Attempt, Queueable, job};
144    use serde_json::{Map, Value};
145
146    use crate::query::Row;
147    use crate::{State, glob, time, versioning};
148
149    /// The prefix of endpoint secrets.
150    pub const SECRET_PREFIX: &str = "whsec_";
151
152    /// A delivery waiting for its first or next attempt.
153    pub const PENDING: &str = "pending";
154    /// A delivery the endpoint accepted.
155    pub const DELIVERED: &str = "delivered";
156    /// A delivery that ran out of attempts.
157    pub const FAILED: &str = "failed";
158
159    /// An event to send to the endpoints that subscribe to its type.
160    #[derive(Debug, Clone)]
161    pub struct Event {
162        kind: String,
163        document: Value,
164        owner: Option<(String, i64)>,
165    }
166
167    impl Event {
168        /// An event of type `kind`, such as `order.created`, carrying a JSON:API document's `data`
169        /// and `included`, such as one from [`ApiQuery::document`](crate::query::ApiQuery::document).
170        #[must_use]
171        pub fn new(kind: impl Into<String>, document: Value) -> Self {
172            Self {
173                kind: kind.into(),
174                document,
175                owner: None,
176            }
177        }
178
179        /// Sends the event only to the endpoints of one owner, such as the order's team, by its
180        /// morph type and ID. Without an owner, every subscribed endpoint gets it.
181        #[must_use]
182        pub fn owner(mut self, kind: impl Into<String>, id: i64) -> Self {
183            self.owner = Some((kind.into(), id));
184            self
185        }
186
187        /// Records a delivery for each active endpoint that subscribes to the event, and queues
188        /// them. Returns the deliveries' IDs.
189        ///
190        /// # Errors
191        ///
192        /// When the tables can't be read or written, or a job can't be queued.
193        pub async fn dispatch(self) -> laravel::Result<Vec<i64>> {
194            let mut query = db::table("webhook_endpoints")
195                .select(["id", "events"])
196                .filter(col("active").eq(true));
197            if let Some((kind, id)) = &self.owner {
198                query = query
199                    .filter(col("owner_type").eq(kind.clone()))
200                    .filter(col("owner_id").eq(*id));
201            }
202            let rows: Vec<Row> = query.get().await?;
203            let endpoints: Vec<i64> = rows
204                .into_iter()
205                .filter(|row| subscribes_to(&row.0, &self.kind))
206                .filter_map(|row| row.0.get("id").and_then(Value::as_i64))
207                .collect();
208            if endpoints.is_empty() {
209                return Ok(Vec::new());
210            }
211
212            let mut payload = Map::new();
213            let event_id = format!("evt_{}", ulid::Ulid::new().to_string().to_lowercase());
214            payload.insert("id".into(), Value::String(event_id.clone()));
215            payload.insert("type".into(), Value::String(self.kind.clone()));
216            payload.insert("created_at".into(), Value::String(time::atom(time::now())));
217            for member in ["data", "included"] {
218                if let Some(value) = self.document.get(member).filter(|value| !value.is_null()) {
219                    payload.insert(member.into(), value.clone());
220                }
221            }
222            let payload = Value::Object(payload).to_string();
223
224            let settings = settings();
225            let mut deliveries = Vec::new();
226            for endpoint in endpoints {
227                let now = laravel::now().timestamp();
228                let id = db::table("webhook_deliveries")
229                    .insert_get_id(
230                        values! {
231                            webhook_endpoint_id: endpoint,
232                            event_id: event_id.clone(),
233                            event_type: self.kind.clone(),
234                            payload: payload.clone(),
235                            status: PENDING,
236                            attempts: 0_i64,
237                            created_at: now,
238                            updated_at: now,
239                        },
240                        "id",
241                    )
242                    .await?;
243                let mut job = DeliverWebhook { delivery_id: id }.dispatch();
244                if let Some(connection) = &settings.connection {
245                    job = job.on_connection(connection);
246                }
247                if let Some(queue) = &settings.queue {
248                    job = job.on_queue(queue);
249                }
250                job.await?;
251                deliveries.push(id);
252            }
253            Ok(deliveries)
254        }
255    }
256
257    fn subscribes_to(endpoint: &Map<String, Value>, kind: &str) -> bool {
258        endpoint
259            .get("events")
260            .and_then(Value::as_str)
261            .and_then(|events| serde_json::from_str::<Vec<String>>(events).ok())
262            .unwrap_or_default()
263            .iter()
264            .any(|pattern| glob(pattern, kind))
265    }
266
267    /// `api.webhooks` in the PHP package.
268    #[derive(Debug, Clone)]
269    pub(crate) struct Settings {
270        pub(crate) connection: Option<String>,
271        pub(crate) queue: Option<String>,
272        pub(crate) timeout: u64,
273        pub(crate) backoff: Vec<u64>,
274        pub(crate) disable_after: Option<i64>,
275        pub(crate) allow_private_addresses: bool,
276    }
277
278    impl Default for Settings {
279        fn default() -> Self {
280            Self {
281                connection: None,
282                queue: None,
283                timeout: 10,
284                backoff: vec![60, 300, 1800, 3600, 10_800, 21_600, 43_200],
285                disable_after: Some(5),
286                allow_private_addresses: false,
287            }
288        }
289    }
290
291    fn state() -> Option<&'static State> {
292        crate::STATE.get().map(AsRef::as_ref)
293    }
294
295    fn settings() -> Settings {
296        state()
297            .map(|state| state.config.webhooks.clone())
298            .unwrap_or_default()
299    }
300
301    /// Registers an endpoint with a new secret, subscribed to `events` (such as `["order.*"]`).
302    /// It is pinned to `version`, or to the latest version when versioning is on, so later
303    /// breaking changes never reach it until it is upgraded. Returns its ID.
304    ///
305    /// # Errors
306    ///
307    /// When the secret can't be encrypted (check `APP_KEY`) or the endpoint can't be written.
308    pub async fn register(
309        url: &str,
310        events: &[&str],
311        version: Option<&str>,
312        description: Option<&str>,
313    ) -> laravel::Result<i64> {
314        let version = version.map(str::to_owned).or_else(|| {
315            state()
316                .and_then(|state| state.registry.as_ref())
317                .map(|registry| registry.latest.to_string())
318        });
319        let secret = new_secret();
320        let now = laravel::now().timestamp();
321        db::table("webhook_endpoints")
322            .insert_get_id(
323                values! {
324                    url: url,
325                    description: description.map(str::to_owned),
326                    secret: laravel::crypt::encrypt_string(&secret)?,
327                    events: serde_json::to_string(events).unwrap_or_default(),
328                    version: version,
329                    active: true,
330                    consecutive_failures: 0_i64,
331                    created_at: now,
332                    updated_at: now,
333                },
334                "id",
335            )
336            .await
337    }
338
339    fn new_secret() -> String {
340        format!("{SECRET_PREFIX}{}", laravel::str::random(32))
341    }
342
343    /// An endpoint's secret, for a receiver that checks signatures.
344    ///
345    /// # Errors
346    ///
347    /// When there is no such endpoint, or its secret can't be decrypted.
348    pub async fn secret(endpoint: i64) -> laravel::Result<String> {
349        let row: Option<Row> = db::table("webhook_endpoints")
350            .select(["secret"])
351            .filter(col("id").eq(endpoint))
352            .first()
353            .await?;
354        let encrypted = row
355            .and_then(|row| {
356                row.0
357                    .get("secret")
358                    .and_then(Value::as_str)
359                    .map(str::to_owned)
360            })
361            .ok_or_else(|| laravel::Error::msg(format!("No webhook endpoint [{endpoint}].")))?;
362        laravel::crypt::decrypt_string(&encrypted)
363    }
364
365    /// Replaces an endpoint's secret, such as after a leak, and returns the new one. Receivers
366    /// must switch to it.
367    ///
368    /// # Errors
369    ///
370    /// When the endpoint can't be written.
371    pub async fn rotate_secret(endpoint: i64) -> laravel::Result<String> {
372        let secret = new_secret();
373        db::table("webhook_endpoints")
374            .filter(col("id").eq(endpoint))
375            .update(values! {
376                secret: laravel::crypt::encrypt_string(&secret)?,
377                updated_at: laravel::now().timestamp(),
378            })
379            .await?;
380        Ok(secret)
381    }
382
383    /// Turns an endpoint back on, such as after it was disabled for failing, with a clean slate.
384    ///
385    /// # Errors
386    ///
387    /// When the endpoint can't be written.
388    pub async fn enable(endpoint: i64) -> laravel::Result<()> {
389        db::table("webhook_endpoints")
390            .filter(col("id").eq(endpoint))
391            .update(values! {
392                active: true,
393                consecutive_failures: 0_i64,
394                disabled_at: None::<String>,
395                updated_at: laravel::now().timestamp(),
396            })
397            .await?;
398        Ok(())
399    }
400
401    /// Posts one delivery to its endpoint.
402    #[derive(Queueable)]
403    pub struct DeliverWebhook {
404        pub delivery_id: i64,
405    }
406
407    // Retries come from `api.webhooks.backoff` and the delivery's own attempt count, so the job
408    // allows as many attempts as a week of releases may need.
409    #[job(name = "fusion-stack.deliver-webhook", retry_for = 7.days())]
410    impl DeliverWebhook {
411        async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
412            deliver(self.delivery_id, attempt).await
413        }
414    }
415
416    fn int(row: &Map<String, Value>, key: &str) -> i64 {
417        match row.get(key) {
418            Some(Value::Bool(value)) => i64::from(*value),
419            Some(value) => value.as_i64().unwrap_or_default(),
420            None => 0,
421        }
422    }
423
424    fn text(row: &Map<String, Value>, key: &str) -> Option<String> {
425        row.get(key).and_then(Value::as_str).map(str::to_owned)
426    }
427
428    async fn deliver(delivery_id: i64, attempt: &Attempt) -> laravel::Result<()> {
429        let delivery: Option<Row> = db::table("webhook_deliveries")
430            .filter(col("id").eq(delivery_id))
431            .first()
432            .await?;
433        let Some(Row(delivery)) = delivery else {
434            return Ok(());
435        };
436        if text(&delivery, "status").as_deref() == Some(DELIVERED) {
437            return Ok(());
438        }
439        let endpoint_id = int(&delivery, "webhook_endpoint_id");
440        let endpoint: Option<Row> = db::table("webhook_endpoints")
441            .filter(col("id").eq(endpoint_id))
442            .first()
443            .await?;
444        let Some(Row(endpoint)) = endpoint else {
445            return Ok(());
446        };
447
448        if int(&endpoint, "active") == 0 {
449            update_delivery(
450                delivery_id,
451                values! { status: FAILED, error: "The endpoint is disabled.", updated_at: laravel::now().timestamp() },
452            )
453            .await?;
454            return Ok(());
455        }
456
457        let settings = settings();
458        let kind = text(&delivery, "event_type").unwrap_or_default();
459        let stored: Value = text(&delivery, "payload")
460            .and_then(|payload| serde_json::from_str(&payload).ok())
461            .unwrap_or(Value::Null);
462        let body = payload(stored, text(&endpoint, "version").as_deref(), &kind).to_string();
463        let secret =
464            laravel::crypt::decrypt_string(&text(&endpoint, "secret").unwrap_or_default())?;
465        let url = text(&endpoint, "url").unwrap_or_default();
466        let event_id = text(&delivery, "event_id").unwrap_or_default();
467
468        let started = Instant::now();
469        let destination = if settings.allow_private_addresses {
470            Destination::Unchecked
471        } else {
472            let url = url.clone();
473            laravel::task::spawn_blocking(move || Destination::of(&url, lookup)).await?
474        };
475        let (status, error) = if let Destination::Refused(reason) = destination {
476            (None, Some(reason))
477        } else {
478            let sent = client::post(url.as_str())
479                .header("Webhook-Id", event_id.as_str())
480                .header(
481                    super::Signer::HEADER,
482                    super::Signer::sign(&body, &secret, time::now()),
483                )
484                .header("User-Agent", "Fusion Stack Webhooks")
485                .body(body, "application/json")
486                .timeout(i64::try_from(settings.timeout).unwrap_or(10).seconds())
487                .configure_transport(move |transport| destination.apply(transport))
488                .await;
489            match sent {
490                Ok(response) if response.successful() => (Some(response.status().as_u16()), None),
491                Ok(response) => {
492                    let status = response.status().as_u16();
493                    (
494                        Some(status),
495                        Some(format!("The endpoint responded with {status}.")),
496                    )
497                }
498                Err(error) => (None, Some(error.to_string())),
499            }
500        };
501
502        let attempts = int(&delivery, "attempts") + 1;
503        // The sync connection runs jobs inline and cannot delay them, so it gets no retries.
504        let retry_in = if error.is_none() || attempt.connection() == "sync" {
505            None
506        } else {
507            usize::try_from(attempts - 1)
508                .ok()
509                .and_then(|index| settings.backoff.get(index))
510                .copied()
511        };
512        let status_text = match (&error, retry_in) {
513            (None, _) => DELIVERED,
514            (Some(_), Some(_)) => PENDING,
515            (Some(_), None) => FAILED,
516        };
517        let now = laravel::now().timestamp();
518        update_delivery(
519            delivery_id,
520            values! {
521                status: status_text,
522                attempts: attempts,
523                response_status: status.map(i64::from),
524                duration_ms: i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX),
525                error: error.as_ref().map(|error| error.chars().take(1000).collect::<String>()),
526                delivered_at: error.is_none().then_some(now),
527                updated_at: now,
528            },
529        )
530        .await?;
531
532        match (error, retry_in) {
533            (None, _) => {
534                if int(&endpoint, "consecutive_failures") > 0 {
535                    db::table("webhook_endpoints")
536                        .filter(col("id").eq(endpoint_id))
537                        .update(values! { consecutive_failures: 0_i64 })
538                        .await?;
539                }
540            }
541            (Some(_), Some(delay)) => {
542                attempt.release(i64::try_from(delay).unwrap_or(i64::MAX).seconds());
543            }
544            (Some(_), None) => count_failure(&endpoint, endpoint_id, &settings).await?,
545        }
546        Ok(())
547    }
548
549    /// Where a delivery's request may connect, decided before it is sent so that it cannot reach
550    /// what only the server can.
551    #[derive(Debug, Clone, PartialEq, Eq)]
552    pub(crate) enum Destination {
553        /// Private addresses are allowed, so the host is not looked at.
554        Unchecked,
555        /// The host is a public IP address, or the URL is one the client rejects itself.
556        Direct,
557        /// A host name whose addresses are all public. The request connects only to them, so a
558        /// second DNS answer cannot move it somewhere else.
559        Pinned(String, Vec<SocketAddr>),
560        /// A host name that resolved to nothing, or to an address that is not public. The request
561        /// fails with the reason in place of a DNS lookup; an HTTP fake still answers it first.
562        Unreachable(String),
563        /// An IP address that is not public. The request is not sent, faked or not.
564        Refused(String),
565    }
566
567    impl Destination {
568        /// The destination for an endpoint's URL. `lookup` gives a host name's addresses.
569        pub(crate) fn of(url: &str, lookup: impl FnOnce(&str, u16) -> Vec<SocketAddr>) -> Self {
570            // The client parses the URL with the same parser, so both read the same host.
571            let Ok(url) = reqwest::Url::parse(url) else {
572                return Self::Direct;
573            };
574            let Some(host) = url.host_str() else {
575                return Self::Direct;
576            };
577            let private = || {
578                format!(
579                    "The endpoint's host [{}] is not on the public internet, so the webhook was not sent.",
580                    host.trim_matches(['[', ']'])
581                )
582            };
583            if let Ok(address) = host.trim_matches(['[', ']']).parse::<IpAddr>() {
584                return if super::is_public(address) {
585                    Self::Direct
586                } else {
587                    Self::Refused(private())
588                };
589            }
590            let addresses = lookup(host, url.port_or_known_default().unwrap_or(443));
591            if addresses.is_empty() {
592                return Self::Unreachable(format!(
593                    "The endpoint's host [{host}] could not be resolved, so the webhook was not sent."
594                ));
595            }
596            if addresses
597                .iter()
598                .all(|address| super::is_public(address.ip()))
599            {
600                Self::Pinned(host.to_owned(), addresses)
601            } else {
602                Self::Unreachable(private())
603            }
604        }
605
606        /// Makes the request's transport keep to the destination. A redirect is never followed:
607        /// it could lead anywhere, and the signed body with it.
608        fn apply(&self, transport: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
609            let transport = transport.redirect(reqwest::redirect::Policy::none());
610            match self {
611                Self::Pinned(host, addresses) => transport.resolve_to_addrs(host, addresses),
612                Self::Unreachable(reason) => transport.dns_resolver(NoLookup(reason.clone())),
613                Self::Unchecked | Self::Direct | Self::Refused(_) => transport,
614            }
615        }
616    }
617
618    /// The system resolver's addresses for a host name, or none when it has none.
619    fn lookup(host: &str, port: u16) -> Vec<SocketAddr> {
620        (host, port)
621            .to_socket_addrs()
622            .map(Iterator::collect)
623            .unwrap_or_default()
624    }
625
626    /// A DNS resolver that fails every lookup with the reason the destination is unreachable.
627    struct NoLookup(String);
628
629    impl reqwest::dns::Resolve for NoLookup {
630        fn resolve(&self, _name: reqwest::dns::Name) -> reqwest::dns::Resolving {
631            let reason = self.0.clone();
632            Box::pin(async move { Err(reason.into()) })
633        }
634    }
635
636    async fn update_delivery(id: i64, values: db::Values) -> laravel::Result<()> {
637        db::table("webhook_deliveries")
638            .filter(col("id").eq(id))
639            .update(values)
640            .await?;
641        Ok(())
642    }
643
644    /// Disables the endpoint when too many deliveries in a row have failed.
645    async fn count_failure(
646        endpoint: &Map<String, Value>,
647        id: i64,
648        settings: &Settings,
649    ) -> laravel::Result<()> {
650        let failures = int(endpoint, "consecutive_failures") + 1;
651        let disable = settings
652            .disable_after
653            .is_some_and(|limit| limit >= 1 && failures >= limit);
654        let now = laravel::now().timestamp();
655        let query = db::table("webhook_endpoints").filter(col("id").eq(id));
656        if disable {
657            query
658                .update(values! { consecutive_failures: failures, active: false, disabled_at: now, updated_at: now })
659                .await?;
660        } else {
661            query
662                .update(values! { consecutive_failures: failures })
663                .await?;
664        }
665        Ok(())
666    }
667
668    /// The delivery's payload in the endpoint's version: `data` and `included` pass through the
669    /// version changes newer than it, as a response would. Changes can target an event type as
670    /// the route `webhooks.order.created`.
671    pub(crate) fn payload(stored: Value, version: Option<&str>, kind: &str) -> Value {
672        let Some(registry) = state().and_then(|state| state.registry.as_ref()) else {
673            return stored;
674        };
675        let version = registry
676            .resolve(version, time::now())
677            .unwrap_or_else(|_| registry.default.clone());
678        let Value::Object(stored) = stored else {
679            return stored;
680        };
681        let mut document = Map::new();
682        let mut payload = Map::new();
683        for (key, value) in stored {
684            if key == "data" || key == "included" {
685                document.insert(key, value);
686            } else {
687                payload.insert(key, value);
688            }
689        }
690        let mut document = Value::Object(document);
691        let route = format!("webhooks.{kind}");
692        let types = versioning::document::types(&document);
693        for change in registry.changes_after(&version, None).iter().rev() {
694            if versioning::applies_to(change.as_ref(), &types, &route) {
695                change.transform_response(&mut document);
696            }
697        }
698        payload.insert("api_version".into(), Value::String(version.to_string()));
699        if let Value::Object(document) = document {
700            payload.extend(document);
701        }
702        Value::Object(payload)
703    }
704}
705
706#[cfg(test)]
707mod tests {
708    use std::net::IpAddr;
709
710    use super::{Signer, is_public};
711
712    #[test]
713    fn tells_public_addresses_from_private_ones() {
714        // The list both packages check, from spec/webhook-addresses.json.
715        let addresses: serde_json::Value = serde_json::from_str(include_str!(concat!(
716            env!("CARGO_MANIFEST_DIR"),
717            "/tests/fixtures/webhook-addresses.json"
718        )))
719        .unwrap_or_default();
720        let verdicts = |list: &str| -> Vec<(String, bool)> {
721            addresses[list]
722                .as_array()
723                .into_iter()
724                .flatten()
725                .filter_map(serde_json::Value::as_str)
726                .map(|address| {
727                    let parsed: Option<IpAddr> = address.parse().ok();
728                    (address.to_owned(), parsed.is_some_and(is_public))
729                })
730                .collect()
731        };
732        let (public, private) = (verdicts("public"), verdicts("private"));
733        assert!(public.len() > 5 && private.len() > 20);
734        assert_eq!(
735            public
736                .iter()
737                .filter(|(_, public)| !public)
738                .collect::<Vec<_>>(),
739            Vec::<&(String, bool)>::new()
740        );
741        assert_eq!(
742            private
743                .iter()
744                .filter(|(_, public)| *public)
745                .collect::<Vec<_>>(),
746            Vec::<&(String, bool)>::new()
747        );
748    }
749
750    #[cfg(feature = "database")]
751    #[test]
752    fn deliveries_connect_only_to_public_addresses_they_checked() {
753        use std::net::SocketAddr;
754
755        use super::Destination;
756
757        let address = |address: &str| -> SocketAddr { address.parse().expect("a socket address") };
758        let never =
759            |_: &str, _: u16| -> Vec<SocketAddr> { panic!("an IP address is not looked up") };
760        let private = |host: &str| {
761            format!(
762                "The endpoint's host [{host}] is not on the public internet, so the webhook was not sent."
763            )
764        };
765
766        for (url, host) in [
767            ("http://127.0.0.1:9/hooks", "127.0.0.1"),
768            // The URL parser reads other spellings of an IPv4 address as the address.
769            ("http://2130706433:9/hooks", "127.0.0.1"),
770            ("http://0x7f.1/hooks", "127.0.0.1"),
771            ("http://[::1]:9/hooks", "::1"),
772            ("http://169.254.169.254/latest/meta-data", "169.254.169.254"),
773            ("https://10.0.0.5/hooks", "10.0.0.5"),
774        ] {
775            assert_eq!(
776                Destination::of(url, never),
777                Destination::Refused(private(host)),
778                "{url}"
779            );
780        }
781        assert_eq!(
782            Destination::of("https://93.184.216.34/hooks", never),
783            Destination::Direct
784        );
785
786        // A name is pinned to the addresses it resolved to, looked up with the URL's port.
787        let public = vec![
788            address("93.184.216.34:443"),
789            address("[2606:4700:4700::1111]:443"),
790        ];
791        assert_eq!(
792            Destination::of("https://hooks.example.com/orders", |host, port| {
793                assert_eq!((host, port), ("hooks.example.com", 443));
794                public.clone()
795            }),
796            Destination::Pinned("hooks.example.com".to_owned(), public.clone())
797        );
798        assert_eq!(
799            Destination::of("http://hooks.example.com:8080/orders", |_, port| vec![
800                SocketAddr::new(public[0].ip(), port)
801            ]),
802            Destination::Pinned(
803                "hooks.example.com".to_owned(),
804                vec![address("93.184.216.34:8080")]
805            )
806        );
807
808        // A name that resolves to a private address among public ones, or to nothing, is refused.
809        assert_eq!(
810            Destination::of("https://hooks.example.com/orders", |_, _| vec![
811                public[0],
812                address("10.0.0.5:443")
813            ]),
814            Destination::Unreachable(private("hooks.example.com"))
815        );
816        assert_eq!(
817            Destination::of("https://localhost/hooks", |_, _| vec![address(
818                "127.0.0.1:443"
819            )]),
820            Destination::Unreachable(private("localhost"))
821        );
822        assert_eq!(
823            Destination::of("https://nowhere.example.com/hooks", |_, _| Vec::new()),
824            Destination::Unreachable(
825                "The endpoint's host [nowhere.example.com] could not be resolved, so the webhook was not sent.".to_owned()
826            )
827        );
828    }
829
830    #[test]
831    fn signatures_verify_within_the_tolerance() {
832        let header = Signer::sign("{\"a\":1}", "whsec_x", 1_000);
833        assert!(header.starts_with("t=1000,v1="));
834        assert!(Signer::verify(
835            "{\"a\":1}",
836            Some(&header),
837            "whsec_x",
838            300,
839            1_200
840        ));
841        assert!(!Signer::verify(
842            "{\"a\":1}",
843            Some(&header),
844            "whsec_x",
845            300,
846            1_301
847        ));
848        assert!(!Signer::verify(
849            "{\"a\":2}",
850            Some(&header),
851            "whsec_x",
852            300,
853            1_000
854        ));
855        assert!(!Signer::verify(
856            "{\"a\":1}",
857            Some(&header),
858            "whsec_y",
859            300,
860            1_000
861        ));
862        // A second, older secret's signature alongside the current one still verifies.
863        let old = Signer::sign("{\"a\":1}", "whsec_old", 1_000);
864        let both = format!("{header},{}", old.split_once(',').unwrap_or_default().1);
865        assert!(Signer::verify(
866            "{\"a\":1}",
867            Some(&both),
868            "whsec_old",
869            300,
870            1_000
871        ));
872        assert!(!Signer::verify("{\"a\":1}", None, "whsec_x", 300, 1_000));
873    }
874
875    #[test]
876    fn signatures_match_php_hash_hmac() {
877        // php -r 'echo hash_hmac("sha256", "1700000000.{}", "whsec_test");'
878        assert_eq!(
879            Signer::sign("{}", "whsec_test", 1_700_000_000),
880            "t=1700000000,v1=35495024f4ef3f94e5a93e22221544c4b75e9a42300cd965ab81cb85cd994e91"
881        );
882    }
883}