Skip to main content

webhook_verify/core/
error.rs

1//! Structured verification errors.
2//!
3//! Design rules (see `spec.md` §2.1): errors never contain the secret, the raw
4//! body, or a computed signature. They may carry header *names*, static reason
5//! strings, and numeric skew values.
6
7use core::fmt;
8use core::time::Duration;
9
10/// Everything that can go wrong while verifying a webhook signature.
11///
12/// `MissingHeader` / `MalformedHeader` / `BadEncoding` indicate malformed
13/// requests; `SignatureMismatch` indicates an active-attack signal (or an
14/// out-of-band misconfiguration). Callers that log differently per class can
15/// match on the variants — but both classes are "reject the request"
16/// outcomes. Never treat a malformed header as "skip verification".
17#[must_use]
18#[non_exhaustive]
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum VerifyError {
21    /// A required signature-related header was absent.
22    MissingHeader {
23        /// Name of the missing header.
24        header: &'static str,
25    },
26    /// A required header was present but could not be parsed into the shape
27    /// the provider's scheme requires (wrong prefix, empty value, ...).
28    MalformedHeader {
29        /// Name of the malformed header.
30        header: &'static str,
31        /// Static description of what was wrong with its shape.
32        reason: &'static str,
33    },
34    /// A value that must decode in the provider's encoding (hex, base64)
35    /// failed to decode, or decoded to the wrong length.
36    BadEncoding {
37        /// Static description of the decoding failure.
38        reason: &'static str,
39    },
40    /// The signature did not match. Returned identically regardless of how
41    /// close the provided signature was to the expected one.
42    SignatureMismatch,
43    /// The signed timestamp is further from "now" than [`VerifyOptions::
44    /// max_age`] allows; skew is how far outside the window it fell.
45    TimestampOutOfTolerance {
46        /// How far outside the tolerance window the timestamp was.
47        skew: Duration,
48        /// The configured maximum age.
49        max_age: Duration,
50    },
51    /// The selected [`crate::Provider`] exists but has no verification
52    /// implementation yet (fail-closed stub for providers not shipped).
53    UnsupportedProvider,
54    /// The provided secret is not usable for this provider's scheme
55    /// (e.g. wrong format for a hex- or base64-encoded key).
56    InvalidSecret {
57        /// Static description of why the secret was rejected.
58        reason: &'static str,
59    },
60    /// Verification for this provider requires caller-supplied request
61    /// context (such as Square's notification URL, via
62    /// [`crate::VerifyOptions::request_url`]) that was not provided. This is
63    /// an operator misconfiguration, not an attack signal — but the request
64    /// is still rejected: fail closed.
65    MissingContext {
66        /// Static description of what context was missing.
67        reason: &'static str,
68    },
69}
70
71impl fmt::Display for VerifyError {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            VerifyError::MissingHeader { header } => write!(f, "missing header `{header}`"),
75            VerifyError::MalformedHeader { header, reason } => {
76                write!(f, "malformed header `{header}`: {reason}")
77            }
78            VerifyError::BadEncoding { reason } => write!(f, "bad encoding: {reason}"),
79            VerifyError::SignatureMismatch => write!(f, "signature mismatch"),
80            VerifyError::TimestampOutOfTolerance { skew, max_age } => write!(
81                f,
82                "timestamp out of tolerance: {}s outside the allowed {}s window",
83                skew.as_secs(),
84                max_age.as_secs()
85            ),
86            VerifyError::UnsupportedProvider => write!(f, "provider not implemented yet"),
87            VerifyError::InvalidSecret { reason } => write!(f, "invalid secret: {reason}"),
88            VerifyError::MissingContext { reason } => {
89                write!(f, "missing verification context: {reason}")
90            }
91        }
92    }
93}
94
95#[cfg(feature = "std")]
96impl std::error::Error for VerifyError {}
97
98#[cfg(test)]
99mod tests {
100    use super::VerifyError;
101
102    #[test]
103    fn display_never_contains_secret_or_signature_material() {
104        // Header names and static reasons only; nothing attacker- or
105        // operator-supplied beyond counts/durations.
106        let e = VerifyError::MalformedHeader {
107            header: "X-Hub-Signature-256",
108            reason: "empty",
109        };
110        assert_eq!(
111            e.to_string(),
112            "malformed header `X-Hub-Signature-256`: empty"
113        );
114    }
115}