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
137
backend/src/middleware/client_ip.rs
Normal file
137
backend/src/middleware/client_ip.rs
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
//! Resolves the originating client IP for each request and exposes it to
|
||||
//! handlers via the [`ClientIp`] request extension.
|
||||
//!
|
||||
//! Resolution order (most-trusted first):
|
||||
//! 1. `X-Forwarded-For` — first hop (the original client). Normogen is deployed
|
||||
//! behind a reverse proxy on Solaria, so this is the primary source.
|
||||
//! 2. `X-Real-IP` — common single-IP proxy header.
|
||||
//! 3. The peer address from Axum's `ConnectInfo<SocketAddr>` (direct connection).
|
||||
//! 4. `"0.0.0.0"` only if none of the above are present.
|
||||
|
||||
#![allow(dead_code)]
|
||||
use axum::{
|
||||
extract::ConnectInfo, extract::Request, http::HeaderMap, middleware::Next, response::Response,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
/// Header carrying the originating client chain (proxy-populated).
|
||||
const X_FORWARDED_FOR: &str = "x-forwarded-for";
|
||||
/// Header some proxies set to the single originating IP.
|
||||
const X_REAL_IP: &str = "x-real-ip";
|
||||
/// Fallback when no IP can be determined.
|
||||
const UNKNOWN_IP: &str = "0.0.0.0";
|
||||
|
||||
/// Extractor carrying the resolved client IP, inserted by [`client_ip_middleware`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClientIp(pub String);
|
||||
|
||||
impl ClientIp {
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ClientIp {
|
||||
type Target = str;
|
||||
fn deref(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the client IP from request headers, falling back to the peer socket.
|
||||
///
|
||||
/// Pure and unit-testable: pass the headers and an optional `ConnectInfo`.
|
||||
pub fn extract_client_ip(headers: &HeaderMap, conn: Option<&ConnectInfo<SocketAddr>>) -> String {
|
||||
// X-Forwarded-For: "client, proxy1, proxy2" — the leftmost entry is the
|
||||
// original client. Only validate it looks like an IP; take the first token.
|
||||
if let Some(xff) = headers.get(X_FORWARDED_FOR).and_then(|h| h.to_str().ok()) {
|
||||
if let Some(first) = xff.split(',').map(str::trim).find(|s| !s.is_empty()) {
|
||||
return first.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// X-Real-IP: single IP.
|
||||
if let Some(ip) = headers.get(X_REAL_IP).and_then(|h| h.to_str().ok()) {
|
||||
let ip = ip.trim();
|
||||
if !ip.is_empty() {
|
||||
return ip.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// Direct peer address, when ConnectInfo is wired (see main.rs).
|
||||
if let Some(info) = conn {
|
||||
return info.0.ip().to_string();
|
||||
}
|
||||
|
||||
UNKNOWN_IP.to_string()
|
||||
}
|
||||
|
||||
/// Middleware that computes the client IP once and stashes it in request
|
||||
/// extensions so handlers can pull it out with `Extension(ClientIp(..))`.
|
||||
pub async fn client_ip_middleware(mut req: Request, next: Next) -> Response {
|
||||
let conn = req.extensions().get::<ConnectInfo<SocketAddr>>();
|
||||
let ip = extract_client_ip(req.headers(), conn);
|
||||
req.extensions_mut().insert(ClientIp(ip));
|
||||
next.run(req).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::extract::ConnectInfo;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
|
||||
fn headers() -> HeaderMap {
|
||||
HeaderMap::new()
|
||||
}
|
||||
|
||||
fn conn() -> ConnectInfo<SocketAddr> {
|
||||
ConnectInfo(SocketAddr::new(
|
||||
IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)),
|
||||
12345,
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefers_x_forwarded_for_first_hop() {
|
||||
let mut h = headers();
|
||||
h.insert(
|
||||
X_FORWARDED_FOR,
|
||||
"198.51.100.2, 10.0.0.1, 10.0.0.2".parse().unwrap(),
|
||||
);
|
||||
assert_eq!(extract_client_ip(&h, Some(&conn())), "198.51.100.2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_x_real_ip_when_no_xff() {
|
||||
let mut h = headers();
|
||||
h.insert(X_REAL_IP, "198.51.100.9".parse().unwrap());
|
||||
assert_eq!(extract_client_ip(&h, Some(&conn())), "198.51.100.9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xff_takes_precedence_over_x_real_ip() {
|
||||
let mut h = headers();
|
||||
h.insert(X_FORWARDED_FOR, "198.51.100.2".parse().unwrap());
|
||||
h.insert(X_REAL_IP, "10.0.0.99".parse().unwrap());
|
||||
assert_eq!(extract_client_ip(&h, Some(&conn())), "198.51.100.2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_socket_when_no_proxy_headers() {
|
||||
assert_eq!(extract_client_ip(&headers(), Some(&conn())), "203.0.113.7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_when_nothing_available() {
|
||||
assert_eq!(extract_client_ip(&headers(), None), UNKNOWN_IP);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_blank_xff_entries() {
|
||||
let mut h = headers();
|
||||
// Leading whitespace/empty entry should be skipped, not returned blank.
|
||||
h.insert(X_FORWARDED_FOR, " , 10.0.0.5".parse().unwrap());
|
||||
assert_eq!(extract_client_ip(&h, None), "10.0.0.5");
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue