feat(auth): httpOnly session cookie with a CSRF check on writes
Groundwork for moving the dashboard token out of localStorage (#33), where any XSS in the dashboard could read it. - register, login and token-login also set the token as an HttpOnly, Secure, SameSite cookie; the JSON body keeps api_token for API clients - the API accepts the cookie when no bearer header is sent; bearer auth (bot, scripts, OpenAI-compatible clients) is unchanged and needs no CSRF token, since browsers never attach it on their own - cookie-authenticated unsafe methods must send X-CSRF-Token: an HMAC of the session token, so the server recomputes it without storing anything and a cross-site page cannot derive it (403 otherwise) - GET /auth/session returns the signed-in account and its CSRF token; logout also clears the cookie - CORS allows credentials for the explicit SOKHAN_CORS_ORIGINS list - AUTH_COOKIE_SECURE / _SAMESITE / _MAX_AGE_DAYS, documented in .env.example and passed through compose
This commit is contained in:
10 files changed
+266
-20
No files matched your search
@@ -94,6 +94,17 @@ MAX_UPLOAD_MB=200
|
||||
# (POST /admin/users/{email}/plan). Leave empty to disable the admin surface.
|
||||
ADMIN_API_KEY=
|
||||
|
||||
# --- Dashboard session cookie ---
|
||||
# The web dashboard signs in with an httpOnly cookie instead of keeping the
|
||||
# API token in localStorage. Secure cookies work on http://localhost; set
|
||||
# AUTH_COOKIE_SECURE=false only for a plain-http install on a LAN address.
|
||||
# Keep SameSite=lax while the web app and the API share a site
|
||||
# (app.example.com + api.example.com); use "none" (requires Secure) when
|
||||
# they live on different sites. SOKHAN_CORS_ORIGINS must list the web origin.
|
||||
AUTH_COOKIE_SECURE=true
|
||||
AUTH_COOKIE_SAMESITE=lax
|
||||
AUTH_COOKIE_MAX_AGE_DAYS=30
|
||||
|
||||
# --- LLM summaries (optional) ---
|
||||
# Any OpenAI-compatible chat-completions endpoint works.
|
||||
# Set SUMMARY_ENABLED=true and provide a key to turn summaries on.
|
||||
|
||||
@@ -5,6 +5,20 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Security
|
||||
|
||||
- Sign-in through the dashboard flows (register, login, connect code) now
|
||||
also sets the token as an `HttpOnly; Secure; SameSite=lax` session
|
||||
cookie, and the API accepts it in place of a bearer header. Every
|
||||
cookie-authenticated write must send the session's CSRF token in
|
||||
`X-CSRF-Token` (403 otherwise); the token is an HMAC of the session
|
||||
token, so nothing extra is stored. `GET /auth/session` returns the
|
||||
signed-in account and its CSRF token, and logout clears the cookie.
|
||||
Bearer auth (bot, API scripts, OpenAI-compatible clients) is unchanged
|
||||
and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE`,
|
||||
`AUTH_COOKIE_SAMESITE`, `AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows
|
||||
credentials for the configured `SOKHAN_CORS_ORIGINS` (#33).
|
||||
|
||||
### Added
|
||||
|
||||
- **Persian accuracy stack (v2)** — measured on the 12-clip Common Voice
|
||||
|
||||
@@ -1,29 +1,59 @@
|
||||
"""Shared FastAPI dependencies: database session, current user and admin key."""
|
||||
"""Shared FastAPI dependencies: database session, current user and admin key.
|
||||
|
||||
A request authenticates in one of two ways:
|
||||
|
||||
- `Authorization: Bearer <token>`: API clients, the bot and scripts. A
|
||||
browser never attaches this header on its own, so no CSRF check applies.
|
||||
- the httpOnly session cookie set at sign-in: the web dashboard. Browsers
|
||||
send it automatically, so every unsafe method must also carry the
|
||||
matching X-CSRF-Token header (see `sokhan.auth.csrf_token_for`).
|
||||
"""
|
||||
|
||||
import secrets
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sokhan.auth import token_hash
|
||||
from sokhan.auth import csrf_token_for, token_hash
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.db import get_db
|
||||
from sokhan.models import User
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
SESSION_COOKIE = "sokhan_session"
|
||||
CSRF_HEADER = "X-CSRF-Token"
|
||||
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||
|
||||
|
||||
def get_request_token(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
) -> str:
|
||||
"""The caller's raw token, from the bearer header or the session cookie.
|
||||
|
||||
Cookie-authenticated unsafe requests must send the CSRF token; a
|
||||
missing or wrong one is a 403 before the token is even looked up.
|
||||
"""
|
||||
if credentials is not None and credentials.credentials:
|
||||
return credentials.credentials
|
||||
token = request.cookies.get(SESSION_COOKIE)
|
||||
if not token:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
|
||||
if request.method not in _SAFE_METHODS:
|
||||
sent = request.headers.get(CSRF_HEADER, "")
|
||||
if not secrets.compare_digest(sent, csrf_token_for(token)):
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "missing or invalid CSRF token")
|
||||
return token
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
token: str = Depends(get_request_token),
|
||||
session: Session = Depends(get_db),
|
||||
) -> User:
|
||||
if credentials is None or not credentials.credentials:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
|
||||
user = session.scalar(
|
||||
select(User).where(User.token_hash == token_hash(credentials.credentials))
|
||||
)
|
||||
user = session.scalar(select(User).where(User.token_hash == token_hash(token)))
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid token")
|
||||
return user
|
||||
|
||||
@@ -8,6 +8,12 @@ Deliberately lightweight for v1:
|
||||
- POST /auth/token-login lets a user paste the connect code shown by the bot
|
||||
to link their browser session
|
||||
- POST /auth/logout revokes the caller's token
|
||||
- GET /auth/session tells the dashboard who is signed in
|
||||
|
||||
Sign-in through the web flows (register, login, token-login) also sets the
|
||||
token as an httpOnly session cookie, so the dashboard never has to keep it
|
||||
in script-readable storage. The JSON body still carries `api_token` for API
|
||||
clients and the bot.
|
||||
"""
|
||||
|
||||
import re
|
||||
@@ -17,11 +23,18 @@ from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sokhan.api.deps import get_current_user
|
||||
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
|
||||
from sokhan.api.deps import SESSION_COOKIE, get_current_user, get_request_token
|
||||
from sokhan.auth import (
|
||||
csrf_token_for,
|
||||
generate_token,
|
||||
hash_password,
|
||||
token_hash,
|
||||
verify_password,
|
||||
)
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.db import get_db
|
||||
from sokhan.models import User
|
||||
from sokhan.schemas import AuthResponse
|
||||
from sokhan.schemas import AuthResponse, SessionOut
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
@@ -61,8 +74,38 @@ def _validate_credentials(email: str, password: str) -> str:
|
||||
return email
|
||||
|
||||
|
||||
def _start_session(response: Response, user: User, token: str) -> AuthResponse:
|
||||
"""Set the httpOnly session cookie and answer with the CSRF token."""
|
||||
settings = get_settings()
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
max_age=settings.auth_cookie_max_age_days * 24 * 3600,
|
||||
path="/",
|
||||
httponly=True,
|
||||
secure=settings.auth_cookie_secure,
|
||||
samesite=settings.auth_cookie_samesite,
|
||||
)
|
||||
return AuthResponse(
|
||||
id=user.id, email=user.email, api_token=token, csrf_token=csrf_token_for(token)
|
||||
)
|
||||
|
||||
|
||||
def _end_session(response: Response) -> None:
|
||||
settings = get_settings()
|
||||
response.delete_cookie(
|
||||
SESSION_COOKIE,
|
||||
path="/",
|
||||
httponly=True,
|
||||
secure=settings.auth_cookie_secure,
|
||||
samesite=settings.auth_cookie_samesite,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/register", response_model=AuthResponse)
|
||||
def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def register(
|
||||
payload: Credentials, response: Response, session: Session = Depends(get_db)
|
||||
) -> AuthResponse:
|
||||
email = _validate_credentials(payload.email, payload.password)
|
||||
if session.scalar(select(User).where(User.email == email)):
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "email already registered")
|
||||
@@ -75,11 +118,13 @@ def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthRe
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=token)
|
||||
return _start_session(response, user, token)
|
||||
|
||||
|
||||
@router.post("/login", response_model=AuthResponse)
|
||||
def login(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def login(
|
||||
payload: Credentials, response: Response, session: Session = Depends(get_db)
|
||||
) -> AuthResponse:
|
||||
email = payload.email.strip().lower()
|
||||
user = session.scalar(select(User).where(User.email == email))
|
||||
if user is None or not verify_password(payload.password, user.password_hash):
|
||||
@@ -88,15 +133,29 @@ def login(payload: Credentials, session: Session = Depends(get_db)) -> AuthRespo
|
||||
token = generate_token()
|
||||
user.token_hash = token_hash(token)
|
||||
session.commit()
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=token)
|
||||
return _start_session(response, user, token)
|
||||
|
||||
|
||||
@router.post("/token-login", response_model=AuthResponse)
|
||||
def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def token_login(
|
||||
payload: TokenLogin, response: Response, session: Session = Depends(get_db)
|
||||
) -> AuthResponse:
|
||||
user = session.scalar(select(User).where(User.token_hash == token_hash(payload.api_token)))
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid connect code")
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
|
||||
return _start_session(response, user, payload.api_token)
|
||||
|
||||
|
||||
@router.get("/session", response_model=SessionOut)
|
||||
def current_session(
|
||||
user: User = Depends(get_current_user), token: str = Depends(get_request_token)
|
||||
) -> SessionOut:
|
||||
"""Who is signed in, plus the CSRF token for this session.
|
||||
|
||||
The dashboard cannot read its httpOnly cookie, so it asks here after a
|
||||
reload; a 401 means signed out.
|
||||
"""
|
||||
return SessionOut(id=user.id, email=user.email, csrf_token=csrf_token_for(token))
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -110,7 +169,9 @@ def logout(user: User = Depends(get_current_user), session: Session = Depends(ge
|
||||
"""
|
||||
user.token_hash = token_hash(generate_token())
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
response = Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
_end_session(response)
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/telegram", response_model=AuthResponse)
|
||||
|
||||
@@ -40,3 +40,13 @@ def generate_token() -> str:
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def csrf_token_for(token: str) -> str:
|
||||
"""The CSRF token bound to a session token (stateless double submit).
|
||||
|
||||
It is an HMAC keyed by the session token itself, so the server can
|
||||
recompute it from the cookie without storing anything, and a cross-site
|
||||
page that cannot read the cookie cannot derive it either.
|
||||
"""
|
||||
return hmac.new(token.encode("utf-8"), b"sokhan-csrf-v1", hashlib.sha256).hexdigest()
|
||||
@@ -74,6 +74,15 @@ class Settings(BaseSettings):
|
||||
# Leave empty to disable the admin endpoints entirely.
|
||||
admin_api_key: str = ""
|
||||
|
||||
# Dashboard session cookie (httpOnly). Secure by default: browsers still
|
||||
# accept it on http://localhost, so only plain-http LAN installs need
|
||||
# AUTH_COOKIE_SECURE=false. SameSite=lax works whenever the web app and
|
||||
# the API share a site (localhost:3000 + localhost:8000, or
|
||||
# app.example.com + api.example.com); different sites need "none".
|
||||
auth_cookie_secure: bool = True
|
||||
auth_cookie_samesite: str = "lax"
|
||||
auth_cookie_max_age_days: int = 30
|
||||
|
||||
# LLM summaries (optional, behind a feature flag)
|
||||
summary_enabled: bool = False
|
||||
llm_api_base: str = ""
|
||||
|
||||
@@ -55,7 +55,9 @@ def create_app() -> FastAPI:
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
allow_credentials=False,
|
||||
# The dashboard's session cookie rides on credentialed requests; the
|
||||
# origins above are an explicit list, never a wildcard.
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@@ -9,6 +9,15 @@ class AuthResponse(BaseModel):
|
||||
id: str
|
||||
email: str
|
||||
api_token: str
|
||||
# Sent back as X-CSRF-Token on cookie-authenticated writes; absent for
|
||||
# flows that set no cookie (the Telegram bot).
|
||||
csrf_token: str | None = None
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
id: str
|
||||
email: str
|
||||
csrf_token: str
|
||||
|
||||
|
||||
class JobCreated(BaseModel):
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""httpOnly cookie sessions for the dashboard, with CSRF on writes (#33)."""
|
||||
|
||||
import pytest
|
||||
from sokhan.auth import csrf_token_for
|
||||
from sokhan.config import get_settings
|
||||
|
||||
CREDENTIALS = {"email": "nima@example.com", "password": "parool-1234"}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def cookie_client(client, monkeypatch):
|
||||
"""The test client speaks plain http, which never sends Secure cookies."""
|
||||
monkeypatch.setenv("AUTH_COOKIE_SECURE", "false")
|
||||
get_settings.cache_clear()
|
||||
return client
|
||||
|
||||
|
||||
def _sign_in(client) -> dict:
|
||||
client.post("/auth/register", json=CREDENTIALS)
|
||||
return client.post("/auth/login", json=CREDENTIALS).json()
|
||||
|
||||
|
||||
def test_login_sets_an_httponly_session_cookie(cookie_client):
|
||||
response = cookie_client.post("/auth/register", json=CREDENTIALS)
|
||||
|
||||
cookie = response.headers["set-cookie"]
|
||||
assert cookie.startswith("sokhan_session=")
|
||||
assert "HttpOnly" in cookie
|
||||
assert "SameSite=lax" in cookie
|
||||
body = response.json()
|
||||
assert body["csrf_token"] == csrf_token_for(body["api_token"])
|
||||
|
||||
|
||||
def test_cookie_is_secure_by_default(client):
|
||||
cookie = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"]
|
||||
assert "Secure" in cookie
|
||||
|
||||
|
||||
def test_cookie_authenticates_reads_without_a_bearer_header(cookie_client):
|
||||
_sign_in(cookie_client)
|
||||
|
||||
assert cookie_client.get("/quota").status_code == 200
|
||||
session = cookie_client.get("/auth/session")
|
||||
assert session.status_code == 200
|
||||
assert session.json()["email"] == CREDENTIALS["email"]
|
||||
|
||||
|
||||
def test_cookie_writes_need_the_csrf_header(cookie_client):
|
||||
body = _sign_in(cookie_client)
|
||||
|
||||
missing = cookie_client.post("/auth/logout")
|
||||
wrong = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": "forged"})
|
||||
|
||||
assert missing.status_code == 403
|
||||
assert wrong.status_code == 403
|
||||
# The session survived both forged attempts.
|
||||
assert cookie_client.get("/quota").status_code == 200
|
||||
|
||||
ok = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": body["csrf_token"]})
|
||||
assert ok.status_code == 204
|
||||
|
||||
|
||||
def test_logout_clears_the_cookie_and_revokes_the_token(cookie_client):
|
||||
body = _sign_in(cookie_client)
|
||||
|
||||
response = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": body["csrf_token"]})
|
||||
|
||||
assert 'sokhan_session=""' in response.headers["set-cookie"]
|
||||
assert cookie_client.get("/auth/session").status_code == 401
|
||||
bearer = {"Authorization": f"Bearer {body['api_token']}"}
|
||||
assert cookie_client.get("/quota", headers=bearer).status_code == 401
|
||||
|
||||
|
||||
def test_bearer_clients_need_no_csrf_token(client):
|
||||
token = client.post("/auth/register", json=CREDENTIALS).json()["api_token"]
|
||||
client.cookies.clear()
|
||||
bearer = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
assert client.get("/auth/session", headers=bearer).status_code == 200
|
||||
assert client.post("/auth/logout", headers=bearer).status_code == 204
|
||||
|
||||
|
||||
def test_session_without_any_credentials_is_401(client):
|
||||
assert client.get("/auth/session").status_code == 401
|
||||
|
||||
|
||||
def test_telegram_flow_sets_no_cookie(client, monkeypatch):
|
||||
monkeypatch.setenv("BOT_API_SECRET", "s3cret")
|
||||
get_settings.cache_clear()
|
||||
|
||||
response = client.post(
|
||||
"/auth/telegram", json={"telegram_id": 7}, headers={"X-Bot-Secret": "s3cret"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "set-cookie" not in response.headers
|
||||
assert response.json()["csrf_token"] is None
|
||||
@@ -53,6 +53,9 @@ services:
|
||||
PLAN_PRO_MAX_FILE_MINUTES: ${PLAN_PRO_MAX_FILE_MINUTES:-180}
|
||||
PLAN_PRO_MONTHLY_MINUTES: ${PLAN_PRO_MONTHLY_MINUTES:-1200}
|
||||
ADMIN_API_KEY: ${ADMIN_API_KEY:-}
|
||||
AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-true}
|
||||
AUTH_COOKIE_SAMESITE: ${AUTH_COOKIE_SAMESITE:-lax}
|
||||
AUTH_COOKIE_MAX_AGE_DAYS: ${AUTH_COOKIE_MAX_AGE_DAYS:-30}
|
||||
MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200}
|
||||
SUMMARY_ENABLED: ${SUMMARY_ENABLED:-false}
|
||||
LLM_API_BASE: ${LLM_API_BASE:-}
|
||||
|
||||
Reference in new issue
Block a user