Skip to main content

hyperlane_plugin_auth/
impl.rs

1use super::*;
2
3/// Precomputed HMAC-SHA256 key implementation.
4impl HmacSha256Key {
5    /// Derives precomputed inner and outer SHA-256 midstates from `key`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&[u8]` - Secret key bytes.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Precomputed HMAC key state.
14    #[inline]
15    pub(crate) fn new(key: &[u8]) -> Self {
16        let mut key_block: [u8; 64] = [0u8; 64];
17        if key.len() > 64 {
18            let hashed: [u8; 32] = sha256(key);
19            key_block[..32].copy_from_slice(&hashed);
20        } else {
21            key_block[..key.len()].copy_from_slice(key);
22        }
23        let mut ipad: [u8; 64] = [0u8; 64];
24        let mut opad: [u8; 64] = [0u8; 64];
25        let mut i: usize = 0;
26        while i < 64 {
27            ipad[i] = key_block[i] ^ 0x36;
28            opad[i] = key_block[i] ^ 0x5c;
29            i += 1;
30        }
31        let mut inner_state: [u32; 8] = SHA256_INIT;
32        let mut outer_state: [u32; 8] = SHA256_INIT;
33        sha256_compress(&mut inner_state, &ipad);
34        sha256_compress(&mut outer_state, &opad);
35        Self {
36            inner_state,
37            outer_state,
38        }
39    }
40
41    /// Computes the HMAC-SHA256 tag of `data` using the precomputed key midstates.
42    ///
43    /// # Arguments
44    ///
45    /// - `&[u8]` - Input message bytes.
46    ///
47    /// # Returns
48    ///
49    /// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
50    #[inline]
51    pub(crate) fn mac(&self, data: &[u8]) -> [u8; 32] {
52        let Self {
53            inner_state,
54            outer_state,
55        } = *self;
56        #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
57        if has_aarch64_sha2() {
58            return unsafe { hmac_sha256_mac_aarch64(inner_state, outer_state, data) };
59        }
60        let inner_words: [u32; 8] = sha256_finish_words_sw(inner_state, 64, data);
61        let outer_w: [u32; 16] = [
62            inner_words[0],
63            inner_words[1],
64            inner_words[2],
65            inner_words[3],
66            inner_words[4],
67            inner_words[5],
68            inner_words[6],
69            inner_words[7],
70            HMAC_OUTER_PAD_M2[0],
71            0,
72            0,
73            0,
74            0,
75            0,
76            0,
77            HMAC_OUTER_PAD_M3[3],
78        ];
79        let mut state: [u32; 8] = outer_state;
80        sha256_compress_words_sw(&mut state, outer_w);
81        sha256_words_to_bytes(state)
82    }
83}
84
85/// Stack-backed JSON serialization buffer implementation.
86impl StackJsonBuf {
87    /// Creates an empty [`StackJsonBuf`] without heap allocation.
88    ///
89    /// # Returns
90    ///
91    /// - `Self` - Empty stack buffer.
92    #[inline]
93    pub(crate) fn new() -> Self {
94        Self {
95            stack: [0u8; JWT_STACK_ENCODE_CAP],
96            len: 0,
97            heap: None,
98        }
99    }
100
101    /// Appends a single byte into stack storage or spills seamlessly to the heap.
102    ///
103    /// # Arguments
104    ///
105    /// - `u8` - Byte to append.
106    #[inline(always)]
107    pub(crate) fn push_byte(&mut self, byte: u8) {
108        let Self { stack, len, heap } = self;
109        if let Some(vec) = heap {
110            vec.push(byte);
111            return;
112        }
113        if *len < stack.len() {
114            stack[*len] = byte;
115            *len += 1;
116        } else {
117            let mut vec: Vec<u8> = Vec::with_capacity(*len + 64);
118            vec.extend_from_slice(&stack[..*len]);
119            vec.push(byte);
120            *heap = Some(vec);
121        }
122    }
123
124    /// Appends a byte slice into stack storage or spills seamlessly to the heap.
125    ///
126    /// # Arguments
127    ///
128    /// - `&[u8]` - Source byte slice.
129    #[inline(always)]
130    pub(crate) fn push_slice(&mut self, buf: &[u8]) {
131        let Self { stack, len, heap } = self;
132        if let Some(vec) = heap {
133            vec.extend_from_slice(buf);
134            return;
135        }
136        let next_len: usize = len.saturating_add(buf.len());
137        if next_len <= stack.len() {
138            stack[*len..next_len].copy_from_slice(buf);
139            *len = next_len;
140        } else {
141            let mut vec: Vec<u8> = Vec::with_capacity(next_len + 64);
142            vec.extend_from_slice(&stack[..*len]);
143            vec.extend_from_slice(buf);
144            *heap = Some(vec);
145        }
146    }
147
148    /// Returns the written bytes as a contiguous slice.
149    ///
150    /// # Returns
151    ///
152    /// - `&[u8]` - Written JSON bytes.
153    #[inline]
154    pub(crate) fn as_slice(&self) -> &[u8] {
155        let Self { stack, len, heap } = self;
156        match heap {
157            Some(buf) => buf.as_slice(),
158            None => &stack[..*len],
159        }
160    }
161}
162
163/// Implements [`Write`] for [`StackJsonBuf`].
164impl Write for StackJsonBuf {
165    /// Appends `buf` to stack storage or spills seamlessly to the heap.
166    ///
167    /// # Arguments
168    ///
169    /// - `&[u8]` - Source byte slice.
170    ///
171    /// # Returns
172    ///
173    /// - `io::Result<usize>` - Number of bytes written.
174    #[inline]
175    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
176        let Self { stack, len, heap } = self;
177        if let Some(vec) = heap {
178            vec.extend_from_slice(buf);
179            return Ok(buf.len());
180        }
181        let next_len: usize = len.saturating_add(buf.len());
182        if next_len <= stack.len() {
183            stack[*len..next_len].copy_from_slice(buf);
184            *len = next_len;
185        } else {
186            let mut vec: Vec<u8> = Vec::with_capacity(next_len);
187            vec.extend_from_slice(&stack[..*len]);
188            vec.extend_from_slice(buf);
189            *heap = Some(vec);
190        }
191        Ok(buf.len())
192    }
193
194    /// No-op flush for in-memory buffer.
195    ///
196    /// # Returns
197    ///
198    /// - `io::Result<()>` - Always `Ok(())`.
199    #[inline]
200    fn flush(&mut self) -> io::Result<()> {
201        Ok(())
202    }
203}
204
205/// Formatting for [`AuthError`].
206impl Display for AuthError {
207    /// Formats a human-readable error summary for [`AuthError`].
208    ///
209    /// # Arguments
210    ///
211    /// - `&mut Formatter<'_>` - Output formatter.
212    ///
213    /// # Returns
214    ///
215    /// - `fmt::Result` - Formatting outcome.
216    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
217        match self {
218            Self::MissingCredentials => f.write_str(MSG_AUTH_MISSING),
219            Self::InvalidCredentials => f.write_str(MSG_AUTH_INVALID),
220            Self::TokenExpired => f.write_str(MSG_AUTH_EXPIRED),
221            Self::TokenNotYetValid => f.write_str(MSG_AUTH_NOT_YET_VALID),
222            Self::UnsupportedAlgorithm => f.write_str(MSG_AUTH_UNSUPPORTED_ALG),
223            Self::ClaimMismatch => f.write_str(MSG_AUTH_CLAIM_MISMATCH),
224            Self::Forbidden => f.write_str(MSG_AUTH_FORBIDDEN),
225        }
226    }
227}
228
229/// Implements [`Error`] for [`AuthError`].
230impl Error for AuthError {}
231
232/// Single-pass Serde serialization for [`JwtClaims`] without `#[serde(flatten)]` overhead.
233impl Serialize for JwtClaims {
234    /// Serializes standard claims and flattened `extra` entries directly into a JSON map.
235    ///
236    /// # Arguments
237    ///
238    /// - `S` - Serde serializer.
239    ///
240    /// # Returns
241    ///
242    /// - `Result<S::Ok, S::Error>` - Serialized representation or error.
243    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
244    where
245        S: Serializer,
246    {
247        let Self {
248            sub,
249            iss,
250            aud,
251            exp,
252            nbf,
253            iat,
254            jti,
255            roles,
256            extra,
257        } = self;
258        let mut field_count: usize = 1 + extra.len();
259        if iss.is_some() {
260            field_count += 1;
261        }
262        if aud.is_some() {
263            field_count += 1;
264        }
265        if exp.is_some() {
266            field_count += 1;
267        }
268        if nbf.is_some() {
269            field_count += 1;
270        }
271        if iat.is_some() {
272            field_count += 1;
273        }
274        if jti.is_some() {
275            field_count += 1;
276        }
277        if !roles.is_empty() {
278            field_count += 1;
279        }
280        let mut map: S::SerializeMap = serializer.serialize_map(Some(field_count))?;
281        map.serialize_entry(CLAIM_SUB, sub)?;
282        if let Some(val) = iss {
283            map.serialize_entry(CLAIM_ISS, val)?;
284        }
285        if let Some(val) = aud {
286            map.serialize_entry(CLAIM_AUD, val)?;
287        }
288        if let Some(val) = exp {
289            map.serialize_entry(CLAIM_EXP, val)?;
290        }
291        if let Some(val) = nbf {
292            map.serialize_entry(CLAIM_NBF, val)?;
293        }
294        if let Some(val) = iat {
295            map.serialize_entry(CLAIM_IAT, val)?;
296        }
297        if let Some(val) = jti {
298            map.serialize_entry(CLAIM_JTI, val)?;
299        }
300        if !roles.is_empty() {
301            map.serialize_entry(CLAIM_ROLES, roles)?;
302        }
303        for (k, v) in extra {
304            map.serialize_entry(k, v)?;
305        }
306        map.end()
307    }
308}
309
310/// Zero-allocation Serde [`Visitor`] implementation for [`JwtClaimField`].
311impl<'de> Visitor<'de> for JwtClaimFieldVisitor {
312    type Value = JwtClaimField;
313
314    /// Describes the expected JSON object key for error diagnostics.
315    ///
316    /// # Arguments
317    ///
318    /// - `&mut Formatter<'_>` - Output formatter.
319    ///
320    /// # Returns
321    ///
322    /// - `fmt::Result` - Formatting outcome.
323    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
324        formatter.write_str(EXPECTING_JWT_FIELD)
325    }
326
327    /// Matches borrowed JSON object keys against standard JWT claims without allocating.
328    ///
329    /// # Arguments
330    ///
331    /// - `&str` - Decoded JSON key string.
332    ///
333    /// # Returns
334    ///
335    /// - `Result<Self::Value, E>` - Matched field variant.
336    #[inline]
337    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
338    where
339        E: de::Error,
340    {
341        Ok(match value {
342            CLAIM_SUB => JwtClaimField::Sub,
343            CLAIM_ISS => JwtClaimField::Iss,
344            CLAIM_AUD => JwtClaimField::Aud,
345            CLAIM_EXP => JwtClaimField::Exp,
346            CLAIM_NBF => JwtClaimField::Nbf,
347            CLAIM_IAT => JwtClaimField::Iat,
348            CLAIM_JTI => JwtClaimField::Jti,
349            CLAIM_ROLES => JwtClaimField::Roles,
350            _ => JwtClaimField::Extra(value.to_owned()),
351        })
352    }
353
354    /// Matches owned JSON object keys without re-allocating when storing into `extra`.
355    ///
356    /// # Arguments
357    ///
358    /// - `String` - Owned decoded JSON key string.
359    ///
360    /// # Returns
361    ///
362    /// - `Result<Self::Value, E>` - Matched field variant.
363    #[inline]
364    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
365    where
366        E: de::Error,
367    {
368        Ok(match value.as_str() {
369            CLAIM_SUB => JwtClaimField::Sub,
370            CLAIM_ISS => JwtClaimField::Iss,
371            CLAIM_AUD => JwtClaimField::Aud,
372            CLAIM_EXP => JwtClaimField::Exp,
373            CLAIM_NBF => JwtClaimField::Nbf,
374            CLAIM_IAT => JwtClaimField::Iat,
375            CLAIM_JTI => JwtClaimField::Jti,
376            CLAIM_ROLES => JwtClaimField::Roles,
377            _ => JwtClaimField::Extra(value),
378        })
379    }
380}
381
382/// Implements [`Deserialize`] for [`JwtClaimField`] using `deserialize_identifier`.
383impl<'de> Deserialize<'de> for JwtClaimField {
384    /// Deserializes a JSON claim field name with zero heap allocation for standard claims.
385    ///
386    /// # Arguments
387    ///
388    /// - `D` - Serde deserializer.
389    ///
390    /// # Returns
391    ///
392    /// - `Result<Self, D::Error>` - Parsed claim field discriminator.
393    #[inline]
394    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
395    where
396        D: Deserializer<'de>,
397    {
398        deserializer.deserialize_identifier(JwtClaimFieldVisitor)
399    }
400}
401
402/// Zero-buffering Serde [`Visitor`] implementation for [`JwtClaims`].
403impl<'de> Visitor<'de> for JwtClaimsVisitor {
404    type Value = JwtClaims;
405
406    /// Describes the expected input structure for Serde error diagnostics.
407    ///
408    /// # Arguments
409    ///
410    /// - `&mut Formatter<'_>` - Output formatter.
411    ///
412    /// # Returns
413    ///
414    /// - `fmt::Result` - Formatting outcome.
415    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
416        formatter.write_str(EXPECTING_JWT_CLAIMS)
417    }
418
419    /// Streams map entries directly into [`JwtClaims`] without buffering into `Content` trees.
420    ///
421    /// # Arguments
422    ///
423    /// - `A` - Serde map access iterator.
424    ///
425    /// # Returns
426    ///
427    /// - `Result<Self::Value, A::Error>` - Deserialized [`JwtClaims`] or error.
428    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
429    where
430        A: MapAccess<'de>,
431    {
432        let mut seen: u8 = 0;
433        let mut sub: Option<String> = None;
434        let mut iss: Option<String> = None;
435        let mut aud: Option<String> = None;
436        let mut exp: Option<u64> = None;
437        let mut nbf: Option<u64> = None;
438        let mut iat: Option<u64> = None;
439        let mut jti: Option<String> = None;
440        let mut roles: Option<Vec<String>> = None;
441        let mut extra: HashMap<String, Value> = HashMap::new();
442        while let Some(field) = map.next_key::<JwtClaimField>()? {
443            match field {
444                JwtClaimField::Sub => {
445                    if (seen & CLAIM_BIT_SUB) != 0 {
446                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_SUB));
447                    }
448                    seen |= CLAIM_BIT_SUB;
449                    sub = Some(map.next_value()?);
450                }
451                JwtClaimField::Iss => {
452                    if (seen & CLAIM_BIT_ISS) != 0 {
453                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_ISS));
454                    }
455                    seen |= CLAIM_BIT_ISS;
456                    iss = map.next_value()?;
457                }
458                JwtClaimField::Aud => {
459                    if (seen & CLAIM_BIT_AUD) != 0 {
460                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_AUD));
461                    }
462                    seen |= CLAIM_BIT_AUD;
463                    aud = map.next_value()?;
464                }
465                JwtClaimField::Exp => {
466                    if (seen & CLAIM_BIT_EXP) != 0 {
467                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_EXP));
468                    }
469                    seen |= CLAIM_BIT_EXP;
470                    exp = map.next_value()?;
471                }
472                JwtClaimField::Nbf => {
473                    if (seen & CLAIM_BIT_NBF) != 0 {
474                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_NBF));
475                    }
476                    seen |= CLAIM_BIT_NBF;
477                    nbf = map.next_value()?;
478                }
479                JwtClaimField::Iat => {
480                    if (seen & CLAIM_BIT_IAT) != 0 {
481                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_IAT));
482                    }
483                    seen |= CLAIM_BIT_IAT;
484                    iat = map.next_value()?;
485                }
486                JwtClaimField::Jti => {
487                    if (seen & CLAIM_BIT_JTI) != 0 {
488                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_JTI));
489                    }
490                    seen |= CLAIM_BIT_JTI;
491                    jti = map.next_value()?;
492                }
493                JwtClaimField::Roles => {
494                    if (seen & CLAIM_BIT_ROLES) != 0 {
495                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_ROLES));
496                    }
497                    seen |= CLAIM_BIT_ROLES;
498                    roles = Some(map.next_value()?);
499                }
500                JwtClaimField::Extra(key) => {
501                    let value: Value = map.next_value()?;
502                    extra.insert(key, value);
503                }
504            }
505        }
506        let sub: String = sub.ok_or_else(|| <A::Error as de::Error>::missing_field(CLAIM_SUB))?;
507        Ok(JwtClaims {
508            sub,
509            iss,
510            aud,
511            exp,
512            nbf,
513            iat,
514            jti,
515            roles: roles.unwrap_or_default(),
516            extra,
517        })
518    }
519}
520
521/// Single-pass Serde deserialization for [`JwtClaims`] without `#[serde(flatten)]` buffering.
522impl<'de> Deserialize<'de> for JwtClaims {
523    /// Deserializes a JSON claims object directly via [`JwtClaimsVisitor`].
524    ///
525    /// # Arguments
526    ///
527    /// - `D` - Serde deserializer.
528    ///
529    /// # Returns
530    ///
531    /// - `Result<Self, D::Error>` - Deserialized [`JwtClaims`] or error.
532    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
533    where
534        D: Deserializer<'de>,
535    {
536        deserializer.deserialize_map(JwtClaimsVisitor)
537    }
538}
539
540/// Inherent implementation of [`JwtClaims`].
541impl JwtClaims {
542    /// Creates a minimal [`JwtClaims`] payload for `subject` expiring in `ttl_secs`.
543    ///
544    /// # Arguments
545    ///
546    /// - `S` - Subject identifier convertible into `String`.
547    /// - `u64` - Lifetime in seconds from current Unix time.
548    ///
549    /// # Returns
550    ///
551    /// - `Self` - Constructed claims payload.
552    pub fn new<S>(subject: S, ttl_secs: u64) -> Self
553    where
554        S: Into<String>,
555    {
556        let now: u64 = auth_now_secs();
557        Self {
558            sub: subject.into(),
559            iss: None,
560            aud: None,
561            exp: Some(now.saturating_add(ttl_secs)),
562            nbf: Some(now),
563            iat: Some(now),
564            jti: None,
565            roles: Vec::new(),
566            extra: HashMap::new(),
567        }
568    }
569
570    /// Attaches RBAC roles to this claims payload.
571    ///
572    /// # Arguments
573    ///
574    /// - `I` - Iterator of role names.
575    ///
576    /// # Returns
577    ///
578    /// - `Self` - Updated claims payload.
579    pub fn with_roles<I, S>(mut self, roles: I) -> Self
580    where
581        I: IntoIterator<Item = S>,
582        S: Into<String>,
583    {
584        self.set_roles(roles.into_iter().map(Into::into).collect());
585        self
586    }
587
588    /// Sets the `iss` issuer claim.
589    ///
590    /// # Arguments
591    ///
592    /// - `S` - Issuer identifier.
593    ///
594    /// # Returns
595    ///
596    /// - `Self` - Updated claims payload.
597    pub fn with_issuer<S>(mut self, issuer: S) -> Self
598    where
599        S: Into<String>,
600    {
601        self.set_iss(Some(issuer.into()));
602        self
603    }
604
605    /// Sets the `aud` audience claim.
606    ///
607    /// # Arguments
608    ///
609    /// - `S` - Audience identifier.
610    ///
611    /// # Returns
612    ///
613    /// - `Self` - Updated claims payload.
614    pub fn with_audience<S>(mut self, audience: S) -> Self
615    where
616        S: Into<String>,
617    {
618        self.set_aud(Some(audience.into()));
619        self
620    }
621}
622
623/// Inherent implementation of [`JwtCodec`].
624impl JwtCodec {
625    /// Creates an HS256 [`JwtCodec`] signed and verified with `secret`.
626    ///
627    /// # Arguments
628    ///
629    /// - `S` - Shared HMAC-SHA256 secret bytes convertible into `Vec<u8>`.
630    ///
631    /// # Returns
632    ///
633    /// - `Self` - Ready JWT codec with 60 s default clock-skew leeway.
634    pub fn new<S>(secret: S) -> Self
635    where
636        S: Into<Vec<u8>>,
637    {
638        let default_secret: Vec<u8> = secret.into();
639        let default_hmac: HmacSha256Key = HmacSha256Key::new(&default_secret);
640        Self {
641            default_secret,
642            default_hmac,
643            default_kid: None,
644            default_header_b64: DEFAULT_HS256_HEADER_B64.to_owned(),
645            keyring: hash_map_xx_hash3_64(),
646            keyring_hmac: hash_map_xx_hash3_64(),
647            leeway_secs: DEFAULT_JWT_LEEWAY_SECS,
648            required_issuer: None,
649            required_audience: None,
650        }
651    }
652
653    /// Registers an additional verification key under `kid` for seamless key rotation.
654    ///
655    /// # Arguments
656    ///
657    /// - `K` - Key identifier convertible into `String`.
658    /// - `S` - Secret bytes for this `kid`.
659    ///
660    /// # Returns
661    ///
662    /// - `Self` - Updated codec.
663    pub fn with_key<K, S>(mut self, kid: K, secret: S) -> Self
664    where
665        K: Into<String>,
666        S: Into<Vec<u8>>,
667    {
668        let Self {
669            keyring,
670            keyring_hmac,
671            ..
672        } = &mut self;
673        let kid_str: String = kid.into();
674        let secret_bytes: Vec<u8> = secret.into();
675        let precomputed: HmacSha256Key = HmacSha256Key::new(&secret_bytes);
676        keyring.insert(kid_str.clone(), secret_bytes);
677        keyring_hmac.insert(kid_str, precomputed);
678        self
679    }
680
681    /// Sets the default `kid` stamped on newly encoded tokens (and registers its secret if absent).
682    ///
683    /// # Arguments
684    ///
685    /// - `K` - Active signing key identifier.
686    ///
687    /// # Returns
688    ///
689    /// - `Self` - Updated codec.
690    pub fn with_default_kid<K>(mut self, kid: K) -> Self
691    where
692        K: Into<String>,
693    {
694        let Self {
695            default_kid,
696            default_secret,
697            default_hmac,
698            default_header_b64,
699            keyring,
700            keyring_hmac,
701            ..
702        } = &mut self;
703        let kid_str: String = kid.into();
704        if !keyring.contains_key(&kid_str) {
705            keyring.insert(kid_str.clone(), default_secret.clone());
706            keyring_hmac.insert(kid_str.clone(), *default_hmac);
707        }
708        *default_header_b64 = encode_hs256_header_b64(Some(&kid_str));
709        *default_kid = Some(kid_str);
710        self
711    }
712
713    /// Sets the allowed clock-skew leeway in seconds for `exp` and `nbf` checks.
714    ///
715    /// # Arguments
716    ///
717    /// - `u64` - Leeway in seconds.
718    ///
719    /// # Returns
720    ///
721    /// - `Self` - Updated codec.
722    pub fn with_leeway_secs(mut self, leeway_secs: u64) -> Self {
723        let Self {
724            leeway_secs: slot, ..
725        } = &mut self;
726        *slot = leeway_secs;
727        self
728    }
729
730    /// Requires every decoded token's `iss` claim to match `issuer`.
731    ///
732    /// # Arguments
733    ///
734    /// - `S` - Required issuer string.
735    ///
736    /// # Returns
737    ///
738    /// - `Self` - Updated codec.
739    pub fn with_required_issuer<S>(mut self, issuer: S) -> Self
740    where
741        S: Into<String>,
742    {
743        let Self {
744            required_issuer, ..
745        } = &mut self;
746        *required_issuer = Some(issuer.into());
747        self
748    }
749
750    /// Requires every decoded token's `aud` claim to match `audience`.
751    ///
752    /// # Arguments
753    ///
754    /// - `S` - Required audience string.
755    ///
756    /// # Returns
757    ///
758    /// - `Self` - Updated codec.
759    pub fn with_required_audience<S>(mut self, audience: S) -> Self
760    where
761        S: Into<String>,
762    {
763        let Self {
764            required_audience, ..
765        } = &mut self;
766        *required_audience = Some(audience.into());
767        self
768    }
769
770    /// Encodes and signs `claims` into a compact HS256 JWT (`header.payload.signature`).
771    ///
772    /// # Arguments
773    ///
774    /// - `&JwtClaims` - Claims payload to sign.
775    ///
776    /// # Returns
777    ///
778    /// - `Result<String, AuthError>` - Compact JWT string, or [`AuthError::InvalidCredentials`] on serialization failure.
779    pub fn encode(&self, claims: &JwtClaims) -> Result<String, AuthError> {
780        let Self {
781            default_hmac,
782            default_kid,
783            default_header_b64,
784            keyring_hmac,
785            ..
786        } = self;
787        let mut claims_buf: StackJsonBuf = StackJsonBuf::new();
788        write_jwt_claims_json(claims, &mut claims_buf)?;
789        let claims_json: &[u8] = claims_buf.as_slice();
790        let claims_b64_len: usize = (claims_json.len() * 4).div_ceil(3);
791        let total_len: usize = default_header_b64.len() + 1 + claims_b64_len + 1 + HMAC_SIG_B64_LEN;
792        let mut token_bytes: Vec<u8> = Vec::with_capacity(total_len);
793        token_bytes.extend_from_slice(default_header_b64.as_bytes());
794        token_bytes.push(ASCII_DOT);
795        base64url_encode_into(claims_json, &mut token_bytes);
796        let hmac_key: &HmacSha256Key = match default_kid {
797            Some(kid) => keyring_hmac.get(kid).unwrap_or(default_hmac),
798            None => default_hmac,
799        };
800        let mac: [u8; 32] = hmac_key.mac(&token_bytes);
801        token_bytes.push(ASCII_DOT);
802        base64url_encode_into(&mac, &mut token_bytes);
803        String::from_utf8(token_bytes).map_err(|_| AuthError::InvalidCredentials)
804    }
805
806    /// Verifies and decodes a compact HS256 JWT at timestamp `now_secs`.
807    ///
808    /// # Arguments
809    ///
810    /// - `&str` - Compact JWT string (`header.payload.signature`).
811    /// - `u64` - Current Unix timestamp in seconds.
812    ///
813    /// # Returns
814    ///
815    /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or detailed [`AuthError`].
816    pub fn decode_at(&self, token: &str, now_secs: u64) -> Result<JwtClaims, AuthError> {
817        let Self {
818            default_hmac,
819            default_kid,
820            default_header_b64,
821            keyring_hmac,
822            leeway_secs,
823            required_issuer,
824            required_audience,
825            ..
826        } = self;
827        let (header_b64, rest): (&str, &str) =
828            token.split_once('.').ok_or(AuthError::InvalidCredentials)?;
829        let (payload_b64, sig_b64): (&str, &str) =
830            rest.split_once('.').ok_or(AuthError::InvalidCredentials)?;
831        if sig_b64.contains('.')
832            || header_b64.is_empty()
833            || payload_b64.is_empty()
834            || sig_b64.is_empty()
835        {
836            return Err(AuthError::InvalidCredentials);
837        }
838        let hmac_key: &HmacSha256Key = if header_b64 == default_header_b64.as_str() {
839            match default_kid {
840                Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
841                None => default_hmac,
842            }
843        } else if header_b64 == DEFAULT_HS256_HEADER_B64 {
844            default_hmac
845        } else {
846            let trimmed_hdr: &[u8] = header_b64.trim_end_matches('=').as_bytes();
847            let decoded_hdr_len: usize = (trimmed_hdr.len() * 3) / 4;
848            let mut hdr_stack: [u8; JWT_STACK_HEADER_CAP] = [0u8; JWT_STACK_HEADER_CAP];
849            let hdr_heap: Vec<u8>;
850            let hdr_slice: &[u8] = if decoded_hdr_len <= JWT_STACK_HEADER_CAP {
851                let written: usize =
852                    decode_base64_into(trimmed_hdr, &BASE64URL_DECODE_TABLE, &mut hdr_stack)
853                        .ok_or(AuthError::InvalidCredentials)?;
854                &hdr_stack[..written]
855            } else {
856                hdr_heap = base64url_decode(header_b64).ok_or(AuthError::InvalidCredentials)?;
857                &hdr_heap
858            };
859            let header: JwtHeaderRef<'_> =
860                from_slice(hdr_slice).map_err(|_| AuthError::InvalidCredentials)?;
861            if header.alg.as_ref() != JWT_ALG_HS256 {
862                return Err(AuthError::UnsupportedAlgorithm);
863            }
864            match header.kid.as_deref() {
865                Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
866                None => default_hmac,
867            }
868        };
869        let provided_sig: [u8; 32] =
870            decode_base64url_32(sig_b64).ok_or(AuthError::InvalidCredentials)?;
871        let signed_len: usize = header_b64.len() + 1 + payload_b64.len();
872        let expected_mac: [u8; 32] = hmac_key.mac(&token.as_bytes()[..signed_len]);
873        if !constant_time_eq(&provided_sig, &expected_mac) {
874            return Err(AuthError::InvalidCredentials);
875        }
876        let trimmed_payload: &[u8] = payload_b64.trim_end_matches('=').as_bytes();
877        let decoded_payload_len: usize = (trimmed_payload.len() * 3) / 4;
878        let claims: JwtClaims = if decoded_payload_len <= JWT_STACK_FAST_PAYLOAD_CAP {
879            let mut fast_stack: [u8; JWT_STACK_FAST_PAYLOAD_CAP] =
880                [0u8; JWT_STACK_FAST_PAYLOAD_CAP];
881            let written: usize =
882                decode_base64_into(trimmed_payload, &BASE64URL_DECODE_TABLE, &mut fast_stack)
883                    .ok_or(AuthError::InvalidCredentials)?;
884            from_slice(&fast_stack[..written]).map_err(|_| AuthError::InvalidCredentials)?
885        } else if decoded_payload_len <= JWT_STACK_PAYLOAD_CAP {
886            let mut payload_stack: [u8; JWT_STACK_PAYLOAD_CAP] = [0u8; JWT_STACK_PAYLOAD_CAP];
887            let written: usize =
888                decode_base64_into(trimmed_payload, &BASE64URL_DECODE_TABLE, &mut payload_stack)
889                    .ok_or(AuthError::InvalidCredentials)?;
890            from_slice(&payload_stack[..written]).map_err(|_| AuthError::InvalidCredentials)?
891        } else {
892            let payload_heap: Vec<u8> =
893                base64url_decode(payload_b64).ok_or(AuthError::InvalidCredentials)?;
894            from_slice(&payload_heap).map_err(|_| AuthError::InvalidCredentials)?
895        };
896        let JwtClaims {
897            iss, aud, exp, nbf, ..
898        } = &claims;
899        if let Some(exp_val) = *exp
900            && now_secs > exp_val.saturating_add(*leeway_secs)
901        {
902            return Err(AuthError::TokenExpired);
903        }
904        if let Some(nbf_val) = *nbf
905            && now_secs.saturating_add(*leeway_secs) < nbf_val
906        {
907            return Err(AuthError::TokenNotYetValid);
908        }
909        if let Some(expected_iss) = required_issuer
910            && iss.as_deref() != Some(expected_iss.as_str())
911        {
912            return Err(AuthError::ClaimMismatch);
913        }
914        if let Some(expected_aud) = required_audience
915            && aud.as_deref() != Some(expected_aud.as_str())
916        {
917            return Err(AuthError::ClaimMismatch);
918        }
919        Ok(claims)
920    }
921
922    /// Verifies and decodes a compact HS256 JWT against current system time.
923    ///
924    /// # Arguments
925    ///
926    /// - `&str` - Compact JWT string.
927    ///
928    /// # Returns
929    ///
930    /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or [`AuthError`].
931    pub fn decode(&self, token: &str) -> Result<JwtClaims, AuthError> {
932        self.decode_at(token, auth_now_secs())
933    }
934}
935
936/// Inherent helpers for [`AuthPrincipal`].
937impl AuthPrincipal {
938    /// Checks whether this principal possesses `role`.
939    ///
940    /// # Arguments
941    ///
942    /// - `&str` - Role name to check.
943    ///
944    /// # Returns
945    ///
946    /// - `bool` - `true` when the role is granted.
947    #[inline]
948    pub fn has_role(&self, role: &str) -> bool {
949        self.get_roles().iter().any(|item: &String| item == role)
950    }
951}
952
953/// Inherent implementation of [`JwtAuthenticator`].
954impl JwtAuthenticator {
955    /// Creates a [`JwtAuthenticator`] backed by `codec`.
956    ///
957    /// # Arguments
958    ///
959    /// - `JwtCodec` - Configured HS256 codec.
960    ///
961    /// # Returns
962    ///
963    /// - `Self` - Bearer JWT authenticator.
964    pub fn new(codec: JwtCodec) -> Self {
965        Self { codec }
966    }
967}
968
969/// Implements [`Authenticator`] for [`JwtAuthenticator`].
970impl Authenticator for JwtAuthenticator {
971    /// Authenticates `Authorization: Bearer <token>` requests via [`JwtCodec`].
972    ///
973    /// # Arguments
974    ///
975    /// - `&'a self` - Shared reference to self.
976    /// - `&'a Context` - Incoming request context.
977    ///
978    /// # Returns
979    ///
980    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
981    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
982        let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
983        Box::pin(async move { result })
984    }
985
986    /// Evaluates Bearer JWT verification synchronously without `Box::pin` allocation.
987    ///
988    /// # Arguments
989    ///
990    /// - `&Self` - Shared reference to self.
991    /// - `&Context` - Incoming request context.
992    ///
993    /// # Returns
994    ///
995    /// - `Option<Result<AuthPrincipal, AuthError>>` - Always `Some` with the verification result.
996    #[inline]
997    fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
998        Some(self.eval_sync(ctx))
999    }
1000}
1001
1002/// Synchronous JWT authentication helper for [`JwtAuthenticator`].
1003impl JwtAuthenticator {
1004    /// Verifies `Authorization: Bearer <token>` synchronously.
1005    ///
1006    /// # Arguments
1007    ///
1008    /// - `&Context` - Incoming request context.
1009    ///
1010    /// # Returns
1011    ///
1012    /// - `Result<AuthPrincipal, AuthError>` - Verified principal or authentication error.
1013    #[inline]
1014    fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
1015        let Self { codec } = self;
1016        match request_header_back(ctx.get_request(), AUTHORIZATION) {
1017            None => Err(AuthError::MissingCredentials),
1018            Some(header) => match strip_auth_scheme(header, PREFIX_BEARER) {
1019                None => Err(AuthError::MissingCredentials),
1020                Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
1021                    subject: claims.get_sub().clone(),
1022                    roles: claims.get_roles().clone(),
1023                    scheme: AuthScheme::BearerJwt,
1024                    claims: Some(claims),
1025                }),
1026            },
1027        }
1028    }
1029}
1030
1031/// Default construction for [`ApiKeyAuthenticator`].
1032impl Default for ApiKeyAuthenticator {
1033    /// Constructs an empty [`ApiKeyAuthenticator`] reading `X-Api-Key`.
1034    fn default() -> Self {
1035        Self::new(X_API_KEY)
1036    }
1037}
1038
1039/// Inherent implementation of [`ApiKeyAuthenticator`].
1040impl ApiKeyAuthenticator {
1041    /// Creates an [`ApiKeyAuthenticator`] reading `header_name`.
1042    ///
1043    /// # Arguments
1044    ///
1045    /// - `H` - Header name convertible into `String`.
1046    ///
1047    /// # Returns
1048    ///
1049    /// - `Self` - Empty API-key authenticator.
1050    pub fn new<H>(header_name: H) -> Self
1051    where
1052        H: Into<String>,
1053    {
1054        Self {
1055            header_name: header_name.into().to_ascii_lowercase(),
1056            entries: Vec::new(),
1057        }
1058    }
1059
1060    /// Registers an allowed API key associated with `subject` and `roles`.
1061    ///
1062    /// # Arguments
1063    ///
1064    /// - `K` - Secret API key string.
1065    /// - `S` - Subject name assigned when matched.
1066    /// - `I` - Iterator of role names.
1067    ///
1068    /// # Returns
1069    ///
1070    /// - `Self` - Updated authenticator.
1071    pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
1072    where
1073        K: Into<String>,
1074        S: Into<String>,
1075        I: IntoIterator<Item = R>,
1076        R: Into<String>,
1077    {
1078        let Self { entries, .. } = &mut self;
1079        entries.push((
1080            api_key.into().into_bytes(),
1081            subject.into(),
1082            roles.into_iter().map(Into::into).collect(),
1083        ));
1084        self
1085    }
1086}
1087
1088/// Implements [`Authenticator`] for [`ApiKeyAuthenticator`].
1089impl Authenticator for ApiKeyAuthenticator {
1090    /// Authenticates incoming API key headers using constant-time key comparisons.
1091    ///
1092    /// # Arguments
1093    ///
1094    /// - `&'a self` - Shared reference to self.
1095    /// - `&'a Context` - Incoming request context.
1096    ///
1097    /// # Returns
1098    ///
1099    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
1100    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1101        let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
1102        Box::pin(async move { result })
1103    }
1104
1105    /// Evaluates API-key verification synchronously without `Box::pin` allocation.
1106    ///
1107    /// # Arguments
1108    ///
1109    /// - `&Self` - Shared reference to self.
1110    /// - `&Context` - Incoming request context.
1111    ///
1112    /// # Returns
1113    ///
1114    /// - `Option<Result<AuthPrincipal, AuthError>>` - Always `Some` with the verification result.
1115    #[inline]
1116    fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
1117        Some(self.eval_sync(ctx))
1118    }
1119}
1120
1121/// Synchronous API-key authentication helper for [`ApiKeyAuthenticator`].
1122impl ApiKeyAuthenticator {
1123    /// Verifies configured API keys synchronously in constant time.
1124    ///
1125    /// # Arguments
1126    ///
1127    /// - `&Context` - Incoming request context.
1128    ///
1129    /// # Returns
1130    ///
1131    /// - `Result<AuthPrincipal, AuthError>` - Verified principal or authentication error.
1132    #[inline]
1133    fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
1134        let Self {
1135            header_name,
1136            entries,
1137        } = self;
1138        match request_header_back(ctx.get_request(), header_name) {
1139            None => Err(AuthError::MissingCredentials),
1140            Some(candidate) => {
1141                let candidate_bytes: &[u8] = candidate.trim().as_bytes();
1142                let mut matched_idx: Option<usize> = None;
1143                for (idx, (secret, _, _)) in entries.iter().enumerate() {
1144                    if constant_time_eq(candidate_bytes, secret) {
1145                        matched_idx = Some(idx);
1146                    }
1147                }
1148                match matched_idx {
1149                    Some(idx) => {
1150                        let (_, subject, roles): &(Vec<u8>, String, Vec<String>) = &entries[idx];
1151                        Ok(AuthPrincipal {
1152                            subject: subject.clone(),
1153                            roles: roles.clone(),
1154                            scheme: AuthScheme::ApiKey,
1155                            claims: None,
1156                        })
1157                    }
1158                    None => Err(AuthError::InvalidCredentials),
1159                }
1160            }
1161        }
1162    }
1163}
1164
1165/// Default construction for [`BasicAuthenticator`].
1166impl Default for BasicAuthenticator {
1167    /// Constructs an empty [`BasicAuthenticator`].
1168    fn default() -> Self {
1169        Self::new()
1170    }
1171}
1172
1173/// Inherent implementation of [`BasicAuthenticator`].
1174impl BasicAuthenticator {
1175    /// Creates an empty [`BasicAuthenticator`].
1176    ///
1177    /// # Returns
1178    ///
1179    /// - `Self` - Empty HTTP Basic authenticator.
1180    pub fn new() -> Self {
1181        Self {
1182            users: hash_map_xx_hash3_64(),
1183        }
1184    }
1185
1186    /// Registers a Basic-auth user with `username`, `password`, and `roles`.
1187    ///
1188    /// # Arguments
1189    ///
1190    /// - `U` - Username string.
1191    /// - `P` - Password string.
1192    /// - `I` - Iterator of role names.
1193    ///
1194    /// # Returns
1195    ///
1196    /// - `Self` - Updated authenticator.
1197    pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
1198    where
1199        U: Into<String>,
1200        P: Into<String>,
1201        I: IntoIterator<Item = R>,
1202        R: Into<String>,
1203    {
1204        let Self { users } = &mut self;
1205        users.insert(
1206            username.into(),
1207            (
1208                password.into().into_bytes(),
1209                roles.into_iter().map(Into::into).collect(),
1210            ),
1211        );
1212        self
1213    }
1214}
1215
1216/// Implements [`Authenticator`] for [`BasicAuthenticator`].
1217impl Authenticator for BasicAuthenticator {
1218    /// Authenticates `Authorization: Basic <base64>` using constant-time password checks.
1219    ///
1220    /// # Arguments
1221    ///
1222    /// - `&'a self` - Shared reference to self.
1223    /// - `&'a Context` - Incoming request context.
1224    ///
1225    /// # Returns
1226    ///
1227    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
1228    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1229        let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
1230        Box::pin(async move { result })
1231    }
1232
1233    /// Evaluates HTTP Basic authentication synchronously without `Box::pin` allocation.
1234    ///
1235    /// # Arguments
1236    ///
1237    /// - `&Self` - Shared reference to self.
1238    /// - `&Context` - Incoming request context.
1239    ///
1240    /// # Returns
1241    ///
1242    /// - `Option<Result<AuthPrincipal, AuthError>>` - Always `Some` with the verification result.
1243    #[inline]
1244    fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
1245        Some(self.eval_sync(ctx))
1246    }
1247}
1248
1249/// Synchronous HTTP Basic authentication helper for [`BasicAuthenticator`].
1250impl BasicAuthenticator {
1251    /// Verifies `Authorization: Basic <base64>` credentials synchronously.
1252    ///
1253    /// # Arguments
1254    ///
1255    /// - `&Context` - Incoming request context.
1256    ///
1257    /// # Returns
1258    ///
1259    /// - `Result<AuthPrincipal, AuthError>` - Verified principal or authentication error.
1260    #[inline]
1261    fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
1262        let Self { users } = self;
1263        match request_header_back(ctx.get_request(), AUTHORIZATION) {
1264            None => Err(AuthError::MissingCredentials),
1265            Some(header) => match strip_auth_scheme(header, PREFIX_BASIC) {
1266                None => Err(AuthError::MissingCredentials),
1267                Some(encoded) => {
1268                    let trimmed_b64: &[u8] = encoded.trim_end_matches('=').as_bytes();
1269                    let decoded_len: usize = (trimmed_b64.len() * 3) / 4;
1270                    let mut stack_buf: [u8; BASIC_STACK_CAP] = [0u8; BASIC_STACK_CAP];
1271                    let heap_buf: Vec<u8>;
1272                    let raw_opt: Option<&[u8]> = if decoded_len <= BASIC_STACK_CAP {
1273                        decode_base64_into(trimmed_b64, &BASE64_STD_DECODE_TABLE, &mut stack_buf)
1274                            .map(|written: usize| &stack_buf[..written])
1275                    } else if let Some(buf) = base64_decode(encoded) {
1276                        heap_buf = buf;
1277                        Some(heap_buf.as_slice())
1278                    } else {
1279                        None
1280                    };
1281                    match raw_opt.and_then(|raw: &[u8]| from_utf8(raw).ok()) {
1282                        None => Err(AuthError::InvalidCredentials),
1283                        Some(decoded) => match decoded.split_once(':') {
1284                            None => Err(AuthError::InvalidCredentials),
1285                            Some((user, pass)) => match users.get(user) {
1286                                Some((expected_pass, roles))
1287                                    if constant_time_eq(pass.as_bytes(), expected_pass) =>
1288                                {
1289                                    Ok(AuthPrincipal {
1290                                        subject: user.to_owned(),
1291                                        roles: roles.clone(),
1292                                        scheme: AuthScheme::Basic,
1293                                        claims: None,
1294                                    })
1295                                }
1296                                _ => Err(AuthError::InvalidCredentials),
1297                            },
1298                        },
1299                    }
1300                }
1301            },
1302        }
1303    }
1304}
1305
1306/// Inherent implementation of [`CompositeAuthenticator`].
1307impl CompositeAuthenticator {
1308    /// Creates a [`CompositeAuthenticator`] chaining `chain` in priority order.
1309    ///
1310    /// # Arguments
1311    ///
1312    /// - `Vec<Arc<dyn Authenticator>>` - Ordered list of authenticators.
1313    ///
1314    /// # Returns
1315    ///
1316    /// - `Self` - Composite authenticator.
1317    pub fn new(chain: Vec<Arc<dyn Authenticator>>) -> Self {
1318        Self { chain }
1319    }
1320}
1321
1322/// Implements [`Authenticator`] for [`CompositeAuthenticator`].
1323impl Authenticator for CompositeAuthenticator {
1324    /// Evaluates each authenticator in order, returning the first verified [`AuthPrincipal`].
1325    ///
1326    /// # Arguments
1327    ///
1328    /// - `&'a self` - Shared reference to self.
1329    /// - `&'a Context` - Incoming request context.
1330    ///
1331    /// # Returns
1332    ///
1333    /// - `AuthFuture<'a>` - Future resolving to the first matching [`AuthPrincipal`] or last non-missing error.
1334    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1335        let Self { chain } = self;
1336        Box::pin(async move {
1337            let mut last_err: AuthError = AuthError::MissingCredentials;
1338            for auth in chain {
1339                match auth.authenticate(ctx).await {
1340                    Ok(principal) => return Ok(principal),
1341                    Err(AuthError::MissingCredentials) => {}
1342                    Err(err) => last_err = err,
1343                }
1344            }
1345            Err(last_err)
1346        })
1347    }
1348}
1349
1350/// Default construction for [`AuthConfig`].
1351impl Default for AuthConfig {
1352    /// Constructs a default [`AuthConfig`] with Bearer realm challenge and no exempt paths.
1353    fn default() -> Self {
1354        Self {
1355            exempt_paths: Vec::new(),
1356            required_roles: Vec::new(),
1357            require_all_roles: false,
1358            www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
1359        }
1360    }
1361}
1362
1363/// Inherent builders for [`AuthConfig`].
1364impl AuthConfig {
1365    /// Configures exact paths excluded from authentication checks.
1366    ///
1367    /// # Arguments
1368    ///
1369    /// - `I` - Iterator of exempt paths.
1370    ///
1371    /// # Returns
1372    ///
1373    /// - `Self` - Updated configuration.
1374    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
1375    where
1376        I: IntoIterator<Item = S>,
1377        S: Into<String>,
1378    {
1379        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
1380        self
1381    }
1382
1383    /// Configures roles required to access protected routes.
1384    ///
1385    /// # Arguments
1386    ///
1387    /// - `I` - Iterator of required role names.
1388    ///
1389    /// # Returns
1390    ///
1391    /// - `Self` - Updated configuration.
1392    pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
1393    where
1394        I: IntoIterator<Item = S>,
1395        S: Into<String>,
1396    {
1397        self.set_required_roles(roles.into_iter().map(Into::into).collect());
1398        self
1399    }
1400}
1401
1402/// Inherent implementation of [`AuthPlugin`].
1403impl AuthPlugin {
1404    /// Initializes the global [`AuthPlugin`] once with `config` and `authenticator`.
1405    ///
1406    /// # Arguments
1407    ///
1408    /// - `AuthConfig` - Path-exclusion and RBAC policy.
1409    /// - `Arc<dyn Authenticator>` - Pluggable authenticator implementation.
1410    ///
1411    /// # Returns
1412    ///
1413    /// - `&'static Self` - Reference to the initialized global plugin.
1414    pub fn init(config: AuthConfig, authenticator: Arc<dyn Authenticator>) -> &'static Self {
1415        AUTH_PLUGIN.get_or_init(|| {
1416            let exempt_set: Option<HashSetXxHash3_64<String>> =
1417                if config.get_exempt_paths().len() > EXEMPT_SET_THRESHOLD {
1418                    let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
1419                    for path in config.get_exempt_paths() {
1420                        set.insert(path.clone());
1421                    }
1422                    Some(set)
1423                } else {
1424                    None
1425                };
1426            let mut resp_401: Response = Response::default();
1427            resp_401
1428                .set_status_code(HttpStatus::Unauthorized.code())
1429                .set_header(WWW_AUTHENTICATE, config.get_www_authenticate())
1430                .set_body(Vec::new());
1431            let prebuilt_401_wire: Vec<u8> = resp_401.build();
1432            let mut resp_403: Response = Response::default();
1433            resp_403
1434                .set_status_code(HttpStatus::Forbidden.code())
1435                .set_body(Vec::new());
1436            let prebuilt_403_wire: Vec<u8> = resp_403.build();
1437            Self {
1438                config,
1439                authenticator,
1440                exempt_set,
1441                prebuilt_401_wire,
1442                prebuilt_403_wire,
1443            }
1444        })
1445    }
1446
1447    /// Returns the initialized global [`AuthPlugin`], if initialized.
1448    ///
1449    /// # Returns
1450    ///
1451    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1452    #[inline(always)]
1453    pub fn get() -> Option<&'static Self> {
1454        AUTH_PLUGIN.get()
1455    }
1456
1457    /// Returns the active [`AuthConfig`].
1458    ///
1459    /// # Returns
1460    ///
1461    /// - `&AuthConfig` - Active authorization policy.
1462    #[inline(always)]
1463    pub fn get_config(&self) -> &AuthConfig {
1464        &self.config
1465    }
1466
1467    /// Returns the active [`Arc<dyn Authenticator>`].
1468    ///
1469    /// # Returns
1470    ///
1471    /// - `&Arc<dyn Authenticator>` - Active authenticator.
1472    #[inline(always)]
1473    pub fn get_authenticator(&self) -> &Arc<dyn Authenticator> {
1474        &self.authenticator
1475    }
1476
1477    /// Checks whether `path` is exempt from authentication without heap allocation.
1478    ///
1479    /// # Arguments
1480    ///
1481    /// - `&str` - Incoming request path.
1482    ///
1483    /// # Returns
1484    ///
1485    /// - `bool` - `true` when `path` is excluded from authentication.
1486    #[inline(always)]
1487    pub(crate) fn is_exempt_path(&self, path: &str) -> bool {
1488        let Self {
1489            config, exempt_set, ..
1490        } = self;
1491        if let Some(set) = exempt_set {
1492            return set.contains(path);
1493        }
1494        let exempt: &[String] = config.get_exempt_paths().as_slice();
1495        if exempt.is_empty() {
1496            return false;
1497        }
1498        exempt.iter().any(|item: &String| item.as_str() == path)
1499    }
1500
1501    /// Retrieves the verified [`AuthPrincipal`] previously stored in `ctx` by [`AuthHook`].
1502    ///
1503    /// # Arguments
1504    ///
1505    /// - `&Context` - Request context.
1506    ///
1507    /// # Returns
1508    ///
1509    /// - `Option<AuthPrincipal>` - Verified caller principal, if authenticated.
1510    pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
1511        ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
1512    }
1513
1514    /// Checks whether `principal` satisfies the configured RBAC role requirements.
1515    ///
1516    /// # Arguments
1517    ///
1518    /// - `&AuthPrincipal` - Verified principal.
1519    ///
1520    /// # Returns
1521    ///
1522    /// - `bool` - `true` when authorized.
1523    pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
1524        let required: &Vec<String> = self.get_config().get_required_roles();
1525        if required.is_empty() {
1526            return true;
1527        }
1528        if self.get_config().get_require_all_roles() {
1529            required
1530                .iter()
1531                .all(|role: &String| principal.has_role(role))
1532        } else {
1533            required
1534                .iter()
1535                .any(|role: &String| principal.has_role(role))
1536        }
1537    }
1538}
1539
1540/// Implements [`ServerHook`] for [`AuthHook`].
1541impl ServerHook for AuthHook {
1542    /// Constructs a per-request [`AuthHook`].
1543    ///
1544    /// # Arguments
1545    ///
1546    /// - `&mut Stream` - Connection stream.
1547    /// - `&mut Context` - Request context.
1548    ///
1549    /// # Returns
1550    ///
1551    /// - `Self` - Hook instance.
1552    #[inline(always)]
1553    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1554        Self
1555    }
1556
1557    /// Authenticates protected requests, verifies required roles, and attaches [`AuthPrincipal`].
1558    ///
1559    /// # Arguments
1560    ///
1561    /// - `Self` - Hook instance.
1562    /// - `&mut Stream` - Connection stream.
1563    /// - `&mut Context` - Request context.
1564    ///
1565    /// # Returns
1566    ///
1567    /// - `Status` - `Status::Continue` when unconfigured, exempt, or authorized; `Status::Reject` on `401`/`403`.
1568    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1569        let Some(plugin) = AuthPlugin::get() else {
1570            return Status::Continue;
1571        };
1572        let path: &str = ctx.get_request().get_path();
1573        if plugin.is_exempt_path(path) {
1574            return Status::Continue;
1575        }
1576        let auth_result: Result<AuthPrincipal, AuthError> =
1577            if let Some(sync_res) = plugin.get_authenticator().authenticate_sync(ctx) {
1578                sync_res
1579            } else {
1580                plugin.get_authenticator().authenticate(ctx).await
1581            };
1582        match auth_result {
1583            Ok(principal) => {
1584                if !plugin.is_authorized(&principal) {
1585                    let _: Result<(), ResponseError> =
1586                        stream.try_send(&plugin.prebuilt_403_wire).await;
1587                    return Status::Reject;
1588                }
1589                ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
1590                Status::Continue
1591            }
1592            Err(AuthError::Forbidden) => {
1593                let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_403_wire).await;
1594                Status::Reject
1595            }
1596            Err(_) => {
1597                let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_401_wire).await;
1598                Status::Reject
1599            }
1600        }
1601    }
1602}