feat(security): HttpOnly cookies + CSP headers + CSRF double-submit protection

- Migrate auth tokens from localStorage to HttpOnly SameSite=Lax cookies
- Add cookie_auth.rs: helpers for setting/clearing auth + CSRF cookies
- Update auth middleware: 3-method auth (Bearer → Basic → Cookie)
- Add 5 security headers: CSP, X-Content-Type-Options, X-Frame-Options,
  Referrer-Policy, Permissions-Policy
- Implement CSRF double-submit cookie pattern (csrf.rs middleware)
- Set CSRF cookie on login/refresh/oidc-exchange, clear on logout
- CookieAuthenticated marker skips CSRF for Bearer/Basic clients
- Frontend: strip all localStorage token refs from 14 JS files
- Frontend: csrf.js utility + all 52 mutating fetch/XHR calls protected
- 121 tests passing, 0 warnings
This commit is contained in:
Dionisio
2026-03-03 01:10:50 +01:00
parent 7b2a8577a9
commit d2c08d31ba
27 changed files with 579 additions and 455 deletions
+148
View File
@@ -0,0 +1,148 @@
//! HttpOnly cookie helpers for secure token transport.
//!
//! Tokens are set as `HttpOnly; SameSite=Lax` cookies so that
//! browser-based JavaScript cannot read them (mitigates XSS token theft).
//! The `Secure` flag is controlled by the `OXICLOUD_COOKIE_SECURE` env var
//! (default: auto-detect from `OXICLOUD_BASE_URL`).
//!
//! A companion **non-HttpOnly** CSRF cookie (`oxicloud_csrf`) is set
//! alongside the auth cookies. The frontend must read it and echo its
//! value back as `X-CSRF-Token` on every state-changing request.
//! A middleware (`csrf_middleware`) validates the match.
//!
//! DAV clients continue to use `Authorization: Basic` with app passwords
//! and are completely unaffected by this mechanism.
use axum::http::header::SET_COOKIE;
use axum::http::{HeaderMap, HeaderValue};
/// Cookie name for the JWT access token.
pub const ACCESS_COOKIE: &str = "oxicloud_access";
/// Cookie name for the opaque refresh token.
pub const REFRESH_COOKIE: &str = "oxicloud_refresh";
/// Cookie name for the CSRF double-submit token (readable by JS).
pub const CSRF_COOKIE: &str = "oxicloud_csrf";
/// Header the frontend must send with the CSRF token value.
pub const CSRF_HEADER: &str = "x-csrf-token";
/// Whether the `Secure` flag should be set on cookies.
/// Auto-detected from `OXICLOUD_BASE_URL` (if it starts with `https`)
/// or overridden with `OXICLOUD_COOKIE_SECURE=true|false`.
fn cookie_secure() -> bool {
if let Ok(v) = std::env::var("OXICLOUD_COOKIE_SECURE") {
return v == "true" || v == "1";
}
// Auto-detect from base URL
std::env::var("OXICLOUD_BASE_URL")
.map(|u| u.starts_with("https"))
.unwrap_or(false)
}
/// Build a `Set-Cookie` header value.
fn build_cookie(name: &str, value: &str, path: &str, max_age_secs: i64) -> String {
let secure = if cookie_secure() { "; Secure" } else { "" };
format!(
"{name}={value}; HttpOnly; SameSite=Lax; Path={path}; Max-Age={max_age_secs}{secure}",
)
}
/// Append `Set-Cookie` headers for both access and refresh tokens.
///
/// The access cookie covers all paths (`/`) because the API lives under
/// `/api`, CalDAV under `/caldav`, WebDAV under `/webdav`, etc.
///
/// The refresh cookie is restricted to `/api/auth` so it is only sent
/// when the client explicitly calls the refresh or logout endpoints.
pub fn append_auth_cookies(
headers: &mut HeaderMap,
access_token: &str,
refresh_token: &str,
access_expiry_secs: i64,
refresh_expiry_secs: i64,
) {
if let Ok(val) = HeaderValue::from_str(&build_cookie(
ACCESS_COOKIE,
access_token,
"/",
access_expiry_secs,
)) {
headers.append(SET_COOKIE, val);
}
if let Ok(val) = HeaderValue::from_str(&build_cookie(
REFRESH_COOKIE,
refresh_token,
"/api/auth",
refresh_expiry_secs,
)) {
headers.append(SET_COOKIE, val);
}
}
/// Append `Set-Cookie` headers that immediately expire both auth cookies,
/// effectively logging the user out on the browser side.
pub fn append_clear_cookies(headers: &mut HeaderMap) {
for (name, path) in [(ACCESS_COOKIE, "/"), (REFRESH_COOKIE, "/api/auth")] {
let secure = if cookie_secure() { "; Secure" } else { "" };
let val = format!(
"{name}=; HttpOnly; SameSite=Lax; Path={path}; Max-Age=0{secure}",
);
if let Ok(hv) = HeaderValue::from_str(&val) {
headers.append(SET_COOKIE, hv);
}
}
}
/// Extract a named cookie value from the `Cookie` request header.
pub fn extract_cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
let cookie_header = headers.get(axum::http::header::COOKIE)?;
let cookie_str = cookie_header.to_str().ok()?;
for pair in cookie_str.split(';') {
let pair = pair.trim();
if let Some(val) = pair.strip_prefix(name) {
let val = val.strip_prefix('=')?;
if !val.is_empty() {
return Some(val.to_string());
}
}
}
None
}
// ────────────────────────────────────────────────────────────
// CSRF double-submit cookie helpers
// ────────────────────────────────────────────────────────────
/// Generate a cryptographically random CSRF token (128-bit UUIDv4, hex-like).
pub fn generate_csrf_token() -> String {
uuid::Uuid::new_v4().to_string()
}
/// Build a **non-HttpOnly** CSRF cookie so that frontend JS can read it
/// via `document.cookie` and echo it back in the `X-CSRF-Token` header.
fn build_csrf_cookie(value: &str, max_age_secs: i64) -> String {
let secure = if cookie_secure() { "; Secure" } else { "" };
format!(
"{CSRF_COOKIE}={value}; SameSite=Lax; Path=/; Max-Age={max_age_secs}{secure}",
)
}
/// Append a CSRF double-submit cookie alongside the auth cookies.
/// Should be called in every endpoint that also sets auth cookies.
pub fn append_csrf_cookie(headers: &mut HeaderMap, access_expiry_secs: i64) {
let token = generate_csrf_token();
if let Ok(val) = HeaderValue::from_str(&build_csrf_cookie(&token, access_expiry_secs)) {
headers.append(SET_COOKIE, val);
}
}
/// Clear the CSRF cookie (on logout).
pub fn append_clear_csrf_cookie(headers: &mut HeaderMap) {
let secure = if cookie_secure() { "; Secure" } else { "" };
let val = format!(
"{CSRF_COOKIE}=; SameSite=Lax; Path=/; Max-Age=0{secure}",
);
if let Ok(hv) = HeaderValue::from_str(&val) {
headers.append(SET_COOKIE, hv);
}
}
+79 -59
View File
@@ -2,7 +2,7 @@ use axum::{
Router,
extract::{Json, Query, State},
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Redirect},
response::{IntoResponse, Redirect, Response},
routing::{get, post, put},
};
use std::sync::Arc;
@@ -12,7 +12,9 @@ use crate::application::dtos::user_dto::{
RefreshTokenDto, RegisterDto,
};
use crate::common::di::AppState;
use crate::interfaces::api::cookie_auth;
use crate::interfaces::errors::AppError;
use crate::interfaces::middleware::auth::CurrentUserId;
pub fn auth_routes() -> Router<Arc<AppState>> {
// Routes that do NOT require authentication
@@ -103,7 +105,7 @@ async fn register(
async fn login(
State(state): State<Arc<AppState>>,
Json(dto): Json<LoginDto>,
) -> Result<impl IntoResponse, AppError> {
) -> Result<Response, AppError> {
// Add detailed logging for debugging
tracing::info!("Login attempt for user: {}", dto.username);
@@ -153,7 +155,20 @@ async fn login(
));
}
Ok((StatusCode::OK, Json(auth_response)))
// ── Set HttpOnly cookies so the browser never stores tokens in JS ──
let mut response = (StatusCode::OK, Json(&auth_response)).into_response();
cookie_auth::append_auth_cookies(
response.headers_mut(),
&auth_response.access_token,
&auth_response.refresh_token,
auth_response.expires_in,
state.core.config.auth.refresh_token_expiry_secs,
);
cookie_auth::append_csrf_cookie(
response.headers_mut(),
auth_response.expires_in,
);
Ok(response)
}
Err(err) => {
tracing::error!("Login failed for user {}: {}", dto.username, err);
@@ -162,58 +177,63 @@ async fn login(
}
}
/// Token refresh — accepts the refresh token from **either**:
/// 1. JSON body `{ "refresh_token": "..." }` (API clients, backward compat)
/// 2. HttpOnly cookie `oxicloud_refresh` (browsers)
async fn refresh_token(
State(state): State<Arc<AppState>>,
Json(dto): Json<RefreshTokenDto>,
) -> Result<impl IntoResponse, AppError> {
// Add rate limiting for token refresh to prevent refresh loops
// Check if this refresh token is being used too frequently
// Log the refresh attempt for debugging
headers: HeaderMap,
body: axum::body::Bytes,
) -> Result<Response, AppError> {
tracing::info!("Token refresh requested");
// Normal process for real tokens
let auth_service = state
.auth_service
.as_ref()
.ok_or_else(|| AppError::internal_error("Authentication service not configured"))?;
// Try JSON body first (backward compat), then fall back to HttpOnly cookie
let refresh_tok = serde_json::from_slice::<RefreshTokenDto>(&body)
.ok()
.map(|dto| dto.refresh_token)
.or_else(|| cookie_auth::extract_cookie_value(&headers, cookie_auth::REFRESH_COOKIE))
.ok_or_else(|| AppError::unauthorized("Refresh token required (JSON body or cookie)"))?;
let dto = RefreshTokenDto {
refresh_token: refresh_tok,
};
let auth_response = auth_service
.auth_application_service
.refresh_token(dto)
.await?;
// Log successful token refresh
tracing::info!("Token refresh successful, new token issued");
Ok((StatusCode::OK, Json(auth_response)))
let mut response = (StatusCode::OK, Json(&auth_response)).into_response();
cookie_auth::append_auth_cookies(
response.headers_mut(),
&auth_response.access_token,
&auth_response.refresh_token,
auth_response.expires_in,
state.core.config.auth.refresh_token_expiry_secs,
);
cookie_auth::append_csrf_cookie(
response.headers_mut(),
auth_response.expires_in,
);
Ok(response)
}
async fn get_current_user(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
CurrentUserId(user_id): CurrentUserId,
) -> Result<impl IntoResponse, AppError> {
// Normal process for all users
let auth_service = state
.auth_service
.as_ref()
.ok_or_else(|| AppError::internal_error("Authentication service not configured"))?;
// Extract and validate the token directly
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.ok_or_else(|| AppError::unauthorized("Authorization token not found"))?;
// Validate the token and get claims
let claims = auth_service
.token_service
.validate_token(token)
.map_err(|e| AppError::unauthorized(format!("Invalid token: {}", e)))?;
let user_id = claims.sub;
// First, update the storage usage statistics
// IMPORTANT: We await the calculation to return updated data
if let Some(storage_usage_service) = state.storage_usage_service.as_ref() {
@@ -247,7 +267,7 @@ async fn get_current_user(
async fn change_password(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
CurrentUserId(user_id): CurrentUserId,
Json(dto): Json<ChangePasswordDto>,
) -> Result<impl IntoResponse, AppError> {
let auth_service = state
@@ -255,22 +275,9 @@ async fn change_password(
.as_ref()
.ok_or_else(|| AppError::internal_error("Authentication service not configured"))?;
// Extract and validate the token directly
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.ok_or_else(|| AppError::unauthorized("Authorization token not found"))?;
// Validate the token and get claims
let claims = auth_service
.token_service
.validate_token(token)
.map_err(|e| AppError::unauthorized(format!("Invalid token: {}", e)))?;
auth_service
.auth_application_service
.change_password(&claims.sub, dto)
.change_password(&user_id, dto)
.await?;
Ok(StatusCode::OK)
@@ -279,32 +286,32 @@ async fn change_password(
async fn logout(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
) -> Result<impl IntoResponse, AppError> {
CurrentUserId(user_id): CurrentUserId,
) -> Result<Response, AppError> {
let auth_service = state
.auth_service
.as_ref()
.ok_or_else(|| AppError::internal_error("Authentication service not configured"))?;
// Extract and validate the token directly
// Obtain the raw access token from Bearer header OR cookie
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(String::from)
.or_else(|| cookie_auth::extract_cookie_value(&headers, cookie_auth::ACCESS_COOKIE))
.ok_or_else(|| AppError::unauthorized("Authorization token not found"))?;
// Validate the token and get claims
let claims = auth_service
.token_service
.validate_token(token)
.map_err(|e| AppError::unauthorized(format!("Invalid token: {}", e)))?;
// Use access token for logout (we don't have refresh token in headers)
auth_service
.auth_application_service
.logout(&claims.sub, token)
.logout(&user_id, &token)
.await?;
Ok(StatusCode::OK)
// Clear HttpOnly + CSRF cookies so the browser forgets the session
let mut response = StatusCode::OK.into_response();
cookie_auth::append_clear_cookies(response.headers_mut());
cookie_auth::append_clear_csrf_cookie(response.headers_mut());
Ok(response)
}
/// Get system status - returns whether admin is configured
@@ -452,7 +459,7 @@ async fn oidc_callback(
async fn oidc_exchange(
State(state): State<Arc<AppState>>,
Json(body): Json<OidcExchangeDto>,
) -> Result<impl IntoResponse, AppError> {
) -> Result<Response, AppError> {
let auth_service = state
.auth_service
.as_ref()
@@ -471,5 +478,18 @@ async fn oidc_exchange(
auth_response.user.username
);
Ok((StatusCode::OK, Json(auth_response)))
// Set HttpOnly cookies for the browser
let mut response = (StatusCode::OK, Json(&auth_response)).into_response();
cookie_auth::append_auth_cookies(
response.headers_mut(),
&auth_response.access_token,
&auth_response.refresh_token,
auth_response.expires_in,
state.core.config.auth.refresh_token_expiry_secs,
);
cookie_auth::append_csrf_cookie(
response.headers_mut(),
auth_response.expires_in,
);
Ok(response)
}
+1
View File
@@ -1,3 +1,4 @@
pub mod cookie_auth;
pub mod handlers;
pub mod routes;
+49 -3
View File
@@ -12,6 +12,12 @@ use crate::common::di::AppState;
// Re-export CurrentUser from application layer for use in handlers
pub use crate::application::dtos::user_dto::CurrentUser;
/// Marker inserted into request extensions when the user was authenticated
/// via the `oxicloud_access` HttpOnly cookie rather than a Bearer/Basic header.
/// The CSRF middleware uses this to decide whether CSRF validation is required.
#[derive(Clone, Copy, Debug)]
pub struct CookieAuthenticated;
// Structure for use in Axum extractors
#[derive(Clone, Debug)]
pub struct AuthUser {
@@ -154,12 +160,15 @@ impl IntoResponse for AuthError {
/// Secure authentication middleware.
///
/// Supports two authentication methods:
/// Supports three authentication methods (tried in order):
/// 1. **Bearer JWT** — standard token in `Authorization: Bearer <token>`
/// 2. **Basic Auth with App Passwords** — for DAV clients (DAVx⁵, Thunderbird, rclone)
/// that send `Authorization: Basic base64(username:app_password)`
/// 3. **HttpOnly Cookie** — `oxicloud_access` cookie set by the login endpoint;
/// used by browser-based sessions so tokens are never exposed to JS.
///
/// Bearer is tried first; if no Bearer header is found, Basic is attempted.
/// Bearer is tried first; if no Bearer header is found, Basic is attempted,
/// then the cookie fallback.
pub async fn auth_middleware(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
@@ -260,7 +269,44 @@ pub async fn auth_middleware(
}
}
// No valid Authorization header found
// ── 3. Try HttpOnly cookie (browser sessions) ────────────────
{
use crate::interfaces::api::cookie_auth;
if let Some(token_str) = cookie_auth::extract_cookie_value(&headers, cookie_auth::ACCESS_COOKIE) {
if !token_str.is_empty() {
tracing::debug!("Processing cookie-based authentication");
if let Some(auth_service) = state.auth_service.as_ref() {
let token_service = &auth_service.token_service;
match token_service.validate_token(&token_str) {
Ok(claims) => {
tracing::debug!(
"Cookie token validated for user: {}",
claims.username
);
let current_user = CurrentUser {
id: claims.sub,
username: claims.username,
email: claims.email,
role: claims.role,
};
request.extensions_mut().insert(current_user);
request.extensions_mut().insert(CookieAuthenticated);
return Ok(next.run(request).await);
}
Err(e) => {
tracing::debug!("Cookie token validation failed: {}", e);
// Don't return error — fall through to "no token" so
// the browser gets a 401 and can redirect to /login.
}
}
}
}
}
}
// No valid credentials found via any method
if state.auth_service.is_none() {
tracing::error!("Auth middleware invoked but auth service is not configured");
return Err(AuthError::AuthServiceUnavailable);
+75
View File
@@ -0,0 +1,75 @@
//! CSRF double-submit cookie middleware.
//!
//! State-changing requests (`POST`, `PUT`, `DELETE`, `PATCH`) that were
//! authenticated via an HttpOnly cookie (i.e. browser sessions) **must**
//! include an `X-CSRF-Token` header whose value matches the `oxicloud_csrf`
//! cookie. Requests authenticated via `Bearer` or `Basic` headers are
//! exempt because they are not vulnerable to CSRF — the browser never
//! attaches those automatically.
//!
//! Safe methods (`GET`, `HEAD`, `OPTIONS`) are always allowed through.
use axum::{
extract::Request,
http::{Method, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
};
use crate::interfaces::api::cookie_auth;
use crate::interfaces::middleware::auth::CookieAuthenticated;
/// Methods considered safe (no side-effects) — CSRF check is skipped.
const SAFE_METHODS: [Method; 3] = [Method::GET, Method::HEAD, Method::OPTIONS];
/// Middleware that enforces CSRF protection for cookie-authenticated browser
/// sessions using the **double-submit cookie** pattern.
///
/// Must be applied **after** `auth_middleware` so that the
/// `CookieAuthenticated` marker is available in extensions.
pub async fn csrf_middleware(request: Request, next: Next) -> Result<Response, Response> {
// Safe methods never need CSRF validation.
if SAFE_METHODS.contains(request.method()) {
return Ok(next.run(request).await);
}
// Only enforce for cookie-authenticated sessions.
let is_cookie_auth = request.extensions().get::<CookieAuthenticated>().is_some();
if !is_cookie_auth {
return Ok(next.run(request).await);
}
// Extract the CSRF token from the cookie.
let cookie_token = cookie_auth::extract_cookie_value(
request.headers(),
cookie_auth::CSRF_COOKIE,
);
// Extract the CSRF token from the request header.
let header_token = request
.headers()
.get(cookie_auth::CSRF_HEADER)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
match (cookie_token, header_token) {
(Some(c), Some(h)) if !c.is_empty() && c == h => {
// Tokens match — allow the request through.
Ok(next.run(request).await)
}
_ => {
tracing::warn!(
method = %request.method(),
uri = %request.uri(),
"CSRF validation failed: missing or mismatched token"
);
Err((
StatusCode::FORBIDDEN,
axum::Json(serde_json::json!({
"error": "CSRF token missing or invalid"
})),
)
.into_response())
}
}
}
+1
View File
@@ -1 +1,2 @@
pub mod auth;
pub mod csrf;