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>
202 lines
7.4 KiB
Python
202 lines
7.4 KiB
Python
"""Rate limiting (REVIEW SEC-004).
|
|
|
|
A token bucket per key, held in memory. No Redis and no slowapi, for the same
|
|
reason the job queue has no Redis (SPEC C8): this deployment is one uvicorn
|
|
process serving a handful of cameras on a LAN, and slowapi's default storage
|
|
is in-process anyway, so a dependency would buy convenience rather than
|
|
capability.
|
|
|
|
**That is an assumption with a name.** ``poorbird serve`` runs a single
|
|
uvicorn process (cli.py passes no ``workers``). If the deployment ever gains
|
|
workers, every worker gets its own buckets and the effective limit multiplies
|
|
by the worker count. Move the state to PostgreSQL or Redis at that point --
|
|
do not just widen the numbers.
|
|
|
|
Buckets allow a burst and then refill steadily, which is the right shape
|
|
here: a camera uploads three to five frames back to back when the radar
|
|
fires, then goes quiet. A fixed window would reject the tail of a legitimate
|
|
burst that happened to straddle a boundary.
|
|
|
|
The limits are deliberately loose. A throttled camera stops delivering
|
|
photographs, which on a private LAN is a worse outcome than the flooding the
|
|
limit is meant to prevent. These are here to stop something pathological --
|
|
a wedged device in a retry loop, or someone grinding at the enrollment
|
|
secret -- not to police normal use.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
from collections import OrderedDict
|
|
from dataclasses import dataclass
|
|
|
|
from fastapi import HTTPException, Request, status
|
|
|
|
from ..config import Settings
|
|
from .deps import DeviceDep, SettingsDep
|
|
|
|
# Enough for a LAN's worth of cameras and then some. Bounded because the
|
|
# enrollment limiter keys on client address, and an unbounded dictionary
|
|
# keyed by something a caller influences is itself a way to exhaust memory.
|
|
MAX_TRACKED_KEYS = 4096
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Limit:
|
|
"""``capacity`` requests available at once, refilled at ``per_second``."""
|
|
|
|
capacity: int
|
|
per_second: float
|
|
|
|
@classmethod
|
|
def per_minute(cls, rate: int, *, burst: int | None = None) -> Limit:
|
|
return cls(capacity=burst or rate, per_second=rate / 60.0)
|
|
|
|
@classmethod
|
|
def per_hour(cls, rate: int, *, burst: int | None = None) -> Limit:
|
|
return cls(capacity=burst or rate, per_second=rate / 3600.0)
|
|
|
|
|
|
class TokenBuckets:
|
|
"""Thread-safe token buckets with an LRU bound.
|
|
|
|
Handlers are sync ``def``, so FastAPI runs them in a threadpool and two
|
|
requests really can land here at once.
|
|
"""
|
|
|
|
def __init__(self, max_keys: int = MAX_TRACKED_KEYS) -> None:
|
|
self._lock = threading.Lock()
|
|
self._state: OrderedDict[str, tuple[float, float]] = OrderedDict()
|
|
self._max_keys = max_keys
|
|
|
|
def take(self, key: str, limit: Limit, *, now: float | None = None) -> float | None:
|
|
"""Spend one token. Returns None if allowed, else seconds to wait."""
|
|
now = time.monotonic() if now is None else now
|
|
|
|
with self._lock:
|
|
tokens, last = self._state.get(key, (float(limit.capacity), now))
|
|
tokens = min(limit.capacity, tokens + (now - last) * limit.per_second)
|
|
|
|
if tokens >= 1.0:
|
|
self._state[key] = (tokens - 1.0, now)
|
|
allowed: float | None = None
|
|
else:
|
|
self._state[key] = (tokens, now)
|
|
allowed = (1.0 - tokens) / limit.per_second
|
|
|
|
self._state.move_to_end(key)
|
|
while len(self._state) > self._max_keys:
|
|
self._state.popitem(last=False)
|
|
|
|
return allowed
|
|
|
|
def reset(self) -> None:
|
|
with self._lock:
|
|
self._state.clear()
|
|
|
|
|
|
BUCKETS = TokenBuckets()
|
|
|
|
|
|
def client_address(request: Request) -> str:
|
|
"""The camera's address, not Caddy's.
|
|
|
|
Caddy sets X-Real-IP (deploy/Caddyfile, both blocks). Without it every
|
|
camera would share one bucket, since they all arrive from 127.0.0.1 via
|
|
the proxy. Trusting the header is safe only because uvicorn binds
|
|
loopback and nothing but Caddy can reach it.
|
|
"""
|
|
forwarded = request.headers.get("x-real-ip")
|
|
if forwarded:
|
|
return forwarded.strip()
|
|
|
|
chain = request.headers.get("x-forwarded-for")
|
|
if chain:
|
|
return chain.split(",")[0].strip()
|
|
|
|
return request.client.host if request.client else "unknown"
|
|
|
|
|
|
def _enforce(key: str, limit: Limit, settings: Settings) -> None:
|
|
if not settings.rate_limit_enabled:
|
|
return
|
|
|
|
retry_after = BUCKETS.take(key, limit)
|
|
if retry_after is None:
|
|
return
|
|
|
|
# 429 and not 401: the firmware clears its token on a 401, and being busy
|
|
# is not a credential problem. Retry-After gives it something better than
|
|
# a guess to back off by.
|
|
raise HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
detail="too many requests",
|
|
headers={"Retry-After": str(max(1, int(retry_after + 0.5)))},
|
|
)
|
|
|
|
|
|
def by_address(name: str, limit: Limit):
|
|
"""Limit by caller address. For endpoints with no device yet."""
|
|
|
|
def dependency(request: Request, settings: SettingsDep) -> None:
|
|
_enforce(f"{name}:{client_address(request)}", limit, settings)
|
|
|
|
return dependency
|
|
|
|
|
|
def by_device(name: str, limit: Limit):
|
|
"""Limit per device.
|
|
|
|
Keyed on the authenticated device rather than the address so that one
|
|
misbehaving camera cannot spend another's allowance. Depends on
|
|
DeviceDep, which FastAPI resolves once per request, so this adds no
|
|
second token lookup.
|
|
"""
|
|
|
|
def dependency(device: DeviceDep, settings: SettingsDep) -> None:
|
|
_enforce(f"{name}:{device.id}", limit, settings)
|
|
|
|
return dependency
|
|
|
|
|
|
# --- the limits -------------------------------------------------------------
|
|
#
|
|
# Each is set well above what the firmware does when healthy, with the
|
|
# relevant firmware behaviour noted so the number can be re-derived rather
|
|
# than guessed at next time.
|
|
|
|
# The device tries its stored secret and then the compiled-in bootstrap one,
|
|
# so a single enrollment attempt is up to two requests. Enrollment is rare --
|
|
# first boot, and a token rotation - so this is the one place worth being
|
|
# strict: it is where a shared secret could be ground at.
|
|
ENROLL = Limit.per_hour(20, burst=6)
|
|
|
|
# 5000 captures/day is ~3.5/min, arriving in bursts of three to five frames
|
|
# when the radar fires. 120/min with a burst of 40 leaves enormous headroom.
|
|
INGEST = Limit.per_minute(120, burst=40)
|
|
|
|
# heartbeat_interval_s defaults to 300 and the firmware clamps it to 30, so
|
|
# the fastest legitimate cadence is 2/min. Ten times that.
|
|
CONDITIONS = Limit.per_minute(20, burst=10)
|
|
|
|
# Pulled only when config_version changes, which is operator-driven.
|
|
CONFIG = Limit.per_minute(10, burst=5)
|
|
|
|
# Acks follow commands, which an operator queues by hand.
|
|
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)
|