fix(backend): P1 — handler unwrap cleanup + rewrite integration tests
P1 items #6 (JWT expiry) and #7 (refresh/logout routes) were already delivered in the P0 pass. This commit covers the two remaining P1 items: #9 — Replace dangerous handler-level .unwrap() calls (13 sites): * handlers/users.rs: 5x ObjectId::parse_str(&claims.sub).unwrap() in get_profile/update_profile/delete_account/get_settings/update_settings now return 401 on a malformed subject instead of panicking (matches the guard already used in change_password). * handlers/auth.rs: the login user.id.ok_or_else(..).unwrap() was a latent panic bug — the crafted 500 response was discarded. Now returns the clean 500 via match. * handlers/health_stats.rs: 6x state.health_stats_repo.as_ref().unwrap() now return 503 SERVICE_UNAVAILABLE if the feature is unconfigured, mirroring the interactions.rs pattern. * Left untouched: 14 test/boot-time unwraps and 7 infallible ones (header literal parsing, infallible TryFrom). The 3 borderline model-layer inserted_id unwraps are flagged for later. #8 — Rewrite the broken integration tests against a real test DB: * Split the crate into bin+lib: new src/lib.rs + src/app.rs (build_app), with main.rs now a thin entrypoint. Tests build the exact production router in-process instead of hitting a live server on a hardcoded port. * tests/common/mod.rs: helpers that connect to Mongo, build a fresh AppState against a unique per-process DB (normogen_test_<uuid>), and tear it down. A 1s connectivity probe makes tests skip gracefully when Mongo is absent, so 'cargo test' stays green without Mongo — CI runs them for real. * Rewrote tests/auth_tests.rs and tests/medication_tests.rs with the ACTUAL API contracts (POST /register {email,username,password}; response has token + refresh_token, not access_token; register returns 201). Covers register, login (right/wrong password), auth enforcement, refresh rotation + reuse detection, logout, and password-change invalidating old tokens. * Added a 'test' CI job with a mongo:7 service container running cargo test --all-targets. * Synced scripts/test-ci-locally.sh: fixed the stale -D warnings (CI is non-strict) and the reverted 'Docker Buildx' claims; added unit + integration test steps with a Mongo skip note. Verified: cargo fmt --check clean, build + clippy --all-targets clean. Full 'cargo test': 18 unit + 9 auth + 4 medication = 31 passed, 0 failed (integration tests skip cleanly when MongoDB is unreachable).
This commit is contained in:
parent
7ba78a31fb
commit
bd1b7c2925
13 changed files with 937 additions and 338 deletions
|
|
@ -1,163 +1,309 @@
|
|||
use reqwest::Client;
|
||||
//! Auth-flow integration tests.
|
||||
//!
|
||||
//! These build the full app in process (via `common::app_for_test`) against an
|
||||
//! isolated MongoDB test database, so they exercise the real router, middleware,
|
||||
//! and handlers. They require a live MongoDB; if one isn't reachable the helper
|
||||
//! returns `None` and every test skips gracefully (see `skip_if_none`).
|
||||
//!
|
||||
//! Contracts verified here reflect the *actual* API (post P0):
|
||||
//! POST /api/auth/register {email, username, password} -> 201 {token, refresh_token, ...}
|
||||
//! POST /api/auth/login {email, password} -> 200 {token, refresh_token, ...}
|
||||
//! POST /api/auth/refresh {refresh_token} -> 200 {token, refresh_token}
|
||||
//! POST /api/auth/logout {refresh_token} -> 204
|
||||
|
||||
mod common;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const BASE_URL: &str = "http://127.0.0.1:8000";
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_health_check() {
|
||||
let client = Client::new();
|
||||
let response = client
|
||||
.get(format!("{}/health", BASE_URL))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
||||
assert_eq!(response.status(), 200);
|
||||
/// When Mongo is unavailable the helper returns `None`; each test bails out
|
||||
/// early (counts as a pass) so `cargo test` stays green without Mongo. CI
|
||||
/// provides Mongo and runs them for real.
|
||||
macro_rules! require_app {
|
||||
($app:expr) => {
|
||||
match $app {
|
||||
Some(x) => x,
|
||||
None => {
|
||||
eprintln!("[integration] skipped (MongoDB unavailable)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ready_check() {
|
||||
let client = Client::new();
|
||||
let response = client
|
||||
.get(format!("{}/ready", BASE_URL))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
async fn health_and_ready() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
|
||||
assert_eq!(response.status(), 200);
|
||||
let (status, _) = common::send_json(&app, "GET", "/ready", None, None).await;
|
||||
assert_eq!(status, 200);
|
||||
|
||||
let (status, body) = common::send_json(&app, "GET", "/health", None, None).await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body["status"], "ok");
|
||||
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_register_user() {
|
||||
let client = Client::new();
|
||||
let email = format!("test_{}@example.com", uuid::Uuid::new_v4());
|
||||
async fn register_returns_token_and_refresh_token() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
let email = unique_email();
|
||||
|
||||
let payload = json!({
|
||||
"email": email,
|
||||
"password_hash": "hashed_password_placeholder",
|
||||
"encrypted_recovery_phrase": "encrypted_phrase_placeholder",
|
||||
"recovery_phrase_iv": "iv_placeholder",
|
||||
"recovery_phrase_auth_tag": "auth_tag_placeholder"
|
||||
});
|
||||
// Correct contract: { email, username, password } (NOT password_hash).
|
||||
let (status, body) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/register",
|
||||
Some(json!({ "email": email, "username": "tester", "password": "supersecret" })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 201, "register should return 201, body: {body}");
|
||||
assert!(body["token"].is_string(), "missing access token: {body}");
|
||||
assert!(
|
||||
body["refresh_token"].is_string(),
|
||||
"missing refresh token: {body}"
|
||||
);
|
||||
assert_eq!(body["email"], email);
|
||||
|
||||
let response = client
|
||||
.post(format!("{}/api/auth/register", BASE_URL))
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
||||
assert_eq!(response.status(), 200);
|
||||
|
||||
let json: Value = response.json().await.expect("Failed to parse JSON");
|
||||
assert_eq!(json["email"], email);
|
||||
assert!(json["user_id"].is_string());
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_login() {
|
||||
let client = Client::new();
|
||||
let email = format!("test_{}@example.com", uuid::Uuid::new_v4());
|
||||
async fn login_with_correct_password() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
let email = unique_email();
|
||||
|
||||
// First register a user
|
||||
let register_payload = json!({
|
||||
"email": email,
|
||||
"password_hash": "hashed_password_placeholder",
|
||||
"encrypted_recovery_phrase": "encrypted_phrase_placeholder",
|
||||
"recovery_phrase_iv": "iv_placeholder",
|
||||
"recovery_phrase_auth_tag": "auth_tag_placeholder"
|
||||
});
|
||||
register(&app, &email, "supersecret").await;
|
||||
|
||||
let _reg_response = client
|
||||
.post(format!("{}/api/auth/register", BASE_URL))
|
||||
.json(®ister_payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
// Correct contract: { email, password }.
|
||||
let (status, body) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/login",
|
||||
Some(json!({ "email": email, "password": "supersecret" })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "login should succeed, body: {body}");
|
||||
assert!(body["token"].is_string());
|
||||
assert!(body["refresh_token"].is_string());
|
||||
|
||||
// Now login
|
||||
let login_payload = json!({
|
||||
"email": email,
|
||||
"password_hash": "hashed_password_placeholder"
|
||||
});
|
||||
|
||||
let response = client
|
||||
.post(format!("{}/api/auth/login", BASE_URL))
|
||||
.json(&login_payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
||||
assert_eq!(response.status(), 200);
|
||||
|
||||
let json: Value = response.json().await.expect("Failed to parse JSON");
|
||||
assert!(json["access_token"].is_string());
|
||||
assert!(json["refresh_token"].is_string());
|
||||
assert_eq!(json["email"], email);
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_profile_without_auth() {
|
||||
let client = Client::new();
|
||||
async fn login_with_wrong_password_is_rejected() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
let email = unique_email();
|
||||
register(&app, &email, "supersecret").await;
|
||||
|
||||
let response = client
|
||||
.get(format!("{}/api/users/me", BASE_URL))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
let (status, body) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/login",
|
||||
Some(json!({ "email": email, "password": "wrong-password" })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 401, "wrong password should 401, body: {body}");
|
||||
|
||||
// Should return 401 Unauthorized without auth token
|
||||
assert_eq!(response.status(), 401);
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_profile_with_auth() {
|
||||
let client = Client::new();
|
||||
let email = format!("test_{}@example.com", uuid::Uuid::new_v4());
|
||||
async fn protected_route_rejects_missing_token() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
|
||||
// Register and login
|
||||
let register_payload = json!({
|
||||
"email": email,
|
||||
"password_hash": "hashed_password_placeholder",
|
||||
"encrypted_recovery_phrase": "encrypted_phrase_placeholder",
|
||||
"recovery_phrase_iv": "iv_placeholder",
|
||||
"recovery_phrase_auth_tag": "auth_tag_placeholder"
|
||||
});
|
||||
let (status, _) = common::send_json(&app, "GET", "/api/users/me", None, None).await;
|
||||
assert_eq!(status, 401);
|
||||
|
||||
client
|
||||
.post(format!("{}/api/auth/register", BASE_URL))
|
||||
.json(®ister_payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
||||
let login_payload = json!({
|
||||
"email": email,
|
||||
"password_hash": "hashed_password_placeholder"
|
||||
});
|
||||
|
||||
let login_response = client
|
||||
.post(format!("{}/api/auth/login", BASE_URL))
|
||||
.json(&login_payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
||||
let login_json: Value = login_response.json().await.expect("Failed to parse JSON");
|
||||
let access_token = login_json["access_token"]
|
||||
.as_str()
|
||||
.expect("No access token");
|
||||
|
||||
// Get profile with auth token
|
||||
let response = client
|
||||
.get(format!("{}/api/users/me", BASE_URL))
|
||||
.header("Authorization", format!("Bearer {}", access_token))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
||||
assert_eq!(response.status(), 200);
|
||||
|
||||
let json: Value = response.json().await.expect("Failed to parse JSON");
|
||||
assert_eq!(json["email"], email);
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn protected_route_accepts_valid_token() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
let email = unique_email();
|
||||
|
||||
let token = register(&app, &email, "supersecret").await;
|
||||
|
||||
let (status, body) = common::send_json(&app, "GET", "/api/users/me", None, Some(&token)).await;
|
||||
assert_eq!(status, 200, "profile fetch should succeed, body: {body}");
|
||||
assert_eq!(body["email"], email);
|
||||
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_rotates_and_revokes_old_token() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
let email = unique_email();
|
||||
|
||||
let _token = register(&app, &email, "supersecret").await;
|
||||
let (_, body) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/login",
|
||||
Some(json!({ "email": email, "password": "supersecret" })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let refresh_token = body["refresh_token"].as_str().unwrap().to_string();
|
||||
|
||||
// Rotate: exchange the refresh token for a new pair.
|
||||
let (status, new_body) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/refresh",
|
||||
Some(json!({ "refresh_token": refresh_token })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "refresh should succeed, body: {new_body}");
|
||||
assert!(new_body["token"].is_string());
|
||||
assert!(new_body["refresh_token"].is_string());
|
||||
assert_ne!(
|
||||
new_body["refresh_token"].as_str().unwrap(),
|
||||
refresh_token,
|
||||
"rotation must issue a new refresh token"
|
||||
);
|
||||
|
||||
// The old refresh token must now be revoked (reuse detection).
|
||||
let (status, _) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/refresh",
|
||||
Some(json!({ "refresh_token": refresh_token })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 401, "reused refresh token must be rejected");
|
||||
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn logout_revokes_refresh_token() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
let email = unique_email();
|
||||
|
||||
register(&app, &email, "supersecret").await;
|
||||
let (_, body) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/login",
|
||||
Some(json!({ "email": email, "password": "supersecret" })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let refresh_token = body["refresh_token"].as_str().unwrap().to_string();
|
||||
|
||||
// Logout revokes the refresh token.
|
||||
let (status, _) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/logout",
|
||||
Some(json!({ "refresh_token": refresh_token })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 204);
|
||||
|
||||
// The logged-out refresh token can no longer mint new tokens.
|
||||
let (status, _) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/refresh",
|
||||
Some(json!({ "refresh_token": refresh_token })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 401);
|
||||
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn password_change_invalidates_existing_tokens() {
|
||||
let (app, db_name) = require_app!(common::app_for_test().await);
|
||||
let email = unique_email();
|
||||
|
||||
let access_token = register(&app, &email, "supersecret").await;
|
||||
let (_, body) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/login",
|
||||
Some(json!({ "email": email, "password": "supersecret" })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let refresh_token = body["refresh_token"].as_str().unwrap().to_string();
|
||||
|
||||
// Change the password (protected route).
|
||||
let (status, _) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/users/me/change-password",
|
||||
Some(json!({ "current_password": "supersecret", "new_password": "newsupersecret" })),
|
||||
Some(&access_token),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 204);
|
||||
|
||||
// Old access token rejected within the token_version cache TTL.
|
||||
let (status, _) =
|
||||
common::send_json(&app, "GET", "/api/users/me", None, Some(&access_token)).await;
|
||||
assert_eq!(
|
||||
status, 401,
|
||||
"old access token must be rejected after password change"
|
||||
);
|
||||
|
||||
// Old refresh token revoked.
|
||||
let (status, _) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/refresh",
|
||||
Some(json!({ "refresh_token": refresh_token })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
status, 401,
|
||||
"old refresh token must be rejected after password change"
|
||||
);
|
||||
|
||||
// New password works.
|
||||
let (status, _) = common::send_json(
|
||||
&app,
|
||||
"POST",
|
||||
"/api/auth/login",
|
||||
Some(json!({ "email": email, "password": "newsupersecret" })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200);
|
||||
|
||||
common::drop_test_db(&db_name).await;
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
fn unique_email() -> String {
|
||||
format!("test_{}@example.com", uuid::Uuid::new_v4())
|
||||
}
|
||||
|
||||
/// Register a user and return the access token.
|
||||
async fn register(app: &axum::Router, email: &str, password: &str) -> String {
|
||||
let (status, body) = common::send_json(
|
||||
app,
|
||||
"POST",
|
||||
"/api/auth/register",
|
||||
Some(json!({ "email": email, "username": "tester", "password": password })),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 201, "register precondition failed, body: {body}");
|
||||
let _: &Value = &body;
|
||||
body["token"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue