The server half of the gallery. Listing and delivery land together because neither is useful alone: a listing with no way to fetch bytes renders empty tiles, and image serving with nothing to enumerate has no entry point. Delivery follows the design deploy/Caddyfile already committed to. The app authorises, then answers empty with X-Accel-Redirect and Caddy reads the file, so a 3 MB JPEG never occupies a Python worker thread. There is no Caddy in development, though, and that header reaching a browser is an empty 200 - every image in the gallery blank, with nothing to explain it. So POORBIRD_SERVE_IMAGES_DIRECTLY makes the app send the bytes instead. The important part is what that flag does NOT do: the authorisation is the same code either way, and the flag only changes how an already-authorised response is finished. A separate unauthenticated file route "only reachable in dev" is exactly the kind of thing that survives into production because it works, and this deliberately is not one. Both delivery paths refuse a path that escapes its root. captures.path is written by our own ingest code so it should never happen, but "should never" is not a security control and the cost of being wrong is serving an arbitrary file off the server. The handoff path needs it just as much as the direct one - a traversal in the header makes *Caddy* read the file, where the app never opens it at all. Keyset paging, not OFFSET. At 5000 captures a day OFFSET gets slower the further back you scroll, which is the direction a gallery scrolls. The cursor carries (received_at, id), and the id is in there for a specific reason: a burst arrives inside the same fraction of a second, so ties are normal rather than exotic, and a timestamp-only cursor would either repeat rows or skip them. A gallery that loses a frame while you scroll is one you cannot trust. Page size is fetched as limit + 1 rather than counted. It answers "is there another page" without a COUNT over the whole filtered set, and the test for a full final page covers the off-by-one that trick invites. Filters cover the columns that have data: device, received-date range, kept, reviewed, pre_trigger, trigger. Taxon and tag filters are in TODO Phase 3 and deliberately absent - both need a join, and neither has anything 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 offers it. Dates filter on received_at and never captured_at_device, which is NULL whenever the camera's clock was unsynced (API.md, X-Captured-At: 0). Filtering on it would silently drop exactly those frames. A missing thumbnail is 404 rather than a fallback to the full JPEG. The grid needs to tell "queued" from "never decoded" and show a placeholder; a silent fallback would make 200 tiles fetch a hundred times the bytes and still look like it worked. `poorbird check` now verifies the layout the handoff depends on: Caddy serves the PARENT of both roots, so they have to be siblings named images/ and thumbs/. Getting it wrong produces 404s from Caddy with nothing in the app's log, which is the kind of thing worth failing a preflight check over rather than discovering in a browser. One test-quality fix worth naming: two delivery tests were inheriting their mode from whatever server/.env happened to say, and broke the moment SERVE_IMAGES_DIRECTLY=true was added there for the dev server's benefit. Both modes are now named explicitly by a fixture, and conftest pins the production default - a test that changes its answer because of an untracked file is not testing the code. Verified against the real server and the six real captures already in the dev database: 401 before signing in, two pages of three with no overlap and correct termination, device_name garden-feeder on the detail, a 1572-byte WebP with RIFF magic and a 3469-byte JPEG with FFD8FF magic, and 401 on the image again immediately after logout. Mutation-tested the two claims that matter: removing the traversal guard and reducing the cursor to a timestamp each failed exactly the tests written for them. The traversal test escapes to a canary file that really exists just outside the root rather than to /etc/passwd, which does not exist on this machine and would have let the test pass for the wrong reason. Tests: 257 -> 293. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
155 lines
6.7 KiB
Python
155 lines
6.7 KiB
Python
"""Configuration.
|
|
|
|
Every value comes from the environment (TODO.md Phase 1.2). Nothing is read
|
|
from a committed config file, and no path, host or secret is baked into code.
|
|
systemd supplies these via ``EnvironmentFile=/etc/poorbird/poorbird.env``; for
|
|
local development a ``.env`` in the working directory is picked up as well.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
from typing import Literal
|
|
|
|
from pydantic import SecretStr, field_validator
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
# Values that mean "nobody filled this in". The .example files ship with these,
|
|
# and a copied-but-unedited example must not boot as if it were configured.
|
|
_PLACEHOLDERS = frozenset({"change_me", "changeme", "todo", "xxx", "secret"})
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
model_config = SettingsConfigDict(
|
|
env_prefix="POORBIRD_",
|
|
env_file=".env",
|
|
env_file_encoding="utf-8",
|
|
extra="ignore",
|
|
)
|
|
|
|
# --- database ---------------------------------------------------------
|
|
# Loopback TCP with scram-sha-256, deliberately not a Unix socket: a socket
|
|
# is the one genuinely container-hostile choice (TODO.md Phase 1.2).
|
|
#
|
|
# No default. A working URL in code means real credentials in code, and the
|
|
# module docstring above already promises none (REVIEW SEC-006). Absence is
|
|
# reported by ``poorbird check`` and raised with a readable message by db.py,
|
|
# rather than silently connecting to whatever happens to be on localhost.
|
|
database_url: str = ""
|
|
# FastAPI runs this app's ``def`` handlers in anyio's threadpool (40 threads
|
|
# by default), and each one holds a session for the whole request. A pool of
|
|
# 5 meant the 6th concurrent request waited on ``pool_timeout`` before it
|
|
# even reached the database (REVIEW §7). The real ceiling is
|
|
# pool_size + db_max_overflow, so both are named here rather than left to
|
|
# SQLAlchemy's invisible default of 10.
|
|
db_pool_size: int = 15
|
|
db_max_overflow: int = 10
|
|
db_echo: bool = False
|
|
|
|
# --- http -------------------------------------------------------------
|
|
api_host: str = "127.0.0.1"
|
|
api_port: int = 8080
|
|
|
|
# --- storage ----------------------------------------------------------
|
|
# A small number of explicit top-level directories, never scattered under
|
|
# the app dir: these are the future volume mounts.
|
|
#
|
|
# image_root is the single source of truth for the image path. Caddy reads
|
|
# the same value, because the auth-checked handoff (SPEC 3.3) needs the app
|
|
# and the proxy to agree on where the bytes live.
|
|
image_root: Path = Path("/srv/poorbird/images")
|
|
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,
|
|
# or you remove the last-resort recovery path for a mounted camera.
|
|
#
|
|
# Environment only, never a literal here (REVIEW SEC-001). Empty is allowed
|
|
# so the Phase 1 commands still run on a fresh clone; the device endpoints
|
|
# 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
|
|
# bucket and start asserting against 429s.
|
|
rate_limit_enabled: bool = True
|
|
|
|
# --- worker -----------------------------------------------------------
|
|
# Idle polling only: the loop drains a non-empty queue back to back without
|
|
# sleeping, so this is the delay before a *newly* enqueued job is noticed,
|
|
# not a per-job cost. 5s trades latency nobody can perceive on a bird camera
|
|
# for 12 idle queries a minute instead of 30.
|
|
worker_poll_interval_s: float = 5.0
|
|
job_max_attempts: int = 3
|
|
|
|
# --- logging ----------------------------------------------------------
|
|
# Always to stdout/stderr. journald catches it now; a log driver would
|
|
# catch it later. Never app-managed log files.
|
|
log_level: str = "INFO"
|
|
log_format: Literal["text", "json"] = "text"
|
|
|
|
@field_validator("database_url")
|
|
@classmethod
|
|
def _reject_unedited_example(cls, v: str) -> str:
|
|
if any(p in v.lower() for p in _PLACEHOLDERS):
|
|
raise ValueError(
|
|
"POORBIRD_DATABASE_URL still contains a placeholder from the "
|
|
"example file. Put the real password in, or leave the variable "
|
|
"unset."
|
|
)
|
|
return v
|
|
|
|
@field_validator("enroll_secret")
|
|
@classmethod
|
|
def _reject_placeholder_secret(cls, v: SecretStr) -> SecretStr:
|
|
if v.get_secret_value().strip().lower() in _PLACEHOLDERS:
|
|
raise ValueError(
|
|
"POORBIRD_ENROLL_SECRET is a placeholder. Generate one with "
|
|
"'openssl rand -hex 32', or leave it unset until Phase 2."
|
|
)
|
|
return v
|
|
|
|
@property
|
|
def database_url_is_set(self) -> bool:
|
|
return bool(self.database_url.strip())
|
|
|
|
@property
|
|
def enroll_secret_is_set(self) -> bool:
|
|
return bool(self.enroll_secret.get_secret_value())
|
|
|
|
def storage_paths(self) -> list[Path]:
|
|
return [self.image_root, self.thumb_root, self.state_dir]
|
|
|
|
|
|
@lru_cache
|
|
def get_settings() -> Settings:
|
|
return Settings()
|