use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use crate::context::Context;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::Response;
pub struct BasicAuth {
name: String,
password: String,
realm: String,
}
impl BasicAuth {
pub fn new(name: impl Into<String>, password: impl Into<String>) -> Self {
let password = password.into();
assert!(!password.is_empty(), "BasicAuth needs a password");
Self {
name: name.into(),
password,
realm: "Application".to_owned(),
}
}
pub fn from_config(section: &str) -> Self {
let config = crate::config::Config::current().ok();
let name = config
.as_ref()
.and_then(|c| {
c.get_opt::<String>(&format!("{section}.username"))
.ok()
.flatten()
})
.unwrap_or_else(|| section.to_owned());
let env_var = format!("{}_PASSWORD", section.to_ascii_uppercase());
let password = config
.as_ref()
.and_then(|c| {
c.secret(&format!("{section}.password"), &env_var)
.ok()
.flatten()
})
.unwrap_or_default();
if password.is_empty() {
tracing::error!(
section,
"BasicAuth has no password ({section}.password or {env_var}); refusing every request"
);
}
Self {
name,
password,
realm: "Application".to_owned(),
}
}
#[must_use]
pub fn realm(mut self, realm: impl Into<String>) -> Self {
self.realm = realm.into().replace('"', "");
self
}
fn allows(&self, header: Option<&str>) -> bool {
if self.password.is_empty() {
return false;
}
let Some(encoded) = header.and_then(|h| {
h.strip_prefix("Basic ")
.or_else(|| h.strip_prefix("basic "))
}) else {
return false;
};
let Ok(decoded) = STANDARD.decode(encoded.trim()) else {
return false;
};
let Ok(decoded) = String::from_utf8(decoded) else {
return false;
};
let Some((name, password)) = decoded.split_once(':') else {
return false;
};
let name_ok = constant_time_eq(name.as_bytes(), self.name.as_bytes());
let password_ok = constant_time_eq(password.as_bytes(), self.password.as_bytes());
name_ok & password_ok
}
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
impl Middleware for BasicAuth {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
if self.allows(ctx.header(http::header::AUTHORIZATION)) {
return Box::pin(next.run(ctx));
}
let challenge = format!("Basic realm=\"{}\", charset=\"UTF-8\"", self.realm);
Box::pin(async move {
Response::text("HTTP Basic: Access denied.\n")
.with_status(http::StatusCode::UNAUTHORIZED)
.with_header(http::header::WWW_AUTHENTICATE, challenge)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn header(credentials: &str) -> String {
format!("Basic {}", STANDARD.encode(credentials))
}
#[test]
fn checks_the_name_and_password() {
let auth = BasicAuth::new("admin", "s3cret");
assert!(auth.allows(Some(&header("admin:s3cret"))));
assert!(!auth.allows(Some(&header("admin:wrong"))));
assert!(!auth.allows(Some(&header("someone:s3cret"))));
assert!(!auth.allows(Some("Basic not-base64!")));
assert!(!auth.allows(Some("Bearer abc")));
assert!(!auth.allows(None));
assert!(BasicAuth::new("a", "b:c").allows(Some(&header("a:b:c"))));
}
}