Skip to main content

hyperlane_plugin_auth/
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 auth_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/// Borrows the last value of a lowercased HTTP request header without heap allocation.
17///
18/// # Arguments
19///
20/// - `&'a Request` - Incoming HTTP request.
21/// - `&str` - Lowercased header key name.
22///
23/// # Returns
24///
25/// - `Option<&'a str>` - Borrowed last header value, if present.
26#[inline(always)]
27pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
28    req.get_headers()
29        .get(lower_key)
30        .and_then(|values: &VecDeque<String>| values.back())
31        .map(String::as_str)
32}
33
34/// Converts eight 32-bit big-endian SHA-256 state words into a 32-byte digest.
35///
36/// # Arguments
37///
38/// - `[u32; 8]` - Final SHA-256 hash state words.
39///
40/// # Returns
41///
42/// - `[u8; 32]` - 256-bit digest in big-endian byte order.
43#[inline(always)]
44pub(crate) fn sha256_words_to_bytes(state: [u32; 8]) -> [u8; 32] {
45    let mut out: [u8; 32] = [0u8; 32];
46    out[0..4].copy_from_slice(&state[0].to_be_bytes());
47    out[4..8].copy_from_slice(&state[1].to_be_bytes());
48    out[8..12].copy_from_slice(&state[2].to_be_bytes());
49    out[12..16].copy_from_slice(&state[3].to_be_bytes());
50    out[16..20].copy_from_slice(&state[4].to_be_bytes());
51    out[20..24].copy_from_slice(&state[5].to_be_bytes());
52    out[24..28].copy_from_slice(&state[6].to_be_bytes());
53    out[28..32].copy_from_slice(&state[7].to_be_bytes());
54    out
55}
56
57/// Reports whether the running `aarch64` CPU supports ARMv8 SHA-256 crypto extensions.
58///
59/// # Returns
60///
61/// - `bool` - `true` when hardware `sha2` instructions are available.
62#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
63#[inline(always)]
64pub(crate) fn has_aarch64_sha2() -> bool {
65    is_aarch64_feature_detected!("sha2")
66}
67
68/// Executes 4 ARMv8 hardware SHA-256 rounds for message vector `m` and round constants at `k_off`.
69///
70/// # Arguments
71///
72/// - `&mut uint32x4_t` - Working state words `[a, b, c, d]`.
73/// - `&mut uint32x4_t` - Working state words `[e, f, g, h]`.
74/// - `uint32x4_t` - Four scheduled message words.
75/// - `usize` - Starting index into [`SHA256_K`].
76#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
77#[target_feature(enable = "sha2")]
78#[inline]
79pub(crate) unsafe fn sha256_round4_aarch64(
80    abcd: &mut uint32x4_t,
81    efgh: &mut uint32x4_t,
82    m: uint32x4_t,
83    k_off: usize,
84) {
85    unsafe {
86        let k: uint32x4_t = vld1q_u32(SHA256_K.as_ptr().add(k_off));
87        let wk: uint32x4_t = vaddq_u32(m, k);
88        let old_abcd: uint32x4_t = *abcd;
89        *abcd = vsha256hq_u32(*abcd, *efgh, wk);
90        *efgh = vsha256h2q_u32(*efgh, old_abcd, wk);
91    }
92}
93
94/// Compresses one pre-loaded 16-word message block in NEON registers using ARMv8 SHA-256 instructions.
95///
96/// # Arguments
97///
98/// - `&mut uint32x4_t` - Running hash state `[H0, H1, H2, H3]`.
99/// - `&mut uint32x4_t` - Running hash state `[H4, H5, H6, H7]`.
100/// - `uint32x4_t` - Message words `w[0..4]`.
101/// - `uint32x4_t` - Message words `w[4..8]`.
102/// - `uint32x4_t` - Message words `w[8..12]`.
103/// - `uint32x4_t` - Message words `w[12..16]`.
104#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
105#[target_feature(enable = "sha2")]
106#[inline]
107pub(crate) unsafe fn sha256_compress_regs_aarch64(
108    abcd: &mut uint32x4_t,
109    efgh: &mut uint32x4_t,
110    mut m0: uint32x4_t,
111    mut m1: uint32x4_t,
112    mut m2: uint32x4_t,
113    mut m3: uint32x4_t,
114) {
115    let abcd_save: uint32x4_t = *abcd;
116    let efgh_save: uint32x4_t = *efgh;
117    unsafe {
118        sha256_round4_aarch64(abcd, efgh, m0, 0);
119        m0 = vsha256su1q_u32(vsha256su0q_u32(m0, m1), m2, m3);
120        sha256_round4_aarch64(abcd, efgh, m1, 4);
121        m1 = vsha256su1q_u32(vsha256su0q_u32(m1, m2), m3, m0);
122        sha256_round4_aarch64(abcd, efgh, m2, 8);
123        m2 = vsha256su1q_u32(vsha256su0q_u32(m2, m3), m0, m1);
124        sha256_round4_aarch64(abcd, efgh, m3, 12);
125        m3 = vsha256su1q_u32(vsha256su0q_u32(m3, m0), m1, m2);
126        sha256_round4_aarch64(abcd, efgh, m0, 16);
127        m0 = vsha256su1q_u32(vsha256su0q_u32(m0, m1), m2, m3);
128        sha256_round4_aarch64(abcd, efgh, m1, 20);
129        m1 = vsha256su1q_u32(vsha256su0q_u32(m1, m2), m3, m0);
130        sha256_round4_aarch64(abcd, efgh, m2, 24);
131        m2 = vsha256su1q_u32(vsha256su0q_u32(m2, m3), m0, m1);
132        sha256_round4_aarch64(abcd, efgh, m3, 28);
133        m3 = vsha256su1q_u32(vsha256su0q_u32(m3, m0), m1, m2);
134        sha256_round4_aarch64(abcd, efgh, m0, 32);
135        m0 = vsha256su1q_u32(vsha256su0q_u32(m0, m1), m2, m3);
136        sha256_round4_aarch64(abcd, efgh, m1, 36);
137        m1 = vsha256su1q_u32(vsha256su0q_u32(m1, m2), m3, m0);
138        sha256_round4_aarch64(abcd, efgh, m2, 40);
139        m2 = vsha256su1q_u32(vsha256su0q_u32(m2, m3), m0, m1);
140        sha256_round4_aarch64(abcd, efgh, m3, 44);
141        m3 = vsha256su1q_u32(vsha256su0q_u32(m3, m0), m1, m2);
142        sha256_round4_aarch64(abcd, efgh, m0, 48);
143        sha256_round4_aarch64(abcd, efgh, m1, 52);
144        sha256_round4_aarch64(abcd, efgh, m2, 56);
145        sha256_round4_aarch64(abcd, efgh, m3, 60);
146        *abcd = vaddq_u32(*abcd, abcd_save);
147        *efgh = vaddq_u32(*efgh, efgh_save);
148    }
149}
150
151/// Loads one 64-byte big-endian block and compresses it into NEON state registers.
152///
153/// # Arguments
154///
155/// - `&mut uint32x4_t` - Running hash state `[H0, H1, H2, H3]`.
156/// - `&mut uint32x4_t` - Running hash state `[H4, H5, H6, H7]`.
157/// - `&[u8; 64]` - Input 64-byte message block.
158#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
159#[target_feature(enable = "sha2")]
160#[inline]
161pub(crate) unsafe fn sha256_compress_block_regs_aarch64(
162    abcd: &mut uint32x4_t,
163    efgh: &mut uint32x4_t,
164    block: &[u8; 64],
165) {
166    unsafe {
167        let ptr: *const u8 = block.as_ptr();
168        let m0: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr)));
169        let m1: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(16))));
170        let m2: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(32))));
171        let m3: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(48))));
172        sha256_compress_regs_aarch64(abcd, efgh, m0, m1, m2, m3);
173    }
174}
175
176/// Compresses one 64-byte block into `state` using ARMv8 SHA-256 hardware instructions.
177///
178/// # Arguments
179///
180/// - `&mut [u32; 8]` - Running SHA-256 state.
181/// - `&[u8; 64]` - Input 64-byte message block.
182#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
183#[target_feature(enable = "sha2")]
184pub(crate) unsafe fn sha256_compress_aarch64(state: &mut [u32; 8], block: &[u8; 64]) {
185    unsafe {
186        let mut abcd: uint32x4_t = vld1q_u32(state.as_ptr());
187        let mut efgh: uint32x4_t = vld1q_u32(state.as_ptr().add(4));
188        sha256_compress_block_regs_aarch64(&mut abcd, &mut efgh, block);
189        vst1q_u32(state.as_mut_ptr(), abcd);
190        vst1q_u32(state.as_mut_ptr().add(4), efgh);
191    }
192}
193
194/// Finishes SHA-256 hashing over `data` into NEON state registers using ARMv8 hardware instructions.
195///
196/// # Arguments
197///
198/// - `&mut uint32x4_t` - Running hash state `[H0, H1, H2, H3]`.
199/// - `&mut uint32x4_t` - Running hash state `[H4, H5, H6, H7]`.
200/// - `u64` - Number of message bytes already compressed into the initial state.
201/// - `&[u8]` - Remaining message bytes.
202#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
203#[target_feature(enable = "sha2")]
204#[inline]
205pub(crate) unsafe fn sha256_finish_regs_aarch64(
206    abcd: &mut uint32x4_t,
207    efgh: &mut uint32x4_t,
208    prefix_bytes: u64,
209    data: &[u8],
210) {
211    let total_bytes: u64 = prefix_bytes.wrapping_add(data.len() as u64);
212    let bit_len: u64 = total_bytes.wrapping_mul(8);
213    let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
214    unsafe {
215        for block in blocks {
216            sha256_compress_block_regs_aarch64(abcd, efgh, block);
217        }
218        let rem: usize = rem_slice.len();
219        let mut tail0: [u8; 64] = [0u8; 64];
220        tail0[..rem].copy_from_slice(rem_slice);
221        tail0[rem] = 0x80;
222        if rem < 56 {
223            tail0[56..64].copy_from_slice(&bit_len.to_be_bytes());
224            sha256_compress_block_regs_aarch64(abcd, efgh, &tail0);
225        } else {
226            sha256_compress_block_regs_aarch64(abcd, efgh, &tail0);
227            let mut tail1: [u8; 64] = [0u8; 64];
228            tail1[56..64].copy_from_slice(&bit_len.to_be_bytes());
229            sha256_compress_block_regs_aarch64(abcd, efgh, &tail1);
230        }
231    }
232}
233
234/// Computes a finalized SHA-256 digest from `init_state` using ARMv8 hardware instructions.
235///
236/// # Arguments
237///
238/// - `[u32; 8]` - Initial or precomputed SHA-256 state.
239/// - `u64` - Number of message bytes already compressed into `init_state`.
240/// - `&[u8]` - Remaining message bytes.
241///
242/// # Returns
243///
244/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
245#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
246#[target_feature(enable = "sha2")]
247pub(crate) unsafe fn sha256_finish_from_aarch64(
248    init_state: [u32; 8],
249    prefix_bytes: u64,
250    data: &[u8],
251) -> [u8; 32] {
252    unsafe {
253        let mut abcd: uint32x4_t = vld1q_u32(init_state.as_ptr());
254        let mut efgh: uint32x4_t = vld1q_u32(init_state.as_ptr().add(4));
255        sha256_finish_regs_aarch64(&mut abcd, &mut efgh, prefix_bytes, data);
256        let mut out: [u8; 32] = [0u8; 32];
257        vst1q_u8(out.as_mut_ptr(), vrev32q_u8(vreinterpretq_u8_u32(abcd)));
258        vst1q_u8(
259            out.as_mut_ptr().add(16),
260            vrev32q_u8(vreinterpretq_u8_u32(efgh)),
261        );
262        out
263    }
264}
265
266/// Computes an HMAC-SHA256 tag from precomputed inner/outer midstates using ARMv8 SHA-256 instructions.
267///
268/// # Arguments
269///
270/// - `[u32; 8]` - Precomputed SHA-256 state after compressing `ipad`.
271/// - `[u32; 8]` - Precomputed SHA-256 state after compressing `opad`.
272/// - `&[u8]` - Input message bytes.
273///
274/// # Returns
275///
276/// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
277#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
278#[target_feature(enable = "sha2")]
279pub(crate) unsafe fn hmac_sha256_mac_aarch64(
280    inner_state: [u32; 8],
281    outer_state: [u32; 8],
282    data: &[u8],
283) -> [u8; 32] {
284    unsafe {
285        let mut inner_abcd: uint32x4_t = vld1q_u32(inner_state.as_ptr());
286        let mut inner_efgh: uint32x4_t = vld1q_u32(inner_state.as_ptr().add(4));
287        sha256_finish_regs_aarch64(&mut inner_abcd, &mut inner_efgh, 64, data);
288        let mut outer_abcd: uint32x4_t = vld1q_u32(outer_state.as_ptr());
289        let mut outer_efgh: uint32x4_t = vld1q_u32(outer_state.as_ptr().add(4));
290        let pad_m2: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M2.as_ptr());
291        let pad_m3: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M3.as_ptr());
292        sha256_compress_regs_aarch64(
293            &mut outer_abcd,
294            &mut outer_efgh,
295            inner_abcd,
296            inner_efgh,
297            pad_m2,
298            pad_m3,
299        );
300        let mut out: [u8; 32] = [0u8; 32];
301        vst1q_u8(
302            out.as_mut_ptr(),
303            vrev32q_u8(vreinterpretq_u8_u32(outer_abcd)),
304        );
305        vst1q_u8(
306            out.as_mut_ptr().add(16),
307            vrev32q_u8(vreinterpretq_u8_u32(outer_efgh)),
308        );
309        out
310    }
311}
312
313/// Computes a one-shot HMAC-SHA256 tag keeping inner and outer states in NEON registers.
314///
315/// # Arguments
316///
317/// - `&[u8]` - Secret key bytes.
318/// - `&[u8]` - Input message bytes.
319///
320/// # Returns
321///
322/// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
323#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
324#[target_feature(enable = "sha2")]
325pub(crate) unsafe fn hmac_sha256_oneshot_aarch64(key: &[u8], data: &[u8]) -> [u8; 32] {
326    unsafe {
327        let mut key_block: [u8; 64] = [0u8; 64];
328        if key.len() > 64 {
329            let hashed: [u8; 32] = sha256_finish_from_aarch64(SHA256_INIT, 0, key);
330            key_block[..32].copy_from_slice(&hashed);
331        } else {
332            key_block[..key.len()].copy_from_slice(key);
333        }
334        let kptr: *const u8 = key_block.as_ptr();
335        let k0: uint8x16_t = vld1q_u8(kptr);
336        let k1: uint8x16_t = vld1q_u8(kptr.add(16));
337        let k2: uint8x16_t = vld1q_u8(kptr.add(32));
338        let k3: uint8x16_t = vld1q_u8(kptr.add(48));
339        let ipad_mask: uint8x16_t = vdupq_n_u8(0x36);
340        let opad_mask: uint8x16_t = vdupq_n_u8(0x5c);
341        let init_abcd: uint32x4_t = vld1q_u32(SHA256_INIT.as_ptr());
342        let init_efgh: uint32x4_t = vld1q_u32(SHA256_INIT.as_ptr().add(4));
343        let mut inner_abcd: uint32x4_t = init_abcd;
344        let mut inner_efgh: uint32x4_t = init_efgh;
345        sha256_compress_regs_aarch64(
346            &mut inner_abcd,
347            &mut inner_efgh,
348            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k0, ipad_mask))),
349            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k1, ipad_mask))),
350            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k2, ipad_mask))),
351            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k3, ipad_mask))),
352        );
353        sha256_finish_regs_aarch64(&mut inner_abcd, &mut inner_efgh, 64, data);
354        let mut outer_abcd: uint32x4_t = init_abcd;
355        let mut outer_efgh: uint32x4_t = init_efgh;
356        sha256_compress_regs_aarch64(
357            &mut outer_abcd,
358            &mut outer_efgh,
359            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k0, opad_mask))),
360            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k1, opad_mask))),
361            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k2, opad_mask))),
362            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k3, opad_mask))),
363        );
364        let pad_m2: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M2.as_ptr());
365        let pad_m3: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M3.as_ptr());
366        sha256_compress_regs_aarch64(
367            &mut outer_abcd,
368            &mut outer_efgh,
369            inner_abcd,
370            inner_efgh,
371            pad_m2,
372            pad_m3,
373        );
374        let mut out: [u8; 32] = [0u8; 32];
375        vst1q_u8(
376            out.as_mut_ptr(),
377            vrev32q_u8(vreinterpretq_u8_u32(outer_abcd)),
378        );
379        vst1q_u8(
380            out.as_mut_ptr().add(16),
381            vrev32q_u8(vreinterpretq_u8_u32(outer_efgh)),
382        );
383        out
384    }
385}
386
387/// Software fallback finalizing SHA-256 into eight big-endian state words.
388///
389/// # Arguments
390///
391/// - `[u32; 8]` - Initial or precomputed SHA-256 state.
392/// - `u64` - Number of message bytes already compressed into `state`.
393/// - `&[u8]` - Remaining message bytes to hash.
394///
395/// # Returns
396///
397/// - `[u32; 8]` - Final SHA-256 hash state words.
398#[inline]
399pub(crate) fn sha256_finish_words_sw(
400    mut state: [u32; 8],
401    prefix_bytes: u64,
402    data: &[u8],
403) -> [u32; 8] {
404    let total_bytes: u64 = prefix_bytes.wrapping_add(data.len() as u64);
405    let bit_len: u64 = total_bytes.wrapping_mul(8);
406    let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
407    for block in blocks {
408        sha256_compress_sw(&mut state, block);
409    }
410    let rem: usize = rem_slice.len();
411    let mut tail0: [u8; 64] = [0u8; 64];
412    tail0[..rem].copy_from_slice(rem_slice);
413    tail0[rem] = 0x80;
414    if rem < 56 {
415        tail0[56..64].copy_from_slice(&bit_len.to_be_bytes());
416        sha256_compress_sw(&mut state, &tail0);
417    } else {
418        sha256_compress_sw(&mut state, &tail0);
419        let mut tail1: [u8; 64] = [0u8; 64];
420        tail1[56..64].copy_from_slice(&bit_len.to_be_bytes());
421        sha256_compress_sw(&mut state, &tail1);
422    }
423    state
424}
425
426/// Compresses all 64-byte chunks of `data` followed by FIPS 180-4 padding from `init_state` and `prefix_bytes`.
427///
428/// # Arguments
429///
430/// - `[u32; 8]` - Initial or precomputed SHA-256 state.
431/// - `u64` - Number of message bytes already compressed into `init_state`.
432/// - `&[u8]` - Remaining message bytes to hash.
433///
434/// # Returns
435///
436/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
437#[inline]
438pub(crate) fn sha256_finish_from(init_state: [u32; 8], prefix_bytes: u64, data: &[u8]) -> [u8; 32] {
439    #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
440    if has_aarch64_sha2() {
441        return unsafe { sha256_finish_from_aarch64(init_state, prefix_bytes, data) };
442    }
443    sha256_words_to_bytes(sha256_finish_words_sw(init_state, prefix_bytes, data))
444}
445
446/// Computes the FIPS 180-4 SHA-256 digest of `data`.
447///
448/// # Arguments
449///
450/// - `&[u8]` - Input byte slice.
451///
452/// # Returns
453///
454/// - `[u8; 32]` - 256-bit SHA-256 digest.
455#[inline]
456pub fn sha256(data: &[u8]) -> [u8; 32] {
457    sha256_finish_from(SHA256_INIT, 0, data)
458}
459
460/// Executes one register-rotating SHA-256 compression step without shifting all 8 state words.
461///
462/// # Arguments
463///
464/// - `(u32, u32, u32, &mut u32)` - Registers `(a, b, c, &mut d)` where `d` is updated to the next `e`.
465/// - `(u32, u32, u32, &mut u32)` - Registers `(e, f, g, &mut h)` where `h` is updated to the next `a`.
466/// - `u32` - Message schedule word `w[i]`.
467/// - `u32` - Round constant `K[i]`.
468#[inline(always)]
469pub(crate) fn sha256_step(
470    abcd: (u32, u32, u32, &mut u32),
471    efgh: (u32, u32, u32, &mut u32),
472    w: u32,
473    k: u32,
474) {
475    let (a, b, c, d): (u32, u32, u32, &mut u32) = abcd;
476    let (e, f, g, h): (u32, u32, u32, &mut u32) = efgh;
477    let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
478    let ch: u32 = (e & f) ^ ((!e) & g);
479    let t1: u32 = (*h)
480        .wrapping_add(s1)
481        .wrapping_add(ch)
482        .wrapping_add(k)
483        .wrapping_add(w);
484    let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
485    let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
486    *d = (*d).wrapping_add(t1);
487    *h = t1.wrapping_add(s0.wrapping_add(maj));
488}
489
490/// Computes one next SHA-256 message schedule word from its four predecessor words.
491///
492/// # Arguments
493///
494/// - `u32` - Word `w[t - 16]`.
495/// - `u32` - Word `w[t - 15]`.
496/// - `u32` - Word `w[t - 7]`.
497/// - `u32` - Word `w[t - 2]`.
498///
499/// # Returns
500///
501/// - `u32` - Expanded schedule word `w[t]`.
502#[inline(always)]
503pub(crate) fn sha256_w_next(w0: u32, w1: u32, w9: u32, w14: u32) -> u32 {
504    let s0: u32 = w1.rotate_right(7) ^ w1.rotate_right(18) ^ (w1 >> 3);
505    let s1: u32 = w14.rotate_right(17) ^ w14.rotate_right(19) ^ (w14 >> 10);
506    w0.wrapping_add(s0).wrapping_add(w9).wrapping_add(s1)
507}
508
509/// Expands the rolling 16-word SHA-256 message schedule in place using compile-time indices.
510///
511/// # Arguments
512///
513/// - `&mut [u32; 16]` - Rolling 16-word message schedule window.
514#[inline(always)]
515pub(crate) fn sha256_expand_16(w: &mut [u32; 16]) {
516    w[0] = sha256_w_next(w[0], w[1], w[9], w[14]);
517    w[1] = sha256_w_next(w[1], w[2], w[10], w[15]);
518    w[2] = sha256_w_next(w[2], w[3], w[11], w[0]);
519    w[3] = sha256_w_next(w[3], w[4], w[12], w[1]);
520    w[4] = sha256_w_next(w[4], w[5], w[13], w[2]);
521    w[5] = sha256_w_next(w[5], w[6], w[14], w[3]);
522    w[6] = sha256_w_next(w[6], w[7], w[15], w[4]);
523    w[7] = sha256_w_next(w[7], w[8], w[0], w[5]);
524    w[8] = sha256_w_next(w[8], w[9], w[1], w[6]);
525    w[9] = sha256_w_next(w[9], w[10], w[2], w[7]);
526    w[10] = sha256_w_next(w[10], w[11], w[3], w[8]);
527    w[11] = sha256_w_next(w[11], w[12], w[4], w[9]);
528    w[12] = sha256_w_next(w[12], w[13], w[5], w[10]);
529    w[13] = sha256_w_next(w[13], w[14], w[6], w[11]);
530    w[14] = sha256_w_next(w[14], w[15], w[7], w[12]);
531    w[15] = sha256_w_next(w[15], w[0], w[8], w[13]);
532}
533
534/// Executes 16 unrolled SHA-256 rounds against the current 16-word schedule window.
535///
536/// # Arguments
537///
538/// - `&mut [u32; 8]` - Working registers `[a, b, c, d, e, f, g, h]`.
539/// - `&[u32; 16]` - Current 16-word message schedule window.
540/// - `usize` - Starting index into [`SHA256_K`] (`0`, `16`, `32`, or `48`).
541#[inline(always)]
542pub(crate) fn sha256_rounds_16(v: &mut [u32; 8], w: &[u32; 16], k_base: usize) {
543    let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h]: [u32; 8] = *v;
544    sha256_step((a, b, c, &mut d), (e, f, g, &mut h), w[0], SHA256_K[k_base]);
545    sha256_step(
546        (h, a, b, &mut c),
547        (d, e, f, &mut g),
548        w[1],
549        SHA256_K[k_base + 1],
550    );
551    sha256_step(
552        (g, h, a, &mut b),
553        (c, d, e, &mut f),
554        w[2],
555        SHA256_K[k_base + 2],
556    );
557    sha256_step(
558        (f, g, h, &mut a),
559        (b, c, d, &mut e),
560        w[3],
561        SHA256_K[k_base + 3],
562    );
563    sha256_step(
564        (e, f, g, &mut h),
565        (a, b, c, &mut d),
566        w[4],
567        SHA256_K[k_base + 4],
568    );
569    sha256_step(
570        (d, e, f, &mut g),
571        (h, a, b, &mut c),
572        w[5],
573        SHA256_K[k_base + 5],
574    );
575    sha256_step(
576        (c, d, e, &mut f),
577        (g, h, a, &mut b),
578        w[6],
579        SHA256_K[k_base + 6],
580    );
581    sha256_step(
582        (b, c, d, &mut e),
583        (f, g, h, &mut a),
584        w[7],
585        SHA256_K[k_base + 7],
586    );
587    sha256_step(
588        (a, b, c, &mut d),
589        (e, f, g, &mut h),
590        w[8],
591        SHA256_K[k_base + 8],
592    );
593    sha256_step(
594        (h, a, b, &mut c),
595        (d, e, f, &mut g),
596        w[9],
597        SHA256_K[k_base + 9],
598    );
599    sha256_step(
600        (g, h, a, &mut b),
601        (c, d, e, &mut f),
602        w[10],
603        SHA256_K[k_base + 10],
604    );
605    sha256_step(
606        (f, g, h, &mut a),
607        (b, c, d, &mut e),
608        w[11],
609        SHA256_K[k_base + 11],
610    );
611    sha256_step(
612        (e, f, g, &mut h),
613        (a, b, c, &mut d),
614        w[12],
615        SHA256_K[k_base + 12],
616    );
617    sha256_step(
618        (d, e, f, &mut g),
619        (h, a, b, &mut c),
620        w[13],
621        SHA256_K[k_base + 13],
622    );
623    sha256_step(
624        (c, d, e, &mut f),
625        (g, h, a, &mut b),
626        w[14],
627        SHA256_K[k_base + 14],
628    );
629    sha256_step(
630        (b, c, d, &mut e),
631        (f, g, h, &mut a),
632        w[15],
633        SHA256_K[k_base + 15],
634    );
635    *v = [a, b, c, d, e, f, g, h];
636}
637
638/// Compresses 16 message schedule words into `state` using the portable software SHA-256 kernel.
639///
640/// # Arguments
641///
642/// - `&mut [u32; 8]` - Running hash state.
643/// - `[u32; 16]` - Input 16 big-endian 32-bit message words.
644#[inline]
645pub(crate) fn sha256_compress_words_sw(state: &mut [u32; 8], mut w: [u32; 16]) {
646    let mut v: [u32; 8] = *state;
647    sha256_rounds_16(&mut v, &w, 0);
648    sha256_expand_16(&mut w);
649    sha256_rounds_16(&mut v, &w, 16);
650    sha256_expand_16(&mut w);
651    sha256_rounds_16(&mut v, &w, 32);
652    sha256_expand_16(&mut w);
653    sha256_rounds_16(&mut v, &w, 48);
654    state[0] = state[0].wrapping_add(v[0]);
655    state[1] = state[1].wrapping_add(v[1]);
656    state[2] = state[2].wrapping_add(v[2]);
657    state[3] = state[3].wrapping_add(v[3]);
658    state[4] = state[4].wrapping_add(v[4]);
659    state[5] = state[5].wrapping_add(v[5]);
660    state[6] = state[6].wrapping_add(v[6]);
661    state[7] = state[7].wrapping_add(v[7]);
662}
663
664/// Compresses one 64-byte SHA-256 block into `state` using the portable software implementation.
665///
666/// # Arguments
667///
668/// - `&mut [u32; 8]` - Running hash state.
669/// - `&[u8; 64]` - Input block.
670pub(crate) fn sha256_compress_sw(state: &mut [u32; 8], block: &[u8; 64]) {
671    let w: [u32; 16] = [
672        u32::from_be_bytes([block[0], block[1], block[2], block[3]]),
673        u32::from_be_bytes([block[4], block[5], block[6], block[7]]),
674        u32::from_be_bytes([block[8], block[9], block[10], block[11]]),
675        u32::from_be_bytes([block[12], block[13], block[14], block[15]]),
676        u32::from_be_bytes([block[16], block[17], block[18], block[19]]),
677        u32::from_be_bytes([block[20], block[21], block[22], block[23]]),
678        u32::from_be_bytes([block[24], block[25], block[26], block[27]]),
679        u32::from_be_bytes([block[28], block[29], block[30], block[31]]),
680        u32::from_be_bytes([block[32], block[33], block[34], block[35]]),
681        u32::from_be_bytes([block[36], block[37], block[38], block[39]]),
682        u32::from_be_bytes([block[40], block[41], block[42], block[43]]),
683        u32::from_be_bytes([block[44], block[45], block[46], block[47]]),
684        u32::from_be_bytes([block[48], block[49], block[50], block[51]]),
685        u32::from_be_bytes([block[52], block[53], block[54], block[55]]),
686        u32::from_be_bytes([block[56], block[57], block[58], block[59]]),
687        u32::from_be_bytes([block[60], block[61], block[62], block[63]]),
688    ];
689    sha256_compress_words_sw(state, w);
690}
691
692/// Compresses one 64-byte SHA-256 block into `state`, dispatching to hardware crypto when available.
693///
694/// # Arguments
695///
696/// - `&mut [u32; 8]` - Running hash state.
697/// - `&[u8; 64]` - Input block.
698#[inline]
699pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
700    #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
701    if has_aarch64_sha2() {
702        unsafe { sha256_compress_aarch64(state, block) };
703        return;
704    }
705    sha256_compress_sw(state, block);
706}
707
708/// Computes the RFC 4231 HMAC-SHA256 tag of `data` under `key` with zero heap allocations.
709///
710/// # Arguments
711///
712/// - `&[u8]` - Secret key bytes.
713/// - `&[u8]` - Input message bytes.
714///
715/// # Returns
716///
717/// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
718#[inline]
719pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
720    #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
721    if has_aarch64_sha2() {
722        return unsafe { hmac_sha256_oneshot_aarch64(key, data) };
723    }
724    HmacSha256Key::new(key).mac(data)
725}
726
727/// Compares two byte slices in constant time with respect to their contents.
728///
729/// # Arguments
730///
731/// - `&[u8]` - First byte slice.
732/// - `&[u8]` - Second byte slice.
733///
734/// # Returns
735///
736/// - `bool` - `true` when lengths and bytes are identical.
737#[inline]
738pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
739    if a.len() != b.len() {
740        return false;
741    }
742    let mut diff: u8 = 0;
743    for i in 0..a.len() {
744        diff |= a[i] ^ b[i];
745    }
746    diff == 0
747}
748
749/// Appends unpadded RFC 4648 base64url bytes of `input` directly into `out`.
750///
751/// # Arguments
752///
753/// - `&[u8]` - Raw bytes to encode.
754/// - `&mut Vec<u8>` - Destination ASCII byte buffer.
755#[inline]
756pub(crate) fn base64url_encode_into(input: &[u8], out: &mut Vec<u8>) {
757    let encoded_len: usize = (input.len() * 4).div_ceil(3);
758    let start: usize = out.len();
759    out.resize(start + encoded_len, 0u8);
760    let dst: &mut [u8] = &mut out[start..];
761    let (triples, rem): (&[[u8; 3]], &[u8]) = input.as_chunks::<3>();
762    let full_out: usize = triples.len() * 4;
763    let (dst_quads, _): (&mut [[u8; 4]], &mut [u8]) = dst[..full_out].as_chunks_mut::<4>();
764    for (chunk, dst_quad) in triples.iter().zip(dst_quads.iter_mut()) {
765        let triple: u32 = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32);
766        dst_quad[0] = BASE64URL_ALPHABET[((triple >> 18) & 0x3F) as usize];
767        dst_quad[1] = BASE64URL_ALPHABET[((triple >> 12) & 0x3F) as usize];
768        dst_quad[2] = BASE64URL_ALPHABET[((triple >> 6) & 0x3F) as usize];
769        dst_quad[3] = BASE64URL_ALPHABET[(triple & 0x3F) as usize];
770    }
771    let tail: &mut [u8] = &mut dst[full_out..];
772    if rem.len() == 1 {
773        let val: u32 = (rem[0] as u32) << 16;
774        tail[0] = BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize];
775        tail[1] = BASE64URL_ALPHABET[((val >> 12) & 0x3F) as usize];
776    } else if rem.len() == 2 {
777        let val: u32 = ((rem[0] as u32) << 16) | ((rem[1] as u32) << 8);
778        tail[0] = BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize];
779        tail[1] = BASE64URL_ALPHABET[((val >> 12) & 0x3F) as usize];
780        tail[2] = BASE64URL_ALPHABET[((val >> 6) & 0x3F) as usize];
781    }
782}
783
784/// Encodes `input` using unpadded RFC 4648 base64url.
785///
786/// # Arguments
787///
788/// - `&[u8]` - Raw bytes to encode.
789///
790/// # Returns
791///
792/// - `String` - Unpadded base64url string.
793#[inline]
794pub fn base64url_encode(input: &[u8]) -> String {
795    let mut buf: Vec<u8> = Vec::with_capacity((input.len() * 4).div_ceil(3));
796    base64url_encode_into(input, &mut buf);
797    String::from_utf8(buf).unwrap_or_default()
798}
799
800/// Decodes base64 or base64url bytes into a caller-supplied slice using a 256-byte lookup table.
801///
802/// # Arguments
803///
804/// - `&[u8]` - Trimmed input ASCII bytes without trailing `=`.
805/// - `&[u8; 256]` - Lookup table mapping ASCII bytes to 6-bit values or [`B64_INVALID`].
806/// - `&mut [u8]` - Destination slice with capacity at least `(bytes.len() * 3) / 4`.
807///
808/// # Returns
809///
810/// - `Option<usize>` - Number of bytes written, or `None` when input is malformed.
811#[inline]
812pub(crate) fn decode_base64_into(bytes: &[u8], table: &[u8; 256], out: &mut [u8]) -> Option<usize> {
813    if bytes.len() % 4 == 1 {
814        return None;
815    }
816    let decoded_len: usize = (bytes.len() * 3) / 4;
817    if out.len() < decoded_len {
818        return None;
819    }
820    let (quads, rem): (&[[u8; 4]], &[u8]) = bytes.as_chunks::<4>();
821    let mut pos: usize = quads.len() * 3;
822    let mut invalid: u8 = 0;
823    let (dst_triples, _): (&mut [[u8; 3]], &mut [u8]) = out[..pos].as_chunks_mut::<3>();
824    for (chunk, dst) in quads.iter().zip(dst_triples.iter_mut()) {
825        let a: u8 = table[chunk[0] as usize];
826        let b: u8 = table[chunk[1] as usize];
827        let c: u8 = table[chunk[2] as usize];
828        let d: u8 = table[chunk[3] as usize];
829        invalid |= (a | b) | (c | d);
830        let quad: u32 = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6) | (d as u32);
831        dst[0] = ((quad >> 16) & 0xFF) as u8;
832        dst[1] = ((quad >> 8) & 0xFF) as u8;
833        dst[2] = (quad & 0xFF) as u8;
834    }
835    if (invalid & 0x80) != 0 {
836        return None;
837    }
838    if rem.len() == 2 {
839        let a: u8 = table[rem[0] as usize];
840        let b: u8 = table[rem[1] as usize];
841        if ((a | b) & 0x80) != 0 {
842            return None;
843        }
844        let val: u32 = ((a as u32) << 18) | ((b as u32) << 12);
845        out[pos] = ((val >> 16) & 0xFF) as u8;
846        pos += 1;
847    } else if rem.len() == 3 {
848        let a: u8 = table[rem[0] as usize];
849        let b: u8 = table[rem[1] as usize];
850        let c: u8 = table[rem[2] as usize];
851        let ab: u8 = a | b;
852        if ((ab | c) & 0x80) != 0 {
853            return None;
854        }
855        let val: u32 = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6);
856        out[pos] = ((val >> 16) & 0xFF) as u8;
857        out[pos + 1] = ((val >> 8) & 0xFF) as u8;
858        pos += 2;
859    }
860    Some(pos)
861}
862
863/// Decodes a 32-byte HS256 base64url signature directly onto the stack with zero heap allocations.
864///
865/// # Arguments
866///
867/// - `&str` - Base64url signature segment.
868///
869/// # Returns
870///
871/// - `Option<[u8; 32]>` - Decoded 32-byte MAC, or `None` when length or encoding is invalid.
872#[inline]
873pub(crate) fn decode_base64url_32(input: &str) -> Option<[u8; 32]> {
874    let trimmed: &[u8] = input.trim_end_matches('=').as_bytes();
875    if trimmed.len() != HMAC_SIG_B64_LEN {
876        return None;
877    }
878    let mut out: [u8; 32] = [0u8; 32];
879    let written: usize = decode_base64_into(trimmed, &BASE64URL_DECODE_TABLE, &mut out)?;
880    if written == 32 { Some(out) } else { None }
881}
882
883/// Decodes unpadded (or padded) base64 / base64url text into raw bytes.
884///
885/// # Arguments
886///
887/// - `&str` - Encoded string.
888/// - `bool` - `true` for base64url, `false` for standard base64.
889///
890/// # Returns
891///
892/// - `Option<Vec<u8>>` - Decoded bytes, or `None` on malformed input.
893#[inline]
894pub(crate) fn decode_base64_inner(input: &str, url_safe: bool) -> Option<Vec<u8>> {
895    let bytes: &[u8] = input.trim_end_matches('=').as_bytes();
896    if bytes.len() % 4 == 1 {
897        return None;
898    }
899    let table: &[u8; 256] = if url_safe {
900        &BASE64URL_DECODE_TABLE
901    } else {
902        &BASE64_STD_DECODE_TABLE
903    };
904    let decoded_len: usize = (bytes.len() * 3) / 4;
905    let mut out: Vec<u8> = vec![0u8; decoded_len];
906    let written: usize = decode_base64_into(bytes, table, &mut out)?;
907    out.truncate(written);
908    Some(out)
909}
910
911/// Decodes an unpadded RFC 4648 base64url string.
912///
913/// # Arguments
914///
915/// - `&str` - Base64url-encoded string.
916///
917/// # Returns
918///
919/// - `Option<Vec<u8>>` - Decoded bytes, or `None` if malformed.
920#[inline]
921pub fn base64url_decode(input: &str) -> Option<Vec<u8>> {
922    decode_base64_inner(input, true)
923}
924
925/// Decodes a standard RFC 4648 base64 string (used by HTTP Basic authentication).
926///
927/// # Arguments
928///
929/// - `&str` - Standard base64-encoded string.
930///
931/// # Returns
932///
933/// - `Option<Vec<u8>>` - Decoded bytes, or `None` if malformed.
934#[inline]
935pub fn base64_decode(input: &str) -> Option<Vec<u8>> {
936    decode_base64_inner(input, false)
937}
938
939/// Extracts a case-insensitive prefix-stripped token from an `Authorization` header.
940///
941/// # Arguments
942///
943/// - `&'a str` - Raw `Authorization` header value.
944/// - `&str` - Expected lowercase scheme prefix ending with space (for example `"bearer "`).
945///
946/// # Returns
947///
948/// - `Option<&'a str>` - Trimmed credential payload, or `None` when the scheme does not match.
949#[inline]
950pub(crate) fn strip_auth_scheme<'a>(header: &'a str, lowercase_prefix: &str) -> Option<&'a str> {
951    let trimmed: &'a str = header.trim();
952    if trimmed.len() < lowercase_prefix.len() {
953        return None;
954    }
955    let (head, tail): (&'a str, &'a str) = trimmed.split_at(lowercase_prefix.len());
956    if head.eq_ignore_ascii_case(lowercase_prefix) {
957        let token: &'a str = tail.trim();
958        if token.is_empty() { None } else { Some(token) }
959    } else {
960        None
961    }
962}
963
964/// Pre-encodes a compact base64url HS256 JWT header for an optional `kid`.
965///
966/// # Arguments
967///
968/// - `Option<&str>` - Optional default `kid`.
969///
970/// # Returns
971///
972/// - `String` - Base64url-encoded JWT header segment.
973pub(crate) fn encode_hs256_header_b64(default_kid: Option<&str>) -> String {
974    let Some(kid) = default_kid else {
975        return DEFAULT_HS256_HEADER_B64.to_owned();
976    };
977    let header: JwtHeader = JwtHeader {
978        alg: JWT_ALG_HS256.to_owned(),
979        typ: Some(JWT_TYP_JWT.to_owned()),
980        kid: Some(kid.to_owned()),
981    };
982    let json_bytes: Vec<u8> = to_vec(&header).unwrap_or_default();
983    base64url_encode(&json_bytes)
984}
985
986/// Appends a JSON-quoted string to `buf`, avoiding `serde_json` overhead when no escaping is needed.
987///
988/// # Arguments
989///
990/// - `&mut StackJsonBuf` - Destination JSON byte buffer.
991/// - `&str` - String value to serialize.
992///
993/// # Returns
994///
995/// - `Result<(), AuthError>` - `Ok(())` on success or [`AuthError::InvalidCredentials`] on write error.
996#[inline]
997pub(crate) fn write_json_str_fast(buf: &mut StackJsonBuf, s: &str) -> Result<(), AuthError> {
998    let bytes: &[u8] = s.as_bytes();
999    let needs_escape: bool = bytes
1000        .iter()
1001        .any(|&b: &u8| b < 0x20 || b == ASCII_QUOTE || b == ASCII_BACKSLASH);
1002    if !needs_escape {
1003        buf.push_byte(ASCII_QUOTE);
1004        buf.push_slice(bytes);
1005        buf.push_byte(ASCII_QUOTE);
1006        return Ok(());
1007    }
1008    to_writer(buf, s).map_err(|_| AuthError::InvalidCredentials)
1009}
1010
1011/// Appends an unsigned 64-bit decimal integer to `buf` using a 2-digit lookup table.
1012///
1013/// # Arguments
1014///
1015/// - `&mut StackJsonBuf` - Destination JSON byte buffer.
1016/// - `u64` - Unsigned integer to format.
1017#[inline]
1018pub(crate) fn write_u64_fast(buf: &mut StackJsonBuf, mut val: u64) {
1019    let mut digits: [u8; 20] = [0u8; 20];
1020    let mut pos: usize = 20;
1021    while val >= 100 {
1022        let pair: usize = ((val % 100) as usize) * 2;
1023        val /= 100;
1024        pos -= 2;
1025        digits[pos] = DEC_DIGITS_LUT[pair];
1026        digits[pos + 1] = DEC_DIGITS_LUT[pair + 1];
1027    }
1028    if val < 10 {
1029        pos -= 1;
1030        digits[pos] = ASCII_ZERO + (val as u8);
1031    } else {
1032        let pair: usize = (val as usize) * 2;
1033        pos -= 2;
1034        digits[pos] = DEC_DIGITS_LUT[pair];
1035        digits[pos + 1] = DEC_DIGITS_LUT[pair + 1];
1036    }
1037    buf.push_slice(&digits[pos..]);
1038}
1039
1040/// Serializes [`JwtClaims`] directly into `buf` without `serde` serializer dispatch for standard claims.
1041///
1042/// # Arguments
1043///
1044/// - `&JwtClaims` - Claims payload to encode.
1045/// - `&mut StackJsonBuf` - Destination JSON byte buffer.
1046///
1047/// # Returns
1048///
1049/// - `Result<(), AuthError>` - `Ok(())` on success or [`AuthError::InvalidCredentials`] on failure.
1050#[inline]
1051pub(crate) fn write_jwt_claims_json(
1052    claims: &JwtClaims,
1053    buf: &mut StackJsonBuf,
1054) -> Result<(), AuthError> {
1055    let JwtClaims {
1056        sub,
1057        iss,
1058        aud,
1059        exp,
1060        nbf,
1061        iat,
1062        jti,
1063        roles,
1064        extra,
1065    } = claims;
1066    buf.push_slice(JSON_SUB_PREFIX);
1067    write_json_str_fast(buf, sub)?;
1068    if let Some(val) = iss {
1069        buf.push_slice(JSON_ISS_PREFIX);
1070        write_json_str_fast(buf, val)?;
1071    }
1072    if let Some(val) = aud {
1073        buf.push_slice(JSON_AUD_PREFIX);
1074        write_json_str_fast(buf, val)?;
1075    }
1076    if let Some(val) = *exp {
1077        buf.push_slice(JSON_EXP_PREFIX);
1078        write_u64_fast(buf, val);
1079    }
1080    if let Some(val) = *nbf {
1081        buf.push_slice(JSON_NBF_PREFIX);
1082        write_u64_fast(buf, val);
1083    }
1084    if let Some(val) = *iat {
1085        buf.push_slice(JSON_IAT_PREFIX);
1086        write_u64_fast(buf, val);
1087    }
1088    if let Some(val) = jti {
1089        buf.push_slice(JSON_JTI_PREFIX);
1090        write_json_str_fast(buf, val)?;
1091    }
1092    if !roles.is_empty() {
1093        buf.push_slice(JSON_ROLES_PREFIX);
1094        for (idx, role) in roles.iter().enumerate() {
1095            if idx > 0 {
1096                buf.push_byte(ASCII_COMMA);
1097            }
1098            write_json_str_fast(buf, role)?;
1099        }
1100        buf.push_byte(ASCII_RBRACKET);
1101    }
1102    for (k, v) in extra {
1103        buf.push_byte(ASCII_COMMA);
1104        write_json_str_fast(buf, k)?;
1105        buf.push_byte(ASCII_COLON);
1106        to_writer(&mut *buf, v).map_err(|_| AuthError::InvalidCredentials)?;
1107    }
1108    buf.push_byte(ASCII_RBRACE);
1109    Ok(())
1110}