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,9 +3,6 @@ use anyhow::Result;
|
|||
use chrono::{Duration, Utc};
|
||||
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::config::JwtConfig;
|
||||
|
||||
|
|
@ -21,9 +18,11 @@ pub struct Claims {
|
|||
}
|
||||
|
||||
impl Claims {
|
||||
pub fn new(user_id: String, email: String, token_version: i32) -> Self {
|
||||
/// Build access-token claims. `expiry` is the access-token lifetime and is
|
||||
/// taken from `JwtConfig` by callers (no longer hardcoded here).
|
||||
pub fn new(user_id: String, email: String, token_version: i32, expiry: Duration) -> Self {
|
||||
let now = Utc::now();
|
||||
let exp = now + Duration::minutes(15); // Access token expires in 15 minutes
|
||||
let exp = now + expiry;
|
||||
|
||||
Self {
|
||||
sub: user_id.clone(),
|
||||
|
|
@ -47,9 +46,10 @@ pub struct RefreshClaims {
|
|||
}
|
||||
|
||||
impl RefreshClaims {
|
||||
pub fn new(user_id: String, token_version: i32) -> Self {
|
||||
/// Build refresh-token claims. `expiry` is taken from `JwtConfig` by callers.
|
||||
pub fn new(user_id: String, token_version: i32, expiry: Duration) -> Self {
|
||||
let now = Utc::now();
|
||||
let exp = now + Duration::days(30); // Refresh token expires in 30 days
|
||||
let exp = now + expiry;
|
||||
|
||||
Self {
|
||||
sub: user_id.clone(),
|
||||
|
|
@ -61,12 +61,15 @@ impl RefreshClaims {
|
|||
}
|
||||
}
|
||||
|
||||
/// JWT Service for token generation and validation
|
||||
/// JWT Service for token generation and validation.
|
||||
///
|
||||
/// Pure crypto service: it signs/verifies tokens but does NOT track them. Token
|
||||
/// persistence (refresh-token storage, revocation) is handled by
|
||||
/// `RefreshTokenRepository` + the auth handlers; token-version staleness is
|
||||
/// enforced in the JWT middleware via `TokenVersionCache`.
|
||||
#[derive(Clone)]
|
||||
pub struct JwtService {
|
||||
config: JwtConfig,
|
||||
// In-memory storage for refresh tokens (user_id -> set of tokens)
|
||||
refresh_tokens: Arc<RwLock<HashMap<String, Vec<String>>>>,
|
||||
encoding_key: EncodingKey,
|
||||
decoding_key: DecodingKey,
|
||||
}
|
||||
|
|
@ -78,27 +81,38 @@ impl JwtService {
|
|||
|
||||
Self {
|
||||
config,
|
||||
refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
|
||||
encoding_key,
|
||||
decoding_key,
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate access and refresh tokens
|
||||
/// Generate access and refresh tokens. Both expiries are derived from the
|
||||
/// configured `JwtConfig` so callers don't need to thread durations through.
|
||||
pub fn generate_tokens(&self, claims: Claims) -> Result<(String, String)> {
|
||||
// Generate access token
|
||||
let access_token = encode(&Header::default(), &claims, &self.encoding_key)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to encode access token: {}", e))?;
|
||||
|
||||
// Generate refresh token
|
||||
let refresh_claims = RefreshClaims::new(claims.user_id.clone(), claims.token_version);
|
||||
let refresh_expiry = Duration::days(self.config.refresh_token_expiry_days);
|
||||
let refresh_claims =
|
||||
RefreshClaims::new(claims.user_id.clone(), claims.token_version, refresh_expiry);
|
||||
let refresh_token = encode(&Header::default(), &refresh_claims, &self.encoding_key)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to encode refresh token: {}", e))?;
|
||||
|
||||
Ok((access_token, refresh_token))
|
||||
}
|
||||
|
||||
/// Validate access token
|
||||
/// The configured refresh-token lifetime, as a chrono `Duration`.
|
||||
pub fn refresh_expiry(&self) -> Duration {
|
||||
Duration::days(self.config.refresh_token_expiry_days)
|
||||
}
|
||||
|
||||
/// The configured access-token lifetime, as a chrono `Duration`.
|
||||
pub fn access_expiry(&self) -> Duration {
|
||||
Duration::minutes(self.config.access_token_expiry_minutes)
|
||||
}
|
||||
|
||||
/// Validate access token (signature + expiry only). Callers are responsible
|
||||
/// for any `token_version` comparison against the user record.
|
||||
pub fn validate_token(&self, token: &str) -> Result<Claims> {
|
||||
let token_data = decode::<Claims>(token, &self.decoding_key, &Validation::default())
|
||||
.map_err(|e| anyhow::anyhow!("Invalid token: {}", e))?;
|
||||
|
|
@ -106,73 +120,59 @@ impl JwtService {
|
|||
Ok(token_data.claims)
|
||||
}
|
||||
|
||||
/// Validate refresh token
|
||||
/// Validate refresh token (signature + expiry only). Callers must still
|
||||
/// confirm the token exists, is not revoked, and has not expired in the
|
||||
/// `RefreshTokenRepository`.
|
||||
pub fn validate_refresh_token(&self, token: &str) -> Result<RefreshClaims> {
|
||||
let token_data = decode::<RefreshClaims>(token, &self.decoding_key, &Validation::default())
|
||||
.map_err(|e| anyhow::anyhow!("Invalid refresh token: {}", e))?;
|
||||
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
}
|
||||
|
||||
/// Store refresh token for a user
|
||||
pub async fn store_refresh_token(&self, user_id: &str, token: &str) -> Result<()> {
|
||||
let mut tokens = self.refresh_tokens.write().await;
|
||||
tokens
|
||||
.entry(user_id.to_string())
|
||||
.or_insert_with(Vec::new)
|
||||
.push(token.to_string());
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Keep only last 5 tokens per user
|
||||
if let Some(user_tokens) = tokens.get_mut(user_id) {
|
||||
user_tokens.sort();
|
||||
user_tokens.dedup();
|
||||
if user_tokens.len() > 5 {
|
||||
*user_tokens = user_tokens.split_off(user_tokens.len() - 5);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify if a refresh token is stored
|
||||
pub async fn verify_refresh_token_stored(&self, user_id: &str, token: &str) -> Result<bool> {
|
||||
let tokens = self.refresh_tokens.read().await;
|
||||
if let Some(user_tokens) = tokens.get(user_id) {
|
||||
Ok(user_tokens.contains(&token.to_string()))
|
||||
} else {
|
||||
Ok(false)
|
||||
fn test_config() -> JwtConfig {
|
||||
JwtConfig {
|
||||
secret: "test-secret".to_string(),
|
||||
access_token_expiry_minutes: 15,
|
||||
refresh_token_expiry_days: 7,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotate refresh token (remove old, add new)
|
||||
pub async fn rotate_refresh_token(
|
||||
&self,
|
||||
user_id: &str,
|
||||
old_token: &str,
|
||||
new_token: &str,
|
||||
) -> Result<()> {
|
||||
// Remove old token
|
||||
self.revoke_refresh_token(old_token).await?;
|
||||
#[test]
|
||||
fn generate_then_validate_roundtrip() {
|
||||
let svc = JwtService::new(test_config());
|
||||
let claims = Claims::new(
|
||||
"user-1".to_string(),
|
||||
"u@example.com".to_string(),
|
||||
0,
|
||||
Duration::minutes(15),
|
||||
);
|
||||
let (access, refresh) = svc.generate_tokens(claims).unwrap();
|
||||
|
||||
// Add new token
|
||||
self.store_refresh_token(user_id, new_token).await?;
|
||||
let access_claims = svc.validate_token(&access).unwrap();
|
||||
assert_eq!(access_claims.user_id, "user-1");
|
||||
assert_eq!(access_claims.token_version, 0);
|
||||
|
||||
Ok(())
|
||||
let refresh_claims = svc.validate_refresh_token(&refresh).unwrap();
|
||||
assert_eq!(refresh_claims.user_id, "user-1");
|
||||
}
|
||||
|
||||
/// Revoke a specific refresh token
|
||||
pub async fn revoke_refresh_token(&self, token: &str) -> Result<()> {
|
||||
let mut tokens = self.refresh_tokens.write().await;
|
||||
for user_tokens in tokens.values_mut() {
|
||||
user_tokens.retain(|t| t != token);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Revoke all refresh tokens for a user
|
||||
pub async fn revoke_all_user_tokens(&self, user_id: &str) -> Result<()> {
|
||||
let mut tokens = self.refresh_tokens.write().await;
|
||||
tokens.remove(user_id);
|
||||
Ok(())
|
||||
#[test]
|
||||
fn refresh_version_is_carried_through() {
|
||||
let svc = JwtService::new(test_config());
|
||||
let claims = Claims::new(
|
||||
"user-2".to_string(),
|
||||
"u2@example.com".to_string(),
|
||||
3,
|
||||
Duration::minutes(15),
|
||||
);
|
||||
let (_access, refresh) = svc.generate_tokens(claims).unwrap();
|
||||
let refresh_claims = svc.validate_refresh_token(&refresh).unwrap();
|
||||
assert_eq!(refresh_claims.token_version, 3);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue