use std::sync::Arc;
use axum::extract::{Request, State};
use axum::http::{HeaderMap, Method, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
const OPEN_PATHS: [&str; 2] = ["/health", "/v1/status"];
pub async fn require_token(State(token): State<Arc<str>>, req: Request, next: Next) -> Response {
let open = matches!(*req.method(), Method::GET | Method::HEAD)
&& OPEN_PATHS.contains(&req.uri().path());
if open || presented(req.headers()).is_some_and(|t| tokens_match(t, token.as_bytes())) {
return next.run(req).await;
}
(
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
"missing or wrong API token",
)
.into_response()
}
fn presented(headers: &HeaderMap) -> Option<&[u8]> {
headers
.get(header::AUTHORIZATION)?
.as_bytes()
.strip_prefix(b"Bearer ")
}
fn tokens_match(given: &[u8], expected: &[u8]) -> bool {
given.len() == expected.len()
&& given
.iter()
.zip(expected)
.fold(0u8, |diff, (a, b)| diff | (a ^ b))
== 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equal_tokens_match() {
assert!(tokens_match(b"abc123", b"abc123"));
}
#[test]
fn different_tokens_do_not_match() {
assert!(!tokens_match(b"abc124", b"abc123"));
assert!(!tokens_match(b"abc12", b"abc123"));
assert!(!tokens_match(b"", b"abc123"));
assert!(!tokens_match(b"abc1234", b"abc123"));
}
}