Skip to main content

webhook_verify/providers/
mod.rs

1//! Provider-specific signing schemes and the [`verify`] dispatch.
2//!
3//! Each provider lives in its own module implementing exactly the scheme
4//! documented in `spec.md` §3, backed by that provider's official test
5//! vectors. Providers without an implementation yet fail closed with
6//! [`VerifyError::UnsupportedProvider`].
7
8mod custom;
9mod discord;
10mod dropbox;
11mod github;
12mod linear;
13#[cfg(feature = "paypal")]
14mod paypal;
15#[cfg(feature = "sendgrid")]
16mod sendgrid;
17mod shopify;
18mod slack;
19mod square;
20mod standard_webhooks;
21mod stripe;
22mod twilio;
23mod zoom;
24
25pub use custom::{CustomScheme, Encoding, HashAlg};
26
27use core::fmt;
28
29#[cfg(any(feature = "tower", feature = "actix"))]
30use alloc::vec;
31
32#[cfg(any(feature = "tower", feature = "actix"))]
33use alloc::vec::Vec;
34
35use crate::core::VerifyOptions;
36use crate::core::error::VerifyError;
37use crate::core::headers::HeaderMap;
38use crate::core::secret::Secret;
39
40/// A webhook provider whose signature scheme this crate knows how to verify.
41///
42/// Variants for providers that do not have an implementation yet are still
43/// listed so the API surface matches `spec.md` §2 and stays additive as
44/// providers ship; calling [`verify()`] with one returns
45/// [`VerifyError::UnsupportedProvider`] (fail-closed).
46#[must_use]
47#[non_exhaustive]
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum Provider {
50    /// Stripe (`Stripe-Signature`, HMAC-SHA256 over `t.body`).
51    Stripe,
52    /// GitHub (`X-Hub-Signature-256`, HMAC-SHA256 over the raw body).
53    GitHub,
54    /// Shopify (`X-Shopify-Hmac-SHA256`, base64-encoded HMAC-SHA256).
55    Shopify,
56    /// Slack (`X-Slack-Signature`, `v0=` scheme with timestamp).
57    Slack,
58    /// Square (HMAC-SHA256 over notification URL + body, base64).
59    Square,
60    /// Twilio (HMAC-SHA1 over full URL + sorted form params; needs
61    /// `VerifyOptions::request_url` and `VerifyOptions::form_params`).
62    Twilio,
63    /// Discord (Ed25519 public-key signatures; `Secret` holds a public key).
64    ///
65    /// Unlike the shared-secret schemes, verification here proves the payload
66    /// was signed with the private key corresponding to the *public* key in
67    /// [`crate::Secret`] — see the provider module's security-model notes.
68    Discord,
69    /// PayPal (certificate-based RSASSA-PKCS1-v1_5 SHA-256; webhook ID and
70    /// certificate via `VerifyOptions::webhook_id` /
71    /// `VerifyOptions::verifying_material`).
72    ///
73    /// Requires the `paypal` crate feature; without it this variant fails
74    /// closed with [`VerifyError::UnsupportedProvider`].
75    PayPal,
76    /// SendGrid (ECDSA P-256; key via `VerifyOptions::verifying_material`).
77    ///
78    /// Requires the `sendgrid` crate feature; without it this variant fails
79    /// closed with [`VerifyError::UnsupportedProvider`].
80    SendGrid,
81    /// Linear (`linear-signature`, HMAC-SHA256).
82    Linear,
83    /// Zoom (`X-Zm-Signature`, HMAC-SHA256 with timestamp).
84    Zoom,
85    /// Dropbox (`X-Dropbox-Signature`, HMAC-SHA256 over the raw body).
86    Dropbox,
87    /// Standard Webhooks spec (`webhook-*` headers; Svix, Clerk, Resend, ...).
88    StandardWebhooks,
89    /// A caller-configured HMAC scheme (`spec.md` §2.2): covers long-tail
90    /// providers and internal senders without waiting on a crate release,
91    /// with the same constant-time and fail-closed guarantees as the
92    /// built-ins. See [`CustomScheme`].
93    Custom(CustomScheme),
94}
95
96impl fmt::Display for Provider {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match self {
99            Provider::Stripe => f.write_str("Stripe"),
100            Provider::GitHub => f.write_str("GitHub"),
101            Provider::Shopify => f.write_str("Shopify"),
102            Provider::Slack => f.write_str("Slack"),
103            Provider::Square => f.write_str("Square"),
104            Provider::Twilio => f.write_str("Twilio"),
105            Provider::Discord => f.write_str("Discord"),
106            Provider::PayPal => f.write_str("PayPal"),
107            Provider::SendGrid => f.write_str("SendGrid"),
108            Provider::Linear => f.write_str("Linear"),
109            Provider::Zoom => f.write_str("Zoom"),
110            Provider::Dropbox => f.write_str("Dropbox"),
111            Provider::StandardWebhooks => f.write_str("StandardWebhooks"),
112            Provider::Custom(scheme) => {
113                write!(f, "Custom({})", scheme.signature_header)
114            }
115        }
116    }
117}
118
119/// Header names that carry signing material for `provider`, per its row in
120/// `spec.md` §3.
121///
122/// Used by framework adapters (behind the `tower`/`actix` features) to reject
123/// requests whose signature headers arrive duplicated with conflicting values
124/// — see the ambiguity contract on [`crate::HeaderMap`] and `spec.md` §4.4,
125/// which the first-match-only lookup cannot detect on its own.
126///
127/// Returns an empty list for providers whose implementation is disabled by a
128/// feature flag; their verification fails closed with
129/// [`VerifyError::UnsupportedProvider`] regardless.
130#[cfg(any(feature = "tower", feature = "actix"))]
131pub(crate) fn signature_header_names(provider: &Provider) -> Vec<&'static str> {
132    match provider {
133        Provider::Stripe => vec![stripe::SIGNATURE_HEADER],
134        Provider::GitHub => vec![github::SIGNATURE_HEADER],
135        Provider::Shopify => vec![shopify::SIGNATURE_HEADER],
136        Provider::Slack => vec![slack::SIGNATURE_HEADER, slack::TIMESTAMP_HEADER],
137        Provider::Square => vec![square::SIGNATURE_HEADER],
138        Provider::Twilio => vec![twilio::SIGNATURE_HEADER],
139        Provider::Discord => {
140            vec![discord::SIGNATURE_HEADER, discord::TIMESTAMP_HEADER]
141        }
142        Provider::Linear => vec![linear::SIGNATURE_HEADER],
143        Provider::Dropbox => vec![dropbox::SIGNATURE_HEADER],
144        Provider::Zoom => vec![zoom::SIGNATURE_HEADER, zoom::TIMESTAMP_HEADER],
145        Provider::StandardWebhooks => vec![
146            standard_webhooks::ID_HEADER,
147            standard_webhooks::TIMESTAMP_HEADER,
148            standard_webhooks::SIGNATURE_HEADER,
149        ],
150        Provider::Custom(scheme) => {
151            let mut names = vec![scheme.signature_header];
152            if let Some(timestamp) = scheme.timestamp_header {
153                names.push(timestamp);
154            }
155            names
156        }
157        #[cfg(feature = "sendgrid")]
158        Provider::SendGrid => {
159            vec![sendgrid::SIGNATURE_HEADER, sendgrid::TIMESTAMP_HEADER]
160        }
161        #[cfg(feature = "paypal")]
162        Provider::PayPal => vec![
163            paypal::TRANSMISSION_ID_HEADER,
164            paypal::TRANSMISSION_TIME_HEADER,
165            paypal::TRANSMISSION_SIG_HEADER,
166            paypal::CERT_URL_HEADER,
167            paypal::AUTH_ALGO_HEADER,
168        ],
169        #[cfg(not(feature = "paypal"))]
170        Provider::PayPal => Vec::new(),
171        #[cfg(not(feature = "sendgrid"))]
172        Provider::SendGrid => Vec::new(),
173    }
174}
175
176/// Verifies that a webhook request was sent by `provider` and was not tampered
177/// with in transit.
178///
179/// * `headers` — request headers via [`HeaderMap`] (any framework's map works).
180/// * `raw_body` — the **exact bytes** received. Never re-serialize or
181///   re-encode the body before calling this.
182/// * `secret` — the shared secret configured with the provider. For asymmetric
183///   schemes (Discord) it holds the public key instead; each provider's docs
184///   state which applies.
185/// * `options` — tolerance/clock knobs; see [`VerifyOptions`].
186///
187/// Errors are structured ([`VerifyError`]) and never contain secret material.
188///
189/// # Errors
190///
191/// Returns [`VerifyError::MissingHeader`] when a required signature header is
192/// absent, [`VerifyError::MalformedHeader`] when a header is present but
193/// unparseable, and [`VerifyError::BadEncoding`] when a hex or base64 value
194/// fails to decode. [`VerifyError::SignatureMismatch`] is returned when the
195/// decoded signature does not match the expected value. Providers with
196/// timestamp-based replay protection return
197/// [`VerifyError::TimestampOutOfTolerance`] when the signed timestamp is too
198/// old. [`VerifyError::UnsupportedProvider`] is returned for providers whose
199/// implementation is disabled by a crate feature (PayPal without `paypal`,
200/// SendGrid without `sendgrid`). [`VerifyError::InvalidSecret`]
201/// is returned when the secret is not in the format the provider requires.
202/// [`VerifyError::MissingContext`] is returned when provider-specific request
203/// context (e.g. Square's notification URL) was not supplied via
204/// [`VerifyOptions`].
205pub fn verify(
206    provider: Provider,
207    headers: &dyn HeaderMap,
208    raw_body: &[u8],
209    secret: &Secret,
210    options: VerifyOptions,
211) -> Result<(), VerifyError> {
212    match provider {
213        Provider::Discord => discord::verify(headers, raw_body, secret, &options),
214        Provider::GitHub => github::verify(headers, raw_body, secret, &options),
215        Provider::Linear => linear::verify(headers, raw_body, secret, &options),
216        Provider::Zoom => zoom::verify(headers, raw_body, secret, &options),
217        Provider::Shopify => shopify::verify(headers, raw_body, secret, &options),
218        Provider::Slack => slack::verify(headers, raw_body, secret, &options),
219        Provider::Square => square::verify(headers, raw_body, secret, &options),
220        Provider::Stripe => stripe::verify(headers, raw_body, secret, &options),
221        Provider::StandardWebhooks => {
222            standard_webhooks::verify(headers, raw_body, secret, &options)
223        }
224        Provider::Twilio => twilio::verify(headers, raw_body, secret, &options),
225        Provider::Dropbox => dropbox::verify(headers, raw_body, secret, &options),
226        #[cfg(feature = "paypal")]
227        Provider::PayPal => paypal::verify(headers, raw_body, secret, &options),
228        #[cfg(not(feature = "paypal"))]
229        Provider::PayPal => Err(VerifyError::UnsupportedProvider),
230        #[cfg(feature = "sendgrid")]
231        Provider::SendGrid => sendgrid::verify(headers, raw_body, secret, &options),
232        #[cfg(not(feature = "sendgrid"))]
233        Provider::SendGrid => Err(VerifyError::UnsupportedProvider),
234        Provider::Custom(scheme) => custom::verify(&scheme, headers, raw_body, secret, &options),
235    }
236}
237
238/// Tries multiple secrets during a zero-downtime rotation window.
239///
240/// Stripe and Standard Webhooks allow multiple valid signatures during secret
241/// rotation (e.g. `v1=...,v1=...`). This function accepts a slice of
242/// [`Secret`]s — each representing an active signing key — and returns
243/// `Ok(())` if *any* of them verifies. On total failure it returns
244/// `Err(VerifyError::SignatureMismatch)` when at least one key was usable
245/// (no timing leak about which key was closest); it returns
246/// `Err(VerifyError::InvalidSecret)` only when *every* key was rejected for
247/// its own formatting.
248///
249/// For providers whose signing scheme itself embeds multiple signatures
250/// (Stripe's `v1=` list, Standard Webhooks' space-delimited `v1,<sig>`
251/// list), prefer [`verify()`] with a single secret — the per-provider
252/// multi-sig logic already accepts any matching element. `verify_any` is
253/// for the *separate* case where the provider's config allows *multiple
254/// distinct keys* to be valid simultaneously (e.g. during key rotation).
255///
256/// # Empty slice
257///
258/// Passing an empty `secrets` slice returns `SignatureMismatch` immediately
259/// — there is nothing to try and no attacker-controlled input to parse.
260///
261/// # Example
262///
263/// ```no_run
264/// use webhook_verify::{verify_any, HeaderMap, Provider, Secret};
265///
266/// # let headers: Vec<(String, String)> = vec![];
267/// # let raw_body: &[u8] = b"";
268/// // During rotation, both the old and new keys are valid.
269/// let secrets = [
270///     Secret::new("whsec_old_key_being_rotated_out"),
271///     Secret::new("whsec_new_key_being_rotated_in"),
272/// ];
273///
274/// let result = verify_any(
275///     Provider::Stripe,
276///     &headers,
277///     raw_body,
278///     &secrets,
279///     Default::default(),
280/// );
281/// ```
282///
283/// # Errors
284///
285/// Structural errors ([`VerifyError::MissingHeader`],
286/// [`VerifyError::MalformedHeader`], [`VerifyError::BadEncoding`],
287/// [`VerifyError::UnsupportedProvider`], [`VerifyError::MissingContext`])
288/// are returned immediately regardless of how many secrets remain, because
289/// they are deterministic across all secrets.
290/// [`VerifyError::TimestampOutOfTolerance`] is also returned immediately
291/// when encountered, since the timestamp is secret-independent.
292/// [`VerifyError::InvalidSecret`] is *not* returned immediately: a secret
293/// rejected for its own formatting is unusable for this request, but a
294/// later key in the slice may still be correct — which is the point of
295/// iterating during a rotation window. [`VerifyError::SignatureMismatch`]
296/// is returned once every secret has been tried without a match, provided
297/// at least one of them was well-formed; only when *every* secret was
298/// invalid does `verify_any` return the first
299/// [`VerifyError::InvalidSecret`], so an all-garbled configuration is
300/// reported as an operator-configuration error rather than disguised as a
301/// forgery.
302pub fn verify_any(
303    provider: Provider,
304    headers: &dyn HeaderMap,
305    raw_body: &[u8],
306    secrets: &[Secret],
307    options: VerifyOptions,
308) -> Result<(), VerifyError> {
309    // First InvalidSecret seen, reported only if *every* secret turns out
310    // to be unusable. Not a structural error: it is specific to one secret,
311    // so it must not abort the rotation search (issue #64).
312    let mut first_invalid_secret: Option<VerifyError> = None;
313    // Set once a well-formed key fails to match. A signature that fails
314    // against a usable key is the definitive total-failure signal and takes
315    // precedence over InvalidSecret in the final report.
316    let mut any_well_formed_mismatch = false;
317
318    for secret in secrets {
319        match verify(provider, headers, raw_body, secret, options.clone()) {
320            // A match on any active key is enough during rotation.
321            Ok(()) => return Ok(()),
322            // A well-formed key that simply doesn't match: keep trying the
323            // remaining keys, but remember that the signature failed against
324            // a usable key in case nothing else matches either.
325            Err(VerifyError::SignatureMismatch) => any_well_formed_mismatch = true,
326            // A garbled/undecodable key is unusable for *this* secret only;
327            // keep trying the rest and remember the first rejection in case
328            // none of them are usable either.
329            Err(invalid @ VerifyError::InvalidSecret { .. }) => {
330                first_invalid_secret.get_or_insert(invalid);
331            }
332            Err(other) => {
333                // Structural errors (MissingHeader, MalformedHeader,
334                // BadEncoding, UnsupportedProvider, MissingContext,
335                // TimestampOutOfTolerance) are deterministic across all
336                // secrets — they occur before any secret-dependent work.
337                // Return it immediately so callers can distinguish a
338                // malformed request from a forged signature.
339                return Err(other);
340            }
341        }
342    }
343    // All secrets exhausted without a match. Prefer the definitive
344    // SignatureMismatch once at least one key was usable; report the first
345    // InvalidSecret only when no usable key existed at all.
346    if !any_well_formed_mismatch {
347        if let Some(invalid) = first_invalid_secret {
348            return Err(invalid);
349        }
350    }
351    Err(VerifyError::SignatureMismatch)
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357    use crate::core::error::VerifyError;
358    use crate::core::secret::Secret;
359    use crate::test_helpers::clocked_at;
360    use std::time::Duration;
361
362    /// Locally constructs a Slack `v0=` signature over `v0:{ts}:{body}` with
363    /// the given secret (HMAC-SHA256, hex-encoded) — mirrors the construction
364    /// in `src/providers/slack.rs` (spec.md §3, Slack row). Test-only.
365    fn slack_signature(secret: &str, ts: u64, body: &[u8]) -> String {
366        use hmac::{Hmac, KeyInit, Mac};
367        use sha2::Sha256;
368
369        let mut mac = match Hmac::<Sha256>::new_from_slice(secret.as_bytes()) {
370            Ok(mac) => mac,
371            // Unreachable for a constant test secret (HMAC accepts
372            // arbitrary-length keys); kept panic-free to honor the crate-wide
373            // clippy deny on unwrap/expect.
374            Err(_) => panic!("HMAC-SHA256 with a constant test secret cannot fail"),
375        };
376        mac.update(format!("v0:{ts}:").as_bytes());
377        mac.update(body);
378        hex::encode(mac.finalize().into_bytes())
379    }
380
381    /// GitHub's documented example vector
382    /// (<https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries>).
383    const GITHUB_SECRET: &str = "It's a Secret to Everybody";
384    const GITHUB_BODY: &[u8] = b"Hello, World!";
385    const GITHUB_SIGNATURE: &str =
386        "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
387
388    fn github_headers() -> Vec<(String, String)> {
389        vec![(
390            "X-Hub-Signature-256".to_string(),
391            GITHUB_SIGNATURE.to_string(),
392        )]
393    }
394
395    #[test]
396    fn verify_any_accepts_first_matching_secret() {
397        // First verify that verify() itself works.
398        let direct = super::verify(
399            Provider::GitHub,
400            &github_headers(),
401            GITHUB_BODY,
402            &Secret::new(GITHUB_SECRET),
403            Default::default(),
404        );
405        assert_eq!(direct, Ok(()), "direct verify: {direct:?}");
406
407        let secrets = [
408            Secret::new("wrong-key"),
409            Secret::new(GITHUB_SECRET),
410            Secret::new("another-wrong-key"),
411        ];
412        assert_eq!(
413            verify_any(
414                Provider::GitHub,
415                &github_headers(),
416                GITHUB_BODY,
417                &secrets,
418                Default::default(),
419            ),
420            Ok(())
421        );
422    }
423
424    #[test]
425    fn verify_any_accepts_single_secret() {
426        let secrets = [Secret::new(GITHUB_SECRET)];
427        assert_eq!(
428            verify_any(
429                Provider::GitHub,
430                &github_headers(),
431                GITHUB_BODY,
432                &secrets,
433                Default::default(),
434            ),
435            Ok(())
436        );
437    }
438
439    #[test]
440    fn verify_any_rejects_when_no_secret_matches() {
441        let secrets = [Secret::new("wrong-1"), Secret::new("wrong-2")];
442        assert_eq!(
443            verify_any(
444                Provider::GitHub,
445                &github_headers(),
446                GITHUB_BODY,
447                &secrets,
448                Default::default(),
449            ),
450            Err(VerifyError::SignatureMismatch)
451        );
452    }
453
454    #[test]
455    fn verify_any_rejects_empty_slice() {
456        let secrets: [Secret; 0] = [];
457        let headers: Vec<(String, String)> = github_headers().to_vec();
458        assert_eq!(
459            verify_any(
460                Provider::GitHub,
461                &headers,
462                GITHUB_BODY,
463                &secrets,
464                Default::default(),
465            ),
466            Err(VerifyError::SignatureMismatch)
467        );
468    }
469
470    #[test]
471    fn verify_any_fails_closed_on_malformed_input() {
472        // Missing header — error comes from parsing, not the secret check.
473        let secrets = [Secret::new(GITHUB_SECRET)];
474        let empty_headers: Vec<(String, String)> = vec![];
475        assert_eq!(
476            verify_any(
477                Provider::GitHub,
478                &empty_headers,
479                GITHUB_BODY,
480                &secrets,
481                Default::default(),
482            ),
483            Err(VerifyError::MissingHeader {
484                header: "X-Hub-Signature-256"
485            })
486        );
487    }
488
489    #[test]
490    fn verify_any_non_first_secret_matches() {
491        // Only the second key is correct; first is wrong.
492        let secrets = [Secret::new("bad"), Secret::new(GITHUB_SECRET)];
493        assert_eq!(
494            verify_any(
495                Provider::GitHub,
496                &github_headers(),
497                GITHUB_BODY,
498                &secrets,
499                Default::default(),
500            ),
501            Ok(())
502        );
503    }
504
505    #[test]
506    fn verify_any_returns_timestamp_tolerance_immediately_across_secrets() {
507        // spec.md §2.1 / verify_any docs: TimestampOutOfTolerance is
508        // deterministic and secret-independent, so it must be returned
509        // immediately rather than continuing the rotation search. Here the
510        // *last* secret is correct, but the timestamp is stale.
511        let slack_secret = "8f742231b10e8888abcd99yyyzzz85a5";
512        let slack_body = b"token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J";
513        let stale_ts = 1_531_420_618u64;
514        // Sign `v0:{ts}:{body}` with the secret (HMAC-SHA256, hex).
515        let sig = slack_signature(slack_secret, stale_ts, slack_body);
516        let sig_value = format!("v0={sig}");
517        let ts_value = stale_ts.to_string();
518        let headers = [
519            ("X-Slack-Signature", sig_value.as_str()),
520            ("X-Slack-Request-Timestamp", ts_value.as_str()),
521        ];
522
523        // Wall-clock "now" is irrelevant here; use a clock far in the future
524        // so the old timestamp is out of tolerance regardless of real time.
525        let options = clocked_at(stale_ts + 3600, Some(Duration::from_secs(300)));
526
527        // First confirm the single-secret direct call rejects on tolerance.
528        assert!(
529            matches!(
530                verify(
531                    Provider::Slack,
532                    &headers,
533                    slack_body,
534                    &Secret::new(slack_secret),
535                    options.clone(),
536                ),
537                Err(VerifyError::TimestampOutOfTolerance { .. })
538            ),
539            "direct verify must reject a stale timestamp"
540        );
541
542        // Even though the last secret is correct, verify_any must return the
543        // deterministic tolerance error, not Ok(()).
544        let secrets = [
545            Secret::new("wrong-key-1"),
546            Secret::new("wrong-key-2"),
547            Secret::new(slack_secret),
548        ];
549        assert!(matches!(
550            verify_any(Provider::Slack, &headers, slack_body, &secrets, options,),
551            Err(VerifyError::TimestampOutOfTolerance { .. })
552        ));
553    }
554
555    #[test]
556    fn verify_any_multiple_secrets_affect_only_matching_not_timestamp() {
557        // Sanity counterpart: with a *fresh* timestamp the last correct secret
558        // must verify Ok, proving the immediate tolerance return above is due
559        // to time, not to any interaction with the secret slice.
560        let slack_secret = "8f742231b10e8888abcd99yyyzzz85a5";
561        let slack_body = b"token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J";
562        let ts = 1_531_420_618u64;
563        let sig = slack_signature(slack_secret, ts, slack_body);
564        let sig_value = format!("v0={sig}");
565        let ts_value = ts.to_string();
566        let headers = [
567            ("X-Slack-Signature", sig_value.as_str()),
568            ("X-Slack-Request-Timestamp", ts_value.as_str()),
569        ];
570        let options = clocked_at(ts, None);
571
572        let secrets = [
573            Secret::new("wrong-key-1"),
574            Secret::new("wrong-key-2"),
575            Secret::new(slack_secret),
576        ];
577        assert_eq!(
578            verify_any(Provider::Slack, &headers, slack_body, &secrets, options),
579            Ok(())
580        );
581    }
582
583    #[test]
584    fn verify_any_all_wrong_secrets_with_fresh_timestamp_is_mismatch() {
585        // Guard against the two tests above accidentally passing because
586        // verify_any returned SignatureMismatch for the wrong reason: fresh
587        // timestamp but every key wrong must be a plain SignatureMismatch. This
588        // pins down that the mismatch branch is exercised with timestamps in
589        // tolerance, distinct from the tolerance path.
590        let slack_secret = "8f742231b10e8888abcd99yyyzzz85a5";
591        let slack_body = b"token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J";
592        let ts = 1_531_420_618u64;
593        let sig = slack_signature(slack_secret, ts, slack_body);
594        let sig_value = format!("v0={sig}");
595        let ts_value = ts.to_string();
596        let headers = [
597            ("X-Slack-Signature", sig_value.as_str()),
598            ("X-Slack-Request-Timestamp", ts_value.as_str()),
599        ];
600        let options = clocked_at(ts, Some(Duration::from_secs(300)));
601
602        let secrets = [Secret::new("wrong-1"), Secret::new("wrong-2")];
603        assert_eq!(
604            verify_any(Provider::Slack, &headers, slack_body, &secrets, options),
605            Err(VerifyError::SignatureMismatch)
606        );
607    }
608
609    #[test]
610    fn provider_display_names() {
611        use super::CustomScheme;
612        use crate::{Encoding, HashAlg};
613
614        assert_eq!(Provider::Stripe.to_string(), "Stripe");
615        assert_eq!(Provider::GitHub.to_string(), "GitHub");
616        assert_eq!(Provider::Shopify.to_string(), "Shopify");
617        assert_eq!(Provider::Slack.to_string(), "Slack");
618        assert_eq!(Provider::Square.to_string(), "Square");
619        assert_eq!(Provider::Twilio.to_string(), "Twilio");
620        assert_eq!(Provider::Discord.to_string(), "Discord");
621        assert_eq!(Provider::PayPal.to_string(), "PayPal");
622        assert_eq!(Provider::SendGrid.to_string(), "SendGrid");
623        assert_eq!(Provider::Linear.to_string(), "Linear");
624        assert_eq!(Provider::Zoom.to_string(), "Zoom");
625        assert_eq!(Provider::Dropbox.to_string(), "Dropbox");
626        assert_eq!(Provider::StandardWebhooks.to_string(), "StandardWebhooks");
627
628        let custom = Provider::Custom(CustomScheme {
629            hash: HashAlg::Sha256,
630            signature_header: "X-My-Sig",
631            timestamp_header: None,
632            encoding: Encoding::Hex,
633            prefix: None,
634            signed_string: |_h, b| b.to_vec(),
635        });
636        assert_eq!(custom.to_string(), "Custom(X-My-Sig)");
637    }
638}