Add sessions, login, logout and CSRF (REVIEW SEC-007)

The three endpoints web/src/auth/AuthProvider.tsx was written against. It
already distinguishes 404 ("this server has no auth at all", show a banner)
from 401 ("not signed in"), so these landing is what makes the banner go away.

Cookies with server-side state, not JWTs, and the reason is revocation. Signing
someone out, or ending every session when a password changes, has to take
effect on the next request. A self-contained token cannot be withdrawn before
it expires without a deny-list, which is the database lookup it was meant to
avoid. So logout DELETEs the row and the old cookie is dead immediately.

The cookie is not the primary key. sessions.id stays internal and the browser
carries a separate 64-hex token of which only the SHA-256 is stored, exactly as
device tokens work. Using the id would have been simpler and would mean a
database dump handed over every live session.

CSRF is a per-session token, checked in middleware rather than per route so a
new endpoint cannot forget it. Two decisions worth keeping:

  - It triggers only on unsafe methods for requests that CARRY THE SESSION
    COOKIE. Device endpoints authenticate with a bearer token and send no
    cookies, so /ingest is untouched - a camera has no way to obtain a CSRF
    token and blocking it would take the whole system down. Login is exempt by
    the same rule, with no special case: there is no session cookie yet.
  - The header is compared against the token on the session row, not against
    the CSRF cookie. Plain double-submit accepts any self-consistent pair, so
    anyone able to write a cookie on the domain can satisfy it while the
    victim's session cookie rides along. Binding it to the session means they
    would also need a value they cannot read.

Login answers every failure identically - same status, same body - because
"no such user" confirms which accounts exist and "wrong code" confirms the
password was right. It also hashes the submitted password when the username
does not exist, so a missing user is not measurably faster than a wrong
password; that timing difference is a username oracle.

Failed logins are audited, not just successful ones. A log of only the
successes cannot answer the question worth asking afterwards.

Rate limited by address rather than by username. Keying on the username would
let someone lock a known account out by failing at it deliberately, turning the
protection into a denial of service against the person it protects.

session_cookie_secure is a setting rather than a constant for one reason worth
writing down: a Secure cookie is silently discarded over http, so with it
hardcoded true every local login would return 200 and never sign anyone in,
with nothing in any log. The tests hit the same trap through http://testserver.

--- and the migration baseline had to be frozen to do any of this ---

0001 called Base.metadata.create_all(). That could not drift from the models,
which was its purpose, but it also meant a fresh database got the *current*
models from 0001 and then had every later migration applied on top of what it
had just created. The first migration added after it therefore failed with
"column token_hash of relation sessions already exists" - not on this machine,
where the columns were added incrementally, but on any clean one.

tests/test_schema_matches_models.py caught it immediately, which is the only
reason it did not reach a deployment. It is also the reason this is fixed now
rather than at the next schema change: the problem gets worse with every
revision added on top of it.

So 0001 is now explicit DDL for the schema as it stood at the end of Phase 1,
generated against an empty database with the new columns temporarily removed
from the model, and it says at the top not to edit it for a model change.
Verified on a fresh database: upgrade to head, downgrade to base, upgrade
again, alembic check clean at each end.

Also: the suite was leaking audit rows. audit_log.user_id is ON DELETE SET NULL
on purpose, and a failed login for a username that never existed writes NULL
from the start, so no user-scoped cleanup could ever match it - seven runs had
quietly left eight rows behind. Swept by id high-water mark now. Two
consecutive suite runs leave zero users, zero sessions, zero audit rows and
zero jobs.

Verified against a real uvicorn as well as the test client: 401 before login,
200 with both cookies and the right HttpOnly flags, 403 on logout without the
CSRF header with the session still alive afterwards, 204 with it, 401 after.

Mutation-tested the three properties this commit claims: comparing CSRF against
the cookie instead of the session, dropping the expiry check, and dropping the
TOTP requirement each failed exactly the tests written for them.

Tests: 221 -> 257.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Thomas KarnerandClaude Opus 5 committed 2026-09-21 18:17:29 +02:00
1 parent 9c44ab6b2a
commit 0c3fb2d837
16 files changed
+1796 -21

No files matched your search

+12 -1
View File
@@ -8,7 +8,8 @@ from fastapi import FastAPI
from .. import __version__
from ..config import get_settings
from ..logging_setup import configure_logging
from .routes import commands, conditions, device_config, enroll, firmware, health, ingest
from .routes import auth, commands, conditions, device_config, enroll, firmware, health, ingest
from .userauth import csrf_middleware
log = logging.getLogger(__name__)
@@ -41,9 +42,19 @@ def create_app() -> FastAPI:
lifespan=lifespan,
)
# CSRF for cookie-authenticated mutations. Middleware rather than a
# per-route dependency so a new endpoint cannot forget it; it applies only
# to unsafe methods on requests that carry the session cookie, which is why
# the device endpoints -- bearer tokens, no cookies -- are unaffected. See
# userauth.csrf_middleware.
app.middleware("http")(csrf_middleware)
app.include_router(health.router, prefix=API_PREFIX, tags=["health"])
app.include_router(health.root_router)
# Phase 3 WebUI endpoints.
app.include_router(auth.router, prefix=API_PREFIX)
# Phase 2 device endpoints. See firmware/API.md for the contract.
app.include_router(enroll.router, prefix=API_PREFIX)
app.include_router(conditions.router, prefix=API_PREFIX)
+10
View File
@@ -189,3 +189,13 @@ ACK = Limit.per_minute(30, burst=15)
# Whole firmware images. Expensive to serve, and a device needs one rarely;
# a loop here would be a device failing verification over and over.
FIRMWARE = Limit.per_hour(12, burst=3)
# --- people -----------------------------------------------------------------
# Login is the one endpoint where the secret is human-chosen and therefore
# guessable, so this is a real control rather than abuse protection. A person
# mistyping a password needs a handful of tries in quick succession; nobody
# needs sixty an hour. Argon2 already makes each attempt cost tens of
# milliseconds of CPU, which is itself a reason to cap the rate: without this,
# the login endpoint is also the cheapest way to spend the server's CPU.
LOGIN = Limit.per_hour(30, burst=8)
+216
View File
@@ -0,0 +1,216 @@
"""Sign in, sign out, and "who am I" (SPEC 3.1, REVIEW SEC-007).
The three endpoints ``web/src/auth/AuthProvider.tsx`` was written against, and
the ones it distinguishes carefully: a 404 there means "the server has no auth
yet" and shows a banner, whereas a 401 means "not signed in". Now that these
exist, 404 stops happening and the banner goes away.
There is no registration endpoint, on purpose. Accounts come from
``poorbird user add`` -- see the note in cli.py.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ...models import AuditLog, User
from ...passwords import hash_password, needs_rehash, verify_password
from ...totp import verify as verify_totp
from .. import ratelimit
from ..deps import DbDep, SettingsDep
from ..ratelimit import client_address
from ..sessions import (
SESSION_COOKIE,
clear_session_cookies,
create_session,
resolve_session,
revoke_session,
set_session_cookies,
)
from ..ui_schemas import LoginRequest, SessionUser
from ..userauth import SessionDep
log = logging.getLogger(__name__)
router = APIRouter(prefix="/auth", tags=["auth"])
def _as_session_user(user: User) -> SessionUser:
return SessionUser(
id=user.id,
username=user.username,
role=user.role,
locale=user.locale,
theme=user.theme,
)
def _audit(
db: DbSession,
*,
action: str,
user_id: int | None,
ip: str | None,
detail: dict | None = None,
) -> None:
"""Record an auth event (SPEC 3.1: audit_log on every mutation).
Failed attempts are recorded as well as successful ones. A log of only the
successes cannot answer the one question worth asking afterwards, which is
how many times someone tried before getting in.
"""
db.add(
AuditLog(
user_id=user_id,
action=action,
entity="session",
entity_id=str(user_id) if user_id is not None else None,
after=detail,
ip=ip[:45] if ip else None,
)
)
@router.post(
"/login",
response_model=SessionUser,
summary="Sign in and open a session",
# By address, not by username: keying on the username would let an attacker
# lock a known account out by failing at it deliberately, turning a rate
# limit into a denial of service against exactly the person it protects.
dependencies=[Depends(ratelimit.by_address("login", ratelimit.LOGIN))],
)
def login(
body: LoginRequest,
request: Request,
response: Response,
db: DbDep,
settings: SettingsDep,
) -> SessionUser:
"""Verify a password and optional TOTP code, then set the session cookies.
Every failure answers with the same 401 and the same message. Saying "no
such user" would confirm which usernames exist, and saying "wrong code"
would confirm that the password was right -- which is most of what an
attacker wanted to know.
"""
ip = client_address(request)
rejected = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid credentials",
)
user = db.scalar(select(User).where(User.username == body.username))
# Verify against a hash even when there is no such user, by hashing the
# submitted password and throwing it away. Returning early would make a
# missing username measurably faster than a wrong password, which is a
# username oracle built out of timing.
stored = user.password_hash if user is not None else hash_password(body.password)
password_ok = verify_password(body.password, stored)
if user is None or not password_ok:
_audit(
db,
action="login_failed",
user_id=user.id if user is not None else None,
ip=ip,
detail={"username": body.username, "reason": "credentials"},
)
db.commit()
log.warning("login failed", extra={"username": body.username, "ip": ip})
raise rejected
if not user.is_active:
_audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "inactive"})
db.commit()
log.warning("login refused, account inactive", extra={"username": user.username, "ip": ip})
raise rejected
# TOTP is required exactly when the account has a secret. The policy that
# admins must have one is enforced at account creation (cli.py), not here:
# enforcing it at login would let the only admin be locked out by their own
# account, with no way back in through the UI.
if user.totp_secret and not verify_totp(user.totp_secret, body.totp):
_audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "totp"})
db.commit()
log.warning("login failed on second factor", extra={"username": user.username, "ip": ip})
raise rejected
# Login is the only moment the plaintext password exists, so it is the only
# moment the hash can be upgraded to current parameters.
if needs_rehash(user.password_hash or ""):
user.password_hash = hash_password(body.password)
log.info("password hash upgraded", extra={"username": user.username})
token, csrf = create_session(
db,
user,
settings=settings,
ip=ip,
user_agent=request.headers.get("user-agent"),
)
user.last_login_at = datetime.now(UTC)
_audit(db, action="login", user_id=user.id, ip=ip, detail={"totp": bool(user.totp_secret)})
db.commit()
set_session_cookies(response, token, csrf, settings=settings)
log.info("login", extra={"username": user.username, "role": user.role, "ip": ip})
return _as_session_user(user)
@router.post(
"/logout",
status_code=status.HTTP_204_NO_CONTENT,
summary="End the current session",
)
def logout(
request: Request,
response: Response,
db: DbDep,
settings: SettingsDep,
) -> None:
"""Delete the session row and clear both cookies.
Deliberately succeeds whether or not there was a session. Signing out is
something a client should always be able to do, and a 401 here would leave a
browser holding a cookie it cannot get rid of.
The row is deleted rather than flagged, which is what makes this immediate:
the next request cannot resolve a session that is gone. That is the whole
reason sessions are server-side rather than a self-contained token.
"""
token = request.cookies.get(SESSION_COOKIE)
resolved = resolve_session(db, token) if token else None
revoke_session(db, token)
if resolved is not None:
_audit(db, action="logout", user_id=resolved[1].id, ip=client_address(request))
log.info("logout", extra={"username": resolved[1].username})
db.commit()
# Cookies are set on the injected Response, whose headers FastAPI merges
# into the 204 it sends. Returning a fresh Response here instead would
# discard them, and the logout would appear to work without clearing
# anything.
clear_session_cookies(response, settings=settings)
@router.get(
"/session",
response_model=SessionUser,
summary="The signed-in user, or 401",
)
def whoami(resolved: SessionDep) -> SessionUser:
"""401 when not signed in, which the UI treats as "anonymous".
Not 200-with-null: the client already distinguishes 401 (signed out) from
404 (no auth on this server), and a 200 carrying null would collapse a
working server into the same shape as one that has no auth at all.
"""
return _as_session_user(resolved[1])
+181
View File
@@ -0,0 +1,181 @@
"""Server-side sessions for the WebUI (SPEC 3.1, REVIEW SEC-007).
Cookies, not JWTs, and the session state lives in Postgres. The reason is
revocation: signing a user out, or ending every session when their password
changes, has to take effect immediately. A self-contained token cannot be
withdrawn before it expires without keeping a deny-list, which is the database
lookup it was supposed to avoid.
The cookie value is a 64-hex token; only its SHA-256 is stored. It reuses
``deps.new_credential``/``hash_credential`` rather than growing a second
implementation of the same idea -- device tokens and session tokens have the
same shape and the same reasoning behind a fast hash: both are CSPRNG output,
not passwords.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime, timedelta
from fastapi import Response
from sqlalchemy import delete, select
from sqlalchemy.orm import Session as DbSession
from ..config import Settings
from ..models import Session as UserSession
from ..models import User
from .deps import hash_credential, new_credential
log = logging.getLogger(__name__)
SESSION_COOKIE = "poorbird_session"
CSRF_COOKIE = "poorbird_csrf"
CSRF_HEADER = "x-csrf-token"
# Lax, not Strict. Strict would also suppress the cookie when someone follows
# an ordinary link into the app from anywhere else, so they arrive apparently
# signed out and sign in again for no reason. Lax still withholds the cookie
# from cross-site POST, which is the CSRF case that matters, and the per-session
# token below covers the rest.
SAMESITE = "lax"
def create_session(
db: DbSession,
user: User,
*,
settings: Settings,
ip: str | None = None,
user_agent: str | None = None,
) -> tuple[str, str]:
"""Open a session for ``user``. Returns ``(session_token, csrf_token)``.
Both are returned in plaintext exactly once, here, and only hashes or
per-session values are persisted. The caller is responsible for putting
them in cookies and for committing.
"""
token = new_credential()
csrf = new_credential()
db.add(
UserSession(
user_id=user.id,
token_hash=hash_credential(token),
csrf_token=csrf,
expires_at=datetime.now(UTC) + timedelta(hours=settings.session_lifetime_h),
# Truncated to the column width rather than allowed to raise: a
# long or hostile User-Agent must not be able to fail a login.
ip=ip[:45] if ip else None,
user_agent=user_agent[:255] if user_agent else None,
)
)
db.flush()
return token, csrf
def resolve_session(db: DbSession, token: str | None) -> tuple[UserSession, User] | None:
"""Look up a live session and its user, or None.
None covers every failure the caller should treat identically: no cookie, an
unknown token, an expired session, a deleted or deactivated user. They are
deliberately not distinguished in the return value -- the endpoint answers
401 for all of them, because telling a caller *which* one it was is telling
them whether a token was ever real.
"""
if not token:
return None
row = db.execute(
select(UserSession, User)
.join(User, User.id == UserSession.user_id)
.where(UserSession.token_hash == hash_credential(token))
).first()
if row is None:
return None
session, user = row
if session.expires_at <= datetime.now(UTC):
# Clear it out on the way past. Nothing else would, between the
# scheduled purge below and the row's own irrelevance.
db.delete(session)
db.commit()
return None
if not user.is_active:
return None
return session, user
def revoke_session(db: DbSession, token: str | None) -> None:
"""End one session. Idempotent: signing out twice is not an error."""
if not token:
return
db.execute(delete(UserSession).where(UserSession.token_hash == hash_credential(token)))
def revoke_all_for_user(db: DbSession, user_id: int) -> int:
"""End every session for one user, and return how many.
Used when a password changes: otherwise the old credential keeps working
through any browser that is already signed in, which is usually the reason
it was changed.
"""
result = db.execute(delete(UserSession).where(UserSession.user_id == user_id))
return result.rowcount or 0
# Deleting expired rows is deliberately *not* here. Expiry is enforced on read
# above, so a leftover row is inert, and the sweep is a scheduled job -- it
# lives with the worker's other housekeeping in worker/handlers.py. Putting it
# here would mean the worker importing from api/, which is the wrong way round
# for the same reason images.py sits at the package root.
# --- cookies ----------------------------------------------------------------
def set_session_cookies(response: Response, token: str, csrf: str, *, settings: Settings) -> None:
"""Attach both cookies to a login response.
The session cookie is HttpOnly so script cannot read it. The CSRF cookie
deliberately is **not**: the whole mechanism depends on the app's own
JavaScript reading it and echoing it in a header, which an attacker on
another origin cannot do.
"""
max_age = settings.session_lifetime_h * 3600
response.set_cookie(
SESSION_COOKIE,
token,
max_age=max_age,
httponly=True,
secure=settings.session_cookie_secure,
samesite=SAMESITE,
path="/",
)
response.set_cookie(
CSRF_COOKIE,
csrf,
max_age=max_age,
httponly=False,
secure=settings.session_cookie_secure,
samesite=SAMESITE,
path="/",
)
def clear_session_cookies(response: Response, *, settings: Settings) -> None:
"""Remove both cookies.
The attributes have to match the ones they were set with or the browser
treats it as a different cookie and leaves the original in place -- a logout
that appears to work and does not.
"""
for name, httponly in ((SESSION_COOKIE, True), (CSRF_COOKIE, False)):
response.delete_cookie(
name,
httponly=httponly,
secure=settings.session_cookie_secure,
samesite=SAMESITE,
path="/",
)
+53
View File
@@ -0,0 +1,53 @@
"""Request and response shapes for the WebUI (Phase 3).
Separate from ``schemas.py``, which is the device contract in
``firmware/API.md`` and is not free to change. These are ours on both sides: the
server and ``web/`` are versioned together and ship together, so a field can be
renamed here in one commit.
The shapes are pinned to what ``web/src/auth/AuthProvider.tsx`` already expects,
because the scaffold was written first and there is no reason to make it move.
"""
from __future__ import annotations
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field
from ..models.users import ROLES, THEMES
Role = Literal[ROLES] # type: ignore[valid-type]
Theme = Literal[THEMES] # type: ignore[valid-type]
class LoginRequest(BaseModel):
model_config = ConfigDict(extra="ignore")
# Bounded, but not validated against a character set. Usernames are matched
# exactly against the database, so there is nothing to sanitise; a length cap
# is here only so an enormous body cannot reach Argon2.
username: Annotated[str, Field(min_length=1, max_length=64)]
# The password floor lives in passwords.validate_password_strength and is
# applied when a password is *set*. Applying it here too would refuse to
# even check a password that predates the rule, which is a lockout rather
# than a policy. Only an upper bound, matching MAX_PASSWORD_LENGTH.
password: Annotated[str, Field(min_length=1, max_length=1024)]
# Six digits when the account has TOTP. Absent, not empty, when it does not.
totp: Annotated[str | None, Field(max_length=16)] = None
class SessionUser(BaseModel):
"""What ``GET /auth/session`` and ``POST /auth/login`` both return.
Deliberately small. It is what the UI needs to render a shell and make role
decisions, and nothing else -- no email, no TOTP state, no password
metadata. A response shape is a place things accumulate, and the browser is
where they end up.
"""
id: int
username: str
role: Role
locale: str
theme: Theme
+153
View File
@@ -0,0 +1,153 @@
"""User authentication and authorization for the WebUI.
Separate from ``deps.py`` on purpose. That file is device auth: bearer tokens,
no cookies, no CSRF, and a 401 there means "clear your token and re-enroll".
This file is people: session cookies, CSRF, and roles. Mixing them is how a
device ends up able to read the gallery, which SPEC 3.1 forbids outright.
"""
from __future__ import annotations
import logging
import secrets
from typing import Annotated
from fastapi import Depends, HTTPException, Request, status
from ..models import Session as UserSession
from ..models import User
from .deps import DbDep
from .ratelimit import client_address
from .sessions import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE, resolve_session
log = logging.getLogger(__name__)
# Methods that can change state. A GET must never need CSRF, and must never
# change anything -- if one did, no CSRF scheme would protect it.
UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
_UNAUTHENTICATED = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="not signed in",
)
def current_session(request: Request, db: DbDep) -> tuple[UserSession, User]:
"""Resolve the session cookie to a live session and user, or 401."""
resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE))
if resolved is None:
raise _UNAUTHENTICATED
return resolved
def current_user(
resolved: Annotated[tuple[UserSession, User], Depends(current_session)],
) -> User:
return resolved[1]
SessionDep = Annotated[tuple[UserSession, User], Depends(current_session)]
CurrentUser = Annotated[User, Depends(current_user)]
def require_role(*roles: str):
"""Dependency factory: allow only these roles (SPEC 3.1).
``admin`` is not implicitly granted everything -- each route names the roles
it accepts, so widening one route cannot silently widen another. Where admin
should be included, it is listed.
403, not 404: the caller is authenticated, and pretending the route does not
exist would only make a permission problem look like a bug.
"""
def guard(user: CurrentUser) -> User:
if user.role not in roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"requires one of: {', '.join(sorted(roles))}",
)
return user
return guard
# --- CSRF -------------------------------------------------------------------
async def csrf_middleware(request: Request, call_next):
"""Reject mutating cookie-authenticated requests without a valid CSRF token.
Applied as middleware rather than per-route so a new endpoint cannot forget
it. The condition is what keeps it correct:
* Only unsafe methods. A GET needing this would mean a GET that mutates.
* Only requests that **carry the session cookie**. Device endpoints
authenticate with a bearer token and never send cookies, so they are
untouched -- which matters, because a camera has no way to obtain a CSRF
token and blocking /ingest would take the whole system down.
* Logging in is therefore exempt without a special case: there is no session
cookie yet. Logging out is not exempt, and should not be -- an attacker
signing someone out is a nuisance worth preventing.
The header is compared against the token stored on the session row, not
merely against the cookie. Plain double-submit would let an attacker who can
write a cookie on the domain set both sides to a value they chose; the
victim's session token, which they cannot read, is what they would also
need.
"""
if request.method not in UNSAFE_METHODS or SESSION_COOKIE not in request.cookies:
return await call_next(request)
presented = request.headers.get(CSRF_HEADER)
if not presented:
return _csrf_failure(request, "missing")
# Middleware runs outside the dependency system, so it opens its own
# session. This is one indexed lookup, on mutating requests only.
from ..db import SessionLocal
with SessionLocal() as db:
resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE))
if resolved is None:
# Not signed in after all. Let the route's own dependency produce
# the 401, so the answer stays consistent with every other route.
return await call_next(request)
session, _user = resolved
if not secrets.compare_digest(presented, session.csrf_token):
return _csrf_failure(request, "mismatch")
return await call_next(request)
def _csrf_failure(request: Request, why: str):
from fastapi.responses import JSONResponse
log.warning(
"csrf check failed",
extra={
"reason": why,
"path": request.url.path,
"method": request.method,
"ip": client_address(request),
},
)
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={
"detail": (
f"CSRF token {why}. Send the value of the {CSRF_COOKIE} cookie "
f"in the {CSRF_HEADER} header."
)
},
)
__all__ = [
"CurrentUser",
"SessionDep",
"csrf_middleware",
"current_session",
"current_user",
"require_role",
]
+13
View File
@@ -72,6 +72,19 @@ class Settings(BaseSettings):
# refuse to serve without it.
enroll_secret: SecretStr = SecretStr("")
# --- user sessions (Phase 3) ------------------------------------------
# SPEC 3.4 lists session lifetime as a UI-editable server setting. It lives
# here until the settings UI exists; promoting it to the settings table then
# is a read, not a redesign.
session_lifetime_h: int = 24 * 14
# Secure cookies require HTTPS, which Caddy always terminates in production.
# It must be false for local development, because the Vite dev server is
# plain http on localhost and a Secure cookie is silently dropped there --
# which presents as "login succeeds but I am never signed in", with nothing
# in any log. Hence a setting rather than a hardcoded True.
session_cookie_secure: bool = True
# --- rate limiting ----------------------------------------------------
# In-process token buckets (api/ratelimit.py), sized for one uvicorn
# process. Off by default in tests, which would otherwise exhaust a
+18
View File
@@ -51,10 +51,28 @@ class User(Base):
class Session(Base):
"""A signed-in browser.
``id`` is internal and never leaves the server. The cookie carries a
separate high-entropy token of which only the SHA-256 is stored, exactly as
device tokens work (api/deps.py). Using ``id`` as the cookie value would be
simpler and would mean a database dump handed over every live session.
``csrf_token`` is per session rather than global, so the double-submit check
cannot be satisfied by an attacker who can merely set a cookie on the
domain -- they would also need this session's token, which is what they do
not have.
"""
__tablename__ = "sessions"
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
# SHA-256 hex of the cookie value. Unique so a collision is a constraint
# error rather than two users sharing a session, and indexed because this
# is the lookup on every authenticated request.
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
csrf_token: Mapped[str] = mapped_column(String(64))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
ip: Mapped[str | None] = mapped_column(String(45))
+18 -1
View File
@@ -12,15 +12,17 @@ from __future__ import annotations
import logging
import uuid
from collections.abc import Callable
from datetime import UTC, datetime
from typing import Any
from pydantic import BaseModel, ValidationError
from sqlalchemy import text
from sqlalchemy import delete, text
from sqlalchemy.orm import Session
from ..config import get_settings
from ..images import UndecodableImage, make_thumbnail, relative_thumb_path, write_atomically
from ..models import Capture
from ..models import Session as UserSession
log = logging.getLogger(__name__)
@@ -114,6 +116,21 @@ def _thumbnail(session: Session, payload: dict[str, Any]) -> None:
)
@handler("purge_expired_sessions")
def _purge_expired_sessions(session: Session, payload: dict[str, Any]) -> None:
"""Delete expired WebUI sessions.
Housekeeping, not security: expiry is already enforced on every read
(api/sessions.resolve_session), so a row left here is inert and cannot
authenticate anything. This only stops the table growing for as long as the
server runs.
"""
result = session.execute(delete(UserSession).where(UserSession.expires_at <= datetime.now(UTC)))
session.commit()
if result.rowcount:
log.info("purged expired sessions", extra={"count": result.rowcount})
@handler("prune_expired_commands")
def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None:
"""Expire commands the device never came back for.
+11
View File
@@ -69,6 +69,17 @@ def _build_scheduler() -> BackgroundScheduler:
coalesce=True,
)
# Hourly is plenty: expired sessions are already refused on read, so this
# is only stopping the table from growing.
scheduler.add_job(
lambda: _enqueue("purge_expired_sessions"),
"interval",
hours=1,
id="purge_expired_sessions",
max_instances=1,
coalesce=True,
)
def _reclaim() -> None:
with SessionLocal() as session:
queue.requeue_stale(session)