Add rate limiting to the device endpoints (REVIEW SEC-004)
In-process token buckets, no Redis and no slowapi - for the same reason the job queue has no Redis (SPEC C8). This 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 assumption is named in the module: poorbird serve runs a single process, and if the deployment ever gains workers each gets its own buckets and the effective limit multiplies. Move the state to PostgreSQL at that point rather than widening the numbers. Buckets rather than fixed windows, because a camera uploads three to five frames back to back when the radar fires and then goes quiet. A window would reject the tail of a legitimate burst that straddled a boundary. Authenticated endpoints key on the device, so one wedged camera cannot spend another's allowance. /enroll keys on the caller address, since there is no device yet and it is the one place a shared secret could be ground at. This required a Caddyfile change, not a cosmetic one: the :8080 camera block proxied without X-Real-IP, so every camera reached the app as 127.0.0.1 and they would all have shared one enrollment bucket - one noisy device locking the rest out. The header is trusted only because uvicorn binds loopback. Limits are deliberately loose, each derived from what the firmware actually does and noted in the code so the number can be re-derived rather than guessed at. A throttled camera stops delivering photographs, which on a private LAN is worse than the flooding the limit prevents. Throttling answers 429, never 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. The key table is LRU-bounded. It is keyed partly on caller address, and an unbounded map keyed by something a caller influences is itself a way to exhaust memory. Off by default in tests, which fire far more requests than any camera would. tests/test_ratelimit.py turns it back on and proves the buckets are wired to the routes. Also fixes the same teardown-in-test-body flaw in the new file, found by re-running a deliberate mutation and noticing a leaked device row. Teardown is in fixtures; the mutation now fails its one test and leaves nothing behind. Tests: 158 -> 175. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
269a6eadcb
commit
e326dd8226
12 files changed
+505
-6
No files matched your search
@@ -14,10 +14,11 @@ from __future__ import annotations
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Response, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...models.devices import DeviceCommand
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep
|
||||
from ..schemas import CommandAck
|
||||
|
||||
@@ -32,6 +33,7 @@ router = APIRouter()
|
||||
response_class=Response,
|
||||
summary="Report the outcome of a command",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("ack", ratelimit.ACK))],
|
||||
)
|
||||
def ack_command(
|
||||
command_id: int,
|
||||
|
||||
@@ -23,9 +23,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import APIRouter, Response, status
|
||||
from fastapi import APIRouter, Depends, Response, status
|
||||
|
||||
from ...models.devices import DeviceStatus
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep
|
||||
from ..envelope import build_envelope
|
||||
from ..schemas import DeviceConditions, Envelope
|
||||
@@ -116,6 +117,7 @@ def _record(db: DbDep, device, body: DeviceConditions) -> None:
|
||||
response_model_exclude_none=True,
|
||||
summary="Device conditions; returns the command envelope",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("heartbeat", ratelimit.CONDITIONS))],
|
||||
)
|
||||
def heartbeat(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Envelope:
|
||||
_record(db, device, body)
|
||||
@@ -130,6 +132,7 @@ def heartbeat(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Envelope:
|
||||
response_class=Response,
|
||||
summary="Device conditions; returns nothing actionable",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("status", ratelimit.CONDITIONS))],
|
||||
)
|
||||
def device_status(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Response:
|
||||
_record(db, device, body)
|
||||
|
||||
@@ -24,8 +24,9 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from .. import ratelimit
|
||||
from ..deps import DeviceDep
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -52,6 +53,7 @@ _COLUMN_BACKED = (
|
||||
"/config",
|
||||
summary="The device's full settings document",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("config", ratelimit.CONFIG))],
|
||||
)
|
||||
def get_config(device: DeviceDep) -> dict[str, Any]:
|
||||
# Start from the stored document, then let the column-backed keys win.
|
||||
|
||||
@@ -16,11 +16,12 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from ...models.devices import Device
|
||||
from .. import ratelimit
|
||||
from ..deps import (
|
||||
DbDep,
|
||||
SettingsDep,
|
||||
@@ -43,6 +44,9 @@ router = APIRouter()
|
||||
response_model=EnrollResponse,
|
||||
summary="Enroll a device, or re-issue its token",
|
||||
tags=["devices"],
|
||||
# Keyed by caller address: there is no device to key on yet, and this is
|
||||
# the one endpoint where a shared secret could be ground at (SEC-004).
|
||||
dependencies=[Depends(ratelimit.by_address("enroll", ratelimit.ENROLL))],
|
||||
)
|
||||
def enroll(
|
||||
body: EnrollRequest,
|
||||
|
||||
@@ -23,12 +23,13 @@ from __future__ import annotations
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...config import Settings
|
||||
from ...models.devices import Firmware
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep, SettingsDep
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -54,6 +55,7 @@ def _resolve(file_path: str, settings: Settings) -> Path:
|
||||
response_class=FileResponse,
|
||||
summary="Download an OTA image",
|
||||
tags=["firmware"],
|
||||
dependencies=[Depends(ratelimit.by_device("firmware", ratelimit.FIRMWARE))],
|
||||
)
|
||||
def download_firmware(
|
||||
version: str,
|
||||
|
||||
@@ -26,6 +26,7 @@ from pydantic import ValidationError
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...models.captures import Capture
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep, SettingsDep
|
||||
from ..envelope import build_envelope
|
||||
from ..images import (
|
||||
@@ -91,6 +92,7 @@ def ingest_meta(
|
||||
response_model_exclude_none=True,
|
||||
summary="Accept a captured frame; returns the command envelope",
|
||||
tags=["captures"],
|
||||
dependencies=[Depends(ratelimit.by_device("ingest", ratelimit.INGEST))],
|
||||
)
|
||||
def ingest(
|
||||
db: DbDep,
|
||||
|
||||
Reference in new issue
Block a user