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 #[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
85impl StackJsonBuf {
87 #[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 #[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 #[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 #[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
163impl Write for StackJsonBuf {
165 #[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 #[inline]
200 fn flush(&mut self) -> io::Result<()> {
201 Ok(())
202 }
203}
204
205impl Display for AuthError {
207 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
229impl Error for AuthError {}
231
232impl Serialize for JwtClaims {
234 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
310impl<'de> Visitor<'de> for JwtClaimFieldVisitor {
312 type Value = JwtClaimField;
313
314 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
324 formatter.write_str(EXPECTING_JWT_FIELD)
325 }
326
327 #[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 #[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
382impl<'de> Deserialize<'de> for JwtClaimField {
384 #[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
402impl<'de> Visitor<'de> for JwtClaimsVisitor {
404 type Value = JwtClaims;
405
406 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
416 formatter.write_str(EXPECTING_JWT_CLAIMS)
417 }
418
419 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
521impl<'de> Deserialize<'de> for JwtClaims {
523 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
533 where
534 D: Deserializer<'de>,
535 {
536 deserializer.deserialize_map(JwtClaimsVisitor)
537 }
538}
539
540impl JwtClaims {
542 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 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 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 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
623impl JwtCodec {
625 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 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 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 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 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 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 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 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 pub fn decode(&self, token: &str) -> Result<JwtClaims, AuthError> {
932 self.decode_at(token, auth_now_secs())
933 }
934}
935
936impl AuthPrincipal {
938 #[inline]
948 pub fn has_role(&self, role: &str) -> bool {
949 self.get_roles().iter().any(|item: &String| item == role)
950 }
951}
952
953impl JwtAuthenticator {
955 pub fn new(codec: JwtCodec) -> Self {
965 Self { codec }
966 }
967}
968
969impl Authenticator for JwtAuthenticator {
971 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
982 let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
983 Box::pin(async move { result })
984 }
985
986 #[inline]
997 fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
998 Some(self.eval_sync(ctx))
999 }
1000}
1001
1002impl JwtAuthenticator {
1004 #[inline]
1014 fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
1015 let Self { codec } = self;
1016 match request_header_back(ctx.get_request(), AUTHORIZATION) {
1017 None => Err(AuthError::MissingCredentials),
1018 Some(header) => match strip_auth_scheme(header, PREFIX_BEARER) {
1019 None => Err(AuthError::MissingCredentials),
1020 Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
1021 subject: claims.get_sub().clone(),
1022 roles: claims.get_roles().clone(),
1023 scheme: AuthScheme::BearerJwt,
1024 claims: Some(claims),
1025 }),
1026 },
1027 }
1028 }
1029}
1030
1031impl Default for ApiKeyAuthenticator {
1033 fn default() -> Self {
1035 Self::new(X_API_KEY)
1036 }
1037}
1038
1039impl ApiKeyAuthenticator {
1041 pub fn new<H>(header_name: H) -> Self
1051 where
1052 H: Into<String>,
1053 {
1054 Self {
1055 header_name: header_name.into().to_ascii_lowercase(),
1056 entries: Vec::new(),
1057 }
1058 }
1059
1060 pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
1072 where
1073 K: Into<String>,
1074 S: Into<String>,
1075 I: IntoIterator<Item = R>,
1076 R: Into<String>,
1077 {
1078 let Self { entries, .. } = &mut self;
1079 entries.push((
1080 api_key.into().into_bytes(),
1081 subject.into(),
1082 roles.into_iter().map(Into::into).collect(),
1083 ));
1084 self
1085 }
1086}
1087
1088impl Authenticator for ApiKeyAuthenticator {
1090 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1101 let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
1102 Box::pin(async move { result })
1103 }
1104
1105 #[inline]
1116 fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
1117 Some(self.eval_sync(ctx))
1118 }
1119}
1120
1121impl ApiKeyAuthenticator {
1123 #[inline]
1133 fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
1134 let Self {
1135 header_name,
1136 entries,
1137 } = self;
1138 match request_header_back(ctx.get_request(), header_name) {
1139 None => Err(AuthError::MissingCredentials),
1140 Some(candidate) => {
1141 let candidate_bytes: &[u8] = candidate.trim().as_bytes();
1142 let mut matched_idx: Option<usize> = None;
1143 for (idx, (secret, _, _)) in entries.iter().enumerate() {
1144 if constant_time_eq(candidate_bytes, secret) {
1145 matched_idx = Some(idx);
1146 }
1147 }
1148 match matched_idx {
1149 Some(idx) => {
1150 let (_, subject, roles): &(Vec<u8>, String, Vec<String>) = &entries[idx];
1151 Ok(AuthPrincipal {
1152 subject: subject.clone(),
1153 roles: roles.clone(),
1154 scheme: AuthScheme::ApiKey,
1155 claims: None,
1156 })
1157 }
1158 None => Err(AuthError::InvalidCredentials),
1159 }
1160 }
1161 }
1162 }
1163}
1164
1165impl Default for BasicAuthenticator {
1167 fn default() -> Self {
1169 Self::new()
1170 }
1171}
1172
1173impl BasicAuthenticator {
1175 pub fn new() -> Self {
1181 Self {
1182 users: hash_map_xx_hash3_64(),
1183 }
1184 }
1185
1186 pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
1198 where
1199 U: Into<String>,
1200 P: Into<String>,
1201 I: IntoIterator<Item = R>,
1202 R: Into<String>,
1203 {
1204 let Self { users } = &mut self;
1205 users.insert(
1206 username.into(),
1207 (
1208 password.into().into_bytes(),
1209 roles.into_iter().map(Into::into).collect(),
1210 ),
1211 );
1212 self
1213 }
1214}
1215
1216impl Authenticator for BasicAuthenticator {
1218 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1229 let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
1230 Box::pin(async move { result })
1231 }
1232
1233 #[inline]
1244 fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
1245 Some(self.eval_sync(ctx))
1246 }
1247}
1248
1249impl BasicAuthenticator {
1251 #[inline]
1261 fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
1262 let Self { users } = self;
1263 match request_header_back(ctx.get_request(), AUTHORIZATION) {
1264 None => Err(AuthError::MissingCredentials),
1265 Some(header) => match strip_auth_scheme(header, PREFIX_BASIC) {
1266 None => Err(AuthError::MissingCredentials),
1267 Some(encoded) => {
1268 let trimmed_b64: &[u8] = encoded.trim_end_matches('=').as_bytes();
1269 let decoded_len: usize = (trimmed_b64.len() * 3) / 4;
1270 let mut stack_buf: [u8; BASIC_STACK_CAP] = [0u8; BASIC_STACK_CAP];
1271 let heap_buf: Vec<u8>;
1272 let raw_opt: Option<&[u8]> = if decoded_len <= BASIC_STACK_CAP {
1273 decode_base64_into(trimmed_b64, &BASE64_STD_DECODE_TABLE, &mut stack_buf)
1274 .map(|written: usize| &stack_buf[..written])
1275 } else if let Some(buf) = base64_decode(encoded) {
1276 heap_buf = buf;
1277 Some(heap_buf.as_slice())
1278 } else {
1279 None
1280 };
1281 match raw_opt.and_then(|raw: &[u8]| from_utf8(raw).ok()) {
1282 None => Err(AuthError::InvalidCredentials),
1283 Some(decoded) => match decoded.split_once(':') {
1284 None => Err(AuthError::InvalidCredentials),
1285 Some((user, pass)) => match users.get(user) {
1286 Some((expected_pass, roles))
1287 if constant_time_eq(pass.as_bytes(), expected_pass) =>
1288 {
1289 Ok(AuthPrincipal {
1290 subject: user.to_owned(),
1291 roles: roles.clone(),
1292 scheme: AuthScheme::Basic,
1293 claims: None,
1294 })
1295 }
1296 _ => Err(AuthError::InvalidCredentials),
1297 },
1298 },
1299 }
1300 }
1301 },
1302 }
1303 }
1304}
1305
1306impl CompositeAuthenticator {
1308 pub fn new(chain: Vec<Arc<dyn Authenticator>>) -> Self {
1318 Self { chain }
1319 }
1320}
1321
1322impl Authenticator for CompositeAuthenticator {
1324 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1335 let Self { chain } = self;
1336 Box::pin(async move {
1337 let mut last_err: AuthError = AuthError::MissingCredentials;
1338 for auth in chain {
1339 match auth.authenticate(ctx).await {
1340 Ok(principal) => return Ok(principal),
1341 Err(AuthError::MissingCredentials) => {}
1342 Err(err) => last_err = err,
1343 }
1344 }
1345 Err(last_err)
1346 })
1347 }
1348}
1349
1350impl Default for AuthConfig {
1352 fn default() -> Self {
1354 Self {
1355 exempt_paths: Vec::new(),
1356 required_roles: Vec::new(),
1357 require_all_roles: false,
1358 www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
1359 }
1360 }
1361}
1362
1363impl AuthConfig {
1365 pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
1375 where
1376 I: IntoIterator<Item = S>,
1377 S: Into<String>,
1378 {
1379 self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
1380 self
1381 }
1382
1383 pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
1393 where
1394 I: IntoIterator<Item = S>,
1395 S: Into<String>,
1396 {
1397 self.set_required_roles(roles.into_iter().map(Into::into).collect());
1398 self
1399 }
1400}
1401
1402impl AuthPlugin {
1404 pub fn init(config: AuthConfig, authenticator: Arc<dyn Authenticator>) -> &'static Self {
1415 AUTH_PLUGIN.get_or_init(|| {
1416 let exempt_set: Option<HashSetXxHash3_64<String>> =
1417 if config.get_exempt_paths().len() > EXEMPT_SET_THRESHOLD {
1418 let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
1419 for path in config.get_exempt_paths() {
1420 set.insert(path.clone());
1421 }
1422 Some(set)
1423 } else {
1424 None
1425 };
1426 let mut resp_401: Response = Response::default();
1427 resp_401
1428 .set_status_code(HttpStatus::Unauthorized.code())
1429 .set_header(WWW_AUTHENTICATE, config.get_www_authenticate())
1430 .set_body(Vec::new());
1431 let prebuilt_401_wire: Vec<u8> = resp_401.build();
1432 let mut resp_403: Response = Response::default();
1433 resp_403
1434 .set_status_code(HttpStatus::Forbidden.code())
1435 .set_body(Vec::new());
1436 let prebuilt_403_wire: Vec<u8> = resp_403.build();
1437 Self {
1438 config,
1439 authenticator,
1440 exempt_set,
1441 prebuilt_401_wire,
1442 prebuilt_403_wire,
1443 }
1444 })
1445 }
1446
1447 #[inline(always)]
1453 pub fn get() -> Option<&'static Self> {
1454 AUTH_PLUGIN.get()
1455 }
1456
1457 #[inline(always)]
1463 pub fn get_config(&self) -> &AuthConfig {
1464 &self.config
1465 }
1466
1467 #[inline(always)]
1473 pub fn get_authenticator(&self) -> &Arc<dyn Authenticator> {
1474 &self.authenticator
1475 }
1476
1477 #[inline(always)]
1487 pub(crate) fn is_exempt_path(&self, path: &str) -> bool {
1488 let Self {
1489 config, exempt_set, ..
1490 } = self;
1491 if let Some(set) = exempt_set {
1492 return set.contains(path);
1493 }
1494 let exempt: &[String] = config.get_exempt_paths().as_slice();
1495 if exempt.is_empty() {
1496 return false;
1497 }
1498 exempt.iter().any(|item: &String| item.as_str() == path)
1499 }
1500
1501 pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
1511 ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
1512 }
1513
1514 pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
1524 let required: &Vec<String> = self.get_config().get_required_roles();
1525 if required.is_empty() {
1526 return true;
1527 }
1528 if self.get_config().get_require_all_roles() {
1529 required
1530 .iter()
1531 .all(|role: &String| principal.has_role(role))
1532 } else {
1533 required
1534 .iter()
1535 .any(|role: &String| principal.has_role(role))
1536 }
1537 }
1538}
1539
1540impl ServerHook for AuthHook {
1542 #[inline(always)]
1553 async fn new(_: &mut Stream, _: &mut Context) -> Self {
1554 Self
1555 }
1556
1557 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1569 let Some(plugin) = AuthPlugin::get() else {
1570 return Status::Continue;
1571 };
1572 let path: &str = ctx.get_request().get_path();
1573 if plugin.is_exempt_path(path) {
1574 return Status::Continue;
1575 }
1576 let auth_result: Result<AuthPrincipal, AuthError> =
1577 if let Some(sync_res) = plugin.get_authenticator().authenticate_sync(ctx) {
1578 sync_res
1579 } else {
1580 plugin.get_authenticator().authenticate(ctx).await
1581 };
1582 match auth_result {
1583 Ok(principal) => {
1584 if !plugin.is_authorized(&principal) {
1585 let _: Result<(), ResponseError> =
1586 stream.try_send(&plugin.prebuilt_403_wire).await;
1587 return Status::Reject;
1588 }
1589 ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
1590 Status::Continue
1591 }
1592 Err(AuthError::Forbidden) => {
1593 let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_403_wire).await;
1594 Status::Reject
1595 }
1596 Err(_) => {
1597 let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_401_wire).await;
1598 Status::Reject
1599 }
1600 }
1601 }
1602}