fix(audit-2026-06-11/C-1): drop cookie auth on /api/v1/admin/*
Same-origin CSRF: the platform co-hosts user-route HTML on the same origin as /api/v1/admin/*; SameSite=Lax did not block a same-origin POST from a malicious script at /<route>, riding the admin's picloud_session cookie. The dashboard already uses Bearer (dashboard/src/lib/auth.ts + api.ts:495), so cookie auth was dead weight on the admin side and exploitable. Cuts the cookie path entirely: - auth_middleware::extract_token is Bearer-only; cookie branch removed. - auth_api::login no longer sets Set-Cookie. - auth_api::logout no longer clears the cookie (the bearer token is still revoked by deleting the session row). - extract_token_for_logout matches. - SESSION_COOKIE const + PICLOUD_COOKIE_SECURE env var deleted. Audit ref: security_audit/07_http_cors_csrf_xss.md#c07-01. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,14 @@
|
||||
//! `/api/v1/admin/auth/*` — login, logout, who-am-I.
|
||||
//!
|
||||
//! Login mints an opaque session token, stores its SHA-256, sets the
|
||||
//! `picloud_session` HttpOnly cookie, and also returns the raw token in
|
||||
//! the JSON body for non-browser clients. The same token works as
|
||||
//! `Authorization: Bearer …` afterward; there is no separate "API
|
||||
//! token" concept yet.
|
||||
//! Login mints an opaque session token, stores its SHA-256, and returns
|
||||
//! the raw token in the JSON body. Clients must send it as
|
||||
//! `Authorization: Bearer …` on subsequent requests; the same token is
|
||||
//! used for the session and admin-API authentication paths (there is no
|
||||
//! separate "API token" concept yet).
|
||||
//!
|
||||
//! Cookie auth was removed in the audit 2026-06-11 C-1 fix — same-origin
|
||||
//! user-route HTML defeated the previous `SameSite=Lax` cookie. The
|
||||
//! dashboard already uses Bearer; non-browser clients always have.
|
||||
//!
|
||||
//! Logout deletes the session row regardless of whether the supplied
|
||||
//! token matched anything (idempotent). `me` returns the row that the
|
||||
@@ -12,7 +16,7 @@
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Extension, Request, State};
|
||||
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::middleware::from_fn_with_state;
|
||||
use axum::response::{IntoResponse, Json, Response};
|
||||
use axum::routing::{get, post};
|
||||
@@ -25,7 +29,7 @@ use serde_json::json;
|
||||
use picloud_shared::Principal;
|
||||
|
||||
use crate::auth::{generate_session_token, hash_token, verify_password};
|
||||
use crate::auth_middleware::{require_authenticated, AuthState, SESSION_COOKIE};
|
||||
use crate::auth_middleware::{require_authenticated, AuthState};
|
||||
|
||||
pub fn auth_router(state: AuthState) -> Router {
|
||||
// /login + /logout are unguarded (login is how you get in; logout
|
||||
@@ -139,19 +143,8 @@ async fn login(State(state): State<AuthState>, Json(input): Json<LoginRequest>)
|
||||
tracing::warn!(?err, "failed to touch admin last_login_at");
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&build_cookie(&token.raw, state.ttl)).unwrap_or_else(|_| {
|
||||
// Cookie text is ASCII-clean by construction; this branch is
|
||||
// unreachable in practice but the type signature requires it.
|
||||
HeaderValue::from_static("")
|
||||
}),
|
||||
);
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
headers,
|
||||
Json(LoginResponse {
|
||||
user: AdminUserDto {
|
||||
id: user_row.id,
|
||||
@@ -167,23 +160,15 @@ async fn login(State(state): State<AuthState>, Json(input): Json<LoginRequest>)
|
||||
}
|
||||
|
||||
async fn logout(State(state): State<AuthState>, req: Request<Body>) -> Response {
|
||||
// Pull token without requiring a valid session (logout is idempotent
|
||||
// and we still want to clear the cookie on the client side).
|
||||
// Pull token without requiring a valid session (logout is idempotent).
|
||||
let token = extract_token_for_logout(&req);
|
||||
if let Some(raw) = token {
|
||||
let hash = hash_token(&raw);
|
||||
if let Err(err) = state.sessions.delete(&hash).await {
|
||||
tracing::error!(?err, "admin_sessions delete failed");
|
||||
// Still clear the cookie below.
|
||||
}
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_static("picloud_session=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0"),
|
||||
);
|
||||
(StatusCode::NO_CONTENT, headers).into_response()
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
|
||||
async fn me(
|
||||
@@ -213,51 +198,18 @@ async fn me(
|
||||
// Helpers
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
fn build_cookie(raw_token: &str, ttl: std::time::Duration) -> String {
|
||||
// Secure is on by default; flip to off for HTTP-only dev with
|
||||
// PICLOUD_COOKIE_SECURE=0. The header-injected bearer token works
|
||||
// either way, so this is purely for browsers that prefer the cookie
|
||||
// path (e.g., direct API hits without the dashboard's auth.ts).
|
||||
let secure = std::env::var("PICLOUD_COOKIE_SECURE").ok().is_none_or(|v| {
|
||||
!matches!(
|
||||
v.to_ascii_lowercase().as_str(),
|
||||
"0" | "false" | "no" | "off"
|
||||
)
|
||||
});
|
||||
let secure_attr = if secure { "; Secure" } else { "" };
|
||||
format!(
|
||||
"{SESSION_COOKIE}={raw_token}; HttpOnly{secure_attr}; SameSite=Lax; Path=/; Max-Age={}",
|
||||
ttl.as_secs()
|
||||
)
|
||||
}
|
||||
|
||||
fn extract_token_for_logout(req: &Request<Body>) -> Option<String> {
|
||||
// Same precedence as the middleware — Authorization first, cookie
|
||||
// fallback. Duplicated here because logout has to read the request
|
||||
// before any middleware would run.
|
||||
if let Some(value) = req.headers().get(header::AUTHORIZATION) {
|
||||
if let Ok(s) = value.to_str() {
|
||||
if let Some(token) = s.strip_prefix("Bearer ") {
|
||||
let trimmed = token.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
// Duplicated from auth_middleware::extract_token because logout runs
|
||||
// before the auth middleware (logout is idempotent and must accept
|
||||
// already-expired tokens). Cookie auth was dropped in the audit
|
||||
// 2026-06-11 C-1 fix — Bearer only.
|
||||
let value = req.headers().get(header::AUTHORIZATION)?;
|
||||
let s = value.to_str().ok()?;
|
||||
let token = s.strip_prefix("Bearer ")?.trim();
|
||||
if token.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Some(value) = req.headers().get(header::COOKIE) {
|
||||
if let Ok(s) = value.to_str() {
|
||||
for chunk in s.split(';') {
|
||||
let chunk = chunk.trim();
|
||||
if let Some(rest) = chunk.strip_prefix(&format!("{SESSION_COOKIE}=")) {
|
||||
if !rest.is_empty() {
|
||||
return Some(rest.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
Some(token.to_string())
|
||||
}
|
||||
|
||||
fn invalid_credentials() -> Response {
|
||||
|
||||
Reference in New Issue
Block a user