use std::fmt;
use axum::http::HeaderValue;
use thiserror::Error;
use crate::result::{ClassifyError, ErrorCode, ErrorKind};
#[derive(Clone, PartialEq, Eq)]
pub struct AuthenticationChallenge(HeaderValue);
impl AuthenticationChallenge {
pub fn try_new(value: &str) -> Result<Self, InvalidAuthenticationChallenge> {
if validate_challenge(value.as_bytes()).is_none() {
return Err(InvalidAuthenticationChallenge);
}
HeaderValue::from_str(value)
.map(Self)
.map_err(|_| InvalidAuthenticationChallenge)
}
#[must_use]
pub const fn as_header_value(&self) -> &HeaderValue {
&self.0
}
}
impl fmt::Debug for AuthenticationChallenge {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("AuthenticationChallenge([REDACTED])")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("invalid HTTP authentication challenge")]
pub struct InvalidAuthenticationChallenge;
impl ClassifyError for InvalidAuthenticationChallenge {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
ErrorCode::internal("invalid_authentication_challenge")
}
}
fn validate_challenge(value: &[u8]) -> Option<()> {
let value = value.trim_ascii();
let (_, rest) = take_token(value)?;
if rest.is_empty() {
return Some(());
}
let mut rest = rest.strip_prefix(b" ")?;
while let Some(tail) = rest.strip_prefix(b" ") {
rest = tail;
}
let end = rest
.iter()
.position(|byte| *byte == b'=')
.unwrap_or(rest.len());
if end > 0
&& rest[..end]
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || b"-._~+/".contains(byte))
&& rest[end..].iter().all(|byte| *byte == b'=')
{
return Some(());
}
let mut names: Vec<&[u8]> = Vec::new();
loop {
let (name, tail) = take_token(rest)?;
if names.iter().any(|other| other.eq_ignore_ascii_case(name)) {
return None;
}
names.push(name);
rest = tail
.trim_ascii_start()
.strip_prefix(b"=")?
.trim_ascii_start();
rest = if rest.starts_with(b"\"") {
after_quoted_string(rest)?
} else {
take_token(rest)?.1
};
rest = rest.trim_ascii_start();
if rest.is_empty() {
return Some(());
}
rest = rest.strip_prefix(b",")?.trim_ascii_start();
}
}
fn take_token(value: &[u8]) -> Option<(&[u8], &[u8])> {
let end = value
.iter()
.position(|byte| !byte.is_ascii_alphanumeric() && !b"!#$%&'*+-.^_`|~".contains(byte))
.unwrap_or(value.len());
(end > 0).then(|| value.split_at(end))
}
fn after_quoted_string(value: &[u8]) -> Option<&[u8]> {
let mut index = 1;
while let Some(&byte) = value.get(index) {
match byte {
b'"' => return Some(&value[index + 1..]),
b'\\' => {
index += 1;
if !matches!(value.get(index), Some(b'\t' | b' '..=b'~' | 0x80..=0xff)) {
return None;
}
}
b'\t' | b' ' | b'!' | b'#'..=b'[' | b']'..=b'~' | 0x80..=0xff => {}
_ => return None,
}
index += 1;
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_one_challenge_and_preserves_wire_value() {
for value in [
"Bearer",
"Bearer realm=\"api\"",
"Bearer realm = \"api\", scope=\"read write\"",
"Basic realm=\"api\", charset=\"UTF-8\"",
"Bearer realm=\"a,b\\\"c\", error=invalid_token",
"Negotiate YWJjZA==",
"Custom a=b, c=\"\", d = \"é\"",
] {
let challenge = AuthenticationChallenge::try_new(value).unwrap();
assert_eq!(challenge.as_header_value().as_bytes(), value.as_bytes());
}
}
#[test]
fn rejects_missing_scheme_injection_and_ambiguous_parameters() {
for value in [
"",
" ",
"realm=\"api\"",
"Bearer\trealm=\"api\"",
"Bearer \trealm=\"api\"",
"Bearer realm=\"unclosed",
"Bearer realm=\"a\" trailing",
"Bearer realm=\"a\", Realm=\"b\"",
"Basic realm=\"a\", Bearer",
"Bearer realm=\"a\",",
"Bearer realm=\"a\",,error=invalid_token",
"Bearer\r\nx-injected: true",
"Bearer realm=\"a\u{7f}b\"",
"Bearer realm=\"a\u{0}b\"",
"Bearer abc=def=ghi",
] {
assert_eq!(
AuthenticationChallenge::try_new(value),
Err(InvalidAuthenticationChallenge),
"{value:?}"
);
}
}
#[test]
fn diagnostics_do_not_expose_challenges() {
let challenge = AuthenticationChallenge::try_new("Bearer realm=\"private\"").unwrap();
assert!(!format!("{challenge:?}").contains("private"));
assert_eq!(
InvalidAuthenticationChallenge.error_kind(),
ErrorKind::Validation
);
}
}