Skip to main content

hyperlane_plugin_webhook/
fn.rs

1use super::*;
2
3/// Returns the current Unix epoch timestamp in whole seconds.
4///
5/// # Returns
6///
7/// - `u64` - Seconds since Unix epoch.
8#[inline]
9pub fn webhook_now_secs() -> u64 {
10    SystemTime::now()
11        .duration_since(UNIX_EPOCH)
12        .map(|dur: Duration| dur.as_secs())
13        .unwrap_or(0)
14}
15
16/// Compresses one 64-byte FIPS 180-4 SHA-256 block into `state`.
17///
18/// # Arguments
19///
20/// - `&mut [u32; 8]` - Running SHA-256 hash state.
21/// - `&[u8; 64]` - 512-bit input block.
22#[inline]
23pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
24    let mut w: [u32; 64] = [0u32; 64];
25    for i in 0..16usize {
26        w[i] = u32::from_be_bytes([
27            block[i * 4],
28            block[i * 4 + 1],
29            block[i * 4 + 2],
30            block[i * 4 + 3],
31        ]);
32    }
33    for i in 16..64usize {
34        let s0: u32 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
35        let s1: u32 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
36        w[i] = w[i - 16]
37            .wrapping_add(s0)
38            .wrapping_add(w[i - 7])
39            .wrapping_add(s1);
40    }
41    let mut a: u32 = state[0];
42    let mut b: u32 = state[1];
43    let mut c: u32 = state[2];
44    let mut d: u32 = state[3];
45    let mut e: u32 = state[4];
46    let mut f: u32 = state[5];
47    let mut g: u32 = state[6];
48    let mut h: u32 = state[7];
49    for i in 0..64usize {
50        let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
51        let ch: u32 = (e & f) ^ ((!e) & g);
52        let temp1: u32 = h
53            .wrapping_add(s1)
54            .wrapping_add(ch)
55            .wrapping_add(SHA256_K[i])
56            .wrapping_add(w[i]);
57        let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
58        let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
59        let temp2: u32 = s0.wrapping_add(maj);
60        h = g;
61        g = f;
62        f = e;
63        e = d.wrapping_add(temp1);
64        d = c;
65        c = b;
66        b = a;
67        a = temp1.wrapping_add(temp2);
68    }
69    state[0] = state[0].wrapping_add(a);
70    state[1] = state[1].wrapping_add(b);
71    state[2] = state[2].wrapping_add(c);
72    state[3] = state[3].wrapping_add(d);
73    state[4] = state[4].wrapping_add(e);
74    state[5] = state[5].wrapping_add(f);
75    state[6] = state[6].wrapping_add(g);
76    state[7] = state[7].wrapping_add(h);
77}
78
79/// Computes the FIPS 180-4 SHA-256 digest of `data` with zero heap allocations.
80///
81/// # Arguments
82///
83/// - `&[u8]` - Input byte slice.
84///
85/// # Returns
86///
87/// - `[u8; 32]` - 256-bit SHA-256 digest.
88#[inline]
89pub fn sha256(data: &[u8]) -> [u8; 32] {
90    let mut hasher: Sha256State = Sha256State::new();
91    hasher.update(data);
92    hasher.finalize()
93}
94
95/// Computes the RFC 4231 HMAC-SHA256 authentication tag of `data` under `key` with zero heap allocations.
96///
97/// # Arguments
98///
99/// - `&[u8]` - Secret key bytes.
100/// - `&[u8]` - Message payload bytes.
101///
102/// # Returns
103///
104/// - `[u8; 32]` - 256-bit HMAC-SHA256 digest.
105#[inline]
106pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
107    HmacSha256Key::new(key).sign(data)
108}
109
110/// Compares two byte slices in constant time with respect to their contents.
111///
112/// # Arguments
113///
114/// - `&[u8]` - First byte slice.
115/// - `&[u8]` - Second byte slice.
116///
117/// # Returns
118///
119/// - `bool` - `true` iff both slices have identical length and contents.
120#[inline]
121pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
122    if a.len() != b.len() {
123        return false;
124    }
125    let mut diff: u8 = 0;
126    for i in 0..a.len() {
127        diff |= a[i] ^ b[i];
128    }
129    diff == 0
130}
131
132/// Encodes a 32-byte digest into a 64-character lowercase hexadecimal string.
133///
134/// # Arguments
135///
136/// - `&[u8; 32]` - 256-bit digest.
137///
138/// # Returns
139///
140/// - `String` - 64-character lowercase hex string.
141pub fn encode_hex_32(bytes: &[u8; 32]) -> String {
142    let mut out: String = String::with_capacity(64);
143    for &byte in bytes {
144        out.push(HEX_DIGITS[(byte >> 4) as usize] as char);
145        out.push(HEX_DIGITS[(byte & 0x0F) as usize] as char);
146    }
147    out
148}
149
150/// Decodes a single ASCII hex nibble (`0-9`, `a-f`, `A-F`) into `0..=15`.
151///
152/// # Arguments
153///
154/// - `u8` - ASCII byte.
155///
156/// # Returns
157///
158/// - `Option<u8>` - Decoded 4-bit nibble.
159#[inline]
160pub(crate) fn decode_hex_nibble(b: u8) -> Option<u8> {
161    match b {
162        b'0'..=b'9' => Some(b - b'0'),
163        b'a'..=b'f' => Some(b - b'a' + 10),
164        b'A'..=b'F' => Some(b - b'A' + 10),
165        _ => None,
166    }
167}
168
169/// Decodes a 64-character ASCII hex digest directly onto the stack without allocating.
170///
171/// # Arguments
172///
173/// - `&str` - 64-character hex string.
174///
175/// # Returns
176///
177/// - `Option<[u8; 32]>` - Decoded 32-byte digest.
178#[inline]
179pub fn decode_hex_32(hex_str: &str) -> Option<[u8; 32]> {
180    let raw: &[u8] = hex_str.trim().as_bytes();
181    if raw.len() != 64 {
182        return None;
183    }
184    let mut out: [u8; 32] = [0u8; 32];
185    for i in 0..32usize {
186        let hi: u8 = decode_hex_nibble(raw[i * 2])?;
187        let lo: u8 = decode_hex_nibble(raw[i * 2 + 1])?;
188        out[i] = (hi << 4) | lo;
189    }
190    Some(out)
191}
192
193/// Encodes a 32-byte digest into standard padded RFC 4648 base64 (44 characters).
194///
195/// # Arguments
196///
197/// - `&[u8; 32]` - 256-bit digest.
198///
199/// # Returns
200///
201/// - `String` - Standard padded base64 string.
202pub fn encode_base64_32(bytes: &[u8; 32]) -> String {
203    let mut out: String = String::with_capacity(44);
204    let mut i: usize = 0;
205    while i + 3 <= 32 {
206        let triple: u32 =
207            ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
208        out.push(BASE64_ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
209        out.push(BASE64_ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
210        out.push(BASE64_ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
211        out.push(BASE64_ALPHABET[(triple & 0x3F) as usize] as char);
212        i += 3;
213    }
214    let pair: u32 = ((bytes[30] as u32) << 16) | ((bytes[31] as u32) << 8);
215    out.push(BASE64_ALPHABET[((pair >> 18) & 0x3F) as usize] as char);
216    out.push(BASE64_ALPHABET[((pair >> 12) & 0x3F) as usize] as char);
217    out.push(BASE64_ALPHABET[((pair >> 6) & 0x3F) as usize] as char);
218    out.push('=');
219    out
220}
221
222/// Decodes one RFC 4648 base64 character (supporting both standard `+/` and URL-safe `-_`).
223///
224/// # Arguments
225///
226/// - `u8` - ASCII base64 symbol byte.
227///
228/// # Returns
229///
230/// - `Option<u8>` - 6-bit value in `0..=63`.
231#[inline]
232pub(crate) fn decode_base64_char(b: u8) -> Option<u8> {
233    match b {
234        b'A'..=b'Z' => Some(b - b'A'),
235        b'a'..=b'z' => Some(b - b'a' + 26),
236        b'0'..=b'9' => Some(b - b'0' + 52),
237        b'+' | b'-' => Some(62),
238        b'/' | b'_' => Some(63),
239        _ => None,
240    }
241}
242
243/// Decodes a 32-byte RFC 4648 base64 digest (44-char padded or 43-char unpadded) onto the stack.
244///
245/// # Arguments
246///
247/// - `&str` - Base64-encoded 32-byte digest.
248///
249/// # Returns
250///
251/// - `Option<[u8; 32]>` - Decoded 32-byte digest.
252#[inline]
253pub fn decode_base64_32(encoded: &str) -> Option<[u8; 32]> {
254    let trimmed: &str = encoded.trim();
255    let unpadded: &[u8] = match trimmed.len() {
256        44 if trimmed.ends_with('=') => &trimmed.as_bytes()[..43],
257        43 => trimmed.as_bytes(),
258        _ => return None,
259    };
260    let mut out: [u8; 32] = [0u8; 32];
261    let mut out_idx: usize = 0;
262    let mut i: usize = 0;
263    while i < 40 {
264        let a: u32 = u32::from(decode_base64_char(unpadded[i])?);
265        let b: u32 = u32::from(decode_base64_char(unpadded[i + 1])?);
266        let c: u32 = u32::from(decode_base64_char(unpadded[i + 2])?);
267        let d: u32 = u32::from(decode_base64_char(unpadded[i + 3])?);
268        let triple: u32 = (a << 18) | (b << 12) | (c << 6) | d;
269        out[out_idx] = (triple >> 16) as u8;
270        out[out_idx + 1] = ((triple >> 8) & 0xFF) as u8;
271        out[out_idx + 2] = (triple & 0xFF) as u8;
272        out_idx += 3;
273        i += 4;
274    }
275    let a: u32 = u32::from(decode_base64_char(unpadded[40])?);
276    let b: u32 = u32::from(decode_base64_char(unpadded[41])?);
277    let c: u32 = u32::from(decode_base64_char(unpadded[42])?);
278    if (c & 0x03) != 0 {
279        return None;
280    }
281    let pair: u32 = (a << 18) | (b << 12) | (c << 6);
282    out[30] = (pair >> 16) as u8;
283    out[31] = ((pair >> 8) & 0xFF) as u8;
284    Some(out)
285}
286
287/// Checks whether `timestamp` lies within `±tolerance_secs` of `now_secs`.
288///
289/// # Arguments
290///
291/// - `u64` - Candidate Unix timestamp in seconds.
292/// - `u64` - Current Unix timestamp in seconds.
293/// - `u64` - Maximum allowed skew in seconds.
294///
295/// # Returns
296///
297/// - `bool` - `true` when within tolerance.
298#[inline]
299pub(crate) fn is_timestamp_within_skew(timestamp: u64, now_secs: u64, tolerance_secs: u64) -> bool {
300    timestamp.abs_diff(now_secs) <= tolerance_secs
301}
302
303/// Looks up a header value without cloning using an `O(1)` lowercase fast path.
304///
305/// # Arguments
306///
307/// - `&'a RequestHeaders` - Request header map.
308/// - `&str` - Canonical lowercase header name.
309///
310/// # Returns
311///
312/// - `Option<&'a str>` - Last header value slice if present.
313#[inline]
314pub(crate) fn find_header_back_ref<'a>(
315    headers: &'a RequestHeaders,
316    lower_name: &str,
317) -> Option<&'a str> {
318    if let Some(vals) = headers.get(lower_name) {
319        return vals.back().map(String::as_str);
320    }
321    headers
322        .iter()
323        .find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
324        .and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
325}
326
327/// Normalizes a path prefix by stripping trailing slashes while preserving `"/"`.
328///
329/// # Arguments
330///
331/// - `&str` - Raw path prefix.
332///
333/// # Returns
334///
335/// - `String` - Normalized prefix.
336pub(crate) fn normalize_prefix(prefix: &str) -> String {
337    let trimmed: &str = prefix.trim();
338    if trimmed == "/" {
339        return "/".to_owned();
340    }
341    let stripped: &str = trimmed.trim_end_matches('/');
342    if stripped.is_empty() {
343        "/".to_owned()
344    } else {
345        stripped.to_owned()
346    }
347}
348
349/// Reports whether `path` matches normalized `prefix` on a segment boundary.
350///
351/// # Arguments
352///
353/// - `&str` - Incoming request path.
354/// - `&str` - Normalized prefix.
355///
356/// # Returns
357///
358/// - `bool` - `true` when matched.
359#[inline]
360pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
361    if prefix == "/" {
362        return true;
363    }
364    let Some(rest) = path.strip_prefix(prefix) else {
365        return false;
366    };
367    rest.is_empty() || rest.starts_with('/')
368}
369
370/// Computes the 32-byte replay cache digest keying `(endpoint_prefix, nonce_bytes)`.
371///
372/// # Arguments
373///
374/// - `&str` - Matched endpoint prefix.
375/// - `&[u8]` - Delivery ID bytes or verified signature digest bytes.
376///
377/// # Returns
378///
379/// - `[u8; 32]` - Collision-resistant replay cache key.
380#[inline]
381pub(crate) fn compute_replay_digest(prefix: &str, nonce: &[u8]) -> [u8; 32] {
382    let mut hasher: Sha256State = Sha256State::new();
383    hasher.update(prefix.as_bytes());
384    hasher.update(REPLAY_SEPARATOR);
385    hasher.update(nonce);
386    hasher.finalize()
387}
388
389/// Builds a pre-serialized static rejection HTTP wire buffer.
390///
391/// # Arguments
392///
393/// - `HttpStatus` - Rejection HTTP status code.
394/// - `&[u8]` - Static plain-text body bytes.
395///
396/// # Returns
397///
398/// - `ResponseData` - Pre-serialized wire bytes.
399pub(crate) fn build_reject_wire(status: HttpStatus, body: &[u8]) -> ResponseData {
400    let mut resp: Response = Response::default();
401    resp.set_status_code(status.code())
402        .set_header(CONTENT_TYPE, REJECT_CONTENT_TYPE)
403        .set_body(body);
404    resp.build()
405}