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