normogen/backend/src/auth/token_version_cache.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

98 lines
3.2 KiB
Rust

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::Result;
use mongodb::bson::oid::ObjectId;
use tokio::sync::RwLock;
use crate::db::MongoDb;
/// How long a cached token_version is considered fresh before re-querying Mongo.
const DEFAULT_TTL: Duration = Duration::from_secs(30);
/// Short-TTL in-memory cache of `{ user_id -> token_version }`.
///
/// This lets the JWT auth middleware reject access tokens whose `token_version`
/// claim is stale (e.g. issued before a password change) without doing a Mongo
/// lookup on every request. Stale entries are evicted on credential changes via
/// [`TokenVersionCache::invalidate`], so a version bump becomes visible within
/// at most `ttl` on other instances, and immediately on the instance that
/// processed the change.
#[derive(Clone)]
pub struct TokenVersionCache {
map: Arc<RwLock<HashMap<ObjectId, (i32, Instant)>>>,
ttl: Duration,
}
impl TokenVersionCache {
pub fn new(ttl: Duration) -> Self {
Self {
map: Arc::new(RwLock::new(HashMap::new())),
ttl,
}
}
/// Build a cache with the default 30s TTL.
pub fn with_default_ttl() -> Self {
Self::new(DEFAULT_TTL)
}
/// Return the user's current `token_version`, loading it from Mongo on a
/// cache miss or once the cached value is older than the TTL.
///
/// Returns `Ok(None)` when the user no longer exists (deleted), so callers
/// can reject the token as unauthorized.
pub async fn get_or_load(&self, user_id: &ObjectId, db: &MongoDb) -> Result<Option<i32>> {
// Fast path: serve from cache if fresh.
{
let cache = self.map.read().await;
if let Some((version, fetched_at)) = cache.get(user_id) {
if fetched_at.elapsed() < self.ttl {
return Ok(Some(*version));
}
}
}
// Slow path: query Mongo and refresh the cache.
let version = match db.find_user_by_id(user_id).await? {
Some(user) => Some(user.token_version),
None => None,
};
let mut cache = self.map.write().await;
match version {
Some(v) => {
cache.insert(*user_id, (v, Instant::now()));
}
None => {
// User was deleted: drop any stale entry so we don't serve it.
cache.remove(user_id);
}
}
Ok(version)
}
/// Drop the cached entry for a user. Call this whenever a user's
/// `token_version` is bumped (password change / recovery) so that the new
/// version becomes visible immediately instead of waiting for TTL expiry.
pub async fn invalidate(&self, user_id: &ObjectId) {
let mut cache = self.map.write().await;
cache.remove(user_id);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn invalidate_removes_entry() {
// We can't easily exercise get_or_load without Mongo, but invalidate on
// an empty cache is a no-op and must not panic.
let cache = TokenVersionCache::with_default_ttl();
cache.invalidate(&ObjectId::new()).await;
assert!(cache.map.read().await.is_empty());
}
}