Skip to main content

webhook_verify/core/
options.rs

1//! Verification options: timestamp tolerance, clock injection, and asymmetric
2//! verification material for public-key providers.
3
4use alloc::string::String;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7use core::fmt;
8use core::time::Duration;
9#[cfg(feature = "std")]
10use std::time::SystemTime;
11
12/// Source of "now", injectable so replay-protection tests are deterministic.
13///
14/// Returns unix seconds (the number of whole seconds since the Unix epoch);
15/// this keeps the crate `no_std + alloc` compatible (`spec.md` §1) — there is
16/// no wall clock in the no_std ecosystem, so callers on such targets supply
17/// their own implementation (e.g. from a platform RTC or NTP-synced counter).
18///
19/// Only providers whose scheme signs a timestamp use a clock; for others
20/// (GitHub, Shopify) no `Clock` is consulted.
21pub trait Clock: Send + Sync {
22    /// The current time as unix seconds.
23    #[must_use]
24    fn now(&self) -> u64;
25}
26
27/// The default [`Clock`]: real wall-clock time. Only available under the
28/// `std` feature, which is on by default.
29#[cfg(feature = "std")]
30#[derive(Debug, Clone, Copy, Default)]
31pub struct SystemClock;
32
33#[cfg(feature = "std")]
34impl Clock for SystemClock {
35    fn now(&self) -> u64 {
36        SystemTime::now()
37            .duration_since(SystemTime::UNIX_EPOCH)
38            .unwrap_or_default()
39            .as_secs()
40    }
41}
42
43/// Caller-supplied asymmetric verification material (`spec.md` §7).
44///
45/// Providers that verify against a configured public key or certificate
46/// (currently SendGrid and PayPal) take their key material here
47/// rather than in a [`Secret`](crate::Secret), because unlike the shared
48/// symmetric schemes the signing key is never a private value this crate
49/// holds — it is the provider's own *public* key. This crate **never** fetches
50/// key material over the network (`spec.md` §1); the caller supplies bytes
51/// already vetted (allow-listed certificate URL, checked key, etc.).
52#[must_use]
53#[non_exhaustive]
54#[derive(Clone, PartialEq, Eq)]
55pub enum VerifyingKeyMaterial {
56    /// DER- or PEM-encoded X.509 certificate (PayPal scheme). Only the embedded
57    /// public key is used; this crate performs no chain validation, so callers
58    /// needing chain/pin enforcement supply an already-validated certificate.
59    X509Certificate(Vec<u8>),
60    /// DER bytes of an ECDSA P-256 `SubjectPublicKeyInfo` public key (SendGrid
61    /// scheme), decoded by the caller from the provider's published base64
62    /// form (the dashboard "Verification Key").
63    EcdsaP256PublicKey(Vec<u8>),
64}
65
66impl fmt::Debug for VerifyingKeyMaterial {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        // Redact key/certificate bytes: consistent with the crate-wide rule
69        // that no secret-bearing material appears in `Debug` output. The
70        // variant name and byte length are enough to diagnose configuration.
71        match self {
72            VerifyingKeyMaterial::X509Certificate(bytes) => f
73                .debug_tuple("X509Certificate")
74                .field(&format_args!("<{} bytes>", bytes.len()))
75                .finish(),
76            VerifyingKeyMaterial::EcdsaP256PublicKey(bytes) => f
77                .debug_tuple("EcdsaP256PublicKey")
78                .field(&format_args!("<{} bytes>", bytes.len()))
79                .finish(),
80        }
81    }
82}
83
84/// Tuning knobs for [`crate::verify()`].
85///
86/// `#[non_exhaustive]`: new knobs are expected to arrive, and adding a field
87/// must never break downstream callers. Outside this crate the fields are
88/// therefore configured only through [`Default`] and the `with_*` builder
89/// methods — struct-literal construction is intentionally unavailable.
90///
91/// ```
92/// use std::time::Duration;
93/// use webhook_verify::VerifyOptions;
94///
95/// let opts = VerifyOptions::default().with_max_age(Some(Duration::from_secs(600)));
96/// assert_eq!(opts.max_age, Some(Duration::from_secs(600)));
97/// ```
98#[must_use]
99#[non_exhaustive]
100#[derive(Clone)]
101pub struct VerifyOptions {
102    /// Maximum allowed age between a signed timestamp and "now", for providers
103    /// whose scheme includes a timestamp. `None` disables the check (not
104    /// recommended). Default: 300 seconds, matching Stripe's and Slack's own
105    /// SDK defaults.
106    ///
107    /// Providers that do not sign timestamps document explicitly that this
108    /// option has no effect on them (see `spec.md` §3).
109    pub max_age: Option<Duration>,
110    /// Clock used for "now". `None` means real system time. Injectable for
111    /// deterministic tests of timestamp-based providers.
112    pub clock: Option<Arc<dyn Clock>>,
113    /// Full URL of the receiving endpoint, required by providers whose
114    /// signature incorporates it (currently Square, whose scheme signs the
115    /// notification URL followed by the raw body, and Twilio, which signs the
116    /// full request URL). The value must match the URL configured with the
117    /// provider **exactly** — a differing trailing slash or scheme makes every
118    /// signature fail. Providers whose scheme does not sign the URL document
119    /// that this option has no effect on them.
120    ///
121    /// Supplying the configured constant from the provider dashboard is the
122    /// intended use; reconstructing the URL from request headers behind a
123    /// proxy is a common source of verification failures.
124    pub request_url: Option<String>,
125    /// Parsed `application/x-www-form-urlencoded` fields, required by Twilio:
126    /// its signature covers the request URL concatenated with the sorted
127    /// form-field names/values, not the raw body. Pass **every** field as
128    /// received — Twilio's own docs warn against verifying against a hardcoded
129    /// subset, since providers may add parameters without notice. Sorting is
130    /// applied here (it is part of the signing scheme), so callers pass fields
131    /// in any order. A duplicate field name keeps its received relative order.
132    ///
133    /// An explicitly empty list is meaningful (Twilio's JSON-body variant signs
134    /// the URL alone); omitting the option entirely fails closed with
135    /// [`crate::VerifyError::MissingContext`] so a caller that forgot to parse
136    /// the body cannot be confused with an attacker-supplied input.
137    pub form_params: Option<Vec<(String, String)>>,
138    /// Verification material for providers whose scheme checks a signature
139    /// against a configured public key/certificate rather than a shared secret
140    /// (currently SendGrid and PayPal). See [`VerifyingKeyMaterial`].
141    ///
142    /// Required-but-absent fails closed with [`crate::VerifyError::MissingContext`]
143    /// (caller misconfiguration, mirroring Square/Twilio's context options);
144    /// malformed material fails with [`crate::VerifyError::InvalidSecret`].
145    ///
146    /// This crate never fetches key material itself (`spec.md` §7): the caller
147    /// supplies bytes that were already obtained and vetted out-of-band.
148    pub verifying_material: Option<VerifyingKeyMaterial>,
149    /// PayPal's webhook ID, required by PayPal's signed-string construction
150    /// (`spec.md` §3). It is *not* a request header or body field — it is the
151    /// ID of the webhook subscription (shown in the PayPal Developer Portal
152    /// for the listener URL) and must be supplied by the caller, mirroring
153    /// Square/Twilio's URL context.
154    ///
155    /// Required-but-absent for `Provider::PayPal` fails closed with
156    /// [`crate::VerifyError::MissingContext`]; an explicitly empty value is
157    /// treated the same way, so operator misconfiguration is never surfaced
158    /// as an attack-looking signature mismatch. Providers whose scheme does
159    /// not sign a webhook ID document that this option has no effect on them.
160    pub webhook_id: Option<String>,
161}
162
163impl Default for VerifyOptions {
164    fn default() -> Self {
165        Self {
166            max_age: Some(Duration::from_secs(300)),
167            clock: None,
168            request_url: None,
169            form_params: None,
170            verifying_material: None,
171            webhook_id: None,
172        }
173    }
174}
175
176impl VerifyOptions {
177    /// Sets [`VerifyOptions::request_url`], for URL-scoped schemes.
178    pub fn with_request_url(mut self, url: impl Into<String>) -> Self {
179        self.request_url = Some(url.into());
180        self
181    }
182
183    /// Sets [`VerifyOptions::form_params`], for schemes that sign parsed form
184    /// fields (currently Twilio). Order does not matter; fields are sorted
185    /// into signing order during verification of Twilio's signed string.
186    pub fn with_form_params<I, K, V>(mut self, params: I) -> Self
187    where
188        I: IntoIterator<Item = (K, V)>,
189        K: Into<String>,
190        V: Into<String>,
191    {
192        self.form_params = Some(
193            params
194                .into_iter()
195                .map(|(k, v)| (k.into(), v.into()))
196                .collect(),
197        );
198        self
199    }
200
201    /// Sets [`VerifyOptions::max_age`], the maximum allowed clock skew for
202    /// providers whose scheme signs a timestamp. `None` disables the check
203    /// (not recommended); the default is `Some(Duration::from_secs(300))`.
204    ///
205    /// Providers that do not sign timestamps document explicitly that this
206    /// option has no effect on them (see `spec.md` §3).
207    pub fn with_max_age(mut self, max_age: Option<Duration>) -> Self {
208        self.max_age = max_age;
209        self
210    }
211
212    /// Sets [`VerifyOptions::clock`], the source of "now" used for replay
213    /// protection. `None` uses real system time. Injectable for deterministic
214    /// tests of timestamp-based providers.
215    pub fn with_clock(mut self, clock: Option<Arc<dyn Clock>>) -> Self {
216        self.clock = clock;
217        self
218    }
219
220    /// Sets [`VerifyOptions::verifying_material`], the asymmetric public-key
221    /// /certificate material required by public-key schemes (currently
222    /// SendGrid's ECDSA P-256 key and PayPal's X.509 certificate).
223    pub fn with_verifying_material(mut self, material: VerifyingKeyMaterial) -> Self {
224        self.verifying_material = Some(material);
225        self
226    }
227
228    /// Sets [`VerifyOptions::webhook_id`], PayPal's webhook-subscription ID,
229    /// required by PayPal's signed-string construction (see the field docs).
230    pub fn with_webhook_id(mut self, webhook_id: impl Into<String>) -> Self {
231        self.webhook_id = Some(webhook_id.into());
232        self
233    }
234
235    /// Resolves "now" in unix seconds from the injected clock, falling back to
236    /// the real wall clock under `std`.
237    #[must_use]
238    pub fn now(&self) -> u64 {
239        match &self.clock {
240            Some(clock) => clock.now(),
241            #[cfg(feature = "std")]
242            None => SystemClock.now(),
243            #[cfg(not(feature = "std"))]
244            None => 0,
245        }
246    }
247}
248
249impl fmt::Debug for VerifyOptions {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        f.debug_struct("VerifyOptions")
252            .field("max_age", &self.max_age)
253            .field("clock", &self.clock.as_ref().map(|_| "<injected>"))
254            .field("request_url_set", &self.request_url.is_some())
255            .field(
256                "form_params_count",
257                &self.form_params.as_ref().map(|p| p.len()),
258            )
259            // VerifyingKeyMaterial has its own redacted Debug (variant name +
260            // byte length only; never the key/certificate bytes).
261            .field("verifying_material", &self.verifying_material)
262            // The webhook ID is not secret, but Debug stays minimal and
263            // presence-only, like request_url.
264            .field("webhook_id_set", &self.webhook_id.is_some())
265            .finish()
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use std::sync::Arc;
272    use std::time::Duration;
273
274    use super::{VerifyOptions, VerifyingKeyMaterial};
275    use crate::test_helpers::{FixedClock, epoch};
276
277    #[test]
278    fn default_is_five_minutes_without_injected_clock() {
279        let opts = VerifyOptions::default();
280        assert_eq!(opts.max_age, Some(Duration::from_secs(300)));
281        assert!(opts.clock.is_none());
282    }
283
284    #[test]
285    fn injected_clock_is_used_for_now() {
286        let fixed = FixedClock(epoch(1_700_000_000));
287        let opts = VerifyOptions {
288            max_age: Some(Duration::from_secs(300)),
289            clock: Some(Arc::new(FixedClock(epoch(1_700_000_000)))),
290            request_url: None,
291            form_params: None,
292            verifying_material: None,
293            webhook_id: None,
294        };
295        assert_eq!(opts.now(), fixed.0);
296    }
297
298    #[test]
299    fn builder_sets_request_url() {
300        let opts = VerifyOptions::default().with_request_url("https://example.com/webhook");
301        assert_eq!(
302            opts.request_url.as_deref(),
303            Some("https://example.com/webhook")
304        );
305    }
306
307    #[test]
308    fn debug_does_not_print_request_url_value() {
309        let opts = VerifyOptions::default().with_request_url("https://internal.example/hook");
310        assert!(!format!("{opts:?}").contains("internal.example"));
311    }
312
313    #[test]
314    fn builder_sets_verifying_material() {
315        let key = b"\x30\x59\x13".to_vec();
316        let opts = VerifyOptions::default()
317            .with_verifying_material(VerifyingKeyMaterial::EcdsaP256PublicKey(key.clone()));
318        assert_eq!(
319            opts.verifying_material,
320            Some(VerifyingKeyMaterial::EcdsaP256PublicKey(key))
321        );
322        assert!(VerifyOptions::default().verifying_material.is_none());
323    }
324
325    #[test]
326    fn builder_sets_webhook_id() {
327        let opts = VerifyOptions::default().with_webhook_id("0NH55953DH663215D");
328        assert_eq!(opts.webhook_id.as_deref(), Some("0NH55953DH663215D"));
329        assert!(VerifyOptions::default().webhook_id.is_none());
330    }
331
332    #[test]
333    fn debug_redacts_verifying_material_bytes() {
334        // Key/certificate bytes must not leak through Debug — only the variant
335        // name and byte length are shown.
336        let opts = VerifyOptions::default()
337            .with_verifying_material(VerifyingKeyMaterial::EcdsaP256PublicKey(vec![0xde, 0xad]));
338        let debug = format!("{opts:?}");
339        assert!(!debug.contains("222")); // 0xde, 0xad decimal concatenated
340        assert!(debug.contains("<2 bytes>"));
341    }
342
343    #[test]
344    fn builder_sets_form_params_in_any_order() {
345        let opts = VerifyOptions::default()
346            .with_request_url("https://example.com/myapp")
347            .with_form_params([("Digits", "1234"), ("CallSid", "CA123")]);
348        assert_eq!(
349            opts.form_params,
350            Some(vec![
351                ("Digits".to_string(), "1234".to_string()),
352                ("CallSid".to_string(), "CA123".to_string())
353            ])
354        );
355    }
356
357    #[test]
358    fn debug_does_not_print_form_param_values() {
359        // Form fields are attacker-controlled request content; like the URL,
360        // their values must not leak through `Debug` (only the count does).
361        let opts = VerifyOptions::default().with_form_params([("Body", "s3cr3t-message")]);
362        let debug = format!("{opts:?}");
363        assert!(!debug.contains("s3cr3t-message"));
364        assert!(debug.contains("form_params_count: Some(1)"));
365    }
366
367    #[test]
368    fn builder_sets_max_age() {
369        let opts = VerifyOptions::default().with_max_age(Some(Duration::from_secs(600)));
370        assert_eq!(opts.max_age, Some(Duration::from_secs(600)));
371    }
372
373    #[test]
374    fn builder_disables_max_age() {
375        let opts = VerifyOptions::default().with_max_age(None);
376        assert!(opts.max_age.is_none());
377    }
378
379    #[test]
380    fn builder_sets_clock() {
381        let fixed = FixedClock(epoch(1_700_000_000));
382        let opts =
383            VerifyOptions::default().with_clock(Some(Arc::new(FixedClock(epoch(1_700_000_000)))));
384        assert_eq!(opts.now(), fixed.0);
385    }
386
387    #[test]
388    fn builder_disables_clock() {
389        // Start with an injected clock, then clear it.
390        let fixed = epoch(1_700_000_000);
391        let opts = VerifyOptions::default()
392            .with_clock(Some(Arc::new(FixedClock(fixed))))
393            .with_clock(None);
394        // With no clock, `now()` falls back to system time — just verify it
395        // doesn't panic and the clock field is None.
396        assert!(opts.clock.is_none());
397        let _ = opts.now();
398    }
399}