Skip to main content

webhook_verify/
actix.rs

1//! [`actix-web`] 4 adapter: a [`FromRequest`] extractor that verifies inbound
2//! webhook signatures with [`crate::verify()`] and yields the exact raw body
3//! bytes on success.
4//!
5//! actix-web 4 is built on `actix-http` 3, which uses the `http` **0.2** types
6//! internally. It therefore cannot reuse this crate's `http` 1.x `HeaderMap`
7//! impl; this module provides its own bridge ([`crate::HeaderMap`] for
8//! actix's header map) plus the extractor below.
9//!
10//! # Why an extractor and not a guard
11//!
12//! Guards run during routing, before any body bytes are read — but signature
13//! verification *requires* the raw body (`spec.md` §4.2), so a guard cannot
14//! perform it. The idiomatic actix-web equivalent is a body extractor: it runs
15//! during handler-argument extraction (after routing, before your handler
16//! logic) and consumes the payload itself.
17//!
18//! # What the extractor guarantees
19//!
20//! - **Raw-body fidelity** (`spec.md` §4.2): the body is buffered exactly as
21//!   received off the wire and those bytes — nothing else — are both verified
22//!   and handed to the handler as [`VerifiedBody`]. No JSON parsing or
23//!   re-serialization happens in between. Do not also take `web::Json<T>` in
24//!   the same handler: extractors run left-to-right and `Json` would consume
25//!   (and re-parse) the body first. Take [`VerifiedBody`] alone and parse from
26//!   its exact bytes yourself if you need structured data.
27//! - **Ambiguous duplicate headers rejected** (`spec.md` §4.4): the
28//!   [`crate::HeaderMap`] trait only sees first values, so the extractor
29//!   inspects the raw actix header map and rejects any request whose
30//!   scheme-relevant signature headers appear multiple times with *differing*
31//!   values (`400 Bad Request`) before any signature work. Identical repeats
32//!   are not ambiguous and verify normally against the first value.
33//! - **Fail closed**: every failure — including a missing
34//!   [`WebhookConfig`] — produces an error response; handler logic never
35//!   sees unverified bytes.
36//!
37//! # Status codes
38//!
39//! Identical to the tower adapter:
40//!
41//! | `VerifyError` class | Status |
42//! |---|---|
43//! | `MissingHeader`, `MalformedHeader`, `BadEncoding` (malformed request) | `400 Bad Request` |
44//! | `SignatureMismatch`, `TimestampOutOfTolerance` (auth signals) | `401 Unauthorized` |
45//! | `UnsupportedProvider`, `InvalidSecret`, `MissingContext` (operator misconfiguration) | `500 Internal Server Error` |
46//!
47//! Bodies are deliberately empty: distinguishing detail belongs in
48//! server-side logging keyed off the structured [`crate::VerifyError`], whose
49//! `Display`/`Debug` never carry secret material (`spec.md` §2.1). A failure
50//! to read the body at transport level (e.g. client disconnect mid-stream)
51//! surfaces as `400 Bad Request` — an incomplete request, never a
52//! verification outcome.
53//!
54//! # Example
55//!
56//! ```no_run
57//! use actix_web::{App, HttpResponse, web};
58//! use webhook_verify::actix::{VerifiedBody, WebhookConfig};
59//! use webhook_verify::{Provider, Secret};
60//!
61//! let app = App::new()
62//!     .app_data(WebhookConfig::new(
63//!         Provider::GitHub,
64//!         Secret::new("It's a Secret to Everybody"),
65//!     ))
66//!     .route(
67//!         "/webhooks/github",
68//!         web::post().to(|body: VerifiedBody| async move {
69//!             // `body` holds the exact bytes off the wire, already verified.
70//!             // Parse them here (never re-extract via web::Json).
71//!             HttpResponse::Ok().finish()
72//!         }),
73//!     );
74//! ```
75//!
76//! # Header lookup without the extractor
77//!
78//! The bridge makes actix's own header map work with [`crate::verify()`]
79//! directly. Note that actix's inherent case-insensitive `get(&str)` shadows
80//! the trait method in method-call position (same caveat as `BTreeMap` on the
81//! [`crate::HeaderMap`] docs); pass the map through the trait explicitly or,
82//! preferably, just call [`crate::verify()`] with it. Duplicate detection
83//! remains the caller's job outside the extractor — see §4.4.
84//!
85//! [`actix-web`]: https://crates.io/crates/actix-web
86
87use std::{
88    fmt,
89    future::{Future, ready},
90    pin::Pin,
91    sync::Arc,
92};
93
94use actix_web::{
95    FromRequest, HttpRequest, ResponseError,
96    dev::Payload,
97    http::{
98        StatusCode,
99        header::{HeaderMap as ActixHeaderMap, HeaderName},
100    },
101    web::Bytes,
102};
103
104use crate::core::adapter_utils::rejection_status;
105use crate::{
106    HeaderMap, Provider, Secret, VerifyError, VerifyOptions, providers::signature_header_names,
107};
108
109/// Configuration used by the [`VerifiedBody`] extractor: provider, secret,
110/// and verification options.
111///
112/// Register it once per app (or per scoped webhook route) with
113/// `App::app_data(...)`. Requests arriving at routes without a registered
114/// config fail closed with `500 Internal Server Error`.
115#[must_use]
116#[derive(Clone)]
117pub struct WebhookConfig {
118    provider: Provider,
119    secret: Arc<Secret>,
120    options: Arc<VerifyOptions>,
121}
122
123impl fmt::Debug for WebhookConfig {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        // Provider name only; `Secret`'s Debug is redacted and
126        // `VerifyOptions`' Debug omits URL/form values (spec.md §4.3).
127        f.debug_struct("WebhookConfig")
128            .field("provider", &self.provider)
129            .field("secret", &self.secret)
130            .field("options", &self.options)
131            .finish()
132    }
133}
134
135impl WebhookConfig {
136    /// Verifies `provider` signatures using the shared `secret`.
137    pub fn new(provider: Provider, secret: Secret) -> Self {
138        Self::with_options(provider, secret, VerifyOptions::default())
139    }
140
141    /// Like [`WebhookConfig::new`], with explicit [`VerifyOptions`]
142    /// (timestamp tolerance, injected clock, URL-scoped schemes such as
143    /// Square/Twilio).
144    pub fn with_options(provider: Provider, secret: Secret, options: VerifyOptions) -> Self {
145        Self {
146            provider,
147            secret: Arc::new(secret),
148            options: Arc::new(options),
149        }
150    }
151}
152
153/// The exact raw request body, verified against the route's
154/// [`WebhookConfig`] before the handler runs.
155///
156/// Produced by the [`FromRequest`] implementation; see the [module docs](self)
157/// for the security contract and status-code table.
158#[must_use]
159pub struct VerifiedBody(Bytes);
160
161impl VerifiedBody {
162    /// The verified raw body bytes.
163    #[must_use]
164    pub fn as_bytes(&self) -> &[u8] {
165        &self.0
166    }
167
168    /// Consumes the extractor, yielding the verified [`Bytes`].
169    pub fn into_inner(self) -> Bytes {
170        self.0
171    }
172}
173
174impl fmt::Debug for VerifiedBody {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        // Never render the body itself (spec.md §3: no body material in
177        // Debug output).
178        f.debug_struct("VerifiedBody")
179            .field("len", &self.0.len())
180            .finish()
181    }
182}
183
184impl std::ops::Deref for VerifiedBody {
185    type Target = [u8];
186
187    fn deref(&self) -> &[u8] {
188        self.as_bytes()
189    }
190}
191
192/// Why a request was rejected by the [`VerifiedBody`] extractor.
193#[derive(Debug)]
194enum Rejection {
195    /// Verification failed with the structured error.
196    Verify(VerifyError),
197    /// The body could not be read to completion (transport-level failure,
198    /// e.g. client disconnect mid-stream). Carries no detail by design.
199    BodyRead,
200}
201
202/// Rejection produced when webhook verification fails; renders as an
203/// empty-bodied response whose status follows the [module table](self#status-codes).
204#[must_use]
205#[derive(Debug)]
206pub struct WebhookVerificationError(Rejection);
207
208impl fmt::Display for WebhookVerificationError {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        match &self.0 {
211            // `VerifyError`'s Display carries only header names, static
212            // reasons, and durations (spec.md §2.1) — safe to surface.
213            Rejection::Verify(error) => write!(f, "webhook verification failed: {error}"),
214            Rejection::BodyRead => f.write_str("webhook body could not be read"),
215        }
216    }
217}
218
219impl std::error::Error for WebhookVerificationError {}
220
221impl ResponseError for WebhookVerificationError {
222    fn status_code(&self) -> StatusCode {
223        match &self.0 {
224            Rejection::BodyRead => StatusCode::BAD_REQUEST,
225            // The status class is a hard-coded constant (400/401/500), so
226            // conversion cannot fail; the fallback still fails closed with
227            // 500 if it ever did.
228            Rejection::Verify(error) => StatusCode::from_u16(rejection_status(error))
229                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
230        }
231    }
232
233    // The default `error_response` builds an empty-bodied response from
234    // `status_code`; that is exactly what we want (spec.md §2.1 / tower
235    // adapter parity), so it is not overridden.
236}
237
238/// Returns the name of the first header in `names` that occurs in `headers`
239/// more than once with *differing* values — the ambiguity `spec.md` §4.4
240/// requires rejecting — or `None` when none is ambiguous.
241///
242/// Static header-name constants always parse, so the parse-error arm is
243/// unreachable in practice and simply fails closed (reported as ambiguous).
244fn conflicting_signature_header(
245    headers: &ActixHeaderMap,
246    names: &[&'static str],
247) -> Option<&'static str> {
248    names.iter().copied().find(|name| {
249        let Ok(key) = HeaderName::from_bytes(name.as_bytes()) else {
250            return true;
251        };
252        let mut values = headers.get_all(&key);
253        let Some(first) = values.next() else {
254            return false;
255        };
256        values.any(|value| value != first)
257    })
258}
259
260type ExtractFuture = Pin<Box<dyn Future<Output = Result<VerifiedBody, WebhookVerificationError>>>>;
261
262impl FromRequest for VerifiedBody {
263    type Error = WebhookVerificationError;
264    type Future = ExtractFuture;
265
266    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
267        // Fail closed when no config is registered for this app/scope:
268        // operator misconfiguration, never a requester fault.
269        let Some(config) = req.app_data::<WebhookConfig>() else {
270            return Box::pin(ready(Err(WebhookVerificationError(Rejection::Verify(
271                VerifyError::MissingContext {
272                    reason: "no WebhookConfig registered via app_data",
273                },
274            )))));
275        };
276
277        // Ambiguity check first: it needs no body bytes, so conflicting
278        // duplicates are rejected without buffering or signature work.
279        let names = signature_header_names(&config.provider);
280        if let Some(header) = conflicting_signature_header(req.headers(), &names) {
281            return Box::pin(ready(Err(WebhookVerificationError(Rejection::Verify(
282                VerifyError::MalformedHeader {
283                    header,
284                    reason: "header present multiple times with different values",
285                },
286            )))));
287        }
288
289        let config = config.clone();
290        let mut payload = payload.take();
291        let req = req.clone();
292
293        Box::pin(async move {
294            // Buffer the exact wire bytes once; these are what gets verified
295            // and what the handler receives (spec.md §4.2).
296            let raw_body = match Bytes::from_request(&req, &mut payload).await {
297                Ok(bytes) => bytes,
298                Err(_) => return Err(WebhookVerificationError(Rejection::BodyRead)),
299            };
300
301            match crate::verify(
302                config.provider,
303                req.headers(),
304                raw_body.as_ref(),
305                &config.secret,
306                (*config.options).clone(),
307            ) {
308                Ok(()) => Ok(VerifiedBody(raw_body)),
309                Err(error) => Err(WebhookVerificationError(Rejection::Verify(error))),
310            }
311        })
312    }
313}
314
315// --- header bridge ----------------------------------------------------------
316
317/// Bridge for actix-web 4's internal `http` 0.2 header map: enables passing
318/// `req.headers()` straight into [`crate::verify()`].
319///
320/// Lookup mirrors the `http` 1.x impl in `src/core/headers.rs`: typed-name
321/// lookups are ASCII case-insensitive and first-value-wins; a value that is
322/// not visible ASCII (which `http` permits but this crate cannot treat as a
323/// signature) is reported as absent, failing closed downstream. Duplicate
324/// detection stays with the adapter — see the trait's ambiguity contract.
325impl HeaderMap for ActixHeaderMap {
326    fn get(&self, name: &str) -> Option<&str> {
327        // `HeaderName::from_bytes` normalizes to lowercase and rejects names
328        // with invalid bytes, so an unparseable lookup name is simply a miss.
329        let key = HeaderName::from_bytes(name.as_bytes()).ok()?;
330        // UFCS reaches the map's *inherent* case-insensitive lookup rather
331        // than recursing into this trait method.
332        let value = ActixHeaderMap::get(self, &key)?;
333        value.to_str().ok()
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    // Aliased: a plain `use ..::test` would make `#[test]` resolve to the
341    // actix module instead of the built-in attribute.
342    #[cfg(feature = "paypal")]
343    use crate::VerifyingKeyMaterial;
344    use crate::test_helpers::{FixedClock, clocked_at, epoch};
345    use actix_web::{App, HttpResponse, http, test as aw_test, web};
346
347    /// GitHub's documented example vector
348    /// (<https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries>),
349    /// same one used across the crate's tests.
350    const GITHUB_SECRET: &str = "It's a Secret to Everybody";
351    const GITHUB_BODY: &[u8] = b"Hello, World!";
352    const GITHUB_SIGNATURE: &str =
353        "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
354
355    /// Slack's documented worked example
356    /// (<https://docs.slack.dev/authentication/verifying-requests-from-slack>),
357    /// same constants used in the tower adapter tests.
358    const SLACK_SECRET: &str = "8f742231b10e8888abcd99yyyzzz85a5";
359    const SLACK_TIMESTAMP: u64 = 1_531_420_618;
360    const SLACK_BODY: &[u8] =
361        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";
362    const SLACK_SIGNATURE: &str =
363        "a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503";
364
365    /// Handler echoing how many body bytes it received, so tests assert the
366    /// verified bytes reach handlers byte-for-byte.
367    async fn echo_len(body: VerifiedBody) -> HttpResponse {
368        HttpResponse::Ok().body(body.len().to_string())
369    }
370
371    async fn echo_len_slack(_body: VerifiedBody) -> HttpResponse {
372        unreachable!("only called where extraction should succeed")
373    }
374
375    /// App under test: GitHub config + echo handler. Each test initializes
376    /// its own service instance (actix services are single-use per request
377    /// pipeline in `init_service` tests).
378    macro_rules! github_app {
379        () => {
380            aw_test::init_service(
381                App::new()
382                    .app_data(WebhookConfig::new(
383                        Provider::GitHub,
384                        Secret::new(GITHUB_SECRET),
385                    ))
386                    .route("/", web::post().to(echo_len)),
387            )
388            .await
389        };
390    }
391
392    fn github_request(body: &'static [u8]) -> aw_test::TestRequest {
393        aw_test::TestRequest::post()
394            .insert_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
395            .set_payload(Bytes::from_static(body))
396    }
397
398    // --- happy path ---------------------------------------------------------
399
400    #[actix_web::test]
401    async fn valid_signature_reaches_handler_with_exact_bytes() {
402        let app = github_app!();
403        let res = aw_test::call_service(&app, github_request(GITHUB_BODY).to_request()).await;
404        assert_eq!(res.status(), StatusCode::OK);
405        assert_eq!(aw_test::read_body(res).await, Bytes::from_static(b"13"));
406    }
407
408    #[actix_web::test]
409    async fn empty_and_unicode_bodies_round_trip_byte_exactly() {
410        // Boundary bodies through the same buffered pipeline. Digests
411        // computed locally with GitHub's recipe:
412        // printf '<body>' | openssl dgst -sha256 -hmac <secret>
413        const EMPTY_SIG: &str =
414            "sha256=66a0c074deaa0f489ead6537e0d32f9a344b90bbeda705b6ed45ecd3b413fb40";
415        const UNICODE_BODY: &[u8] = "héllo, 🦀 world!".as_bytes();
416        const UNICODE_SIG: &str =
417            "sha256=815772f88bf8950c7457b57856f4b33ca9d07e7ef7a50646b067b4a613f735c4";
418
419        for (body, signature) in [
420            (&b""[..], EMPTY_SIG),
421            (UNICODE_BODY, UNICODE_SIG),
422            (GITHUB_BODY, GITHUB_SIGNATURE),
423        ] {
424            let expected_len = body.len().to_string();
425            let app = github_app!();
426            let req = aw_test::TestRequest::post()
427                .insert_header(("X-Hub-Signature-256", signature))
428                .set_payload(Bytes::copy_from_slice(body))
429                .to_request();
430            let res = aw_test::call_service(&app, req).await;
431            assert_eq!(res.status(), StatusCode::OK);
432            assert_eq!(aw_test::read_body(res).await, Bytes::from(expected_len));
433        }
434    }
435
436    // --- negative: tampered payload -----------------------------------------
437
438    #[actix_web::test]
439    async fn tampered_body_is_unauthorized_and_never_reaches_handler() {
440        let app = github_app!();
441        let res = aw_test::call_service(&app, github_request(b"Hello, World?").to_request()).await;
442        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
443    }
444
445    // --- negative: malformed / ambiguous headers -----------------------------
446
447    #[actix_web::test]
448    async fn missing_signature_header_is_bad_request() {
449        let app = github_app!();
450        let req = aw_test::TestRequest::post()
451            .set_payload(Bytes::from_static(GITHUB_BODY))
452            .to_request();
453        let res = aw_test::call_service(&app, req).await;
454        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
455    }
456
457    #[actix_web::test]
458    async fn conflicting_duplicate_signature_headers_are_rejected() {
459        // Second value differs from the first: ambiguous under spec §4.4 even
460        // though each value alone would just fail verification normally.
461        let app = github_app!();
462        let req = aw_test::TestRequest::post()
463            .append_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
464            .append_header((
465                "x-hub-signature-256",
466                "sha256=0000000000000000000000000000000000000000000000000000000000000000",
467            ))
468            .set_payload(Bytes::from_static(GITHUB_BODY))
469            .to_request();
470        let res = aw_test::call_service(&app, req).await;
471        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
472    }
473
474    #[actix_web::test]
475    async fn identical_duplicate_signature_headers_still_verify() {
476        let app = github_app!();
477        let req = aw_test::TestRequest::post()
478            .append_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
479            .append_header(("x-hub-signature-256", GITHUB_SIGNATURE))
480            .set_payload(Bytes::from_static(GITHUB_BODY))
481            .to_request();
482        let res = aw_test::call_service(&app, req).await;
483        assert_eq!(res.status(), StatusCode::OK);
484    }
485
486    #[actix_web::test]
487    async fn conflicting_duplicate_timestamp_header_is_rejected_for_slack() {
488        // Valid-shaped signature plus two conflicting timestamps: ambiguity
489        // lives in the timestamp header, not the signature header itself.
490        let app = aw_test::init_service(
491            App::new()
492                .app_data(WebhookConfig::new(
493                    Provider::Slack,
494                    Secret::new(SLACK_SECRET),
495                ))
496                .route("/", web::post().to(echo_len_slack)),
497        )
498        .await;
499        let req = aw_test::TestRequest::post()
500            .insert_header(("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}")))
501            .append_header(("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string()))
502            .append_header(("x-slack-request-timestamp", "1700000001"))
503            .set_payload(Bytes::from_static(SLACK_BODY))
504            .to_request();
505        let res = aw_test::call_service(&app, req).await;
506        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
507    }
508
509    // --- replay protection through the adapter -------------------------------
510
511    #[actix_web::test]
512    async fn stale_timestamp_is_unauthorized_through_adapter() {
513        // "Now" ten minutes after signing: outside the default 300s window.
514        let late = epoch(SLACK_TIMESTAMP + 600);
515
516        let app = aw_test::init_service(
517            App::new()
518                .app_data(WebhookConfig::with_options(
519                    Provider::Slack,
520                    Secret::new(SLACK_SECRET),
521                    crate::VerifyOptions {
522                        clock: Some(Arc::new(FixedClock(late))),
523                        ..crate::VerifyOptions::default()
524                    },
525                ))
526                .route("/", web::post().to(echo_len_slack)),
527        )
528        .await;
529
530        let req = aw_test::TestRequest::post()
531            .insert_header(("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}")))
532            .insert_header(("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string()))
533            .set_payload(Bytes::from_static(SLACK_BODY))
534            .to_request();
535        let res = aw_test::call_service(&app, req).await;
536        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
537    }
538
539    // --- custom schemes and unsupported providers ----------------------------
540
541    #[actix_web::test]
542    async fn custom_scheme_headers_are_dup_checked_too() {
543        // HMAC-SHA256 hex of the body with key "k":
544        // printf 'Hello, World!' | openssl dgst -sha256 -hmac "k"
545        const DIGEST: &str = "11316937114e6970aa59bd5326a6f38dd525f4ade64670e402bff41e2f7c4071";
546        let scheme = crate::CustomScheme {
547            hash: crate::HashAlg::Sha256,
548            signature_header: "X-My-Sig",
549            timestamp_header: None,
550            encoding: crate::Encoding::Hex,
551            prefix: Some("sha256="),
552            signed_string: |_headers, body| body.to_vec(),
553        };
554
555        // Conflicting duplicates of the custom scheme's signature header are
556        // caught before any verification work.
557        let ambiguous_app = aw_test::init_service(
558            App::new()
559                .app_data(WebhookConfig::new(
560                    Provider::Custom(scheme),
561                    Secret::new("k"),
562                ))
563                .route("/", web::post().to(echo_len_slack)),
564        )
565        .await;
566        let req = aw_test::TestRequest::post()
567            .append_header(("X-My-Sig", format!("sha256={DIGEST}")))
568            .append_header(("x-my-sig", "sha256=00"))
569            .set_payload(Bytes::from_static(GITHUB_BODY))
570            .to_request();
571        let res = aw_test::call_service(&ambiguous_app, req).await;
572        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
573
574        // A single well-formed value verifies end to end.
575        let good_app = aw_test::init_service(
576            App::new()
577                .app_data(WebhookConfig::new(
578                    Provider::Custom(scheme),
579                    Secret::new("k"),
580                ))
581                .route("/", web::post().to(echo_len)),
582        )
583        .await;
584        let req = aw_test::TestRequest::post()
585            .insert_header(("X-My-Sig", format!("sha256={DIGEST}")))
586            .set_payload(Bytes::from_static(GITHUB_BODY))
587            .to_request();
588        let res = aw_test::call_service(&good_app, req).await;
589        assert_eq!(res.status(), StatusCode::OK);
590    }
591
592    // PayPal stays "unsupported" only when the `paypal` feature is off; the
593    // mapping of that error class to 500 lives in core::adapter_utils tests.
594    #[cfg(not(feature = "paypal"))]
595    #[actix_web::test]
596    async fn unsupported_provider_maps_to_internal_server_error() {
597        let app = aw_test::init_service(
598            App::new()
599                .app_data(WebhookConfig::new(Provider::PayPal, Secret::new("unused")))
600                .route("/", web::post().to(echo_len_slack)),
601        )
602        .await;
603        let req = aw_test::TestRequest::post()
604            .set_payload(Bytes::from_static(b"{}"))
605            .to_request();
606        let res = aw_test::call_service(&app, req).await;
607        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
608    }
609
610    #[cfg(feature = "paypal")]
611    #[actix_web::test]
612    async fn paypal_verifies_through_the_extractor() {
613        let cert = include_bytes!("../tests/data/paypal_test_cert.pem");
614        // Reuse the documented PayPal construction's options plus the vector's
615        // headers (see src/providers/paypal.rs tests). The clock is pinned to
616        // the vector's transmission time so the replay window is satisfied.
617        let config = WebhookConfig::with_options(
618            Provider::PayPal,
619            Secret::new("unused"),
620            clocked_at(1_715_836_763, None)
621                .with_webhook_id("0NH55953DH663215D")
622                .with_verifying_material(VerifyingKeyMaterial::X509Certificate(cert.to_vec())),
623        );
624        let app = aw_test::init_service(
625            App::new()
626                .app_data(config)
627                .route("/", web::post().to(echo_len)),
628        )
629        .await;
630        let body = include_bytes!("../tests/data/paypal_docs_body.json");
631        let req = aw_test::TestRequest::post()
632            .insert_header(("PayPal-Transmission-Id", "db49fb10-1343-11ef-ac58-e32457403f67"))
633            .insert_header(("PayPal-Transmission-Time", "2024-05-16T05:19:23Z"))
634            .insert_header((
635                "PayPal-Transmission-Sig",
636                "aGYe/s6lwrASh2zyTRIAz8Edo705ezMKekirejT08ev3VXdWAkq4JWADiNPUGelx5qrEKxC7mPIHmAwQ5hOT6unhY9n33M/DbXTKGsuITPdXRA7qYVmc2wsIp68BpzB6pC6+5vt/YLQvflsrwrutGa0KyZc5FinuYNN8pTNomv4uiygasWqfnDyKViKQPNZecowag6tY/9pj7+bgBu/joBpYUq0+cQxfGqNnlvywBJ7HCOf4edeTIvM/c1CvvAHGtNTU54kLjWGue640twn6iXPL8tnaABZ8Fr9m0z87v8oY0vBobERV0Yu8thUToKhvQEFF26Rckqy07VVddg1CmA==",
637            ))
638            .insert_header(("PayPal-Cert-Url", "https://example.invalid/cert-url"))
639            .insert_header(("PayPal-Auth-Algo", "SHA256withRSA"))
640            .set_payload(Bytes::from_static(body))
641            .to_request();
642        let res = aw_test::call_service(&app, req).await;
643        assert_eq!(res.status(), StatusCode::OK);
644    }
645
646    #[actix_web::test]
647    async fn missing_config_fails_closed_with_internal_server_error() {
648        let app = aw_test::init_service(App::new().route("/", web::post().to(echo_len))).await;
649        let req = aw_test::TestRequest::post()
650            .insert_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
651            .set_payload(Bytes::from_static(GITHUB_BODY))
652            .to_request();
653        let res = aw_test::call_service(&app, req).await;
654        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
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 name = HeaderName::from_static("x-hub-signature-256");
664        let mut headers = ActixHeaderMap::new();
665        let value = http::header::HeaderValue::from_bytes(&[0xFF])
666            .unwrap_or_else(|_| unreachable!("permitted"));
667        headers.append(name.clone(), value.clone());
668        headers.append(name, value);
669        assert!(conflicting_signature_header(&headers, &["X-Hub-Signature-256"]).is_none());
670    }
671
672    #[test]
673    fn unparseable_header_name_fails_closed_as_ambiguous() {
674        // A header-name string actix's http crate refuses to parse (embedded
675        // whitespace) must fail closed as "ambiguous" per §4.4 — the parse-
676        // error arm exists precisely so attacker-supplied garbage can never
677        // turn into a permissive lookup.
678        let headers = ActixHeaderMap::new();
679        assert_eq!(
680            conflicting_signature_header(&headers, &["x-hub-signature-256 invalid"]),
681            Some("x-hub-signature-256 invalid")
682        );
683    }
684
685    #[test]
686    fn bridge_lookup_is_ascii_case_insensitive_and_fail_closed() {
687        let mut headers = ActixHeaderMap::new();
688        headers.insert(
689            HeaderName::from_static("x-hub-signature-256"),
690            http::header::HeaderValue::from_static(GITHUB_SIGNATURE),
691        );
692        assert_eq!(
693            HeaderMap::get(&headers, "x-hub-signature-256"),
694            Some(GITHUB_SIGNATURE)
695        );
696        assert_eq!(
697            HeaderMap::get(&headers, "X-HUB-SIGNATURE-256"),
698            Some(GITHUB_SIGNATURE)
699        );
700        assert_eq!(HeaderMap::get(&headers, "bad name\n"), None);
701        // Opaque-byte values cannot be signatures; reported absent.
702        let mut opaque = ActixHeaderMap::new();
703        opaque.insert(
704            HeaderName::from_static("x-webhook-sig"),
705            http::header::HeaderValue::from_bytes(&[0xFF])
706                .unwrap_or_else(|_| unreachable!("permitted")),
707        );
708        assert_eq!(HeaderMap::get(&opaque, "X-Webhook-Sig"), None);
709    }
710
711    #[test]
712    fn bridge_verifies_github_delivery_end_to_end() {
713        let mut headers = ActixHeaderMap::new();
714        headers.insert(
715            HeaderName::from_static("x-hub-signature-256"),
716            http::header::HeaderValue::from_static(GITHUB_SIGNATURE),
717        );
718        let result = crate::verify(
719            Provider::GitHub,
720            &headers,
721            GITHUB_BODY,
722            &Secret::new(GITHUB_SECRET),
723            Default::default(),
724        );
725        assert_eq!(result, Ok(()));
726
727        let result = crate::verify(
728            Provider::GitHub,
729            &headers,
730            b"Hello, World?",
731            &Secret::new(GITHUB_SECRET),
732            Default::default(),
733        );
734        assert_eq!(result, Err(VerifyError::SignatureMismatch));
735    }
736
737    #[test]
738    fn debug_output_never_contains_secrets_or_bodies() {
739        let config = WebhookConfig::with_options(
740            Provider::GitHub,
741            Secret::new("super-secret-hmac-key"),
742            crate::VerifyOptions::default().with_request_url("https://internal.example/hook"),
743        );
744        let debug = format!("{config:?}");
745        assert!(!debug.contains("super-secret-hmac-key"));
746        assert!(!debug.contains("internal.example"));
747
748        let body = VerifiedBody(Bytes::from_static(b"raw-secret-payload-bytes"));
749        let debug = format!("{body:?}");
750        assert!(!debug.contains("raw-secret-payload-bytes"));
751        assert!(debug.contains("len: 24"));
752    }
753
754    #[test]
755    fn rejection_display_never_contains_secret_material() {
756        let e = WebhookVerificationError(Rejection::Verify(VerifyError::MissingHeader {
757            header: "X-Hub-Signature-256",
758        }));
759        assert_eq!(
760            e.to_string(),
761            "webhook verification failed: missing header `X-Hub-Signature-256`"
762        );
763        let e = WebhookVerificationError(Rejection::BodyRead);
764        assert_eq!(e.to_string(), "webhook body could not be read");
765        assert_eq!(e.status_code(), StatusCode::BAD_REQUEST);
766    }
767}