From 9328451a25e15164c4d45286f24cf75b5163ff7d Mon Sep 17 00:00:00 2001 From: Fergus Molloy Date: Thu, 24 Jul 2025 17:32:50 +0100 Subject: [PATCH] swap to nextest --- backend/scripts/test.sh | 2 +- backend/src/router.rs | 36 +++++++++++++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/backend/scripts/test.sh b/backend/scripts/test.sh index 303a4bd..ca15478 100755 --- a/backend/scripts/test.sh +++ b/backend/scripts/test.sh @@ -11,4 +11,4 @@ curl -s -X POST localhost:7001/admin/shutdown 2>&1 > /dev/null cargo run --features shutdown -- --port 7001 2>&1 > logs/nuchat.log & # run tests -cargo test | tee logs/test-output.log +cargo nextest run 2>&1 | tee logs/test-output.log diff --git a/backend/src/router.rs b/backend/src/router.rs index d754fe6..6c83bcf 100644 --- a/backend/src/router.rs +++ b/backend/src/router.rs @@ -12,7 +12,7 @@ use http::StatusCode; use tower::ServiceBuilder; use tower_http::timeout::TimeoutLayer; use tower_http::trace::TraceLayer; -use tracing::Level; +use tracing::{Level, warn}; use uuid::Uuid; pub fn app() -> (Router, mpsc::Receiver) { @@ -42,15 +42,22 @@ pub fn app() -> (Router, mpsc::Receiver) { } fn admin(tx: mpsc::Sender) -> Router { - let r = Router::new().route("/test", get(async || StatusCode::OK)); + let r = Router::new().route("/", get(async || StatusCode::OK)); let r = add_shutdown_endpoint(r, tx); r.layer(from_fn(async |req: Request, next: Next| { if let Ok(secret) = std::env::var("ADMIN_SECRET") { - println!("ADMIN_SECRET: {secret}"); match req.headers().get("Authorization") { Some(key) if secret == *key => (), + Some(key) => { + warn!("Unauthorized request with key: {key:?}"); + return Response::builder() + .status(StatusCode::UNAUTHORIZED) + .body(Body::empty()) + .unwrap(); + } _ => { + warn!("Unauthorized request no key given"); return Response::builder() .status(StatusCode::UNAUTHORIZED) .body(Body::empty()) @@ -82,3 +89,26 @@ fn add_shutdown_endpoint(r: Router, tx: mpsc::Sender) -> Router { fn add_shutdown_endpoint(r: Router, _: mpsc::Sender) -> Router { r } + +#[cfg(test)] +mod tests { + use super::*; + use tower::{self, ServiceExt}; + + #[tokio::test] + async fn test_authorization_disables_when_no_env_var_set() { + let (app, _) = app(); + + let resp = app + .oneshot( + axum::http::Request::builder() + .uri("/admin") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::OK); + } +}