Skip to main content

webhook_verify/providers/
custom.rs

1//! User-configurable HMAC schemes ([`CustomScheme`], `spec.md` §2.2).
2//!
3//! Lets callers verify a long-tail provider (or an internal sender) without
4//! waiting on a crate release, by describing the scheme declaratively:
5//! hash algorithm, signature header, encoding, optional prefix, optional
6//! timestamp header for replay protection, and a function building the
7//! signed string.
8//!
9//! # Security model
10//!
11//! Custom schemes get exactly the same guarantees as built-in providers:
12//! HMAC construction and constant-time comparison run through the audited
13//! helpers in [`crate::core::crypto`]; parsing paths fail closed with
14//! structured errors instead of panicking. What is *not* covered is choosing
15//! the scheme itself — a mis-described scheme (e.g. signing a re-serialized
16//! body instead of raw bytes) will verify nothing useful. Configure
17//! `signed_string` to reproduce the provider's documented recipe exactly.
18//! `signed_string` is a plain `fn`, so it cannot capture values from its
19//! environment; if the scheme signs request context (such as a URL), read it
20//! out of `headers` inside the function — for
21//! [`VerifyOptions::request_url`] contents, construct your scheme headers to
22//! carry the URL.
23//!
24//! # Example
25//!
26//! ```
27//! use webhook_verify::{verify, CustomScheme, Encoding, HashAlg, Provider, Secret};
28//!
29//! // A fictional provider that signs the raw body with HMAC-SHA256 and
30//! // sends it hex-encoded in `X-Webhook-Sig`.
31//! let scheme = CustomScheme {
32//!     hash: HashAlg::Sha256,
33//!     signature_header: "X-Webhook-Sig",
34//!     timestamp_header: None,
35//!     encoding: Encoding::Hex,
36//!     prefix: None,
37//!     signed_string: |_headers, raw_body| raw_body.to_vec(),
38//! };
39//!
40//! let result = verify(
41//!     Provider::Custom(scheme),
42//!     &[("X-Webhook-Sig", "0e7320e558b4421b7aa464a9027132b7176c02adf16ed36778ce302d6f2a6ac3")],
43//!     b"payload",
44//!     &Secret::new("shared-secret"),
45//!     Default::default(),
46//! );
47//!
48//! assert!(result.is_ok());
49//! ```
50
51#![deny(clippy::unwrap_used, clippy::expect_used)]
52
53use alloc::vec::Vec;
54use core::fmt;
55
56use crate::core::VerifyOptions;
57use crate::core::crypto::{verify_hmac_sha1, verify_hmac_sha256, verify_hmac_sha512};
58use crate::core::error::VerifyError;
59use crate::core::headers::HeaderMap;
60use crate::core::replay::{check_replay, parse_timestamp};
61use crate::core::secret::Secret;
62use base64::Engine;
63
64/// HMAC hash algorithms available to a [`CustomScheme`] (`spec.md` §2.2).
65#[must_use]
66#[non_exhaustive]
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68pub enum HashAlg {
69    /// HMAC-SHA256; 32-byte digest.
70    Sha256,
71    /// HMAC-SHA1; 20-byte digest. As Twilio's docs note, HMAC construction
72    /// is not affected by SHA-1 collision attacks given a secret key — but
73    /// prefer SHA-256 unless the sender's scheme mandates SHA-1.
74    Sha1,
75    /// HMAC-SHA512; 64-byte digest.
76    Sha512,
77}
78
79impl fmt::Display for HashAlg {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        match self {
82            HashAlg::Sha256 => f.write_str("SHA-256"),
83            HashAlg::Sha1 => f.write_str("SHA-1"),
84            HashAlg::Sha512 => f.write_str("SHA-512"),
85        }
86    }
87}
88
89impl HashAlg {
90    /// Digest output length in bytes; decoded signatures must match it.
91    fn digest_len(self) -> usize {
92        match self {
93            HashAlg::Sha256 => 32,
94            HashAlg::Sha1 => 20,
95            HashAlg::Sha512 => 64,
96        }
97    }
98}
99
100/// Wire encoding of the signature in its header (`spec.md` §2.2).
101#[must_use]
102#[non_exhaustive]
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104pub enum Encoding {
105    /// Lower/uppercase hexadecimal (both accepted by the decoder).
106    Hex,
107    /// Standard base64 alphabet with padding.
108    Base64,
109}
110
111impl fmt::Display for Encoding {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            Encoding::Hex => f.write_str("hex"),
115            Encoding::Base64 => f.write_str("base64"),
116        }
117    }
118}
119
120/// A user-configured HMAC verification scheme for providers not yet built in
121/// (`spec.md` §2.2). Also the prototyping shape new built-in providers are
122/// implemented against before promotion into the [`Provider`](crate::Provider)
123/// enum.
124///
125/// All comparisons are constant-time and all decoding fails closed, exactly
126/// as for built-in providers.
127///
128/// [`PartialEq`] compares the declarative configuration only; `signed_string`
129/// is excluded — function pointers have no meaningful or reliable equality.
130#[must_use]
131#[derive(Debug, Clone, Copy)]
132pub struct CustomScheme {
133    /// HMAC hash algorithm the sender uses.
134    pub hash: HashAlg,
135    /// Name of the header carrying the encoded signature.
136    pub signature_header: &'static str,
137    /// Name of the header carrying the unix-seconds timestamp, when the
138    /// sender signs one. Setting this enables replay protection with the
139    /// shared symmetric tolerance (`|now - t| <= max_age`, default 300s);
140    /// leaving it `None` disables replay checks for this scheme, mirroring
141    /// built-ins like GitHub whose schemes sign no timestamp.
142    pub timestamp_header: Option<&'static str>,
143    /// Encoding of the signature value in its header.
144    pub encoding: Encoding,
145    /// Literal prefix required before the encoded signature (e.g. `"v0="`
146    /// or `"sha256="`). When set, a header not starting with it is rejected
147    /// as malformed rather than leniently accepted — prevents downgrade
148    /// confusion between scheme versions.
149    pub prefix: Option<&'static str>,
150    /// Builds the exact byte string the sender HMACs, from the request
151    /// headers and the **raw** body bytes. Read any additional signed inputs
152    /// (timestamps, URL context) out of `headers`; never re-serialize or
153    /// normalize `raw_body`.
154    pub signed_string: fn(&dyn HeaderMap, &[u8]) -> Vec<u8>,
155}
156
157impl PartialEq for CustomScheme {
158    fn eq(&self, other: &Self) -> bool {
159        self.hash == other.hash
160            && self.signature_header == other.signature_header
161            && self.timestamp_header == other.timestamp_header
162            && self.encoding == other.encoding
163            && self.prefix == other.prefix
164    }
165}
166
167impl Eq for CustomScheme {}
168
169impl core::hash::Hash for CustomScheme {
170    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
171        self.hash.hash(state);
172        self.signature_header.hash(state);
173        self.timestamp_header.hash(state);
174        self.encoding.hash(state);
175        self.prefix.hash(state);
176    }
177}
178
179pub(crate) fn verify(
180    scheme: &CustomScheme,
181    headers: &dyn HeaderMap,
182    raw_body: &[u8],
183    secret: &Secret,
184    options: &VerifyOptions,
185) -> Result<(), VerifyError> {
186    let signature_value =
187        headers
188            .get(scheme.signature_header)
189            .ok_or(VerifyError::MissingHeader {
190                header: scheme.signature_header,
191            })?;
192
193    // The timestamp header is fetched up front so a missing one is reported
194    // as such even when the signature would also have failed — matching how
195    // built-in timestamped schemes report. Its value is parsed after the
196    // signature, same parse order as the built-ins.
197    let timestamp_raw = match scheme.timestamp_header {
198        Some(timestamp_header) => Some((
199            timestamp_header,
200            headers
201                .get(timestamp_header)
202                .ok_or(VerifyError::MissingHeader {
203                    header: timestamp_header,
204                })?,
205        )),
206        None => None,
207    };
208
209    let provided_signature = parse_signature(scheme, signature_value)?;
210
211    let timestamp = match timestamp_raw {
212        Some((timestamp_header, raw)) => Some(parse_timestamp(timestamp_header, raw)?),
213        None => None,
214    };
215
216    let signed_string = (scheme.signed_string)(headers, raw_body);
217
218    let matched = match scheme.hash {
219        HashAlg::Sha256 => {
220            verify_hmac_sha256(secret.as_bytes(), &signed_string, &provided_signature)
221        }
222        HashAlg::Sha1 => verify_hmac_sha1(secret.as_bytes(), &signed_string, &provided_signature),
223        HashAlg::Sha512 => {
224            verify_hmac_sha512(secret.as_bytes(), &signed_string, &provided_signature)
225        }
226    };
227
228    if !matched {
229        return Err(VerifyError::SignatureMismatch);
230    }
231
232    if let Some(timestamp) = timestamp {
233        check_replay(timestamp, options)?;
234    }
235
236    Ok(())
237}
238
239/// Decodes the signature header value per the scheme's prefix and encoding.
240fn parse_signature(scheme: &CustomScheme, value: &str) -> Result<Vec<u8>, VerifyError> {
241    if value.is_empty() {
242        return Err(VerifyError::MalformedHeader {
243            header: scheme.signature_header,
244            reason: "header is empty",
245        });
246    }
247
248    let encoded = match scheme.prefix {
249        Some(prefix) => value
250            .strip_prefix(prefix)
251            .ok_or(VerifyError::MalformedHeader {
252                header: scheme.signature_header,
253                reason: "signature does not start with the configured scheme prefix",
254            })?,
255        None => value,
256    };
257
258    if encoded.is_empty() {
259        return Err(VerifyError::MalformedHeader {
260            header: scheme.signature_header,
261            reason: "empty signature after prefix",
262        });
263    }
264
265    let bytes = match scheme.encoding {
266        Encoding::Hex => hex::decode(encoded).map_err(|_| VerifyError::BadEncoding {
267            reason: "signature is not valid hexadecimal",
268        })?,
269        Encoding::Base64 => base64::engine::general_purpose::STANDARD
270            .decode(encoded)
271            .map_err(|_| VerifyError::BadEncoding {
272                reason: "signature is not valid base64",
273            })?,
274    };
275
276    if bytes.len() != scheme.hash.digest_len() {
277        return Err(VerifyError::BadEncoding {
278            reason: "signature length does not match the hash algorithm's digest size",
279        });
280    }
281
282    Ok(bytes)
283}
284
285#[cfg(test)]
286mod tests {
287    use super::{CustomScheme, Encoding, HashAlg};
288    use crate::core::error::VerifyError;
289    use crate::core::options::VerifyOptions;
290    use crate::core::secret::Secret;
291    use crate::providers::Provider;
292    use crate::test_helpers::clocked_at;
293    use crate::verify;
294    use std::time::Duration;
295
296    /// Signing secret from the worked example in Slack's official docs
297    /// (<https://docs.slack.dev/authentication/verifying-requests-from-slack>);
298    /// also the anchor vector proving `CustomScheme` can express a real
299    /// documented scheme bit-for-bit.
300    const SLACK_SECRET: &str = "8f742231b10e8888abcd99yyyzzz85a5";
301    /// Raw body from the same worked example.
302    const SLACK_BODY: &[u8] = b"token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c";
303    const SLACK_TIMESTAMP: u64 = 1_531_420_618;
304    /// Official published signature for that example:
305    /// `v0=a2114d57...` (Slack docs, same URL as above).
306    const SLACK_SIGNATURE: &str =
307        "a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503";
308
309    /// Key/data of RFC 4231 test case 2 (HMAC-SHA256/SHA512) and RFC 2202
310    /// test case 2 (HMAC-SHA1); digests below cross-checked locally against
311    /// those RFCs and re-encoded to base64 with `base64(1)` semantics.
312    const RFC_KEY: &str = "Jefe";
313    const RFC_DATA: &[u8] = b"what do ya want for nothing?";
314
315    /// A fictional sender signing `"{timestamp}.{raw_body}"` with
316    /// HMAC-SHA256, hex-encoded behind a `sha256=` prefix, timestamp in its
317    /// own header. Locally constructed deterministic vectors.
318    mod ts_scheme {
319        pub const SECRET: &str = "custom_shared_secret";
320        pub const HEADER: &str = "X-Example-Signature";
321        pub const TS_HEADER: &str = "X-Example-Timestamp";
322        pub const TIMESTAMP: u64 = 1_700_000_000;
323        pub const PING_BODY: &[u8] = b"{\"event\":\"ping\"}";
324        /// HMAC-SHA256 over `1700000000.{PING_BODY}`.
325        pub const PING_SIG: &str =
326            "9db1e644e50830b54efa1992679fb889d28ae7d6e4474cb4ca27e867091021f8";
327        /// Over an empty body (boundary case).
328        pub const EMPTY_BODY_SIG: &str =
329            "e859e71951a27e39c00f05e1cdb40c1b0d13171f43f635f10e5ccab222b3e67b";
330        /// Over `"héllo, 🦀 world!"` (unicode boundary case).
331        pub const UNICODE_BODY_SIG: &str =
332            "a651431edb322282434426d3e5bbb1c39eadd68e32d68e7604b28f3deee73791";
333    }
334
335    fn ts_signed_string(headers: &dyn crate::HeaderMap, raw_body: &[u8]) -> Vec<u8> {
336        let ts = headers.get(ts_scheme::TS_HEADER).unwrap_or_default();
337        let mut signed = Vec::with_capacity(ts.len() + 1 + raw_body.len());
338        signed.extend_from_slice(ts.as_bytes());
339        signed.push(b'.');
340        signed.extend_from_slice(raw_body);
341        signed
342    }
343
344    fn ts_scheme_config() -> CustomScheme {
345        CustomScheme {
346            hash: HashAlg::Sha256,
347            signature_header: ts_scheme::HEADER,
348            timestamp_header: Some(ts_scheme::TS_HEADER),
349            encoding: Encoding::Hex,
350            prefix: Some("sha256="),
351            signed_string: ts_signed_string,
352        }
353    }
354
355    fn verify_custom(
356        scheme: &CustomScheme,
357        headers: &dyn crate::HeaderMap,
358        body: &[u8],
359        secret: &str,
360        options: VerifyOptions,
361    ) -> Result<(), VerifyError> {
362        verify(
363            Provider::Custom(*scheme),
364            headers,
365            body,
366            &Secret::new(secret),
367            options,
368        )
369    }
370
371    // --- 1. Official vectors ------------------------------------------------
372
373    /// Slack's documented `v0=` scheme, expressed through `CustomScheme`,
374    /// verified against the signature Slack's own docs publish for this
375    /// exact secret/body/timestamp triple.
376    #[test]
377    fn reproduces_official_slack_vector() {
378        let scheme = CustomScheme {
379            hash: HashAlg::Sha256,
380            signature_header: "X-Slack-Signature",
381            timestamp_header: Some("X-Slack-Request-Timestamp"),
382            encoding: Encoding::Hex,
383            prefix: Some("v0="),
384            signed_string: |headers, raw_body| {
385                // `v0:{timestamp}:{raw_body}` — timestamp verbatim from its
386                // header, per Slack's docs.
387                let ts = headers.get("X-Slack-Request-Timestamp").unwrap_or_default();
388                let mut signed = Vec::with_capacity(3 + ts.len() + 1 + raw_body.len());
389                signed.extend_from_slice(b"v0:");
390                signed.extend_from_slice(ts.as_bytes());
391                signed.push(b':');
392                signed.extend_from_slice(raw_body);
393                signed
394            },
395        };
396
397        let result = verify_custom(
398            &scheme,
399            &[
400                (
401                    "X-Slack-Signature",
402                    format!("v0={SLACK_SIGNATURE}").as_str(),
403                ),
404                ("X-Slack-Request-Timestamp", "1531420618"),
405            ],
406            SLACK_BODY,
407            SLACK_SECRET,
408            clocked_at(SLACK_TIMESTAMP, Some(Duration::from_secs(300))),
409        );
410        assert_eq!(result, Ok(()));
411    }
412
413    /// Raw-body schemes across all three hash algorithms, checked against
414    /// RFC 4231 / RFC 2202 digests (hex), plus base64 encodings of the same
415    /// digests.
416    #[test]
417    fn rfc_vectors_across_hash_and_encoding_combinations() {
418        let raw_body_scheme = |hash, encoding| CustomScheme {
419            hash,
420            signature_header: "X-Raw-Sig",
421            timestamp_header: None,
422            encoding,
423            prefix: None,
424            signed_string: |_headers, raw_body| raw_body.to_vec(),
425        };
426
427        // (hash, encoding, expected signature header value)
428        let cases: &[(HashAlg, Encoding, &str)] = &[
429            (
430                HashAlg::Sha256,
431                Encoding::Hex,
432                "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
433            ),
434            (
435                HashAlg::Sha256,
436                Encoding::Base64,
437                "W9zBRr9gdU5qBCQmCJV1x1oAPwidJzmDnexYuWTsOEM=",
438            ),
439            (
440                HashAlg::Sha1,
441                Encoding::Hex,
442                "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
443            ),
444            (
445                HashAlg::Sha1,
446                Encoding::Base64,
447                "7/zfauXrL6LSdBbV8YTfnCWafHk=",
448            ),
449            (
450                HashAlg::Sha512,
451                Encoding::Hex,
452                "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737",
453            ),
454            (
455                HashAlg::Sha512,
456                Encoding::Base64,
457                "Fkt6e/z4GeLjlfvnO1bgo4e9ZCIugx/WECcM1+olBVSXWL91wFqZSm0DT2X48Ob9yuqxo01Ka0tjbgcKOLznNw==",
458            ),
459        ];
460
461        for &(hash, encoding, signature) in cases {
462            let scheme = raw_body_scheme(hash, encoding);
463            let result = verify_custom(
464                &scheme,
465                &[("X-Raw-Sig", signature)],
466                RFC_DATA,
467                RFC_KEY,
468                Default::default(),
469            );
470            assert_eq!(result, Ok(()), "{hash:?} + {encoding:?}");
471        }
472    }
473
474    // --- Boundary bodies on the local timestamped scheme --------------------
475
476    fn ts_headers(timestamp: u64, signature: &str) -> [(String, String); 2] {
477        [
478            (ts_scheme::HEADER.to_string(), format!("sha256={signature}")),
479            (ts_scheme::TS_HEADER.to_string(), timestamp.to_string()),
480        ]
481    }
482
483    fn verify_ts_fresh(body: &[u8], signature: &str) -> Result<(), VerifyError> {
484        verify_custom(
485            &ts_scheme_config(),
486            &ts_headers(ts_scheme::TIMESTAMP, signature),
487            body,
488            ts_scheme::SECRET,
489            // "now" == signed timestamp: always within tolerance.
490            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
491        )
492    }
493
494    #[test]
495    fn boundary_bodies_verify() {
496        assert_eq!(verify_ts_fresh(b"", ts_scheme::EMPTY_BODY_SIG), Ok(()));
497        assert_eq!(
498            verify_ts_fresh("héllo, 🦀 world!".as_bytes(), ts_scheme::UNICODE_BODY_SIG),
499            Ok(())
500        );
501    }
502
503    #[test]
504    fn header_names_are_case_insensitive() {
505        let result = verify_custom(
506            &ts_scheme_config(),
507            &[
508                (
509                    "x-example-signature",
510                    format!("sha256={}", ts_scheme::PING_SIG).as_str(),
511                ),
512                ("X-EXAMPLE-TIMESTAMP", "1700000000"),
513            ],
514            ts_scheme::PING_BODY,
515            ts_scheme::SECRET,
516            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
517        );
518        assert_eq!(result, Ok(()));
519    }
520
521    // --- 2. Negative tests ---------------------------------------------------
522
523    #[test]
524    fn flipped_signature_byte_fails() {
525        // Swap the first hex character for another in-alphabet one so this
526        // exercises a wrong-but-well-formed signature, not a decoding error.
527        let first = &ts_scheme::PING_SIG[..1];
528        let replacement = if first == "9" { "a" } else { "9" };
529        let flipped = format!("{replacement}{}", &ts_scheme::PING_SIG[1..]);
530        assert_ne!(flipped, ts_scheme::PING_SIG);
531        assert_eq!(
532            verify_ts_fresh(ts_scheme::PING_BODY, &flipped),
533            Err(VerifyError::SignatureMismatch)
534        );
535    }
536
537    #[test]
538    fn wrong_secret_fails() {
539        assert_eq!(
540            verify_ts_fresh_with_secret(
541                ts_scheme::PING_BODY,
542                ts_scheme::PING_SIG,
543                "another secret"
544            ),
545            Err(VerifyError::SignatureMismatch)
546        );
547    }
548
549    fn verify_ts_fresh_with_secret(
550        body: &[u8],
551        signature: &str,
552        secret: &str,
553    ) -> Result<(), VerifyError> {
554        verify_custom(
555            &ts_scheme_config(),
556            &ts_headers(ts_scheme::TIMESTAMP, signature),
557            body,
558            secret,
559            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
560        )
561    }
562
563    // --- 3. Tamper tests ------------------------------------------------------
564
565    #[test]
566    fn tampered_body_fails() {
567        assert_eq!(
568            verify_ts_fresh(
569                b"{\"event\":\"ping\",\"tampered\":true}",
570                ts_scheme::PING_SIG
571            ),
572            Err(VerifyError::SignatureMismatch)
573        );
574    }
575
576    #[test]
577    fn tampered_timestamp_fails_signature_check() {
578        // The timestamp is inside the signed string, so changing it must not
579        // verify even though it stays within replay tolerance.
580        let result = verify_custom(
581            &ts_scheme_config(),
582            &ts_headers(ts_scheme::TIMESTAMP - 1, ts_scheme::PING_SIG),
583            ts_scheme::PING_BODY,
584            ts_scheme::SECRET,
585            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
586        );
587        assert_eq!(result, Err(VerifyError::SignatureMismatch));
588    }
589
590    // --- 4. Replay tests -------------------------------------------------------
591
592    #[test]
593    fn stale_timestamp_rejected() {
594        let result = verify_custom(
595            &ts_scheme_config(),
596            &ts_headers(ts_scheme::TIMESTAMP, ts_scheme::PING_SIG),
597            ts_scheme::PING_BODY,
598            ts_scheme::SECRET,
599            clocked_at(ts_scheme::TIMESTAMP + 301, Some(Duration::from_secs(300))),
600        );
601        assert_eq!(
602            result,
603            Err(VerifyError::TimestampOutOfTolerance {
604                skew: Duration::from_secs(301),
605                max_age: Duration::from_secs(300),
606            })
607        );
608    }
609
610    #[test]
611    fn future_timestamp_rejected_symmetrically() {
612        let result = verify_custom(
613            &ts_scheme_config(),
614            &ts_headers(ts_scheme::TIMESTAMP, ts_scheme::PING_SIG),
615            ts_scheme::PING_BODY,
616            ts_scheme::SECRET,
617            clocked_at(ts_scheme::TIMESTAMP - 301, Some(Duration::from_secs(300))),
618        );
619        assert_eq!(
620            result,
621            Err(VerifyError::TimestampOutOfTolerance {
622                skew: Duration::from_secs(301),
623                max_age: Duration::from_secs(300),
624            })
625        );
626    }
627
628    #[test]
629    fn window_edges_are_in_tolerance() {
630        for now in [ts_scheme::TIMESTAMP - 300, ts_scheme::TIMESTAMP + 300] {
631            let result = verify_custom(
632                &ts_scheme_config(),
633                &ts_headers(ts_scheme::TIMESTAMP, ts_scheme::PING_SIG),
634                ts_scheme::PING_BODY,
635                ts_scheme::SECRET,
636                clocked_at(now, Some(Duration::from_secs(300))),
637            );
638            assert_eq!(result, Ok(()), "now = {now}");
639        }
640    }
641
642    #[test]
643    fn disabled_max_age_skips_replay_check() {
644        let result = verify_custom(
645            &ts_scheme_config(),
646            &ts_headers(ts_scheme::TIMESTAMP, ts_scheme::PING_SIG),
647            ts_scheme::PING_BODY,
648            ts_scheme::SECRET,
649            clocked_at(ts_scheme::TIMESTAMP + 86_400 * 365, None),
650        );
651        assert_eq!(result, Ok(()));
652    }
653
654    #[test]
655    fn no_timestamp_header_means_no_replay_requirements() {
656        // Schemes without a timestamp behave like GitHub/Linear: no clock is
657        // consulted and no timestamp header is required. The raw-body scheme
658        // from the RFC vectors is exactly this shape.
659        let scheme = CustomScheme {
660            hash: HashAlg::Sha256,
661            signature_header: "X-Raw-Sig",
662            timestamp_header: None,
663            encoding: Encoding::Hex,
664            prefix: None,
665            signed_string: |_headers, raw_body| raw_body.to_vec(),
666        };
667        let result = verify_custom(
668            &scheme,
669            &[(
670                "X-Raw-Sig",
671                "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
672            )],
673            RFC_DATA,
674            RFC_KEY,
675            VerifyOptions {
676                max_age: Some(Duration::ZERO),
677                clock: None,
678                request_url: None,
679                form_params: None,
680                verifying_material: None,
681                webhook_id: None,
682            },
683        );
684        assert_eq!(result, Ok(()));
685    }
686
687    // --- 5. Malformed-header battery -------------------------------------------
688
689    #[test]
690    fn missing_headers_error_distinctly() {
691        let missing_signature = verify_custom(
692            &ts_scheme_config(),
693            &[(ts_scheme::TS_HEADER.to_string(), "1700000000".to_string())],
694            ts_scheme::PING_BODY,
695            ts_scheme::SECRET,
696            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
697        );
698        assert_eq!(
699            missing_signature,
700            Err(VerifyError::MissingHeader {
701                header: ts_scheme::HEADER
702            })
703        );
704
705        let missing_timestamp = verify_custom(
706            &ts_scheme_config(),
707            &[(
708                ts_scheme::HEADER.to_string(),
709                format!("sha256={}", ts_scheme::PING_SIG),
710            )],
711            ts_scheme::PING_BODY,
712            ts_scheme::SECRET,
713            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
714        );
715        assert_eq!(
716            missing_timestamp,
717            Err(VerifyError::MissingHeader {
718                header: ts_scheme::TS_HEADER
719            })
720        );
721    }
722
723    #[test]
724    fn malformed_signature_plus_missing_timestamp_reports_missing_header() {
725        // When the signature is present but malformed *and* the timestamp
726        // header is absent, the timestamp header (like all built-in
727        // timestamped schemes) is reported as missing rather than the
728        // signature as malformed — the header lookup precedes parsing.
729        let result = verify_custom(
730            &ts_scheme_config(),
731            &[(ts_scheme::HEADER.to_string(), "garbage".to_string())],
732            ts_scheme::PING_BODY,
733            ts_scheme::SECRET,
734            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
735        );
736        assert_eq!(
737            result,
738            Err(VerifyError::MissingHeader {
739                header: ts_scheme::TS_HEADER
740            })
741        );
742    }
743
744    #[test]
745    fn malformed_signature_values_error_distinctly() {
746        let cases: Vec<(String, VerifyError)> = vec![
747            (
748                String::new(),
749                VerifyError::MalformedHeader {
750                    header: ts_scheme::HEADER,
751                    reason: "header is empty",
752                },
753            ),
754            (
755                // Missing the configured prefix entirely.
756                ts_scheme::PING_SIG.to_string(),
757                VerifyError::MalformedHeader {
758                    header: ts_scheme::HEADER,
759                    reason: "signature does not start with the configured scheme prefix",
760                },
761            ),
762            (
763                // A different scheme version's prefix: reject, never accept.
764                format!("sha512={}", ts_scheme::PING_SIG),
765                VerifyError::MalformedHeader {
766                    header: ts_scheme::HEADER,
767                    reason: "signature does not start with the configured scheme prefix",
768                },
769            ),
770            (
771                "sha256=".to_string(),
772                VerifyError::MalformedHeader {
773                    header: ts_scheme::HEADER,
774                    reason: "empty signature after prefix",
775                },
776            ),
777        ];
778        for (value, expected) in cases {
779            let result = verify_custom(
780                &ts_scheme_config(),
781                &[
782                    (ts_scheme::HEADER.to_string(), value.clone()),
783                    (ts_scheme::TS_HEADER.to_string(), "1700000000".to_string()),
784                ],
785                ts_scheme::PING_BODY,
786                ts_scheme::SECRET,
787                clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
788            );
789            assert_eq!(result, Err(expected), "input: {value:?}");
790        }
791    }
792
793    #[test]
794    fn bad_encoding_errors_distinctly() {
795        let cases: Vec<String> = vec![
796            // Not hex at all.
797            "sha256=zzzz".to_string(),
798            // Valid hex but wrong digest length for SHA-256 (20-byte SHA-1 size).
799            "sha256=deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".to_string(),
800        ];
801        for value in cases {
802            let result = verify_custom(
803                &ts_scheme_config(),
804                &[
805                    (ts_scheme::HEADER.to_string(), value.clone()),
806                    (ts_scheme::TS_HEADER.to_string(), "1700000000".to_string()),
807                ],
808                ts_scheme::PING_BODY,
809                ts_scheme::SECRET,
810                clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
811            );
812            match result {
813                Err(VerifyError::BadEncoding { .. }) => {}
814                other => panic!("expected BadEncoding for {value:?}, got {other:?}"),
815            }
816        }
817
818        // Base64 encoding path rejects non-base64 garbage distinctly too.
819        let b64_scheme = CustomScheme {
820            encoding: Encoding::Base64,
821            ..ts_scheme_config()
822        };
823        let result = verify_custom(
824            &b64_scheme,
825            &[
826                (ts_scheme::HEADER.to_string(), "sha256=!!!".to_string()),
827                (ts_scheme::TS_HEADER.to_string(), "1700000000".to_string()),
828            ],
829            ts_scheme::PING_BODY,
830            ts_scheme::SECRET,
831            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
832        );
833        match result {
834            Err(VerifyError::BadEncoding { .. }) => {}
835            other => panic!("expected BadEncoding, got {other:?}"),
836        }
837    }
838
839    #[test]
840    fn malformed_timestamps_error_distinctly() {
841        let cases: Vec<(String, VerifyError)> = vec![
842            (
843                String::new(),
844                VerifyError::MalformedHeader {
845                    header: ts_scheme::TS_HEADER,
846                    reason: "header is empty",
847                },
848            ),
849            (
850                "not-a-number".to_string(),
851                VerifyError::MalformedHeader {
852                    header: ts_scheme::TS_HEADER,
853                    reason: "timestamp is not a valid unix timestamp",
854                },
855            ),
856            (
857                "-5".to_string(),
858                VerifyError::MalformedHeader {
859                    header: ts_scheme::TS_HEADER,
860                    reason: "timestamp is not a valid unix timestamp",
861                },
862            ),
863            (
864                "99999999999999999999999".to_string(),
865                VerifyError::MalformedHeader {
866                    header: ts_scheme::TS_HEADER,
867                    reason: "timestamp overflows unix seconds",
868                },
869            ),
870        ];
871        for (value, expected) in cases {
872            let result = verify_custom(
873                &ts_scheme_config(),
874                &[
875                    (
876                        ts_scheme::HEADER.to_string(),
877                        format!("sha256={}", ts_scheme::PING_SIG),
878                    ),
879                    (ts_scheme::TS_HEADER.to_string(), value.clone()),
880                ],
881                ts_scheme::PING_BODY,
882                ts_scheme::SECRET,
883                clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
884            );
885            assert_eq!(result, Err(expected), "input: {value:?}");
886        }
887    }
888
889    #[test]
890    fn empty_prefix_behaves_as_no_prefix() {
891        let scheme = CustomScheme {
892            prefix: Some(""),
893            ..ts_scheme_config()
894        };
895        let headers = [
896            (
897                ts_scheme::HEADER.to_string(),
898                ts_scheme::PING_SIG.to_string(),
899            ),
900            (ts_scheme::TS_HEADER.to_string(), "1700000000".to_string()),
901        ];
902        let result = verify_custom(
903            &scheme,
904            &headers,
905            ts_scheme::PING_BODY,
906            ts_scheme::SECRET,
907            clocked_at(ts_scheme::TIMESTAMP, Some(Duration::from_secs(300))),
908        );
909        assert_eq!(result, Ok(()));
910    }
911}