use super::*;
impl HmacSha256Key {
#[inline]
pub(crate) fn new(key: &[u8]) -> Self {
let mut key_block: [u8; 64] = [0u8; 64];
if key.len() > 64 {
let hashed: [u8; 32] = sha256(key);
key_block[..32].copy_from_slice(&hashed);
} else {
key_block[..key.len()].copy_from_slice(key);
}
let mut ipad: [u8; 64] = [0u8; 64];
let mut opad: [u8; 64] = [0u8; 64];
let mut i: usize = 0;
while i < 64 {
ipad[i] = key_block[i] ^ 0x36;
opad[i] = key_block[i] ^ 0x5c;
i += 1;
}
let mut inner_state: [u32; 8] = SHA256_INIT;
let mut outer_state: [u32; 8] = SHA256_INIT;
sha256_compress(&mut inner_state, &ipad);
sha256_compress(&mut outer_state, &opad);
Self {
inner_state,
outer_state,
}
}
#[inline]
pub(crate) fn mac(&self, data: &[u8]) -> [u8; 32] {
let Self {
inner_state,
outer_state,
} = *self;
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
if has_aarch64_sha2() {
return unsafe { hmac_sha256_mac_aarch64(inner_state, outer_state, data) };
}
let inner_words: [u32; 8] = sha256_finish_words_sw(inner_state, 64, data);
let outer_w: [u32; 16] = [
inner_words[0],
inner_words[1],
inner_words[2],
inner_words[3],
inner_words[4],
inner_words[5],
inner_words[6],
inner_words[7],
HMAC_OUTER_PAD_M2[0],
0,
0,
0,
0,
0,
0,
HMAC_OUTER_PAD_M3[3],
];
let mut state: [u32; 8] = outer_state;
sha256_compress_words_sw(&mut state, outer_w);
sha256_words_to_bytes(state)
}
}
impl StackJsonBuf {
#[inline]
pub(crate) fn new() -> Self {
Self {
stack: [0u8; JWT_STACK_ENCODE_CAP],
len: 0,
heap: None,
}
}
#[inline(always)]
pub(crate) fn push_byte(&mut self, byte: u8) {
let Self { stack, len, heap } = self;
if let Some(vec) = heap {
vec.push(byte);
return;
}
if *len < stack.len() {
stack[*len] = byte;
*len += 1;
} else {
let mut vec: Vec<u8> = Vec::with_capacity(*len + 64);
vec.extend_from_slice(&stack[..*len]);
vec.push(byte);
*heap = Some(vec);
}
}
#[inline(always)]
pub(crate) fn push_slice(&mut self, buf: &[u8]) {
let Self { stack, len, heap } = self;
if let Some(vec) = heap {
vec.extend_from_slice(buf);
return;
}
let next_len: usize = len.saturating_add(buf.len());
if next_len <= stack.len() {
stack[*len..next_len].copy_from_slice(buf);
*len = next_len;
} else {
let mut vec: Vec<u8> = Vec::with_capacity(next_len + 64);
vec.extend_from_slice(&stack[..*len]);
vec.extend_from_slice(buf);
*heap = Some(vec);
}
}
#[inline]
pub(crate) fn as_slice(&self) -> &[u8] {
let Self { stack, len, heap } = self;
match heap {
Some(buf) => buf.as_slice(),
None => &stack[..*len],
}
}
}
impl Write for StackJsonBuf {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let Self { stack, len, heap } = self;
if let Some(vec) = heap {
vec.extend_from_slice(buf);
return Ok(buf.len());
}
let next_len: usize = len.saturating_add(buf.len());
if next_len <= stack.len() {
stack[*len..next_len].copy_from_slice(buf);
*len = next_len;
} else {
let mut vec: Vec<u8> = Vec::with_capacity(next_len);
vec.extend_from_slice(&stack[..*len]);
vec.extend_from_slice(buf);
*heap = Some(vec);
}
Ok(buf.len())
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Display for AuthError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::MissingCredentials => f.write_str(MSG_AUTH_MISSING),
Self::InvalidCredentials => f.write_str(MSG_AUTH_INVALID),
Self::TokenExpired => f.write_str(MSG_AUTH_EXPIRED),
Self::TokenNotYetValid => f.write_str(MSG_AUTH_NOT_YET_VALID),
Self::UnsupportedAlgorithm => f.write_str(MSG_AUTH_UNSUPPORTED_ALG),
Self::ClaimMismatch => f.write_str(MSG_AUTH_CLAIM_MISMATCH),
Self::Forbidden => f.write_str(MSG_AUTH_FORBIDDEN),
}
}
}
impl Error for AuthError {}
impl Serialize for JwtClaims {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let Self {
sub,
iss,
aud,
exp,
nbf,
iat,
jti,
roles,
extra,
} = self;
let mut field_count: usize = 1 + extra.len();
if iss.is_some() {
field_count += 1;
}
if aud.is_some() {
field_count += 1;
}
if exp.is_some() {
field_count += 1;
}
if nbf.is_some() {
field_count += 1;
}
if iat.is_some() {
field_count += 1;
}
if jti.is_some() {
field_count += 1;
}
if !roles.is_empty() {
field_count += 1;
}
let mut map: S::SerializeMap = serializer.serialize_map(Some(field_count))?;
map.serialize_entry(CLAIM_SUB, sub)?;
if let Some(val) = iss {
map.serialize_entry(CLAIM_ISS, val)?;
}
if let Some(val) = aud {
map.serialize_entry(CLAIM_AUD, val)?;
}
if let Some(val) = exp {
map.serialize_entry(CLAIM_EXP, val)?;
}
if let Some(val) = nbf {
map.serialize_entry(CLAIM_NBF, val)?;
}
if let Some(val) = iat {
map.serialize_entry(CLAIM_IAT, val)?;
}
if let Some(val) = jti {
map.serialize_entry(CLAIM_JTI, val)?;
}
if !roles.is_empty() {
map.serialize_entry(CLAIM_ROLES, roles)?;
}
for (k, v) in extra {
map.serialize_entry(k, v)?;
}
map.end()
}
}
impl<'de> Visitor<'de> for JwtClaimFieldVisitor {
type Value = JwtClaimField;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(EXPECTING_JWT_FIELD)
}
#[inline]
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(match value {
CLAIM_SUB => JwtClaimField::Sub,
CLAIM_ISS => JwtClaimField::Iss,
CLAIM_AUD => JwtClaimField::Aud,
CLAIM_EXP => JwtClaimField::Exp,
CLAIM_NBF => JwtClaimField::Nbf,
CLAIM_IAT => JwtClaimField::Iat,
CLAIM_JTI => JwtClaimField::Jti,
CLAIM_ROLES => JwtClaimField::Roles,
_ => JwtClaimField::Extra(value.to_owned()),
})
}
#[inline]
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(match value.as_str() {
CLAIM_SUB => JwtClaimField::Sub,
CLAIM_ISS => JwtClaimField::Iss,
CLAIM_AUD => JwtClaimField::Aud,
CLAIM_EXP => JwtClaimField::Exp,
CLAIM_NBF => JwtClaimField::Nbf,
CLAIM_IAT => JwtClaimField::Iat,
CLAIM_JTI => JwtClaimField::Jti,
CLAIM_ROLES => JwtClaimField::Roles,
_ => JwtClaimField::Extra(value),
})
}
}
impl<'de> Deserialize<'de> for JwtClaimField {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_identifier(JwtClaimFieldVisitor)
}
}
impl<'de> Visitor<'de> for JwtClaimsVisitor {
type Value = JwtClaims;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(EXPECTING_JWT_CLAIMS)
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut seen: u8 = 0;
let mut sub: Option<String> = None;
let mut iss: Option<String> = None;
let mut aud: Option<String> = None;
let mut exp: Option<u64> = None;
let mut nbf: Option<u64> = None;
let mut iat: Option<u64> = None;
let mut jti: Option<String> = None;
let mut roles: Option<Vec<String>> = None;
let mut extra: HashMap<String, Value> = HashMap::new();
while let Some(field) = map.next_key::<JwtClaimField>()? {
match field {
JwtClaimField::Sub => {
if (seen & CLAIM_BIT_SUB) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_SUB));
}
seen |= CLAIM_BIT_SUB;
sub = Some(map.next_value()?);
}
JwtClaimField::Iss => {
if (seen & CLAIM_BIT_ISS) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_ISS));
}
seen |= CLAIM_BIT_ISS;
iss = map.next_value()?;
}
JwtClaimField::Aud => {
if (seen & CLAIM_BIT_AUD) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_AUD));
}
seen |= CLAIM_BIT_AUD;
aud = map.next_value()?;
}
JwtClaimField::Exp => {
if (seen & CLAIM_BIT_EXP) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_EXP));
}
seen |= CLAIM_BIT_EXP;
exp = map.next_value()?;
}
JwtClaimField::Nbf => {
if (seen & CLAIM_BIT_NBF) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_NBF));
}
seen |= CLAIM_BIT_NBF;
nbf = map.next_value()?;
}
JwtClaimField::Iat => {
if (seen & CLAIM_BIT_IAT) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_IAT));
}
seen |= CLAIM_BIT_IAT;
iat = map.next_value()?;
}
JwtClaimField::Jti => {
if (seen & CLAIM_BIT_JTI) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_JTI));
}
seen |= CLAIM_BIT_JTI;
jti = map.next_value()?;
}
JwtClaimField::Roles => {
if (seen & CLAIM_BIT_ROLES) != 0 {
return Err(<A::Error as de::Error>::duplicate_field(CLAIM_ROLES));
}
seen |= CLAIM_BIT_ROLES;
roles = Some(map.next_value()?);
}
JwtClaimField::Extra(key) => {
let value: Value = map.next_value()?;
extra.insert(key, value);
}
}
}
let sub: String = sub.ok_or_else(|| <A::Error as de::Error>::missing_field(CLAIM_SUB))?;
Ok(JwtClaims {
sub,
iss,
aud,
exp,
nbf,
iat,
jti,
roles: roles.unwrap_or_default(),
extra,
})
}
}
impl<'de> Deserialize<'de> for JwtClaims {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(JwtClaimsVisitor)
}
}
impl JwtClaims {
pub fn new<S>(subject: S, ttl_secs: u64) -> Self
where
S: Into<String>,
{
let now: u64 = auth_now_secs();
Self {
sub: subject.into(),
iss: None,
aud: None,
exp: Some(now.saturating_add(ttl_secs)),
nbf: Some(now),
iat: Some(now),
jti: None,
roles: Vec::new(),
extra: HashMap::new(),
}
}
pub fn with_roles<I, S>(mut self, roles: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_roles(roles.into_iter().map(Into::into).collect());
self
}
pub fn with_issuer<S>(mut self, issuer: S) -> Self
where
S: Into<String>,
{
self.set_iss(Some(issuer.into()));
self
}
pub fn with_audience<S>(mut self, audience: S) -> Self
where
S: Into<String>,
{
self.set_aud(Some(audience.into()));
self
}
}
impl JwtCodec {
pub fn new<S>(secret: S) -> Self
where
S: Into<Vec<u8>>,
{
let default_secret: Vec<u8> = secret.into();
let default_hmac: HmacSha256Key = HmacSha256Key::new(&default_secret);
Self {
default_secret,
default_hmac,
default_kid: None,
default_header_b64: DEFAULT_HS256_HEADER_B64.to_owned(),
keyring: hash_map_xx_hash3_64(),
keyring_hmac: hash_map_xx_hash3_64(),
leeway_secs: DEFAULT_JWT_LEEWAY_SECS,
required_issuer: None,
required_audience: None,
}
}
pub fn with_key<K, S>(mut self, kid: K, secret: S) -> Self
where
K: Into<String>,
S: Into<Vec<u8>>,
{
let Self {
keyring,
keyring_hmac,
..
} = &mut self;
let kid_str: String = kid.into();
let secret_bytes: Vec<u8> = secret.into();
let precomputed: HmacSha256Key = HmacSha256Key::new(&secret_bytes);
keyring.insert(kid_str.clone(), secret_bytes);
keyring_hmac.insert(kid_str, precomputed);
self
}
pub fn with_default_kid<K>(mut self, kid: K) -> Self
where
K: Into<String>,
{
let Self {
default_kid,
default_secret,
default_hmac,
default_header_b64,
keyring,
keyring_hmac,
..
} = &mut self;
let kid_str: String = kid.into();
if !keyring.contains_key(&kid_str) {
keyring.insert(kid_str.clone(), default_secret.clone());
keyring_hmac.insert(kid_str.clone(), *default_hmac);
}
*default_header_b64 = encode_hs256_header_b64(Some(&kid_str));
*default_kid = Some(kid_str);
self
}
pub fn with_leeway_secs(mut self, leeway_secs: u64) -> Self {
let Self {
leeway_secs: slot, ..
} = &mut self;
*slot = leeway_secs;
self
}
pub fn with_required_issuer<S>(mut self, issuer: S) -> Self
where
S: Into<String>,
{
let Self {
required_issuer, ..
} = &mut self;
*required_issuer = Some(issuer.into());
self
}
pub fn with_required_audience<S>(mut self, audience: S) -> Self
where
S: Into<String>,
{
let Self {
required_audience, ..
} = &mut self;
*required_audience = Some(audience.into());
self
}
pub fn encode(&self, claims: &JwtClaims) -> Result<String, AuthError> {
let Self {
default_hmac,
default_kid,
default_header_b64,
keyring_hmac,
..
} = self;
let mut claims_buf: StackJsonBuf = StackJsonBuf::new();
write_jwt_claims_json(claims, &mut claims_buf)?;
let claims_json: &[u8] = claims_buf.as_slice();
let claims_b64_len: usize = (claims_json.len() * 4).div_ceil(3);
let total_len: usize = default_header_b64.len() + 1 + claims_b64_len + 1 + HMAC_SIG_B64_LEN;
let mut token_bytes: Vec<u8> = Vec::with_capacity(total_len);
token_bytes.extend_from_slice(default_header_b64.as_bytes());
token_bytes.push(ASCII_DOT);
base64url_encode_into(claims_json, &mut token_bytes);
let hmac_key: &HmacSha256Key = match default_kid {
Some(kid) => keyring_hmac.get(kid).unwrap_or(default_hmac),
None => default_hmac,
};
let mac: [u8; 32] = hmac_key.mac(&token_bytes);
token_bytes.push(ASCII_DOT);
base64url_encode_into(&mac, &mut token_bytes);
String::from_utf8(token_bytes).map_err(|_| AuthError::InvalidCredentials)
}
pub fn decode_at(&self, token: &str, now_secs: u64) -> Result<JwtClaims, AuthError> {
let Self {
default_hmac,
default_kid,
default_header_b64,
keyring_hmac,
leeway_secs,
required_issuer,
required_audience,
..
} = self;
let (header_b64, rest): (&str, &str) =
token.split_once('.').ok_or(AuthError::InvalidCredentials)?;
let (payload_b64, sig_b64): (&str, &str) =
rest.split_once('.').ok_or(AuthError::InvalidCredentials)?;
if sig_b64.contains('.')
|| header_b64.is_empty()
|| payload_b64.is_empty()
|| sig_b64.is_empty()
{
return Err(AuthError::InvalidCredentials);
}
let hmac_key: &HmacSha256Key = if header_b64 == default_header_b64.as_str() {
match default_kid {
Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
None => default_hmac,
}
} else if header_b64 == DEFAULT_HS256_HEADER_B64 {
default_hmac
} else {
let trimmed_hdr: &[u8] = header_b64.trim_end_matches('=').as_bytes();
let decoded_hdr_len: usize = (trimmed_hdr.len() * 3) / 4;
let mut hdr_stack: [u8; JWT_STACK_HEADER_CAP] = [0u8; JWT_STACK_HEADER_CAP];
let hdr_heap: Vec<u8>;
let hdr_slice: &[u8] = if decoded_hdr_len <= JWT_STACK_HEADER_CAP {
let written: usize =
decode_base64_into(trimmed_hdr, &BASE64URL_DECODE_TABLE, &mut hdr_stack)
.ok_or(AuthError::InvalidCredentials)?;
&hdr_stack[..written]
} else {
hdr_heap = base64url_decode(header_b64).ok_or(AuthError::InvalidCredentials)?;
&hdr_heap
};
let header: JwtHeaderRef<'_> =
from_slice(hdr_slice).map_err(|_| AuthError::InvalidCredentials)?;
if header.alg.as_ref() != JWT_ALG_HS256 {
return Err(AuthError::UnsupportedAlgorithm);
}
match header.kid.as_deref() {
Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
None => default_hmac,
}
};
let provided_sig: [u8; 32] =
decode_base64url_32(sig_b64).ok_or(AuthError::InvalidCredentials)?;
let signed_len: usize = header_b64.len() + 1 + payload_b64.len();
let expected_mac: [u8; 32] = hmac_key.mac(&token.as_bytes()[..signed_len]);
if !constant_time_eq(&provided_sig, &expected_mac) {
return Err(AuthError::InvalidCredentials);
}
let trimmed_payload: &[u8] = payload_b64.trim_end_matches('=').as_bytes();
let decoded_payload_len: usize = (trimmed_payload.len() * 3) / 4;
let claims: JwtClaims = if decoded_payload_len <= JWT_STACK_FAST_PAYLOAD_CAP {
let mut fast_stack: [u8; JWT_STACK_FAST_PAYLOAD_CAP] =
[0u8; JWT_STACK_FAST_PAYLOAD_CAP];
let written: usize =
decode_base64_into(trimmed_payload, &BASE64URL_DECODE_TABLE, &mut fast_stack)
.ok_or(AuthError::InvalidCredentials)?;
from_slice(&fast_stack[..written]).map_err(|_| AuthError::InvalidCredentials)?
} else if decoded_payload_len <= JWT_STACK_PAYLOAD_CAP {
let mut payload_stack: [u8; JWT_STACK_PAYLOAD_CAP] = [0u8; JWT_STACK_PAYLOAD_CAP];
let written: usize =
decode_base64_into(trimmed_payload, &BASE64URL_DECODE_TABLE, &mut payload_stack)
.ok_or(AuthError::InvalidCredentials)?;
from_slice(&payload_stack[..written]).map_err(|_| AuthError::InvalidCredentials)?
} else {
let payload_heap: Vec<u8> =
base64url_decode(payload_b64).ok_or(AuthError::InvalidCredentials)?;
from_slice(&payload_heap).map_err(|_| AuthError::InvalidCredentials)?
};
let JwtClaims {
iss, aud, exp, nbf, ..
} = &claims;
if let Some(exp_val) = *exp
&& now_secs > exp_val.saturating_add(*leeway_secs)
{
return Err(AuthError::TokenExpired);
}
if let Some(nbf_val) = *nbf
&& now_secs.saturating_add(*leeway_secs) < nbf_val
{
return Err(AuthError::TokenNotYetValid);
}
if let Some(expected_iss) = required_issuer
&& iss.as_deref() != Some(expected_iss.as_str())
{
return Err(AuthError::ClaimMismatch);
}
if let Some(expected_aud) = required_audience
&& aud.as_deref() != Some(expected_aud.as_str())
{
return Err(AuthError::ClaimMismatch);
}
Ok(claims)
}
pub fn decode(&self, token: &str) -> Result<JwtClaims, AuthError> {
self.decode_at(token, auth_now_secs())
}
}
impl AuthPrincipal {
#[inline]
pub fn has_role(&self, role: &str) -> bool {
self.get_roles().iter().any(|item: &String| item == role)
}
}
impl JwtAuthenticator {
pub fn new(codec: JwtCodec) -> Self {
Self { codec }
}
}
impl Authenticator for JwtAuthenticator {
fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
let Self { codec } = self;
Box::pin(async move {
match request_header_back(ctx.get_request(), AUTHORIZATION) {
None => Err(AuthError::MissingCredentials),
Some(header) => match strip_auth_scheme(header, PREFIX_BEARER) {
None => Err(AuthError::MissingCredentials),
Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
subject: claims.get_sub().clone(),
roles: claims.get_roles().clone(),
scheme: AuthScheme::BearerJwt,
claims: Some(claims),
}),
},
}
})
}
}
impl Default for ApiKeyAuthenticator {
fn default() -> Self {
Self::new(X_API_KEY)
}
}
impl ApiKeyAuthenticator {
pub fn new<H>(header_name: H) -> Self
where
H: Into<String>,
{
Self {
header_name: header_name.into().to_ascii_lowercase(),
entries: Vec::new(),
}
}
pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
where
K: Into<String>,
S: Into<String>,
I: IntoIterator<Item = R>,
R: Into<String>,
{
let Self { entries, .. } = &mut self;
entries.push((
api_key.into().into_bytes(),
subject.into(),
roles.into_iter().map(Into::into).collect(),
));
self
}
}
impl Authenticator for ApiKeyAuthenticator {
fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
let Self {
header_name,
entries,
} = self;
Box::pin(async move {
match request_header_back(ctx.get_request(), header_name) {
None => Err(AuthError::MissingCredentials),
Some(candidate) => {
let candidate_bytes: &[u8] = candidate.trim().as_bytes();
let mut matched_idx: Option<usize> = None;
for (idx, (secret, _, _)) in entries.iter().enumerate() {
if constant_time_eq(candidate_bytes, secret) {
matched_idx = Some(idx);
}
}
match matched_idx {
Some(idx) => {
let (_, subject, roles): &(Vec<u8>, String, Vec<String>) =
&entries[idx];
Ok(AuthPrincipal {
subject: subject.clone(),
roles: roles.clone(),
scheme: AuthScheme::ApiKey,
claims: None,
})
}
None => Err(AuthError::InvalidCredentials),
}
}
}
})
}
}
impl Default for BasicAuthenticator {
fn default() -> Self {
Self::new()
}
}
impl BasicAuthenticator {
pub fn new() -> Self {
Self {
users: hash_map_xx_hash3_64(),
}
}
pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
where
U: Into<String>,
P: Into<String>,
I: IntoIterator<Item = R>,
R: Into<String>,
{
let Self { users } = &mut self;
users.insert(
username.into(),
(
password.into().into_bytes(),
roles.into_iter().map(Into::into).collect(),
),
);
self
}
}
impl Authenticator for BasicAuthenticator {
fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
let Self { users } = self;
Box::pin(async move {
match request_header_back(ctx.get_request(), AUTHORIZATION) {
None => Err(AuthError::MissingCredentials),
Some(header) => match strip_auth_scheme(header, PREFIX_BASIC) {
None => Err(AuthError::MissingCredentials),
Some(encoded) => {
let trimmed_b64: &[u8] = encoded.trim_end_matches('=').as_bytes();
let decoded_len: usize = (trimmed_b64.len() * 3) / 4;
let mut stack_buf: [u8; BASIC_STACK_CAP] = [0u8; BASIC_STACK_CAP];
let heap_buf: Vec<u8>;
let raw_opt: Option<&[u8]> = if decoded_len <= BASIC_STACK_CAP {
decode_base64_into(
trimmed_b64,
&BASE64_STD_DECODE_TABLE,
&mut stack_buf,
)
.map(|written: usize| &stack_buf[..written])
} else if let Some(buf) = base64_decode(encoded) {
heap_buf = buf;
Some(heap_buf.as_slice())
} else {
None
};
match raw_opt.and_then(|raw: &[u8]| from_utf8(raw).ok()) {
None => Err(AuthError::InvalidCredentials),
Some(decoded) => match decoded.split_once(':') {
None => Err(AuthError::InvalidCredentials),
Some((user, pass)) => match users.get(user) {
Some((expected_pass, roles))
if constant_time_eq(pass.as_bytes(), expected_pass) =>
{
Ok(AuthPrincipal {
subject: user.to_owned(),
roles: roles.clone(),
scheme: AuthScheme::Basic,
claims: None,
})
}
_ => Err(AuthError::InvalidCredentials),
},
},
}
}
},
}
})
}
}
impl CompositeAuthenticator {
pub fn new(chain: Vec<Arc<dyn Authenticator>>) -> Self {
Self { chain }
}
}
impl Authenticator for CompositeAuthenticator {
fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
let Self { chain } = self;
Box::pin(async move {
let mut last_err: AuthError = AuthError::MissingCredentials;
for auth in chain {
match auth.authenticate(ctx).await {
Ok(principal) => return Ok(principal),
Err(AuthError::MissingCredentials) => {}
Err(err) => last_err = err,
}
}
Err(last_err)
})
}
}
impl Default for AuthConfig {
fn default() -> Self {
Self {
exempt_paths: Vec::new(),
required_roles: Vec::new(),
require_all_roles: false,
www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
}
}
}
impl AuthConfig {
pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
self
}
pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.set_required_roles(roles.into_iter().map(Into::into).collect());
self
}
}
impl AuthPlugin {
pub fn init(config: AuthConfig, authenticator: Arc<dyn Authenticator>) -> &'static Self {
AUTH_PLUGIN.get_or_init(|| {
let exempt_set: Option<HashSetXxHash3_64<String>> =
if config.get_exempt_paths().len() > EXEMPT_SET_THRESHOLD {
let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
for path in config.get_exempt_paths() {
set.insert(path.clone());
}
Some(set)
} else {
None
};
let mut resp_401: Response = Response::default();
resp_401
.set_status_code(HttpStatus::Unauthorized.code())
.set_header(WWW_AUTHENTICATE, config.get_www_authenticate())
.set_body(Vec::new());
let prebuilt_401_wire: Vec<u8> = resp_401.build();
let mut resp_403: Response = Response::default();
resp_403
.set_status_code(HttpStatus::Forbidden.code())
.set_body(Vec::new());
let prebuilt_403_wire: Vec<u8> = resp_403.build();
Self {
config,
authenticator,
exempt_set,
prebuilt_401_wire,
prebuilt_403_wire,
}
})
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
AUTH_PLUGIN.get()
}
#[inline(always)]
pub fn get_config(&self) -> &AuthConfig {
&self.config
}
#[inline(always)]
pub fn get_authenticator(&self) -> &Arc<dyn Authenticator> {
&self.authenticator
}
#[inline(always)]
pub(crate) fn is_exempt_path(&self, path: &str) -> bool {
let Self {
config, exempt_set, ..
} = self;
if let Some(set) = exempt_set {
return set.contains(path);
}
let exempt: &[String] = config.get_exempt_paths().as_slice();
if exempt.is_empty() {
return false;
}
exempt.iter().any(|item: &String| item.as_str() == path)
}
pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
}
pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
let required: &Vec<String> = self.get_config().get_required_roles();
if required.is_empty() {
return true;
}
if self.get_config().get_require_all_roles() {
required
.iter()
.all(|role: &String| principal.has_role(role))
} else {
required
.iter()
.any(|role: &String| principal.has_role(role))
}
}
}
impl ServerHook for AuthHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = AuthPlugin::get() else {
return Status::Continue;
};
let path: &str = ctx.get_request().get_path();
if plugin.is_exempt_path(path) {
return Status::Continue;
}
match plugin.get_authenticator().authenticate(ctx).await {
Ok(principal) => {
if !plugin.is_authorized(&principal) {
let _: Result<(), ResponseError> =
stream.try_send(&plugin.prebuilt_403_wire).await;
return Status::Reject;
}
ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
Status::Continue
}
Err(AuthError::Forbidden) => {
let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_403_wire).await;
Status::Reject
}
Err(_) => {
let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_401_wire).await;
Status::Reject
}
}
}
}