cratefield-core 0.6.0

Cratefield harness kernel: Module trait, Harness builder, ports, 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
//! Generic webhook signature verification (issue #533).
//!
//! [`RoutePolicy::Signature`](crate::route_policy::RoutePolicy::Signature)
//! used to mean exactly one verifier: `Payments::verify_webhook`, so a
//! venture receiving **signed** webhooks from a provider that never takes a
//! payment had no policy it could declare honestly. This module is the other
//! half: one HMAC-SHA256 core ([`WebhookVerifier`]) with pluggable header
//! schemes ([`SignatureScheme`]) — Svix ([`Svix`], also what Resend signs
//! with), Stripe-style ([`StripeStyle`]) and a configured provider layout
//! ([`ProviderScheme`]).
//!
//! Verification always runs over the **raw body bytes** — the handler must
//! read the body before anything parses it — and every path fails closed.

use std::borrow::Cow;
use std::sync::Arc;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use hmac::{Hmac, KeyInit, Mac};
use http::HeaderMap;
use sha2::Sha256;
use subtle::ConstantTimeEq;

type HmacSha256 = Hmac<Sha256>;

/// How far a delivery's timestamp may be from now, in seconds, either way —
/// Svix's and Stripe's own tolerance, and the [`WebhookVerifier`] default.
/// The signature stays valid forever; the timestamp is what stops replays.
pub const DEFAULT_TOLERANCE_SECS: i64 = 300;

/// What a [`SignatureScheme`] read out of one delivery: the bytes the
/// provider signed, the candidate signatures to compare, the timestamp the
/// replay tolerance runs on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedDelivery {
    /// Exactly the bytes `HMAC-SHA256(secret, ·)` ran over.
    pub signed_payload: Vec<u8>,
    /// Every candidate the delivery carried, decoded; empty refuses.
    pub candidates: Vec<Vec<u8>>,
    /// The Unix seconds the provider says it sent the delivery. `None`
    /// skips the replay tolerance — the scheme is then only as replay-safe
    /// as the provider makes it.
    pub timestamp: Option<i64>,
}

/// How a provider puts its signature material on the wire. Implement this
/// for a provider none of the built-in schemes speak; the HMAC core is
/// [`WebhookVerifier`]'s either way. Fail closed: `None` for a delivery
/// whose headers cannot be read in full, never a guess.
pub trait SignatureScheme: Send + Sync {
    /// Reads one delivery's signature material out of the request headers
    /// and the raw body bytes. `None` on any input the scheme cannot fully
    /// read; an empty candidate list counts as unreadable.
    fn extract(&self, headers: &HeaderMap, body: &[u8]) -> Option<SignedDelivery>;

    /// The key bytes the HMAC runs over: the trimmed secret's own bytes,
    /// unless the scheme's providers hand out encoded secrets (Svix's
    /// base64 `whsec_…`), which decode here. `None` refuses.
    fn secret_key<'a>(&self, secret: &'a str) -> Option<Cow<'a, [u8]>> {
        let trimmed = secret.trim();
        (!trimmed.is_empty()).then_some(Cow::Borrowed(trimmed.as_bytes()))
    }
}

/// The HMAC-SHA256 core every scheme shares: compute the expected tag over
/// the scheme's signed payload, compare it against **every** candidate in
/// constant time with no early exit, and hold the delivery to its timestamp.
#[derive(Clone)]
pub struct WebhookVerifier {
    scheme: Arc<dyn SignatureScheme>,
    tolerance_secs: i64,
}

impl WebhookVerifier {
    /// A verifier with the default tolerance ([`DEFAULT_TOLERANCE_SECS`]).
    ///
    /// ```
    /// use cratefield_core::{Svix, WebhookVerifier};
    /// use http::HeaderMap;
    ///
    /// let verifier = WebhookVerifier::new(Svix);
    /// // `raw` is the body exactly as it arrived, before any parsing; the
    /// // empty secret here means the delivery is refused, never guessed at.
    /// assert!(!verifier.verify("", &HeaderMap::new(), b"{}", 0));
    /// ```
    #[must_use]
    pub fn new(scheme: impl SignatureScheme + 'static) -> Self {
        Self {
            scheme: Arc::new(scheme),
            tolerance_secs: DEFAULT_TOLERANCE_SECS,
        }
    }

    /// Overrides the replay tolerance, in seconds, in both directions.
    #[must_use]
    pub const fn tolerance_secs(mut self, secs: i64) -> Self {
        self.tolerance_secs = secs;
        self
    }

    /// Whether `body` really was signed for this delivery with `secret`.
    /// Fails closed on every unreadable input; a timestamp in the future
    /// counts against the tolerance exactly as a stale one does.
    ///
    /// # Panics
    ///
    /// Only if `HMAC-SHA256` refused the derived key — which it cannot:
    /// HMAC accepts keys of any length.
    #[must_use]
    pub fn verify(&self, secret: &str, headers: &HeaderMap, body: &[u8], now_unix: i64) -> bool {
        if secret.trim().is_empty() {
            return false; // an empty secret is not a key
        }
        let Some(delivery) = self.scheme.extract(headers, body) else {
            return false;
        };
        if let Some(sent) = delivery.timestamp
            && now_unix
                .saturating_sub(sent)
                .checked_abs()
                .is_none_or(|delta| delta > self.tolerance_secs)
        {
            return false; // a clock this far out is out of tolerance
        }
        let Some(key) = self.scheme.secret_key(secret) else {
            return false;
        };
        let mut mac =
            <HmacSha256 as KeyInit>::new_from_slice(&key).expect("HMAC accepts any key length");
        mac.update(&delivery.signed_payload);
        let expected = mac.finalize().into_bytes();
        // No early exit: every candidate is compared and the results OR-ed,
        // so timing says nothing about how much of a wrong signature was
        // right — nor which candidate (if any) matched.
        let mut matched = false;
        for candidate in &delivery.candidates {
            matched |= bool::from(candidate.as_slice().ct_eq(expected.as_slice()));
        }
        matched
    }
}

impl std::fmt::Debug for WebhookVerifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WebhookVerifier")
            .field("tolerance_secs", &self.tolerance_secs)
            .finish_non_exhaustive()
    }
}

/// Svix's scheme — the one Resend, Clerk and a growing list of providers
/// sign with. Headers `svix-id` / `svix-timestamp` / `svix-signature` (the
/// `webhook-*` aliases are accepted too); payload `{id}.{timestamp}.{body}`;
/// signature header a space-separated list of `<version>,<base64>` pairs of
/// which only `v1` is read — how an endpoint survives a secret rotation.
#[derive(Debug, Clone, Copy, Default)]
pub struct Svix;

/// The Svix signing headers: canonical names and `webhook-*` aliases.
const SVIX_HEADERS: [(&str, &str, &str); 2] = [
    ("svix-id", "svix-timestamp", "svix-signature"),
    ("webhook-id", "webhook-timestamp", "webhook-signature"),
];

impl SignatureScheme for Svix {
    fn extract(&self, headers: &HeaderMap, body: &[u8]) -> Option<SignedDelivery> {
        let (id, timestamp, signatures) = SVIX_HEADERS.iter().find_map(|(id, at, sig)| {
            Some((
                header(headers, id)?,
                header(headers, at)?,
                header(headers, sig)?,
            ))
        })?;
        let sent = timestamp.trim().parse::<i64>().ok()?;
        let mut candidates = Vec::new();
        for entry in signatures.split_whitespace() {
            let Some((version, value)) = entry.split_once(',') else {
                continue;
            };
            // Only `v1` is understood; unknown versions are ignored, the way
            // an endpoint survives a provider adding one.
            if version == "v1"
                && let Ok(bytes) = STANDARD.decode(value)
            {
                candidates.push(bytes);
            }
        }
        if candidates.is_empty() {
            return None;
        }
        Some(SignedDelivery {
            signed_payload: [id.as_bytes(), b".", timestamp.as_bytes(), b".", body].concat(),
            candidates,
            timestamp: Some(sent),
        })
    }

    fn secret_key<'a>(&self, secret: &'a str) -> Option<Cow<'a, [u8]>> {
        svix_secret_key(secret).map(Cow::Owned)
    }
}

/// An Svix endpoint secret's key bytes: base64, with or without the
/// `whsec_` prefix Svix writes it with. `None` when it does not decode.
#[must_use]
pub fn svix_secret_key(secret: &str) -> Option<Vec<u8>> {
    let trimmed = secret.trim();
    let encoded = trimmed.strip_prefix("whsec_").unwrap_or(trimmed);
    STANDARD.decode(encoded).ok().filter(|key| !key.is_empty())
}

/// Stripe's scheme, the shape `adapter-stripe` verifies: one header of
/// `t=<unix>,v1=<hex>[,v1=<hex>…]`, payload `{t}.{body}`. The header name is
/// configurable because other providers use the same layout under their own
/// name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StripeStyle {
    /// The header carrying `t=…,v1=…`.
    pub header: &'static str,
}

impl Default for StripeStyle {
    fn default() -> Self {
        Self {
            header: "Stripe-Signature",
        }
    }
}

impl SignatureScheme for StripeStyle {
    fn extract(&self, headers: &HeaderMap, body: &[u8]) -> Option<SignedDelivery> {
        let raw = header(headers, self.header)?;
        let mut timestamp = None;
        let mut candidates = Vec::new();
        for part in raw.split(',') {
            let Some((key, value)) = part.split_once('=') else {
                continue;
            };
            match key.trim() {
                "t" => timestamp = value.trim().parse::<i64>().ok(),
                "v1" => {
                    if let Some(bytes) = hex_decode(value.trim()) {
                        candidates.push(bytes);
                    }
                }
                _ => {} // unknown keys are ignored, as the adapter ignores them
            }
        }
        let sent = timestamp?;
        if candidates.is_empty() {
            return None;
        }
        Some(SignedDelivery {
            signed_payload: [sent.to_string().as_bytes(), b".", body].concat(),
            candidates,
            timestamp: Some(sent),
        })
    }
}

/// A provider-specific scheme, configured rather than coded. Entries are
/// separated by commas or spaces, so a provider may send several — for
/// instance during a secret rotation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProviderScheme {
    /// The header carrying the signature (or several).
    pub signature: &'static str,
    /// How each entry is encoded in the header.
    pub encoding: SignatureEncoding,
    /// A literal prefix stripped from each entry before decoding (`sha256=`).
    pub prefix: Option<&'static str>,
    /// The header carrying a Unix-seconds timestamp the provider signs.
    /// When set, the payload is `{timestamp}.{body}` and the replay
    /// tolerance applies; when `None`, the payload is the raw body.
    pub timestamp: Option<&'static str>,
}

impl SignatureScheme for ProviderScheme {
    fn extract(&self, headers: &HeaderMap, body: &[u8]) -> Option<SignedDelivery> {
        let raw = header(headers, self.signature)?;
        // A configured timestamp header that is missing or unreadable
        // refuses; it never downgrades to "no tolerance".
        let timestamp = match self.timestamp {
            Some(name) => Some(header(headers, name)?.trim().parse::<i64>().ok()?),
            None => None,
        };
        let mut candidates = Vec::new();
        for entry in raw.split([',', ' ']) {
            let Some(entry) = entry.strip_prefix(self.prefix.unwrap_or("")) else {
                continue;
            };
            let decoded = match self.encoding {
                SignatureEncoding::Hex => hex_decode(entry),
                SignatureEncoding::Base64 => STANDARD.decode(entry).ok(),
            };
            if let Some(bytes) = decoded {
                candidates.push(bytes);
            }
        }
        if candidates.is_empty() {
            return None;
        }
        Some(SignedDelivery {
            signed_payload: match timestamp {
                Some(sent) => [sent.to_string().as_bytes(), b".", body].concat(),
                None => body.to_vec(),
            },
            candidates,
            timestamp,
        })
    }
}

/// How a provider encodes signature bytes in its header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureEncoding {
    /// Hexadecimal, upper- or lowercase, two digits per byte.
    Hex,
    /// Standard base64, with padding.
    Base64,
}

/// The first header value, as a string; non-UTF-8 is unreadable, and
/// unreadable is refused.
fn header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers.get(name)?.to_str().ok()
}

/// Hex, any case, an even number of digits; `None` otherwise.
fn hex_decode(value: &str) -> Option<Vec<u8>> {
    if !value.len().is_multiple_of(2) {
        return None;
    }
    (0..value.len())
        .step_by(2)
        .map(|at| u8::from_str_radix(&value[at..at + 2], 16).ok())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::SignatureEncoding::{Base64, Hex};
    use super::*;

    const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
    const WRONG: &str = "whsec_AAAAAAAA"; // a different, decodable secret
    const ID: &str = "msg_p5jXN8AQM9LWM0D4loKWxJek";
    const NOW: i64 = 1_800_000_000;
    const STRIPE_SECRET: &str = "stripe-endpoint-secret-dummy";
    const PROVIDER_SECRET: &str = "provider-endpoint-secret-dummy";

    fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
        pairs
            .iter()
            .map(|(name, value)| {
                let name = name
                    .parse::<http::header::HeaderName>()
                    .expect("test header name");
                (name, value.parse().expect("test header value"))
            })
            .collect()
    }

    fn hex(bytes: &[u8]) -> String {
        use std::fmt::Write as _;
        bytes.iter().fold(String::new(), |mut out, byte| {
            let _ = write!(out, "{byte:02x}");
            out
        })
    }

    fn mac(key: &[u8], parts: &[&[u8]]) -> Vec<u8> {
        let mut mac =
            <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");
        for part in parts {
            mac.update(part);
        }
        mac.finalize().into_bytes().to_vec()
    }

    /// The `svix-signature` header a provider would send for this body.
    fn svix_sign(secret: &str, id: &str, at: i64, body: &[u8]) -> String {
        let key = svix_secret_key(secret).expect("the fixture secret decodes");
        let ts = at.to_string();
        let payload = [id.as_bytes(), b".", ts.as_bytes(), b".", body];
        format!("v1,{}", STANDARD.encode(mac(&key, &payload)))
    }

    fn svix_headers(at: &str, sigs: &str) -> HeaderMap {
        headers(&[
            ("svix-id", ID),
            ("svix-timestamp", at),
            ("svix-signature", sigs),
        ])
    }

    /// Whether an Svix delivery with these header values verifies.
    fn svix_verifies(secret: &str, at: &str, sigs: &str, body: &[u8], now: i64) -> bool {
        WebhookVerifier::new(Svix).verify(secret, &svix_headers(at, sigs), body, now)
    }

    /// The `t=,v1=` header Stripe would send for this body.
    fn stripe_sign(secret: &str, at: i64, body: &[u8]) -> String {
        let ts = at.to_string();
        let payload = [ts.as_bytes(), b".", body];
        let digest = hex(&mac(secret.as_bytes(), &payload));
        format!("t={at},v1={digest}")
    }

    /// Whether a Stripe delivery with this header value verifies.
    fn stripe_verifies(secret: &str, header: &str, body: &[u8], now: i64) -> bool {
        let got = headers(&[("Stripe-Signature", header)]);
        WebhookVerifier::new(StripeStyle::default()).verify(secret, &got, body, now)
    }

    fn provider(
        enc: SignatureEncoding,
        prefix: Option<&'static str>,
        at: Option<&'static str>,
    ) -> WebhookVerifier {
        WebhookVerifier::new(ProviderScheme {
            signature: "X-Signature",
            encoding: enc,
            prefix,
            timestamp: at,
        })
    }

    /// The bare hex signature a hex `ProviderScheme` reads.
    fn provider_sign(at: Option<i64>, body: &[u8]) -> String {
        let key = PROVIDER_SECRET.as_bytes();
        let digest = match at {
            Some(sent) => mac(key, &[sent.to_string().as_bytes(), b".", body]),
            None => mac(key, &[body]),
        };
        hex(&digest)
    }

    #[test]
    fn an_svix_delivery_verifies() {
        let body = br#"{"type":"pos.order.created"}"#;
        let header = svix_sign(SECRET, ID, NOW, body);
        assert!(svix_verifies(SECRET, "1800000000", &header, body, NOW));
        // `webhook-*` aliases, and the secret without its `whsec_` prefix.
        let aliased = headers(&[
            ("webhook-id", ID),
            ("webhook-timestamp", "1800000000"),
            ("webhook-signature", &header),
        ]);
        assert!(WebhookVerifier::new(Svix).verify(SECRET, &aliased, body, NOW));
        let bare = SECRET.strip_prefix("whsec_").expect("prefixed");
        assert!(svix_verifies(bare, "1800000000", &header, body, NOW));
    }

    #[test]
    fn a_tampered_delivery_or_wrong_secret_refuses_but_a_rotation_matches() {
        let body = b"{}";
        let header = svix_sign(SECRET, ID, NOW, body);
        let old = svix_sign(WRONG, ID, NOW, body);
        let tampered = br#"{"changed":true}"#;
        assert!(!svix_verifies(SECRET, "1800000000", &header, tampered, NOW));
        assert!(!svix_verifies(WRONG, "1800000000", &header, body, NOW));
        // The id is part of what is signed, so it cannot be swapped either.
        let swapped = svix_sign(SECRET, "msg_another", NOW, body);
        assert!(!svix_verifies(SECRET, "1800000000", &swapped, body, NOW));
        // A rotation: the provider signs with both secrets for the overlap,
        // an unknown version among them is ignored, and a header holding
        // only unknown versions refuses.
        let both = format!("{old} v0,AAAA {header}");
        assert!(svix_verifies(SECRET, "1800000000", &both, body, NOW));
        assert!(!svix_verifies(SECRET, "1800000000", "v0,AAAA", body, NOW));
    }

    #[test]
    fn a_delivery_outside_the_tolerance_is_refused() {
        let body = b"{}";
        let sent = NOW - DEFAULT_TOLERANCE_SECS - 1;
        let stale = svix_sign(SECRET, ID, sent, body);
        // The signature stays perfectly valid; the timestamp is what stops
        // it being replayed forever — in either direction.
        assert!(svix_verifies(SECRET, &sent.to_string(), &stale, body, sent));
        assert!(!svix_verifies(SECRET, &sent.to_string(), &stale, body, NOW));
        let future = NOW + DEFAULT_TOLERANCE_SECS + 1;
        let late = svix_sign(SECRET, ID, future, body);
        assert!(!svix_verifies(
            SECRET,
            &future.to_string(),
            &late,
            body,
            NOW
        ));
        // The tolerance is configurable.
        let wide = WebhookVerifier::new(Svix).tolerance_secs(DEFAULT_TOLERANCE_SECS * 2);
        assert!(wide.verify(SECRET, &svix_headers(&sent.to_string(), &stale), body, NOW));
    }

    #[test]
    fn unreadable_svix_input_refuses() {
        let body = b"{}";
        let header = svix_sign(SECRET, ID, NOW, body);
        // Missing headers entirely; a timestamp that is not a number; a
        // signature list with no readable entry.
        assert!(!WebhookVerifier::new(Svix).verify(SECRET, &headers(&[]), body, NOW));
        assert!(!svix_verifies(SECRET, "recently", &header, body, NOW));
        assert!(!svix_verifies(SECRET, "1800000000", "garbage", body, NOW));
        // A secret that does not decode is a misconfiguration, not a
        // fallback; an empty secret is not a key.
        assert!(!svix_verifies(
            "whsec_!!!!",
            "1800000000",
            &header,
            body,
            NOW
        ));
        assert!(!svix_verifies("", "1800000000", &header, body, NOW));
    }

    #[test]
    fn a_stripe_delivery_verifies_and_malformed_ones_refuse() {
        let body = b"{}";
        let header = stripe_sign(STRIPE_SECRET, NOW, body);
        assert!(stripe_verifies(STRIPE_SECRET, &header, body, NOW));
        // The header name is configurable: the same layout under another.
        let renamed = WebhookVerifier::new(StripeStyle {
            header: "X-Signature",
        });
        let under = headers(&[("X-Signature", &header)]);
        assert!(renamed.verify(STRIPE_SECRET, &under, body, NOW));
        // Body changed; another endpoint's secret.
        assert!(!stripe_verifies(STRIPE_SECRET, &header, b"x", NOW));
        assert!(!stripe_verifies("another-secret-dummy", &header, body, NOW));
        // No `t=` (nothing to hold the tolerance to), a `t=` that is not a
        // number, and no `v1=` at all.
        let digest = hex(&mac(
            STRIPE_SECRET.as_bytes(),
            &[NOW.to_string().as_bytes(), b".", body],
        ));
        assert!(!stripe_verifies(
            STRIPE_SECRET,
            &format!("v1={digest}"),
            body,
            NOW
        ));
        assert!(!stripe_verifies(
            STRIPE_SECRET,
            &format!("t=recently,v1={digest}"),
            body,
            NOW
        ));
        assert!(!stripe_verifies(STRIPE_SECRET, "t=1800000000", body, NOW));
        // The timestamp carries the replay tolerance here too.
        let sent = NOW - DEFAULT_TOLERANCE_SECS - 1;
        let stale = stripe_sign(STRIPE_SECRET, sent, body);
        assert!(!stripe_verifies(STRIPE_SECRET, &stale, body, NOW));
    }

    #[test]
    fn a_provider_scheme_verifies_raw_and_timestamped_deliveries() {
        let body = br#"{"event":"order.created"}"#;
        let raw = provider(Hex, None, None);
        let got = headers(&[("X-Signature", &provider_sign(None, body))]);
        // No timestamp header: the payload is the raw body and the
        // tolerance does not apply — "now" is whatever the caller says.
        assert!(raw.verify(PROVIDER_SECRET, &got, body, NOW));
        assert!(raw.verify(PROVIDER_SECRET, &got, body, NOW + 10_000));
        assert!(!raw.verify(PROVIDER_SECRET, &got, b"x", NOW));
        assert!(!raw.verify("other", &got, body, NOW));
        assert!(
            !raw.verify("", &got, body, NOW),
            "an empty secret is not a key"
        );
        // With a timestamp header the payload is `{timestamp}.{body}`, a
        // configured header that is not sent refuses instead of silently
        // downgrading, and a prefixed entry is stripped before decoding.
        let stamped = provider(Hex, Some("sha256="), Some("X-At"));
        let header = format!("sha256={}", provider_sign(Some(NOW), body));
        let with_at = headers(&[("X-Signature", &header), ("X-At", "1800000000")]);
        assert!(stamped.verify(PROVIDER_SECRET, &with_at, body, NOW));
        let no_at = headers(&[("X-Signature", &header)]);
        assert!(!stamped.verify(PROVIDER_SECRET, &no_at, body, NOW));
        let no_sig = headers(&[("X-At", "1800000000")]);
        assert!(!stamped.verify(PROVIDER_SECRET, &no_sig, body, NOW));
        // Base64 encoding works too; an entry that does not decode is
        // skipped rather than fatal.
        let b64 = provider(Base64, None, None);
        let encoded = STANDARD.encode(mac(PROVIDER_SECRET.as_bytes(), &[body]));
        let b64hdr = headers(&[("X-Signature", &encoded)]);
        assert!(b64.verify(PROVIDER_SECRET, &b64hdr, body, NOW));
        let junk = headers(&[("X-Signature", "!!!!")]);
        assert!(!b64.verify(PROVIDER_SECRET, &junk, body, NOW));
    }
}