Skip to main content

webhook_verify/
tower.rs

1//! Generic [`tower`] adapter: a [`tower_layer::Layer`] /
2//! [`tower_service::Service`] middleware that verifies inbound webhook
3//! signatures with [`crate::verify()`] before the request reaches your
4//! handler.
5//!
6//! Because axum routers are tower services, this layer also drops straight
7//! into `Router::layer(...)` — see the framework note below.
8//!
9//! # What the middleware guarantees
10//!
11//! - **Raw-body fidelity** (`spec.md` §4.2): the body is buffered *exactly*
12//!   as received off the wire (`http_body_util` collects the raw frame bytes)
13//!   and those bytes — and nothing else — go both to [`crate::verify()`] and
14//!   onward to the inner service. No JSON parsing or re-serialization happens
15//!   anywhere in between, so handlers can deserialize freely after
16//!   verification.
17//! - **Ambiguous duplicate headers rejected** (`spec.md` §4.4): the
18//!   [`crate::HeaderMap`] trait only sees first values, so this middleware
19//!   inspects the raw `http::HeaderMap` itself and rejects any request whose
20//!   scheme-relevant signature headers appear multiple times with *differing*
21//!   values (`400 Bad Request`) before any signature work. Identical repeats
22//!   are not ambiguous and verify normally against the first value.
23//! - **Fail closed**: every verification failure produces an empty-bodied
24//!   error response; the request never reaches the inner service.
25//!
26//! # Status codes
27//!
28//! | `VerifyError` class | Status |
29//! |---|---|
30//! | `MissingHeader`, `MalformedHeader`, `BadEncoding` (malformed request) | `400 Bad Request` |
31//! | `SignatureMismatch`, `TimestampOutOfTolerance` (auth signals) | `401 Unauthorized` |
32//! | `UnsupportedProvider`, `InvalidSecret`, `MissingContext` (operator misconfiguration) | `500 Internal Server Error` |
33//!
34//! Bodies are deliberately empty: distinguishing detail belongs in
35//! server-side logging keyed off the structured [`crate::VerifyError`], whose
36//! `Display`/`Debug` never carry secret material (`spec.md` §2.1).
37//!
38//! # Example
39//!
40//! ```rust
41//! use bytes::Bytes;
42//! use futures_executor::block_on;
43//! use http::{Request, Response};
44//! use http_body_util::Full;
45//! use tower::{Layer, Service, service_fn};
46//! use webhook_verify::tower::VerifyLayer;
47//! use webhook_verify::{Provider, Secret};
48//!
49//! // GitHub's documented example vector.
50//! const SIGNATURE: &str =
51//!     "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
52//!
53//! # fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
54//! let mut svc = VerifyLayer::new(Provider::GitHub, Secret::new("It's a Secret to Everybody"))
55//!     .layer(service_fn(|req: Request<Bytes>| async move {
56//!         Ok::<_, std::convert::Infallible>(Response::new(Full::new(Bytes::from_static(b"ok"))))
57//!     }));
58//!
59//! let request = Request::builder()
60//!     .header("X-Hub-Signature-256", SIGNATURE)
61//!     .body(Full::new(Bytes::from_static(b"Hello, World!")))?;
62//!
63//! let response = block_on(svc.call(request))?;
64//! assert_eq!(response.status(), 200);
65//! # Ok(())
66//! # }
67//! # run().unwrap_or_else(|error| panic!("example must be self-contained: {error}"));
68//! ```
69//!
70//! # Framework note (downstream body type)
71//!
72//! After buffering, the inner service receives the request body as `Bytes`
73//! by default. The type parameter picks another body type — anything that
74//! converts from [`Bytes`] — without retyping the middleware; for axum
75//! that is `axum::body::Body`, inferred automatically by `Router::layer`:
76//!
77//! ```ignore
78//! let app = Router::new()
79//!     .route("/webhooks/github", post(handler))
80//!     .layer(webhook_verify::tower::VerifyLayer::new(Provider::GitHub, secret));
81//! ```
82//!
83//! # Axum: verifying without the middleware
84//!
85//! If you call [`crate::verify()`] directly instead of using this layer,
86//! verify *before* any extractor consumes the request. Extractors run
87//! top-down and body-consuming ones (`Json`, `Bytes`, `String`) drain the
88//! request; once they have run, the original wire bytes are gone and any
89//! signature computed over re-serialized data will (correctly) fail. Capture
90//! the body first (`Bytes` as your first extractor), verify those exact
91//! bytes against an `http::HeaderMap` via the `http` feature, then
92//! deserialize from a copy. Prefer the layer: it makes this ordering
93//! impossible to get wrong.
94//!
95//! # Errors
96//!
97//! Transport-level failures while reading the request body (e.g. the client
98//! disconnected mid-stream) surface through the middleware's `Err` half,
99//! matching tower conventions — they are connection problems, not
100//! verification outcomes.
101//!
102//! [`tower`]: https://crates.io/crates/tower
103
104use std::{
105    error::Error,
106    fmt,
107    future::Future,
108    marker::PhantomData,
109    pin::Pin,
110    sync::Arc,
111    task::{Context, Poll},
112};
113
114use ::bytes::Bytes;
115use ::http::{Request, Response, StatusCode};
116use ::http_body_util::BodyExt;
117use ::tower_layer::Layer;
118use ::tower_service::Service;
119
120use crate::core::adapter_utils::rejection_status;
121use crate::{Provider, Secret, VerifyError, VerifyOptions, providers::signature_header_names};
122
123/// Boxed error type used by the middleware, per tower conventions.
124pub type BoxError = Box<dyn Error + Send + Sync>;
125
126/// Shared configuration handed to every service built from a [`VerifyLayer`].
127///
128/// `Secret` and `VerifyOptions` live behind `Arc`s so cloning the layer (or
129/// the resulting middleware, as tower runners routinely do) never copies key
130/// material around.
131#[derive(Clone)]
132struct Config {
133    provider: Provider,
134    secret: Arc<Secret>,
135    options: Arc<VerifyOptions>,
136}
137
138impl fmt::Debug for Config {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        // Provider name only; `Secret`'s own Debug is redacted and
141        // `VerifyOptions`' Debug omits URL/form values (spec.md §4.3).
142        f.debug_struct("Config")
143            .field("provider", &self.provider)
144            .field("secret", &self.secret)
145            .field("options", &self.options)
146            .finish()
147    }
148}
149
150/// A [`tower_layer::Layer`] verifying webhook signatures with
151/// [`crate::verify()`] before passing the request to the inner service.
152///
153/// See the [module docs](self) for the security contract, status-code table,
154/// and framework notes. The type parameter selects the body type the inner
155/// service receives after buffering (default [`Bytes`]); anything convertible
156/// from `Bytes` works, e.g. `axum::body::Body`.
157#[must_use]
158#[derive(Clone, Debug)]
159pub struct VerifyLayer<B = Bytes> {
160    config: Config,
161    _body: PhantomData<B>,
162}
163
164impl<B> VerifyLayer<B> {
165    /// Verifies `provider` signatures using the shared `secret`.
166    pub fn new(provider: Provider, secret: Secret) -> Self {
167        Self::with_options(provider, secret, VerifyOptions::default())
168    }
169
170    /// Like [`VerifyLayer::new`], with explicit [`VerifyOptions`] (timestamp
171    /// tolerance, injected clock, URL-scoped schemes such as Square/Twilio).
172    pub fn with_options(provider: Provider, secret: Secret, options: VerifyOptions) -> Self {
173        Self {
174            config: Config {
175                provider,
176                secret: Arc::new(secret),
177                options: Arc::new(options),
178            },
179            _body: PhantomData,
180        }
181    }
182}
183
184// `Layer::layer` takes `&self`, so the layer acts as its own factory: every
185// application clones the shared config rather than moving key material.
186impl<S, B> Layer<S> for VerifyLayer<B> {
187    type Service = VerifyMiddleware<S, B>;
188
189    fn layer(&self, inner: S) -> Self::Service {
190        VerifyMiddleware {
191            inner,
192            config: self.config.clone(),
193            _body: PhantomData,
194        }
195    }
196}
197
198/// The [`Service`] produced by [`VerifyLayer`]; see the [module docs](self).
199#[must_use]
200pub struct VerifyMiddleware<S, B = Bytes> {
201    inner: S,
202    config: Config,
203    _body: PhantomData<B>,
204}
205
206impl<S: Clone, B> Clone for VerifyMiddleware<S, B> {
207    fn clone(&self) -> Self {
208        Self {
209            inner: self.inner.clone(),
210            config: self.config.clone(),
211            _body: PhantomData,
212        }
213    }
214}
215
216impl<S: fmt::Debug, B> fmt::Debug for VerifyMiddleware<S, B> {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        f.debug_struct("VerifyMiddleware")
219            .field("inner", &self.inner)
220            .field("config", &self.config)
221            .finish()
222    }
223}
224
225/// Returns the name of the first header in `names` that occurs in `headers`
226/// more than once with *differing* values — the ambiguity `spec.md` §4.4
227/// requires rejecting — or `None` when none is ambiguous.
228///
229/// Static header-name constants always parse, so the parse-error arm is
230/// unreachable in practice and simply fails closed (reported as ambiguous).
231fn conflicting_signature_header(
232    headers: &::http::HeaderMap,
233    names: &[&'static str],
234) -> Option<&'static str> {
235    names.iter().copied().find(|name| {
236        let Ok(key) = ::http::header::HeaderName::from_bytes(name.as_bytes()) else {
237            return true;
238        };
239        let mut values = headers.get_all(&key).iter();
240        let Some(first) = values.next() else {
241            return false;
242        };
243        values.any(|value| value != first)
244    })
245}
246
247/// Empty-bodied rejection response; no error detail leaks over the wire.
248fn rejection_response<ResB: Default>(error: &VerifyError) -> Response<ResB> {
249    let mut response = Response::new(ResB::default());
250    // The status class is a hard-coded constant (400/401/500), so conversion
251    // cannot fail; the fallback still fails closed with 500 if it ever did.
252    *response.status_mut() =
253        StatusCode::from_u16(rejection_status(error)).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
254    response
255}
256
257impl<S, ReqB, ResB, OutB> Service<Request<ReqB>> for VerifyMiddleware<S, OutB>
258where
259    S: Service<Request<OutB>, Response = Response<ResB>> + Clone + Send + 'static,
260    S::Error: Into<BoxError>,
261    S::Future: Send + 'static,
262    ReqB: ::http_body::Body<Data = Bytes> + Send + 'static,
263    ReqB::Error: Into<BoxError>,
264    ResB: Default + Send + 'static,
265    OutB: From<Bytes> + Send + 'static,
266{
267    type Response = Response<ResB>;
268    type Error = BoxError;
269    type Future = Pin<Box<dyn Future<Output = Result<Response<ResB>, BoxError>> + Send>>;
270
271    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
272        self.inner.poll_ready(cx).map_err(Into::into)
273    }
274
275    fn call(&mut self, req: Request<ReqB>) -> Self::Future {
276        // Ambiguity check first: it needs no body bytes, so conflicting
277        // duplicates are rejected without buffering or signature work.
278        let names = signature_header_names(&self.config.provider);
279        if let Some(header) = conflicting_signature_header(req.headers(), &names) {
280            let response = rejection_response::<ResB>(&VerifyError::MalformedHeader {
281                header,
282                reason: "header present multiple times with different values",
283            });
284            return Box::pin(async { Ok(response) });
285        }
286
287        let mut inner = self.inner.clone();
288        let config = self.config.clone();
289
290        Box::pin(async move {
291            let (parts, body) = req.into_parts();
292
293            // Buffer the exact wire bytes once; these are both what gets
294            // verified and what the inner service receives (spec.md §4.2).
295            let raw_body = match BodyExt::collect(body).await {
296                Ok(collected) => collected.to_bytes(),
297                // Transport-level read failure (client disconnect, body
298                // decode error): a connection problem, not a verification
299                // outcome — surfaced per tower conventions.
300                Err(error) => return Err(error.into()),
301            };
302
303            if let Err(error) = crate::verify(
304                config.provider,
305                &parts.headers,
306                raw_body.as_ref(),
307                &config.secret,
308                (*config.options).clone(),
309            ) {
310                return Ok(rejection_response::<ResB>(&error));
311            }
312
313            let request = Request::from_parts(parts, OutB::from(raw_body));
314            inner.call(request).await.map_err(Into::into)
315        })
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    #[cfg(feature = "paypal")]
323    use crate::VerifyingKeyMaterial;
324    use crate::test_helpers::{FixedClock, clocked_at, epoch};
325    use ::http_body_util::Full;
326    use ::tower::ServiceExt;
327    use futures_executor::block_on;
328
329    /// GitHub's documented example vector
330    /// (<https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries>).
331    const GITHUB_SECRET: &str = "It's a Secret to Everybody";
332    const GITHUB_BODY: &[u8] = b"Hello, World!";
333    const GITHUB_SIGNATURE: &str =
334        "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
335
336    /// Slack's documented worked example
337    /// (<https://docs.slack.dev/authentication/verifying-requests-from-slack>),
338    /// same constants used in the provider's own tests.
339    const SLACK_SECRET: &str = "8f742231b10e8888abcd99yyyzzz85a5";
340    const SLACK_TIMESTAMP: u64 = 1_531_420_618;
341    const SLACK_BODY: &[u8] =
342        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";
343    const SLACK_SIGNATURE: &str =
344        "a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503";
345
346    type TestBody = Full<Bytes>;
347
348    /// Inner service echoing how many body bytes it saw, so tests assert the
349    /// buffered bytes survive the round trip byte-for-byte.
350    #[derive(Clone)]
351    struct EchoLen;
352
353    impl Service<Request<Bytes>> for EchoLen {
354        type Response = Response<TestBody>;
355        type Error = BoxError;
356        type Future = std::future::Ready<Result<Response<TestBody>, BoxError>>;
357
358        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
359            Poll::Ready(Ok(()))
360        }
361
362        fn call(&mut self, req: Request<Bytes>) -> Self::Future {
363            let len = req.body().len();
364            std::future::ready(Ok(Response::new(TestBody::new(Bytes::from(
365                len.to_string(),
366            )))))
367        }
368    }
369
370    fn github_service() -> VerifyMiddleware<EchoLen, Bytes> {
371        VerifyLayer::new(Provider::GitHub, Secret::new(GITHUB_SECRET)).layer(EchoLen)
372    }
373
374    fn github_request(body: &'static [u8]) -> Request<TestBody> {
375        Request::builder()
376            .header("X-Hub-Signature-256", GITHUB_SIGNATURE)
377            .body(TestBody::new(Bytes::from_static(body)))
378            .unwrap_or_else(|_| unreachable!("static parts build a valid request"))
379    }
380
381    // --- happy path ---------------------------------------------------------
382
383    #[test]
384    fn valid_signature_reaches_inner_service_with_exact_bytes() {
385        block_on(async {
386            let svc = github_service();
387            let response = svc
388                .oneshot(github_request(GITHUB_BODY))
389                .await
390                .unwrap_or_else(|error| panic!("verification should pass: {error}"));
391            assert_eq!(response.status(), StatusCode::OK);
392            // EchoLen reports how many raw bytes reached the inner service.
393            assert_eq!(
394                response.into_body().into_inner().unwrap_or_default(),
395                Bytes::from_static(b"13")
396            );
397        });
398    }
399
400    #[test]
401    fn empty_and_unicode_bodies_round_trip_byte_exactly() {
402        // Boundary bodies through the same buffered pipeline. Digests
403        // computed locally with GitHub's recipe:
404        // printf '<body>' | openssl dgst -sha256 -hmac <secret>
405        const EMPTY_SIG: &str =
406            "sha256=66a0c074deaa0f489ead6537e0d32f9a344b90bbeda705b6ed45ecd3b413fb40";
407        const UNICODE_BODY: &[u8] = "héllo, 🦀 world!".as_bytes();
408        const UNICODE_SIG: &str =
409            "sha256=815772f88bf8950c7457b57856f4b33ca9d07e7ef7a50646b067b4a613f735c4";
410
411        for (body, signature) in [
412            (&b""[..], EMPTY_SIG),
413            (UNICODE_BODY, UNICODE_SIG),
414            (GITHUB_BODY, GITHUB_SIGNATURE),
415        ] {
416            let request = Request::builder()
417                .header("X-Hub-Signature-256", signature)
418                .body(TestBody::new(Bytes::copy_from_slice(body)))
419                .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
420            let svc = github_service();
421            block_on(async {
422                let response = svc
423                    .oneshot(request)
424                    .await
425                    .unwrap_or_else(|error| panic!("{error}"));
426                assert_eq!(response.status(), StatusCode::OK);
427                assert_eq!(
428                    response.into_body().into_inner().unwrap_or_default(),
429                    Bytes::from(body.len().to_string())
430                );
431            });
432        }
433    }
434
435    // --- negative: tampered payload -----------------------------------------
436
437    #[test]
438    fn tampered_body_is_unauthorized_and_never_reaches_handler() {
439        let request = github_request(b"Hello, World?");
440        block_on(async {
441            let svc = github_service();
442            let response = svc
443                .oneshot(request)
444                .await
445                .unwrap_or_else(|error| panic!("middleware should respond, not error: {error}"));
446            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
447        });
448    }
449
450    // --- negative: malformed / ambiguous headers -----------------------------
451
452    #[test]
453    fn missing_signature_header_is_bad_request() {
454        let request = Request::builder()
455            .body(TestBody::new(Bytes::from_static(GITHUB_BODY)))
456            .unwrap_or_else(|_| unreachable!("no headers to misbuild"));
457        block_on(async {
458            let svc = github_service();
459            let response = svc
460                .oneshot(request)
461                .await
462                .unwrap_or_else(|error| panic!("{error}"));
463            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
464        });
465    }
466
467    #[test]
468    fn conflicting_duplicate_signature_headers_are_rejected() {
469        // Second value differs from the first: ambiguous under spec §4.4 even
470        // though each value alone would just fail verification normally.
471        let request = Request::builder()
472            .header("X-Hub-Signature-256", GITHUB_SIGNATURE)
473            .header(
474                "x-hub-signature-256",
475                "sha256=0000000000000000000000000000000000000000000000000000000000000000",
476            )
477            .body(TestBody::new(Bytes::from_static(GITHUB_BODY)))
478            .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
479        block_on(async {
480            let svc = github_service();
481            let response = svc
482                .oneshot(request)
483                .await
484                .unwrap_or_else(|error| panic!("{error}"));
485            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
486        });
487    }
488
489    #[test]
490    fn identical_duplicate_signature_headers_still_verify() {
491        let request = Request::builder()
492            .header("X-Hub-Signature-256", GITHUB_SIGNATURE)
493            .header("x-hub-signature-256", GITHUB_SIGNATURE)
494            .body(TestBody::new(Bytes::from_static(GITHUB_BODY)))
495            .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
496        block_on(async {
497            let svc = github_service();
498            let response = svc
499                .oneshot(request)
500                .await
501                .unwrap_or_else(|error| panic!("{error}"));
502            assert_eq!(response.status(), StatusCode::OK);
503        });
504    }
505
506    #[test]
507    fn conflicting_duplicate_timestamp_header_is_rejected_for_slack() {
508        // Valid-shaped signature plus two conflicting timestamps: ambiguity
509        // lives in the timestamp header, not the signature header itself.
510        let request = Request::builder()
511            .header("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}"))
512            .header("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string())
513            .header("x-slack-request-timestamp", "1700000001")
514            .body(TestBody::new(Bytes::from_static(SLACK_BODY)))
515            .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
516
517        let svc = VerifyLayer::new(Provider::Slack, Secret::new(SLACK_SECRET)).layer(EchoLen);
518        block_on(async {
519            let response = svc
520                .oneshot(request)
521                .await
522                .unwrap_or_else(|error| panic!("{error}"));
523            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
524        });
525    }
526
527    // --- replay protection through the adapter -------------------------------
528
529    #[test]
530    fn stale_timestamp_is_unauthorized_through_adapter() {
531        let request = Request::builder()
532            .header("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}"))
533            .header("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string())
534            .body(TestBody::new(Bytes::from_static(SLACK_BODY)))
535            .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
536
537        // "Now" ten minutes after signing: outside the default 300s window.
538        let late = epoch(SLACK_TIMESTAMP + 600);
539        let svc = VerifyLayer::with_options(
540            Provider::Slack,
541            Secret::new(SLACK_SECRET),
542            crate::VerifyOptions {
543                clock: Some(Arc::new(FixedClock(late))),
544                ..crate::VerifyOptions::default()
545            },
546        )
547        .layer(EchoLen);
548
549        block_on(async {
550            let response = svc
551                .oneshot(request)
552                .await
553                .unwrap_or_else(|error| panic!("{error}"));
554            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
555        });
556    }
557
558    // --- custom schemes and unsupported providers ----------------------------
559
560    #[test]
561    fn custom_scheme_headers_are_dup_checked_too() {
562        // HMAC-SHA256 hex of the body with key "k":
563        // printf 'Hello, World!' | openssl dgst -sha256 -hmac "k"
564        const DIGEST: &str = "11316937114e6970aa59bd5326a6f38dd525f4ade64670e402bff41e2f7c4071";
565        let scheme = crate::CustomScheme {
566            hash: crate::HashAlg::Sha256,
567            signature_header: "X-My-Sig",
568            timestamp_header: None,
569            encoding: crate::Encoding::Hex,
570            prefix: Some("sha256="),
571            signed_string: |_headers, body| body.to_vec(),
572        };
573
574        // Conflicting duplicates of the custom scheme's signature header are
575        // caught before any verification work.
576        let ambiguous = Request::builder()
577            .header("X-My-Sig", format!("sha256={DIGEST}"))
578            .header("x-my-sig", "sha256=00")
579            .body(TestBody::new(Bytes::from_static(GITHUB_BODY)))
580            .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
581        let svc = VerifyLayer::new(Provider::Custom(scheme), Secret::new("k")).layer(EchoLen);
582        block_on(async {
583            let response = svc
584                .oneshot(ambiguous)
585                .await
586                .unwrap_or_else(|error| panic!("{error}"));
587            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
588        });
589
590        // A single well-formed value verifies end to end.
591        let good = Request::builder()
592            .header("X-My-Sig", format!("sha256={DIGEST}"))
593            .body(TestBody::new(Bytes::from_static(GITHUB_BODY)))
594            .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
595        block_on(async {
596            let svc = VerifyLayer::new(Provider::Custom(scheme), Secret::new("k")).layer(EchoLen);
597            let response = svc
598                .oneshot(good)
599                .await
600                .unwrap_or_else(|error| panic!("{error}"));
601            assert_eq!(response.status(), StatusCode::OK);
602        });
603    }
604
605    #[test]
606    fn unsupported_provider_maps_to_internal_server_error() {
607        // PayPal stays "unsupported" only when the `paypal` feature is off;
608        // see the feature-gated variant below for the implemented path.
609        #[cfg(not(feature = "paypal"))]
610        {
611            let svc = VerifyLayer::new(Provider::PayPal, Secret::new("unused")).layer(EchoLen);
612            let request = Request::builder()
613                .body(TestBody::new(Bytes::from_static(b"{}")))
614                .unwrap_or_else(|_| unreachable!("no headers to misbuild"));
615            block_on(async {
616                let response = svc
617                    .oneshot(request)
618                    .await
619                    .unwrap_or_else(|error| panic!("{error}"));
620                assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
621            });
622        }
623        #[cfg(feature = "paypal")]
624        {
625            let cert = include_bytes!("../tests/data/paypal_test_cert.pem");
626            // Clock pinned to the vector's transmission time (replay window).
627            let options = clocked_at(1_715_836_763, None)
628                .with_webhook_id("0NH55953DH663215D")
629                .with_verifying_material(VerifyingKeyMaterial::X509Certificate(cert.to_vec()));
630            let svc = VerifyLayer::with_options(Provider::PayPal, Secret::new("unused"), options)
631                .layer(EchoLen);
632            let body = include_bytes!("../tests/data/paypal_docs_body.json");
633            let request = Request::builder()
634                .header(
635                    "PayPal-Transmission-Id",
636                    "db49fb10-1343-11ef-ac58-e32457403f67",
637                )
638                .header("PayPal-Transmission-Time", "2024-05-16T05:19:23Z")
639                .header(
640                    "PayPal-Transmission-Sig",
641                    "aGYe/s6lwrASh2zyTRIAz8Edo705ezMKekirejT08ev3VXdWAkq4JWADiNPUGelx5qrEKxC7mPIHmAwQ5hOT6unhY9n33M/DbXTKGsuITPdXRA7qYVmc2wsIp68BpzB6pC6+5vt/YLQvflsrwrutGa0KyZc5FinuYNN8pTNomv4uiygasWqfnDyKViKQPNZecowag6tY/9pj7+bgBu/joBpYUq0+cQxfGqNnlvywBJ7HCOf4edeTIvM/c1CvvAHGtNTU54kLjWGue640twn6iXPL8tnaABZ8Fr9m0z87v8oY0vBobERV0Yu8thUToKhvQEFF26Rckqy07VVddg1CmA==",
642                )
643                .header("PayPal-Cert-Url", "https://example.invalid/cert-url")
644                .header("PayPal-Auth-Algo", "SHA256withRSA")
645                .body(TestBody::new(Bytes::from_static(body)))
646                .unwrap_or_else(|_| unreachable!("static parts build a valid request"));
647            block_on(async {
648                let response = svc
649                    .oneshot(request)
650                    .await
651                    .unwrap_or_else(|error| panic!("{error}"));
652                assert_eq!(response.status(), StatusCode::OK);
653            });
654        }
655    }
656
657    // --- unit-level checks ----------------------------------------------------
658
659    #[test]
660    fn identical_opaque_duplicate_values_are_not_ambiguous_but_fail_verification() {
661        // Two identical opaque-byte values are not ambiguous per §4.4 (same
662        // value); downstream lookup reports them absent and fails closed.
663        let mut headers = ::http::HeaderMap::new();
664        let value = ::http::HeaderValue::from_bytes(&[0xFF])
665            .unwrap_or_else(|_| unreachable!("0xFF is permitted"));
666        headers.append("X-Hub-Signature-256", value.clone());
667        headers.append("X-Hub-Signature-256", value);
668        assert!(conflicting_signature_header(&headers, &["X-Hub-Signature-256"]).is_none());
669    }
670
671    #[test]
672    fn unparseable_header_name_fails_closed_as_ambiguous() {
673        // A header-name string the http crate refuses to parse (embedded
674        // whitespace) must fail closed as "ambiguous" per §4.4 — the parse-
675        // error arm exists precisely so attacker-supplied garbage can never
676        // turn into a permissive lookup.
677        let headers = ::http::HeaderMap::new();
678        assert_eq!(
679            conflicting_signature_header(&headers, &["x-hub-signature-256 invalid"]),
680            Some("x-hub-signature-256 invalid")
681        );
682    }
683
684    #[test]
685    fn debug_output_never_contains_secrets() {
686        let layer = VerifyLayer::<Bytes>::with_options(
687            Provider::GitHub,
688            Secret::new("super-secret-hmac-key"),
689            crate::VerifyOptions::default().with_request_url("https://internal.example/hook"),
690        );
691        let debug = format!("{layer:?}");
692        assert!(!debug.contains("super-secret-hmac-key"));
693        assert!(!debug.contains("internal.example"));
694    }
695}