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        let inner_hash: [u8; 32] = sha256_finish_from(inner_state, 64, data);
57        let mut outer_block: [u8; 64] = [0u8; 64];
58        outer_block[..32].copy_from_slice(&inner_hash);
59        outer_block[32] = 0x80;
60        outer_block[62] = 0x03;
61        let mut state: [u32; 8] = outer_state;
62        sha256_compress(&mut state, &outer_block);
63        let mut out: [u8; 32] = [0u8; 32];
64        out[0..4].copy_from_slice(&state[0].to_be_bytes());
65        out[4..8].copy_from_slice(&state[1].to_be_bytes());
66        out[8..12].copy_from_slice(&state[2].to_be_bytes());
67        out[12..16].copy_from_slice(&state[3].to_be_bytes());
68        out[16..20].copy_from_slice(&state[4].to_be_bytes());
69        out[20..24].copy_from_slice(&state[5].to_be_bytes());
70        out[24..28].copy_from_slice(&state[6].to_be_bytes());
71        out[28..32].copy_from_slice(&state[7].to_be_bytes());
72        out
73    }
74}
75
76/// Stack-backed JSON serialization buffer implementation.
77impl StackJsonBuf {
78    /// Creates an empty [`StackJsonBuf`] without heap allocation.
79    ///
80    /// # Returns
81    ///
82    /// - `Self` - Empty stack buffer.
83    #[inline]
84    pub(crate) fn new() -> Self {
85        Self {
86            stack: [0u8; JWT_STACK_PAYLOAD_CAP],
87            len: 0,
88            heap: None,
89        }
90    }
91
92    /// Returns the written bytes as a contiguous slice.
93    ///
94    /// # Returns
95    ///
96    /// - `&[u8]` - Written JSON bytes.
97    #[inline]
98    pub(crate) fn as_slice(&self) -> &[u8] {
99        let Self { stack, len, heap } = self;
100        match heap {
101            Some(buf) => buf.as_slice(),
102            None => &stack[..*len],
103        }
104    }
105}
106
107/// Implements [`Write`] for [`StackJsonBuf`].
108impl Write for StackJsonBuf {
109    /// Appends `buf` to stack storage or spills seamlessly to the heap.
110    ///
111    /// # Arguments
112    ///
113    /// - `&[u8]` - Source byte slice.
114    ///
115    /// # Returns
116    ///
117    /// - `io::Result<usize>` - Number of bytes written.
118    #[inline]
119    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
120        let Self { stack, len, heap } = self;
121        if let Some(vec) = heap {
122            vec.extend_from_slice(buf);
123            return Ok(buf.len());
124        }
125        let next_len: usize = len.saturating_add(buf.len());
126        if next_len <= stack.len() {
127            stack[*len..next_len].copy_from_slice(buf);
128            *len = next_len;
129        } else {
130            let mut vec: Vec<u8> = Vec::with_capacity(next_len);
131            vec.extend_from_slice(&stack[..*len]);
132            vec.extend_from_slice(buf);
133            *heap = Some(vec);
134        }
135        Ok(buf.len())
136    }
137
138    /// No-op flush for in-memory buffer.
139    ///
140    /// # Returns
141    ///
142    /// - `io::Result<()>` - Always `Ok(())`.
143    #[inline]
144    fn flush(&mut self) -> io::Result<()> {
145        Ok(())
146    }
147}
148
149/// Formatting for [`AuthError`].
150impl Display for AuthError {
151    /// Formats a human-readable error summary for [`AuthError`].
152    ///
153    /// # Arguments
154    ///
155    /// - `&mut Formatter<'_>` - Output formatter.
156    ///
157    /// # Returns
158    ///
159    /// - `fmt::Result` - Formatting outcome.
160    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
161        match self {
162            Self::MissingCredentials => f.write_str(MSG_AUTH_MISSING),
163            Self::InvalidCredentials => f.write_str(MSG_AUTH_INVALID),
164            Self::TokenExpired => f.write_str(MSG_AUTH_EXPIRED),
165            Self::TokenNotYetValid => f.write_str(MSG_AUTH_NOT_YET_VALID),
166            Self::UnsupportedAlgorithm => f.write_str(MSG_AUTH_UNSUPPORTED_ALG),
167            Self::ClaimMismatch => f.write_str(MSG_AUTH_CLAIM_MISMATCH),
168            Self::Forbidden => f.write_str(MSG_AUTH_FORBIDDEN),
169        }
170    }
171}
172
173/// Implements [`Error`] for [`AuthError`].
174impl Error for AuthError {}
175
176/// Inherent implementation of [`JwtClaims`].
177impl JwtClaims {
178    /// Creates a minimal [`JwtClaims`] payload for `subject` expiring in `ttl_secs`.
179    ///
180    /// # Arguments
181    ///
182    /// - `S` - Subject identifier convertible into `String`.
183    /// - `u64` - Lifetime in seconds from current Unix time.
184    ///
185    /// # Returns
186    ///
187    /// - `Self` - Constructed claims payload.
188    pub fn new<S>(subject: S, ttl_secs: u64) -> Self
189    where
190        S: Into<String>,
191    {
192        let now: u64 = auth_now_secs();
193        Self {
194            sub: subject.into(),
195            iss: None,
196            aud: None,
197            exp: Some(now.saturating_add(ttl_secs)),
198            nbf: Some(now),
199            iat: Some(now),
200            jti: None,
201            roles: Vec::new(),
202            extra: HashMap::new(),
203        }
204    }
205
206    /// Attaches RBAC roles to this claims payload.
207    ///
208    /// # Arguments
209    ///
210    /// - `I` - Iterator of role names.
211    ///
212    /// # Returns
213    ///
214    /// - `Self` - Updated claims payload.
215    pub fn with_roles<I, S>(mut self, roles: I) -> Self
216    where
217        I: IntoIterator<Item = S>,
218        S: Into<String>,
219    {
220        self.set_roles(roles.into_iter().map(Into::into).collect());
221        self
222    }
223
224    /// Sets the `iss` issuer claim.
225    ///
226    /// # Arguments
227    ///
228    /// - `S` - Issuer identifier.
229    ///
230    /// # Returns
231    ///
232    /// - `Self` - Updated claims payload.
233    pub fn with_issuer<S>(mut self, issuer: S) -> Self
234    where
235        S: Into<String>,
236    {
237        self.set_iss(Some(issuer.into()));
238        self
239    }
240
241    /// Sets the `aud` audience claim.
242    ///
243    /// # Arguments
244    ///
245    /// - `S` - Audience identifier.
246    ///
247    /// # Returns
248    ///
249    /// - `Self` - Updated claims payload.
250    pub fn with_audience<S>(mut self, audience: S) -> Self
251    where
252        S: Into<String>,
253    {
254        self.set_aud(Some(audience.into()));
255        self
256    }
257}
258
259/// Inherent implementation of [`JwtCodec`].
260impl JwtCodec {
261    /// Creates an HS256 [`JwtCodec`] signed and verified with `secret`.
262    ///
263    /// # Arguments
264    ///
265    /// - `S` - Shared HMAC-SHA256 secret bytes convertible into `Vec<u8>`.
266    ///
267    /// # Returns
268    ///
269    /// - `Self` - Ready JWT codec with 60 s default clock-skew leeway.
270    pub fn new<S>(secret: S) -> Self
271    where
272        S: Into<Vec<u8>>,
273    {
274        let default_secret: Vec<u8> = secret.into();
275        let default_hmac: HmacSha256Key = HmacSha256Key::new(&default_secret);
276        Self {
277            default_secret,
278            default_hmac,
279            default_kid: None,
280            default_header_b64: DEFAULT_HS256_HEADER_B64.to_owned(),
281            keyring: hash_map_xx_hash3_64(),
282            keyring_hmac: hash_map_xx_hash3_64(),
283            leeway_secs: DEFAULT_JWT_LEEWAY_SECS,
284            required_issuer: None,
285            required_audience: None,
286        }
287    }
288
289    /// Registers an additional verification key under `kid` for seamless key rotation.
290    ///
291    /// # Arguments
292    ///
293    /// - `K` - Key identifier convertible into `String`.
294    /// - `S` - Secret bytes for this `kid`.
295    ///
296    /// # Returns
297    ///
298    /// - `Self` - Updated codec.
299    pub fn with_key<K, S>(mut self, kid: K, secret: S) -> Self
300    where
301        K: Into<String>,
302        S: Into<Vec<u8>>,
303    {
304        let Self {
305            keyring,
306            keyring_hmac,
307            ..
308        } = &mut self;
309        let kid_str: String = kid.into();
310        let secret_bytes: Vec<u8> = secret.into();
311        let precomputed: HmacSha256Key = HmacSha256Key::new(&secret_bytes);
312        keyring.insert(kid_str.clone(), secret_bytes);
313        keyring_hmac.insert(kid_str, precomputed);
314        self
315    }
316
317    /// Sets the default `kid` stamped on newly encoded tokens (and registers its secret if absent).
318    ///
319    /// # Arguments
320    ///
321    /// - `K` - Active signing key identifier.
322    ///
323    /// # Returns
324    ///
325    /// - `Self` - Updated codec.
326    pub fn with_default_kid<K>(mut self, kid: K) -> Self
327    where
328        K: Into<String>,
329    {
330        let Self {
331            default_kid,
332            default_secret,
333            default_hmac,
334            default_header_b64,
335            keyring,
336            keyring_hmac,
337            ..
338        } = &mut self;
339        let kid_str: String = kid.into();
340        if !keyring.contains_key(&kid_str) {
341            keyring.insert(kid_str.clone(), default_secret.clone());
342            keyring_hmac.insert(kid_str.clone(), *default_hmac);
343        }
344        *default_header_b64 = encode_hs256_header_b64(Some(&kid_str));
345        *default_kid = Some(kid_str);
346        self
347    }
348
349    /// Sets the allowed clock-skew leeway in seconds for `exp` and `nbf` checks.
350    ///
351    /// # Arguments
352    ///
353    /// - `u64` - Leeway in seconds.
354    ///
355    /// # Returns
356    ///
357    /// - `Self` - Updated codec.
358    pub fn with_leeway_secs(mut self, leeway_secs: u64) -> Self {
359        let Self {
360            leeway_secs: slot, ..
361        } = &mut self;
362        *slot = leeway_secs;
363        self
364    }
365
366    /// Requires every decoded token's `iss` claim to match `issuer`.
367    ///
368    /// # Arguments
369    ///
370    /// - `S` - Required issuer string.
371    ///
372    /// # Returns
373    ///
374    /// - `Self` - Updated codec.
375    pub fn with_required_issuer<S>(mut self, issuer: S) -> Self
376    where
377        S: Into<String>,
378    {
379        let Self {
380            required_issuer, ..
381        } = &mut self;
382        *required_issuer = Some(issuer.into());
383        self
384    }
385
386    /// Requires every decoded token's `aud` claim to match `audience`.
387    ///
388    /// # Arguments
389    ///
390    /// - `S` - Required audience string.
391    ///
392    /// # Returns
393    ///
394    /// - `Self` - Updated codec.
395    pub fn with_required_audience<S>(mut self, audience: S) -> Self
396    where
397        S: Into<String>,
398    {
399        let Self {
400            required_audience, ..
401        } = &mut self;
402        *required_audience = Some(audience.into());
403        self
404    }
405
406    /// Encodes and signs `claims` into a compact HS256 JWT (`header.payload.signature`).
407    ///
408    /// # Arguments
409    ///
410    /// - `&JwtClaims` - Claims payload to sign.
411    ///
412    /// # Returns
413    ///
414    /// - `Result<String, AuthError>` - Compact JWT string, or [`AuthError::InvalidCredentials`] on serialization failure.
415    pub fn encode(&self, claims: &JwtClaims) -> Result<String, AuthError> {
416        let Self {
417            default_hmac,
418            default_kid,
419            default_header_b64,
420            keyring_hmac,
421            ..
422        } = self;
423        let mut claims_buf: StackJsonBuf = StackJsonBuf::new();
424        to_writer(&mut claims_buf, claims).map_err(|_| AuthError::InvalidCredentials)?;
425        let claims_json: &[u8] = claims_buf.as_slice();
426        let claims_b64_len: usize = (claims_json.len() * 4).div_ceil(3);
427        let total_len: usize = default_header_b64.len() + 1 + claims_b64_len + 1 + HMAC_SIG_B64_LEN;
428        let mut token_bytes: Vec<u8> = Vec::with_capacity(total_len);
429        token_bytes.extend_from_slice(default_header_b64.as_bytes());
430        token_bytes.push(b'.');
431        base64url_encode_into(claims_json, &mut token_bytes);
432        let hmac_key: &HmacSha256Key = match default_kid {
433            Some(kid) => keyring_hmac.get(kid).unwrap_or(default_hmac),
434            None => default_hmac,
435        };
436        let mac: [u8; 32] = hmac_key.mac(&token_bytes);
437        token_bytes.push(b'.');
438        base64url_encode_into(&mac, &mut token_bytes);
439        String::from_utf8(token_bytes).map_err(|_| AuthError::InvalidCredentials)
440    }
441
442    /// Verifies and decodes a compact HS256 JWT at timestamp `now_secs`.
443    ///
444    /// # Arguments
445    ///
446    /// - `&str` - Compact JWT string (`header.payload.signature`).
447    /// - `u64` - Current Unix timestamp in seconds.
448    ///
449    /// # Returns
450    ///
451    /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or detailed [`AuthError`].
452    pub fn decode_at(&self, token: &str, now_secs: u64) -> Result<JwtClaims, AuthError> {
453        let Self {
454            default_hmac,
455            default_kid,
456            default_header_b64,
457            keyring_hmac,
458            leeway_secs,
459            required_issuer,
460            required_audience,
461            ..
462        } = self;
463        let (header_b64, rest): (&str, &str) =
464            token.split_once('.').ok_or(AuthError::InvalidCredentials)?;
465        let (payload_b64, sig_b64): (&str, &str) =
466            rest.split_once('.').ok_or(AuthError::InvalidCredentials)?;
467        if sig_b64.contains('.')
468            || header_b64.is_empty()
469            || payload_b64.is_empty()
470            || sig_b64.is_empty()
471        {
472            return Err(AuthError::InvalidCredentials);
473        }
474        let hmac_key: &HmacSha256Key = if header_b64 == default_header_b64.as_str() {
475            match default_kid {
476                Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
477                None => default_hmac,
478            }
479        } else if header_b64 == DEFAULT_HS256_HEADER_B64 {
480            default_hmac
481        } else {
482            let trimmed_hdr: &[u8] = header_b64.trim_end_matches('=').as_bytes();
483            let decoded_hdr_len: usize = (trimmed_hdr.len() * 3) / 4;
484            let mut hdr_stack: [u8; JWT_STACK_HEADER_CAP] = [0u8; JWT_STACK_HEADER_CAP];
485            let hdr_heap: Vec<u8>;
486            let hdr_slice: &[u8] = if decoded_hdr_len <= JWT_STACK_HEADER_CAP {
487                let written: usize =
488                    decode_base64_into(trimmed_hdr, &BASE64URL_DECODE_TABLE, &mut hdr_stack)
489                        .ok_or(AuthError::InvalidCredentials)?;
490                &hdr_stack[..written]
491            } else {
492                hdr_heap = base64url_decode(header_b64).ok_or(AuthError::InvalidCredentials)?;
493                &hdr_heap
494            };
495            let header: JwtHeaderRef<'_> =
496                from_slice(hdr_slice).map_err(|_| AuthError::InvalidCredentials)?;
497            if header.alg.as_ref() != JWT_ALG_HS256 {
498                return Err(AuthError::UnsupportedAlgorithm);
499            }
500            match header.kid.as_deref() {
501                Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
502                None => default_hmac,
503            }
504        };
505        let provided_sig: [u8; 32] =
506            decode_base64url_32(sig_b64).ok_or(AuthError::InvalidCredentials)?;
507        let signed_len: usize = header_b64.len() + 1 + payload_b64.len();
508        let expected_mac: [u8; 32] = hmac_key.mac(&token.as_bytes()[..signed_len]);
509        if !constant_time_eq(&provided_sig, &expected_mac) {
510            return Err(AuthError::InvalidCredentials);
511        }
512        let trimmed_payload: &[u8] = payload_b64.trim_end_matches('=').as_bytes();
513        let decoded_payload_len: usize = (trimmed_payload.len() * 3) / 4;
514        let mut payload_stack: [u8; JWT_STACK_PAYLOAD_CAP] = [0u8; JWT_STACK_PAYLOAD_CAP];
515        let payload_heap: Vec<u8>;
516        let payload_slice: &[u8] = if decoded_payload_len <= JWT_STACK_PAYLOAD_CAP {
517            let written: usize =
518                decode_base64_into(trimmed_payload, &BASE64URL_DECODE_TABLE, &mut payload_stack)
519                    .ok_or(AuthError::InvalidCredentials)?;
520            &payload_stack[..written]
521        } else {
522            payload_heap = base64url_decode(payload_b64).ok_or(AuthError::InvalidCredentials)?;
523            &payload_heap
524        };
525        let claims: JwtClaims =
526            from_slice(payload_slice).map_err(|_| AuthError::InvalidCredentials)?;
527        let JwtClaims {
528            iss, aud, exp, nbf, ..
529        } = &claims;
530        if let Some(exp_val) = *exp
531            && now_secs > exp_val.saturating_add(*leeway_secs)
532        {
533            return Err(AuthError::TokenExpired);
534        }
535        if let Some(nbf_val) = *nbf
536            && now_secs.saturating_add(*leeway_secs) < nbf_val
537        {
538            return Err(AuthError::TokenNotYetValid);
539        }
540        if let Some(expected_iss) = required_issuer
541            && iss.as_deref() != Some(expected_iss.as_str())
542        {
543            return Err(AuthError::ClaimMismatch);
544        }
545        if let Some(expected_aud) = required_audience
546            && aud.as_deref() != Some(expected_aud.as_str())
547        {
548            return Err(AuthError::ClaimMismatch);
549        }
550        Ok(claims)
551    }
552
553    /// Verifies and decodes a compact HS256 JWT against current system time.
554    ///
555    /// # Arguments
556    ///
557    /// - `&str` - Compact JWT string.
558    ///
559    /// # Returns
560    ///
561    /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or [`AuthError`].
562    pub fn decode(&self, token: &str) -> Result<JwtClaims, AuthError> {
563        self.decode_at(token, auth_now_secs())
564    }
565}
566
567/// Inherent helpers for [`AuthPrincipal`].
568impl AuthPrincipal {
569    /// Checks whether this principal possesses `role`.
570    ///
571    /// # Arguments
572    ///
573    /// - `&str` - Role name to check.
574    ///
575    /// # Returns
576    ///
577    /// - `bool` - `true` when the role is granted.
578    #[inline]
579    pub fn has_role(&self, role: &str) -> bool {
580        self.get_roles().iter().any(|item: &String| item == role)
581    }
582}
583
584/// Inherent implementation of [`JwtAuthenticator`].
585impl JwtAuthenticator {
586    /// Creates a [`JwtAuthenticator`] backed by `codec`.
587    ///
588    /// # Arguments
589    ///
590    /// - `JwtCodec` - Configured HS256 codec.
591    ///
592    /// # Returns
593    ///
594    /// - `Self` - Bearer JWT authenticator.
595    pub fn new(codec: JwtCodec) -> Self {
596        Self { codec }
597    }
598}
599
600/// Implements [`Authenticator`] for [`JwtAuthenticator`].
601impl Authenticator for JwtAuthenticator {
602    /// Authenticates `Authorization: Bearer <token>` requests via [`JwtCodec`].
603    ///
604    /// # Arguments
605    ///
606    /// - `&'a self` - Shared reference to self.
607    /// - `&'a Context` - Incoming request context.
608    ///
609    /// # Returns
610    ///
611    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
612    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
613        let Self { codec } = self;
614        Box::pin(async move {
615            match request_header_back(ctx.get_request(), AUTHORIZATION) {
616                None => Err(AuthError::MissingCredentials),
617                Some(header) => match strip_auth_scheme(header, PREFIX_BEARER) {
618                    None => Err(AuthError::MissingCredentials),
619                    Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
620                        subject: claims.get_sub().clone(),
621                        roles: claims.get_roles().clone(),
622                        scheme: AuthScheme::BearerJwt,
623                        claims: Some(claims),
624                    }),
625                },
626            }
627        })
628    }
629}
630
631/// Default construction for [`ApiKeyAuthenticator`].
632impl Default for ApiKeyAuthenticator {
633    /// Constructs an empty [`ApiKeyAuthenticator`] reading `X-Api-Key`.
634    fn default() -> Self {
635        Self::new(X_API_KEY)
636    }
637}
638
639/// Inherent implementation of [`ApiKeyAuthenticator`].
640impl ApiKeyAuthenticator {
641    /// Creates an [`ApiKeyAuthenticator`] reading `header_name`.
642    ///
643    /// # Arguments
644    ///
645    /// - `H` - Header name convertible into `String`.
646    ///
647    /// # Returns
648    ///
649    /// - `Self` - Empty API-key authenticator.
650    pub fn new<H>(header_name: H) -> Self
651    where
652        H: Into<String>,
653    {
654        Self {
655            header_name: header_name.into().to_ascii_lowercase(),
656            entries: Vec::new(),
657        }
658    }
659
660    /// Registers an allowed API key associated with `subject` and `roles`.
661    ///
662    /// # Arguments
663    ///
664    /// - `K` - Secret API key string.
665    /// - `S` - Subject name assigned when matched.
666    /// - `I` - Iterator of role names.
667    ///
668    /// # Returns
669    ///
670    /// - `Self` - Updated authenticator.
671    pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
672    where
673        K: Into<String>,
674        S: Into<String>,
675        I: IntoIterator<Item = R>,
676        R: Into<String>,
677    {
678        let Self { entries, .. } = &mut self;
679        entries.push((
680            api_key.into().into_bytes(),
681            subject.into(),
682            roles.into_iter().map(Into::into).collect(),
683        ));
684        self
685    }
686}
687
688/// Implements [`Authenticator`] for [`ApiKeyAuthenticator`].
689impl Authenticator for ApiKeyAuthenticator {
690    /// Authenticates incoming API key headers using constant-time key comparisons.
691    ///
692    /// # Arguments
693    ///
694    /// - `&'a self` - Shared reference to self.
695    /// - `&'a Context` - Incoming request context.
696    ///
697    /// # Returns
698    ///
699    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
700    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
701        let Self {
702            header_name,
703            entries,
704        } = self;
705        Box::pin(async move {
706            match request_header_back(ctx.get_request(), header_name) {
707                None => Err(AuthError::MissingCredentials),
708                Some(candidate) => {
709                    let candidate_bytes: &[u8] = candidate.trim().as_bytes();
710                    let mut matched_idx: Option<usize> = None;
711                    for (idx, (secret, _, _)) in entries.iter().enumerate() {
712                        if constant_time_eq(candidate_bytes, secret) {
713                            matched_idx = Some(idx);
714                        }
715                    }
716                    match matched_idx {
717                        Some(idx) => {
718                            let (_, subject, roles): &(Vec<u8>, String, Vec<String>) =
719                                &entries[idx];
720                            Ok(AuthPrincipal {
721                                subject: subject.clone(),
722                                roles: roles.clone(),
723                                scheme: AuthScheme::ApiKey,
724                                claims: None,
725                            })
726                        }
727                        None => Err(AuthError::InvalidCredentials),
728                    }
729                }
730            }
731        })
732    }
733}
734
735/// Default construction for [`BasicAuthenticator`].
736impl Default for BasicAuthenticator {
737    /// Constructs an empty [`BasicAuthenticator`].
738    fn default() -> Self {
739        Self::new()
740    }
741}
742
743/// Inherent implementation of [`BasicAuthenticator`].
744impl BasicAuthenticator {
745    /// Creates an empty [`BasicAuthenticator`].
746    ///
747    /// # Returns
748    ///
749    /// - `Self` - Empty HTTP Basic authenticator.
750    pub fn new() -> Self {
751        Self {
752            users: hash_map_xx_hash3_64(),
753        }
754    }
755
756    /// Registers a Basic-auth user with `username`, `password`, and `roles`.
757    ///
758    /// # Arguments
759    ///
760    /// - `U` - Username string.
761    /// - `P` - Password string.
762    /// - `I` - Iterator of role names.
763    ///
764    /// # Returns
765    ///
766    /// - `Self` - Updated authenticator.
767    pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
768    where
769        U: Into<String>,
770        P: Into<String>,
771        I: IntoIterator<Item = R>,
772        R: Into<String>,
773    {
774        let Self { users } = &mut self;
775        users.insert(
776            username.into(),
777            (
778                password.into().into_bytes(),
779                roles.into_iter().map(Into::into).collect(),
780            ),
781        );
782        self
783    }
784}
785
786/// Implements [`Authenticator`] for [`BasicAuthenticator`].
787impl Authenticator for BasicAuthenticator {
788    /// Authenticates `Authorization: Basic <base64>` using constant-time password checks.
789    ///
790    /// # Arguments
791    ///
792    /// - `&'a self` - Shared reference to self.
793    /// - `&'a Context` - Incoming request context.
794    ///
795    /// # Returns
796    ///
797    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
798    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
799        let Self { users } = self;
800        Box::pin(async move {
801            match request_header_back(ctx.get_request(), AUTHORIZATION) {
802                None => Err(AuthError::MissingCredentials),
803                Some(header) => match strip_auth_scheme(header, PREFIX_BASIC) {
804                    None => Err(AuthError::MissingCredentials),
805                    Some(encoded) => {
806                        let trimmed_b64: &[u8] = encoded.trim_end_matches('=').as_bytes();
807                        let decoded_len: usize = (trimmed_b64.len() * 3) / 4;
808                        let mut stack_buf: [u8; BASIC_STACK_CAP] = [0u8; BASIC_STACK_CAP];
809                        let heap_buf: Vec<u8>;
810                        let raw_opt: Option<&[u8]> = if decoded_len <= BASIC_STACK_CAP {
811                            decode_base64_into(
812                                trimmed_b64,
813                                &BASE64_STD_DECODE_TABLE,
814                                &mut stack_buf,
815                            )
816                            .map(|written: usize| &stack_buf[..written])
817                        } else if let Some(buf) = base64_decode(encoded) {
818                            heap_buf = buf;
819                            Some(heap_buf.as_slice())
820                        } else {
821                            None
822                        };
823                        match raw_opt.and_then(|raw: &[u8]| from_utf8(raw).ok()) {
824                            None => Err(AuthError::InvalidCredentials),
825                            Some(decoded) => match decoded.split_once(':') {
826                                None => Err(AuthError::InvalidCredentials),
827                                Some((user, pass)) => match users.get(user) {
828                                    Some((expected_pass, roles))
829                                        if constant_time_eq(pass.as_bytes(), expected_pass) =>
830                                    {
831                                        Ok(AuthPrincipal {
832                                            subject: user.to_owned(),
833                                            roles: roles.clone(),
834                                            scheme: AuthScheme::Basic,
835                                            claims: None,
836                                        })
837                                    }
838                                    _ => Err(AuthError::InvalidCredentials),
839                                },
840                            },
841                        }
842                    }
843                },
844            }
845        })
846    }
847}
848
849/// Inherent implementation of [`CompositeAuthenticator`].
850impl CompositeAuthenticator {
851    /// Creates a [`CompositeAuthenticator`] chaining `chain` in priority order.
852    ///
853    /// # Arguments
854    ///
855    /// - `Vec<SharedAuthenticator>` - Ordered list of authenticators.
856    ///
857    /// # Returns
858    ///
859    /// - `Self` - Composite authenticator.
860    pub fn new(chain: Vec<SharedAuthenticator>) -> Self {
861        Self { chain }
862    }
863}
864
865/// Implements [`Authenticator`] for [`CompositeAuthenticator`].
866impl Authenticator for CompositeAuthenticator {
867    /// Evaluates each authenticator in order, returning the first verified [`AuthPrincipal`].
868    ///
869    /// # Arguments
870    ///
871    /// - `&'a self` - Shared reference to self.
872    /// - `&'a Context` - Incoming request context.
873    ///
874    /// # Returns
875    ///
876    /// - `AuthFuture<'a>` - Future resolving to the first matching [`AuthPrincipal`] or last non-missing error.
877    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
878        let Self { chain } = self;
879        Box::pin(async move {
880            let mut last_err: AuthError = AuthError::MissingCredentials;
881            for auth in chain {
882                match auth.authenticate(ctx).await {
883                    Ok(principal) => return Ok(principal),
884                    Err(AuthError::MissingCredentials) => {}
885                    Err(err) => last_err = err,
886                }
887            }
888            Err(last_err)
889        })
890    }
891}
892
893/// Default construction for [`AuthConfig`].
894impl Default for AuthConfig {
895    /// Constructs a default [`AuthConfig`] with Bearer realm challenge and no exempt paths.
896    fn default() -> Self {
897        Self {
898            exempt_paths: Vec::new(),
899            required_roles: Vec::new(),
900            require_all_roles: false,
901            www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
902        }
903    }
904}
905
906/// Inherent builders for [`AuthConfig`].
907impl AuthConfig {
908    /// Configures exact paths excluded from authentication checks.
909    ///
910    /// # Arguments
911    ///
912    /// - `I` - Iterator of exempt paths.
913    ///
914    /// # Returns
915    ///
916    /// - `Self` - Updated configuration.
917    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
918    where
919        I: IntoIterator<Item = S>,
920        S: Into<String>,
921    {
922        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
923        self
924    }
925
926    /// Configures roles required to access protected routes.
927    ///
928    /// # Arguments
929    ///
930    /// - `I` - Iterator of required role names.
931    ///
932    /// # Returns
933    ///
934    /// - `Self` - Updated configuration.
935    pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
936    where
937        I: IntoIterator<Item = S>,
938        S: Into<String>,
939    {
940        self.set_required_roles(roles.into_iter().map(Into::into).collect());
941        self
942    }
943}
944
945/// Inherent implementation of [`AuthPlugin`].
946impl AuthPlugin {
947    /// Initializes the global [`AuthPlugin`] once with `config` and `authenticator`.
948    ///
949    /// # Arguments
950    ///
951    /// - `AuthConfig` - Path-exclusion and RBAC policy.
952    /// - `SharedAuthenticator` - Pluggable authenticator implementation.
953    ///
954    /// # Returns
955    ///
956    /// - `&'static Self` - Reference to the initialized global plugin.
957    pub fn init(config: AuthConfig, authenticator: SharedAuthenticator) -> &'static Self {
958        AUTH_PLUGIN.get_or_init(|| {
959            let exempt_set: Option<HashSetXxHash3_64<String>> =
960                if config.get_exempt_paths().len() > EXEMPT_SET_THRESHOLD {
961                    let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
962                    for path in config.get_exempt_paths() {
963                        set.insert(path.clone());
964                    }
965                    Some(set)
966                } else {
967                    None
968                };
969            Self {
970                config,
971                authenticator,
972                exempt_set,
973            }
974        })
975    }
976
977    /// Returns the initialized global [`AuthPlugin`], if initialized.
978    ///
979    /// # Returns
980    ///
981    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
982    #[inline(always)]
983    pub fn get() -> Option<&'static Self> {
984        AUTH_PLUGIN.get()
985    }
986
987    /// Returns the active [`AuthConfig`].
988    ///
989    /// # Returns
990    ///
991    /// - `&AuthConfig` - Active authorization policy.
992    #[inline(always)]
993    pub fn get_config(&self) -> &AuthConfig {
994        &self.config
995    }
996
997    /// Returns the active [`SharedAuthenticator`].
998    ///
999    /// # Returns
1000    ///
1001    /// - `&SharedAuthenticator` - Active authenticator.
1002    #[inline(always)]
1003    pub fn get_authenticator(&self) -> &SharedAuthenticator {
1004        &self.authenticator
1005    }
1006
1007    /// Checks whether `path` is exempt from authentication without heap allocation.
1008    ///
1009    /// # Arguments
1010    ///
1011    /// - `&str` - Incoming request path.
1012    ///
1013    /// # Returns
1014    ///
1015    /// - `bool` - `true` when `path` is excluded from authentication.
1016    #[inline(always)]
1017    pub(crate) fn is_exempt_path(&self, path: &str) -> bool {
1018        let Self {
1019            config, exempt_set, ..
1020        } = self;
1021        if let Some(set) = exempt_set {
1022            return set.contains(path);
1023        }
1024        let exempt: &[String] = config.get_exempt_paths().as_slice();
1025        if exempt.is_empty() {
1026            return false;
1027        }
1028        exempt.iter().any(|item: &String| item.as_str() == path)
1029    }
1030
1031    /// Retrieves the verified [`AuthPrincipal`] previously stored in `ctx` by [`AuthHook`].
1032    ///
1033    /// # Arguments
1034    ///
1035    /// - `&Context` - Request context.
1036    ///
1037    /// # Returns
1038    ///
1039    /// - `Option<AuthPrincipal>` - Verified caller principal, if authenticated.
1040    pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
1041        ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
1042    }
1043
1044    /// Checks whether `principal` satisfies the configured RBAC role requirements.
1045    ///
1046    /// # Arguments
1047    ///
1048    /// - `&AuthPrincipal` - Verified principal.
1049    ///
1050    /// # Returns
1051    ///
1052    /// - `bool` - `true` when authorized.
1053    pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
1054        let required: &Vec<String> = self.get_config().get_required_roles();
1055        if required.is_empty() {
1056            return true;
1057        }
1058        if self.get_config().get_require_all_roles() {
1059            required
1060                .iter()
1061                .all(|role: &String| principal.has_role(role))
1062        } else {
1063            required
1064                .iter()
1065                .any(|role: &String| principal.has_role(role))
1066        }
1067    }
1068}
1069
1070/// Implements [`ServerHook`] for [`AuthHook`].
1071impl ServerHook for AuthHook {
1072    /// Constructs a per-request [`AuthHook`].
1073    ///
1074    /// # Arguments
1075    ///
1076    /// - `&mut Stream` - Connection stream.
1077    /// - `&mut Context` - Request context.
1078    ///
1079    /// # Returns
1080    ///
1081    /// - `Self` - Hook instance.
1082    #[inline(always)]
1083    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1084        Self
1085    }
1086
1087    /// Authenticates protected requests, verifies required roles, and attaches [`AuthPrincipal`].
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `Self` - Hook instance.
1092    /// - `&mut Stream` - Connection stream.
1093    /// - `&mut Context` - Request context.
1094    ///
1095    /// # Returns
1096    ///
1097    /// - `Status` - `Status::Continue` when unconfigured, exempt, or authorized; `Status::Reject` on `401`/`403`.
1098    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1099        let Some(plugin) = AuthPlugin::get() else {
1100            return Status::Continue;
1101        };
1102        let path: &str = ctx.get_request().get_path();
1103        if plugin.is_exempt_path(path) {
1104            return Status::Continue;
1105        }
1106        match plugin.get_authenticator().authenticate(ctx).await {
1107            Ok(principal) => {
1108                if !plugin.is_authorized(&principal) {
1109                    ctx.get_mut_response()
1110                        .set_status_code(HttpStatus::Forbidden.code())
1111                        .set_body(Vec::new());
1112                    let wire: ResponseData = ctx.get_mut_response().build();
1113                    let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1114                    return Status::Reject;
1115                }
1116                ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
1117                Status::Continue
1118            }
1119            Err(AuthError::Forbidden) => {
1120                ctx.get_mut_response()
1121                    .set_status_code(HttpStatus::Forbidden.code())
1122                    .set_body(Vec::new());
1123                let wire: ResponseData = ctx.get_mut_response().build();
1124                let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1125                Status::Reject
1126            }
1127            Err(_) => {
1128                ctx.get_mut_response()
1129                    .set_status_code(HttpStatus::Unauthorized.code())
1130                    .set_header(WWW_AUTHENTICATE, plugin.get_config().get_www_authenticate())
1131                    .set_body(Vec::new());
1132                let wire: ResponseData = ctx.get_mut_response().build();
1133                let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1134                Status::Reject
1135            }
1136        }
1137    }
1138}