second-brain-api 0.13.5

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
mod common;

use axum::body::Body;
use axum::http::{HeaderValue, Method, Request, StatusCode, header};
use tower::ServiceExt;

use common::{delete, get, json_body, post_json, state};

const TOKEN: &str = "5f1d0c3a9b7e42d68a0f1e2d3c4b5a69";

fn app() -> axum::Router {
    second_brain_api::app(state(), TOKEN.to_string())
}

fn bearer(mut req: Request<Body>, value: &str) -> Request<Body> {
    req.headers_mut()
        .insert(header::AUTHORIZATION, HeaderValue::from_str(value).unwrap());
    req
}

fn protected_requests() -> Vec<Request<Body>> {
    vec![
        post_json("/v1/remember", serde_json::json!({"content": "x"})),
        post_json("/v1/recall", serde_json::json!({"query": "x"})),
        get("/v1/memory/00000000-0000-0000-0000-000000000000"),
        delete("/v1/memory/00000000-0000-0000-0000-000000000000"),
        get("/v1/health"),
        post_json("/v1/status", serde_json::json!({})),
        post_json("/health", serde_json::json!({})),
        get("/health/"),
        get("/v1/status/"),
        get("//health"),
    ]
}

#[tokio::test]
async fn protected_routes_reject_a_missing_token() {
    for req in protected_requests() {
        let uri = req.uri().clone();
        let response = app().oneshot(req).await.unwrap();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{uri}");
        assert_eq!(response.headers()[header::WWW_AUTHENTICATE], "Bearer");
    }
}

#[tokio::test]
async fn protected_routes_reject_a_wrong_token() {
    let wrong = [
        "Bearer 5f1d0c3a9b7e42d68a0f1e2d3c4b5a60".to_string(),
        "Bearer 5f1d0c3a".to_string(),
        format!("Bearer {TOKEN}x"),
        format!("Basic {TOKEN}"),
        TOKEN.to_string(),
        "Bearer ".to_string(),
    ];
    for value in wrong {
        for req in protected_requests() {
            let uri = req.uri().clone();
            let response = app().oneshot(bearer(req, &value)).await.unwrap();
            assert_eq!(
                response.status(),
                StatusCode::UNAUTHORIZED,
                "{uri} with {value:?}"
            );
        }
    }
}

#[tokio::test]
async fn the_right_token_reaches_the_route() {
    let app = app();
    let response = app
        .clone()
        .oneshot(bearer(
            post_json("/v1/remember", serde_json::json!({"content": "authed"})),
            &format!("Bearer {TOKEN}"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let id = json_body(response).await["id"]
        .as_str()
        .unwrap()
        .to_string();

    let response = app
        .oneshot(bearer(
            get(&format!("/v1/memory/{id}")),
            &format!("Bearer {TOKEN}"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(json_body(response).await["content"], "authed");
}

#[tokio::test]
async fn health_and_status_stay_open() {
    for method in [Method::GET, Method::HEAD] {
        for uri in ["/health", "/v1/status"] {
            let req = Request::builder()
                .method(method.clone())
                .uri(uri)
                .body(Body::empty())
                .unwrap();
            let response = app().oneshot(req).await.unwrap();
            assert_eq!(response.status(), StatusCode::OK, "{method} {uri}");
        }
    }
}

#[tokio::test]
async fn cross_origin_requests_get_no_cors_headers() {
    let preflight = Request::builder()
        .method(Method::OPTIONS)
        .uri("/v1/recall")
        .header(header::ORIGIN, "https://evil.example")
        .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
        .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "authorization")
        .body(Body::empty())
        .unwrap();
    let mut simple = get("/health");
    simple.headers_mut().insert(
        header::ORIGIN,
        HeaderValue::from_static("https://evil.example"),
    );

    for req in [preflight, simple] {
        let response = app().oneshot(req).await.unwrap();
        let cors: Vec<_> = response
            .headers()
            .keys()
            .filter(|k| k.as_str().starts_with("access-control-"))
            .collect();
        assert!(cors.is_empty(), "{cors:?}");
    }
}