fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Webhooks, as the PHP package sends them: endpoints subscribe to event types (with patterns such
//! as `order.*`) and are pinned to a version, events are recorded as one delivery per subscribed
//! endpoint, and a queued job posts each delivery, signed with the endpoint's secret, in the
//! endpoint's version. Failed deliveries are retried after the configured delays, and an endpoint
//! whose deliveries fail too many times in a row is disabled.
//!
//! Receivers check `Webhook-Signature` with [`Signer::verify`]; it is `t=<unix time>,v1=<hex>`,
//! where the hex is an HMAC-SHA256 of `<unix time>.<body>` with the endpoint's secret.
//!
//! An endpoint's URL may come from a user, so a delivery is only sent to an address on the public
//! internet ([`is_public`]) and redirects are not followed, unless
//! [`Config::webhook_private_addresses`](crate::Config::webhook_private_addresses) allows it.

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;

/// Signs and checks webhook bodies.
pub struct Signer;

impl Signer {
    /// The request header that carries the signature.
    pub const HEADER: &'static str = "Webhook-Signature";

    /// The signature of `body` with `secret`, made at `timestamp` (unix seconds).
    #[must_use]
    pub fn sign(body: &str, secret: &str, timestamp: i64) -> String {
        format!("t={timestamp},v1={}", hash(body, secret, timestamp))
    }

    /// Whether `header` is a valid signature of `body` with `secret`, made within `tolerance`
    /// seconds of `now`. Any of several `v1` signatures may match, so a sender can sign with an
    /// old and a new secret while receivers switch.
    #[must_use]
    pub fn verify(
        body: &str,
        header: Option<&str>,
        secret: &str,
        tolerance: i64,
        now: i64,
    ) -> bool {
        let mut timestamp = None;
        let mut signatures = Vec::new();
        for part in header.unwrap_or_default().split(',') {
            let (key, value) = part.trim().split_once('=').unwrap_or((part.trim(), ""));
            if key == "t" && !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
                timestamp = value.parse::<i64>().ok();
            } else if key == "v1" && !value.is_empty() {
                signatures.push(value);
            }
        }
        let Some(timestamp) = timestamp.filter(|timestamp| (now - timestamp).abs() <= tolerance)
        else {
            return false;
        };
        let expected = hash(body, secret, timestamp);
        signatures
            .iter()
            .any(|signature| constant_time_eq(expected.as_bytes(), signature.as_bytes()))
    }
}

fn hash(body: &str, secret: &str, timestamp: i64) -> String {
    let mut mac =
        Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes keys of any length");
    mac.update(format!("{timestamp}.{body}").as_bytes());
    mac.finalize()
        .into_bytes()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0, |diff, (x, y)| diff | (x ^ y)) == 0
}

/// Whether an IP address is on the public internet: globally reachable, as RFC 6890 lists them,
/// which leaves out loopback, private networks and link-local addresses such as a cloud metadata
/// service's. A NAT64 address counts as the IPv4 address it carries, which is where it connects.
/// The same addresses as the PHP package's `PublicAddressHandler::isPublic`.
#[must_use]
pub fn is_public(address: IpAddr) -> bool {
    match address {
        IpAddr::V4(address) => is_public_v4(address),
        IpAddr::V6(address) => is_public_v6(address),
    }
}

fn is_public_v4(address: Ipv4Addr) -> bool {
    let [a, b, c, _] = address.octets();
    let special = a == 0
        || a == 10
        || (a == 100 && (64..=127).contains(&b))
        || a == 127
        || (a == 169 && b == 254)
        || (a == 172 && (16..=31).contains(&b))
        || (a == 192 && b == 0 && (c == 0 || c == 2))
        || (a == 192 && b == 168)
        || (a == 198 && (b == 18 || b == 19))
        || (a == 198 && b == 51 && c == 100)
        || (a == 203 && b == 0 && c == 113)
        || a >= 240;
    !special
}

fn is_public_v6(address: Ipv6Addr) -> bool {
    let segments = address.segments();
    // 64:ff9b::/96 carries an IPv4 address in its last four bytes; the rest of 64:ff9b::/32, such
    // as 64:ff9b:1::/48, is for local use.
    if segments[0] == 0x64 && segments[1] == 0xff9b {
        let [.., a, b, c, d] = address.octets();
        return segments[2..6] == [0; 4] && is_public_v4(Ipv4Addr::new(a, b, c, d));
    }
    let special = address.is_unspecified()
        || address.is_loopback()
        // IPv4-mapped addresses.
        || segments[..6] == [0, 0, 0, 0, 0, 0xffff]
        || segments[..4] == [0x100, 0, 0, 0]
        // IETF protocol assignments (2001::/23), documentation and 6to4.
        || (segments[0] == 0x2001 && segments[1] <= 0x1ff)
        || (segments[0] == 0x2001 && segments[1] == 0xdb8)
        || segments[0] == 0x2002
        // Unique local and link-local.
        || segments[0] & 0xfe00 == 0xfc00
        || segments[0] & 0xffc0 == 0xfe80;
    !special
}

#[cfg(feature = "database")]
pub use self::store::*;

#[cfg(feature = "database")]
mod store {
    use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
    use std::time::Instant;

    use laravel::db::{self, col, values};
    use laravel::http::client;
    use laravel::http::client::reqwest;
    use laravel::prelude::ToSpan;
    use laravel::queue::{Attempt, Queueable, job};
    use serde_json::{Map, Value};

    use crate::query::Row;
    use crate::{State, glob, time, versioning};

    /// The prefix of endpoint secrets.
    pub const SECRET_PREFIX: &str = "whsec_";

    /// A delivery waiting for its first or next attempt.
    pub const PENDING: &str = "pending";
    /// A delivery the endpoint accepted.
    pub const DELIVERED: &str = "delivered";
    /// A delivery that ran out of attempts.
    pub const FAILED: &str = "failed";

    /// An event to send to the endpoints that subscribe to its type.
    #[derive(Debug, Clone)]
    pub struct Event {
        kind: String,
        document: Value,
        owner: Option<(String, i64)>,
    }

    impl Event {
        /// An event of type `kind`, such as `order.created`, carrying a JSON:API document's `data`
        /// and `included`, such as one from [`ApiQuery::document`](crate::query::ApiQuery::document).
        #[must_use]
        pub fn new(kind: impl Into<String>, document: Value) -> Self {
            Self {
                kind: kind.into(),
                document,
                owner: None,
            }
        }

        /// Sends the event only to the endpoints of one owner, such as the order's team, by its
        /// morph type and ID. Without an owner, every subscribed endpoint gets it.
        #[must_use]
        pub fn owner(mut self, kind: impl Into<String>, id: i64) -> Self {
            self.owner = Some((kind.into(), id));
            self
        }

        /// Records a delivery for each active endpoint that subscribes to the event, and queues
        /// them. Returns the deliveries' IDs.
        ///
        /// # Errors
        ///
        /// When the tables can't be read or written, or a job can't be queued.
        pub async fn dispatch(self) -> laravel::Result<Vec<i64>> {
            let mut query = db::table("webhook_endpoints")
                .select(["id", "events"])
                .filter(col("active").eq(true));
            if let Some((kind, id)) = &self.owner {
                query = query
                    .filter(col("owner_type").eq(kind.clone()))
                    .filter(col("owner_id").eq(*id));
            }
            let rows: Vec<Row> = query.get().await?;
            let endpoints: Vec<i64> = rows
                .into_iter()
                .filter(|row| subscribes_to(&row.0, &self.kind))
                .filter_map(|row| row.0.get("id").and_then(Value::as_i64))
                .collect();
            if endpoints.is_empty() {
                return Ok(Vec::new());
            }

            let mut payload = Map::new();
            let event_id = format!("evt_{}", ulid::Ulid::new().to_string().to_lowercase());
            payload.insert("id".into(), Value::String(event_id.clone()));
            payload.insert("type".into(), Value::String(self.kind.clone()));
            payload.insert("created_at".into(), Value::String(time::atom(time::now())));
            for member in ["data", "included"] {
                if let Some(value) = self.document.get(member).filter(|value| !value.is_null()) {
                    payload.insert(member.into(), value.clone());
                }
            }
            let payload = Value::Object(payload).to_string();

            let settings = settings();
            let mut deliveries = Vec::new();
            for endpoint in endpoints {
                let now = laravel::now().timestamp();
                let id = db::table("webhook_deliveries")
                    .insert_get_id(
                        values! {
                            webhook_endpoint_id: endpoint,
                            event_id: event_id.clone(),
                            event_type: self.kind.clone(),
                            payload: payload.clone(),
                            status: PENDING,
                            attempts: 0_i64,
                            created_at: now,
                            updated_at: now,
                        },
                        "id",
                    )
                    .await?;
                let mut job = DeliverWebhook { delivery_id: id }.dispatch();
                if let Some(connection) = &settings.connection {
                    job = job.on_connection(connection);
                }
                if let Some(queue) = &settings.queue {
                    job = job.on_queue(queue);
                }
                job.await?;
                deliveries.push(id);
            }
            Ok(deliveries)
        }
    }

    fn subscribes_to(endpoint: &Map<String, Value>, kind: &str) -> bool {
        endpoint
            .get("events")
            .and_then(Value::as_str)
            .and_then(|events| serde_json::from_str::<Vec<String>>(events).ok())
            .unwrap_or_default()
            .iter()
            .any(|pattern| glob(pattern, kind))
    }

    /// `api.webhooks` in the PHP package.
    #[derive(Debug, Clone)]
    pub(crate) struct Settings {
        pub(crate) connection: Option<String>,
        pub(crate) queue: Option<String>,
        pub(crate) timeout: u64,
        pub(crate) backoff: Vec<u64>,
        pub(crate) disable_after: Option<i64>,
        pub(crate) allow_private_addresses: bool,
    }

    impl Default for Settings {
        fn default() -> Self {
            Self {
                connection: None,
                queue: None,
                timeout: 10,
                backoff: vec![60, 300, 1800, 3600, 10_800, 21_600, 43_200],
                disable_after: Some(5),
                allow_private_addresses: false,
            }
        }
    }

    fn state() -> Option<&'static State> {
        crate::STATE.get().map(AsRef::as_ref)
    }

    fn settings() -> Settings {
        state()
            .map(|state| state.config.webhooks.clone())
            .unwrap_or_default()
    }

    /// Registers an endpoint with a new secret, subscribed to `events` (such as `["order.*"]`).
    /// It is pinned to `version`, or to the latest version when versioning is on, so later
    /// breaking changes never reach it until it is upgraded. Returns its ID.
    ///
    /// # Errors
    ///
    /// When the secret can't be encrypted (check `APP_KEY`) or the endpoint can't be written.
    pub async fn register(
        url: &str,
        events: &[&str],
        version: Option<&str>,
        description: Option<&str>,
    ) -> laravel::Result<i64> {
        let version = version.map(str::to_owned).or_else(|| {
            state()
                .and_then(|state| state.registry.as_ref())
                .map(|registry| registry.latest.to_string())
        });
        let secret = new_secret();
        let now = laravel::now().timestamp();
        db::table("webhook_endpoints")
            .insert_get_id(
                values! {
                    url: url,
                    description: description.map(str::to_owned),
                    secret: laravel::crypt::encrypt_string(&secret)?,
                    events: serde_json::to_string(events).unwrap_or_default(),
                    version: version,
                    active: true,
                    consecutive_failures: 0_i64,
                    created_at: now,
                    updated_at: now,
                },
                "id",
            )
            .await
    }

    fn new_secret() -> String {
        format!("{SECRET_PREFIX}{}", laravel::str::random(32))
    }

    /// An endpoint's secret, for a receiver that checks signatures.
    ///
    /// # Errors
    ///
    /// When there is no such endpoint, or its secret can't be decrypted.
    pub async fn secret(endpoint: i64) -> laravel::Result<String> {
        let row: Option<Row> = db::table("webhook_endpoints")
            .select(["secret"])
            .filter(col("id").eq(endpoint))
            .first()
            .await?;
        let encrypted = row
            .and_then(|row| {
                row.0
                    .get("secret")
                    .and_then(Value::as_str)
                    .map(str::to_owned)
            })
            .ok_or_else(|| laravel::Error::msg(format!("No webhook endpoint [{endpoint}].")))?;
        laravel::crypt::decrypt_string(&encrypted)
    }

    /// Replaces an endpoint's secret, such as after a leak, and returns the new one. Receivers
    /// must switch to it.
    ///
    /// # Errors
    ///
    /// When the endpoint can't be written.
    pub async fn rotate_secret(endpoint: i64) -> laravel::Result<String> {
        let secret = new_secret();
        db::table("webhook_endpoints")
            .filter(col("id").eq(endpoint))
            .update(values! {
                secret: laravel::crypt::encrypt_string(&secret)?,
                updated_at: laravel::now().timestamp(),
            })
            .await?;
        Ok(secret)
    }

    /// Turns an endpoint back on, such as after it was disabled for failing, with a clean slate.
    ///
    /// # Errors
    ///
    /// When the endpoint can't be written.
    pub async fn enable(endpoint: i64) -> laravel::Result<()> {
        db::table("webhook_endpoints")
            .filter(col("id").eq(endpoint))
            .update(values! {
                active: true,
                consecutive_failures: 0_i64,
                disabled_at: None::<String>,
                updated_at: laravel::now().timestamp(),
            })
            .await?;
        Ok(())
    }

    /// Posts one delivery to its endpoint.
    #[derive(Queueable)]
    pub struct DeliverWebhook {
        pub delivery_id: i64,
    }

    // Retries come from `api.webhooks.backoff` and the delivery's own attempt count, so the job
    // allows as many attempts as a week of releases may need.
    #[job(name = "fusion-stack.deliver-webhook", retry_for = 7.days())]
    impl DeliverWebhook {
        async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
            deliver(self.delivery_id, attempt).await
        }
    }

    fn int(row: &Map<String, Value>, key: &str) -> i64 {
        match row.get(key) {
            Some(Value::Bool(value)) => i64::from(*value),
            Some(value) => value.as_i64().unwrap_or_default(),
            None => 0,
        }
    }

    fn text(row: &Map<String, Value>, key: &str) -> Option<String> {
        row.get(key).and_then(Value::as_str).map(str::to_owned)
    }

    async fn deliver(delivery_id: i64, attempt: &Attempt) -> laravel::Result<()> {
        let delivery: Option<Row> = db::table("webhook_deliveries")
            .filter(col("id").eq(delivery_id))
            .first()
            .await?;
        let Some(Row(delivery)) = delivery else {
            return Ok(());
        };
        if text(&delivery, "status").as_deref() == Some(DELIVERED) {
            return Ok(());
        }
        let endpoint_id = int(&delivery, "webhook_endpoint_id");
        let endpoint: Option<Row> = db::table("webhook_endpoints")
            .filter(col("id").eq(endpoint_id))
            .first()
            .await?;
        let Some(Row(endpoint)) = endpoint else {
            return Ok(());
        };

        if int(&endpoint, "active") == 0 {
            update_delivery(
                delivery_id,
                values! { status: FAILED, error: "The endpoint is disabled.", updated_at: laravel::now().timestamp() },
            )
            .await?;
            return Ok(());
        }

        let settings = settings();
        let kind = text(&delivery, "event_type").unwrap_or_default();
        let stored: Value = text(&delivery, "payload")
            .and_then(|payload| serde_json::from_str(&payload).ok())
            .unwrap_or(Value::Null);
        let body = payload(stored, text(&endpoint, "version").as_deref(), &kind).to_string();
        let secret =
            laravel::crypt::decrypt_string(&text(&endpoint, "secret").unwrap_or_default())?;
        let url = text(&endpoint, "url").unwrap_or_default();
        let event_id = text(&delivery, "event_id").unwrap_or_default();

        let started = Instant::now();
        let destination = if settings.allow_private_addresses {
            Destination::Unchecked
        } else {
            let url = url.clone();
            laravel::task::spawn_blocking(move || Destination::of(&url, lookup)).await?
        };
        let (status, error) = if let Destination::Refused(reason) = destination {
            (None, Some(reason))
        } else {
            let sent = client::post(url.as_str())
                .header("Webhook-Id", event_id.as_str())
                .header(
                    super::Signer::HEADER,
                    super::Signer::sign(&body, &secret, time::now()),
                )
                .header("User-Agent", "Fusion Stack Webhooks")
                .body(body, "application/json")
                .timeout(i64::try_from(settings.timeout).unwrap_or(10).seconds())
                .configure_transport(move |transport| destination.apply(transport))
                .await;
            match sent {
                Ok(response) if response.successful() => (Some(response.status().as_u16()), None),
                Ok(response) => {
                    let status = response.status().as_u16();
                    (
                        Some(status),
                        Some(format!("The endpoint responded with {status}.")),
                    )
                }
                Err(error) => (None, Some(error.to_string())),
            }
        };

        let attempts = int(&delivery, "attempts") + 1;
        // The sync connection runs jobs inline and cannot delay them, so it gets no retries.
        let retry_in = if error.is_none() || attempt.connection() == "sync" {
            None
        } else {
            usize::try_from(attempts - 1)
                .ok()
                .and_then(|index| settings.backoff.get(index))
                .copied()
        };
        let status_text = match (&error, retry_in) {
            (None, _) => DELIVERED,
            (Some(_), Some(_)) => PENDING,
            (Some(_), None) => FAILED,
        };
        let now = laravel::now().timestamp();
        update_delivery(
            delivery_id,
            values! {
                status: status_text,
                attempts: attempts,
                response_status: status.map(i64::from),
                duration_ms: i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX),
                error: error.as_ref().map(|error| error.chars().take(1000).collect::<String>()),
                delivered_at: error.is_none().then_some(now),
                updated_at: now,
            },
        )
        .await?;

        match (error, retry_in) {
            (None, _) => {
                if int(&endpoint, "consecutive_failures") > 0 {
                    db::table("webhook_endpoints")
                        .filter(col("id").eq(endpoint_id))
                        .update(values! { consecutive_failures: 0_i64 })
                        .await?;
                }
            }
            (Some(_), Some(delay)) => {
                attempt.release(i64::try_from(delay).unwrap_or(i64::MAX).seconds());
            }
            (Some(_), None) => count_failure(&endpoint, endpoint_id, &settings).await?,
        }
        Ok(())
    }

    /// Where a delivery's request may connect, decided before it is sent so that it cannot reach
    /// what only the server can.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub(crate) enum Destination {
        /// Private addresses are allowed, so the host is not looked at.
        Unchecked,
        /// The host is a public IP address, or the URL is one the client rejects itself.
        Direct,
        /// A host name whose addresses are all public. The request connects only to them, so a
        /// second DNS answer cannot move it somewhere else.
        Pinned(String, Vec<SocketAddr>),
        /// A host name that resolved to nothing, or to an address that is not public. The request
        /// fails with the reason in place of a DNS lookup; an HTTP fake still answers it first.
        Unreachable(String),
        /// An IP address that is not public. The request is not sent, faked or not.
        Refused(String),
    }

    impl Destination {
        /// The destination for an endpoint's URL. `lookup` gives a host name's addresses.
        pub(crate) fn of(url: &str, lookup: impl FnOnce(&str, u16) -> Vec<SocketAddr>) -> Self {
            // The client parses the URL with the same parser, so both read the same host.
            let Ok(url) = reqwest::Url::parse(url) else {
                return Self::Direct;
            };
            let Some(host) = url.host_str() else {
                return Self::Direct;
            };
            let private = || {
                format!(
                    "The endpoint's host [{}] is not on the public internet, so the webhook was not sent.",
                    host.trim_matches(['[', ']'])
                )
            };
            if let Ok(address) = host.trim_matches(['[', ']']).parse::<IpAddr>() {
                return if super::is_public(address) {
                    Self::Direct
                } else {
                    Self::Refused(private())
                };
            }
            let addresses = lookup(host, url.port_or_known_default().unwrap_or(443));
            if addresses.is_empty() {
                return Self::Unreachable(format!(
                    "The endpoint's host [{host}] could not be resolved, so the webhook was not sent."
                ));
            }
            if addresses
                .iter()
                .all(|address| super::is_public(address.ip()))
            {
                Self::Pinned(host.to_owned(), addresses)
            } else {
                Self::Unreachable(private())
            }
        }

        /// Makes the request's transport keep to the destination. A redirect is never followed:
        /// it could lead anywhere, and the signed body with it.
        fn apply(&self, transport: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
            let transport = transport.redirect(reqwest::redirect::Policy::none());
            match self {
                Self::Pinned(host, addresses) => transport.resolve_to_addrs(host, addresses),
                Self::Unreachable(reason) => transport.dns_resolver(NoLookup(reason.clone())),
                Self::Unchecked | Self::Direct | Self::Refused(_) => transport,
            }
        }
    }

    /// The system resolver's addresses for a host name, or none when it has none.
    fn lookup(host: &str, port: u16) -> Vec<SocketAddr> {
        (host, port)
            .to_socket_addrs()
            .map(Iterator::collect)
            .unwrap_or_default()
    }

    /// A DNS resolver that fails every lookup with the reason the destination is unreachable.
    struct NoLookup(String);

    impl reqwest::dns::Resolve for NoLookup {
        fn resolve(&self, _name: reqwest::dns::Name) -> reqwest::dns::Resolving {
            let reason = self.0.clone();
            Box::pin(async move { Err(reason.into()) })
        }
    }

    async fn update_delivery(id: i64, values: db::Values) -> laravel::Result<()> {
        db::table("webhook_deliveries")
            .filter(col("id").eq(id))
            .update(values)
            .await?;
        Ok(())
    }

    /// Disables the endpoint when too many deliveries in a row have failed.
    async fn count_failure(
        endpoint: &Map<String, Value>,
        id: i64,
        settings: &Settings,
    ) -> laravel::Result<()> {
        let failures = int(endpoint, "consecutive_failures") + 1;
        let disable = settings
            .disable_after
            .is_some_and(|limit| limit >= 1 && failures >= limit);
        let now = laravel::now().timestamp();
        let query = db::table("webhook_endpoints").filter(col("id").eq(id));
        if disable {
            query
                .update(values! { consecutive_failures: failures, active: false, disabled_at: now, updated_at: now })
                .await?;
        } else {
            query
                .update(values! { consecutive_failures: failures })
                .await?;
        }
        Ok(())
    }

    /// The delivery's payload in the endpoint's version: `data` and `included` pass through the
    /// version changes newer than it, as a response would. Changes can target an event type as
    /// the route `webhooks.order.created`.
    pub(crate) fn payload(stored: Value, version: Option<&str>, kind: &str) -> Value {
        let Some(registry) = state().and_then(|state| state.registry.as_ref()) else {
            return stored;
        };
        let version = registry
            .resolve(version, time::now())
            .unwrap_or_else(|_| registry.default.clone());
        let Value::Object(stored) = stored else {
            return stored;
        };
        let mut document = Map::new();
        let mut payload = Map::new();
        for (key, value) in stored {
            if key == "data" || key == "included" {
                document.insert(key, value);
            } else {
                payload.insert(key, value);
            }
        }
        let mut document = Value::Object(document);
        let route = format!("webhooks.{kind}");
        let types = versioning::document::types(&document);
        for change in registry.changes_after(&version, None).iter().rev() {
            if versioning::applies_to(change.as_ref(), &types, &route) {
                change.transform_response(&mut document);
            }
        }
        payload.insert("api_version".into(), Value::String(version.to_string()));
        if let Value::Object(document) = document {
            payload.extend(document);
        }
        Value::Object(payload)
    }
}

#[cfg(test)]
mod tests {
    use std::net::IpAddr;

    use super::{Signer, is_public};

    #[test]
    fn tells_public_addresses_from_private_ones() {
        // The list both packages check, from spec/webhook-addresses.json.
        let addresses: serde_json::Value = serde_json::from_str(include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/fixtures/webhook-addresses.json"
        )))
        .unwrap_or_default();
        let verdicts = |list: &str| -> Vec<(String, bool)> {
            addresses[list]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(serde_json::Value::as_str)
                .map(|address| {
                    let parsed: Option<IpAddr> = address.parse().ok();
                    (address.to_owned(), parsed.is_some_and(is_public))
                })
                .collect()
        };
        let (public, private) = (verdicts("public"), verdicts("private"));
        assert!(public.len() > 5 && private.len() > 20);
        assert_eq!(
            public
                .iter()
                .filter(|(_, public)| !public)
                .collect::<Vec<_>>(),
            Vec::<&(String, bool)>::new()
        );
        assert_eq!(
            private
                .iter()
                .filter(|(_, public)| *public)
                .collect::<Vec<_>>(),
            Vec::<&(String, bool)>::new()
        );
    }

    #[cfg(feature = "database")]
    #[test]
    fn deliveries_connect_only_to_public_addresses_they_checked() {
        use std::net::SocketAddr;

        use super::Destination;

        let address = |address: &str| -> SocketAddr { address.parse().expect("a socket address") };
        let never =
            |_: &str, _: u16| -> Vec<SocketAddr> { panic!("an IP address is not looked up") };
        let private = |host: &str| {
            format!(
                "The endpoint's host [{host}] is not on the public internet, so the webhook was not sent."
            )
        };

        for (url, host) in [
            ("http://127.0.0.1:9/hooks", "127.0.0.1"),
            // The URL parser reads other spellings of an IPv4 address as the address.
            ("http://2130706433:9/hooks", "127.0.0.1"),
            ("http://0x7f.1/hooks", "127.0.0.1"),
            ("http://[::1]:9/hooks", "::1"),
            ("http://169.254.169.254/latest/meta-data", "169.254.169.254"),
            ("https://10.0.0.5/hooks", "10.0.0.5"),
        ] {
            assert_eq!(
                Destination::of(url, never),
                Destination::Refused(private(host)),
                "{url}"
            );
        }
        assert_eq!(
            Destination::of("https://93.184.216.34/hooks", never),
            Destination::Direct
        );

        // A name is pinned to the addresses it resolved to, looked up with the URL's port.
        let public = vec![
            address("93.184.216.34:443"),
            address("[2606:4700:4700::1111]:443"),
        ];
        assert_eq!(
            Destination::of("https://hooks.example.com/orders", |host, port| {
                assert_eq!((host, port), ("hooks.example.com", 443));
                public.clone()
            }),
            Destination::Pinned("hooks.example.com".to_owned(), public.clone())
        );
        assert_eq!(
            Destination::of("http://hooks.example.com:8080/orders", |_, port| vec![
                SocketAddr::new(public[0].ip(), port)
            ]),
            Destination::Pinned(
                "hooks.example.com".to_owned(),
                vec![address("93.184.216.34:8080")]
            )
        );

        // A name that resolves to a private address among public ones, or to nothing, is refused.
        assert_eq!(
            Destination::of("https://hooks.example.com/orders", |_, _| vec![
                public[0],
                address("10.0.0.5:443")
            ]),
            Destination::Unreachable(private("hooks.example.com"))
        );
        assert_eq!(
            Destination::of("https://localhost/hooks", |_, _| vec![address(
                "127.0.0.1:443"
            )]),
            Destination::Unreachable(private("localhost"))
        );
        assert_eq!(
            Destination::of("https://nowhere.example.com/hooks", |_, _| Vec::new()),
            Destination::Unreachable(
                "The endpoint's host [nowhere.example.com] could not be resolved, so the webhook was not sent.".to_owned()
            )
        );
    }

    #[test]
    fn signatures_verify_within_the_tolerance() {
        let header = Signer::sign("{\"a\":1}", "whsec_x", 1_000);
        assert!(header.starts_with("t=1000,v1="));
        assert!(Signer::verify(
            "{\"a\":1}",
            Some(&header),
            "whsec_x",
            300,
            1_200
        ));
        assert!(!Signer::verify(
            "{\"a\":1}",
            Some(&header),
            "whsec_x",
            300,
            1_301
        ));
        assert!(!Signer::verify(
            "{\"a\":2}",
            Some(&header),
            "whsec_x",
            300,
            1_000
        ));
        assert!(!Signer::verify(
            "{\"a\":1}",
            Some(&header),
            "whsec_y",
            300,
            1_000
        ));
        // A second, older secret's signature alongside the current one still verifies.
        let old = Signer::sign("{\"a\":1}", "whsec_old", 1_000);
        let both = format!("{header},{}", old.split_once(',').unwrap_or_default().1);
        assert!(Signer::verify(
            "{\"a\":1}",
            Some(&both),
            "whsec_old",
            300,
            1_000
        ));
        assert!(!Signer::verify("{\"a\":1}", None, "whsec_x", 300, 1_000));
    }

    #[test]
    fn signatures_match_php_hash_hmac() {
        // php -r 'echo hash_hmac("sha256", "1700000000.{}", "whsec_test");'
        assert_eq!(
            Signer::sign("{}", "whsec_test", 1_700_000_000),
            "t=1700000000,v1=35495024f4ef3f94e5a93e22221544c4b75e9a42300cd965ab81cb85cd994e91"
        );
    }
}