hyperlane_plugin_auth/impl.rs
1use super::*;
2
3/// Formatting for [`AuthError`].
4impl Display for AuthError {
5 /// Formats a human-readable error summary for [`AuthError`].
6 ///
7 /// # Arguments
8 ///
9 /// - `&mut Formatter<'_>` - Output formatter.
10 ///
11 /// # Returns
12 ///
13 /// - `fmt::Result` - Formatting outcome.
14 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15 match self {
16 Self::MissingCredentials => f.write_str(MSG_AUTH_MISSING),
17 Self::InvalidCredentials => f.write_str(MSG_AUTH_INVALID),
18 Self::TokenExpired => f.write_str(MSG_AUTH_EXPIRED),
19 Self::TokenNotYetValid => f.write_str(MSG_AUTH_NOT_YET_VALID),
20 Self::UnsupportedAlgorithm => f.write_str(MSG_AUTH_UNSUPPORTED_ALG),
21 Self::ClaimMismatch => f.write_str(MSG_AUTH_CLAIM_MISMATCH),
22 Self::Forbidden => f.write_str(MSG_AUTH_FORBIDDEN),
23 }
24 }
25}
26
27/// Implements [`Error`] for [`AuthError`].
28impl Error for AuthError {}
29
30/// Inherent implementation of [`JwtClaims`].
31impl JwtClaims {
32 /// Creates a minimal [`JwtClaims`] payload for `subject` expiring in `ttl_secs`.
33 ///
34 /// # Arguments
35 ///
36 /// - `S` - Subject identifier convertible into `String`.
37 /// - `u64` - Lifetime in seconds from current Unix time.
38 ///
39 /// # Returns
40 ///
41 /// - `Self` - Constructed claims payload.
42 pub fn new<S>(subject: S, ttl_secs: u64) -> Self
43 where
44 S: Into<String>,
45 {
46 let now: u64 = auth_now_secs();
47 Self {
48 sub: subject.into(),
49 iss: None,
50 aud: None,
51 exp: Some(now.saturating_add(ttl_secs)),
52 nbf: Some(now),
53 iat: Some(now),
54 jti: None,
55 roles: Vec::new(),
56 extra: HashMap::new(),
57 }
58 }
59
60 /// Attaches RBAC roles to this claims payload.
61 ///
62 /// # Arguments
63 ///
64 /// - `I` - Iterator of role names.
65 ///
66 /// # Returns
67 ///
68 /// - `Self` - Updated claims payload.
69 pub fn with_roles<I, S>(mut self, roles: I) -> Self
70 where
71 I: IntoIterator<Item = S>,
72 S: Into<String>,
73 {
74 self.set_roles(roles.into_iter().map(Into::into).collect());
75 self
76 }
77
78 /// Sets the `iss` issuer claim.
79 ///
80 /// # Arguments
81 ///
82 /// - `S` - Issuer identifier.
83 ///
84 /// # Returns
85 ///
86 /// - `Self` - Updated claims payload.
87 pub fn with_issuer<S>(mut self, issuer: S) -> Self
88 where
89 S: Into<String>,
90 {
91 self.set_iss(Some(issuer.into()));
92 self
93 }
94
95 /// Sets the `aud` audience claim.
96 ///
97 /// # Arguments
98 ///
99 /// - `S` - Audience identifier.
100 ///
101 /// # Returns
102 ///
103 /// - `Self` - Updated claims payload.
104 pub fn with_audience<S>(mut self, audience: S) -> Self
105 where
106 S: Into<String>,
107 {
108 self.set_aud(Some(audience.into()));
109 self
110 }
111}
112
113/// Inherent implementation of [`JwtCodec`].
114impl JwtCodec {
115 /// Creates an HS256 [`JwtCodec`] signed and verified with `secret`.
116 ///
117 /// # Arguments
118 ///
119 /// - `S` - Shared HMAC-SHA256 secret bytes convertible into `Vec<u8>`.
120 ///
121 /// # Returns
122 ///
123 /// - `Self` - Ready JWT codec with 60 s default clock-skew leeway.
124 pub fn new<S>(secret: S) -> Self
125 where
126 S: Into<Vec<u8>>,
127 {
128 Self {
129 default_secret: secret.into(),
130 default_kid: None,
131 keyring: hash_map_xx_hash3_64(),
132 leeway_secs: DEFAULT_JWT_LEEWAY_SECS,
133 required_issuer: None,
134 required_audience: None,
135 }
136 }
137
138 /// Registers an additional verification key under `kid` for seamless key rotation.
139 ///
140 /// # Arguments
141 ///
142 /// - `K` - Key identifier convertible into `String`.
143 /// - `S` - Secret bytes for this `kid`.
144 ///
145 /// # Returns
146 ///
147 /// - `Self` - Updated codec.
148 pub fn with_key<K, S>(mut self, kid: K, secret: S) -> Self
149 where
150 K: Into<String>,
151 S: Into<Vec<u8>>,
152 {
153 let Self { keyring, .. } = &mut self;
154 keyring.insert(kid.into(), secret.into());
155 self
156 }
157
158 /// Sets the default `kid` stamped on newly encoded tokens (and registers its secret if absent).
159 ///
160 /// # Arguments
161 ///
162 /// - `K` - Active signing key identifier.
163 ///
164 /// # Returns
165 ///
166 /// - `Self` - Updated codec.
167 pub fn with_default_kid<K>(mut self, kid: K) -> Self
168 where
169 K: Into<String>,
170 {
171 let Self {
172 default_kid,
173 default_secret,
174 keyring,
175 ..
176 } = &mut self;
177 let kid_str: String = kid.into();
178 keyring
179 .entry(kid_str.clone())
180 .or_insert_with(|| default_secret.clone());
181 *default_kid = Some(kid_str);
182 self
183 }
184
185 /// Sets the allowed clock-skew leeway in seconds for `exp` and `nbf` checks.
186 ///
187 /// # Arguments
188 ///
189 /// - `u64` - Leeway in seconds.
190 ///
191 /// # Returns
192 ///
193 /// - `Self` - Updated codec.
194 pub fn with_leeway_secs(mut self, leeway_secs: u64) -> Self {
195 let Self {
196 leeway_secs: slot, ..
197 } = &mut self;
198 *slot = leeway_secs;
199 self
200 }
201
202 /// Requires every decoded token's `iss` claim to match `issuer`.
203 ///
204 /// # Arguments
205 ///
206 /// - `S` - Required issuer string.
207 ///
208 /// # Returns
209 ///
210 /// - `Self` - Updated codec.
211 pub fn with_required_issuer<S>(mut self, issuer: S) -> Self
212 where
213 S: Into<String>,
214 {
215 let Self {
216 required_issuer, ..
217 } = &mut self;
218 *required_issuer = Some(issuer.into());
219 self
220 }
221
222 /// Requires every decoded token's `aud` claim to match `audience`.
223 ///
224 /// # Arguments
225 ///
226 /// - `S` - Required audience string.
227 ///
228 /// # Returns
229 ///
230 /// - `Self` - Updated codec.
231 pub fn with_required_audience<S>(mut self, audience: S) -> Self
232 where
233 S: Into<String>,
234 {
235 let Self {
236 required_audience, ..
237 } = &mut self;
238 *required_audience = Some(audience.into());
239 self
240 }
241
242 /// Encodes and signs `claims` into a compact HS256 JWT (`header.payload.signature`).
243 ///
244 /// # Arguments
245 ///
246 /// - `&JwtClaims` - Claims payload to sign.
247 ///
248 /// # Returns
249 ///
250 /// - `Result<String, AuthError>` - Compact JWT string, or [`AuthError::InvalidCredentials`] on serialization failure.
251 pub fn encode(&self, claims: &JwtClaims) -> Result<String, AuthError> {
252 let Self {
253 default_secret,
254 default_kid,
255 keyring,
256 ..
257 } = self;
258 let header: JwtHeader = JwtHeader {
259 alg: JWT_ALG_HS256.to_owned(),
260 typ: Some(JWT_TYP_JWT.to_owned()),
261 kid: default_kid.clone(),
262 };
263 let header_json: Vec<u8> = to_vec(&header).map_err(|_| AuthError::InvalidCredentials)?;
264 let claims_json: Vec<u8> = to_vec(claims).map_err(|_| AuthError::InvalidCredentials)?;
265 let header_b64: String = base64url_encode(&header_json);
266 let claims_b64: String = base64url_encode(&claims_json);
267 let mut signing_input: String =
268 String::with_capacity(header_b64.len() + claims_b64.len() + 1);
269 signing_input.push_str(&header_b64);
270 signing_input.push('.');
271 signing_input.push_str(&claims_b64);
272 let secret: &[u8] = match default_kid {
273 Some(kid) => keyring
274 .get(kid)
275 .map(Vec::as_slice)
276 .unwrap_or(default_secret.as_slice()),
277 None => default_secret.as_slice(),
278 };
279 let mac: [u8; 32] = hmac_sha256(secret, signing_input.as_bytes());
280 let sig_b64: String = base64url_encode(&mac);
281 let mut token: String = String::with_capacity(signing_input.len() + 1 + sig_b64.len());
282 token.push_str(&signing_input);
283 token.push('.');
284 token.push_str(&sig_b64);
285 Ok(token)
286 }
287
288 /// Verifies and decodes a compact HS256 JWT at timestamp `now_secs`.
289 ///
290 /// # Arguments
291 ///
292 /// - `&str` - Compact JWT string (`header.payload.signature`).
293 /// - `u64` - Current Unix timestamp in seconds.
294 ///
295 /// # Returns
296 ///
297 /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or detailed [`AuthError`].
298 pub fn decode_at(&self, token: &str, now_secs: u64) -> Result<JwtClaims, AuthError> {
299 let Self {
300 default_secret,
301 keyring,
302 leeway_secs,
303 required_issuer,
304 required_audience,
305 ..
306 } = self;
307 let mut parts: Split<'_, char> = token.split('.');
308 let header_b64: &str = parts.next().ok_or(AuthError::InvalidCredentials)?;
309 let payload_b64: &str = parts.next().ok_or(AuthError::InvalidCredentials)?;
310 let sig_b64: &str = parts.next().ok_or(AuthError::InvalidCredentials)?;
311 if parts.next().is_some()
312 || header_b64.is_empty()
313 || payload_b64.is_empty()
314 || sig_b64.is_empty()
315 {
316 return Err(AuthError::InvalidCredentials);
317 }
318 let header_bytes: Vec<u8> =
319 base64url_decode(header_b64).ok_or(AuthError::InvalidCredentials)?;
320 let header: JwtHeader =
321 from_slice(&header_bytes).map_err(|_| AuthError::InvalidCredentials)?;
322 if header.get_alg() != JWT_ALG_HS256 {
323 return Err(AuthError::UnsupportedAlgorithm);
324 }
325 let secret: &[u8] = match header.get_kid() {
326 Some(kid) => keyring
327 .get(&kid)
328 .map(Vec::as_slice)
329 .ok_or(AuthError::InvalidCredentials)?,
330 None => default_secret.as_slice(),
331 };
332 let provided_sig: Vec<u8> =
333 base64url_decode(sig_b64).ok_or(AuthError::InvalidCredentials)?;
334 let signed_len: usize = header_b64.len() + 1 + payload_b64.len();
335 let expected_mac: [u8; 32] = hmac_sha256(secret, &token.as_bytes()[..signed_len]);
336 if !constant_time_eq(&provided_sig, &expected_mac) {
337 return Err(AuthError::InvalidCredentials);
338 }
339 let payload_bytes: Vec<u8> =
340 base64url_decode(payload_b64).ok_or(AuthError::InvalidCredentials)?;
341 let claims: JwtClaims =
342 from_slice(&payload_bytes).map_err(|_| AuthError::InvalidCredentials)?;
343 if let Some(exp) = claims.get_exp()
344 && now_secs > exp.saturating_add(*leeway_secs)
345 {
346 return Err(AuthError::TokenExpired);
347 }
348 if let Some(nbf) = claims.get_nbf()
349 && now_secs.saturating_add(*leeway_secs) < nbf
350 {
351 return Err(AuthError::TokenNotYetValid);
352 }
353 if let Some(expected_iss) = required_issuer
354 && claims.get_iss().as_deref() != Some(expected_iss.as_str())
355 {
356 return Err(AuthError::ClaimMismatch);
357 }
358 if let Some(expected_aud) = required_audience
359 && claims.get_aud().as_deref() != Some(expected_aud.as_str())
360 {
361 return Err(AuthError::ClaimMismatch);
362 }
363 Ok(claims)
364 }
365
366 /// Verifies and decodes a compact HS256 JWT against current system time.
367 ///
368 /// # Arguments
369 ///
370 /// - `&str` - Compact JWT string.
371 ///
372 /// # Returns
373 ///
374 /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or [`AuthError`].
375 pub fn decode(&self, token: &str) -> Result<JwtClaims, AuthError> {
376 self.decode_at(token, auth_now_secs())
377 }
378}
379
380/// Inherent helpers for [`AuthPrincipal`].
381impl AuthPrincipal {
382 /// Checks whether this principal possesses `role`.
383 ///
384 /// # Arguments
385 ///
386 /// - `&str` - Role name to check.
387 ///
388 /// # Returns
389 ///
390 /// - `bool` - `true` when the role is granted.
391 pub fn has_role(&self, role: &str) -> bool {
392 self.get_roles().iter().any(|item: &String| item == role)
393 }
394}
395
396/// Inherent implementation of [`JwtAuthenticator`].
397impl JwtAuthenticator {
398 /// Creates a [`JwtAuthenticator`] backed by `codec`.
399 ///
400 /// # Arguments
401 ///
402 /// - `JwtCodec` - Configured HS256 codec.
403 ///
404 /// # Returns
405 ///
406 /// - `Self` - Bearer JWT authenticator.
407 pub fn new(codec: JwtCodec) -> Self {
408 Self { codec }
409 }
410}
411
412/// Implements [`Authenticator`] for [`JwtAuthenticator`].
413impl Authenticator for JwtAuthenticator {
414 /// Authenticates `Authorization: Bearer <token>` requests via [`JwtCodec`].
415 ///
416 /// # Arguments
417 ///
418 /// - `&'a self` - Shared reference to self.
419 /// - `&'a Context` - Incoming request context.
420 ///
421 /// # Returns
422 ///
423 /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
424 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
425 let Self { codec } = self;
426 let result: Result<AuthPrincipal, AuthError> =
427 match ctx.get_request().try_get_header_back(AUTHORIZATION) {
428 None => Err(AuthError::MissingCredentials),
429 Some(header) => match strip_auth_scheme(&header, PREFIX_BEARER) {
430 None => Err(AuthError::MissingCredentials),
431 Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
432 subject: claims.get_sub().clone(),
433 roles: claims.get_roles().clone(),
434 scheme: AuthScheme::BearerJwt,
435 claims: Some(claims),
436 }),
437 },
438 };
439 Box::pin(async move { result })
440 }
441}
442
443/// Default construction for [`ApiKeyAuthenticator`].
444impl Default for ApiKeyAuthenticator {
445 /// Constructs an empty [`ApiKeyAuthenticator`] reading `X-Api-Key`.
446 fn default() -> Self {
447 Self::new(X_API_KEY)
448 }
449}
450
451/// Inherent implementation of [`ApiKeyAuthenticator`].
452impl ApiKeyAuthenticator {
453 /// Creates an [`ApiKeyAuthenticator`] reading `header_name`.
454 ///
455 /// # Arguments
456 ///
457 /// - `H` - Header name convertible into `String`.
458 ///
459 /// # Returns
460 ///
461 /// - `Self` - Empty API-key authenticator.
462 pub fn new<H>(header_name: H) -> Self
463 where
464 H: Into<String>,
465 {
466 Self {
467 header_name: header_name.into(),
468 entries: Vec::new(),
469 }
470 }
471
472 /// Registers an allowed API key associated with `subject` and `roles`.
473 ///
474 /// # Arguments
475 ///
476 /// - `K` - Secret API key string.
477 /// - `S` - Subject name assigned when matched.
478 /// - `I` - Iterator of role names.
479 ///
480 /// # Returns
481 ///
482 /// - `Self` - Updated authenticator.
483 pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
484 where
485 K: Into<String>,
486 S: Into<String>,
487 I: IntoIterator<Item = R>,
488 R: Into<String>,
489 {
490 let Self { entries, .. } = &mut self;
491 entries.push((
492 api_key.into().into_bytes(),
493 subject.into(),
494 roles.into_iter().map(Into::into).collect(),
495 ));
496 self
497 }
498}
499
500/// Implements [`Authenticator`] for [`ApiKeyAuthenticator`].
501impl Authenticator for ApiKeyAuthenticator {
502 /// Authenticates incoming API key headers using constant-time key comparisons.
503 ///
504 /// # Arguments
505 ///
506 /// - `&'a self` - Shared reference to self.
507 /// - `&'a Context` - Incoming request context.
508 ///
509 /// # Returns
510 ///
511 /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
512 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
513 let Self {
514 header_name,
515 entries,
516 } = self;
517 let result: Result<AuthPrincipal, AuthError> =
518 match ctx.get_request().try_get_header_back(header_name) {
519 None => Err(AuthError::MissingCredentials),
520 Some(candidate) => {
521 let candidate_bytes: &[u8] = candidate.trim().as_bytes();
522 let mut matched: Option<AuthPrincipal> = None;
523 for (secret, subject, roles) in entries {
524 if constant_time_eq(candidate_bytes, secret) {
525 matched = Some(AuthPrincipal {
526 subject: subject.clone(),
527 roles: roles.clone(),
528 scheme: AuthScheme::ApiKey,
529 claims: None,
530 });
531 }
532 }
533 matched.ok_or(AuthError::InvalidCredentials)
534 }
535 };
536 Box::pin(async move { result })
537 }
538}
539
540/// Default construction for [`BasicAuthenticator`].
541impl Default for BasicAuthenticator {
542 /// Constructs an empty [`BasicAuthenticator`].
543 fn default() -> Self {
544 Self::new()
545 }
546}
547
548/// Inherent implementation of [`BasicAuthenticator`].
549impl BasicAuthenticator {
550 /// Creates an empty [`BasicAuthenticator`].
551 ///
552 /// # Returns
553 ///
554 /// - `Self` - Empty HTTP Basic authenticator.
555 pub fn new() -> Self {
556 Self {
557 users: hash_map_xx_hash3_64(),
558 }
559 }
560
561 /// Registers a Basic-auth user with `username`, `password`, and `roles`.
562 ///
563 /// # Arguments
564 ///
565 /// - `U` - Username string.
566 /// - `P` - Password string.
567 /// - `I` - Iterator of role names.
568 ///
569 /// # Returns
570 ///
571 /// - `Self` - Updated authenticator.
572 pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
573 where
574 U: Into<String>,
575 P: Into<String>,
576 I: IntoIterator<Item = R>,
577 R: Into<String>,
578 {
579 let Self { users } = &mut self;
580 users.insert(
581 username.into(),
582 (
583 password.into().into_bytes(),
584 roles.into_iter().map(Into::into).collect(),
585 ),
586 );
587 self
588 }
589}
590
591/// Implements [`Authenticator`] for [`BasicAuthenticator`].
592impl Authenticator for BasicAuthenticator {
593 /// Authenticates `Authorization: Basic <base64>` using constant-time password checks.
594 ///
595 /// # Arguments
596 ///
597 /// - `&'a self` - Shared reference to self.
598 /// - `&'a Context` - Incoming request context.
599 ///
600 /// # Returns
601 ///
602 /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
603 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
604 let Self { users } = self;
605 let result: Result<AuthPrincipal, AuthError> =
606 match ctx.get_request().try_get_header_back(AUTHORIZATION) {
607 None => Err(AuthError::MissingCredentials),
608 Some(header) => match strip_auth_scheme(&header, PREFIX_BASIC) {
609 None => Err(AuthError::MissingCredentials),
610 Some(encoded) => match base64_decode(encoded)
611 .and_then(|raw: Vec<u8>| String::from_utf8(raw).ok())
612 {
613 None => Err(AuthError::InvalidCredentials),
614 Some(decoded) => match decoded.split_once(':') {
615 None => Err(AuthError::InvalidCredentials),
616 Some((user, pass)) => match users.get(user) {
617 Some((expected_pass, roles))
618 if constant_time_eq(pass.as_bytes(), expected_pass) =>
619 {
620 Ok(AuthPrincipal {
621 subject: user.to_owned(),
622 roles: roles.clone(),
623 scheme: AuthScheme::Basic,
624 claims: None,
625 })
626 }
627 _ => Err(AuthError::InvalidCredentials),
628 },
629 },
630 },
631 },
632 };
633 Box::pin(async move { result })
634 }
635}
636
637/// Inherent implementation of [`CompositeAuthenticator`].
638impl CompositeAuthenticator {
639 /// Creates a [`CompositeAuthenticator`] chaining `chain` in priority order.
640 ///
641 /// # Arguments
642 ///
643 /// - `Vec<SharedAuthenticator>` - Ordered list of authenticators.
644 ///
645 /// # Returns
646 ///
647 /// - `Self` - Composite authenticator.
648 pub fn new(chain: Vec<SharedAuthenticator>) -> Self {
649 Self { chain }
650 }
651}
652
653/// Implements [`Authenticator`] for [`CompositeAuthenticator`].
654impl Authenticator for CompositeAuthenticator {
655 /// Evaluates each authenticator in order, returning the first verified [`AuthPrincipal`].
656 ///
657 /// # Arguments
658 ///
659 /// - `&'a self` - Shared reference to self.
660 /// - `&'a Context` - Incoming request context.
661 ///
662 /// # Returns
663 ///
664 /// - `AuthFuture<'a>` - Future resolving to the first matching [`AuthPrincipal`] or last non-missing error.
665 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
666 let Self { chain } = self;
667 Box::pin(async move {
668 let mut last_err: AuthError = AuthError::MissingCredentials;
669 for auth in chain {
670 match auth.authenticate(ctx).await {
671 Ok(principal) => return Ok(principal),
672 Err(AuthError::MissingCredentials) => {}
673 Err(err) => last_err = err,
674 }
675 }
676 Err(last_err)
677 })
678 }
679}
680
681/// Default construction for [`AuthConfig`].
682impl Default for AuthConfig {
683 /// Constructs a default [`AuthConfig`] with Bearer realm challenge and no exempt paths.
684 fn default() -> Self {
685 Self {
686 exempt_paths: Vec::new(),
687 required_roles: Vec::new(),
688 require_all_roles: false,
689 www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
690 }
691 }
692}
693
694/// Inherent builders for [`AuthConfig`].
695impl AuthConfig {
696 /// Configures exact paths excluded from authentication checks.
697 ///
698 /// # Arguments
699 ///
700 /// - `I` - Iterator of exempt paths.
701 ///
702 /// # Returns
703 ///
704 /// - `Self` - Updated configuration.
705 pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
706 where
707 I: IntoIterator<Item = S>,
708 S: Into<String>,
709 {
710 self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
711 self
712 }
713
714 /// Configures roles required to access protected routes.
715 ///
716 /// # Arguments
717 ///
718 /// - `I` - Iterator of required role names.
719 ///
720 /// # Returns
721 ///
722 /// - `Self` - Updated configuration.
723 pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
724 where
725 I: IntoIterator<Item = S>,
726 S: Into<String>,
727 {
728 self.set_required_roles(roles.into_iter().map(Into::into).collect());
729 self
730 }
731}
732
733/// Inherent implementation of [`AuthPlugin`].
734impl AuthPlugin {
735 /// Initializes the global [`AuthPlugin`] once with `config` and `authenticator`.
736 ///
737 /// # Arguments
738 ///
739 /// - `AuthConfig` - Path-exclusion and RBAC policy.
740 /// - `SharedAuthenticator` - Pluggable authenticator implementation.
741 ///
742 /// # Returns
743 ///
744 /// - `&'static Self` - Reference to the initialized global plugin.
745 pub fn init(config: AuthConfig, authenticator: SharedAuthenticator) -> &'static Self {
746 AUTH_PLUGIN.get_or_init(|| Self {
747 config,
748 authenticator,
749 })
750 }
751
752 /// Returns the initialized global [`AuthPlugin`], if initialized.
753 ///
754 /// # Returns
755 ///
756 /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
757 pub fn get() -> Option<&'static Self> {
758 AUTH_PLUGIN.get()
759 }
760
761 /// Returns the active [`AuthConfig`].
762 ///
763 /// # Returns
764 ///
765 /// - `&AuthConfig` - Active authorization policy.
766 pub fn get_config(&self) -> &AuthConfig {
767 &self.config
768 }
769
770 /// Returns the active [`SharedAuthenticator`].
771 ///
772 /// # Returns
773 ///
774 /// - `&SharedAuthenticator` - Active authenticator.
775 pub fn get_authenticator(&self) -> &SharedAuthenticator {
776 &self.authenticator
777 }
778
779 /// Retrieves the verified [`AuthPrincipal`] previously stored in `ctx` by [`AuthHook`].
780 ///
781 /// # Arguments
782 ///
783 /// - `&Context` - Request context.
784 ///
785 /// # Returns
786 ///
787 /// - `Option<AuthPrincipal>` - Verified caller principal, if authenticated.
788 pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
789 ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
790 }
791
792 /// Checks whether `principal` satisfies the configured RBAC role requirements.
793 ///
794 /// # Arguments
795 ///
796 /// - `&AuthPrincipal` - Verified principal.
797 ///
798 /// # Returns
799 ///
800 /// - `bool` - `true` when authorized.
801 pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
802 let required: &Vec<String> = self.get_config().get_required_roles();
803 if required.is_empty() {
804 return true;
805 }
806 if self.get_config().get_require_all_roles() {
807 required
808 .iter()
809 .all(|role: &String| principal.has_role(role))
810 } else {
811 required
812 .iter()
813 .any(|role: &String| principal.has_role(role))
814 }
815 }
816}
817
818/// Implements [`ServerHook`] for [`AuthHook`].
819impl ServerHook for AuthHook {
820 /// Constructs a per-request [`AuthHook`].
821 ///
822 /// # Arguments
823 ///
824 /// - `&mut Stream` - Connection stream.
825 /// - `&mut Context` - Request context.
826 ///
827 /// # Returns
828 ///
829 /// - `Self` - Hook instance.
830 async fn new(_: &mut Stream, _: &mut Context) -> Self {
831 Self
832 }
833
834 /// Authenticates protected requests, verifies required roles, and attaches [`AuthPrincipal`].
835 ///
836 /// # Arguments
837 ///
838 /// - `Self` - Hook instance.
839 /// - `&mut Stream` - Connection stream.
840 /// - `&mut Context` - Request context.
841 ///
842 /// # Returns
843 ///
844 /// - `Status` - `Status::Continue` when unconfigured, exempt, or authorized; `Status::Reject` on `401`/`403`.
845 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
846 let Some(plugin) = AuthPlugin::get() else {
847 return Status::Continue;
848 };
849 let path: &str = ctx.get_request().get_path();
850 if plugin
851 .get_config()
852 .get_exempt_paths()
853 .iter()
854 .any(|exempt: &String| exempt == path)
855 {
856 return Status::Continue;
857 }
858 match plugin.get_authenticator().authenticate(ctx).await {
859 Ok(principal) => {
860 if !plugin.is_authorized(&principal) {
861 ctx.get_mut_response()
862 .set_status_code(HttpStatus::Forbidden.code())
863 .set_body(Vec::new());
864 let wire: ResponseData = ctx.get_mut_response().build();
865 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
866 return Status::Reject;
867 }
868 ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
869 Status::Continue
870 }
871 Err(AuthError::Forbidden) => {
872 ctx.get_mut_response()
873 .set_status_code(HttpStatus::Forbidden.code())
874 .set_body(Vec::new());
875 let wire: ResponseData = ctx.get_mut_response().build();
876 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
877 Status::Reject
878 }
879 Err(_) => {
880 ctx.get_mut_response()
881 .set_status_code(HttpStatus::Unauthorized.code())
882 .set_header(WWW_AUTHENTICATE, plugin.get_config().get_www_authenticate())
883 .set_body(Vec::new());
884 let wire: ResponseData = ctx.get_mut_response().build();
885 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
886 Status::Reject
887 }
888 }
889 }
890}