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 Self { codec } = self;
983        Box::pin(async move {
984            match request_header_back(ctx.get_request(), AUTHORIZATION) {
985                None => Err(AuthError::MissingCredentials),
986                Some(header) => match strip_auth_scheme(header, PREFIX_BEARER) {
987                    None => Err(AuthError::MissingCredentials),
988                    Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
989                        subject: claims.get_sub().clone(),
990                        roles: claims.get_roles().clone(),
991                        scheme: AuthScheme::BearerJwt,
992                        claims: Some(claims),
993                    }),
994                },
995            }
996        })
997    }
998}
999
1000/// Default construction for [`ApiKeyAuthenticator`].
1001impl Default for ApiKeyAuthenticator {
1002    /// Constructs an empty [`ApiKeyAuthenticator`] reading `X-Api-Key`.
1003    fn default() -> Self {
1004        Self::new(X_API_KEY)
1005    }
1006}
1007
1008/// Inherent implementation of [`ApiKeyAuthenticator`].
1009impl ApiKeyAuthenticator {
1010    /// Creates an [`ApiKeyAuthenticator`] reading `header_name`.
1011    ///
1012    /// # Arguments
1013    ///
1014    /// - `H` - Header name convertible into `String`.
1015    ///
1016    /// # Returns
1017    ///
1018    /// - `Self` - Empty API-key authenticator.
1019    pub fn new<H>(header_name: H) -> Self
1020    where
1021        H: Into<String>,
1022    {
1023        Self {
1024            header_name: header_name.into().to_ascii_lowercase(),
1025            entries: Vec::new(),
1026        }
1027    }
1028
1029    /// Registers an allowed API key associated with `subject` and `roles`.
1030    ///
1031    /// # Arguments
1032    ///
1033    /// - `K` - Secret API key string.
1034    /// - `S` - Subject name assigned when matched.
1035    /// - `I` - Iterator of role names.
1036    ///
1037    /// # Returns
1038    ///
1039    /// - `Self` - Updated authenticator.
1040    pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
1041    where
1042        K: Into<String>,
1043        S: Into<String>,
1044        I: IntoIterator<Item = R>,
1045        R: Into<String>,
1046    {
1047        let Self { entries, .. } = &mut self;
1048        entries.push((
1049            api_key.into().into_bytes(),
1050            subject.into(),
1051            roles.into_iter().map(Into::into).collect(),
1052        ));
1053        self
1054    }
1055}
1056
1057/// Implements [`Authenticator`] for [`ApiKeyAuthenticator`].
1058impl Authenticator for ApiKeyAuthenticator {
1059    /// Authenticates incoming API key headers using constant-time key comparisons.
1060    ///
1061    /// # Arguments
1062    ///
1063    /// - `&'a self` - Shared reference to self.
1064    /// - `&'a Context` - Incoming request context.
1065    ///
1066    /// # Returns
1067    ///
1068    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
1069    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1070        let Self {
1071            header_name,
1072            entries,
1073        } = self;
1074        Box::pin(async move {
1075            match request_header_back(ctx.get_request(), header_name) {
1076                None => Err(AuthError::MissingCredentials),
1077                Some(candidate) => {
1078                    let candidate_bytes: &[u8] = candidate.trim().as_bytes();
1079                    let mut matched_idx: Option<usize> = None;
1080                    for (idx, (secret, _, _)) in entries.iter().enumerate() {
1081                        if constant_time_eq(candidate_bytes, secret) {
1082                            matched_idx = Some(idx);
1083                        }
1084                    }
1085                    match matched_idx {
1086                        Some(idx) => {
1087                            let (_, subject, roles): &(Vec<u8>, String, Vec<String>) =
1088                                &entries[idx];
1089                            Ok(AuthPrincipal {
1090                                subject: subject.clone(),
1091                                roles: roles.clone(),
1092                                scheme: AuthScheme::ApiKey,
1093                                claims: None,
1094                            })
1095                        }
1096                        None => Err(AuthError::InvalidCredentials),
1097                    }
1098                }
1099            }
1100        })
1101    }
1102}
1103
1104/// Default construction for [`BasicAuthenticator`].
1105impl Default for BasicAuthenticator {
1106    /// Constructs an empty [`BasicAuthenticator`].
1107    fn default() -> Self {
1108        Self::new()
1109    }
1110}
1111
1112/// Inherent implementation of [`BasicAuthenticator`].
1113impl BasicAuthenticator {
1114    /// Creates an empty [`BasicAuthenticator`].
1115    ///
1116    /// # Returns
1117    ///
1118    /// - `Self` - Empty HTTP Basic authenticator.
1119    pub fn new() -> Self {
1120        Self {
1121            users: hash_map_xx_hash3_64(),
1122        }
1123    }
1124
1125    /// Registers a Basic-auth user with `username`, `password`, and `roles`.
1126    ///
1127    /// # Arguments
1128    ///
1129    /// - `U` - Username string.
1130    /// - `P` - Password string.
1131    /// - `I` - Iterator of role names.
1132    ///
1133    /// # Returns
1134    ///
1135    /// - `Self` - Updated authenticator.
1136    pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
1137    where
1138        U: Into<String>,
1139        P: Into<String>,
1140        I: IntoIterator<Item = R>,
1141        R: Into<String>,
1142    {
1143        let Self { users } = &mut self;
1144        users.insert(
1145            username.into(),
1146            (
1147                password.into().into_bytes(),
1148                roles.into_iter().map(Into::into).collect(),
1149            ),
1150        );
1151        self
1152    }
1153}
1154
1155/// Implements [`Authenticator`] for [`BasicAuthenticator`].
1156impl Authenticator for BasicAuthenticator {
1157    /// Authenticates `Authorization: Basic <base64>` using constant-time password checks.
1158    ///
1159    /// # Arguments
1160    ///
1161    /// - `&'a self` - Shared reference to self.
1162    /// - `&'a Context` - Incoming request context.
1163    ///
1164    /// # Returns
1165    ///
1166    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
1167    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1168        let Self { users } = self;
1169        Box::pin(async move {
1170            match request_header_back(ctx.get_request(), AUTHORIZATION) {
1171                None => Err(AuthError::MissingCredentials),
1172                Some(header) => match strip_auth_scheme(header, PREFIX_BASIC) {
1173                    None => Err(AuthError::MissingCredentials),
1174                    Some(encoded) => {
1175                        let trimmed_b64: &[u8] = encoded.trim_end_matches('=').as_bytes();
1176                        let decoded_len: usize = (trimmed_b64.len() * 3) / 4;
1177                        let mut stack_buf: [u8; BASIC_STACK_CAP] = [0u8; BASIC_STACK_CAP];
1178                        let heap_buf: Vec<u8>;
1179                        let raw_opt: Option<&[u8]> = if decoded_len <= BASIC_STACK_CAP {
1180                            decode_base64_into(
1181                                trimmed_b64,
1182                                &BASE64_STD_DECODE_TABLE,
1183                                &mut stack_buf,
1184                            )
1185                            .map(|written: usize| &stack_buf[..written])
1186                        } else if let Some(buf) = base64_decode(encoded) {
1187                            heap_buf = buf;
1188                            Some(heap_buf.as_slice())
1189                        } else {
1190                            None
1191                        };
1192                        match raw_opt.and_then(|raw: &[u8]| from_utf8(raw).ok()) {
1193                            None => Err(AuthError::InvalidCredentials),
1194                            Some(decoded) => match decoded.split_once(':') {
1195                                None => Err(AuthError::InvalidCredentials),
1196                                Some((user, pass)) => match users.get(user) {
1197                                    Some((expected_pass, roles))
1198                                        if constant_time_eq(pass.as_bytes(), expected_pass) =>
1199                                    {
1200                                        Ok(AuthPrincipal {
1201                                            subject: user.to_owned(),
1202                                            roles: roles.clone(),
1203                                            scheme: AuthScheme::Basic,
1204                                            claims: None,
1205                                        })
1206                                    }
1207                                    _ => Err(AuthError::InvalidCredentials),
1208                                },
1209                            },
1210                        }
1211                    }
1212                },
1213            }
1214        })
1215    }
1216}
1217
1218/// Inherent implementation of [`CompositeAuthenticator`].
1219impl CompositeAuthenticator {
1220    /// Creates a [`CompositeAuthenticator`] chaining `chain` in priority order.
1221    ///
1222    /// # Arguments
1223    ///
1224    /// - `Vec<Arc<dyn Authenticator>>` - Ordered list of authenticators.
1225    ///
1226    /// # Returns
1227    ///
1228    /// - `Self` - Composite authenticator.
1229    pub fn new(chain: Vec<Arc<dyn Authenticator>>) -> Self {
1230        Self { chain }
1231    }
1232}
1233
1234/// Implements [`Authenticator`] for [`CompositeAuthenticator`].
1235impl Authenticator for CompositeAuthenticator {
1236    /// Evaluates each authenticator in order, returning the first verified [`AuthPrincipal`].
1237    ///
1238    /// # Arguments
1239    ///
1240    /// - `&'a self` - Shared reference to self.
1241    /// - `&'a Context` - Incoming request context.
1242    ///
1243    /// # Returns
1244    ///
1245    /// - `AuthFuture<'a>` - Future resolving to the first matching [`AuthPrincipal`] or last non-missing error.
1246    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1247        let Self { chain } = self;
1248        Box::pin(async move {
1249            let mut last_err: AuthError = AuthError::MissingCredentials;
1250            for auth in chain {
1251                match auth.authenticate(ctx).await {
1252                    Ok(principal) => return Ok(principal),
1253                    Err(AuthError::MissingCredentials) => {}
1254                    Err(err) => last_err = err,
1255                }
1256            }
1257            Err(last_err)
1258        })
1259    }
1260}
1261
1262/// Default construction for [`AuthConfig`].
1263impl Default for AuthConfig {
1264    /// Constructs a default [`AuthConfig`] with Bearer realm challenge and no exempt paths.
1265    fn default() -> Self {
1266        Self {
1267            exempt_paths: Vec::new(),
1268            required_roles: Vec::new(),
1269            require_all_roles: false,
1270            www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
1271        }
1272    }
1273}
1274
1275/// Inherent builders for [`AuthConfig`].
1276impl AuthConfig {
1277    /// Configures exact paths excluded from authentication checks.
1278    ///
1279    /// # Arguments
1280    ///
1281    /// - `I` - Iterator of exempt paths.
1282    ///
1283    /// # Returns
1284    ///
1285    /// - `Self` - Updated configuration.
1286    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
1287    where
1288        I: IntoIterator<Item = S>,
1289        S: Into<String>,
1290    {
1291        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
1292        self
1293    }
1294
1295    /// Configures roles required to access protected routes.
1296    ///
1297    /// # Arguments
1298    ///
1299    /// - `I` - Iterator of required role names.
1300    ///
1301    /// # Returns
1302    ///
1303    /// - `Self` - Updated configuration.
1304    pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
1305    where
1306        I: IntoIterator<Item = S>,
1307        S: Into<String>,
1308    {
1309        self.set_required_roles(roles.into_iter().map(Into::into).collect());
1310        self
1311    }
1312}
1313
1314/// Inherent implementation of [`AuthPlugin`].
1315impl AuthPlugin {
1316    /// Initializes the global [`AuthPlugin`] once with `config` and `authenticator`.
1317    ///
1318    /// # Arguments
1319    ///
1320    /// - `AuthConfig` - Path-exclusion and RBAC policy.
1321    /// - `Arc<dyn Authenticator>` - Pluggable authenticator implementation.
1322    ///
1323    /// # Returns
1324    ///
1325    /// - `&'static Self` - Reference to the initialized global plugin.
1326    pub fn init(config: AuthConfig, authenticator: Arc<dyn Authenticator>) -> &'static Self {
1327        AUTH_PLUGIN.get_or_init(|| {
1328            let exempt_set: Option<HashSetXxHash3_64<String>> =
1329                if config.get_exempt_paths().len() > EXEMPT_SET_THRESHOLD {
1330                    let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
1331                    for path in config.get_exempt_paths() {
1332                        set.insert(path.clone());
1333                    }
1334                    Some(set)
1335                } else {
1336                    None
1337                };
1338            let mut resp_401: Response = Response::default();
1339            resp_401
1340                .set_status_code(HttpStatus::Unauthorized.code())
1341                .set_header(WWW_AUTHENTICATE, config.get_www_authenticate())
1342                .set_body(Vec::new());
1343            let prebuilt_401_wire: Vec<u8> = resp_401.build();
1344            let mut resp_403: Response = Response::default();
1345            resp_403
1346                .set_status_code(HttpStatus::Forbidden.code())
1347                .set_body(Vec::new());
1348            let prebuilt_403_wire: Vec<u8> = resp_403.build();
1349            Self {
1350                config,
1351                authenticator,
1352                exempt_set,
1353                prebuilt_401_wire,
1354                prebuilt_403_wire,
1355            }
1356        })
1357    }
1358
1359    /// Returns the initialized global [`AuthPlugin`], if initialized.
1360    ///
1361    /// # Returns
1362    ///
1363    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1364    #[inline(always)]
1365    pub fn get() -> Option<&'static Self> {
1366        AUTH_PLUGIN.get()
1367    }
1368
1369    /// Returns the active [`AuthConfig`].
1370    ///
1371    /// # Returns
1372    ///
1373    /// - `&AuthConfig` - Active authorization policy.
1374    #[inline(always)]
1375    pub fn get_config(&self) -> &AuthConfig {
1376        &self.config
1377    }
1378
1379    /// Returns the active [`Arc<dyn Authenticator>`].
1380    ///
1381    /// # Returns
1382    ///
1383    /// - `&Arc<dyn Authenticator>` - Active authenticator.
1384    #[inline(always)]
1385    pub fn get_authenticator(&self) -> &Arc<dyn Authenticator> {
1386        &self.authenticator
1387    }
1388
1389    /// Checks whether `path` is exempt from authentication without heap allocation.
1390    ///
1391    /// # Arguments
1392    ///
1393    /// - `&str` - Incoming request path.
1394    ///
1395    /// # Returns
1396    ///
1397    /// - `bool` - `true` when `path` is excluded from authentication.
1398    #[inline(always)]
1399    pub(crate) fn is_exempt_path(&self, path: &str) -> bool {
1400        let Self {
1401            config, exempt_set, ..
1402        } = self;
1403        if let Some(set) = exempt_set {
1404            return set.contains(path);
1405        }
1406        let exempt: &[String] = config.get_exempt_paths().as_slice();
1407        if exempt.is_empty() {
1408            return false;
1409        }
1410        exempt.iter().any(|item: &String| item.as_str() == path)
1411    }
1412
1413    /// Retrieves the verified [`AuthPrincipal`] previously stored in `ctx` by [`AuthHook`].
1414    ///
1415    /// # Arguments
1416    ///
1417    /// - `&Context` - Request context.
1418    ///
1419    /// # Returns
1420    ///
1421    /// - `Option<AuthPrincipal>` - Verified caller principal, if authenticated.
1422    pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
1423        ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
1424    }
1425
1426    /// Checks whether `principal` satisfies the configured RBAC role requirements.
1427    ///
1428    /// # Arguments
1429    ///
1430    /// - `&AuthPrincipal` - Verified principal.
1431    ///
1432    /// # Returns
1433    ///
1434    /// - `bool` - `true` when authorized.
1435    pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
1436        let required: &Vec<String> = self.get_config().get_required_roles();
1437        if required.is_empty() {
1438            return true;
1439        }
1440        if self.get_config().get_require_all_roles() {
1441            required
1442                .iter()
1443                .all(|role: &String| principal.has_role(role))
1444        } else {
1445            required
1446                .iter()
1447                .any(|role: &String| principal.has_role(role))
1448        }
1449    }
1450}
1451
1452/// Implements [`ServerHook`] for [`AuthHook`].
1453impl ServerHook for AuthHook {
1454    /// Constructs a per-request [`AuthHook`].
1455    ///
1456    /// # Arguments
1457    ///
1458    /// - `&mut Stream` - Connection stream.
1459    /// - `&mut Context` - Request context.
1460    ///
1461    /// # Returns
1462    ///
1463    /// - `Self` - Hook instance.
1464    #[inline(always)]
1465    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1466        Self
1467    }
1468
1469    /// Authenticates protected requests, verifies required roles, and attaches [`AuthPrincipal`].
1470    ///
1471    /// # Arguments
1472    ///
1473    /// - `Self` - Hook instance.
1474    /// - `&mut Stream` - Connection stream.
1475    /// - `&mut Context` - Request context.
1476    ///
1477    /// # Returns
1478    ///
1479    /// - `Status` - `Status::Continue` when unconfigured, exempt, or authorized; `Status::Reject` on `401`/`403`.
1480    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1481        let Some(plugin) = AuthPlugin::get() else {
1482            return Status::Continue;
1483        };
1484        let path: &str = ctx.get_request().get_path();
1485        if plugin.is_exempt_path(path) {
1486            return Status::Continue;
1487        }
1488        match plugin.get_authenticator().authenticate(ctx).await {
1489            Ok(principal) => {
1490                if !plugin.is_authorized(&principal) {
1491                    let _: Result<(), ResponseError> =
1492                        stream.try_send(&plugin.prebuilt_403_wire).await;
1493                    return Status::Reject;
1494                }
1495                ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
1496                Status::Continue
1497            }
1498            Err(AuthError::Forbidden) => {
1499                let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_403_wire).await;
1500                Status::Reject
1501            }
1502            Err(_) => {
1503                let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_401_wire).await;
1504                Status::Reject
1505            }
1506        }
1507    }
1508}