hyperlane_plugin_webhook/struct.rs
1use super::*;
2
3/// Streaming FIPS 180-4 SHA-256 hasher with zero heap allocations.
4#[derive(Clone)]
5pub struct Sha256State {
6 /// Eight 32-bit working hash state words.
7 pub(crate) state: [u32; 8],
8 /// Partial 64-byte input block accumulator.
9 pub(crate) buf: [u8; 64],
10 /// Number of valid bytes currently buffered in `buf`.
11 pub(crate) buf_len: usize,
12 /// Total message length absorbed in bytes.
13 pub(crate) total_bytes: u64,
14}
15
16/// Precomputed HMAC-SHA256 key holding ipad and opad midstates for zero-allocation signing/verification.
17#[derive(Clone)]
18pub struct HmacSha256Key {
19 /// SHA-256 state after compressing the 64-byte `key ^ 0x36` inner pad block.
20 pub(crate) ipad_state: [u32; 8],
21 /// SHA-256 state after compressing the 64-byte `key ^ 0x5c` outer pad block.
22 pub(crate) opad_state: [u32; 8],
23}
24
25/// Named secret key participating in per-route webhook secret rotation.
26#[derive(Clone, Data, Eq, PartialEq)]
27pub struct WebhookSecret {
28 /// Logical key identifier surfaced in [`WebhookEvent`] upon successful verification.
29 pub(crate) id: String,
30 /// Raw HMAC-SHA256 signing secret bytes.
31 pub(crate) secret: Vec<u8>,
32}
33
34/// Verification rules for one inbound webhook route or prefix.
35#[derive(Clone, Data, Debug, Eq, PartialEq)]
36pub struct WebhookEndpoint {
37 /// Route path or segment-bounded prefix (for example `"/webhooks/stripe"`).
38 pub(crate) path_prefix: String,
39 /// Request header carrying the webhook signature (stored lowercased).
40 pub(crate) signature_header: String,
41 /// Signature framing and encoding scheme.
42 pub(crate) scheme: WebhookScheme,
43 /// Active signing secrets checked in constant time for zero-downtime key rotation.
44 pub(crate) secrets: Vec<WebhookSecret>,
45 /// Optional separate Unix-seconds timestamp header for `Hex`/`Base64` schemes.
46 #[get(type(clone))]
47 pub(crate) timestamp_header: Option<String>,
48 /// Optional separator when signing `<timestamp><sep><body>` with a separate `timestamp_header`.
49 #[get(type(clone))]
50 pub(crate) timestamp_payload_separator: Option<String>,
51 /// Optional delivery nonce header (for example `X-GitHub-Delivery`) keyed into the replay cache.
52 #[get(type(clone))]
53 pub(crate) id_header: Option<String>,
54 /// Maximum allowed absolute clock skew in seconds (`0` disables skew checks when no timestamp is required).
55 #[get(type(copy))]
56 pub(crate) tolerance_secs: u64,
57 /// Replay-nonce retention TTL in seconds (`0` disables replay caching for this endpoint).
58 #[get(type(copy))]
59 pub(crate) replay_ttl_secs: u64,
60 /// Maximum inbound body length in bytes accepted for verification.
61 #[get(type(copy))]
62 pub(crate) max_body_bytes: usize,
63}
64
65/// Top-level configuration for [`WebhookVerifier`] and [`WebhookPlugin`].
66#[derive(Clone, Data, Debug, Eq, PartialEq)]
67pub struct WebhookConfig {
68 /// Configured webhook endpoints (matched longest-prefix first).
69 pub(crate) endpoints: Vec<WebhookEndpoint>,
70 /// Maximum tracked replay nonces across all 64 shards.
71 #[get(type(copy))]
72 pub(crate) replay_max_entries: usize,
73}
74
75/// Verified webhook delivery metadata injected into Hyperlane [`Context`] under [`ATTR_WEBHOOK_EVENT`].
76#[derive(Clone, Data, Debug, Eq, PartialEq)]
77pub struct WebhookEvent {
78 /// Matched configured endpoint prefix.
79 pub(crate) endpoint_prefix: String,
80 /// Identifier of the active [`WebhookSecret`] that authenticated the payload.
81 pub(crate) secret_id: String,
82 /// Verified Unix epoch timestamp in seconds, when supplied by the scheme or timestamp header.
83 #[get(type(copy))]
84 pub(crate) timestamp: Option<u64>,
85 /// Extracted delivery identifier header value, when present.
86 #[get(type(clone))]
87 pub(crate) delivery_id: Option<String>,
88 /// Verified raw request body length in bytes.
89 #[get(type(copy))]
90 pub(crate) body_len: usize,
91 /// Always `true` when produced by a passing verification.
92 #[get(type(copy))]
93 pub(crate) verified: bool,
94}
95
96/// Precompiled named secret with precomputed HMAC-SHA256 midstates.
97#[derive(Clone)]
98pub(crate) struct CompiledSecret {
99 /// Logical key identifier.
100 pub(crate) id: String,
101 /// Precomputed zero-allocation HMAC-SHA256 key.
102 pub(crate) key: HmacSha256Key,
103}
104
105/// Zero-cost identity hasher reading 8 bytes directly from already-uniform SHA-256 replay digests.
106#[derive(Clone, Copy, Default)]
107pub(crate) struct DigestIdentityHasher {
108 /// Extracted 64-bit hash word.
109 pub(crate) state: u64,
110}
111
112/// Cache-line-aligned replay cache shard avoiding false sharing across worker threads.
113#[repr(align(64))]
114pub(crate) struct ReplayShard {
115 /// Per-shard mutex guarding the digest expiration table.
116 pub(crate) map: Mutex<ReplayShardMap>,
117}
118
119/// Precompiled endpoint entry ready for hot-path verification.
120#[derive(Clone)]
121pub(crate) struct CompiledEndpoint {
122 /// Normalized path prefix.
123 pub(crate) prefix: String,
124 /// Lowercased signature header name.
125 pub(crate) signature_header: String,
126 /// Signature framing scheme.
127 pub(crate) scheme: WebhookScheme,
128 /// Precompiled active signing secrets.
129 pub(crate) secrets: Vec<CompiledSecret>,
130 /// Optional lowercased separate timestamp header name.
131 pub(crate) timestamp_header: Option<String>,
132 /// Optional separator when signing `<timestamp><sep><body>`.
133 pub(crate) timestamp_payload_separator: Option<String>,
134 /// Optional lowercased delivery ID header name.
135 pub(crate) id_header: Option<String>,
136 /// Timestamp skew window in seconds.
137 pub(crate) tolerance_secs: u64,
138 /// Replay-nonce retention TTL in seconds.
139 pub(crate) replay_ttl_secs: u64,
140 /// Maximum accepted payload length in bytes.
141 pub(crate) max_body_bytes: usize,
142 /// Pre-seeded SHA-256 state after absorbing `prefix || REPLAY_SEPARATOR`.
143 pub(crate) replay_prefix_state: Sha256State,
144 /// Precomputed flag indicating whether verification requires wall-clock seconds.
145 pub(crate) needs_now: bool,
146}
147
148/// Shared interior state of the 64-way sharded bounded [`ReplayNonceCache`].
149pub(crate) struct ReplayNonceCacheInner {
150 /// Maximum tracked nonces across all 64 shards.
151 pub(crate) max_entries: usize,
152 /// Lock-free active entry count.
153 pub(crate) count: AtomicUsize,
154 /// 64-way lock-striped digest tables.
155 pub(crate) shards: Box<[ReplayShard; REPLAY_SHARD_COUNT]>,
156}
157
158/// High-concurrency 64-way sharded bounded TTL replay-nonce cache.
159#[derive(Clone)]
160pub struct ReplayNonceCache {
161 /// Shared sharded cache state.
162 pub(crate) inner: Arc<ReplayNonceCacheInner>,
163}
164
165/// Compiled inbound webhook verification engine backing [`WebhookPlugin`].
166#[derive(Clone)]
167pub struct WebhookVerifier {
168 /// Precompiled endpoints sorted longest-prefix first.
169 pub(crate) endpoints: Arc<Vec<CompiledEndpoint>>,
170 /// 64-shard bounded replay-nonce cache.
171 pub(crate) replay_cache: ReplayNonceCache,
172 /// Prebuilt `401 Unauthorized` wire bytes.
173 pub(crate) prebuilt_unauthorized_wire: Vec<u8>,
174 /// Prebuilt `409 Conflict` wire bytes for detected replays.
175 pub(crate) prebuilt_replay_wire: Vec<u8>,
176 /// Prebuilt `413 Payload Too Large` wire bytes.
177 pub(crate) prebuilt_too_large_wire: Vec<u8>,
178}
179
180/// Process-wide [`WebhookPlugin`] singleton holding a [`WebhookVerifier`].
181#[derive(Clone)]
182pub struct WebhookPlugin {
183 /// Compiled webhook verifier.
184 pub(crate) verifier: WebhookVerifier,
185}
186
187/// Opt-in request middleware verifying inbound webhook signatures and injecting [`WebhookEvent`].
188#[derive(Clone, Copy, Debug, Default)]
189#[hyperlane::request_middleware(-58)]
190pub struct WebhookHook;