normogen/backend/src/middleware/auth.rs
goose 7ba78a31fb fix(backend): P0 security hardening pass
Address the four P0 security items from the project review:

* token_version validation (#1): the JWT middleware now rejects access tokens
  whose token_version claim is stale (e.g. issued before a password change).
  A short-TTL (30s) in-memory cache (TokenVersionCache) avoids a Mongo lookup
  per request; credential changes invalidate the cache immediately on the
  handling instance.

* Fail-fast config (#2): add APP_ENVIRONMENT (development|production). In
  production the server refuses to boot unless JWT_SECRET and ENCRYPTION_KEY
  are set to non-default values; development keeps the insecure defaults with
  a warning.

* Real client IP in audit logs (#4): new client_ip middleware resolves the
  originating IP (X-Forwarded-For > X-Real-IP > ConnectInfo socket) and
  exposes it via a ClientIp extractor. All five hardcoded "0.0.0.0" audit
  calls are replaced, and the missing PasswordChanged audit event is added to
  change_password. axum::serve now uses into_make_service_with_connect_info.

* Refresh token persistence (#5): refresh tokens are now stored hashed in
  MongoDB (RefreshTokenRepository) instead of an in-memory map lost on restart.
  Added /api/auth/refresh (with rotation + token_version check) and
  /api/auth/logout routes; register/login return a refresh_token; password
  change/recovery revoke all of a user's refresh tokens. JwtService now honors
  JwtConfig expiries instead of hardcoding 15min/30d, and the dead in-memory
  refresh store is removed.

Also: wire up DatabaseInitializer (was never called), fix the refresh_tokens
index to tokenHash + add an expiresAt TTL index, add sha2 dep.

Rate limiting (#3) is deferred per scope; the stub remains.

Verified: cargo fmt --check clean, cargo build/clippy --all-targets clean,
18 unit tests pass (9 new). Integration tests (tests/*) still need a live
server — fixing them is tracked as P1.

BREAKING CHANGE: AuthResponse now includes a refresh_token field.
2026-06-27 13:12:19 -03:00

68 lines
1.9 KiB
Rust

#![allow(dead_code)]
#![allow(unused_imports)]
use crate::auth::jwt::Claims;
use crate::config::AppState;
use axum::{
extract::{Request, State},
http::StatusCode,
middleware::Next,
response::Response,
};
use mongodb::bson::oid::ObjectId;
pub async fn jwt_auth_middleware(
State(state): State<AppState>,
mut req: Request,
next: Next,
) -> Result<Response, StatusCode> {
let headers = req.headers();
// Extract Authorization header
let auth_header = headers
.get("Authorization")
.and_then(|h| h.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
// Check Bearer token format
if !auth_header.starts_with("Bearer ") {
return Err(StatusCode::UNAUTHORIZED);
}
let token = &auth_header[7..]; // Remove "Bearer " prefix
// Verify signature and expiry.
let claims = state
.jwt_service
.validate_token(token)
.map_err(|_| StatusCode::UNAUTHORIZED)?;
// Reject tokens whose version is stale (e.g. issued before a password
// change). The user's current version is cached briefly so we don't hit
// Mongo on every request; a missing user (deleted) also means 401.
let user_oid = ObjectId::parse_str(&claims.sub).map_err(|_| StatusCode::UNAUTHORIZED)?;
let current_version = state
.token_version_cache
.get_or_load(&user_oid, &state.db)
.await
.map_err(|_| StatusCode::UNAUTHORIZED)?;
match current_version {
Some(v) if v == claims.token_version => {}
_ => return Err(StatusCode::UNAUTHORIZED),
}
// Add claims to request extensions for handlers to use
req.extensions_mut().insert(claims);
Ok(next.run(req).await)
}
// Extension method to extract claims from request
pub trait RequestClaimsExt {
fn claims(&self) -> Option<&Claims>;
}
impl RequestClaimsExt for Request {
fn claims(&self) -> Option<&Claims> {
self.extensions().get::<Claims>()
}
}