Skip to main content

second_brain_api/
auth.rs

1use std::sync::Arc;
2
3use axum::extract::{Request, State};
4use axum::http::{HeaderMap, Method, StatusCode, header};
5use axum::middleware::Next;
6use axum::response::{IntoResponse, Response};
7
8const OPEN_PATHS: [&str; 2] = ["/health", "/v1/status"];
9
10pub async fn require_token(State(token): State<Arc<str>>, req: Request, next: Next) -> Response {
11    let open = matches!(*req.method(), Method::GET | Method::HEAD)
12        && OPEN_PATHS.contains(&req.uri().path());
13    if open || presented(req.headers()).is_some_and(|t| tokens_match(t, token.as_bytes())) {
14        return next.run(req).await;
15    }
16    (
17        StatusCode::UNAUTHORIZED,
18        [(header::WWW_AUTHENTICATE, "Bearer")],
19        "missing or wrong API token",
20    )
21        .into_response()
22}
23
24fn presented(headers: &HeaderMap) -> Option<&[u8]> {
25    headers
26        .get(header::AUTHORIZATION)?
27        .as_bytes()
28        .strip_prefix(b"Bearer ")
29}
30
31fn tokens_match(given: &[u8], expected: &[u8]) -> bool {
32    given.len() == expected.len()
33        && given
34            .iter()
35            .zip(expected)
36            .fold(0u8, |diff, (a, b)| diff | (a ^ b))
37            == 0
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn equal_tokens_match() {
46        assert!(tokens_match(b"abc123", b"abc123"));
47    }
48
49    #[test]
50    fn different_tokens_do_not_match() {
51        assert!(!tokens_match(b"abc124", b"abc123"));
52        assert!(!tokens_match(b"abc12", b"abc123"));
53        assert!(!tokens_match(b"", b"abc123"));
54        assert!(!tokens_match(b"abc1234", b"abc123"));
55    }
56}