normogen/backend/tests/auth_tests.rs
goose 8ee8012aca
Some checks failed
Lint and Build / format (pull_request) Successful in 42s
Lint and Build / clippy (pull_request) Successful in 1m46s
Lint and Build / build (pull_request) Successful in 3m47s
Lint and Build / test (pull_request) Failing after 0s
feat(auth): add per-account X25519 identity keypair (#3)
Phase A1 of the multi-person sharing ADR
(docs/adr/multi-person-sharing.md). Each account now gets an X25519
keypair at registration: the public half stored plaintext, the private
half wrapped under the account DEK and stored as opaque ciphertext. The
keypair is generated client-side; the backend adds no crypto deps and
stores everything verbatim, preserving the zero-knowledge contract.

This change only introduces the keypair and threads it through the auth
flows — it is not consumed yet. It unblocks Phase B (profile sharing)
without touching the data model or the ~11 frontend encrypt call sites,
which is Phase A2 (per-profile DEKs).

Backend:
- User model: identity_public_key, identity_private_key_wrapped{,_iv}
  (all Option<String>, backward compatible).
- RegisterRequest/AuthResponse carry the 3 fields; register + login
  echo them. No changes to change_password/recover (DEK value is
  unchanged across both, so the wrapped private key is too).
- 2 new integration tests: round-trip through register/login, and
  optional-fields backward compat.

Frontend:
- crypto/keys.ts: generateIdentityKeyPair, wrapIdentityPrivateKey,
  unwrapIdentityPrivateKey + in-memory identity store mirroring the DEK.
- types/api.ts: AuthTokens + RegisterRequest extended (removes an
  existing `as any` cast).
- useStore register/login/logout + UnlockPage unwrap the private key
  alongside the DEK.
- 3 new crypto tests (X25519 lifecycle, wrong-DEK rejection, distinct
  shared secrets); skip gracefully where the runtime lacks X25519.

Backend: cargo test + clippy green. Frontend: npm test + tsc green.

Also gitignore .zcode/ (local tooling artifact).
2026-07-18 20:00:01 -03:00

383 lines
12 KiB
Rust

//! 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};
/// 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 health_and_ready() {
let (app, db_name) = require_app!(common::app_for_test().await);
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 register_returns_token_and_refresh_token() {
let (app, db_name) = require_app!(common::app_for_test().await);
let email = unique_email();
// 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);
common::drop_test_db(&db_name).await;
}
#[tokio::test]
async fn login_with_correct_password() {
let (app, db_name) = require_app!(common::app_for_test().await);
let email = unique_email();
register(&app, &email, "supersecret").await;
// 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());
common::drop_test_db(&db_name).await;
}
#[tokio::test]
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 (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}");
common::drop_test_db(&db_name).await;
}
#[tokio::test]
async fn protected_route_rejects_missing_token() {
let (app, db_name) = require_app!(common::app_for_test().await);
let (status, _) = common::send_json(&app, "GET", "/api/users/me", None, None).await;
assert_eq!(status, 401);
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;
}
#[tokio::test]
async fn identity_keypair_round_trips_through_register_and_login() {
// Phase A1 (#3): the X25519 identity keypair fields (public plaintext,
// private wrapped under the account DEK) are stored verbatim at register
// and echoed back on login. The server never inspects or derives them.
let (app, db_name) = require_app!(common::app_for_test().await);
let email = unique_email();
// Opaque blobs — the server treats these as base64 strings, nothing more.
let public_key = "base64-x25519-public-key-for-test";
let priv_wrapped = "base64-wrapped-priv-ciphertext";
let priv_wrapped_iv = "base64-12-byte-iv";
let (status, body) = common::send_json(
&app,
"POST",
"/api/auth/register",
Some(json!({
"email": email,
"username": "tester",
"password": "supersecret",
"identity_public_key": public_key,
"identity_private_key_wrapped": priv_wrapped,
"identity_private_key_wrapped_iv": priv_wrapped_iv,
})),
None,
)
.await;
assert_eq!(status, 201, "register should return 201, body: {body}");
assert_eq!(body["identity_public_key"], public_key);
assert_eq!(body["identity_private_key_wrapped"], priv_wrapped);
assert_eq!(body["identity_private_key_wrapped_iv"], priv_wrapped_iv);
// Login must echo the same stored values.
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 return 200, body: {body}");
assert_eq!(body["identity_public_key"], public_key);
assert_eq!(body["identity_private_key_wrapped"], priv_wrapped);
assert_eq!(body["identity_private_key_wrapped_iv"], priv_wrapped_iv);
common::drop_test_db(&db_name).await;
}
#[tokio::test]
async fn register_without_identity_keypair_stays_optional() {
// Backward compat: existing clients that don't send identity fields must
// still register successfully, and the fields are absent from the response.
let (app, db_name) = require_app!(common::app_for_test().await);
let email = unique_email();
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.get("identity_public_key").is_none() || body["identity_public_key"].is_null(),
"identity_public_key should be absent when not provided: {body}"
);
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()
}