Lines
100 %
Functions
94.74 %
Branches
use axum::response::IntoResponse;
use axum::{
Router,
body::Body,
http::{Request, StatusCode},
routing::{get, post},
};
use serde_json::json;
use tests_integration::tenant_guard::TestTenant;
use tower::ServiceExt;
use crate::common::{create_mock_jwt_auth, create_mock_user, create_test_app_state};
async fn body_of(response: axum::response::Response) -> String {
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.expect("response body");
String::from_utf8(bytes.to_vec()).expect("utf-8 body")
}
#[supp_macro::shared_runtime_test]
async fn test_login_handler_with_valid_json() {
let app_state = create_test_app_state().await;
let app = Router::new()
.route("/auth/login", post(web::login::login_user_handler))
.with_state(app_state);
let login_data = json!({
"email": "test@example.com",
"password": "password123"
});
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/auth/login")
.header("content-type", "application/json")
.body(Body::from(login_data.to_string()))
.unwrap(),
)
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
assert_eq!(
body_of(response).await,
r#"{"message":"Invalid email or password","status":"error"}"#
);
async fn test_login_handler_missing_content_type() {
assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert!(body_of(response).await.contains("application/json"));
async fn test_register_handler_missing_fields() {
.route("/auth/register", post(web::register::register_user_handler))
let register_data = json!({
"name": "Test User"
// Missing email and password
.uri("/auth/register")
.body(Body::from(register_data.to_string()))
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert!(body_of(response).await.contains("missing field `email`"));
async fn test_refresh_handler_without_cookie() {
.route(
"/auth/refresh",
get(web::session::refresh_access_token_handler),
// The route lives behind `auth` in production, which is what inserts
// this extension; without it axum rejects before the handler runs.
.layer(axum::Extension(create_mock_jwt_auth(create_mock_user())))
.method("GET")
.uri("/auth/refresh")
.body(Body::empty())
async fn test_refresh_handler_with_simple_invalid_cookie() {
.header("cookie", "refresh_token=invalid")
/// Registration must produce a *verified* user.
///
/// `jwt_auth` re-reads `users.verified` on every authenticated request and 401s
/// when it is false, and nothing in the codebase ever sets the flag — there is
/// no verification endpoint and no email flow. So an account created with the
/// column default authenticates once and is then unusable, which is exactly
/// what the first real registration hit on 2026-09-06. Registration is
/// admin-gated, so the admin creating the account has already vouched for it.
async fn test_register_handler_creates_a_verified_user() {
let email = format!(
"verified-probe-{}@example.com",
uuid::Uuid::new_v4().simple()
let _tenant = TestTenant::registered(email.clone());
.body(Body::from(
json!({ "name": "Verified Probe", "email": email, "password": "password123" })
.to_string(),
))
let mut conn = server::db::get_connection().await.expect("connection");
let verified: Option<bool> = sqlx::query_scalar("SELECT verified FROM users WHERE email = $1")
.bind(&email)
.fetch_optional(&mut *conn)
.expect("the directory lookup");
assert_eq!(response.status(), StatusCode::OK, "registration failed");
let verified = verified.expect("the registered row");
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
let fragment = String::from_utf8(body.to_vec()).expect("html body");
fragment,
format!(r#"<div class="success-alert">User {email} created</div>"#)
assert!(
verified,
"a registered user must be verified; an unverified one 401s on every request"
/// The A2 gate itself: `verify` compares the token's generation against the
/// directory. Nothing else covers that join — the server tests cover the bump,
/// the token tests cover the claim riding in the signature.
async fn test_password_change_stops_existing_tokens_verifying() {
let id = uuid::Uuid::new_v4();
let _row = TestTenant::directory_row(id);
seed_directory_user(id).await;
let token = web::token::generate_jwt_token(
id,
15,
crate::common::TEST_PRIVATE_KEY_B64,
web::token::TokenType::Access,
0,
.expect("sign")
.token
.expect("token string");
let verifies = async || {
web::auth_keys::verify(&token, web::token::TokenType::Access)
.expect("the directory is reachable in this test")
.is_some()
let before = verifies().await;
let changed = server::command::user::change_password(id, "password123", "password456").await;
let after = verifies().await;
assert!(before, "a freshly minted token must verify");
assert!(changed.is_ok(), "the password change must succeed");
assert!(!after, "it must stop verifying once the password changes");
/// A directory row whose password is `password123`, with the fixture public key
/// so `verify` can check a token we signed locally. No tenant database: `verify`
/// reads only the global directory.
async fn seed_directory_user(id: uuid::Uuid) {
let hash = argon2::PasswordHasher::hash_password(&argon2::Argon2::default(), b"password123")
.expect("hash")
.to_string();
sqlx::query(
"INSERT INTO users (id, user_name, email, user_password, database_name, \
jwt_public_key, verified) VALUES ($1, 'pw-probe', $2, $3, 'unused', $4, TRUE)",
.bind(id)
.bind(format!("pwchange-{}@example.test", id.simple()))
.bind(&hash)
.bind(crate::common::TEST_PUBLIC_KEY_B64)
.execute(&mut *conn)
.expect("seed the probe row");
async fn a_session_refreshed_on_the_way_in_is_reported_not_redeemed() {
let mut jwt = create_mock_jwt_auth(create_mock_user());
jwt.refreshed = true;
let response = web::session::refresh_access_token_handler(
axum_extra::extract::CookieJar::default(),
axum::Extension(jwt),
axum::extract::State(app_state),
.expect("the refresh is reported")
.into_response();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["refreshed_by"], "session");
async fn post_register(app: &Router, email: &str) -> axum::response::Response {
app.clone()
json!({ "name": "Twice", "email": email, "password": "password123" })
.unwrap()
async fn test_register_handler_refuses_the_same_email_twice() {
.with_state(create_test_app_state().await);
let email = format!("twice-{}@example.com", uuid::Uuid::new_v4().simple());
let first = post_register(&app, &email).await;
let second = post_register(&app, &format!(" {} ", email.to_uppercase())).await;
assert_eq!(first.status(), StatusCode::OK);
assert_eq!(second.status(), StatusCode::CONFLICT);
body_of(second).await,
r#"{"message":"User with that email already exists","status":"error"}"#
async fn test_register_handler_refuses_a_blank_email() {
let response = post_register(&app, " \t ").await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
r#"{"message":"Email must not be empty","status":"error"}"#