diff --git a/server/deploy/poorbird.env.example b/server/deploy/poorbird.env.example index eb8d9d2..5d2ffbe 100644 --- a/server/deploy/poorbird.env.example +++ b/server/deploy/poorbird.env.example @@ -36,6 +36,24 @@ POORBIRD_IMAGE_ROOT=/srv/poorbird/images POORBIRD_THUMB_ROOT=/srv/poorbird/thumbs POORBIRD_STATE_DIR=/var/lib/poorbird +# Who copies the image bytes (SPEC 3.3). +# +# Leave this FALSE in production. The app authorises the request and answers +# with X-Accel-Redirect, and Caddy reads the file, so a 3 MB JPEG never +# occupies a Python worker thread. +# +# Set it true ONLY for local development, where there is no Caddy to honour +# that header and every image in the gallery would otherwise arrive as an +# empty 200. It does NOT relax the authorisation -- the same check runs either +# way; it only changes how an already-authorised response is finished. +# +# NOTE: with this false, IMAGE_ROOT and THUMB_ROOT must be siblings named +# images/ and thumbs/ under the directory the Caddyfile's file_server serves +# (deploy/Caddyfile, the protected_files snippet). `poorbird check` verifies +# that, because getting it wrong produces 404s from Caddy and nothing in the +# app's log. +POORBIRD_SERVE_IMAGES_DIRECTLY=false + # --- devices ---------------------------------------------------------------- # Shared bootstrap secret the firmware presents in X-Enroll-Secret. # Generate with: openssl rand -hex 32 diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py index 40858e0..09b9798 100644 --- a/server/src/poorbird/api/app.py +++ b/server/src/poorbird/api/app.py @@ -8,7 +8,17 @@ from fastapi import FastAPI from .. import __version__ from ..config import get_settings from ..logging_setup import configure_logging -from .routes import auth, commands, conditions, device_config, enroll, firmware, health, ingest +from .routes import ( + auth, + captures, + commands, + conditions, + device_config, + enroll, + firmware, + health, + ingest, +) from .userauth import csrf_middleware log = logging.getLogger(__name__) @@ -54,6 +64,7 @@ def create_app() -> FastAPI: # Phase 3 WebUI endpoints. app.include_router(auth.router, prefix=API_PREFIX) + app.include_router(captures.router, prefix=API_PREFIX) # Phase 2 device endpoints. See firmware/API.md for the contract. app.include_router(enroll.router, prefix=API_PREFIX) diff --git a/server/src/poorbird/api/delivery.py b/server/src/poorbird/api/delivery.py new file mode 100644 index 0000000..7cf5224 --- /dev/null +++ b/server/src/poorbird/api/delivery.py @@ -0,0 +1,111 @@ +"""Auth-checked file delivery (SPEC 3.3). + +"An unguessable URL is not access control." Every image byte goes through a +route that authorises first; only then is the file delivered. What differs +between environments is *who copies the bytes*, and deliberately nothing else: + +* **Production.** The app answers empty with ``X-Accel-Redirect: /images/...`` + and Caddy serves the file from disk (see deploy/Caddyfile, the + ``protected_files`` snippet). Python never touches the payload, so a 3 MB + JPEG does not occupy a worker thread. +* **Development.** There is no Caddy -- the Vite dev server proxies straight to + uvicorn -- so that header would reach the browser as an empty 200 and every + image would silently be blank. With ``POORBIRD_SERVE_IMAGES_DIRECTLY=true`` + the app sends the bytes itself. + +The authorisation is the *same code either way*. This is not a route that +bypasses auth in development: it is one authorised route with two ways of +finishing. That distinction is the whole point -- a separate unauthenticated +file route "only reachable in dev" is exactly the kind of thing that survives +into production because it works. +""" + +from __future__ import annotations + +import logging +from pathlib import Path + +from fastapi import HTTPException, Response, status +from fastapi.responses import FileResponse + +from ..config import Settings + +log = logging.getLogger(__name__) + +# URL prefixes Caddy maps onto disk. These are coupled to deploy/Caddyfile, +# whose file_server root is the PARENT of image_root and thumb_root -- so the +# last segment of each root has to be exactly this. Change one, change both. +IMAGE_URL_PREFIX = "/images" +THUMB_URL_PREFIX = "/thumbs" + + +def _safe_absolute(root: Path, relative: str) -> Path: + """Resolve ``relative`` under ``root``, or 404. + + ``captures.path`` is written by our own ingest code, so this should never + fire. It is here because the cost of being wrong is serving an arbitrary + file off the server, and "should never" is not a security control. A + traversal attempt is answered as a missing file rather than as a refusal, + because confirming that a path is interesting is itself information. + """ + root = root.resolve() + candidate = (root / relative).resolve() + if candidate != root and root not in candidate.parents: + log.error( + "refusing a path that escapes its root", + extra={"root": str(root), "relative": relative}, + ) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found") + return candidate + + +def deliver( + *, + settings: Settings, + root: Path, + url_prefix: str, + relative: str, + media_type: str, + filename: str, +) -> Response: + """Hand an already-authorised file to the client. + + Callers must have checked permission before reaching here; this function + knows nothing about who is asking. + """ + absolute = _safe_absolute(root, relative) + + if settings.serve_images_directly: + if not absolute.is_file(): + # The row says there is a file and there is not. Worth logging + # loudly: it means the database and the disk have diverged, which + # a backup restore or a half-finished retention run can do. + log.error("capture file is missing from disk", extra={"path": str(absolute)}) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found") + return FileResponse( + absolute, + media_type=media_type, + # Long and immutable: the filename contains the capture UUID and + # the bytes at that path never change. Private, because the whole + # point is that this response was authorised for one person. + headers={ + "Cache-Control": "private, max-age=31536000, immutable", + "Content-Disposition": f'inline; filename="{filename}"', + }, + ) + + # Production: Caddy serves it. The body stays empty on purpose -- if this + # reaches a browser directly it is a deployment mistake, and an empty + # response is a louder symptom than a plausible-looking one. + # + # Existence is deliberately not checked here. Doing so would mean a stat() + # on the request path for a file the app is not going to open, and Caddy + # answers 404 by itself if it is gone. + return Response( + status_code=status.HTTP_200_OK, + headers={ + "X-Accel-Redirect": f"{url_prefix}/{relative}", + "Cache-Control": "private, max-age=31536000, immutable", + "Content-Disposition": f'inline; filename="{filename}"', + }, + ) diff --git a/server/src/poorbird/api/routes/captures.py b/server/src/poorbird/api/routes/captures.py new file mode 100644 index 0000000..fdccb96 --- /dev/null +++ b/server/src/poorbird/api/routes/captures.py @@ -0,0 +1,287 @@ +"""The gallery: listing captures, and serving their bytes (SPEC 3.3). + +Four routes, all behind a session. Any signed-in role may read the gallery -- +that is what a ``viewer`` is for (SPEC 3.1) -- while a *device* never can: a +device token is scoped to the ingest endpoints and cannot resolve to a user at +all (api/deps.py vs api/userauth.py). + +The image routes authorise and then hand off; see api/delivery.py for why the +bytes are Caddy's job in production and the app's in development. +""" + +from __future__ import annotations + +import base64 +import binascii +import logging +import uuid +from datetime import UTC, datetime +from typing import Annotated + +from fastapi import APIRouter, HTTPException, Query, Response, status +from sqlalchemy import Select, select, tuple_ +from sqlalchemy.orm import selectinload + +from ...models import Capture, Device +from ..delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX, deliver +from ..deps import DbDep, SettingsDep +from ..ui_schemas import CaptureDetail, CapturePage, CaptureSummary +from ..userauth import CurrentUser + +log = logging.getLogger(__name__) + +router = APIRouter(prefix="/captures", tags=["gallery"]) + +# A virtualised grid asks for a screenful at a time. 200 is about four +# screens on a large monitor; beyond that the response is bigger than the +# scroll it serves. +DEFAULT_LIMIT = 50 +MAX_LIMIT = 200 + + +def _encode_cursor(capture: Capture) -> str: + """Opaque-ish cursor: the sort key of the last row on this page. + + Base64 so it does not look like something to hand-edit, not because it is + a secret -- it is a timestamp and a UUID the caller was just given. + """ + raw = f"{capture.received_at.astimezone(UTC).isoformat()}|{capture.id}" + return base64.urlsafe_b64encode(raw.encode()).decode() + + +def _decode_cursor(cursor: str) -> tuple[datetime, uuid.UUID]: + """Parse a cursor, or 422. + + Everything here is caller-supplied, so every failure mode is a bad request + rather than a 500: bad base64, bad UTF-8, a missing separator, an + unparseable timestamp, a malformed UUID. + """ + try: + raw = base64.urlsafe_b64decode(cursor.encode()).decode("utf-8") + stamp, _, ident = raw.partition("|") + if not ident: + raise ValueError("cursor has no id") + return datetime.fromisoformat(stamp), uuid.UUID(ident) + except (ValueError, binascii.Error, UnicodeDecodeError) as exc: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail="invalid cursor", + ) from exc + + +def _apply_filters( + stmt: Select, + *, + device_id: int | None, + received_from: datetime | None, + received_to: datetime | None, + kept: bool | None, + reviewed: bool | None, + pre_trigger: bool | None, + trigger: str | None, +) -> Select: + """Filters over columns that exist today. + + Taxon and tag filters are in TODO Phase 3 and are deliberately not here + yet: both need a join, and neither has any data to join to until the + observation editor and a seeded ``taxa`` table exist. A filter that can + only ever return nothing is worse than an absent one, because the UI would + offer it. + + Dates filter on ``received_at``, never ``captured_at_device``, which is + NULL whenever the camera's clock was unsynced. Filtering on it would + silently drop exactly those frames. + """ + if device_id is not None: + stmt = stmt.where(Capture.device_id == device_id) + if received_from is not None: + stmt = stmt.where(Capture.received_at >= received_from) + if received_to is not None: + stmt = stmt.where(Capture.received_at <= received_to) + if kept is not None: + stmt = stmt.where(Capture.kept == kept) + if reviewed is not None: + stmt = stmt.where(Capture.reviewed == reviewed) + if pre_trigger is not None: + stmt = stmt.where(Capture.pre_trigger == pre_trigger) + if trigger is not None: + stmt = stmt.where(Capture.trigger == trigger) + return stmt + + +def _summary(capture: Capture) -> CaptureSummary: + return CaptureSummary( + id=capture.id, + device_id=capture.device_id, + received_at=capture.received_at, + captured_at_device=capture.captured_at_device, + width=capture.width, + height=capture.height, + bytes=capture.bytes, + trigger=capture.trigger, + pre_trigger=capture.pre_trigger, + burst_id=capture.burst_id, + burst_index=capture.burst_index, + burst_count=capture.burst_count, + reviewed=capture.reviewed, + kept=capture.kept, + has_thumb=capture.thumb_path is not None, + ) + + +@router.get( + "", + response_model=CapturePage, + summary="List captures, newest first", +) +def list_captures( + db: DbDep, + _user: CurrentUser, + limit: Annotated[int, Query(ge=1, le=MAX_LIMIT)] = DEFAULT_LIMIT, + cursor: Annotated[str | None, Query()] = None, + device_id: Annotated[int | None, Query()] = None, + received_from: Annotated[datetime | None, Query()] = None, + received_to: Annotated[datetime | None, Query()] = None, + kept: Annotated[bool | None, Query()] = None, + reviewed: Annotated[bool | None, Query()] = None, + pre_trigger: Annotated[bool | None, Query()] = None, + trigger: Annotated[str | None, Query()] = None, +) -> CapturePage: + """Newest first, keyset-paginated. + + The sort is ``(received_at DESC, id DESC)``. The id is in the key not for + ordering's sake but because a burst arrives within the same fraction of a + second: on ties, a cursor that only carried the timestamp would either + repeat rows or skip them, and a gallery that loses a frame while scrolling + is a gallery you cannot trust. + """ + stmt = select(Capture) + stmt = _apply_filters( + stmt, + device_id=device_id, + received_from=received_from, + received_to=received_to, + kept=kept, + reviewed=reviewed, + pre_trigger=pre_trigger, + trigger=trigger, + ) + + if cursor is not None: + last_received, last_id = _decode_cursor(cursor) + # Row-value comparison, which maps onto the (device_id, received_at) + # index the same way a plain inequality would and needs no OR. + stmt = stmt.where(tuple_(Capture.received_at, Capture.id) < (last_received, last_id)) + + # One more than asked for, purely to learn whether another page exists + # without also running a COUNT over the whole filtered set. + rows = list( + db.scalars( + stmt.order_by(Capture.received_at.desc(), Capture.id.desc()).limit(limit + 1) + ).all() + ) + + has_more = len(rows) > limit + page = rows[:limit] + return CapturePage( + items=[_summary(c) for c in page], + next_cursor=_encode_cursor(page[-1]) if has_more and page else None, + ) + + +def _get_capture(db: DbDep, capture_id: uuid.UUID) -> Capture: + capture = db.get(Capture, capture_id) + if capture is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture") + return capture + + +@router.get( + "/{capture_id}", + response_model=CaptureDetail, + summary="One capture, with its observations and tags", +) +def get_capture(capture_id: uuid.UUID, db: DbDep, _user: CurrentUser) -> CaptureDetail: + capture = db.scalar( + select(Capture) + .where(Capture.id == capture_id) + # Eager, or rendering one capture with three observations is four + # queries and the pattern repeats per row the moment this is reused. + .options( + selectinload(Capture.observations), + selectinload(Capture.tags), + ) + ) + if capture is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture") + + device = db.get(Device, capture.device_id) + return CaptureDetail( + **_summary(capture).model_dump(), + # The device row is ON DELETE CASCADE from captures, so this is only + # None in a torn state. Naming it rather than crashing. + device_name=device.name if device is not None else "unknown", + sha256=capture.sha256, + radar_state=capture.radar_state, + radar_distance_cm=capture.radar_distance_cm, + radar_energy=capture.radar_energy, + battery_mv=capture.battery_mv, + rssi=capture.rssi, + temp_c=capture.temp_c, + frame_seq=capture.frame_seq, + observations=list(capture.observations), + tags=list(capture.tags), + ) + + +@router.get( + "/{capture_id}/image", + summary="The full JPEG, after an authorisation check", + response_class=Response, +) +def get_capture_image( + capture_id: uuid.UUID, + db: DbDep, + settings: SettingsDep, + _user: CurrentUser, +) -> Response: + capture = _get_capture(db, capture_id) + return deliver( + settings=settings, + root=settings.image_root, + url_prefix=IMAGE_URL_PREFIX, + relative=capture.path, + media_type="image/jpeg", + filename=f"{capture.id}.jpg", + ) + + +@router.get( + "/{capture_id}/thumb", + summary="The 400px WebP thumbnail, after an authorisation check", + response_class=Response, +) +def get_capture_thumb( + capture_id: uuid.UUID, + db: DbDep, + settings: SettingsDep, + _user: CurrentUser, +) -> Response: + capture = _get_capture(db, capture_id) + if capture.thumb_path is None: + # Either the job has not run yet or the frame could not be decoded. + # 404 rather than falling back to the full image: a grid that quietly + # served 200 full-size JPEGs would look like it worked and would be a + # hundred times the bytes. + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="no thumbnail for this capture yet", + ) + return deliver( + settings=settings, + root=settings.thumb_root, + url_prefix=THUMB_URL_PREFIX, + relative=capture.thumb_path, + media_type="image/webp", + filename=f"{capture.id}_400.webp", + ) diff --git a/server/src/poorbird/api/ui_schemas.py b/server/src/poorbird/api/ui_schemas.py index f4e7e07..a613e93 100644 --- a/server/src/poorbird/api/ui_schemas.py +++ b/server/src/poorbird/api/ui_schemas.py @@ -11,14 +11,18 @@ because the scaffold was written first and there is no reason to make it move. from __future__ import annotations +import uuid +from datetime import datetime from typing import Annotated, Literal from pydantic import BaseModel, ConfigDict, Field +from ..models.captures import TRIGGERS from ..models.users import ROLES, THEMES Role = Literal[ROLES] # type: ignore[valid-type] Theme = Literal[THEMES] # type: ignore[valid-type] +Trigger = Literal[TRIGGERS] # type: ignore[valid-type] class LoginRequest(BaseModel): @@ -51,3 +55,112 @@ class SessionUser(BaseModel): role: Role locale: str theme: Theme + + +# --- gallery ---------------------------------------------------------------- + + +class CaptureSummary(BaseModel): + """One tile in the grid. + + Kept deliberately small, because a page of these is 50-200 rows and the + grid re-fetches on every filter change. Anything only the detail view + needs -- radar energy, battery, observations, tags -- is in + :class:`CaptureDetail` instead. + + No image URLs. The client builds those from the id in lib/api.ts, which is + already the one place that knows the API prefix; putting them here would + duplicate that knowledge in every response. + """ + + model_config = ConfigDict(from_attributes=True) + + id: uuid.UUID + device_id: int + # SPEC C7: server time, always authoritative. captured_at_device is NULL + # when the camera's clock was unsynced, and the UI must not present it as + # 1970 -- see API.md on X-Captured-At: 0. + received_at: datetime + captured_at_device: datetime | None + width: int | None + height: int | None + bytes: int + trigger: Trigger + pre_trigger: bool + burst_id: str | None + burst_index: int | None + burst_count: int | None + reviewed: bool + kept: bool + # False while the thumbnail job is still queued, or permanently for a frame + # that could not be decoded. The grid shows a placeholder rather than a + # broken image, so it has to be able to tell. + has_thumb: bool + + +class CapturePage(BaseModel): + """A keyset page, not an offset page. + + At 5000 captures a day, OFFSET gets slower the further back you scroll, + which is precisely the direction a gallery scrolls. The cursor carries the + last row's ``(received_at, id)``; ``next_cursor`` is null at the end. + """ + + items: list[CaptureSummary] + next_cursor: str | None + + +class TagOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + label: str + colour: str | None + + +class TaxonOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + scientific_name: str + name_de: str | None + name_en: str | None + + +class ObservationOut(BaseModel): + """A label on a capture. + + ``source`` separates human labels from model predictions in one table + (SPEC 3.2), so the edit UI is already the training-data pipeline. The UI + must show which is which -- a prediction presented as a human label would + poison exactly that. + """ + + model_config = ConfigDict(from_attributes=True) + + id: int + taxon: TaxonOut | None + individuals: int + age: str + sex: str + behaviour: str | None + certainty: str + notes: str | None + source: Literal["human", "model"] + confidence: float | None + + +class CaptureDetail(CaptureSummary): + """Everything about one capture, for the full-screen view.""" + + device_name: str + sha256: str + radar_state: int | None + radar_distance_cm: int | None + radar_energy: int | None + battery_mv: int | None + rssi: int | None + temp_c: float | None + frame_seq: int | None + observations: list[ObservationOut] + tags: list[TagOut] diff --git a/server/src/poorbird/cli.py b/server/src/poorbird/cli.py index 4c7dea2..6ba6c4c 100644 --- a/server/src/poorbird/cli.py +++ b/server/src/poorbird/cli.py @@ -265,7 +265,35 @@ def cmd_check(_args: argparse.Namespace) -> int: print(f" path {path} ok") if not settings.enroll_secret_is_set: - print(" enroll_secret NOT SET (fine for Phase 1, required for Phase 2)") + print(" enroll_secret NOT SET (device enrollment will refuse requests)") + + # The Caddy handoff (SPEC 3.3) needs the app and the proxy to agree on the + # layout: Caddy serves the PARENT of both roots and the app sends paths + # under /images and /thumbs. If the directories are not siblings with + # those names, every image 404s from Caddy with nothing in the app's log + # to explain it -- so it is worth saying here rather than discovering in a + # browser. + if settings.serve_images_directly: + print(" images served by the app (development only)") + else: + from .api.delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX + + image_root, thumb_root = settings.image_root, settings.thumb_root + expected_image = IMAGE_URL_PREFIX.lstrip("/") + expected_thumb = THUMB_URL_PREFIX.lstrip("/") + if ( + image_root.parent != thumb_root.parent + or image_root.name != expected_image + or thumb_root.name != expected_thumb + ): + print( + f" images LAYOUT MISMATCH: Caddy expects " + f"/{expected_image} and /{expected_thumb}, " + f"got {image_root} and {thumb_root}" + ) + problems.append("image/thumb roots do not match the Caddy handoff layout") + else: + print(f" images handed off to Caddy from {image_root.parent}") if problems: print(f"\n{len(problems)} problem(s): " + "; ".join(problems)) diff --git a/server/src/poorbird/config.py b/server/src/poorbird/config.py index f9587a6..a73f314 100644 --- a/server/src/poorbird/config.py +++ b/server/src/poorbird/config.py @@ -62,6 +62,17 @@ class Settings(BaseSettings): thumb_root: Path = Path("/srv/poorbird/thumbs") state_dir: Path = Path("/var/lib/poorbird") + # Who copies the image bytes (SPEC 3.3, api/delivery.py). + # + # False in production: the app authorises and answers with + # X-Accel-Redirect, and Caddy reads the file. Python never handles the + # payload. True for local development, where there is no Caddy to honour + # that header and every image would otherwise arrive empty. + # + # This does NOT relax the authorisation -- the same check runs either way. + # It only changes how an already-authorised response is finished. + serve_images_directly: bool = False + # --- devices ---------------------------------------------------------- # Shared bootstrap secret presented by a device in X-Enroll-Secret. # See firmware/API.md: do NOT rotate this without shipping new firmware, diff --git a/server/tests/conftest.py b/server/tests/conftest.py index a61e68e..829ac08 100644 --- a/server/tests/conftest.py +++ b/server/tests/conftest.py @@ -19,6 +19,11 @@ os.environ.setdefault("POORBIRD_RATE_LIMIT_ENABLED", "false") # same trap catches local development against the Vite dev server, which is # why this is a setting at all. See config.session_cookie_secure. os.environ.setdefault("POORBIRD_SESSION_COOKIE_SECURE", "false") +# Pin the production default. A developer's server/.env sets this true so the +# Vite dev server can show images, and an untracked file must not be able to +# change what the suite asserts. Tests that care about either mode name it +# explicitly -- see test_captures.py. +os.environ.setdefault("POORBIRD_SERVE_IMAGES_DIRECTLY", "false") def database_is_reachable() -> bool: diff --git a/server/tests/test_captures.py b/server/tests/test_captures.py new file mode 100644 index 0000000..0ad81a5 --- /dev/null +++ b/server/tests/test_captures.py @@ -0,0 +1,646 @@ +"""The gallery: listing, paging, filtering and auth-checked delivery (SPEC 3.3). + +Needs a real PostgreSQL. The paging is a row-value comparison against a real +index, and the thing most worth testing about it -- that a burst arriving +within one millisecond does not lose or repeat a frame -- only happens with +real ordering semantics. +""" + +from __future__ import annotations + +import secrets +import uuid +from datetime import UTC, datetime, timedelta + +import pytest +from conftest import needs_db +from sqlalchemy import delete, func, select, text + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.config import Settings, get_settings +from poorbird.models import AuditLog, Capture, Device, Observation, Tag, User +from poorbird.passwords import hash_password + +pytestmark = [pytest.mark.db, needs_db] + +PASSWORD = "gallery-test-passphrase" + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture(autouse=True) +def clean_cookies(client): + client.cookies.clear() + yield + client.cookies.clear() + + +@pytest.fixture(autouse=True) +def no_audit_leaks(db): + """Logging in writes an audit row; sweep by id so none survive the test.""" + high_water = db.scalar(select(func.coalesce(func.max(AuditLog.id), 0))) + yield + db.execute(delete(AuditLog).where(AuditLog.id > high_water)) + db.commit() + + +@pytest.fixture +def make_user(db): + created: list[int] = [] + + def make(role: str = "viewer") -> User: + user = User( + username=f"g_{secrets.token_hex(6)}", + password_hash=hash_password(PASSWORD), + role=role, + ) + db.add(user) + db.commit() + db.refresh(user) + created.append(user.id) + return user + + yield make + for user_id in created: + db.execute(text("DELETE FROM audit_log WHERE user_id = :i"), {"i": user_id}) + db.execute(text("DELETE FROM sessions WHERE user_id = :i"), {"i": user_id}) + db.execute(text("DELETE FROM users WHERE id = :i"), {"i": user_id}) + db.commit() + + +@pytest.fixture +def signed_in(client, make_user): + """A signed-in viewer. Returns the user.""" + + def sign_in(role: str = "viewer") -> User: + user = make_user(role) + response = client.post( + "/api/v1/auth/login", json={"username": user.username, "password": PASSWORD} + ) + assert response.status_code == 200, response.text + return user + + return sign_in + + +@pytest.fixture +def make_device(db): + """Devices, and everything that hangs off them. + + Teardown in a fixture, not at the end of the test body: a failing + assertion skips the rest of the body and leaves rows behind. Observations + and tag links cascade from captures, but the thumbnail *jobs* /ingest + enqueues do not, so they are cleared explicitly -- that exact omission + broke test_queue.py once already. + """ + created: list[int] = [] + + def make(name: str = "cam") -> Device: + device = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(new_credential()), + enabled=True, + ) + db.add(device) + db.commit() + db.refresh(device) + created.append(device.id) + return device + + yield make + + for device_id in created: + db.execute( + text( + "DELETE FROM jobs WHERE kind = 'thumbnail' AND (payload->>'capture_id') IN " + "(SELECT id::text FROM captures WHERE device_id = :i)" + ), + {"i": device_id}, + ) + db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device_id}) + db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device_id}) + db.commit() + + +@pytest.fixture +def make_capture(db): + def make( + device: Device, + *, + received_at: datetime | None = None, + thumb: bool = True, + kept: bool = True, + reviewed: bool = False, + pre_trigger: bool = False, + trigger: str = "radar", + path: str | None = None, + ) -> Capture: + capture_id = uuid.uuid4() + capture = Capture( + id=capture_id, + device_id=device.id, + path=path if path is not None else f"2026/09/20/{capture_id}.jpg", + thumb_path=f"{capture_id}_400.webp" if thumb else None, + sha256=secrets.token_hex(32), + width=1600, + height=1200, + bytes=123456, + received_at=received_at or datetime.now(UTC), + trigger=trigger, + pre_trigger=pre_trigger, + kept=kept, + reviewed=reviewed, + ) + db.add(capture) + db.commit() + return capture + + return make + + +def _delivery_mode(client, *, directly: bool): + """Pin the delivery mode for one test. + + Both modes are named explicitly rather than inherited from whatever + server/.env happens to say. These two tests failed the moment + POORBIRD_SERVE_IMAGES_DIRECTLY=true was added to a developer's .env for + the dev server's benefit -- a test that changes answer because of an + untracked file is not testing the code. + """ + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, + serve_images_directly=directly, + session_cookie_secure=False, + ) + + +@pytest.fixture +def direct_delivery(client): + """Serve bytes from the app, as local development does.""" + _delivery_mode(client, directly=True) + yield + client.app.dependency_overrides.clear() + + +@pytest.fixture +def handoff_delivery(client): + """Authorise and let Caddy serve, as production does.""" + _delivery_mode(client, directly=False) + yield + client.app.dependency_overrides.clear() + + +# --- who may read the gallery ----------------------------------------------- + + +def test_listing_requires_a_session(client): + assert client.get("/api/v1/captures").status_code == 401 + + +def test_a_device_token_does_not_open_the_gallery(client, make_device): + """SPEC 3.1: a device is not a user. Its token is scoped to ingest and + cannot resolve to a person, so it must not read captures -- the camera + uploads, it does not browse.""" + token = new_credential() + device = make_device() + from poorbird.db import SessionLocal + + with SessionLocal() as s: + row = s.get(Device, device.id) + row.token_hash = hash_credential(token) + s.commit() + + response = client.get("/api/v1/captures", headers={"Authorization": f"Bearer {token}"}) + assert response.status_code == 401 + + +def test_a_viewer_may_read_the_gallery(client, signed_in, make_device, make_capture): + """The lowest role is exactly the one the gallery exists for.""" + signed_in("viewer") + make_capture(make_device()) + assert client.get("/api/v1/captures").status_code == 200 + + +def test_the_image_route_requires_a_session(client, make_device, make_capture): + """An unguessable URL is not access control (SPEC 3.3). The id is a UUID, + and that is still not a reason to serve it to anyone who has it.""" + capture = make_capture(make_device()) + assert client.get(f"/api/v1/captures/{capture.id}/image").status_code == 401 + assert client.get(f"/api/v1/captures/{capture.id}/thumb").status_code == 401 + + +# --- listing ---------------------------------------------------------------- + + +def test_captures_come_back_newest_first(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + now = datetime.now(UTC) + oldest = make_capture(device, received_at=now - timedelta(hours=2)) + newest = make_capture(device, received_at=now) + middle = make_capture(device, received_at=now - timedelta(hours=1)) + + items = client.get(f"/api/v1/captures?device_id={device.id}").json()["items"] + assert [i["id"] for i in items] == [str(newest.id), str(middle.id), str(oldest.id)] + + +def test_the_summary_carries_what_a_tile_needs(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + capture = make_capture(device) + + item = client.get(f"/api/v1/captures?device_id={device.id}").json()["items"][0] + assert item["id"] == str(capture.id) + assert item["width"] == 1600 + assert item["has_thumb"] is True + assert item["trigger"] == "radar" + # received_at is authoritative (SPEC C7) and always present. + assert item["received_at"] is not None + + +def test_has_thumb_is_false_while_the_job_has_not_run(client, signed_in, make_device, make_capture): + """The grid needs to tell "not yet" from "never" without fetching, or it + shows a broken image instead of a placeholder.""" + signed_in() + device = make_device() + make_capture(device, thumb=False) + + item = client.get(f"/api/v1/captures?device_id={device.id}").json()["items"][0] + assert item["has_thumb"] is False + + +def test_an_empty_gallery_is_an_empty_page_not_an_error(client, signed_in, make_device): + signed_in() + device = make_device() + body = client.get(f"/api/v1/captures?device_id={device.id}").json() + assert body == {"items": [], "next_cursor": None} + + +# --- paging ----------------------------------------------------------------- + + +def test_paging_walks_every_row_exactly_once(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + now = datetime.now(UTC) + expected = { + str(make_capture(device, received_at=now - timedelta(minutes=i)).id) for i in range(7) + } + + seen: list[str] = [] + cursor = None + for _ in range(20): # generous bound; the loop should end on its own + url = f"/api/v1/captures?device_id={device.id}&limit=2" + if cursor: + url += f"&cursor={cursor}" + body = client.get(url).json() + seen.extend(i["id"] for i in body["items"]) + cursor = body["next_cursor"] + if cursor is None: + break + + assert cursor is None, "paging did not terminate" + assert len(seen) == len(set(seen)), "a row was returned on two pages" + assert set(seen) == expected + + +def test_paging_does_not_lose_frames_from_the_same_burst( + client, signed_in, make_device, make_capture +): + """The real reason the cursor carries the id as well as the timestamp. + + A burst arrives within the same fraction of a second, so received_at ties + are normal rather than exotic. With a timestamp-only cursor these rows + would be skipped or repeated, and a gallery that drops a frame while you + scroll is one you cannot trust. + """ + signed_in() + device = make_device() + same_instant = datetime.now(UTC) + expected = {str(make_capture(device, received_at=same_instant).id) for _ in range(5)} + + seen: list[str] = [] + cursor = None + for _ in range(20): + url = f"/api/v1/captures?device_id={device.id}&limit=1" + if cursor: + url += f"&cursor={cursor}" + body = client.get(url).json() + seen.extend(i["id"] for i in body["items"]) + cursor = body["next_cursor"] + if cursor is None: + break + + assert set(seen) == expected + assert len(seen) == len(set(seen)) + + +def test_the_last_page_has_no_cursor(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + make_capture(device) + body = client.get(f"/api/v1/captures?device_id={device.id}&limit=50").json() + assert len(body["items"]) == 1 + assert body["next_cursor"] is None + + +def test_a_full_page_with_nothing_after_it_still_ends(client, signed_in, make_device, make_capture): + """limit=2 with exactly 2 rows must not offer a cursor to an empty page. + + This is the off-by-one the "fetch limit + 1" trick exists to avoid, and + the one a COUNT would have hidden. + """ + signed_in() + device = make_device() + now = datetime.now(UTC) + make_capture(device, received_at=now) + make_capture(device, received_at=now - timedelta(minutes=1)) + + body = client.get(f"/api/v1/captures?device_id={device.id}&limit=2").json() + assert len(body["items"]) == 2 + assert body["next_cursor"] is None + + +@pytest.mark.parametrize( + "cursor", + ["not-base64!!", "", "Zm9v", "MjAyNi0wMS0wMXxub3QtYS11dWlk", "fDEyMw=="], +) +def test_a_malformed_cursor_is_422_not_500(client, signed_in, cursor): + """Every part of a cursor is caller-supplied, so every failure is a bad + request: bad base64, bad UTF-8, no separator, bad date, bad UUID.""" + signed_in() + assert client.get(f"/api/v1/captures?cursor={cursor}").status_code == 422 + + +def test_limit_is_bounded(client, signed_in): + signed_in() + assert client.get("/api/v1/captures?limit=0").status_code == 422 + assert client.get("/api/v1/captures?limit=9999").status_code == 422 + + +# --- filters ---------------------------------------------------------------- + + +def test_filtering_by_device(client, signed_in, make_device, make_capture): + signed_in() + mine, other = make_device("mine"), make_device("other") + make_capture(mine) + make_capture(other) + + items = client.get(f"/api/v1/captures?device_id={mine.id}").json()["items"] + assert len(items) == 1 + assert items[0]["device_id"] == mine.id + + +def test_filtering_by_received_date_range(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + now = datetime.now(UTC) + recent = make_capture(device, received_at=now - timedelta(hours=1)) + make_capture(device, received_at=now - timedelta(days=5)) + + # params=, not an f-string: an ISO timestamp ends in "+00:00" and a raw "+" + # in a query string means a space, so the interpolated version arrives + # unparseable and answers 422. A real client encodes it; this test has to + # as well, rather than testing its own URL building. + response = client.get( + "/api/v1/captures", + params={ + "device_id": device.id, + "received_from": (now - timedelta(hours=3)).isoformat(), + }, + ) + assert response.status_code == 200, response.text + assert [i["id"] for i in response.json()["items"]] == [str(recent.id)] + + +def test_a_date_range_can_also_exclude_the_newest(client, signed_in, make_device, make_capture): + """The other end of the range, so a one-sided bug cannot pass both.""" + signed_in() + device = make_device() + now = datetime.now(UTC) + make_capture(device, received_at=now) + older = make_capture(device, received_at=now - timedelta(days=5)) + + response = client.get( + "/api/v1/captures", + params={ + "device_id": device.id, + "received_to": (now - timedelta(days=1)).isoformat(), + }, + ) + assert [i["id"] for i in response.json()["items"]] == [str(older.id)] + + +@pytest.mark.parametrize( + ("field", "query"), + [ + ("kept", "kept=false"), + ("reviewed", "reviewed=true"), + ("pre_trigger", "pre_trigger=true"), + ], +) +def test_filtering_by_triage_flags(client, signed_in, make_device, make_capture, field, query): + signed_in() + device = make_device() + wanted = make_capture(device, **{field: field != "kept"}) + make_capture(device, **{field: field == "kept"}) + + items = client.get(f"/api/v1/captures?device_id={device.id}&{query}").json()["items"] + assert [i["id"] for i in items] == [str(wanted.id)] + + +def test_filtering_by_trigger(client, signed_in, make_device, make_capture): + signed_in() + device = make_device() + manual = make_capture(device, trigger="manual") + make_capture(device, trigger="radar") + + items = client.get(f"/api/v1/captures?device_id={device.id}&trigger=manual").json()["items"] + assert [i["id"] for i in items] == [str(manual.id)] + + +# --- detail ----------------------------------------------------------------- + + +def test_an_unknown_capture_is_404(client, signed_in): + signed_in() + assert client.get(f"/api/v1/captures/{uuid.uuid4()}").status_code == 404 + + +def test_detail_includes_the_device_name_and_radar_fields( + client, signed_in, make_device, make_capture, db +): + signed_in() + device = make_device("garden") + capture = make_capture(device) + row = db.get(Capture, capture.id) + row.radar_distance_cm = 180 + db.commit() + + body = client.get(f"/api/v1/captures/{capture.id}").json() + assert body["device_name"] == "garden" + assert body["radar_distance_cm"] == 180 + assert body["observations"] == [] + assert body["tags"] == [] + + +def test_detail_includes_observations_and_marks_their_source( + client, signed_in, make_device, make_capture, db +): + """A model prediction shown as a human label would poison the very + training data this table exists to collect (SPEC 3.2).""" + signed_in() + capture = make_capture(make_device()) + db.add(Observation(capture_id=capture.id, source="model", confidence=0.8, individuals=2)) + db.commit() + + body = client.get(f"/api/v1/captures/{capture.id}").json() + assert len(body["observations"]) == 1 + assert body["observations"][0]["source"] == "model" + assert body["observations"][0]["confidence"] == 0.8 + assert body["observations"][0]["individuals"] == 2 + + +def test_detail_includes_tags(client, signed_in, make_device, make_capture, db): + signed_in() + capture = make_capture(make_device()) + tag = Tag(label=f"t_{secrets.token_hex(4)}", colour="#0066cc") + db.add(tag) + db.commit() + db.execute( + text("INSERT INTO capture_tags (capture_id, tag_id) VALUES (:c, :t)"), + {"c": capture.id, "t": tag.id}, + ) + db.commit() + + try: + body = client.get(f"/api/v1/captures/{capture.id}").json() + assert [t["label"] for t in body["tags"]] == [tag.label] + finally: + db.execute(text("DELETE FROM capture_tags WHERE tag_id = :t"), {"t": tag.id}) + db.execute(text("DELETE FROM tags WHERE id = :t"), {"t": tag.id}) + db.commit() + + +# --- delivery --------------------------------------------------------------- + + +def test_production_hands_off_to_caddy_without_reading_the_file( + client, signed_in, make_device, make_capture, handoff_delivery +): + """The default: authorise, then let Caddy serve the bytes (SPEC 3.3). + + The body must be empty. Python never opening the file is the point -- a + 3 MB JPEG should not occupy a worker thread. + """ + signed_in() + capture = make_capture(make_device()) + + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 200 + assert response.content == b"" + assert response.headers["x-accel-redirect"] == f"/images/2026/09/20/{capture.id}.jpg" + + +def test_the_thumbnail_hands_off_from_the_thumb_root( + client, signed_in, make_device, make_capture, handoff_delivery +): + signed_in() + capture = make_capture(make_device()) + + response = client.get(f"/api/v1/captures/{capture.id}/thumb") + assert response.status_code == 200 + assert response.headers["x-accel-redirect"] == f"/thumbs/{capture.id}_400.webp" + + +def test_development_serves_the_bytes_itself( + client, signed_in, make_device, make_capture, direct_delivery +): + """Without this the Vite dev server would proxy an empty 200 and every + image in the gallery would be blank, with nothing to explain why.""" + signed_in() + capture = make_capture(make_device()) + + source = get_settings().image_root / capture.path + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(b"\xff\xd8\xffnot a real jpeg but bytes") + + try: + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 200 + assert response.content == b"\xff\xd8\xffnot a real jpeg but bytes" + assert response.headers["content-type"] == "image/jpeg" + assert "x-accel-redirect" not in response.headers + finally: + source.unlink(missing_ok=True) + + +def test_a_missing_file_is_404_when_the_app_serves_it( + client, signed_in, make_device, make_capture, direct_delivery +): + """The row says there is a file and there is not -- the database and the + disk have diverged. 404, and logged loudly.""" + signed_in() + capture = make_capture(make_device()) + assert client.get(f"/api/v1/captures/{capture.id}/image").status_code == 404 + + +def test_a_capture_with_no_thumbnail_is_404_not_the_full_image( + client, signed_in, make_device, make_capture +): + """Falling back to the full JPEG would make a grid of 200 tiles quietly + fetch a hundred times the bytes and still look like it worked.""" + signed_in() + capture = make_capture(make_device(), thumb=False) + + response = client.get(f"/api/v1/captures/{capture.id}/thumb") + assert response.status_code == 404 + assert "x-accel-redirect" not in response.headers + + +def test_a_stored_path_cannot_escape_the_image_root( + client, signed_in, make_device, make_capture, direct_delivery +): + """captures.path is written by our own ingest code, so this should never + happen. "Should never" is not a security control, and the cost of being + wrong is serving an arbitrary file off the server. + + The escape target is a file that really exists just outside the root, not + /etc/passwd: on Windows that path is absent anyway, so the test would pass + for the wrong reason and would not notice the check being removed. + """ + signed_in() + root = get_settings().image_root + outside = root.parent / "not-for-the-web.txt" + outside.parent.mkdir(parents=True, exist_ok=True) + outside.write_bytes(b"SECRET-CANARY") + + capture = make_capture(make_device(), path=f"../{outside.name}") + + try: + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 404 + assert b"SECRET-CANARY" not in response.content + finally: + outside.unlink(missing_ok=True) + + +def test_the_handoff_path_cannot_escape_either( + client, signed_in, make_device, make_capture, handoff_delivery +): + """The production path must refuse it too. A traversal in the header would + make *Caddy* read the file, where the app never touches it at all.""" + signed_in() + capture = make_capture(make_device(), path="../../etc/passwd") + + response = client.get(f"/api/v1/captures/{capture.id}/image") + assert response.status_code == 404 + assert "x-accel-redirect" not in response.headers