1use super::*;
2
3impl HmacSha256Key {
5 #[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 #[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
76impl StackJsonBuf {
78 #[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 #[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
107impl Write for StackJsonBuf {
109 #[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 #[inline]
144 fn flush(&mut self) -> io::Result<()> {
145 Ok(())
146 }
147}
148
149impl Display for AuthError {
151 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
173impl Error for AuthError {}
175
176impl JwtClaims {
178 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 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 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 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
259impl JwtCodec {
261 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 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 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 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 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 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 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 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 pub fn decode(&self, token: &str) -> Result<JwtClaims, AuthError> {
563 self.decode_at(token, auth_now_secs())
564 }
565}
566
567impl AuthPrincipal {
569 #[inline]
579 pub fn has_role(&self, role: &str) -> bool {
580 self.get_roles().iter().any(|item: &String| item == role)
581 }
582}
583
584impl JwtAuthenticator {
586 pub fn new(codec: JwtCodec) -> Self {
596 Self { codec }
597 }
598}
599
600impl Authenticator for JwtAuthenticator {
602 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
631impl Default for ApiKeyAuthenticator {
633 fn default() -> Self {
635 Self::new(X_API_KEY)
636 }
637}
638
639impl ApiKeyAuthenticator {
641 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 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
688impl Authenticator for ApiKeyAuthenticator {
690 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
735impl Default for BasicAuthenticator {
737 fn default() -> Self {
739 Self::new()
740 }
741}
742
743impl BasicAuthenticator {
745 pub fn new() -> Self {
751 Self {
752 users: hash_map_xx_hash3_64(),
753 }
754 }
755
756 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
786impl Authenticator for BasicAuthenticator {
788 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
849impl CompositeAuthenticator {
851 pub fn new(chain: Vec<SharedAuthenticator>) -> Self {
861 Self { chain }
862 }
863}
864
865impl Authenticator for CompositeAuthenticator {
867 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
893impl Default for AuthConfig {
895 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
906impl AuthConfig {
908 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 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
945impl AuthPlugin {
947 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 #[inline(always)]
983 pub fn get() -> Option<&'static Self> {
984 AUTH_PLUGIN.get()
985 }
986
987 #[inline(always)]
993 pub fn get_config(&self) -> &AuthConfig {
994 &self.config
995 }
996
997 #[inline(always)]
1003 pub fn get_authenticator(&self) -> &SharedAuthenticator {
1004 &self.authenticator
1005 }
1006
1007 #[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 pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
1041 ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
1042 }
1043
1044 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
1070impl ServerHook for AuthHook {
1072 #[inline(always)]
1083 async fn new(_: &mut Stream, _: &mut Context) -> Self {
1084 Self
1085 }
1086
1087 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}