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.
This commit is contained in:
parent
46695ae2a0
commit
7ba78a31fb
17 changed files with 950 additions and 128 deletions
|
|
@ -3,7 +3,10 @@ use mongodb::bson::oid::ObjectId;
|
|||
use serde::{Deserialize, Serialize};
|
||||
use validator::Validate;
|
||||
|
||||
use crate::{auth::jwt::Claims, config::AppState, models::user::User};
|
||||
use crate::{
|
||||
auth::jwt::Claims, config::AppState, middleware::ClientIp, models::audit_log::AuditEventType,
|
||||
models::user::User,
|
||||
};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UserProfileResponse {
|
||||
|
|
@ -162,6 +165,7 @@ pub struct ChangePasswordRequest {
|
|||
pub async fn change_password(
|
||||
State(state): State<AppState>,
|
||||
Extension(claims): Extension<Claims>,
|
||||
Extension(client_ip): Extension<ClientIp>,
|
||||
Json(req): Json<ChangePasswordRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(errors) = req.validate() {
|
||||
|
|
@ -175,7 +179,18 @@ pub async fn change_password(
|
|||
.into_response();
|
||||
}
|
||||
|
||||
let user_id = ObjectId::parse_str(&claims.sub).unwrap();
|
||||
// The middleware already validated this against a real user, but guard
|
||||
// against a malformed subject anyway rather than panicking.
|
||||
let user_id = match ObjectId::parse_str(&claims.sub) {
|
||||
Ok(oid) => oid,
|
||||
Err(_) => {
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({ "error": "invalid token" })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
|
||||
let mut user = match state.db.find_user_by_id(&user_id).await {
|
||||
Ok(Some(u)) => u,
|
||||
|
|
@ -224,7 +239,7 @@ pub async fn change_password(
|
|||
}
|
||||
}
|
||||
|
||||
// Update password
|
||||
// Update password (this also bumps token_version in memory)
|
||||
match user.update_password(req.new_password) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
|
|
@ -240,7 +255,33 @@ pub async fn change_password(
|
|||
}
|
||||
|
||||
match state.db.update_user(&user).await {
|
||||
Ok(_) => (StatusCode::NO_CONTENT, ()).into_response(),
|
||||
Ok(_) => {
|
||||
// Invalidate all sessions: the bumped token_version rejects existing
|
||||
// access tokens, and we revoke every refresh token immediately so
|
||||
// they can't mint new access tokens.
|
||||
if let Some(ref repo) = state.refresh_token_repo {
|
||||
if let Err(e) = repo.revoke_all_by_user(&user_id.to_string()).await {
|
||||
tracing::warn!("Failed to revoke refresh tokens on password change: {}", e);
|
||||
}
|
||||
}
|
||||
state.token_version_cache.invalidate(&user_id).await;
|
||||
|
||||
// Audit the credential change.
|
||||
if let Some(ref audit) = state.audit_logger {
|
||||
let _ = audit
|
||||
.log_event(
|
||||
AuditEventType::PasswordChanged,
|
||||
Some(user_id),
|
||||
Some(user.email.clone()),
|
||||
client_ip.as_str().to_string(),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
(StatusCode::NO_CONTENT, ()).into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to update user: {}", e);
|
||||
(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue