Skip to main content

hyperlane_plugin_webhook/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`DigestIdentityHasher`] reading 8 uniform entropy bytes directly from SHA-256 digests.
4impl Hasher for DigestIdentityHasher {
5    /// Returns the extracted 64-bit digest word.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Uniform 64-bit hash key.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { state } = *self;
13        state
14    }
15
16    /// Reads bytes `8..16` from a 32-byte SHA-256 digest without hashing overhead.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Digest byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { state } = self;
24        if bytes.len() >= 16 {
25            *state = u64::from_ne_bytes([
26                bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14],
27                bytes[15],
28            ]);
29        } else if bytes.len() >= 8 {
30            *state = u64::from_ne_bytes([
31                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
32            ]);
33        } else {
34            let mut acc: u64 = 0;
35            for &b in bytes {
36                acc = (acc << 8) | u64::from(b);
37            }
38            *state = acc;
39        }
40    }
41}
42
43/// Default construction for [`Sha256State`].
44impl Default for Sha256State {
45    /// Initializes a fresh FIPS 180-4 SHA-256 streaming state.
46    ///
47    /// # Returns
48    ///
49    /// - `Self` - Initialized SHA-256 state.
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55/// Streaming FIPS 180-4 SHA-256 implementation without heap allocations.
56impl Sha256State {
57    /// Creates a fresh SHA-256 hasher state initialized to `SHA256_INIT`.
58    ///
59    /// # Returns
60    ///
61    /// - `Self` - Fresh SHA-256 state.
62    #[inline]
63    pub fn new() -> Self {
64        Self {
65            state: SHA256_INIT,
66            buf: [0u8; 64],
67            buf_len: 0,
68            total_bytes: 0,
69        }
70    }
71
72    /// Creates a SHA-256 state pre-seeded from a compressed 64-byte midstate block.
73    ///
74    /// # Arguments
75    ///
76    /// - `[u32; 8]` - Precomputed state after compressing 64 prefix bytes.
77    ///
78    /// # Returns
79    ///
80    /// - `Self` - Pre-seeded streaming SHA-256 state.
81    #[inline]
82    pub(crate) fn from_block_midstate(midstate: [u32; 8]) -> Self {
83        Self {
84            state: midstate,
85            buf: [0u8; 64],
86            buf_len: 0,
87            total_bytes: 64,
88        }
89    }
90
91    /// Feeds `data` into the streaming SHA-256 state compressing aligned chunks directly without copy.
92    ///
93    /// # Arguments
94    ///
95    /// - `&[u8]` - Input byte slice.
96    #[inline]
97    pub fn update(&mut self, data: &[u8]) {
98        let Self {
99            state,
100            buf,
101            buf_len,
102            total_bytes,
103        } = self;
104        *total_bytes = total_bytes.wrapping_add(data.len() as u64);
105        let mut slice: &[u8] = data;
106        if *buf_len > 0 {
107            let need: usize = 64 - *buf_len;
108            if slice.len() < need {
109                buf[*buf_len..*buf_len + slice.len()].copy_from_slice(slice);
110                *buf_len += slice.len();
111                return;
112            }
113            buf[*buf_len..64].copy_from_slice(&slice[..need]);
114            sha256_compress(state, buf);
115            *buf_len = 0;
116            slice = &slice[need..];
117        }
118        let (blocks, rem): (&[[u8; 64]], &[u8]) = slice.as_chunks::<64>();
119        for block in blocks {
120            sha256_compress(state, block);
121        }
122        if !rem.is_empty() {
123            buf[..rem.len()].copy_from_slice(rem);
124            *buf_len = rem.len();
125        }
126    }
127
128    /// Pads and finalizes the SHA-256 state in-place into a 32-byte digest.
129    ///
130    /// # Returns
131    ///
132    /// - `[u8; 32]` - 256-bit SHA-256 digest.
133    #[inline]
134    pub fn finalize(mut self) -> [u8; 32] {
135        let Self {
136            ref mut state,
137            ref mut buf,
138            buf_len,
139            total_bytes,
140        } = self;
141        let bit_len: u64 = total_bytes.wrapping_mul(8);
142        buf[buf_len] = 0x80;
143        buf[buf_len + 1..64].fill(0);
144        if buf_len < 56 {
145            buf[56..64].copy_from_slice(&bit_len.to_be_bytes());
146            sha256_compress(state, buf);
147        } else {
148            sha256_compress(state, buf);
149            let mut tail1: [u8; 64] = [0u8; 64];
150            tail1[56..64].copy_from_slice(&bit_len.to_be_bytes());
151            sha256_compress(state, &tail1);
152        }
153        sha256_state_to_bytes(state)
154    }
155}
156
157/// Redacts precomputed midstate words when formatting [`HmacSha256Key`] for debugging.
158impl Debug for HmacSha256Key {
159    /// Formats [`HmacSha256Key`] without exposing secret-derived state.
160    ///
161    /// # Arguments
162    ///
163    /// - `&mut Formatter<'_>` - Output formatter.
164    ///
165    /// # Returns
166    ///
167    /// - `fmt::Result` - Formatting outcome.
168    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
169        f.debug_tuple(DEBUG_HMAC_KEY)
170            .field(&DEBUG_REDACTED)
171            .finish()
172    }
173}
174
175/// Precomputed-midstate RFC 4231 HMAC-SHA256 implementation.
176impl HmacSha256Key {
177    /// Precomputes ipad and opad SHA-256 midstates for `secret` once at startup.
178    ///
179    /// # Arguments
180    ///
181    /// - `&[u8]` - Raw secret key bytes of arbitrary length.
182    ///
183    /// # Returns
184    ///
185    /// - `Self` - Precomputed zero-allocation HMAC-SHA256 key.
186    pub fn new(secret: &[u8]) -> Self {
187        let mut key_block: [u8; 64] = [0u8; 64];
188        if secret.len() > 64 {
189            let hashed: [u8; 32] = sha256(secret);
190            key_block[..32].copy_from_slice(&hashed);
191        } else {
192            key_block[..secret.len()].copy_from_slice(secret);
193        }
194        let mut ipad: [u8; 64] = [0u8; 64];
195        let mut opad: [u8; 64] = [0u8; 64];
196        for i in 0..64usize {
197            ipad[i] = key_block[i] ^ 0x36;
198            opad[i] = key_block[i] ^ 0x5c;
199        }
200        let mut ipad_state: [u32; 8] = SHA256_INIT;
201        sha256_compress(&mut ipad_state, &ipad);
202        let mut opad_state: [u32; 8] = SHA256_INIT;
203        sha256_compress(&mut opad_state, &opad);
204        Self {
205            ipad_state,
206            opad_state,
207        }
208    }
209
210    /// Computes HMAC-SHA256 over a single byte slice with zero heap allocations.
211    ///
212    /// # Arguments
213    ///
214    /// - `&[u8]` - Message bytes.
215    ///
216    /// # Returns
217    ///
218    /// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
219    #[inline]
220    pub fn sign(&self, data: &[u8]) -> [u8; 32] {
221        let Self {
222            ipad_state,
223            opad_state,
224        } = self;
225        let inner_digest: [u8; 32] = sha256_finish_from(*ipad_state, 64, data);
226        hmac_finish_outer(*opad_state, &inner_digest)
227    }
228
229    /// Computes HMAC-SHA256 over multiple non-contiguous message slices with zero heap allocations.
230    ///
231    /// # Arguments
232    ///
233    /// - `&[&[u8]]` - Ordered slices hashed as their concatenation.
234    ///
235    /// # Returns
236    ///
237    /// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
238    #[inline]
239    pub fn sign_parts(&self, parts: &[&[u8]]) -> [u8; 32] {
240        let Self {
241            ipad_state,
242            opad_state,
243        } = self;
244        let mut inner: Sha256State = Sha256State::from_block_midstate(*ipad_state);
245        for part in parts {
246            inner.update(part);
247        }
248        let inner_digest: [u8; 32] = inner.finalize();
249        hmac_finish_outer(*opad_state, &inner_digest)
250    }
251}
252
253/// Redacts secret bytes when formatting [`WebhookSecret`] for debugging.
254impl Debug for WebhookSecret {
255    /// Formats [`WebhookSecret`] showing `id` while redacting raw key material.
256    ///
257    /// # Arguments
258    ///
259    /// - `&mut Formatter<'_>` - Output formatter.
260    ///
261    /// # Returns
262    ///
263    /// - `fmt::Result` - Formatting outcome.
264    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
265        f.debug_struct(DEBUG_WEBHOOK_SECRET)
266            .field("id", &self.id)
267            .field("secret", &DEBUG_REDACTED)
268            .finish()
269    }
270}
271
272/// Inherent constructors for [`WebhookSecret`].
273impl WebhookSecret {
274    /// Constructs a named webhook signing secret for per-route rotation.
275    ///
276    /// # Arguments
277    ///
278    /// - `I` - Logical key identifier (for example `"primary"` or `"key-2026-01"`).
279    /// - `S` - Raw secret key bytes.
280    ///
281    /// # Returns
282    ///
283    /// - `Self` - Named secret.
284    pub fn new<I, S>(id: I, secret: S) -> Self
285    where
286        I: Into<String>,
287        S: Into<Vec<u8>>,
288    {
289        Self {
290            id: id.into(),
291            secret: secret.into(),
292        }
293    }
294}
295
296/// Inherent preset constructors and fluent builders for [`WebhookEndpoint`].
297impl WebhookEndpoint {
298    /// Creates a webhook endpoint verifying `scheme` signatures delivered in `signature_header`.
299    ///
300    /// # Arguments
301    ///
302    /// - `P` - Route path or prefix (for example `"/webhooks/events"`).
303    /// - `H` - Signature request header name.
304    /// - `WebhookScheme` - Signature encoding/framing scheme.
305    /// - `Vec<WebhookSecret>` - Active signing secrets (supports rotation).
306    ///
307    /// # Returns
308    ///
309    /// - `Self` - Constructed endpoint definition.
310    pub fn new<P, H>(
311        path_prefix: P,
312        signature_header: H,
313        scheme: WebhookScheme,
314        secrets: Vec<WebhookSecret>,
315    ) -> Self
316    where
317        P: Into<String>,
318        H: AsRef<str>,
319    {
320        Self {
321            path_prefix: path_prefix.into(),
322            signature_header: signature_header.as_ref().trim().to_ascii_lowercase(),
323            scheme,
324            secrets,
325            timestamp_header: None,
326            timestamp_payload_separator: None,
327            id_header: None,
328            tolerance_secs: DEFAULT_TOLERANCE_SECS,
329            replay_ttl_secs: DEFAULT_REPLAY_TTL_SECS,
330            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
331        }
332    }
333
334    /// Preset for Stripe-style `Stripe-Signature: t=...,v1=...` timestamped webhooks.
335    ///
336    /// # Arguments
337    ///
338    /// - `P` - Route path or prefix (for example `"/webhooks/stripe"`).
339    /// - `Vec<WebhookSecret>` - Active Stripe signing secrets.
340    ///
341    /// # Returns
342    ///
343    /// - `Self` - Stripe-compatible endpoint configuration.
344    pub fn stripe<P>(path_prefix: P, secrets: Vec<WebhookSecret>) -> Self
345    where
346        P: Into<String>,
347    {
348        Self::new(
349            path_prefix,
350            HEADER_STRIPE_SIGNATURE,
351            WebhookScheme::StripeTimestamped {
352                version: DEFAULT_STRIPE_VERSION.to_owned(),
353            },
354            secrets,
355        )
356    }
357
358    /// Preset for GitHub `X-Hub-Signature-256: sha256=<hex>` webhooks with `X-GitHub-Delivery` replay defense.
359    ///
360    /// # Arguments
361    ///
362    /// - `P` - Route path or prefix (for example `"/webhooks/github"`).
363    /// - `Vec<WebhookSecret>` - Active GitHub webhook secrets.
364    ///
365    /// # Returns
366    ///
367    /// - `Self` - GitHub-compatible endpoint configuration.
368    pub fn github<P>(path_prefix: P, secrets: Vec<WebhookSecret>) -> Self
369    where
370        P: Into<String>,
371    {
372        Self::new(
373            path_prefix,
374            HEADER_GITHUB_SIGNATURE_256,
375            WebhookScheme::Hex {
376                prefix: Some(GITHUB_SHA256_PREFIX.to_owned()),
377            },
378            secrets,
379        )
380        .with_id_header(HEADER_GITHUB_DELIVERY)
381    }
382
383    /// Preset for Shopify `X-Shopify-Hmac-Sha256: <base64>` webhooks.
384    ///
385    /// # Arguments
386    ///
387    /// - `P` - Route path or prefix (for example `"/webhooks/shopify"`).
388    /// - `Vec<WebhookSecret>` - Active Shopify webhook secrets.
389    ///
390    /// # Returns
391    ///
392    /// - `Self` - Shopify-compatible endpoint configuration.
393    pub fn shopify<P>(path_prefix: P, secrets: Vec<WebhookSecret>) -> Self
394    where
395        P: Into<String>,
396    {
397        Self::new(
398            path_prefix,
399            HEADER_SHOPIFY_HMAC_SHA256,
400            WebhookScheme::Base64 { prefix: None },
401            secrets,
402        )
403    }
404
405    /// Appends an additional active secret key for zero-downtime key rotation.
406    ///
407    /// # Arguments
408    ///
409    /// - `WebhookSecret` - Rotated or secondary signing secret.
410    ///
411    /// # Returns
412    ///
413    /// - `Self` - Updated endpoint.
414    pub fn with_secret(mut self, secret: WebhookSecret) -> Self {
415        self.get_mut_secrets().push(secret);
416        self
417    }
418
419    /// Configures a separate Unix-seconds timestamp header and optional `<ts><sep><body>` signing separator.
420    ///
421    /// # Arguments
422    ///
423    /// - `H` - Timestamp request header name.
424    /// - `Option<String>` - Separator inserted between timestamp and body when signing (or `None` to sign raw body only).
425    ///
426    /// # Returns
427    ///
428    /// - `Self` - Updated endpoint.
429    pub fn with_timestamp_header<H>(mut self, header: H, separator: Option<String>) -> Self
430    where
431        H: AsRef<str>,
432    {
433        self.set_timestamp_header(Some(header.as_ref().trim().to_ascii_lowercase()))
434            .set_timestamp_payload_separator(separator);
435        self
436    }
437
438    /// Configures the delivery identifier header used as the replay-cache nonce.
439    ///
440    /// # Arguments
441    ///
442    /// - `H` - Delivery ID header name (for example `"x-github-delivery"` or `"webhook-id"`).
443    ///
444    /// # Returns
445    ///
446    /// - `Self` - Updated endpoint.
447    pub fn with_id_header<H>(mut self, header: H) -> Self
448    where
449        H: AsRef<str>,
450    {
451        self.set_id_header(Some(header.as_ref().trim().to_ascii_lowercase()));
452        self
453    }
454
455    /// Sets the allowed timestamp skew tolerance in seconds (`±tolerance_secs`).
456    ///
457    /// # Arguments
458    ///
459    /// - `u64` - Tolerance window in seconds.
460    ///
461    /// # Returns
462    ///
463    /// - `Self` - Updated endpoint.
464    pub fn with_tolerance_secs(mut self, tolerance_secs: u64) -> Self {
465        self.set_tolerance_secs(tolerance_secs);
466        self
467    }
468
469    /// Sets the replay-nonce cache TTL in seconds (`0` disables replay caching for this endpoint).
470    ///
471    /// # Arguments
472    ///
473    /// - `u64` - Replay retention TTL in seconds.
474    ///
475    /// # Returns
476    ///
477    /// - `Self` - Updated endpoint.
478    pub fn with_replay_ttl_secs(mut self, replay_ttl_secs: u64) -> Self {
479        self.set_replay_ttl_secs(replay_ttl_secs);
480        self
481    }
482
483    /// Sets the maximum inbound webhook payload length in bytes.
484    ///
485    /// # Arguments
486    ///
487    /// - `usize` - Maximum body bytes (`>= 1`).
488    ///
489    /// # Returns
490    ///
491    /// - `Self` - Updated endpoint.
492    pub fn with_max_body_bytes(mut self, max_body_bytes: usize) -> Self {
493        self.set_max_body_bytes(max_body_bytes.max(1));
494        self
495    }
496}
497
498/// Default construction for [`WebhookConfig`].
499impl Default for WebhookConfig {
500    /// Constructs an empty [`WebhookConfig`] with 65 536 max replay cache entries.
501    ///
502    /// # Returns
503    ///
504    /// - `Self` - Default configuration.
505    fn default() -> Self {
506        Self {
507            endpoints: Vec::new(),
508            replay_max_entries: DEFAULT_REPLAY_MAX_ENTRIES,
509        }
510    }
511}
512
513/// Fluent configuration builders for [`WebhookConfig`].
514impl WebhookConfig {
515    /// Appends a configured [`WebhookEndpoint`].
516    ///
517    /// # Arguments
518    ///
519    /// - `WebhookEndpoint` - Endpoint verification rules.
520    ///
521    /// # Returns
522    ///
523    /// - `Self` - Updated configuration.
524    pub fn with_endpoint(mut self, endpoint: WebhookEndpoint) -> Self {
525        self.get_mut_endpoints().push(endpoint);
526        self
527    }
528
529    /// Sets the maximum number of replay nonces retained across all 64 shards.
530    ///
531    /// # Arguments
532    ///
533    /// - `usize` - Maximum entry cap (`>= 1`).
534    ///
535    /// # Returns
536    ///
537    /// - `Self` - Updated configuration.
538    pub fn with_replay_max_entries(mut self, max_entries: usize) -> Self {
539        self.set_replay_max_entries(max_entries.max(1));
540        self
541    }
542}
543
544/// Context extraction helper for [`WebhookEvent`].
545impl WebhookEvent {
546    /// Retrieves the verified [`WebhookEvent`] injected by [`WebhookHook`] from `ctx`.
547    ///
548    /// # Arguments
549    ///
550    /// - `&Context` - Active Hyperlane request context.
551    ///
552    /// # Returns
553    ///
554    /// - `Option<Self>` - Verified event metadata when present.
555    pub fn from_context(ctx: &Context) -> Option<Self> {
556        ctx.try_get_attribute::<Self, _>(ATTR_WEBHOOK_EVENT)
557    }
558}
559
560/// Inherent 64-shard bounded TTL replay-nonce operations for [`ReplayNonceCache`].
561impl ReplayNonceCache {
562    /// Creates a 64-way sharded bounded [`ReplayNonceCache`].
563    ///
564    /// # Arguments
565    ///
566    /// - `usize` - Maximum entries tracked across all shards (`>= 1`).
567    ///
568    /// # Returns
569    ///
570    /// - `Self` - Ready replay cache.
571    pub fn new(max_entries: usize) -> Self {
572        let shards: Box<[ReplayShard; REPLAY_SHARD_COUNT]> =
573            Box::new(from_fn(|_: usize| ReplayShard {
574                map: Mutex::new(HashMap::default()),
575            }));
576        Self {
577            inner: Arc::new(ReplayNonceCacheInner {
578                max_entries: max_entries.max(1),
579                count: AtomicUsize::new(0),
580                shards,
581            }),
582        }
583    }
584
585    /// Returns the active entry count across all 64 shards in `O(1)` time.
586    ///
587    /// # Returns
588    ///
589    /// - `usize` - Tracked nonce count.
590    #[inline]
591    pub fn len(&self) -> usize {
592        let Self { inner } = self;
593        inner.count.load(Ordering::Relaxed)
594    }
595
596    /// Reports whether the replay cache holds zero entries.
597    ///
598    /// # Returns
599    ///
600    /// - `bool` - `true` when empty.
601    #[inline]
602    pub fn is_empty(&self) -> bool {
603        self.len() == 0
604    }
605
606    /// Checks and atomically inserts `digest` with `ttl_secs`; returns `false` if already seen and unexpired.
607    ///
608    /// # Arguments
609    ///
610    /// - `[u8; 32]` - 32-byte replay nonce digest.
611    /// - `u64` - Current Unix timestamp in seconds.
612    /// - `u64` - Retention TTL in seconds.
613    ///
614    /// # Returns
615    ///
616    /// - `bool` - `true` if fresh (inserted); `false` if replayed within TTL.
617    #[inline]
618    pub fn check_and_insert(&self, digest: [u8; 32], now_secs: u64, ttl_secs: u64) -> bool {
619        if ttl_secs == 0 {
620            return true;
621        }
622        let Self { inner } = self;
623        let shard_idx: usize = (digest[0] as usize) & (REPLAY_SHARD_COUNT - 1);
624        let Ok(mut map): Result<MutexGuard<'_, ReplayShardMap>, _> =
625            inner.shards[shard_idx].map.lock()
626        else {
627            return true;
628        };
629        let expires_next: u64 = now_secs.saturating_add(ttl_secs);
630        match map.entry(digest) {
631            Entry::Occupied(mut occ) => {
632                if now_secs < *occ.get() {
633                    return false;
634                }
635                *occ.get_mut() = expires_next;
636                return true;
637            }
638            Entry::Vacant(vac) => {
639                if inner.count.load(Ordering::Relaxed) < inner.max_entries {
640                    vac.insert(expires_next);
641                    inner.count.fetch_add(1, Ordering::Relaxed);
642                    return true;
643                }
644            }
645        }
646        let mut purged: usize = 0;
647        map.retain(|_: &[u8; 32], exp: &mut u64| {
648            if now_secs >= *exp {
649                purged += 1;
650                false
651            } else {
652                true
653            }
654        });
655        if purged > 0 {
656            inner.count.fetch_sub(purged, Ordering::Relaxed);
657        }
658        while inner.count.load(Ordering::Relaxed) >= inner.max_entries && !map.is_empty() {
659            let oldest: Option<[u8; 32]> = map
660                .iter()
661                .min_by_key(|(_, exp): &(&[u8; 32], &u64)| **exp)
662                .map(|(k, _): (&[u8; 32], &u64)| *k);
663            if let Some(evict) = oldest
664                && map.remove(&evict).is_some()
665            {
666                inner.count.fetch_sub(1, Ordering::Relaxed);
667            } else {
668                break;
669            }
670        }
671        map.insert(digest, expires_next);
672        inner.count.fetch_add(1, Ordering::Relaxed);
673        true
674    }
675}
676
677/// Inherent verification logic for one precompiled [`CompiledEndpoint`].
678impl CompiledEndpoint {
679    /// Verifies headers and body for this endpoint against `now_secs` and `replay_cache`.
680    ///
681    /// # Arguments
682    ///
683    /// - `&RequestHeaders` - Incoming HTTP request headers.
684    /// - `&[u8]` - Raw HTTP request body bytes.
685    /// - `u64` - Current Unix epoch seconds.
686    /// - `&ReplayNonceCache` - Shared 64-shard replay cache.
687    ///
688    /// # Returns
689    ///
690    /// - `Result<WebhookEvent, WebhookRejectReason>` - Verified event metadata or rejection reason.
691    pub(crate) fn verify_at(
692        &self,
693        headers: &RequestHeaders,
694        body: &[u8],
695        now_secs: u64,
696        replay_cache: &ReplayNonceCache,
697    ) -> Result<WebhookEvent, WebhookRejectReason> {
698        let Self {
699            prefix,
700            signature_header,
701            scheme,
702            secrets,
703            timestamp_header,
704            timestamp_payload_separator,
705            id_header,
706            tolerance_secs,
707            replay_ttl_secs,
708            max_body_bytes,
709            replay_prefix_state,
710            ..
711        } = self;
712        if body.len() > *max_body_bytes {
713            return Err(WebhookRejectReason::BodyTooLarge);
714        }
715        let Some(raw_sig_header) = find_header_back_ref(headers, signature_header) else {
716            return Err(WebhookRejectReason::MissingSignature);
717        };
718        let delivery_id: Option<&str> = id_header
719            .as_deref()
720            .and_then(|h: &str| find_header_back_ref(headers, h))
721            .map(str::trim)
722            .filter(|s: &&str| !s.is_empty());
723        let (matched_secret_id, verified_ts, verified_digest): (&str, Option<u64>, [u8; 32]) =
724            match scheme {
725                WebhookScheme::StripeTimestamped { version } => {
726                    let mut ts_str: Option<&str> = None;
727                    let mut parsed_ts: Option<u64> = None;
728                    let mut stack_cands: [[u8; 32]; STRIPE_STACK_CANDIDATES] =
729                        [[0u8; 32]; STRIPE_STACK_CANDIDATES];
730                    let mut stack_len: usize = 0;
731                    let mut extra_cands: Vec<[u8; 32]> = Vec::new();
732                    let version_str: &str = version.as_str();
733                    for segment in raw_sig_header.split(',') {
734                        let trimmed: &str = segment.trim();
735                        if let Some((k, v)) = trimmed.split_once('=') {
736                            let key: &str = k.trim();
737                            if key == STRIPE_TIME_KEY {
738                                if ts_str.is_none() {
739                                    let val: &str = v.trim();
740                                    ts_str = Some(val);
741                                    parsed_ts = val.parse::<u64>().ok();
742                                }
743                            } else if key == version_str
744                                && let Some(provided) = decode_hex_32(v)
745                            {
746                                if stack_len < STRIPE_STACK_CANDIDATES {
747                                    stack_cands[stack_len] = provided;
748                                    stack_len += 1;
749                                } else {
750                                    extra_cands.push(provided);
751                                }
752                            }
753                        }
754                    }
755                    let (Some(raw_ts), Some(ts_val)) = (ts_str, parsed_ts) else {
756                        return Err(WebhookRejectReason::MissingTimestamp);
757                    };
758                    if *tolerance_secs > 0
759                        && !is_timestamp_within_skew(ts_val, now_secs, *tolerance_secs)
760                    {
761                        return Err(WebhookRejectReason::TimestampOutOfRange);
762                    }
763                    if stack_len == 0 {
764                        return Err(WebhookRejectReason::MalformedSignature);
765                    }
766                    let mut matched: Option<(&str, [u8; 32])> = None;
767                    for secret in secrets {
768                        let expected: [u8; 32] =
769                            secret
770                                .key
771                                .sign_parts(&[raw_ts.as_bytes(), STRIPE_TIMESTAMP_SEP, body]);
772                        for cand in &stack_cands[..stack_len] {
773                            if constant_time_eq(&expected, cand) && matched.is_none() {
774                                matched = Some((secret.id.as_str(), expected));
775                            }
776                        }
777                        for cand in &extra_cands {
778                            if constant_time_eq(&expected, cand) && matched.is_none() {
779                                matched = Some((secret.id.as_str(), expected));
780                            }
781                        }
782                    }
783                    let (secret_id, digest): (&str, [u8; 32]) =
784                        matched.ok_or(WebhookRejectReason::InvalidSignature)?;
785                    (secret_id, Some(ts_val), digest)
786                }
787                WebhookScheme::Hex { prefix: sig_prefix }
788                | WebhookScheme::Base64 { prefix: sig_prefix } => {
789                    let trimmed_sig: &str = raw_sig_header.trim();
790                    let stripped: &str = match sig_prefix.as_deref() {
791                        Some(p) => trimmed_sig
792                            .strip_prefix(p)
793                            .ok_or(WebhookRejectReason::MalformedSignature)?,
794                        None => trimmed_sig,
795                    };
796                    let provided: [u8; 32] = match scheme {
797                        WebhookScheme::Hex { .. } => decode_hex_32(stripped)
798                            .ok_or(WebhookRejectReason::MalformedSignature)?,
799                        WebhookScheme::Base64 { .. } => decode_base64_32(stripped)
800                            .ok_or(WebhookRejectReason::MalformedSignature)?,
801                        WebhookScheme::StripeTimestamped { .. } => {
802                            return Err(WebhookRejectReason::MalformedSignature);
803                        }
804                    };
805                    let (raw_ts_opt, ts_val_opt): (Option<&str>, Option<u64>) =
806                        match timestamp_header.as_deref() {
807                            Some(ts_hdr) => {
808                                let raw_ts: &str = find_header_back_ref(headers, ts_hdr)
809                                    .map(str::trim)
810                                    .ok_or(WebhookRejectReason::MissingTimestamp)?;
811                                let parsed: u64 = raw_ts
812                                    .parse::<u64>()
813                                    .map_err(|_| WebhookRejectReason::MissingTimestamp)?;
814                                if *tolerance_secs > 0
815                                    && !is_timestamp_within_skew(parsed, now_secs, *tolerance_secs)
816                                {
817                                    return Err(WebhookRejectReason::TimestampOutOfRange);
818                                }
819                                (Some(raw_ts), Some(parsed))
820                            }
821                            None => (None, None),
822                        };
823                    let mut matched: Option<(&str, [u8; 32])> = None;
824                    for secret in secrets {
825                        let expected: [u8; 32] =
826                            match (raw_ts_opt, timestamp_payload_separator.as_deref()) {
827                                (Some(ts_s), Some(sep)) => {
828                                    secret
829                                        .key
830                                        .sign_parts(&[ts_s.as_bytes(), sep.as_bytes(), body])
831                                }
832                                _ => secret.key.sign(body),
833                            };
834                        if constant_time_eq(&expected, &provided) && matched.is_none() {
835                            matched = Some((secret.id.as_str(), expected));
836                        }
837                    }
838                    let (secret_id, digest): (&str, [u8; 32]) =
839                        matched.ok_or(WebhookRejectReason::InvalidSignature)?;
840                    (secret_id, ts_val_opt, digest)
841                }
842            };
843        if *replay_ttl_secs > 0 {
844            let nonce_bytes: &[u8] = match delivery_id {
845                Some(id) => id.as_bytes(),
846                None => &verified_digest,
847            };
848            let mut hasher: Sha256State = replay_prefix_state.clone();
849            hasher.update(nonce_bytes);
850            let replay_key: [u8; 32] = hasher.finalize();
851            if !replay_cache.check_and_insert(replay_key, now_secs, *replay_ttl_secs) {
852                return Err(WebhookRejectReason::ReplayDetected);
853            }
854        }
855        Ok(WebhookEvent {
856            endpoint_prefix: prefix.clone(),
857            secret_id: matched_secret_id.to_owned(),
858            timestamp: verified_ts,
859            delivery_id: delivery_id.map(str::to_owned),
860            body_len: body.len(),
861            verified: true,
862        })
863    }
864}
865
866/// Compiled webhook verifier engine backing [`WebhookPlugin`].
867impl WebhookVerifier {
868    /// Precompiles all endpoints, HMAC-SHA256 midstates, replay cache, and error wire buffers.
869    ///
870    /// # Arguments
871    ///
872    /// - `WebhookConfig` - Webhook endpoints and replay-cache settings.
873    ///
874    /// # Returns
875    ///
876    /// - `Self` - Ready webhook verifier.
877    pub fn new(config: WebhookConfig) -> Self {
878        let mut endpoints: Vec<CompiledEndpoint> = config
879            .get_endpoints()
880            .iter()
881            .filter(|ep: &&WebhookEndpoint| !ep.get_path_prefix().trim().is_empty())
882            .map(|ep: &WebhookEndpoint| {
883                let secrets: Vec<CompiledSecret> = ep
884                    .get_secrets()
885                    .iter()
886                    .map(|s: &WebhookSecret| CompiledSecret {
887                        id: s.get_id().clone(),
888                        key: HmacSha256Key::new(s.get_secret()),
889                    })
890                    .collect();
891                let prefix: String = normalize_prefix(ep.get_path_prefix());
892                let mut replay_prefix_state: Sha256State = Sha256State::new();
893                replay_prefix_state.update(prefix.as_bytes());
894                replay_prefix_state.update(REPLAY_SEPARATOR);
895                let scheme: WebhookScheme = ep.get_scheme().clone();
896                let timestamp_header: Option<String> = ep.try_get_timestamp_header();
897                let tolerance_secs: u64 = ep.get_tolerance_secs();
898                let replay_ttl_secs: u64 = ep.get_replay_ttl_secs();
899                let needs_now: bool = replay_ttl_secs > 0
900                    || (tolerance_secs > 0
901                        && (matches!(scheme, WebhookScheme::StripeTimestamped { .. })
902                            || timestamp_header.is_some()));
903                CompiledEndpoint {
904                    prefix,
905                    signature_header: ep.get_signature_header().to_ascii_lowercase(),
906                    scheme,
907                    secrets,
908                    timestamp_header,
909                    timestamp_payload_separator: ep.try_get_timestamp_payload_separator(),
910                    id_header: ep.try_get_id_header(),
911                    tolerance_secs,
912                    replay_ttl_secs,
913                    max_body_bytes: ep.get_max_body_bytes(),
914                    replay_prefix_state,
915                    needs_now,
916                }
917            })
918            .collect();
919        endpoints.sort_by_key(|ep: &CompiledEndpoint| Reverse(ep.prefix.len()));
920        let replay_cache: ReplayNonceCache = ReplayNonceCache::new(config.get_replay_max_entries());
921        let prebuilt_unauthorized_wire: Vec<u8> =
922            build_reject_wire(HttpStatus::Unauthorized, BODY_UNAUTHORIZED);
923        let prebuilt_replay_wire: Vec<u8> = build_reject_wire(HttpStatus::Conflict, BODY_REPLAY);
924        let prebuilt_too_large_wire: Vec<u8> =
925            build_reject_wire(HttpStatus::PayloadTooLarge, BODY_TOO_LARGE);
926        Self {
927            endpoints: Arc::new(endpoints),
928            replay_cache,
929            prebuilt_unauthorized_wire,
930            prebuilt_replay_wire,
931            prebuilt_too_large_wire,
932        }
933    }
934
935    /// Finds the longest matching compiled endpoint for `path`.
936    ///
937    /// # Arguments
938    ///
939    /// - `&str` - Incoming request path.
940    ///
941    /// # Returns
942    ///
943    /// - `Option<&CompiledEndpoint>` - Matched endpoint configuration.
944    #[inline]
945    pub(crate) fn match_endpoint(&self, path: &str) -> Option<&CompiledEndpoint> {
946        let Self { endpoints, .. } = self;
947        endpoints
948            .iter()
949            .find(|ep: &&CompiledEndpoint| path_matches_prefix(path, &ep.prefix))
950    }
951
952    /// Returns the shared [`ReplayNonceCache`].
953    ///
954    /// # Returns
955    ///
956    /// - `&ReplayNonceCache` - Replay nonce cache.
957    #[inline]
958    pub fn get_replay_cache(&self) -> &ReplayNonceCache {
959        let Self { replay_cache, .. } = self;
960        replay_cache
961    }
962
963    /// Maps a [`WebhookRejectReason`] to its prebuilt zero-allocation HTTP wire buffer.
964    ///
965    /// # Arguments
966    ///
967    /// - `WebhookRejectReason` - Rejection classification.
968    ///
969    /// # Returns
970    ///
971    /// - `&Vec<u8>` - Pre-serialized wire bytes.
972    #[inline]
973    pub fn reject_wire(&self, reason: WebhookRejectReason) -> &Vec<u8> {
974        let Self {
975            prebuilt_unauthorized_wire,
976            prebuilt_replay_wire,
977            prebuilt_too_large_wire,
978            ..
979        } = self;
980        match reason {
981            WebhookRejectReason::BodyTooLarge => prebuilt_too_large_wire,
982            WebhookRejectReason::ReplayDetected => prebuilt_replay_wire,
983            WebhookRejectReason::MissingSignature
984            | WebhookRejectReason::MalformedSignature
985            | WebhookRejectReason::MissingTimestamp
986            | WebhookRejectReason::TimestampOutOfRange
987            | WebhookRejectReason::InvalidSignature => prebuilt_unauthorized_wire,
988        }
989    }
990
991    /// Verifies a request context at an explicit `now_secs` timestamp and injects [`WebhookEvent`] on success.
992    ///
993    /// Returns `Ok(None)` when `ctx`'s path does not match any configured webhook endpoint.
994    ///
995    /// # Arguments
996    ///
997    /// - `&mut Context` - Incoming Hyperlane request context.
998    /// - `u64` - Current Unix epoch seconds.
999    ///
1000    /// # Returns
1001    ///
1002    /// - `Result<Option<WebhookEvent>, WebhookRejectReason>` - Verified event, `None` if unmatched, or rejection reason.
1003    pub fn verify_context_at(
1004        &self,
1005        ctx: &mut Context,
1006        now_secs: u64,
1007    ) -> Result<Option<WebhookEvent>, WebhookRejectReason> {
1008        let Self { replay_cache, .. } = self;
1009        let path: &str = ctx.get_request().get_path();
1010        let Some(endpoint) = self.match_endpoint(path) else {
1011            return Ok(None);
1012        };
1013        let event: WebhookEvent = endpoint.verify_at(
1014            ctx.get_request().get_headers(),
1015            ctx.get_request().get_body(),
1016            now_secs,
1017            replay_cache,
1018        )?;
1019        store_webhook_event_attr(ctx, event.clone());
1020        Ok(Some(event))
1021    }
1022
1023    /// Verifies a request context using [`webhook_now_secs`] lazily after endpoint matching.
1024    ///
1025    /// # Arguments
1026    ///
1027    /// - `&mut Context` - Incoming Hyperlane request context.
1028    ///
1029    /// # Returns
1030    ///
1031    /// - `Result<Option<WebhookEvent>, WebhookRejectReason>` - Verified event, `None` if unmatched, or rejection reason.
1032    #[inline]
1033    pub fn verify_context(
1034        &self,
1035        ctx: &mut Context,
1036    ) -> Result<Option<WebhookEvent>, WebhookRejectReason> {
1037        let Self { replay_cache, .. } = self;
1038        let path: &str = ctx.get_request().get_path();
1039        let Some(endpoint) = self.match_endpoint(path) else {
1040            return Ok(None);
1041        };
1042        let now_secs: u64 = if endpoint.needs_now {
1043            webhook_now_secs()
1044        } else {
1045            0
1046        };
1047        let event: WebhookEvent = endpoint.verify_at(
1048            ctx.get_request().get_headers(),
1049            ctx.get_request().get_body(),
1050            now_secs,
1051            replay_cache,
1052        )?;
1053        store_webhook_event_attr(ctx, event.clone());
1054        Ok(Some(event))
1055    }
1056
1057    /// Verifies a request context for [`WebhookHook`] without cloning [`WebhookEvent`].
1058    ///
1059    /// # Arguments
1060    ///
1061    /// - `&mut Context` - Incoming Hyperlane request context.
1062    ///
1063    /// # Returns
1064    ///
1065    /// - `Result<(), WebhookRejectReason>` - `Ok(())` when unmatched or verified; rejection reason otherwise.
1066    #[inline]
1067    pub(crate) fn verify_context_hook(&self, ctx: &mut Context) -> Result<(), WebhookRejectReason> {
1068        let Self { replay_cache, .. } = self;
1069        let path: &str = ctx.get_request().get_path();
1070        let Some(endpoint) = self.match_endpoint(path) else {
1071            return Ok(());
1072        };
1073        let now_secs: u64 = if endpoint.needs_now {
1074            webhook_now_secs()
1075        } else {
1076            0
1077        };
1078        let event: WebhookEvent = endpoint.verify_at(
1079            ctx.get_request().get_headers(),
1080            ctx.get_request().get_body(),
1081            now_secs,
1082            replay_cache,
1083        )?;
1084        store_webhook_event_attr(ctx, event);
1085        Ok(())
1086    }
1087}
1088
1089/// Process-wide singleton management for [`WebhookPlugin`].
1090impl WebhookPlugin {
1091    /// Initializes the global [`WebhookPlugin`] once with `config`.
1092    ///
1093    /// # Arguments
1094    ///
1095    /// - `WebhookConfig` - Webhook endpoints and replay-cache configuration.
1096    ///
1097    /// # Returns
1098    ///
1099    /// - `&'static Self` - Reference to the initialized global plugin.
1100    pub fn init(config: WebhookConfig) -> &'static Self {
1101        WEBHOOK_PLUGIN.get_or_init(|| Self {
1102            verifier: WebhookVerifier::new(config),
1103        })
1104    }
1105
1106    /// Returns the initialized global [`WebhookPlugin`], if initialized.
1107    ///
1108    /// # Returns
1109    ///
1110    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1111    #[inline]
1112    pub fn get() -> Option<&'static Self> {
1113        WEBHOOK_PLUGIN.get()
1114    }
1115
1116    /// Returns the compiled [`WebhookVerifier`].
1117    ///
1118    /// # Returns
1119    ///
1120    /// - `&WebhookVerifier` - Active verifier engine.
1121    #[inline]
1122    pub fn get_verifier(&self) -> &WebhookVerifier {
1123        let Self { verifier } = self;
1124        verifier
1125    }
1126}
1127
1128/// Implements [`ServerHook`] for [`WebhookHook`].
1129impl ServerHook for WebhookHook {
1130    /// Constructs a per-request [`WebhookHook`].
1131    ///
1132    /// # Arguments
1133    ///
1134    /// - `&mut Stream` - Connection stream.
1135    /// - `&mut Context` - Request context.
1136    ///
1137    /// # Returns
1138    ///
1139    /// - `Self` - Hook instance.
1140    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1141        Self
1142    }
1143
1144    /// Verifies matched inbound webhooks in constant time and short-circuits invalid/replayed requests.
1145    ///
1146    /// # Arguments
1147    ///
1148    /// - `Self` - Hook instance.
1149    /// - `&mut Stream` - Connection stream.
1150    /// - `&mut Context` - Request context.
1151    ///
1152    /// # Returns
1153    ///
1154    /// - `Status` - `Status::Reject` after sending prebuilt `401`/`409`/`413` wire bytes; `Status::Continue` otherwise.
1155    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1156        let Some(plugin) = WebhookPlugin::get() else {
1157            return Status::Continue;
1158        };
1159        let verifier: &WebhookVerifier = plugin.get_verifier();
1160        match verifier.verify_context_hook(ctx) {
1161            Ok(()) => Status::Continue,
1162            Err(reason) => {
1163                let _: Result<(), ResponseError> =
1164                    stream.try_send(verifier.reject_wire(reason)).await;
1165                Status::Reject
1166            }
1167        }
1168    }
1169}