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 Self { codec } = self;
983 Box::pin(async move {
984 match request_header_back(ctx.get_request(), AUTHORIZATION) {
985 None => Err(AuthError::MissingCredentials),
986 Some(header) => match strip_auth_scheme(header, PREFIX_BEARER) {
987 None => Err(AuthError::MissingCredentials),
988 Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
989 subject: claims.get_sub().clone(),
990 roles: claims.get_roles().clone(),
991 scheme: AuthScheme::BearerJwt,
992 claims: Some(claims),
993 }),
994 },
995 }
996 })
997 }
998}
999
1000impl Default for ApiKeyAuthenticator {
1002 fn default() -> Self {
1004 Self::new(X_API_KEY)
1005 }
1006}
1007
1008impl ApiKeyAuthenticator {
1010 pub fn new<H>(header_name: H) -> Self
1020 where
1021 H: Into<String>,
1022 {
1023 Self {
1024 header_name: header_name.into().to_ascii_lowercase(),
1025 entries: Vec::new(),
1026 }
1027 }
1028
1029 pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
1041 where
1042 K: Into<String>,
1043 S: Into<String>,
1044 I: IntoIterator<Item = R>,
1045 R: Into<String>,
1046 {
1047 let Self { entries, .. } = &mut self;
1048 entries.push((
1049 api_key.into().into_bytes(),
1050 subject.into(),
1051 roles.into_iter().map(Into::into).collect(),
1052 ));
1053 self
1054 }
1055}
1056
1057impl Authenticator for ApiKeyAuthenticator {
1059 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1070 let Self {
1071 header_name,
1072 entries,
1073 } = self;
1074 Box::pin(async move {
1075 match request_header_back(ctx.get_request(), header_name) {
1076 None => Err(AuthError::MissingCredentials),
1077 Some(candidate) => {
1078 let candidate_bytes: &[u8] = candidate.trim().as_bytes();
1079 let mut matched_idx: Option<usize> = None;
1080 for (idx, (secret, _, _)) in entries.iter().enumerate() {
1081 if constant_time_eq(candidate_bytes, secret) {
1082 matched_idx = Some(idx);
1083 }
1084 }
1085 match matched_idx {
1086 Some(idx) => {
1087 let (_, subject, roles): &(Vec<u8>, String, Vec<String>) =
1088 &entries[idx];
1089 Ok(AuthPrincipal {
1090 subject: subject.clone(),
1091 roles: roles.clone(),
1092 scheme: AuthScheme::ApiKey,
1093 claims: None,
1094 })
1095 }
1096 None => Err(AuthError::InvalidCredentials),
1097 }
1098 }
1099 }
1100 })
1101 }
1102}
1103
1104impl Default for BasicAuthenticator {
1106 fn default() -> Self {
1108 Self::new()
1109 }
1110}
1111
1112impl BasicAuthenticator {
1114 pub fn new() -> Self {
1120 Self {
1121 users: hash_map_xx_hash3_64(),
1122 }
1123 }
1124
1125 pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
1137 where
1138 U: Into<String>,
1139 P: Into<String>,
1140 I: IntoIterator<Item = R>,
1141 R: Into<String>,
1142 {
1143 let Self { users } = &mut self;
1144 users.insert(
1145 username.into(),
1146 (
1147 password.into().into_bytes(),
1148 roles.into_iter().map(Into::into).collect(),
1149 ),
1150 );
1151 self
1152 }
1153}
1154
1155impl Authenticator for BasicAuthenticator {
1157 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1168 let Self { users } = self;
1169 Box::pin(async move {
1170 match request_header_back(ctx.get_request(), AUTHORIZATION) {
1171 None => Err(AuthError::MissingCredentials),
1172 Some(header) => match strip_auth_scheme(header, PREFIX_BASIC) {
1173 None => Err(AuthError::MissingCredentials),
1174 Some(encoded) => {
1175 let trimmed_b64: &[u8] = encoded.trim_end_matches('=').as_bytes();
1176 let decoded_len: usize = (trimmed_b64.len() * 3) / 4;
1177 let mut stack_buf: [u8; BASIC_STACK_CAP] = [0u8; BASIC_STACK_CAP];
1178 let heap_buf: Vec<u8>;
1179 let raw_opt: Option<&[u8]> = if decoded_len <= BASIC_STACK_CAP {
1180 decode_base64_into(
1181 trimmed_b64,
1182 &BASE64_STD_DECODE_TABLE,
1183 &mut stack_buf,
1184 )
1185 .map(|written: usize| &stack_buf[..written])
1186 } else if let Some(buf) = base64_decode(encoded) {
1187 heap_buf = buf;
1188 Some(heap_buf.as_slice())
1189 } else {
1190 None
1191 };
1192 match raw_opt.and_then(|raw: &[u8]| from_utf8(raw).ok()) {
1193 None => Err(AuthError::InvalidCredentials),
1194 Some(decoded) => match decoded.split_once(':') {
1195 None => Err(AuthError::InvalidCredentials),
1196 Some((user, pass)) => match users.get(user) {
1197 Some((expected_pass, roles))
1198 if constant_time_eq(pass.as_bytes(), expected_pass) =>
1199 {
1200 Ok(AuthPrincipal {
1201 subject: user.to_owned(),
1202 roles: roles.clone(),
1203 scheme: AuthScheme::Basic,
1204 claims: None,
1205 })
1206 }
1207 _ => Err(AuthError::InvalidCredentials),
1208 },
1209 },
1210 }
1211 }
1212 },
1213 }
1214 })
1215 }
1216}
1217
1218impl CompositeAuthenticator {
1220 pub fn new(chain: Vec<Arc<dyn Authenticator>>) -> Self {
1230 Self { chain }
1231 }
1232}
1233
1234impl Authenticator for CompositeAuthenticator {
1236 fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
1247 let Self { chain } = self;
1248 Box::pin(async move {
1249 let mut last_err: AuthError = AuthError::MissingCredentials;
1250 for auth in chain {
1251 match auth.authenticate(ctx).await {
1252 Ok(principal) => return Ok(principal),
1253 Err(AuthError::MissingCredentials) => {}
1254 Err(err) => last_err = err,
1255 }
1256 }
1257 Err(last_err)
1258 })
1259 }
1260}
1261
1262impl Default for AuthConfig {
1264 fn default() -> Self {
1266 Self {
1267 exempt_paths: Vec::new(),
1268 required_roles: Vec::new(),
1269 require_all_roles: false,
1270 www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
1271 }
1272 }
1273}
1274
1275impl AuthConfig {
1277 pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
1287 where
1288 I: IntoIterator<Item = S>,
1289 S: Into<String>,
1290 {
1291 self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
1292 self
1293 }
1294
1295 pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
1305 where
1306 I: IntoIterator<Item = S>,
1307 S: Into<String>,
1308 {
1309 self.set_required_roles(roles.into_iter().map(Into::into).collect());
1310 self
1311 }
1312}
1313
1314impl AuthPlugin {
1316 pub fn init(config: AuthConfig, authenticator: Arc<dyn Authenticator>) -> &'static Self {
1327 AUTH_PLUGIN.get_or_init(|| {
1328 let exempt_set: Option<HashSetXxHash3_64<String>> =
1329 if config.get_exempt_paths().len() > EXEMPT_SET_THRESHOLD {
1330 let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
1331 for path in config.get_exempt_paths() {
1332 set.insert(path.clone());
1333 }
1334 Some(set)
1335 } else {
1336 None
1337 };
1338 let mut resp_401: Response = Response::default();
1339 resp_401
1340 .set_status_code(HttpStatus::Unauthorized.code())
1341 .set_header(WWW_AUTHENTICATE, config.get_www_authenticate())
1342 .set_body(Vec::new());
1343 let prebuilt_401_wire: Vec<u8> = resp_401.build();
1344 let mut resp_403: Response = Response::default();
1345 resp_403
1346 .set_status_code(HttpStatus::Forbidden.code())
1347 .set_body(Vec::new());
1348 let prebuilt_403_wire: Vec<u8> = resp_403.build();
1349 Self {
1350 config,
1351 authenticator,
1352 exempt_set,
1353 prebuilt_401_wire,
1354 prebuilt_403_wire,
1355 }
1356 })
1357 }
1358
1359 #[inline(always)]
1365 pub fn get() -> Option<&'static Self> {
1366 AUTH_PLUGIN.get()
1367 }
1368
1369 #[inline(always)]
1375 pub fn get_config(&self) -> &AuthConfig {
1376 &self.config
1377 }
1378
1379 #[inline(always)]
1385 pub fn get_authenticator(&self) -> &Arc<dyn Authenticator> {
1386 &self.authenticator
1387 }
1388
1389 #[inline(always)]
1399 pub(crate) fn is_exempt_path(&self, path: &str) -> bool {
1400 let Self {
1401 config, exempt_set, ..
1402 } = self;
1403 if let Some(set) = exempt_set {
1404 return set.contains(path);
1405 }
1406 let exempt: &[String] = config.get_exempt_paths().as_slice();
1407 if exempt.is_empty() {
1408 return false;
1409 }
1410 exempt.iter().any(|item: &String| item.as_str() == path)
1411 }
1412
1413 pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
1423 ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
1424 }
1425
1426 pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
1436 let required: &Vec<String> = self.get_config().get_required_roles();
1437 if required.is_empty() {
1438 return true;
1439 }
1440 if self.get_config().get_require_all_roles() {
1441 required
1442 .iter()
1443 .all(|role: &String| principal.has_role(role))
1444 } else {
1445 required
1446 .iter()
1447 .any(|role: &String| principal.has_role(role))
1448 }
1449 }
1450}
1451
1452impl ServerHook for AuthHook {
1454 #[inline(always)]
1465 async fn new(_: &mut Stream, _: &mut Context) -> Self {
1466 Self
1467 }
1468
1469 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1481 let Some(plugin) = AuthPlugin::get() else {
1482 return Status::Continue;
1483 };
1484 let path: &str = ctx.get_request().get_path();
1485 if plugin.is_exempt_path(path) {
1486 return Status::Continue;
1487 }
1488 match plugin.get_authenticator().authenticate(ctx).await {
1489 Ok(principal) => {
1490 if !plugin.is_authorized(&principal) {
1491 let _: Result<(), ResponseError> =
1492 stream.try_send(&plugin.prebuilt_403_wire).await;
1493 return Status::Reject;
1494 }
1495 ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
1496 Status::Continue
1497 }
1498 Err(AuthError::Forbidden) => {
1499 let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_403_wire).await;
1500 Status::Reject
1501 }
1502 Err(_) => {
1503 let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_401_wire).await;
1504 Status::Reject
1505 }
1506 }
1507 }
1508}