hyperlane-plugin-webhook 22.14.1

A production inbound HTTP webhook verification plugin for the Hyperlane framework featuring zero-allocation precomputed-midstate pure-Rust HMAC-SHA256 (Hex, Base64, and Stripe-style timestamped schemes), per-route secret rotation, timestamp skew enforcement, 64-shard bounded TTL replay-nonce caching, and verified WebhookEvent Context injection.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use super::*;

/// Returns the current Unix epoch timestamp in whole seconds.
///
/// # Returns
///
/// - `u64` - Seconds since Unix epoch.
#[inline]
pub fn webhook_now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_secs())
        .unwrap_or(0)
}

/// Compresses one 64-byte FIPS 180-4 SHA-256 block into `state`.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running SHA-256 hash state.
/// - `&[u8; 64]` - 512-bit input block.
#[inline]
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
    let mut w: [u32; 64] = [0u32; 64];
    for i in 0..16usize {
        w[i] = u32::from_be_bytes([
            block[i * 4],
            block[i * 4 + 1],
            block[i * 4 + 2],
            block[i * 4 + 3],
        ]);
    }
    for i in 16..64usize {
        let s0: u32 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
        let s1: u32 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
        w[i] = w[i - 16]
            .wrapping_add(s0)
            .wrapping_add(w[i - 7])
            .wrapping_add(s1);
    }
    let mut a: u32 = state[0];
    let mut b: u32 = state[1];
    let mut c: u32 = state[2];
    let mut d: u32 = state[3];
    let mut e: u32 = state[4];
    let mut f: u32 = state[5];
    let mut g: u32 = state[6];
    let mut h: u32 = state[7];
    for i in 0..64usize {
        let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
        let ch: u32 = (e & f) ^ ((!e) & g);
        let temp1: u32 = h
            .wrapping_add(s1)
            .wrapping_add(ch)
            .wrapping_add(SHA256_K[i])
            .wrapping_add(w[i]);
        let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
        let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
        let temp2: u32 = s0.wrapping_add(maj);
        h = g;
        g = f;
        f = e;
        e = d.wrapping_add(temp1);
        d = c;
        c = b;
        b = a;
        a = temp1.wrapping_add(temp2);
    }
    state[0] = state[0].wrapping_add(a);
    state[1] = state[1].wrapping_add(b);
    state[2] = state[2].wrapping_add(c);
    state[3] = state[3].wrapping_add(d);
    state[4] = state[4].wrapping_add(e);
    state[5] = state[5].wrapping_add(f);
    state[6] = state[6].wrapping_add(g);
    state[7] = state[7].wrapping_add(h);
}

/// Computes the FIPS 180-4 SHA-256 digest of `data` with zero heap allocations.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit SHA-256 digest.
#[inline]
pub fn sha256(data: &[u8]) -> [u8; 32] {
    let mut hasher: Sha256State = Sha256State::new();
    hasher.update(data);
    hasher.finalize()
}

/// Computes the RFC 4231 HMAC-SHA256 authentication tag of `data` under `key` with zero heap allocations.
///
/// # Arguments
///
/// - `&[u8]` - Secret key bytes.
/// - `&[u8]` - Message payload bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC-SHA256 digest.
#[inline]
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    HmacSha256Key::new(key).sign(data)
}

/// Compares two byte slices in constant time with respect to their contents.
///
/// # Arguments
///
/// - `&[u8]` - First byte slice.
/// - `&[u8]` - Second byte slice.
///
/// # Returns
///
/// - `bool` - `true` iff both slices have identical length and contents.
#[inline]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for i in 0..a.len() {
        diff |= a[i] ^ b[i];
    }
    diff == 0
}

/// Encodes a 32-byte digest into a 64-character lowercase hexadecimal string.
///
/// # Arguments
///
/// - `&[u8; 32]` - 256-bit digest.
///
/// # Returns
///
/// - `String` - 64-character lowercase hex string.
pub fn encode_hex_32(bytes: &[u8; 32]) -> String {
    let mut out: String = String::with_capacity(64);
    for &byte in bytes {
        out.push(HEX_DIGITS[(byte >> 4) as usize] as char);
        out.push(HEX_DIGITS[(byte & 0x0F) as usize] as char);
    }
    out
}

/// Decodes a single ASCII hex nibble (`0-9`, `a-f`, `A-F`) into `0..=15`.
///
/// # Arguments
///
/// - `u8` - ASCII byte.
///
/// # Returns
///
/// - `Option<u8>` - Decoded 4-bit nibble.
#[inline]
pub(crate) fn decode_hex_nibble(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// Decodes a 64-character ASCII hex digest directly onto the stack without allocating.
///
/// # Arguments
///
/// - `&str` - 64-character hex string.
///
/// # Returns
///
/// - `Option<[u8; 32]>` - Decoded 32-byte digest.
#[inline]
pub fn decode_hex_32(hex_str: &str) -> Option<[u8; 32]> {
    let raw: &[u8] = hex_str.trim().as_bytes();
    if raw.len() != 64 {
        return None;
    }
    let mut out: [u8; 32] = [0u8; 32];
    for i in 0..32usize {
        let hi: u8 = decode_hex_nibble(raw[i * 2])?;
        let lo: u8 = decode_hex_nibble(raw[i * 2 + 1])?;
        out[i] = (hi << 4) | lo;
    }
    Some(out)
}

/// Encodes a 32-byte digest into standard padded RFC 4648 base64 (44 characters).
///
/// # Arguments
///
/// - `&[u8; 32]` - 256-bit digest.
///
/// # Returns
///
/// - `String` - Standard padded base64 string.
pub fn encode_base64_32(bytes: &[u8; 32]) -> String {
    let mut out: String = String::with_capacity(44);
    let mut i: usize = 0;
    while i + 3 <= 32 {
        let triple: u32 =
            ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
        out.push(BASE64_ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
        out.push(BASE64_ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
        out.push(BASE64_ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
        out.push(BASE64_ALPHABET[(triple & 0x3F) as usize] as char);
        i += 3;
    }
    let pair: u32 = ((bytes[30] as u32) << 16) | ((bytes[31] as u32) << 8);
    out.push(BASE64_ALPHABET[((pair >> 18) & 0x3F) as usize] as char);
    out.push(BASE64_ALPHABET[((pair >> 12) & 0x3F) as usize] as char);
    out.push(BASE64_ALPHABET[((pair >> 6) & 0x3F) as usize] as char);
    out.push('=');
    out
}

/// Decodes one RFC 4648 base64 character (supporting both standard `+/` and URL-safe `-_`).
///
/// # Arguments
///
/// - `u8` - ASCII base64 symbol byte.
///
/// # Returns
///
/// - `Option<u8>` - 6-bit value in `0..=63`.
#[inline]
pub(crate) fn decode_base64_char(b: u8) -> Option<u8> {
    match b {
        b'A'..=b'Z' => Some(b - b'A'),
        b'a'..=b'z' => Some(b - b'a' + 26),
        b'0'..=b'9' => Some(b - b'0' + 52),
        b'+' | b'-' => Some(62),
        b'/' | b'_' => Some(63),
        _ => None,
    }
}

/// Decodes a 32-byte RFC 4648 base64 digest (44-char padded or 43-char unpadded) onto the stack.
///
/// # Arguments
///
/// - `&str` - Base64-encoded 32-byte digest.
///
/// # Returns
///
/// - `Option<[u8; 32]>` - Decoded 32-byte digest.
#[inline]
pub fn decode_base64_32(encoded: &str) -> Option<[u8; 32]> {
    let trimmed: &str = encoded.trim();
    let unpadded: &[u8] = match trimmed.len() {
        44 if trimmed.ends_with('=') => &trimmed.as_bytes()[..43],
        43 => trimmed.as_bytes(),
        _ => return None,
    };
    let mut out: [u8; 32] = [0u8; 32];
    let mut out_idx: usize = 0;
    let mut i: usize = 0;
    while i < 40 {
        let a: u32 = u32::from(decode_base64_char(unpadded[i])?);
        let b: u32 = u32::from(decode_base64_char(unpadded[i + 1])?);
        let c: u32 = u32::from(decode_base64_char(unpadded[i + 2])?);
        let d: u32 = u32::from(decode_base64_char(unpadded[i + 3])?);
        let triple: u32 = (a << 18) | (b << 12) | (c << 6) | d;
        out[out_idx] = (triple >> 16) as u8;
        out[out_idx + 1] = ((triple >> 8) & 0xFF) as u8;
        out[out_idx + 2] = (triple & 0xFF) as u8;
        out_idx += 3;
        i += 4;
    }
    let a: u32 = u32::from(decode_base64_char(unpadded[40])?);
    let b: u32 = u32::from(decode_base64_char(unpadded[41])?);
    let c: u32 = u32::from(decode_base64_char(unpadded[42])?);
    if (c & 0x03) != 0 {
        return None;
    }
    let pair: u32 = (a << 18) | (b << 12) | (c << 6);
    out[30] = (pair >> 16) as u8;
    out[31] = ((pair >> 8) & 0xFF) as u8;
    Some(out)
}

/// Checks whether `timestamp` lies within `±tolerance_secs` of `now_secs`.
///
/// # Arguments
///
/// - `u64` - Candidate Unix timestamp in seconds.
/// - `u64` - Current Unix timestamp in seconds.
/// - `u64` - Maximum allowed skew in seconds.
///
/// # Returns
///
/// - `bool` - `true` when within tolerance.
#[inline]
pub(crate) fn is_timestamp_within_skew(timestamp: u64, now_secs: u64, tolerance_secs: u64) -> bool {
    timestamp.abs_diff(now_secs) <= tolerance_secs
}

/// Looks up a header value without cloning using an `O(1)` lowercase fast path.
///
/// # Arguments
///
/// - `&'a RequestHeaders` - Request header map.
/// - `&str` - Canonical lowercase header name.
///
/// # Returns
///
/// - `Option<&'a str>` - Last header value slice if present.
#[inline]
pub(crate) fn find_header_back_ref<'a>(
    headers: &'a RequestHeaders,
    lower_name: &str,
) -> Option<&'a str> {
    if let Some(vals) = headers.get(lower_name) {
        return vals.back().map(String::as_str);
    }
    headers
        .iter()
        .find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
        .and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}

/// Normalizes a path prefix by stripping trailing slashes while preserving `"/"`.
///
/// # Arguments
///
/// - `&str` - Raw path prefix.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    let stripped: &str = trimmed.trim_end_matches('/');
    if stripped.is_empty() {
        "/".to_owned()
    } else {
        stripped.to_owned()
    }
}

/// Reports whether `path` matches normalized `prefix` on a segment boundary.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized prefix.
///
/// # Returns
///
/// - `bool` - `true` when matched.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == "/" {
        return true;
    }
    let Some(rest) = path.strip_prefix(prefix) else {
        return false;
    };
    rest.is_empty() || rest.starts_with('/')
}

/// Computes the 32-byte replay cache digest keying `(endpoint_prefix, nonce_bytes)`.
///
/// # Arguments
///
/// - `&str` - Matched endpoint prefix.
/// - `&[u8]` - Delivery ID bytes or verified signature digest bytes.
///
/// # Returns
///
/// - `[u8; 32]` - Collision-resistant replay cache key.
#[inline]
pub(crate) fn compute_replay_digest(prefix: &str, nonce: &[u8]) -> [u8; 32] {
    let mut hasher: Sha256State = Sha256State::new();
    hasher.update(prefix.as_bytes());
    hasher.update(REPLAY_SEPARATOR);
    hasher.update(nonce);
    hasher.finalize()
}

/// Builds a pre-serialized static rejection HTTP wire buffer.
///
/// # Arguments
///
/// - `HttpStatus` - Rejection HTTP status code.
/// - `&[u8]` - Static plain-text body bytes.
///
/// # Returns
///
/// - `ResponseData` - Pre-serialized wire bytes.
pub(crate) fn build_reject_wire(status: HttpStatus, body: &[u8]) -> ResponseData {
    let mut resp: Response = Response::default();
    resp.set_status_code(status.code())
        .set_header(CONTENT_TYPE, REJECT_CONTENT_TYPE)
        .set_body(body);
    resp.build()
}