diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f1d70ac --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Node / web build +node_modules/ +dist/ +.vite/ +*.tsbuildinfo + +# Python (server/ has its own .gitignore; these are a repo-wide safety net) +.venv/ +venv/ +__pycache__/ +*.py[cod] +*.egg-info/ +.pytest_cache/ +.ruff_cache/ + +# Secrets - never commit. Use the .example files instead. +.env +.env.* +!.env.example +!*.env.example + +# Local runtime state +*.log + +# OS / editor +Thumbs.db +desktop.ini +.DS_Store diff --git a/TODO.md b/TODO.md index 19a5629..47f7df1 100644 --- a/TODO.md +++ b/TODO.md @@ -26,10 +26,10 @@ Anything here that contradicts SPEC means SPEC needs an edit, not a workaround. | Area | State | |---|---| | Firmware | Written, compiles, **never run on hardware**. Known gaps below. | -| Device↔server contract | Specified in full (`firmware/API.md`). Nothing implements the server half. | -| Data model | Designed (SPEC §3) + §0 additions. No migration written. | -| Server | Phase 1 skeleton in [`server/`](server/) — config, schema, health, job queue, scheduler, systemd units. Verified end to end on Python 3.14.7 against PostgreSQL 17: 12/12 tests, migrations applied, API serving, worker draining the queue. Not yet on the real host. | -| WebUI | **Nothing exists.** | +| Device↔server contract | Specified in full (`firmware/API.md`). Server half of the **device** endpoints implemented (Phase 2); the operator-facing half (firmware upload, device management) waits on user auth in Phase 3. | +| Data model | Designed (SPEC §3) + §0 additions, migration written and applied, guarded by a drift test. | +| Server | Phases 1 and 2 in [`server/`](server/) — config, schema, health, job queue, scheduler, systemd units, and every device endpoint the firmware calls. Verified on Python 3.14.7 against PostgreSQL 17: 194 tests, migrations applied, real HTTP ingest through the worker to a WebP thumbnail on disk. Not yet on the real host, and **never yet spoken to by real firmware**. | +| WebUI | **Nothing exists** beyond the Vite scaffold on `feature/UI_Basic_implementation`. | --- @@ -89,7 +89,7 @@ written vs. what still needs doing on the real host: - [ ] PostgreSQL 17 from the distro or PGDG repo; dedicated role + database; **loopback TCP with `scram-sha-256`, not a Unix socket** (see 1.2) - [ ] Caddy DNS provider plugin build (`caddy add-package …`) and a real hostname - [ ] Tailscale for remote access -- [ ] Image store at `/srv/poorbird/images/YYYY/MM/DD/.jpg`, thumbs alongside as `_400.webp` (SPEC §3.3) — paths configured, writer is Phase 2 +- [x] Image store at `/srv/poorbird/images/YYYY/MM/DD/.jpg`, thumbs alongside as `_400.webp` (SPEC §3.3) — writer landed with Phase 2; writes are atomic (`.part` then `os.replace`) so a crash cannot leave a half-JPEG that a thumbnail job would then fail on - [ ] journald log retention capped, disk usage alarmed ### 1.1 Schema — SPEC §3 plus the §0 additions @@ -126,15 +126,30 @@ cheap today and most are the better native choice regardless. The first milestone worth celebrating. Nothing below this line matters until a real bird photo appears in a browser. -- [ ] `POST /api/v1/enroll` — bootstrap secret in, per-device `reenroll_secret` + token out. +- [x] `POST /api/v1/enroll` — bootstrap secret in, per-device `reenroll_secret` + token out. **Re-enrolling a known `device_uid` must return the existing row with a fresh token, never a duplicate.** -- [ ] `POST /api/v1/ingest` — multipart image + JSON meta, honour `X-Pre-Trigger`, dedupe on sha256 -- [ ] `POST /api/v1/heartbeat` and `POST /status` — full conditions report into `device_status` -- [ ] `GET /api/v1/config` — enums by name not number, `config_version` bump semantics -- [ ] Response envelope + `server_time` in **every** response (SPEC C7: `received_at` stays authoritative) -- [ ] Thumbnail job on ingest -- [ ] Minimal gallery page, no auth yet, purely to prove the path -- [ ] **End-to-end test on real hardware:** bird walks past → burst uploads → visible in browser + Accepts the shared secret *or* that device's own `reenroll_secret`; checking only the + shared one would lock out every device already enrolled. Hardware facts (`mac`, + `hw_revision`, `fw_version`) refresh on every enrollment, the operator's `name` does not. +- [x] `POST /api/v1/ingest` — **raw JPEG body with metadata in headers, not multipart.** + `firmware/API.md` and `uploader.cpp` send the bytes directly; multipart was a + misreading. Honours `X-Pre-Trigger`, dedupes on sha256 per device. +- [x] `POST /api/v1/heartbeat` and `POST /status` — full conditions report into `device_status` +- [x] `GET /api/v1/config` — enums by name not number, `config_version` bump semantics. + Column-backed keys win over stale JSONB copies, so an operator rename actually reaches + the device; the device's own `config_version` never overwrites the server's. +- [x] Response envelope + `server_time` (SPEC C7: `received_at` stays authoritative). + On `/heartbeat` and `/ingest`. **Not** on `/status`, which is 204 with no body per + `firmware/API.md` — "every response" was not compatible with the firmware contract. +- [x] Thumbnail job on ingest — 400px WebP, decode kept off the request path +- [x] Device authentication, rate limiting, `POST /commands/{id}/ack`, `GET /firmware/{v}.bin` + — not in the original list, but the firmware calls them (see `docs/reviews/`) +- [~] Minimal gallery page purely to prove the path — **superseded.** The scaffold's System page + already proves browser → proxy → FastAPI → Postgres, and SPEC §3.3 requires image serving + to be auth-checked, so "no auth yet" is not a state the gallery can legitimately pass + through. The real grid is Phase 3, behind sessions. +- [ ] **End-to-end test on real hardware:** bird walks past → burst uploads → visible in browser. + Blocked on Phase 0: the server side is proven only against synthetic uploads. --- @@ -155,10 +170,16 @@ and the System page reads live data through the Vite proxy. - [ ] Observation editor — `captures` 1—n `observations`, so a photo can hold two species or none - [ ] Taxon autocomplete; seed `taxa` with 60–80 Central European garden species incl. GBIF keys, `name_de` + `name_en`, `is_local_common` ranking first - [ ] Tags, favourite/reject (`kept`), review flag -- [ ] Three themes — light, dark, blue — as design tokens → CSS custom properties, persisted per user +- [ ] Persist the theme choice **per user** (`users.theme`) rather than in localStorage — the + tokens and the switcher are done (above); this is the half that needs accounts to exist - [ ] Auth: session cookies, Argon2id, CSRF, RBAC per SPEC §3.1 (viewer / editor / admin), `audit_log` on every mutation - [ ] **Auth-checked image serving** — the app authorizes, Caddy serves the bytes. An unguessable URL is not access control - [ ] TOTP 2FA — see 3.0 for the policy +- [ ] **Revisit CORS.** Deliberately not configured in Phase 2: Caddy serves the built UI and the + API from one origin, so there is no cross-origin request to permit, and adding permissive + headers "for the UI" would only weaken that. The Vite dev server proxies `/api` for the + same reason, so development matches production. Decide it properly only if the UI is ever + served from somewhere else — *then* it matters. ### 3.0 UI decisions (2026-09-21) @@ -231,7 +252,11 @@ brings real captures, which is the only test that counts. - [ ] Device list with live/awake state, last seen, RSSI, heap/PSRAM, ring depth - [ ] Settings editor writing the `devices` settings surface → `apply_config` → `config_version` - [ ] Command queue UI: `wake_and_hold`, `capture_now`, `apply_config`, `ota_update`, `stream_start`, `reboot`; commands ride along on the ingest response -- [ ] Firmware upload, SHA-256, target marking, per-device staged rollout +- [ ] Firmware upload, SHA-256, target marking, per-device staged rollout. + `GET /firmware/{version}.bin` already serves the bytes; the upload half was left out of + Phase 2 because it needs operator auth. **Constrain `firmware.is_target` to a single row + while doing this** — nothing enforces it today, and the lookup takes the first match, so + two target rows would pick non-deterministically between them. - [ ] Verify the full OTA path on hardware: **trial boot and automatic rollback**. The camera is unreachable once mounted — this is the one feature with no recovery if it is broken - [ ] Document that rotating the shared bootstrap secret server-side without shipping new firmware **removes the last-resort escape hatch** diff --git a/docs/reviews/server-basic-implementation/REVIEW.AI.md b/docs/reviews/server-basic-implementation/REVIEW.AI.md new file mode 100644 index 0000000..c5b06f2 --- /dev/null +++ b/docs/reviews/server-basic-implementation/REVIEW.AI.md @@ -0,0 +1,1301 @@ +# AI Reviewer Guide: poorBird Server (feature/Server_Basic_implementation) + +**Purpose:** This document provides comprehensive context for AI systems to analyze and improve the poorBird codebase, with specific focus on Phase 1 (Server Foundation) completion and Phase 2 (Device Endpoints) preparation. + +**Target Audience:** AI code review systems (like Mistral Vibe, Claude, etc.) + +**Created:** 2026-09-21 by Mistral Vibe + +**Branch:** feature/Server_Basic_implementation (Commit: 142b476) + +--- + +## 0. Branch Context (CRITICAL FOR AI UNDERSTANDING) + +### Branch Identity +- **Name:** feature/Server_Basic_implementation +- **Commit:** 142b476 ("Server: Phase 2 (REVIEW not respected yet)") +- **Actual Content:** Server code only (Phase 1 COMPLETE + Phase 2 STARTED) +- **Relation:** Canonical server branch, basis for feature/UI_Basic_implementation +- **Purpose:** Server foundation and Phase 2 device endpoints + +### Important Observation +This branch is the **canonical server branch**. It contains: +- ✅ Complete server infrastructure (Phase 1) +- ✅ All database models +- ✅ Job queue with PostgreSQL (FOR UPDATE SKIP LOCKED) +- ✅ Health endpoints +- ✅ Systemd units and Caddy configuration +- ✅ Migrations and schema validation +- ❌ **No device endpoints yet** (Phase 2 not fully implemented) +- ❌ **No authentication** (needed for Phase 2/3) + +**Note:** Commit 142b476 added web/ build files (Vite dist output), but these are build artifacts, not source code. The actual server source code is identical to feature/UI_Basic_implementation at commit 5d16ded. + +### Phase Information +``` +Phase 1 (DONE): Server foundation, config, schema, health, job queue, scheduler +Phase 2 (STARTED): Device endpoints (/enroll, /ingest, /heartbeat, /status, /config) +Phase 3 (TARGET): WebUI (React+TS+Vite) - in feature/UI_Basic_implementation +Phase 4: Device management, OTA +Phase 5: Operations (backup, retention, alarms) +Phase 6: Streaming +``` + +### Key Difference from UI Branch +- This branch: **Server-only**, canonical server code +- UI branch: **Server + UI review files**, but same server code base +- Both branches share the same server implementation (commit 5d16ded) + +--- + +## 1. Project Overview (ESSENTIAL CONTEXT) + +### Core Purpose +Radar-triggered bird camera system that: +1. Detects birds using LD2410 radar sensor +2. Captures images with ESP32 camera +3. Transmits to server via MQTT +4. Stores images and metadata in PostgreSQL +5. Provides web interface for viewing and managing captures + +### Domain +- **Primary:** IoT + Computer Vision + Web Application +- **Secondary:** Data Management, Device Management, User Management + +### Users +| User Type | Access Level | Use Cases | +|-----------|--------------|----------| +| Device | API only | Enroll, ingest images, send status | +| Viewer | Read-only | View gallery, search, filter | +| Editor | Read+Write | View + add observations, tags, edit metadata | +| Admin | Full | All editor + device management, user management, settings | + +### Deployment Architecture +``` +┌─────────────────────────────────────────────────────────┐ +│ Client (Browser) │ +└─────────────────────────┬───────────────────────────────┘ + │ HTTPS (TLS via DNS-01) + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Caddy (Reverse Proxy) │ +│ ┌─────────────────────┐ ┌─────────────────────────┐ │ +│ │ Static UI Files │ │ API Requests │ │ +│ │ /srv/poorbird/ │ │ /api/v1/* │ │ +│ └──────────┬────────────┘ └──────────┬─────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────────────────────────────────────────────┐│ +│ │ React/TS Frontend ││ +│ │ (NOT YET IMPLEMENTED) ││ +│ └─────────────────────────────────────────────────────┘│ +│ │ +└──────────────────────────────────────────────┬─────┘ + │ + ┌────────────────────────────────▼─────────────┐ + │ FastAPI Backend (Phase 1 Complete) │ + │ ┌──────────────┐ ┌──────────────┐ │ + │ │ API Layer │ │ Worker Layer │ │ + │ │ /api/v1/* │ │ Job Queue │ │ + │ └──────────────┘ └──────────────┘ │ + │ │ │ │ + │ ▼ ▼ │ + │ ┌─────────────────────────────────────────┐│ + │ │ PostgreSQL 17 ││ + │ │ ┌──────────┐ ┌──────────┐ ││ + │ │ │ Schema │ │ Job Q │ ││ + │ │ │ (Phase 1)│ │ (Phase 1)│ ││ + │ │ └──────────┘ └──────────┘ ││ + │ └─────────────────────────────────────────┘│ + └────────────────────────────────────────────────┘ +``` + +### Technology Stack +| Layer | Technology | Version | Status | +|-------|------------|---------|--------| +| Backend | Python | 3.14.7 (verified) | Phase 1 Complete | +| Framework | FastAPI | Latest | Phase 1 Complete | +| Database | PostgreSQL | 17 | Phase 1 Complete | +| ORM | SQLAlchemy | 2.0 | Phase 1 Complete | +| Migrations | Alembic | Latest | Phase 1 Complete | +| Logging | structlog/stdout | - | Phase 1 Complete | +| Proxy | Caddy | 2.x | Phase 1 Complete | +| **Frontend** | **React + TypeScript** | **18+** | **NOT STARTED** | + +### Scale Expectations +| Metric | Value | Notes | +|--------|-------|-------| +| Cameras | 1-10 (Phase 3), 100+ (future) | Current: 1 | +| Captures/day | 5000 | 1 camera, ~10/hour | +| Image Size | 200-500KB | JPEG | +| Thumb Size | 20-50KB | WebP, 400px | +| Concurrent Users | 1-5 typical, 10 peak | LAN-only | +| Storage/month | ~1GB | 5000 images * 200KB | +| DB Queries/day | ~10,000 | 5000 captures + 5000 status | + +--- + +## 2. External Contracts (CRITICAL FOR AI UNDERSTANDING) + +### Device ↔ Server API Contract (firmware/API.md) + +**ALL DEVICE ENDPOINTS ARE NOT YET IMPLEMENTED - Phase 2 Task** + +The server MUST implement these endpoints to satisfy the firmware contract. See `firmware/API.md` for complete specification. + +#### Endpoints Overview +- `POST /api/v1/enroll` - Device enrollment +- `POST /api/v1/ingest` - Image ingest with metadata +- `POST /api/v1/heartbeat` - Device heartbeat +- `POST /api/v1/status` - Device status report +- `GET /api/v1/config` - Get device configuration +- `POST /api/v1/firmware` - Firmware upload (admin only) + +### UI-Specific Contract Requirements (SPEC 3.3) + +**Image Serving:** +- **NEVER** serve images directly from filesystem +- **ALWAYS** check authorization in app first +- **THEN** have Caddy serve the bytes via X-Accel-Redirect +- **URL Pattern:** `/images/YYYY/MM/DD/.jpg` +- **Thumb Pattern:** `/thumbs/_400.webp` + +**Authentication:** +- Device auth: X-Enroll-Secret header +- User auth: Session cookies (not JWT for WebUI) +- CSRF protection for all mutating requests +- RBAC: viewer, editor, admin +- Optional TOTP 2FA (SPEC Q14) + +--- + +## 3. Architecture Decisions (WHY THEY MATTER FOR AI) + +### Core Decisions + +| Decision | Rationale | Alternatives | Trade-offs | Impact | +|----------|-----------|--------------|------------|--------| +| **Native Deployment** | SPEC requirement, no container overhead | Docker, Kubernetes | Simpler, but less portable | Must respect | +| **Sync SQLAlchemy** | 1 camera, few K frames/day - async overhead not justified | Async SQLAlchemy | Simpler code, but blocks event loop | OK for current scale | +| **PostgreSQL over TCP** | Container-ready, better performance | Unix socket | More portable | Must use TCP | +| **FOR UPDATE SKIP LOCKED** | Job queue without Redis dependency | Redis, RabbitMQ | No external service, PostgreSQL-only | Works perfectly | +| **JSONB for Config** | 40+ optional settings, firmware evolves | Separate columns | Flexible, but can't index individual settings | Good for device settings | +| **UUID for Captures** | Safe for URLs, distributed systems | Sequential int | Better for URLs | Perfect for /gallery/ | +| **Single Image Root** | App and Caddy must agree on path | Multiple roots | Simpler, single source of truth | Critical for auth-checked handoff | + +### Constraints (AI MUST RESPECT THESE) + +**Hard Constraints:** +- NO Docker (SPEC requirement) +- Native Linux deployment +- PostgreSQL (not SQLite) +- Loopback TCP (not Unix socket) +- systemd units (not supervisor) +- Caddy (not nginx, not Apache) +- No public streaming (Phase 6 is internal only) + +**Soft Constraints:** +- Container-ready design (even though not using containers) +- All config from environment +- All mutable state in explicit directories +- Log to stdout/stderr only +- All paths configurable via environment variables + +**Non-Goals:** +- NO Kubernetes +- NO public streaming (Phase 6 is internal only) +- NO audio/BirdNET (different sensor) +- NO TLS on device (SPEC C2) + +--- + +## 4. Security Analysis (CRITICAL FOR AI) + +### Severity System +- **CRITICAL:** Must fix before any production use. Blocks Phase 2/3. +- **HIGH:** Must fix before Phase 3. Serious risk. +- **MEDIUM:** Should fix before Phase 3. Moderate risk. +- **LOW:** Nice to have. Low risk. + +### Critical Issues (BLOCK PHASE 2/3) + +#### SEC-001: Enroll Secret in Plaintext +- **Location:** config.py:53, .env files, systemd EnvironmentFile +- **Code:** `enroll_secret: SecretStr = SecretStr("")` +- **Issue:** Bootstrap secret stored in plaintext in files +- **Risk:** Filesystem access = complete device spoofing. If any endpoint exposes device management, attacker can enroll malicious devices. +- **Impact:** Catastrophic. Compromises entire device network. +- **Vulnerability Type:** Credential Exposure +- **CVSS:** 9.8 (Critical) +- **Solution:** + ```python + # Option 1: Remove default, CLI-only + enroll_secret: SecretStr # No default + # Only set via: poorbird config set enroll_secret + + # Option 2: Environment variable only + enroll_secret: SecretStr + ``` +- **Files to Modify:** config.py, .env.example, deploy/poorbird.env.example +- **Tests Needed:** Verify secret not logged, not in error messages +- **Priority:** CRITICAL +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 2-4 hours + +#### SEC-002: No Request Authentication +- **Location:** All API endpoints (none have auth yet) +- **Issue:** No authentication for any endpoint +- **Risk:** Anyone can send device commands, access admin functions, manage users +- **Impact:** Complete system compromise. Device endpoints would be wide open. +- **Vulnerability Type:** Missing Authentication +- **CVSS:** 10.0 (Critical) +- **Solution:** + ```python + # Device auth (for /enroll, /ingest, /heartbeat, /status) + from fastapi import Request, HTTPException, Header + + async def verify_device(request: Request, + x_enroll_secret: str = Header(None)): + if not x_enroll_secret: + raise HTTPException(status_code=401) + # Verify against enroll_secret hash + # Lookup device by token + + # User auth (for UI endpoints - Phase 3) + from fastapi import Cookie + + async def verify_user(request: Request, + session_id: str = Cookie(None)): + if not session_id: + raise HTTPException(status_code=401) + # Verify session in DB + # Return user with roles + ``` +- **Files to Create:** api/routes/auth.py, api/deps.py +- **Files to Modify:** app.py (add auth dependencies) +- **Tests Needed:** Auth tests for all endpoint types +- **Priority:** CRITICAL +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 1-2 days + +#### SEC-003: No Input Validation +- **Location:** queue.py:47-66 (enqueue function), all future endpoints +- **Issue:** Payloads not validated before DB insert +- **Risk:** SQL injection, XSS, malicious data, data corruption +- **Impact:** High. Device endpoints accept device input, UI accepts user input. +- **Vulnerability Type:** Missing Input Validation +- **CVSS:** 8.1 (High) +- **Solution:** + ```python + # Example: Job payload validation + from pydantic import BaseModel, Field + from typing import Literal, Optional, Union + + class NoopJobPayload(BaseModel): + """Payload for noop job.""" + message: Optional[str] = None + + class ThumbnailJobPayload(BaseModel): + """Payload for thumbnail job.""" + capture_id: str # UUID + quality: int = Field(ge=1, le=100) + width: int = Field(ge=100, le=2000) + + JobPayload = Union[NoopJobPayload, ThumbnailJobPayload] + + # All enqueue calls must use validated payloads + def enqueue(session: Session, + kind: Literal["noop", "thumbnail"], + payload: JobPayload, + ...): + # Now payload is validated! + ``` +- **Files to Create:** api/schemas.py (Pydantic models for all requests) +- **Files to Modify:** queue.py (add validation to enqueue function) +- **Tests Needed:** Validation tests for all payload types +- **Priority:** CRITICAL +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 1-2 days + +#### SEC-004: No Rate Limiting +- **Location:** API layer (app.py) +- **Issue:** No protection against DoS or brute force +- **Risk:** Device endpoints can be flooded, server overload +- **Impact:** High. Device endpoints would be vulnerable to attack. +- **Vulnerability Type:** Missing Rate Limiting +- **CVSS:** 7.5 (High) +- **Solution:** + ```python + from slowapi import Limiter + from slowapi.util import get_remote_address + from slowapi.errors import RateLimitExceeded + from fastapi import Request + from fastapi.responses import JSONResponse + + limiter = Limiter(key_func=get_remote_address) + + @app.exception_handler(RateLimitExceeded) + async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded): + return JSONResponse( + status_code=429, + content={"detail": "Too many requests"}, + headers={"Retry-After": str(exc.retry_after)} + ) + + # Apply to device endpoints + @app.post("/api/v1/enroll") + @limiter.limit("10/hour") # Enrollment should be rate-limited + async def enroll_device(request: Request): + ... + + @app.post("/api/v1/ingest") + @limiter.limit("100/minute") # Higher limit for image uploads + async def ingest_image(request: Request): + ... + ``` +- **Files to Create:** None (add to app.py) +- **Files to Modify:** app.py +- **Configuration:** Add to pyproject.toml: slowapi +- **Tests Needed:** Rate limiting tests +- **Priority:** HIGH +- **Block:** Phase 2 (Device Endpoints) +- **Effort:** 1 day + +### High Priority Issues (FIX BEFORE PHASE 2) + +#### SEC-005: No CORS Configuration +- **Location:** API layer +- **Issue:** No CORS headers configured +- **Risk:** Future WebUI cannot make requests if on different origin +- **Impact:** UI development will be blocked +- **Vulnerability Type:** Missing CORS +- **CVSS:** 6.5 (Medium) +- **Solution:** + ```python + from fastapi.middleware.cors import CORSMiddleware + + app.add_middleware( + CORSMiddleware, + allow_origins=[ + "http://localhost:3000", # Dev + "http://localhost:5173", # Vite dev + "https://poorbird.local", # Prod + ], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + expose_headers=["X-Request-ID"], + ) + ``` +- **Files to Modify:** app.py +- **Tests Needed:** CORS test +- **Priority:** HIGH +- **Effort:** 1 hour + +#### SEC-006: DB URL with Credentials in Defaults +- **Location:** config.py:30 +- **Issue:** Default value contains plaintext credentials +- **Risk:** Accidental commit of credentials to repo +- **Impact:** Medium. Security risk if committed. +- **Vulnerability Type:** Hardcoded Credentials +- **CVSS:** 7.5 (High) +- **Solution:** + ```python + # Change from: + database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird" + + # To: + database_url: str = "" # Must be set via POORBIRD_DATABASE_URL + ``` +- **Files to Modify:** config.py +- **Tests Needed:** Verify app fails gracefully if not set +- **Priority:** HIGH +- **Effort:** 1 hour + +#### SEC-007: No Session Management +- **Location:** models/users.py has Session model, but not used +- **Issue:** Session table exists but no implementation +- **Risk:** Cannot implement user login/logout for WebUI +- **Impact:** High. Phase 3 (WebUI) authentication impossible. +- **Vulnerability Type:** Missing Functionality +- **Solution:** + ```python + # Session creation on login + from datetime import datetime, timedelta + from sqlalchemy.orm import Session as DbSession + from .models import Session, User + + def create_session(db: DbSession, user: User) -> Session: + session = Session( + user_id=user.id, + expires_at=datetime.utcnow() + timedelta(days=30), + ip=request.client.host, + user_agent=request.headers.get("user-agent"), + ) + db.add(session) + db.commit() + db.refresh(session) + return session + + def verify_session(db: DbSession, session_id: str) -> User | None: + session = db.query(Session).filter( + Session.id == session_id, + Session.expires_at > datetime.utcnow() + ).first() + if session: + session.expires_at = datetime.utcnow() + timedelta(days=30) + db.commit() + return session.user + return None + ``` +- **Files to Create:** api/routes/auth.py +- **Files to Modify:** models/users.py (add session management methods) +- **Tests Needed:** Session lifecycle tests +- **Priority:** HIGH +- **Effort:** 1 day + +### Medium Priority Issues + +#### SEC-008: No Password Hashing Implementation +- **Location:** models/users.py (password_hash column exists) +- **Issue:** password_hash column exists but no hashing implementation +- **Risk:** If someone implements password setting without hashing, passwords stored in plaintext +- **Impact:** Medium. Future security risk. +- **Solution:** + ```python + import argon2 + from argon2 import PasswordHasher + + ph = PasswordHasher( + time_cost=3, + memory_cost=65536, + parallelism=4, + hash_len=32, + salt_len=16, + ) + + def hash_password(password: str) -> str: + return ph.hash(password) + + def verify_password(password: str, hash: str) -> bool: + try: + return ph.verify(hash, password) + except: + return False + ``` +- **Files to Create:** api/utils/auth.py +- **Files to Modify:** models/users.py +- **Tests Needed:** Password hashing tests +- **Priority:** MEDIUM +- **Effort:** 2-4 hours + +#### SEC-009: No Image Upload Validation +- **Location:** Future device ingest endpoint +- **Issue:** Images not validated before saving +- **Risk:** Malicious file uploads (e.g., PHP files, scripts) +- **Impact:** Medium. Could lead to server compromise. +- **Solution:** + ```python + import magic # python-magic + from pathlib import Path + + ALLOWED_TYPES = {"image/jpeg", "image/png", "image/webp"} + MAX_SIZE = 10 * 1024 * 1024 # 10MB + MAX_DIMENSIONS = (4000, 4000) # width, height + + def validate_image(file_path: Path) -> tuple[bool, str]: + # Check file size + if file_path.stat().st_size > MAX_SIZE: + return False, "File too large" + + # Check MIME type + mime = magic.from_file(file_path, mime=True) + if mime not in ALLOWED_TYPES: + return False, f"Invalid file type: {mime}" + + # Check dimensions + try: + from PIL import Image + with Image.open(file_path) as img: + if img.size[0] > MAX_DIMENSIONS[0] or img.size[1] > MAX_DIMENSIONS[1]: + return False, "Image too large" + except: + return False, "Invalid image" + + return True, "Valid" + ``` +- **Files to Create:** api/utils/image_validation.py +- **Tests Needed:** Image validation tests +- **Priority:** MEDIUM +- **Effort:** 2-4 hours + +--- + +## 5. Data Model Analysis (FOR DEVICE & UI DEVELOPMENT) + +### Complete Schema + +The data model is **excellent** and perfectly designed for the requirements. All tables from SPEC S3 are implemented plus additional tables from SPEC S0. + +```sql +-- Users and Authentication +CREATE TABLE users (...) -- Roles: admin, editor, viewer +CREATE TABLE sessions (...) -- UUID primary key, user_id, expires_at + +-- Devices and Commands +CREATE TABLE devices (...) -- device_uid (MAC-based), config JSONB, token_hash +CREATE TABLE device_commands (...) -- type, payload JSONB, created_by, delivered_at +CREATE TABLE device_status (...) -- Time-series data from devices + +-- Firmware +CREATE TABLE firmware (...) -- version, semver, file_path, sha256 + +-- Captures and Observations (CORE) +CREATE TABLE captures (...) -- UUID primary key, path, thumb_path, sha256 +CREATE TABLE observations (...) -- capture_id, taxon_id, individuals, source (human/model) +CREATE TABLE taxa (...) -- scientific_name, name_de, name_en, gbif_key +CREATE TABLE tags (...) -- label, colour +CREATE TABLE capture_tags (...) -- Many-to-many + +-- Operational Tables +CREATE TABLE settings (...) -- key, value, scope (server/device) +CREATE TABLE audit_log (...) -- user_id, action, entity, before/after JSONB +CREATE TABLE backup_runs (...) -- started_at, finished_at, status + +-- Job Queue (PostgreSQL-backed) +CREATE TABLE jobs (...) -- kind, payload JSONB, status, priority, run_at +``` + +### Key Relationships +``` +users (1) ── (n) sessions + └── (n) audit_log + └── (n) device_commands (created_by) + └── (n) firmware (uploaded_by) + └── (n) observations (created_by) + +devices (1) ── (n) captures + ├── (n) device_status + ├── (n) device_commands + └── (1) current firmware (via is_target) + +captures (1) ── (n) observations + ├── (n) tags (via capture_tags) + └── (1) device + +observations (n) ── (1) taxa +observations (n) ── (1) capture +observations (n) ── (1) user (created_by) + +tags (n) ── (n) captures (via capture_tags) +``` + +### UI-Relevant Fields (for Phase 3) + +**Captures:** +- `id` (UUID) - Primary key, used in URLs +- `path`, `thumb_path` - File paths for images +- `received_at` - **AUTHORITATIVE timestamp** (SPEC C7) +- `trigger` - How capture was triggered (radar, manual, timer, stream_grab) +- `pre_trigger` - Was this frame captured BEFORE the trigger fired? +- `kept` - Soft reject flag +- `reviewed` - Has this been reviewed? +- `radar_*` - Radar data for analysis +- `battery_*`, `rssi`, `temp_c` - Device conditions at capture time + +**Observations:** +- `source` - 'human' or 'model' (future ML integration) +- `taxon_id` - Links to species data +- `model_version`, `confidence`, `bbox` - For ML predictions +- `age`, `sex`, `behaviour`, `certainty` - Observation metadata +- `individuals` - Number of birds in this observation + +**Taxa:** +- `scientific_name` - Unique scientific name +- `name_de`, `name_en` - Localized names +- `gbif_key` - GBIF identifier +- `is_local_common` - For autocomplete ranking (local species first) + +**Devices:** +- `device_uid` - MAC-based identity, survives reflashing +- `config` - JSONB with all device settings +- `config_version` - Increments on every config change +- `battery_valid` - **CRITICAL**: false = **NOT MEASURED**, not empty! +- `awake` - Device is awake and responsive + +**Device Status:** +- All fields are time-series data +- Counters (captured_today, etc.) are from RTC memory +- **CRITICAL**: Counters reset on power loss +- **UI Display**: Counters show GAP between captured and delivered + +--- + +## 6. Current Implementation Status + +### What Exists (Phase 1 - Server Foundation) + +``` +server/ +├── src/poorbird/ +│ ├── __init__.py # Version: 0.1.0 +│ ├── config.py # All settings from environment +│ ├── logging_setup.py # stdout-only logging +│ ├── db.py # SQLAlchemy engine + session +│ ├── schema_compare.py # Schema drift normalization (GENIUS!) +│ ├── models/ +│ │ ├── __init__.py # Imports all models +│ │ ├── base.py # Base class + naming convention +│ │ ├── captures.py # Captures, Observations, Taxa, Tags +│ │ ├── devices.py # Devices, Commands, Status, Firmware +│ │ ├── ops.py # Settings, AuditLog, BackupRun, Job +│ │ └── users.py # Users, Sessions +│ ├── api/ +│ │ ├── __init__.py +│ │ ├── app.py # FastAPI app + lifespan +│ │ ├── deps.py # Empty (potential for dependencies) +│ │ └── routes/ +│ │ ├── __init__.py +│ │ └── health.py # /api/v1/health, /healthz +│ ├── worker/ +│ │ ├── __init__.py +│ │ ├── main.py # Worker + scheduler +│ │ ├── queue.py # Job queue (FOR UPDATE SKIP LOCKED) +│ │ └── handlers.py # Job handlers (noop, prune_expired_commands) +│ └── cli.py # CLI: serve, worker, migrate, check, enqueue +├── migrations/ +│ ├── env.py # Alembic environment +│ ├── script.py.mako +│ └── versions/ +│ └── 0001_initial.py # Baseline migration +├── deploy/ +│ ├── INSTALL.md +│ ├── poorbird.env.example +│ ├── poorbird-api.service +│ ├── poorbird-worker.service +│ └── Caddyfile +├── tests/ +│ ├── conftest.py +│ ├── test_health.py +│ ├── test_queue.py +│ ├── test_schema_matches_models.py +│ └── test_config.py +├── alembic.ini +├── pyproject.toml +└── README.md +``` + +### What's Missing for Phase 2 + +``` +MISSING - Device Endpoints: +server/src/poorbird/api/routes/ +├── enroll.py # POST /api/v1/enroll +├── ingest.py # POST /api/v1/ingest +├── heartbeat.py # POST /api/v1/heartbeat +├── status.py # POST /api/v1/status +├── config.py # GET /api/v1/config +└── firmware.py # POST /api/v1/firmware + +MISSING - Authentication: +├── Device authentication (X-Enroll-Secret validation) +├── Token generation and management +├── Token hashing +└── Request authentication middleware + +MISSING - Security: +├── Rate limiting +├── CORS configuration +└── Input validation for all endpoints +``` + +### What's Missing for Phase 3 (UI) + +``` +MISSING - Backend (UI Endpoints): +server/src/poorbird/api/routes/ +├── gallery.py # Capture listing, filtering +├── observations.py # Observation CRUD +├── taxa.py # Taxon search/autocomplete +├── tags.py # Tag management +├── devices.py # Device management (UI view) +└── auth.py # User authentication endpoints + +MISSING - Authentication: +├── Session management +├── Password hashing (Argon2id) +├── CSRF protection +└── User role management (RBAC) +``` + +### Implementation Status by Phase + +| Phase | Status | Components | Tests | +|-------|--------|------------|-------| +| Phase 1 | ✅ COMPLETE | Server foundation, config, schema, health, job queue, scheduler | 12/12 | +| Phase 2 | ❌ NOT STARTED | Device endpoints, device authentication | 0/0 | +| Phase 3 | ❌ NOT STARTED | WebUI (React+TS+Vite), UI endpoints, user authentication | 0/0 | +| Phase 4 | ❌ NOT STARTED | Device management, OTA | 0/0 | +| Phase 5 | ❌ NOT STARTED | Operations (backup, retention, alarms) | 0/0 | +| Phase 6 | ❌ NOT STARTED | Streaming | 0/0 | + +--- + +## 7. Performance Analysis + +### Current Configuration + +| Component | Setting | Current Value | Impact | Rating | Recommendation | +|-----------|---------|---------------|--------|--------|----------------| +| DB Connection Pool | db_pool_size | 5 | May block concurrent requests | 3/5 | 15-20 for Phase 3 | +| Worker Poll Interval | worker_poll_interval_s | 2.0 | Frequent polling on empty queue | 3/5 | 5.0 for Phase 2 | +| Batch Size | worker_batch_size | 1 | Single job processing | 3/5 | 5-10 for Phase 2 | +| Sync SQLAlchemy | - | Enabled | Blocks event loop under load | 4/5 | OK for current scale | +| Log Level | log_level | INFO | Good for development | 4/5 | OK | +| Image Root | image_root | /srv/poorbird/images | Good structure | 5/5 | OK | +| Thumb Root | thumb_root | /srv/poorbird/thumbs | Good structure | 5/5 | OK | + +### Expected Load Profile + +**Device Communication:** +- Heartbeat: Every 5-15 minutes per device +- Status: Every 15-30 minutes per device +- Image ingest: ~10/hour/camera (5000/day) +- Burst images: 3-5 images per trigger event + +**Phase 2 Load (1 Camera):** +- API requests: ~200-300/day +- DB writes: ~5000 captures + ~200 device_status = 5200/day +- Image storage: ~1GB/month + +**Phase 3 Load (WebUI):** +- Gallery page: 20-50 images initial, 20 per scroll +- Filter queries: 100-500ms with proper indexes +- Concurrent users: 1-5 typical, 10 peak + +### Bottlenecks to Address Before Phase 2 + +1. **DB Connection Pool (MEDIUM)** + - Current: 5 connections + - Issue: May block under concurrent device requests + - Solution: Increase to 10-15 for Phase 2 + - Impact: Supports multiple concurrent devices + +2. **Worker Poll Interval (LOW)** + - Current: 2 seconds + - Issue: Frequent polling on empty queue + - Solution: Increase to 5 seconds + - Impact: Reduced CPU usage + +3. **Sync SQLAlchemy (FUTURE)** + - Current: Synchronous + - Issue: Blocks event loop under heavy load + - Solution: Evaluate async for Phase 6 (MJPEG streaming) + - Impact: May be needed for high-concurrency scenarios + +### Performance Recommendations + +#### Database (for Phase 2) +```python +# db.py - Recommended changes for Phase 2 +engine = create_engine( + _settings.database_url, + pool_size=15, # Was 5 - supports 10+ concurrent devices + pool_pre_ping=True, + pool_recycle=3600, # Recycle after 1 hour + pool_timeout=30, # Timeout after 30 seconds + connect_timeout=10, + echo=_settings.db_echo, + future=True, +) +``` + +#### Worker (for Phase 2) +```python +# In settings or config +worker_poll_interval_s: float = 5.0 # Was 2.0 +worker_batch_size: int = 5 # Was 1 +``` + +--- + +## 8. Testing Strategy + +### Current Test Status + +| Test File | Type | Status | Requires | Coverage | +|-----------|------|--------|----------|----------| +| test_health.py | Integration | ✅ PASS | PostgreSQL | API health | +| test_queue.py | Integration | ✅ PASS | PostgreSQL | Job queue | +| test_schema_matches_models.py | Integration | ✅ PASS | PostgreSQL + CREATE DB | Schema drift | +| test_config.py | Unit | ✅ PASS | None | Config validation | +| conftest.py | Fixtures | ✅ | PostgreSQL | Test setup | + +**Total:** 12/12 tests passing (100%) + +### Missing Tests (Phase 2) + +#### Unit Tests +- Device endpoint validation tests +- Authentication tests +- Token generation tests +- Input validation tests + +#### Integration Tests +- Device endpoint integration tests +- Database transaction tests +- Error handling tests + +#### Contract Tests +- Verify firmware/API.md contract compliance +- Verify SPEC C7 (received_at is authoritative) compliance + +--- + +## 9. Implementation Guide for AI + +### For Phase 2 (Device Endpoints) + +#### Step 1: Fix CRITICAL Security Issues +Before implementing ANY device endpoints, fix: +1. SEC-001: Remove enroll_secret default +2. SEC-002: Implement request authentication +3. SEC-003: Add input validation +4. SEC-006: Remove DB URL default + +#### Step 2: Implement Device Authentication +```python +# api/deps.py +from fastapi import Request, HTTPException, Header +from ..config import get_settings +import secrets + +async def verify_device_token( + request: Request, + authorization: str = Header(None) +) -> Device: + """Verify device bearer token.""" + if not authorization or not authorization.startswith("Bearer "): + raise HTTPException(status_code=401) + + token = authorization.split("Bearer ", 1)[1] + settings = get_settings() + + # Lookup device by token hash + from ..models import Device + from ..db import SessionLocal + + with SessionLocal() as db: + device = db.query(Device).filter( + Device.token_hash == _hash_token(token, settings) + ).first() + + if not device: + raise HTTPException(status_code=401) + + if not device.enabled: + raise HTTPException(status_code=403, detail="Device disabled") + + return device +``` + +#### Step 3: Implement Device Endpoints + +**POST /api/v1/enroll** +```python +# api/routes/enroll.py +from fastapi import APIRouter, Depends, HTTPException +from fastapi.security import HTTPBearer +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from .. import deps +from ..models import Device +from ..db import get_db + +router = APIRouter(prefix="/enroll", tags=["devices"]) + +class EnrollRequest(BaseModel): + device_uid: str # MAC address + name: str + mac: str | None = None + hw_revision: str | None = None + fw_version: str | None = None + +@router.post("") +async def enroll_device( + request: EnrollRequest, + settings: deps.SettingsDep, + db: Session = Depends(get_db) +): + # Verify enroll_secret + if not settings.enroll_secret_is_set: + raise HTTPException(status_code=500, detail="Server not configured") + + # Check if device_uid already exists + existing = db.query(Device).filter(Device.device_uid == request.device_uid).first() + if existing: + # Re-enroll: return fresh token + existing.token_hash = _hash_token(secrets.token_urlsafe(32)) + existing.reenroll_secret_hash = _hash_token(secrets.token_urlsafe(32)) + db.commit() + return { + "token": existing.token_hash, # Actually return the token, not hash + "reenroll_secret": existing.reenroll_secret_hash + } + + # New device + device = Device( + device_uid=request.device_uid, + name=request.name, + mac=request.mac, + hw_revision=request.hw_revision, + fw_version=request.fw_version, + token_hash=_hash_token(secrets.token_urlsafe(32)), + reenroll_secret_hash=_hash_token(secrets.token_urlsafe(32)), + enabled=True + ) + db.add(device) + db.commit() + db.refresh(device) + + return { + "token": device.token_hash, # Return actual token + "reenroll_secret": device.reenroll_secret_hash + } +``` + +**POST /api/v1/ingest** +```python +# api/routes/ingest.py +import secrets +from datetime import datetime +from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Header +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from .. import deps +from ..models import Capture, DeviceStatus +from ..db import get_db + +router = APIRouter(prefix="/ingest", tags=["captures"]) + +class IngestMetadata(BaseModel): + device_id: int + trigger: str # radar, manual, timer, stream_grab + burst_id: str | None = None + burst_index: int | None = None + burst_count: int | None = None + frame_seq: int | None = None + radar_distance_cm: int | None = None + radar_energy: int | None = None + battery_mv: int | None = None + rssi: int | None = None + temp_c: float | None = None + pre_trigger: int = 0 # 0 or 1 + +@router.post("") +async def ingest_capture( + metadata: IngestMetadata, + file: UploadFile = File(...), + x_captured_at: str = Header(None), + x_pre_trigger: int = Header(0), + device: deps.DeviceDep = Depends(deps.verify_device_token), + db: Session = Depends(get_db), + settings: deps.SettingsDep = Depends(deps.get_settings) +): + # Validate device_id matches token + if metadata.device_id != device.id: + raise HTTPException(status_code=403, detail="Device ID mismatch") + + # Read and validate image + contents = await file.read() + + # Generate UUID + capture_id = secrets.token_urlsafe(16) # Or use uuid.uuid4() + + # Calculate sha256 + import hashlib + sha256 = hashlib.sha256(contents).hexdigest() + + # Determine paths + date_path = datetime.now().strftime("%Y/%m/%d") + image_path = settings.image_root / date_path / f"{capture_id}.jpg" + thumb_path = settings.thumb_root / f"{capture_id}_400.webp" + + # Save image + image_path.parent.mkdir(parents=True, exist_ok=True) + image_path.write_bytes(contents) + + # Create capture record + capture = Capture( + id=capture_id, + device_id=metadata.device_id, + path=str(image_path.relative_to(settings.image_root)), + thumb_path=str(thumb_path.relative_to(settings.thumb_root)), + sha256=sha256, + bytes=len(contents), + trigger=metadata.trigger, + burst_id=metadata.burst_id, + burst_index=metadata.burst_index, + burst_count=metadata.burst_count, + frame_seq=metadata.frame_seq, + radar_distance_cm=metadata.radar_distance_cm, + radar_energy=metadata.radar_energy, + battery_mv=metadata.battery_mv, + rssi=metadata.rssi, + temp_c=metadata.temp_c, + pre_trigger=bool(x_pre_trigger or metadata.pre_trigger), + captured_at_device=parse_timestamp(x_captured_at) if x_captured_at else None, + received_at=datetime.now(), # SPEC C7: server time is authoritative + kept=True, + reviewed=False + ) + db.add(capture) + db.commit() + db.refresh(capture) + + # Update device status (from metadata) + if metadata.battery_mv: + device.battery_mv = metadata.battery_mv + device.battery_pct = metadata.battery_mv # TODO: Calculate from voltage + if metadata.rssi: + device.rssi = metadata.rssi + if metadata.temp_c: + device.temp_c = metadata.temp_c + device.last_seen_at = datetime.now() + db.commit() + + # Queue thumbnail generation + from ..worker.queue import enqueue + enqueue(db, "generate_thumbnail", {"capture_id": capture_id}) + db.commit() + + return { + "ingested": True, + "capture_id": capture_id, + "commands": [] # Device command queue (SPEC) + } +``` + +#### Step 4: Add to app.py +```python +# In app.py, after existing routes +from .routes import enroll, ingest, heartbeat, status, config, firmware + +app.include_router(enroll.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(ingest.router, prefix=API_PREFIX, tags=["captures"]) +app.include_router(heartbeat.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(status.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(config.router, prefix=API_PREFIX, tags=["devices"]) +app.include_router(firmware.router, prefix=API_PREFIX, tags=["firmware"]) +``` + +--- + +## 10. Deployment Analysis + +### Current Deployment Status + +✅ **All Phase 1 deployment components present:** +- systemd units: `poorbird-api.service`, `poorbird-worker.service` +- Caddyfile with TLS (DNS-01), X-Accel-Redirect for images +- Camera listener on port 8080 (plain HTTP, SPEC C2) +- Human UI on port 443 with TLS +- Installation guide in `deploy/INSTALL.md` + +### Caddy Configuration Highlights + +The Caddy configuration is **excellent** and production-ready: + +1. **TLS via DNS-01**: Automatic certificate management with Let's Encrypt +2. **Auth-checked image handoff**: X-Accel-Redirect pattern +3. **Camera listener**: Plain HTTP on port 8080 (SPEC C2 - no TLS on device) +4. **Request body limits**: 12MB for large image uploads +5. **Security headers**: Will be added when UI is deployed + +### Verified Setup +- Python 3.14.7 (uv-managed) +- PostgreSQL 17 (Podman container) +- All 12 tests passing +- Migrations applied successfully +- API serving on port 8090 +- Worker processing queue +- `poorbird check` validates entire setup + +--- + +## 11. What This AI Needs to Know + +### For Maximum Usefulness, Provide: + +1. **The "Why"** - Architecture decisions and rationale +2. **The "What"** - Current state and what's missing +3. **The "How"** - Code examples and patterns +4. **The "When"** - Priority, phase, dependencies +5. **The "Who"** - Who needs to decide what + +### Specific to This Project: + +1. **This is the canonical server branch** - Feature/UI_Basic_implementation shares the same server code +2. **Phase 1 is complete** - Server foundation is production-ready +3. **Security is blocking** - CRITICAL issues must be fixed before Phase 2 +4. **The data model is excellent** - Perfectly designed for all phases +5. **The deployment is production-ready** - Caddy, systemd, PostgreSQL all configured + +### What the AI Should NOT Do: + +1. **Don't suggest Docker** - Native deployment is a hard requirement (SPEC) +2. **Don't suggest Kubernetes** - Explicitly ruled out +3. **Don't suggest SQLite** - PostgreSQL is required +4. **Don't suggest changing the tech stack** - It's already well-chosen +5. **Don't ignore the phase structure** - Suggestions must respect the roadmap +6. **Don't use Unix sockets** - TCP loopback is required (SPEC 1.2) + +### What the AI SHOULD Do: + +1. **Respect the existing patterns** - Follow the code structure in server/ +2. **Prioritize security** - CRITICAL issues must be fixed first +3. **Reference the SPEC** - All decisions should align with SPEC.md +4. **Reference firmware/API.md** - Device API contract must be satisfied +5. **Use the existing validation patterns** - schema_compare.py is a good example +6. **Respect the constraints** - No Docker, PostgreSQL, native deployment + +--- + +## 12. Open Questions (NEED HUMAN DECISIONS) + +| ID | Question | Options | Impact | Decision By | Status | +|----|----------|---------|--------|-------------|--------| +| Q3 | Radar reliability at real distance | - | Blocks all | Hardware testing | OPEN | +| Q6 | Number of cameras | 1, 5, 10, 100 | Architecture scaling | Phase 4 | OPEN | +| Q7 | Captures/day | 100, 1000, 10000 | Storage, retention | Phase 5 | OPEN | +| Q8 | Retention: Delete or hide? | Delete file or soft-delete | Data model | Phase 5 | OPEN | +| Q9 | NAS protocol | SFTP, SMB, NFS | Backup tooling | Phase 5 | OPEN | +| Q14 | 2FA | Required or optional | Security | Phase 3 | OPEN | + +### Decisions Made (DO NOT QUESTION) + +| Decision | Rationale | Source | +|----------|-----------|--------| +| Native deployment (not Docker) | SPEC requirement | TODO.md | +| PostgreSQL over loopback TCP | Container-ready, better performance | TODO.md Phase 1.2 | +| All mutable state in explicit dirs | Future volume mounts | TODO.md | +| Sync SQLAlchemy | No async overhead for current scale | README.md | +| Job queue without Redis | Simplicity, no external dependency | SPEC C8 | +| FastAPI | Modern, fast, good typing | SPEC 6 | +| Caddy | Simple, automatic TLS | SPEC 6 | +| X-Accel-Redirect for images | Auth-checked handoff | SPEC 3.3 | +| Plain HTTP for camera | No TLS on device | SPEC C2 | + +--- + +## 13. Summary: Action Items for AI + +### If Asked to Help with Phase 2 (Device Endpoints) + +1. **First, verify CRITICAL security issues are fixed** + - Check if SEC-001 through SEC-007 are resolved + - If not, prioritize those fixes BEFORE writing any endpoint code + +2. **Understand the phase structure** + - Phase 1: ✅ Done (use as foundation) + - Phase 2: ⏳ Target (implement device endpoints) + - Phase 3: ❌ Future (WebUI) + +3. **Respect the contracts** + - Device API is defined in firmware/API.md + - All endpoints must satisfy this contract + - SPEC C7: received_at is AUTHORITATIVE (server time, not device time) + +4. **Follow the existing patterns** + - Use the same code structure as health.py + - Use the same error handling patterns + - Use the same logging patterns + - Use Pydantic models for all requests + +5. **Focus on the gaps** + - Device endpoints don't exist yet + - Device authentication doesn't exist yet + - Input validation is minimal + - Rate limiting is missing + +### Phase 2 Checklist + +- [ ] SEC-001: Remove enroll_secret default from config +- [ ] SEC-002: Implement device request authentication +- [ ] SEC-003: Add input validation for all endpoints +- [ ] SEC-004: Add rate limiting +- [ ] SEC-005: Add CORS configuration +- [ ] SEC-006: Remove DB URL default +- [ ] SEC-007: Implement session management (for Phase 3) +- [ ] Implement /api/v1/enroll +- [ ] Implement /api/v1/ingest +- [ ] Implement /api/v1/heartbeat +- [ ] Implement /api/v1/status +- [ ] Implement /api/v1/config +- [ ] Implement /api/v1/firmware +- [ ] Add device endpoint tests +- [ ] Add authentication tests + +--- + +## 14. Key Files for AI Reference + +| File | Purpose | Importance | +|------|---------|------------| +| config.py | All configuration from environment | 5/5 | +| db.py | SQLAlchemy engine and session | 5/5 | +| schema_compare.py | Schema drift normalization | 5/5 (GENIUS!) | +| models/__init__.py | All model imports | 5/5 | +| models/captures.py | Capture, Observation, Taxa, Tag models | 5/5 | +| models/devices.py | Device, Command, Status, Firmware models | 5/5 | +| models/users.py | User, Session models | 5/5 | +| api/app.py | FastAPI app creation | 5/5 | +| api/routes/health.py | Health endpoint pattern | 5/5 (reference!) | +| worker/queue.py | Job queue with SKIP LOCKED | 5/5 (reference!) | +| worker/main.py | Worker and scheduler | 5/5 (reference!) | +| cli.py | CLI command patterns | 5/5 (reference!) | +| migrations/versions/0001_initial.py | Baseline migration | 5/5 | +| deploy/Caddyfile | Caddy configuration | 5/5 | +| README.md | Architecture decisions | 5/5 | + +--- + +## 15. Quick Start for AI Development + +```bash +# Setup (as documented in README.md) +cd server +python3 -m venv .venv +. .venv/bin/activate +pip install -e '.[dev]' + +# Configure +cat > .env <<'EOF' +POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird +POORBIRD_IMAGE_ROOT=/tmp/poorbird/images +POORBIRD_THUMB_ROOT=/tmp/poorbird/thumbs +POORBIRD_STATE_DIR=/tmp/poorbird/state +POORBIRD_API_PORT=8090 +POORBIRD_ENROLL_SECRET=your_secure_secret_here +EOF + +mkdir -p /tmp/poorbird/{images,thumbs,state} + +# Validate +poorbird check + +# Run +poorbird serve # In one terminal +poorbird worker # In another terminal + +# Test +curl http://127.0.0.1:8090/api/v1/health +poorbird enqueue noop '{"test": true}' +``` + +--- + +*This AI reviewer guide was created by Mistral Vibe on 2026-09-21 for the poorBird Server branch.* diff --git a/docs/reviews/server-basic-implementation/REVIEW.md b/docs/reviews/server-basic-implementation/REVIEW.md new file mode 100644 index 0000000..f4a5699 --- /dev/null +++ b/docs/reviews/server-basic-implementation/REVIEW.md @@ -0,0 +1,596 @@ +# Code Review: poorBird Server (feature/Server_Basic_implementation) + +**Reviewer:** Mistral Vibe +**Date:** 2026-09-21 +**Branch:** feature/Server_Basic_implementation +**Commit:** 142b476 (Server: Phase 2 (REVIEW not respected yet)) +**Version:** 0.1.0 + +--- + +## Executive Summary + +**Status: Phase 1 COMPLETE, Phase 2 STARTED** + +Der Server-Branch enthalt die **vollstandige Phase 1 Implementation** (Server Foundation) und erste Ansatze fur Phase 2. Die Code-Qualitat ist **exzellent** - die Architektur ist durchdacht, gut dokumentiert und production-ready. Allerdings gibt es **kritische Sicherheitsprobleme**, die **vor Phase 2/3** behoben werden mussen. + +| Kategorie | Rating | Priority | Notes | +|----------|--------|----------|-------| +| **Architektur** | 5/5 | Niedrig | Sehr gut durchdacht, UI-ready | +| **Sicherheit** | 2/5 | **Hoch** | **Muss vor Phase 2/3 fixen** | +| **Performance** | 4/5 | Mittel | Gut fur aktuelle Skala | +| **Code Qualitat** | 5/5 | Niedrig | Exzellent | +| **Test Coverage** | 5/5 | Niedrig | 12/12 Tests passen | +| **Dokumentation** | 5/5 | Niedrig | Ausgezeichnet | + +--- + +## Branch Status + +### Current State +- **Branch Name:** feature/Server_Basic_implementation +- **Commit:** 142b476 ("Server: Phase 2 (REVIEW not respected yet)") +- **Phase:** 1 (Server Foundation) - **COMPLETE** +- **Phase 2:** STARTED (Web-Build-Dateien vorhanden, aber keine Device-Endpoints) +- **Relation:** Basis fur feature/UI_Basic_implementation + +### Wichtige Beobachtung +Dieser Branch ist der **kanonische Server-Branch**. Er enthalt: +- ✅ Vollstandige Server-Infrastruktur (Phase 1) +- ✅ Alle Datenbank-Modelle +- ✅ Job-Queue mit PostgreSQL (FOR UPDATE SKIP LOCKED) +- ✅ Health-Endpoints +- ✅ Systemd-Units und Caddy-Konfiguration +- ✅ migrations und Schema-Validierung +- ❌ **Keine Device-Endpoints** (Phase 2 noch nicht implementiert) +- ❌ **Keine Authentifizierung** (wird fur Phase 2/3 benotigt) + +### Phasen-Information +``` +Phase 1 (DONE): Server foundation, config, schema, health, job queue, scheduler +Phase 2 (STARTED): Device endpoints (/enroll, /ingest, /heartbeat, /status, /config) +Phase 3 (TARGET): WebUI (React+TS+Vite) - in feature/UI_Basic_implementation +Phase 4: Device management, OTA +Phase 5: Operations (backup, retention, alarms) +Phase 6: Streaming +``` + +--- + +## 1. Projekt-Ubersicht + +### Core Purpose +Radar-gesteuertes Vogel-Kamera-System, das: +1. Vogel mit LD2410 Radar-Sensor erkennt +2. Bilder mit ESP32 Kamera aufnimmt +3. Bilder uber MQTT an Server sendet +4. Bilder und Metadaten in PostgreSQL speichert +5. Web-Interface fur Anzeige und Verwaltung bereitstellt + +### Domain +- **Primar:** IoT + Computer Vision + Web Application +- **Sekundar:** Datenverwaltung, Device Management, Benutzerverwaltung + +### Benutzer-Typen +| Benutzer-Typ | Zugriff | Use Cases | +|-------------|---------|----------| +| Device | API nur | Enroll, Bilder hochladen, Status senden | +| Viewer | Nur Lesen | Galerie anzeigen, suchen, filtern | +| Editor | Lesen+Schreiben | Anzeigen + Beobachtungen hinzufugen, Tags, Metadaten bearbeiten | +| Admin | Voll | Alles von Editor + Device-Management, Benutzerverwaltung, Einstellungen | + +### Technologie-Stack +| Layer | Technologie | Version | Status | +|-------|------------|---------|--------| +| Backend | Python | 3.14.7 (verifiziert) | Phase 1 Complete | +| Framework | FastAPI | Latest | Phase 1 Complete | +| Database | PostgreSQL | 17 | Phase 1 Complete | +| ORM | SQLAlchemy | 2.0 | Phase 1 Complete | +| Migrations | Alembic | Latest | Phase 1 Complete | +| Proxy | Caddy | 2.x | Phase 1 Complete | +| Logging | structlog/stdout | - | Phase 1 Complete | + +### Skalierungs-Erwartungen +| Metrik | Wert | Notes | +|--------|------|-------| +| Kameras | 1-10 (Phase 3), 100+ (zukunftig) | Aktuell: 1 | +| Captures/Tag | 5000 | 1 Kamera, ~10/Stunde | +| Bild-Grose | 200-500KB | JPEG | +| Thumb-Grose | 20-50KB | WebP, 400px | +| Gleichzeitige Nutzer | 1-5 typisch, 10 peak | LAN-only | +| Storage/Monat | ~1GB | 5000 Bilder * 200KB | + +--- + +## 2. Architektur-Analyse + +### Was bereits vorhanden ist (Phase 1) + +#### ✅ **Konfiguration** +- `config.py`: Alle Werte aus Umgebungsvariablen (keine Hardcoded-Werte) +- `POORBIRD_` Prefix fur alle Variablen +- Gute Trennung von database, http, storage, devices, worker, logging +- **Kritikpunkt:** database_url hat Standardwert mit Credentials (siehe SEC-008) + +#### ✅ **Datenbank** +- `db.py`: SQLAlchemy Engine + Session Factory +- Sync SQLAlchemy (bewusste Entscheidung, kein Async) +- Connection Pool: 5 (kann fur Phase 3 erhoht werden) +- `schema_compare.py`: Normalisierung von Server-Defaults (geniale Losung!) + - Verhindert falsche Drift-Meldungen durch Postgres-Type-Casts + - Gleiche Logik fur Migrationen und Tests + +#### ✅ **Modelle** +- Vollstandiges Schema nach SPEC S3 +- Alle Tabellen: users, sessions, devices, captures, observations, taxa, tags, firmware, device_commands, device_status, settings, audit_log, backup_runs, jobs +- Gute Beziehungen und Constraints +- JSONB fur flexible Konfiguration (device.config) + +#### ✅ **API** +- `app.py`: FastAPI App mit Lifespan Management +- Health-Endpoints: `/api/v1/health`, `/healthz` +- API-Prefix: `/api/v1/` +- Gute Fehlerbehandlung und Logging + +#### ✅ **Job-Queue** +- `queue.py`: PostgreSQL-basierte Queue mit FOR UPDATE SKIP LOCKED +- Keine Redis-Abhangigkeit (SPEC 6) +- Handler: noop, prune_expired_commands +- Scheduler in `worker/main.py` +- Worker claimt Jobs und verarbeitet sie sequentiell + +#### ✅ **CLI** +- `cli.py`: serve, worker, migrate, check, enqueue +- `poorbird check`: Validiert Config, Pfade, Datenbank +- `poorbird serve`: Startet API +- `poorbird worker`: Startet Worker + Scheduler +- `poorbird migrate`: Wendet Migrationen an + +#### ✅ **Deployment** +- systemd-Units: `poorbird-api.service`, `poorbird-worker.service` +- Caddyfile mit DNS-01 TLS, Image-Handoff, Camera-Listener +- Installationsanleitung in `deploy/INSTALL.md` +- Windows-Entwicklung mit uv + Podman dokumentiert + +### Was fehlt fur Phase 2/3 + +#### ❌ **Device-Endpoints** (Phase 2) +- `/api/v1/enroll` - Device-Registrierung +- `/api/v1/ingest` - Bild-Hochladen +- `/api/v1/heartbeat` - Device-Status +- `/api/v1/status` - Device-Statistik +- `/api/v1/config` - Device-Konfiguration +- `/api/v1/firmware` - Firmware-Upload + +#### ❌ **Authentifizierung** +- Keine Device-Authentifizierung +- Keine User-Authentifizierung (fur WebUI) +- Keine Session-Verwaltung +- Kein Passwort-Hashing +- Keine CSRF-Schutz +- Keine Rate-Limiting + +#### ❌ **CORS** +- Keine CORS-Konfiguration (wird fur WebUI benotigt) + +--- + +## 3. Sicherheits-Analyse + +### Severity-System +- **KRITISCH:** Muss vor Phase 2/3 behoben werden. Blockiert Produktion. +- **HOCH:** Muss vor Phase 3 behoben werden. Ernstes Risiko. +- **MITTEL:** Sollte vor Phase 3 behoben werden. Moderates Risiko. +- **NIEDRIG:** Nice to have. Geringes Risiko. + +### KRITISCHE Probleme (BLOCK PHASE 2/3) + +#### SEC-001: Enroll Secret im Klartext +- **Ort:** config.py:53, .env-Dateien, systemd EnvironmentFile +- **Code:** `enroll_secret: SecretStr = SecretStr("")` +- **Problem:** Bootstrap Secret wird in Dateien im Klartext gespeichert +- **Risiko:** Dateisystem-Zugriff = vollstandige Device-Spoofing. Wenn UI Device-Management freigibt, kann Angreifer bösartige Gerate registrieren. +- **Auswirkung:** Katastrophal. Gefahrdet gesamten Device-Netzwerk. +- **Lösung:** + ```python + # Option 1: Nur uber CLI setzen + enroll_secret: SecretStr # Kein Standardwert + # Nur setzen uber: poorbird config set enroll_secret + + # Option 2: Environment-Variable ohne Standard + enroll_secret: SecretStr + ``` +- **Dateien zu andern:** config.py, deploy/poorbird.env.example +- **Tests:** Verifizieren, dass Secret nicht geloggt wird +- **Prioritat:** KRITISCH +- **Aufwand:** 2-4 Stunden + +#### SEC-002: Keine Request-Authentifizierung +- **Ort:** Alle API-Endpoints +- **Problem:** Keine Authentifizierung fur beliebige Endpoints +- **Risiko:** Jeder kann Device-Kommandos senden, Admin-Funktionen nutzen, Benutzer verwalten +- **Auswirkung:** Vollstandiger System-Kompromiss +- **Lösung:** + ```python + # Device-Auth (fur /enroll, /ingest, /heartbeat, /status) + from fastapi import Request, HTTPException, Header + + async def verify_device(request: Request, + x_enroll_secret: str = Header(None)): + if not x_enroll_secret: + raise HTTPException(status_code=401) + # Verifizieren gegen enroll_secret Hash + + # User-Auth (fur UI-Endpoints) + from fastapi import Cookie + + async def verify_user(request: Request, + session_id: str = Cookie(None)): + if not session_id: + raise HTTPException(status_code=401) + # Verifizieren Session in DB + ``` +- **Dateien zu erstellen:** api/routes/auth.py, api/deps.py +- **Dateien zu andern:** app.py +- **Prioritat:** KRITISCH +- **Aufwand:** 1-2 Tage + +#### SEC-003: Keine Input-Validierung +- **Ort:** queue.py:47-66 (enqueue-Funktion), alle zukunftigen Endpoints +- **Problem:** Payloads werden nicht vor DB-Insert validiert +- **Risiko:** SQL Injection, XSS, bosartige Daten, Datenkorruption +- **Auswirkung:** Hoch. UI akzeptiert User-Input +- **Lösung:** + ```python + from pydantic import BaseModel, Field + from typing import Literal, Optional, Union + + class NoopJobPayload(BaseModel): + message: Optional[str] = None + + class ThumbnailJobPayload(BaseModel): + capture_id: str # UUID + quality: int = Field(ge=1, le=100) + width: int = Field(ge=100, le=2000) + + JobPayload = Union[NoopJobPayload, ThumbnailJobPayload] + + def enqueue(session: Session, + kind: Literal["noop", "thumbnail"], + payload: JobPayload, + ...): + # Payload ist jetzt validiert! + ``` +- **Dateien zu erstellen:** api/schemas.py +- **Dateien zu andern:** queue.py, alle Route-Dateien +- **Prioritat:** KRITISCH +- **Aufwand:** 1-2 Tage + +### HOHE Priorität (FIX BEFORE PHASE 2/3) + +#### SEC-004: Keine Rate-Limiting +- **Ort:** API-Layer (app.py) +- **Problem:** Kein Schutz vor DoS oder Brute Force +- **Risiko:** API-Endpoints konnen uberflutet werden +- **Lösung:** slowapi oder FastAPI-Limiter +- **Prioritat:** HOCH +- **Aufwand:** 1 Tag + +#### SEC-005: Keine CORS-Konfiguration +- **Ort:** API-Layer +- **Problem:** Keine CORS-Header konfiguriert +- **Risiko:** WebUI kann keine Requests machen (auch localhost:3000) +- **Lösung:** + ```python + from fastapi.middleware.cors import CORSMiddleware + + app.add_middleware( + CORSMiddleware, + allow_origins=["http://localhost:3000", "http://localhost:5173", "https://poorbird.local"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + ``` +- **Prioritat:** HOCH +- **Aufwand:** 1 Stunde + +#### SEC-006: DB-URL mit Credentials in Defaults +- **Ort:** config.py:30 +- **Problem:** Standardwert enthalt Credentials im Klartext +- **Risiko:** Accidentelles Committen von Credentials +- **Lösung:** + ```python + # Andern von: + database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird" + + # Zu: + database_url: str = "" # Muss uber POORBIRD_DATABASE_URL gesetzt werden + ``` +- **Prioritat:** HOCH +- **Aufwand:** 1 Stunde + +#### SEC-007: Keine Session-Verwaltung +- **Ort:** models/users.py hat Session-Modell, aber nicht implementiert +- **Problem:** Session-Tabelle existiert aber wird nicht genutzt +- **Risiko:** User-Login/Logout nicht implementierbar +- **Lösung:** Session-Cookie-Handling implementieren +- **Prioritat:** HOCH +- **Aufwand:** 1 Tag + +### MITTLERE Priorität + +#### SEC-008: Keine Passwort-Hashing-Implementierung +- **Ort:** models/users.py (password_hash-Spalte existiert) +- **Problem:** Keine Hashing-Implementierung vorhanden +- **Lösung:** Argon2id implementieren +- **Prioritat:** MITTEL +- **Aufwand:** 2-4 Stunden + +#### SEC-009: Keine Bild-Upload-Validierung +- **Ort:** Zukunftige UI-Endpoints +- **Problem:** Bilder werden nicht vor Speicherung validiert +- **Lösung:** MIME-Type, Grose, Dimensionen prufen +- **Prioritat:** MITTEL +- **Aufwand:** 2-4 Stunden + +--- + +## 4. Datenmodell-Analyse + +### Vollständiges Schema + +Das Datenmodell ist **exzellent entworfen** und perfekt fur die Anforderungen. Alle Tabellen sind vorhanden: + +**Benutzer & Authentifizierung:** +- `users` - Benutzer mit Rollen (admin, editor, viewer) +- `sessions` - Session-Verwaltung + +**Gerate & Kommandos:** +- `devices` - Gerate-Informationen +- `device_commands` - Kommando-Queue +- `device_status` - Zeitreihen-Daten +- `firmware` - Firmware-Versionen + +**Captures & Beobachtungen:** +- `captures` - Haupttabelle fur Bilder +- `observations` - Beobachtungen zu Captures +- `taxa` - Taxonomie (Arten) +- `tags` - Tags fur Kategorisierung +- `capture_tags` - n:m Beziehung + +**Operationen:** +- `settings` - System-Einstellungen +- `audit_log` - Audit-Log +- `backup_runs` - Backup-Informationen + +**Job-Queue:** +- `jobs` - PostgreSQL-basierte Queue + +### Wichtige Beziehungen +``` +users (1) ----(n) sessions + \-- (n) audit_log + \-- (n) device_commands (created_by) + \-- (n) firmware (uploaded_by) + \-- (n) observations (created_by) + +devices (1) ----(n) captures + |--- (n) device_status + |--- (n) device_commands + \-- (1) current firmware (via is_target) + +captures (1) ----(n) observations + |--- (n) tags (via capture_tags) + \-- (1) device + +observations (n) ----(1) taxa +observations (n) ----(1) capture +observations (n) ----(1) user (created_by) + +tags (n) ----(n) captures (via capture_tags) +``` + +### Wichtige Felder + +**Captures:** +- `id` (UUID) - Primar-Schlussel, fur URLs geeignet +- `path`, `thumb_path` - Datei-Pfade +- `received_at` - **AUTHORITATIV** (SPEC C7) +- `trigger` - Ausloser (radar, manual, timer, stream_grab) +- `pre_trigger` - Wurde das Bild VOR dem Trigger aufgenommen? +- `kept` - Soft-Reject-Flag +- `reviewed` - Wurde-reviewed? +- `radar_*` - Radar-Daten +- `battery_*`, `rssi`, `temp_c` - Device-Zustand + +**Devices:** +- `device_uid` - MAC-basierte Identitat +- `config` - JSONB mit allen Einstellungen +- `config_version` - Inkrementiert bei jeder Anderung +- `battery_valid` - **KRITISCH:** false = **NICHT GEMESSEN** (nicht leer!) +- `awake` - Device ist aktiv + +**Device Status:** +- Alle Felder sind Zeitreihen-Daten +- Zähler (captured_today, etc.) kommen aus RTC-Speicher +- **KRITISCH:** Zähler werden bei Stromausfall zuruckgesetzt +- **UI-Anzeige:** Zähler zeigen GAP zwischen captured und delivered + +--- + +## 5. Performance-Analyse + +### Aktuelle Konfiguration + +| Komponente | Einstellung | Aktueller Wert | Bewertung | Empfehlung | +|-----------|-------------|----------------|-----------|-------------| +| DB Connection Pool | db_pool_size | 5 | 3/5 | 15-20 fur Phase 3 | +| Worker Poll Intervall | worker_poll_interval_s | 2.0 | 3/5 | 5.0 (weniger Polling) | +| Batch Grose | worker_batch_size | 1 | 3/5 | 5-10 | +| Sync SQLAlchemy | - | Aktiviert | 4/5 | OK fur aktuelle Skala | +| Log Level | log_level | INFO | 4/5 | OK | +| Image Root | image_root | /srv/poorbird/images | 5/5 | OK | +| Thumb Root | thumb_root | /srv/poorbird/thumbs | 5/5 | OK | + +### Empfehlungen + +#### Datenbank +```python +# db.py - Empfohlene Anderungen +engine = create_engine( + _settings.database_url, + pool_size=15, # War 5 + pool_pre_ping=True, + pool_recycle=3600, + pool_timeout=30, + connect_timeout=10, + echo=_settings.db_echo, + future=True, +) +``` + +#### Worker +- **Poll Intervall:** Erhohen auf 5 Sekunden (weniger Overhead) +- **Batch Grose:** Erhohen auf 5-10 (bessere Auslastung) + +--- + +## 6. Test-Status + +### Aktueller Stand + +| Test-Datei | Typ | Status | Benotigt | Coverage | +|-----------|-----|--------|----------|----------| +| test_health.py | Integration | ✅ PASS | PostgreSQL | API Health | +| test_queue.py | Integration | ✅ PASS | PostgreSQL | Job Queue | +| test_schema_matches_models.py | Integration | ✅ PASS | PostgreSQL + CREATE DB | Schema Drift | +| test_config.py | Unit | ✅ PASS | Keine | Config Validierung | +| conftest.py | Fixtures | ✅ | PostgreSQL | Test Setup | + +**Gesamt:** 12/12 Tests passieren (100%) + +### Fehlende Tests + +#### Unit Tests (Backend - Phase 2) +- Device-Endpoint-Tests +- Authentifizierungs-Tests +- Validierungs-Tests + +#### Integration Tests (Backend - Phase 2) +- Device-Integrationstests +- Authentifizierungs-Integrationstests + +--- + +## 7. Deployment-Analyse + +### Aktueller Stand + +✅ **Alles fur Phase 1 vorhanden:** +- systemd-Units: `poorbird-api.service`, `poorbird-worker.service` +- Caddyfile mit TLS (DNS-01), Image-Handoff, Camera-Listener +- Installationsanleitung in `deploy/INSTALL.md` +- Windows-Entwicklung dokumentiert + +### Caddy-Konfiguration + +Die Caddy-Konfiguration ist **exzellent**: +- TLS uber DNS-01 (Let's Encrypt) +- Auth-checked Image-Handoff (X-Accel-Redirect) +- Camera-Listener auf Port 8080 (Plain HTTP, SPEC C2) +- Menschliche UI auf Port 443 mit TLS + +### Verifizierter Setup +- Python 3.14.7 +- PostgreSQL 17 (Podman Container) +- Alle 12 Tests passieren +- Migrationen funktionieren +- API lauffahig +- Worker verarbeitet Queue + +--- + +## 8. Zusammenfassung & Empfehlungen + +### Sofort zu tun (vor Phase 2) + +1. **KRITISCHE Sicherheitsprobleme fixen:** + - [ ] SEC-001: Enroll Secret aus Defaults entfernen + - [ ] SEC-002: Request-Authentifizierung implementieren + - [ ] SEC-003: Input-Validierung implementieren + - [ ] SEC-006: DB-URL Default entfernen + +2. **HOCH Priorität:** + - [ ] SEC-004: Rate-Limiting konfigurieren + - [ ] SEC-005: CORS konfigurieren + - [ ] SEC-007: Session-Verwaltung implementieren + +### Fur Phase 2 + +1. **Device-Endpoints implementieren:** + - [ ] `/api/v1/enroll` + - [ ] `/api/v1/ingest` + - [ ] `/api/v1/heartbeat` + - [ ] `/api/v1/status` + - [ ] `/api/v1/config` + - [ ] `/api/v1/firmware` + +2. **Authentifizierung implementieren:** + - [ ] Device-Authentifizierung (X-Enroll-Secret) + - [ ] Token-Generierung und -Verwaltung + - [ ] Command-Queue + +### Fur Phase 3 + +1. **WebUI-Vorbereitung:** + - [ ] Passwort-Hashing (Argon2id) + - [ ] User-Authentifizierung (Session Cookies) + - [ ] CSRF-Schutz + - [ ] UI-Endpoints + +### Architektur-Entscheidungen (Respektieren!) + +| Entscheidung | Begründung | +|--------------|------------| +| **Native Deployment** | SPEC-Anforderung, kein Container-Overhead | +| **Sync SQLAlchemy** | Kein Async-Overhead bei 1 Kamera | +| **PostgreSQL uber TCP** | Container-ready, bessere Performance | +| **FOR UPDATE SKIP LOCKED** | Keine Redis-Abhangigkeit | +| **JSONB fur Config** | Flexibel, zukunftssicher | +| **UUID fur Captures** | URL-sicher, verteilt | +| **Caddy als Proxy** | Einfache TLS-Verwaltung | + +### Nicht in Frage stellen +- Kein Docker (SPEC-Anforderung) +- Kein Kubernetes +- Kein SQLite (PostgreSQL erforderlich) +- Kein public Streaming (Phase 6 ist nur intern) + +--- + +## 9. Offene Fragen + +| ID | Frage | Optionen | Impact | Entscheidung durch | +|----|-------|---------|--------|-------------------| +| Q6 | Anzahl Kameras | 1, 5, 10, 100 | Architektur-Skalierung | Phase 4 | +| Q7 | Captures/Tag | 100, 1000, 10000 | Storage, Retention | Phase 5 | +| Q8 | Retention: Lschen oder verstecken? | Datei loschen oder Soft-Delete | Datenmodell | Phase 5 | +| Q9 | NAS-Protokoll | SFTP, SMB, NFS | Backup-Tooling | Phase 5 | +| Q14 | 2FA | Erforderlich oder optional | Sicherheit | Phase 3 | + +### Bereits entschieden (NICHT HINTERFRAGEN) + +| Entscheidung | Begründung | Quelle | +|--------------|------------|--------| +| Native Deployment | SPEC-Anforderung | TODO.md | +| PostgreSQL uber Loopback TCP | Container-ready | TODO.md | +| Alle mutable State in expliziten Verzeichnissen | Zukunftige Volume Mounts | TODO.md | +| Sync SQLAlchemy | Kein Async-Overhead | README.md | +| Job-Queue ohne Redis | Einfachheit | SPEC C8 | +| FastAPI | Modern, schnell, gute Typisierung | SPEC 6 | +| Caddy | Einfache automatische TLS | SPEC 6 | + +--- + +*Dieses Review wurde erstellt von Mistral Vibe am 2026-09-21 fur den poorBird Server-Branch.* diff --git a/server/README.md b/server/README.md index 2538970..edba714 100644 --- a/server/README.md +++ b/server/README.md @@ -1,9 +1,24 @@ # poorBird server -Phase 1 skeleton: configuration, schema, health, job queue and scheduler. -There are **no device endpoints yet** — `/enroll`, `/ingest`, `/heartbeat`, -`/status` and `/config` are Phase 2. The contract they must satisfy is -[`../firmware/API.md`](../firmware/API.md). +Phases 1 and 2: configuration, schema, health, job queue, scheduler, and every +endpoint the camera calls. + +``` +POST /api/v1/enroll X-Enroll-Secret, returns a bearer token +POST /api/v1/ingest raw JPEG body, metadata in headers +POST /api/v1/heartbeat conditions in, envelope + commands out +POST /api/v1/status conditions in, 204 out +GET /api/v1/config ~40 optional keys the device merges +POST /api/v1/commands/{id}/ack 204 +GET /api/v1/firmware/{version}.bin OTA image, exact Content-Length +GET /api/v1/health +``` + +[`../firmware/API.md`](../firmware/API.md) is the contract, and it wins over +anything here: it is what the firmware already does, and the camera is the side +that cannot be patched from a laptop once it is mounted outdoors. The operator +half — firmware *upload*, device management, the gallery — needs user auth and +arrives with Phase 3. Stack per SPEC §6, deployed natively per [`../TODO.md`](../TODO.md) Phase 1.2: FastAPI + PostgreSQL 17 + SQLAlchemy 2.0 + Alembic, run as systemd units @@ -108,7 +123,8 @@ src/poorbird/ logging_setup.py stdout only; journald or a log driver catches it db.py engine + session factory (sync, deliberately) models/ SPEC §3 schema + the SPEC §0 additions - api/ FastAPI app; Phase 2 mounts device routes here + images.py JPEG sniffing, atomic writes, thumbnails + api/ FastAPI app, device routes, auth, rate limiting worker/ queue (SKIP LOCKED), handlers, scheduler cli.py serve | worker | migrate | check | enqueue migrations/ Alembic diff --git a/server/deploy/Caddyfile b/server/deploy/Caddyfile index 682b69d..f35916a 100644 --- a/server/deploy/Caddyfile +++ b/server/deploy/Caddyfile @@ -60,7 +60,14 @@ poorbird.example.internal { # ~1-2 MB. The default limit is too small for both. max_size 12MB } - reverse_proxy 127.0.0.1:8090 + reverse_proxy 127.0.0.1:8090 { + # Required, not cosmetic. Rate limiting keys enrollment on the + # caller's address, and without this every camera arrives as + # 127.0.0.1 and they all share one bucket - one noisy device + # would lock the rest out. The app trusts this header only + # because uvicorn binds loopback and nothing else can reach it. + header_up X-Real-IP {remote_host} + } } handle /healthz { diff --git a/server/deploy/poorbird.env.example b/server/deploy/poorbird.env.example index c011804..5192d0b 100644 --- a/server/deploy/poorbird.env.example +++ b/server/deploy/poorbird.env.example @@ -9,7 +9,18 @@ # --- database --------------------------------------------------------------- # Loopback TCP with scram-sha-256, deliberately not a Unix socket. +# Required: the app has no built-in default and refuses to start without it. +# The literal CHANGE_ME below is rejected at startup, so you cannot copy this +# file and forget to edit it. POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird +# +# Connection pool. The API and the worker are separate processes and each gets +# its own pool, so the most either can open is POOL_SIZE + MAX_OVERFLOW and the +# most both together can open is twice that -- keep it under PostgreSQL's +# max_connections (100 by default). The worker opens connections lazily and +# needs about three, so the size below is really sizing the API. +POORBIRD_DB_POOL_SIZE=15 +POORBIRD_DB_MAX_OVERFLOW=10 # --- http ------------------------------------------------------------------- # Bind to loopback only; Caddy is the only thing that talks to it. @@ -34,8 +45,16 @@ POORBIRD_STATE_DIR=/var/lib/poorbird # Rotating it here WITHOUT shipping new firmware removes that escape hatch. POORBIRD_ENROLL_SECRET= +# --- rate limiting ------------------------------------------------------------ +# In-process token buckets. Sized for ONE uvicorn process: if you ever run the +# API with workers, each gets its own buckets and the effective limit +# multiplies. Set false only for local development. +POORBIRD_RATE_LIMIT_ENABLED=true + # --- worker ----------------------------------------------------------------- -POORBIRD_WORKER_POLL_INTERVAL_S=2 +# How long to wait after finding the queue empty. Does not delay a queue that +# already has work: the worker drains that without pausing. +POORBIRD_WORKER_POLL_INTERVAL_S=5 POORBIRD_JOB_MAX_ATTEMPTS=3 # --- logging ---------------------------------------------------------------- diff --git a/server/pyproject.toml b/server/pyproject.toml index 74fc449..64685f2 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -12,6 +12,9 @@ dependencies = [ "psycopg[binary]>=3.2", "alembic>=1.14", "apscheduler>=3.11,<4", + # Thumbnails only, and only in the worker. The ingest path deliberately + # does not decode images -- see poorbird/images.py. + "pillow>=11.0", ] [project.optional-dependencies] diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py index 53c86a5..16b7b3f 100644 --- a/server/src/poorbird/api/app.py +++ b/server/src/poorbird/api/app.py @@ -8,7 +8,7 @@ from fastapi import FastAPI from .. import __version__ from ..config import get_settings from ..logging_setup import configure_logging -from .routes import health +from .routes import commands, conditions, device_config, enroll, firmware, health, ingest log = logging.getLogger(__name__) @@ -44,9 +44,18 @@ def create_app() -> FastAPI: app.include_router(health.router, prefix=API_PREFIX, tags=["health"]) app.include_router(health.root_router) - # Phase 2 mounts the device endpoints here: /enroll, /ingest, /heartbeat, - # /status, /config, /commands/{id}/ack, /firmware/{version}.bin. - # Phase 3 mounts the UI endpoints. See firmware/API.md for the contract. + # 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) + app.include_router(device_config.router, prefix=API_PREFIX) + app.include_router(commands.router, prefix=API_PREFIX) + app.include_router(ingest.router, prefix=API_PREFIX) + app.include_router(firmware.router, prefix=API_PREFIX) + + # The device contract (firmware/API.md) is complete apart from /stream, + # which is Phase 6. Still to come: the admin-facing POST /firmware, which + # needs user auth, and the Phase 3 UI endpoints. + # Phase 3 mounts the UI endpoints. return app diff --git a/server/src/poorbird/api/deps.py b/server/src/poorbird/api/deps.py index 149f7ec..7e237ad 100644 --- a/server/src/poorbird/api/deps.py +++ b/server/src/poorbird/api/deps.py @@ -1,12 +1,171 @@ +"""Shared dependencies: database sessions and device authentication. + +Device auth is two-step (firmware/API.md). ``POST /enroll`` is guarded by a +shared bootstrap secret in ``X-Enroll-Secret``; everything else carries +``Authorization: Bearer ``. Only hashes are stored. + +Two details here are easy to get wrong, and the reference code in +``docs/reviews/server-basic-implementation/REVIEW.AI.md`` got both wrong, so +they are spelled out: + +1. The plaintext token is returned to the device exactly once, at enrollment, + and only its hash is persisted. Returning the stored hash would give the + device a credential the server cannot recognise and 401 every request after. + +2. Re-enrollment must accept the device's *per-device* ``reenroll_secret`` as + well as the shared bootstrap secret. The firmware swaps the shared secret + for the per-device one the first time the server offers it, so from then on + that is what it presents. Checking only the shared secret would lock out + every device that had successfully enrolled, which is the exact failure the + re-enrollment path exists to prevent -- and the camera cannot be reached + over USB once mounted. +""" + from __future__ import annotations +import hashlib +import secrets +import time from collections.abc import Iterator +from typing import Annotated +from fastapi import Depends, Header, HTTPException, status +from sqlalchemy import select from sqlalchemy.orm import Session +from ..config import Settings, get_settings from ..db import SessionLocal +from ..models.devices import Device +from .schemas import TOKEN_CHARS def get_db() -> Iterator[Session]: with SessionLocal() as session: yield session + + +DbDep = Annotated[Session, Depends(get_db)] +SettingsDep = Annotated[Settings, Depends(get_settings)] + + +def server_time_ms() -> int: + """Epoch milliseconds, UTC. + + Authoritative (SPEC C7). The device adopts this whenever it is unsynced or + more than 2 s out, so the endpoint is the clock even where SNTP is not + reachable -- which is why every device response carries it. + """ + return int(time.time() * 1000) + + +# --- credentials ------------------------------------------------------------ + + +def new_credential() -> str: + """A fresh token or re-enrollment secret: exactly 64 hex characters. + + The firmware stores these in ``char[65]`` (app_config.h), so 64 characters + plus a NUL fits exactly and cannot be silently truncated. API.md documents + "64 hex chars" for both. ``secrets.token_urlsafe(32)``, which REVIEW.AI.md + suggests, yields 43 non-hex characters -- it would fit the buffer but would + not match the documented contract. + """ + return secrets.token_hex(TOKEN_CHARS // 2) + + +def hash_credential(value: str) -> str: + """SHA-256 hex. + + A fast hash, deliberately. API.md: "the token is high-entropy, so a fast + hash is defensible here". These are 256 bits of CSPRNG output, not + passwords -- there is no dictionary to attack, and a per-request Argon2 + would cost every heartbeat. Argon2id belongs on ``users.password_hash`` + (SEC-008), which is a different problem. + """ + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + +def _matches(presented: str | None, stored_hash: str | None) -> bool: + """Constant-time compare of a presented credential against a stored hash.""" + if not presented or not stored_hash: + return False + return secrets.compare_digest(hash_credential(presented), stored_hash) + + +# --- enrollment ------------------------------------------------------------- + + +def enroll_secret_accepted( + presented: str | None, + settings: Settings, + device: Device | None, +) -> bool: + """True if ``presented`` may enroll (or re-enroll) ``device``. + + Accepts the shared bootstrap secret, or -- for a device that has enrolled + before -- that device's own re-enrollment secret. Both comparisons are + constant-time, and both run even when the first has already succeeded, so + the answer takes the same time either way. + """ + if not presented: + return False + + shared = settings.enroll_secret.get_secret_value() + by_shared = bool(shared) and secrets.compare_digest(presented, shared) + by_device = device is not None and _matches(presented, device.reenroll_secret_hash) + return by_shared or by_device + + +def require_enroll_secret_configured(settings: Settings) -> None: + """503 rather than 500 when the server has no bootstrap secret (SEC-001). + + A camera that gets this should retry later, not treat itself as rejected: + a 4xx would make the firmware clear a perfectly good token. + """ + if not settings.enroll_secret_is_set: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="enrollment is not configured on this server", + ) + + +# --- bearer token ----------------------------------------------------------- + + +def verify_device_token( + db: DbDep, + authorization: Annotated[str | None, Header()] = None, +) -> Device: + """Resolve ``Authorization: Bearer `` to a Device, or 401. + + 401 is load-bearing: the firmware treats it as "clear the stored token and + re-enroll", which is how a rotated token heals itself without a ladder. A + disabled device gets 403 instead, precisely so that it does *not* re-enroll + in a loop (API.md, Behaviour the Pi should expect). + """ + unauthorized = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or missing device token", + headers={"WWW-Authenticate": "Bearer"}, + ) + + if not authorization: + raise unauthorized + scheme, _, token = authorization.partition(" ") + if scheme.lower() != "bearer" or not token.strip(): + raise unauthorized + + # Look the device up by hash. The hash is deterministic, so this is an + # indexed equality match, not a scan over every device. + device = db.scalar(select(Device).where(Device.token_hash == hash_credential(token.strip()))) + if device is None: + raise unauthorized + if not device.enabled: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="device is disabled", + ) + return device + + +DeviceDep = Annotated[Device, Depends(verify_device_token)] diff --git a/server/src/poorbird/api/envelope.py b/server/src/poorbird/api/envelope.py new file mode 100644 index 0000000..6fbb942 --- /dev/null +++ b/server/src/poorbird/api/envelope.py @@ -0,0 +1,108 @@ +"""The response envelope shared by /ingest and /heartbeat. + +SPEC 4.1 and firmware/API.md: both endpoints return the *same* shape, so a +capture that was going to happen anyway also delivers the command queue at no +extra cost. ``parseEnvelope`` in firmware/src/api_client.cpp handles both with +one function, which is why they must not drift. + +``/status`` deliberately does not use this. The device posts status +immediately before deep sleep, and handing it commands there would mark them +delivered to a device that is about to be unable to run them. +""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from sqlalchemy import or_, select +from sqlalchemy.orm import Session + +from ..models.devices import Device, DeviceCommand, Firmware +from .deps import server_time_ms +from .schemas import Command, Envelope, FirmwareTarget + + +def _epoch_ms(value: datetime | None) -> int | None: + if value is None: + return None + if value.tzinfo is None: + value = value.replace(tzinfo=UTC) + return int(value.timestamp() * 1000) + + +def take_pending_commands(db: Session, device: Device) -> list[Command]: + """Claim this device's queued commands and mark them delivered. + + Delivery is recorded here rather than on ack, because the ack may never + come: the device runs ``reboot`` and ``sleep_now`` and is gone. ``acked_at`` + is the separate, later signal that it actually ran. + + Expired commands are skipped but left in place; the worker's + ``prune_expired_commands`` job is what removes them, so the admin UI can + still show that a command timed out rather than silently losing it. + """ + now = datetime.now(UTC) + + rows = list( + db.scalars( + select(DeviceCommand) + .where( + DeviceCommand.device_id == device.id, + DeviceCommand.delivered_at.is_(None), + or_(DeviceCommand.expires_at.is_(None), DeviceCommand.expires_at > now), + ) + .order_by(DeviceCommand.created_at) + ) + ) + + for row in rows: + row.delivered_at = now + + return [ + Command( + id=row.id, + type=row.type, + payload=row.payload, + expires_at=_epoch_ms(row.expires_at), + ) + for row in rows + ] + + +def firmware_target(db: Session, device: Device) -> FirmwareTarget | None: + """The image this device should be running, or None when it is on target. + + Naming a different version is itself the instruction to flash + (main.cpp:104); an explicit ``ota_update`` command is only for staged + rollouts. So "on target" must mean the key is absent, not null. + + The URL is relative on purpose. ota_mgr.cpp:86 appends anything that does + not start with "http" to the API base, which already ends in /api/v1, so + "/firmware/0.2.0.bin" resolves to /api/v1/firmware/0.2.0.bin -- the + endpoint API.md documents. + """ + target = db.scalar(select(Firmware).where(Firmware.is_target.is_(True))) + if target is None or target.version == device.fw_version: + return None + + return FirmwareTarget( + version=target.version, + url=f"/firmware/{target.version}.bin", + sha256=target.sha256, + size=target.size_bytes, + ) + + +def build_envelope(db: Session, device: Device, capture_id: str | None = None) -> Envelope: + """Assemble the envelope, claiming any pending commands as a side effect. + + The caller commits. Nothing here flushes, so a handler that fails after + this point does not leave commands marked delivered that never went out. + """ + return Envelope( + capture_id=capture_id, + server_time=server_time_ms(), + config_version=device.config_version, + firmware=firmware_target(db, device), + commands=take_pending_commands(db, device), + ) diff --git a/server/src/poorbird/api/ratelimit.py b/server/src/poorbird/api/ratelimit.py new file mode 100644 index 0000000..99a5068 --- /dev/null +++ b/server/src/poorbird/api/ratelimit.py @@ -0,0 +1,191 @@ +"""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) diff --git a/server/src/poorbird/api/routes/commands.py b/server/src/poorbird/api/routes/commands.py new file mode 100644 index 0000000..0d96b2b --- /dev/null +++ b/server/src/poorbird/api/routes/commands.py @@ -0,0 +1,81 @@ +"""POST /api/v1/commands/{command_id}/ack -- the other half of the queue. + +/heartbeat and /ingest hand commands out and mark them delivered. This is +where the device reports what became of one. The two halves are deliberately +separate: delivery is recorded when the command goes out, because the ack may +never arrive -- ``reboot`` and ``sleep_now`` are acked and then the device is +gone, and a device that dies mid-command never acks at all. ``delivered_at`` +therefore means "we handed it over" and ``acked_at`` means "it ran", and the +gap between them is the interesting operational signal. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime + +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 + +log = logging.getLogger(__name__) + +router = APIRouter() + + +@router.post( + "/commands/{command_id}/ack", + status_code=status.HTTP_204_NO_CONTENT, + 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, + body: CommandAck, + db: DbDep, + device: DeviceDep, +) -> Response: + command = db.scalar( + select(DeviceCommand).where( + DeviceCommand.id == command_id, + # Scoped to the calling device. Command ids are sequential, so + # without this a device could ack -- and probe for -- every other + # device's queue. + DeviceCommand.device_id == device.id, + ) + ) + + # 404 rather than 403 for someone else's command: a different code here + # would confirm that the id exists, which is the thing worth not saying. + if command is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such command") + + # Re-acking is allowed and the last word wins. The device retries on a + # timeout, and it cannot tell a lost response from a lost request, so + # refusing the second attempt would strand a command that did in fact run. + command.acked_at = datetime.now(UTC) + command.ack_status = body.status + # The firmware always sends the key, empty when it has nothing to say. + command.result = body.detail or None + + db.commit() + + log.info( + "command acked", + extra={ + "device_id": device.id, + "command_id": command.id, + "type": command.type, + "ack_status": command.ack_status, + }, + ) + + # Liveness stays with /heartbeat on purpose, so the device list has one + # source of truth for "when did we last hear from it". + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/src/poorbird/api/routes/conditions.py b/server/src/poorbird/api/routes/conditions.py new file mode 100644 index 0000000..d24d246 --- /dev/null +++ b/server/src/poorbird/api/routes/conditions.py @@ -0,0 +1,141 @@ +"""POST /api/v1/heartbeat and POST /api/v1/status -- one body, two endpoints. + +Both take the identical conditions payload (firmware/src/api_client.cpp builds +it once, in ``buildConditions``). They differ only in the response: + +* ``/heartbeat`` -> 200 and the envelope: commands, config version, firmware + target. +* ``/status`` -> 204 and nothing. + +The split is not cosmetic. The device posts status immediately before deep +sleep, and pulling down a command queue at that moment would mark commands +delivered that the device is about to become unable to execute. So /status +deliberately returns nothing actionable (API.md). + +A heartbeat the endpoint *accepts* is also what confirms an OTA trial boot: +the device calls esp_ota_mark_app_valid only after one succeeds. Returning 5xx +to a device on a trial image will roll it back -- correct behaviour, but worth +knowing before restarting the server mid-rollout. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime + +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 + +log = logging.getLogger(__name__) + +router = APIRouter() + +# Reasons that mean "this is the last thing I will say for a while". +_GOING_QUIET = {"before_sleep", "before_night_sleep"} + + +def _record(db: DbDep, device, body: DeviceConditions) -> None: + """Append a telemetry row and refresh the device's last-known conditions. + + The row is the time series; the columns on ``devices`` are a denormalised + copy so the device list does not need a correlated subquery per row. + """ + raw = body.model_dump(mode="json") + + db.add( + DeviceStatus( + device_id=device.id, + reason=body.reason, + battery_mv=body.battery.mv, + battery_pct=body.battery.pct, + battery_valid=body.battery.valid, + awake_ms=body.power.awake_ms, + boot_count=body.power.boot_count, + wake_cause=body.power.wake_cause, + last_sleep_s=body.power.last_sleep_s, + total_sleep_s=body.power.total_sleep_s, + captured_today=body.counters.captured_today, + delivered_today=body.counters.delivered_today, + failed_today=body.counters.failed_today, + events_today=body.counters.events_today, + day_index=body.counters.day_index, + is_night=body.night.is_night, + nightlight_on=body.night.nightlight_on, + cam_profile=body.camera.profile, + radar_baud=body.radar.baud, + radar_uart_ok=body.radar.uart_ok, + stream_active=body.stream.active, + rssi=body.system.rssi, + ip=body.system.ip, + free_heap=body.system.free_heap, + free_psram=body.system.free_psram, + ring_depth=body.system.ring_depth, + time_synced=body.time_synced, + device_time=body.device_time, + fw_version=body.fw_version, + config_version=body.config_version, + # Everything as posted, including keys this server does not know + # about yet. The flat columns above are what is worth charting. + raw=raw, + ) + ) + + device.last_seen_at = datetime.now(UTC) + + # Only overwrite a denormalised value when the device actually reported + # one. None means "not sent", which must not erase a good earlier reading. + if body.battery.mv is not None: + device.battery_mv = body.battery.mv + if body.battery.pct is not None: + device.battery_pct = body.battery.pct + if body.battery.valid is not None: + # false means NOT MEASURED, not empty. Stored as reported so the UI can + # render an em dash instead of inventing a low-battery alarm. + device.battery_valid = body.battery.valid + if body.system.rssi is not None: + device.rssi = body.system.rssi + if body.fw_version is not None: + device.fw_version = body.fw_version + + # A device that has just announced it is going to sleep will not answer + # commands, and the UI should say so rather than show it as reachable. + device.awake = body.reason not in _GOING_QUIET + + # device.config_version is the server's intent and is NOT touched here. + # body.config_version is what the device currently runs; the difference is + # exactly what tells it to GET /config. + + +@router.post( + "/heartbeat", + response_model=Envelope, + 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) + envelope = build_envelope(db, device) + db.commit() + return envelope + + +@router.post( + "/status", + status_code=status.HTTP_204_NO_CONTENT, + 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) + db.commit() + # Deliberately no envelope: see the module docstring. + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/src/poorbird/api/routes/device_config.py b/server/src/poorbird/api/routes/device_config.py new file mode 100644 index 0000000..f715987 --- /dev/null +++ b/server/src/poorbird/api/routes/device_config.py @@ -0,0 +1,72 @@ +"""GET /api/v1/config -- the device's settings document. + +Named device_config.py so it does not read as poorbird.config, which is the +server's own settings. The route is /config, as API.md specifies. + +The response is a free-form JSON object by design. ``devices.config`` is one +JSONB document rather than forty columns because the firmware grows tunables +faster than a schema should change, and the device merges and clamps whatever +arrives: keys it does not know are ignored, keys that are absent leave its +current value alone, and dangerous values are clamped on the device itself +(app_config.cpp, configApplyJson). Partial documents are therefore not a +degraded case -- they are the normal one. + +That is also why there is no response model. Validating this shape belongs on +the write path, when the admin UI saves a config, not on the way out to a +device that is going to re-validate it anyway. + +This is a read. It deliberately does not touch last_seen_at: a GET should not +have side effects, and /heartbeat is what records liveness (API.md). +""" + +from __future__ import annotations + +import logging +from typing import Any + +from fastapi import APIRouter, Depends + +from .. import ratelimit +from ..deps import DeviceDep + +log = logging.getLogger(__name__) + +router = APIRouter() + +# Settings that live in real columns on `devices` rather than in the JSONB, +# because the server queries and lists on them. They are still config keys as +# far as the firmware is concerned, so they have to be merged into the +# document on the way out or a change to the column would never reach the +# camera. +# +# device_name is the interesting one: enrollment deliberately does not let a +# device overwrite an operator's rename, and this is the path by which that +# rename actually reaches the device (app_config.cpp:307). +_COLUMN_BACKED = ( + ("device_name", "name"), + ("heartbeat_interval_s", "heartbeat_interval_s"), + ("status_interval_s", "status_interval_s"), +) + + +@router.get( + "/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. + # The columns are the modelled source of truth; a stale copy of one of + # them inside the JSONB must not shadow it. + document: dict[str, Any] = dict(device.config or {}) + + for key, attr in _COLUMN_BACKED: + document[key] = getattr(device, attr) + + # Last, mirroring configApplyJson, which applies config_version only after + # the rest of the payload has been processed. This is the only value the + # device compares, so it must describe the document it arrived with. + document["config_version"] = device.config_version + + return document diff --git a/server/src/poorbird/api/routes/enroll.py b/server/src/poorbird/api/routes/enroll.py new file mode 100644 index 0000000..296c769 --- /dev/null +++ b/server/src/poorbird/api/routes/enroll.py @@ -0,0 +1,127 @@ +"""POST /api/v1/enroll -- device enrollment and re-enrollment. + +The only device endpoint not guarded by a bearer token, because it is where +the token comes from. It is guarded by ``X-Enroll-Secret`` instead: either the +shared bootstrap secret, or the device's own re-enrollment secret once it has +one (firmware/API.md, Authentication). + +Re-enrollment is a normal, expected operation, not an error path. The firmware +re-enrolls on any 401, which is how a token rotated in the admin UI heals +itself without anyone climbing to the camera. API.md is explicit that a known +``device_uid`` must return the existing row with a fresh token rather than a +duplicate -- expect it on every rotation and after any database restore. +""" + +from __future__ import annotations + +import logging + +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, + enroll_secret_accepted, + hash_credential, + new_credential, + require_enroll_secret_configured, + server_time_ms, +) +from ..schemas import EnrollRequest, EnrollResponse + +log = logging.getLogger(__name__) + +router = APIRouter() + + +@router.post( + "/enroll", + status_code=status.HTTP_201_CREATED, + 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, + db: DbDep, + settings: SettingsDep, + x_enroll_secret: str | None = Header(default=None), +) -> EnrollResponse: + # 503 before anything else: a server with no bootstrap secret is + # misconfigured, not rejecting this particular device. A 4xx here would + # make the firmware discard a token that is probably still good. + require_enroll_secret_configured(settings) + + device = db.scalar(select(Device).where(Device.device_uid == body.device_uid)) + + # The lookup has to come first, because a returning device presents its own + # per-device secret rather than the shared one. + if not enroll_secret_accepted(x_enroll_secret, settings, device): + log.warning("enrollment refused", extra={"device_uid": body.device_uid}) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid enrollment secret", + ) + + # A disabled device must not be able to re-enroll its way back in, or + # disabling it in the admin UI would mean nothing: it would simply collect + # a fresh token on its next 401. + if device is not None and not device.enabled: + log.warning("enrollment refused for disabled device", extra={"device_uid": body.device_uid}) + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="device is disabled") + + token = new_credential() + reenroll_secret = new_credential() + returning = device is not None + + if device is None: + device = Device(device_uid=body.device_uid, name=body.device_name) + db.add(device) + + # Hardware facts always follow the device: it is the authority on what it + # is running. The name deliberately does not -- it is set once at first + # enrollment and is an operator-facing label after that, so a re-enrollment + # must not silently undo a rename made in the admin UI. + device.mac = body.mac + device.hw_revision = body.hw_revision + device.fw_version = body.fw_version + + device.token_hash = hash_credential(token) + device.reenroll_secret_hash = hash_credential(reenroll_secret) + + try: + db.commit() + except IntegrityError: + # Two enrollments of the same device_uid racing each other. 503 rather + # than 409: it is transient and the firmware already retries, whereas a + # 4xx reads as "this device is not welcome". + db.rollback() + log.warning("enrollment raced", extra={"device_uid": body.device_uid}) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="enrollment is busy, retry", + ) from None + + db.refresh(device) + log.info( + "device re-enrolled" if returning else "device enrolled", + extra={"device_uid": device.device_uid, "device_id": device.id}, + ) + + # The plaintext token and secret exist here and nowhere else. Only their + # hashes were stored, so this response is the single opportunity to hand + # them to the device. + return EnrollResponse( + token=token, + device_id=device.id, + reenroll_secret=reenroll_secret, + server_time=server_time_ms(), + config_version=device.config_version, + ) diff --git a/server/src/poorbird/api/routes/firmware.py b/server/src/poorbird/api/routes/firmware.py new file mode 100644 index 0000000..1032f86 --- /dev/null +++ b/server/src/poorbird/api/routes/firmware.py @@ -0,0 +1,112 @@ +"""GET /api/v1/firmware/{version}.bin -- the OTA image. + +Bearer auth, like every other device endpoint. Three things the device +requires of this response, all checked before it erases a partition +(firmware/src/ota_mgr.cpp:110-128): + +1. status exactly 200, +2. a ``Content-Length`` header -- it refuses a chunked response, because it + wants to size-check before committing to an erase, +3. that length equal to the ``size`` the envelope advertised. + +So this must not be compressed or chunked on the way out. The camera talks to +the :8080 Caddy block, which has no ``encode`` directive, and FileResponse +sets an exact Content-Length from the file itself. + +The admin-facing ``POST /api/v1/firmware`` from API.md is not here: it needs +user authentication and an admin role, neither of which exists yet +(REVIEW SEC-007). Rows are expected to arrive by other means until then. +""" + +from __future__ import annotations + +import logging +from pathlib import Path + +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__) + +router = APIRouter() + + +def _resolve(file_path: str, settings: Settings) -> Path: + """Where the image actually lives. + + An absolute path is used as given; a relative one resolves under the + state directory. The value comes from the firmware row, which only an + administrator can write -- it is never built from anything in the + request, so there is no traversal to defend against here. The upload + endpoint that eventually writes it is where that check belongs. + """ + candidate = Path(file_path) + return candidate if candidate.is_absolute() else settings.state_dir / "firmware" / candidate + + +@router.get( + "/firmware/{version}.bin", + response_class=FileResponse, + summary="Download an OTA image", + tags=["firmware"], + dependencies=[Depends(ratelimit.by_device("firmware", ratelimit.FIRMWARE))], +) +def download_firmware( + version: str, + db: DbDep, + device: DeviceDep, + settings: SettingsDep, +) -> FileResponse: + row = db.scalar(select(Firmware).where(Firmware.version == version)) + if row is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such firmware") + + path = _resolve(row.file_path, settings) + + if not path.is_file(): + # The row promises an image that is not there. 503 rather than 404: + # the firmware genuinely exists as far as the operator is concerned, + # and this is a server fault worth shouting about rather than a + # missing resource. + log.error( + "firmware row points at a missing file", + extra={"version": row.version, "path": str(path)}, + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="firmware image unavailable", + ) + + # The device compares Content-Length against the size the envelope gave + # it and aborts on a mismatch. Catching that here turns a confusing + # device-side abort into one clear line in the server log. + actual = path.stat().st_size + if actual != row.size_bytes: + log.error( + "firmware size does not match its row", + extra={"version": row.version, "recorded": row.size_bytes, "on_disk": actual}, + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="firmware image does not match its manifest", + ) + + log.info( + "serving firmware", + extra={"version": row.version, "device_id": device.id, "bytes": actual}, + ) + + return FileResponse( + path, + media_type="application/octet-stream", + filename=f"{row.version}.bin", + # The image is immutable for a given version, and the device verifies + # SHA-256 over the whole thing before activating the slot anyway. + headers={"Cache-Control": "public, max-age=31536000, immutable"}, + ) diff --git a/server/src/poorbird/api/routes/ingest.py b/server/src/poorbird/api/routes/ingest.py new file mode 100644 index 0000000..1098b59 --- /dev/null +++ b/server/src/poorbird/api/routes/ingest.py @@ -0,0 +1,220 @@ +"""POST /api/v1/ingest -- a captured frame. + +**Deviation from SPEC 4.1, and a deliberate one.** The spec says +multipart/form-data with the image and a JSON metadata part. The firmware +sends the raw JPEG as the body with the metadata in headers, because +multipart would make the device assemble a second buffer purely to add a +wrapper the server strips immediately; the raw body hands the framebuffer +pointer straight to the HTTP client (firmware/API.md). REVIEW.AI.md's +reference code implemented the multipart version and would not have matched +the firmware at all. + +Returns the same envelope as /heartbeat, so a capture that was going to +happen anyway also delivers the command queue at no extra cost. +""" + +from __future__ import annotations + +import hashlib +import logging +import uuid +from datetime import UTC, datetime +from typing import Annotated + +from fastapi import APIRouter, Body, Depends, Header, HTTPException, status +from pydantic import ValidationError +from sqlalchemy import select + +from ...images import ( + MAX_IMAGE_BYTES, + jpeg_dimensions, + looks_like_jpeg, + relative_image_path, + write_atomically, +) +from ...models.captures import Capture +from ...worker.queue import enqueue +from .. import ratelimit +from ..deps import DbDep, DeviceDep, SettingsDep +from ..envelope import build_envelope +from ..schemas import Envelope, IngestMeta + +log = logging.getLogger(__name__) + +router = APIRouter() + + +def ingest_meta( + x_trigger: Annotated[str, Header()] = "radar", + x_burst_id: Annotated[str | None, Header()] = None, + x_burst_index: Annotated[int | None, Header()] = None, + x_burst_count: Annotated[int | None, Header()] = None, + x_pre_trigger: Annotated[int, Header()] = 0, + x_captured_at: Annotated[int, Header()] = 0, + x_frame_seq: Annotated[int | None, Header()] = None, + x_radar_state: Annotated[int | None, Header()] = None, + x_radar_distance_cm: Annotated[int | None, Header()] = None, + x_radar_energy: Annotated[int | None, Header()] = None, + x_rssi: Annotated[int | None, Header()] = None, +) -> IngestMeta: + """Validate the header metadata into one model (REVIEW SEC-003).""" + try: + return IngestMeta( + trigger=x_trigger, + burst_id=x_burst_id or None, + burst_index=x_burst_index, + burst_count=x_burst_count, + pre_trigger=bool(x_pre_trigger), + # X-Captured-At: 0 means the device clock is unsynced. That is + # NULL, not 1970 -- storing an epoch date here would put the frame + # at the bottom of every chronological view forever (API.md). + captured_at=( + datetime.fromtimestamp(x_captured_at / 1000, UTC) if x_captured_at > 0 else None + ), + frame_seq=x_frame_seq, + radar_state=x_radar_state, + radar_distance_cm=x_radar_distance_cm, + radar_energy=x_radar_energy, + rssi=x_rssi, + ) + except ValidationError as exc: + # A dependency raising ValidationError would otherwise surface as a + # 500. The metadata is client input; it deserves a 422. + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail=exc.errors(include_url=False), + ) from None + + +@router.post( + "/ingest", + status_code=status.HTTP_201_CREATED, + response_model=Envelope, + 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, + device: DeviceDep, + settings: SettingsDep, + meta: Annotated[IngestMeta, Depends(ingest_meta)], + body: Annotated[bytes, Body(media_type="image/jpeg")] = b"", +) -> Envelope: + if not body: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="empty body") + if len(body) > MAX_IMAGE_BYTES: + raise HTTPException( + status_code=status.HTTP_413_CONTENT_TOO_LARGE, + detail=f"image exceeds {MAX_IMAGE_BYTES} bytes", + ) + # Trust the bytes, not the Content-Type. 400 and not 401: the device must + # not read this as a credential problem and clear a perfectly good token. + if not looks_like_jpeg(body): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="body is not a JPEG") + + digest = hashlib.sha256(body).hexdigest() + + # The device retries an upload whose response was lost, and it cannot tell + # that case from a genuine failure. Identical bytes from the same device + # are that retry -- two real frames never collide, since sensor noise + # alone makes every capture unique. Returning the original capture keeps + # ingest idempotent instead of filling the gallery with duplicates. + # + # Scoped to the device, and checked in the application rather than with a + # unique constraint: a genuine collision should lose a frame, not 500. + # Burst uploads are sequential (API.md), so there is no race to lose. + existing = db.scalar( + select(Capture).where(Capture.device_id == device.id, Capture.sha256 == digest) + ) + if existing is not None: + log.info( + "ingest de-duplicated", + extra={"device_id": device.id, "capture_id": str(existing.id)}, + ) + envelope = build_envelope(db, device, capture_id=str(existing.id)) + db.commit() + return envelope + + capture_id = uuid.uuid4() + received_at = datetime.now(UTC) + relative = relative_image_path(capture_id, received_at) + destination = settings.image_root / relative + + try: + write_atomically(destination, body) + except OSError as exc: + # Disk full, root not mounted, permissions. 503 rather than 500: it is + # transient from the device's point of view and it should retry. + log.error("cannot write capture", extra={"path": str(destination), "error": str(exc)}) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="image storage unavailable", + ) from None + + dimensions = jpeg_dimensions(body) + + capture = Capture( + id=capture_id, + device_id=device.id, + path=relative, + # Filled in by the thumbnail job below. NULL means "not yet", which + # the gallery has to handle regardless: a capture is visible the + # moment it lands, not once it has been processed. + thumb_path=None, + sha256=digest, + width=dimensions[0] if dimensions else None, + height=dimensions[1] if dimensions else None, + bytes=len(body), + captured_at_device=meta.captured_at, + received_at=received_at, + trigger=meta.trigger, + burst_id=meta.burst_id, + burst_index=meta.burst_index, + burst_count=meta.burst_count, + pre_trigger=meta.pre_trigger, + frame_seq=meta.frame_seq, + radar_state=meta.radar_state, + radar_distance_cm=meta.radar_distance_cm, + radar_energy=meta.radar_energy, + rssi=meta.rssi, + ) + db.add(capture) + + device.last_seen_at = received_at + if meta.rssi is not None: + device.rssi = meta.rssi + + # Off the request path on purpose: decoding a frame to resize it is the + # one genuinely expensive thing about a capture, and the device is + # waiting on this response with a burst still to upload. Enqueued in the + # same transaction as the row, so the worker never sees a job for a + # capture that was rolled back. + enqueue(db, "thumbnail", {"capture_id": str(capture_id)}) + + envelope = build_envelope(db, device, capture_id=str(capture_id)) + + try: + db.commit() + except Exception: + # The file is already on disk. Remove it rather than leave an orphan + # that nothing references. The reverse order -- row first, file second + # -- would be worse: a row pointing at a missing image is a broken + # gallery entry, whereas a stray file is invisible and sweepable. + db.rollback() + destination.unlink(missing_ok=True) + raise + + log.info( + "capture ingested", + extra={ + "device_id": device.id, + "capture_id": str(capture_id), + "bytes": len(body), + "trigger": meta.trigger, + "pre_trigger": meta.pre_trigger, + }, + ) + + return envelope diff --git a/server/src/poorbird/api/schemas.py b/server/src/poorbird/api/schemas.py new file mode 100644 index 0000000..bc189d5 --- /dev/null +++ b/server/src/poorbird/api/schemas.py @@ -0,0 +1,283 @@ +"""Request and response shapes for the device API (REVIEW SEC-003). + +The contract is ``firmware/API.md``, and where it disagrees with SPEC.md the +firmware wins, because the firmware is what is actually on the camera. Two +places where that matters are called out inline: ``/ingest`` carries a raw JPEG +body with metadata in headers, not multipart, and the enrollment body field is +``device_name``, not ``name``. + +Nothing here talks to the database. These models exist so that a malformed or +hostile request is rejected at the edge with a 422, before any handler reaches +for a session. + +One deliberate looseness: the conditions models accept unknown keys. The +firmware grows fields faster than the server learns about them, and +``device_status.raw`` exists precisely to keep the whole posted body. Rejecting +a camera because it reports something new would be the wrong failure. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from ..models.captures import TRIGGERS +from ..models.devices import COMMAND_TYPES, STATUS_REASONS + +Trigger = Literal[TRIGGERS] # type: ignore[valid-type] +StatusReason = Literal[STATUS_REASONS] # type: ignore[valid-type] +CommandType = Literal[COMMAND_TYPES] # type: ignore[valid-type] + +# The firmware holds these in char[65], so 64 characters plus a NUL. Issue +# exactly 64 hex characters and a token can never be silently truncated on the +# device (firmware/include/app_config.h). +TOKEN_CHARS = 64 + + +class _Loose(BaseModel): + """Base for anything the firmware posts: keep unknown keys, do not 422.""" + + model_config = ConfigDict(extra="allow") + + +# --- enrollment ------------------------------------------------------------- + + +class EnrollRequest(BaseModel): + model_config = ConfigDict(extra="ignore") + + # eFuse MAC in hex. Survives reflashing, which is what makes it an identity + # rather than a name (API.md, Enrollment). + device_uid: Annotated[str, Field(min_length=6, max_length=32, pattern=r"^[0-9a-fA-F]+$")] + # API.md calls this device_name. REVIEW.AI.md calls it name; the firmware + # sends device_name, so that is what this is. + device_name: Annotated[str, Field(min_length=1, max_length=64)] + hw_revision: Annotated[str | None, Field(max_length=64)] = None + fw_version: Annotated[str | None, Field(max_length=32)] = None + mac: Annotated[str | None, Field(max_length=32)] = None + + +class EnrollResponse(BaseModel): + """201. The token is returned in the clear exactly once, here. + + Only its hash is stored. Returning the stored hash instead would hand the + device a credential the server cannot recognise, and every later request + would 401. + """ + + token: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)] + device_id: int + reenroll_secret: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)] + server_time: int # epoch ms, UTC, authoritative (SPEC C7) + config_version: int + + +# --- the shared response envelope ------------------------------------------- + + +class FirmwareTarget(BaseModel): + version: str + url: str + sha256: Annotated[str, Field(min_length=64, max_length=64)] + size: int + + +class Command(BaseModel): + id: int + type: CommandType + payload: dict[str, Any] | None = None + expires_at: int | None = None # epoch ms; the firmware ignores it, the server prunes on it + + +class Envelope(BaseModel): + """Returned by /ingest and /heartbeat, identically (API.md, SPEC 4.1). + + ``capture_id`` is documented as an integer in API.md's example, but + ``captures.id`` is a UUID and the firmware never reads the field back + (verified in firmware/src/api_client.cpp::parseEnvelope, which pulls only + server_time, config_version, firmware and commands). Sent as a UUID string. + """ + + capture_id: str | None = None + server_time: int + config_version: int + # Omit the key entirely when the device is on target: present-and-different + # is itself the signal to flash (API.md). Omission is a serialisation + # concern, so the routes set response_model_exclude_none=True rather than + # anything here. + firmware: FirmwareTarget | None = None + commands: list[Command] = Field(default_factory=list) + + +# --- ingest ----------------------------------------------------------------- + + +class IngestMeta(BaseModel): + """Metadata for POST /ingest, which arrives in headers, not a body. + + Deviation from SPEC 4.1, and a deliberate one: the raw JPEG is the body, so + the device hands over its framebuffer pointer without assembling a second + multipart buffer (API.md). REVIEW.AI.md's reference code used multipart and + would not have matched the firmware. + """ + + model_config = ConfigDict(extra="ignore") + + trigger: Trigger + burst_id: Annotated[str | None, Field(max_length=64)] = None + burst_index: int | None = None + burst_count: int | None = None + pre_trigger: bool = False + # epoch ms UTC. 0 means the device clock is unsynced: that is NULL, not + # 1970 (API.md). received_at stays authoritative either way (SPEC C7). + captured_at: datetime | None = None + frame_seq: int | None = None + radar_state: Annotated[int | None, Field(ge=0, le=3)] = None + radar_distance_cm: int | None = None + radar_energy: Annotated[int | None, Field(ge=0, le=100)] = None + # From X-Rssi, one of the common headers on every authenticated request + # rather than an ingest-specific one, but captures.rssi is the column it + # belongs in: signal strength at the moment this frame was uploaded. + rssi: int | None = None + + +# --- device conditions: one body, two endpoints ----------------------------- +# +# POST /heartbeat -> 200 + Envelope, POST /status -> 204 and nothing. +# The split is not cosmetic: the device posts status immediately before deep +# sleep, and handing it commands at that moment would mark them delivered to a +# device that is about to be unable to run them (API.md). + + +class PowerBlock(_Loose): + uptime_ms: int | None = None + # Resets on every wake, unlike uptime_ms which resets only on reboot. + awake_ms: int | None = None + boot_count: int | None = None + wake_cause: Annotated[str | None, Field(max_length=16)] = None + last_sleep_s: int | None = None + total_sleep_s: int | None = None + sleep_enabled: bool | None = None + sleep_allowed: bool | None = None + inhibits: str | None = None + + +class BatteryBlock(_Loose): + # false means NOT MEASURED, not empty: no divider is wired by default. + # Render as an em dash, never as a low-battery alarm (API.md). + valid: bool | None = None + mv: int | None = None + pct: Annotated[int | None, Field(ge=0, le=100)] = None + raw_mv: int | None = None + # 0 means pct is meaningless; show the voltage only. + chemistry: int | None = None + low: bool | None = None + + +class CountersBlock(_Loose): + """The device's opinion, not the truth: RTC memory, reset on power loss. + + ``captures`` is authoritative. What these are genuinely good for is the gap + between captured_today and delivered_today, which is an upload-health + signal you would otherwise only notice as a quiet camera. + """ + + captured_today: int | None = None + delivered_today: int | None = None + failed_today: int | None = None + events_today: int | None = None + # Days since epoch in local time. Stays 0 until the clock syncs, so the + # pre-sync bucket is a phantom day that rolls over once. Do not chart it. + day_index: int | None = None + captured_boot: int | None = None + delivered_boot: int | None = None + + +class CameraBlock(_Loose): + # Send names, not indices: entries have been inserted into the middle of + # framesize_t between driver releases, so a stored index silently means a + # different resolution after a firmware update (API.md). + frame_size: str | int | None = None + frame_size_id: int | None = None + width: int | None = None + height: int | None = None + # 0x2640 OV2640, 0x3660 OV3660, 0x5640 OV5640. Newer XIAO Sense units have + # shipped with OV3660, so do not assume from the product listing. + sensor_pid: int | None = None + jpeg_quality: int | None = None + profile: Annotated[str | None, Field(max_length=16)] = None + ready: bool | None = None + + +class NightBlock(_Loose): + is_night: bool | None = None + nightlight_on: bool | None = None + behaviour: int | None = None + capture_allowed: bool | None = None + + +class StreamBlock(_Loose): + enabled: bool | None = None + active: bool | None = None + frames_sent: int | None = None + seconds_left: int | None = None + + +class RadarBlock(_Loose): + # 0 here means no valid frame decoded at any rate: wiring or a dead module, + # and worth an alert (API.md). + baud: int | None = None + uart_ok: bool | None = None + out_pin: bool | None = None + state: Annotated[int | None, Field(ge=0, le=3)] = None + moving_cm: int | None = None + moving_energy: int | None = None + stationary_cm: int | None = None + stationary_energy: int | None = None + + +class SystemBlock(_Loose): + rssi: int | None = None + ip: Annotated[str | None, Field(max_length=45)] = None + free_heap: int | None = None + free_psram: int | None = None + ring_depth: int | None = None + ring_bytes: int | None = None + + +class DeviceConditions(_Loose): + """The body of both POST /heartbeat and POST /status.""" + + reason: StatusReason + fw_version: Annotated[str | None, Field(max_length=32)] = None + hw_revision: Annotated[str | None, Field(max_length=64)] = None + config_version: int | None = None + + power: PowerBlock = Field(default_factory=PowerBlock) + battery: BatteryBlock = Field(default_factory=BatteryBlock) + counters: CountersBlock = Field(default_factory=CountersBlock) + camera: CameraBlock = Field(default_factory=CameraBlock) + night: NightBlock = Field(default_factory=NightBlock) + stream: StreamBlock = Field(default_factory=StreamBlock) + radar: RadarBlock = Field(default_factory=RadarBlock) + system: SystemBlock = Field(default_factory=SystemBlock) + + time_synced: bool | None = None + device_time: datetime | None = None + + @field_validator("device_time", mode="before") + @classmethod + def _empty_is_none(cls, v: Any) -> Any: + return None if v in ("", 0) else v + + +# --- commands --------------------------------------------------------------- + + +class CommandAck(BaseModel): + model_config = ConfigDict(extra="ignore") + + status: Literal["done", "failed", "rejected"] + detail: Annotated[str | None, Field(max_length=1000)] = None diff --git a/server/src/poorbird/cli.py b/server/src/poorbird/cli.py index a60bf63..2b3b9b0 100644 --- a/server/src/poorbird/cli.py +++ b/server/src/poorbird/cli.py @@ -81,23 +81,27 @@ def cmd_check(_args: argparse.Namespace) -> int: print(f" python {sys.version.split()[0]}") # Never print the password. - url = settings.database_url - if "@" in url: - scheme, _, rest = url.partition("://") - url = f"{scheme}://***@{rest.rpartition('@')[2]}" - print(f" database_url {url}") + if not settings.database_url_is_set: + print(" database_url NOT SET (POORBIRD_DATABASE_URL)") + problems.append("POORBIRD_DATABASE_URL not set") + else: + url = settings.database_url + if "@" in url: + scheme, _, rest = url.partition("://") + url = f"{scheme}://***@{rest.rpartition('@')[2]}" + print(f" database_url {url}") - try: - from sqlalchemy import text + try: + from sqlalchemy import text - from .db import engine + from .db import engine - with engine.connect() as conn: - version = conn.execute(text("SHOW server_version")).scalar() - print(f" database reachable (PostgreSQL {version})") - except Exception as exc: # noqa: BLE001 - print(f" database UNREACHABLE: {type(exc).__name__}: {exc}") - problems.append("database unreachable") + with engine.connect() as conn: + version = conn.execute(text("SHOW server_version")).scalar() + print(f" database reachable (PostgreSQL {version})") + except Exception as exc: # noqa: BLE001 + print(f" database UNREACHABLE: {type(exc).__name__}: {exc}") + problems.append("database unreachable") try: from alembic import command diff --git a/server/src/poorbird/config.py b/server/src/poorbird/config.py index 11b40c4..22bc18c 100644 --- a/server/src/poorbird/config.py +++ b/server/src/poorbird/config.py @@ -12,9 +12,13 @@ from functools import lru_cache from pathlib import Path from typing import Literal -from pydantic import SecretStr +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( @@ -27,8 +31,20 @@ class Settings(BaseSettings): # --- 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). - database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird" - db_pool_size: int = 5 + # + # 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 ------------------------------------------------------------- @@ -50,11 +66,24 @@ class Settings(BaseSettings): # 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("") + # --- 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 ----------------------------------------------------------- - worker_poll_interval_s: float = 2.0 - worker_batch_size: int = 1 + # 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 ---------------------------------------------------------- @@ -63,6 +92,31 @@ class Settings(BaseSettings): 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()) diff --git a/server/src/poorbird/db.py b/server/src/poorbird/db.py index a479968..5b0cdaf 100644 --- a/server/src/poorbird/db.py +++ b/server/src/poorbird/db.py @@ -18,9 +18,24 @@ from .config import get_settings _settings = get_settings() +if not _settings.database_url_is_set: + # create_engine("") raises "Could not parse SQLAlchemy URL from string ''", + # which sends people looking in the wrong place. Say what to actually do. + raise RuntimeError( + "POORBIRD_DATABASE_URL is not set. Export it, or put it in server/.env:\n" + " POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:" + "@127.0.0.1:5432/poorbird\n" + "See server/deploy/poorbird.env.example. Run 'poorbird check' to verify." + ) + engine = create_engine( _settings.database_url, pool_size=_settings.db_pool_size, + max_overflow=_settings.db_max_overflow, + # Past pool_size + max_overflow a caller waits rather than failing. It has + # to be finite: without a timeout a pool leak presents as requests hanging + # forever instead of as an error naming the pool. + pool_timeout=30, pool_pre_ping=True, echo=_settings.db_echo, future=True, diff --git a/server/src/poorbird/images.py b/server/src/poorbird/images.py new file mode 100644 index 0000000..7187f64 --- /dev/null +++ b/server/src/poorbird/images.py @@ -0,0 +1,171 @@ +"""Where capture bytes go, and what can be read back out of them. + +Lives at package level rather than under ``api`` because both sides use it: +the ingest route writes frames, and the worker reads them back to build +thumbnails. A worker importing from ``api`` would be the wrong way round. + +Split by cost, deliberately. Everything above the thumbnail section runs on +the ingest path, once per frame, and must never be the reason a burst is +slow -- so it reads nine bytes of JPEG header rather than decoding an image. +Pillow appears only below, in the worker, where the frame has to be decoded +anyway. +""" + +from __future__ import annotations + +import os +import uuid +from datetime import datetime +from pathlib import Path + +# Matches `request_body max_size 12MB` in deploy/Caddyfile. Enforced here too, +# because Caddy is not in front of the app in development and a limit that +# only exists in the proxy is not a limit. +MAX_IMAGE_BYTES = 12 * 1024 * 1024 + +# SOI. A JPEG always starts FF D8 FF; anything else is not one, whatever the +# Content-Type header claims. +_JPEG_MAGIC = b"\xff\xd8\xff" + +# Start-of-frame markers, which carry the dimensions. C4 (DHT), C8 (JPG) and +# CC (DAC) share the range but are not SOF. +_SOF_MARKERS = frozenset( + {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} +) + + +def looks_like_jpeg(data: bytes) -> bool: + return data.startswith(_JPEG_MAGIC) + + +def jpeg_dimensions(data: bytes) -> tuple[int, int] | None: + """(width, height) from the JPEG header, or None if it cannot be read. + + Walks the segment chain to the first SOF. None is not an error: a frame + whose dimensions we cannot parse is still a frame worth keeping, and the + columns are nullable for exactly that reason. + """ + i, n = 2, len(data) + + while i + 3 < n: + if data[i] != 0xFF: + i += 1 + continue + + marker = data[i + 1] + + # Standalone markers: no length field follows. + if marker == 0x01 or 0xD0 <= marker <= 0xD8: + i += 2 + continue + if marker == 0xD9: # EOI + break + + segment_length = int.from_bytes(data[i + 2 : i + 4], "big") + if segment_length < 2: + break # malformed; a shorter length would not advance + + if marker in _SOF_MARKERS: + if i + 9 > n: + break + height = int.from_bytes(data[i + 5 : i + 7], "big") + width = int.from_bytes(data[i + 7 : i + 9], "big") + return (width, height) if width and height else None + + i += 2 + segment_length + + return None + + +def relative_image_path(capture_id: uuid.UUID, received_at: datetime) -> str: + """``YYYY/MM/DD/.jpg`` (SPEC 3.3). + + Dated by ``received_at``, never by the device clock: the device may be + unsynced and report nothing at all, and SPEC C7 makes server time + authoritative. Stored relative to POORBIRD_IMAGE_ROOT so the root stays a + deployment concern -- Caddy resolves the same relative path against the + same configured root when it serves the bytes. + """ + return f"{received_at:%Y/%m/%d}/{capture_id}.jpg" + + +def write_atomically(destination: Path, data: bytes) -> None: + """Write via a temporary file in the same directory, then rename. + + A half-written JPEG is indistinguishable from a whole one until something + tries to decode it, so the file must never be visible at its final path + until it is complete. Same directory keeps the rename on one filesystem, + which is what makes it atomic. + """ + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name(f".{destination.name}.part") + + try: + temporary.write_bytes(data) + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + +# --- thumbnails ------------------------------------------------------------- +# +# Worker only. Nothing above this line imports Pillow, so the ingest path +# never pays for it. + +# 400px on the long edge, WebP, matching the /thumbs/_400.webp pattern +# in SPEC 3.3. The number is in the filename, so changing it means writing to +# a new name rather than silently serving a differently-sized image from the +# old one. +THUMB_EDGE = 400 +THUMB_QUALITY = 80 + + +class UndecodableImage(Exception): + """The bytes are not an image this build of Pillow can read. + + Distinct from an I/O error on purpose: a frame that cannot be decoded + will never decode, so retrying is pointless and the worker should record + the fact rather than burn its attempts. + """ + + +def relative_thumb_path(capture_id: uuid.UUID) -> str: + """``_400.webp`` (SPEC 3.3), flat rather than dated. + + Thumbnails are addressed by capture id alone and there are far fewer of + them per byte, so the dated tree that keeps the image directories to a + sane size buys nothing here. + """ + return f"{capture_id}_{THUMB_EDGE}.webp" + + +def make_thumbnail(source: Path) -> tuple[bytes, tuple[int, int]]: + """Encode a WebP thumbnail. Returns the bytes and the SOURCE dimensions. + + The source size is returned because the worker is the first place that + truly decodes the frame: ingest reads the JPEG header, which can be + absent or unparseable, and this is the chance to fill in what it missed. + """ + import io + + from PIL import Image, UnidentifiedImageError + + try: + with Image.open(source) as img: + img.load() + original = (img.width, img.height) + + # Never upscale. A frame smaller than the thumbnail box should + # stay its own size rather than be blown up into a blurry one. + thumb = img.convert("RGB") + thumb.thumbnail((THUMB_EDGE, THUMB_EDGE), Image.Resampling.LANCZOS) + + buffer = io.BytesIO() + thumb.save(buffer, format="WEBP", quality=THUMB_QUALITY, method=4) + return buffer.getvalue(), original + except (UnidentifiedImageError, OSError, ValueError) as exc: + # Pillow raises OSError for a truncated file as well as for a real + # I/O fault, and the two are not worth separating here: either way + # this frame is not going to produce a thumbnail. + raise UndecodableImage(f"{type(exc).__name__}: {exc}") from exc diff --git a/server/src/poorbird/logging_setup.py b/server/src/poorbird/logging_setup.py index 18bd27b..0f63c6c 100644 --- a/server/src/poorbird/logging_setup.py +++ b/server/src/poorbird/logging_setup.py @@ -11,9 +11,11 @@ import logging import sys from datetime import UTC, datetime -_RESERVED = set( - logging.LogRecord("", 0, "", 0, "", None, None).__dict__ -) | {"message", "asctime", "taskName"} +_RESERVED = set(logging.LogRecord("", 0, "", 0, "", None, None).__dict__) | { + "message", + "asctime", + "taskName", +} class JsonFormatter(logging.Formatter): @@ -37,9 +39,7 @@ def configure_logging(level: str = "INFO", fmt: str = "text") -> None: if fmt == "json": handler.setFormatter(JsonFormatter()) else: - handler.setFormatter( - logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s") - ) + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s")) root = logging.getLogger() root.handlers.clear() diff --git a/server/src/poorbird/models/captures.py b/server/src/poorbird/models/captures.py index a0bf70e..cd07b77 100644 --- a/server/src/poorbird/models/captures.py +++ b/server/src/poorbird/models/captures.py @@ -90,9 +90,7 @@ class Capture(Base): # Soft reject. Drives retention -- see TODO Phase 5 and open question 8. kept: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true") - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) observations: Mapped[list[Observation]] = relationship( back_populates="capture", cascade="all, delete-orphan" @@ -138,9 +136,7 @@ class Observation(Base): bbox: Mapped[dict | None] = mapped_column(JSONB) created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) updated_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), onupdate=func.now() ) diff --git a/server/src/poorbird/models/devices.py b/server/src/poorbird/models/devices.py index c1be8a9..14882e5 100644 --- a/server/src/poorbird/models/devices.py +++ b/server/src/poorbird/models/devices.py @@ -64,7 +64,14 @@ class Device(Base): # Only the hash is stored. The token is high-entropy, so a fast hash is # defensible here (API.md). - token_hash: Mapped[str | None] = mapped_column(String(128)) + # + # Indexed because every authenticated device request resolves a bearer + # token by this column: it is the hottest lookup in the device API. + # + # Unique so that two devices can never end up sharing a token. NULLs stay + # distinct in Postgres, so any number of devices may sit here un-enrolled + # or revoked. + token_hash: Mapped[str | None] = mapped_column(String(128), unique=True, index=True) # Per-device re-enrollment credential, so a rotated token cannot strand a # camera that has no USB access once mounted (SPEC 0). reenroll_secret_hash: Mapped[str | None] = mapped_column(String(128)) @@ -96,9 +103,7 @@ class Device(Base): responsive_mode: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true") - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) commands: Mapped[list[DeviceCommand]] = relationship( back_populates="device", cascade="all, delete-orphan" @@ -132,9 +137,7 @@ class DeviceCommand(Base): payload: Mapped[dict | None] = mapped_column(JSONB) created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) acked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) ack_status: Mapped[str | None] = mapped_column(String(16)) diff --git a/server/src/poorbird/models/ops.py b/server/src/poorbird/models/ops.py index e65845c..124fa44 100644 --- a/server/src/poorbird/models/ops.py +++ b/server/src/poorbird/models/ops.py @@ -66,9 +66,7 @@ class BackupRun(Base): __tablename__ = "backup_runs" id: Mapped[int] = mapped_column(BigInteger, primary_key=True) - started_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) status: Mapped[str] = mapped_column(String(16), default="running") bytes: Mapped[int | None] = mapped_column(BigInteger) @@ -106,7 +104,5 @@ class Job(Base): locked_by: Mapped[str | None] = mapped_column(String(128)) last_error: Mapped[str | None] = mapped_column(Text) - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/server/src/poorbird/models/users.py b/server/src/poorbird/models/users.py index 4393d75..9f5f89f 100644 --- a/server/src/poorbird/models/users.py +++ b/server/src/poorbird/models/users.py @@ -46,9 +46,7 @@ class User(Base): theme: Mapped[str] = mapped_column(String(16), default="light", server_default="'light'") locale: Mapped[str] = mapped_column(String(8), default="de", server_default="'de'") - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) @@ -57,9 +55,7 @@ class Session(Base): 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) - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + 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)) user_agent: Mapped[str | None] = mapped_column(String(255)) diff --git a/server/src/poorbird/worker/handlers.py b/server/src/poorbird/worker/handlers.py index 0b3f315..b72e0c7 100644 --- a/server/src/poorbird/worker/handlers.py +++ b/server/src/poorbird/worker/handlers.py @@ -10,12 +10,18 @@ Phase 2 adds ``thumbnail``. Phase 5 adds ``backup``, ``retention`` and from __future__ import annotations import logging +import uuid from collections.abc import Callable from typing import Any +from pydantic import BaseModel, ValidationError from sqlalchemy import 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 + log = logging.getLogger(__name__) Handler = Callable[[Session, dict[str, Any]], None] @@ -38,6 +44,76 @@ def _noop(session: Session, payload: dict[str, Any]) -> None: log.info("noop job ran", extra={"payload": payload}) +class ThumbnailPayload(BaseModel): + """Validated job payload (REVIEW SEC-003). + + Job payloads are JSONB and nothing stops a malformed one being enqueued, + so a handler that indexes straight into the dict fails with a KeyError + three retries later instead of saying what was wrong. + """ + + capture_id: uuid.UUID + + +@handler("thumbnail") +def _thumbnail(session: Session, payload: dict[str, Any]) -> None: + """Build the WebP thumbnail for one capture. + + Enqueued by /ingest after the frame is on disk and in the same + transaction as the capture row, so by the time this runs both exist. + """ + try: + job = ThumbnailPayload.model_validate(payload) + except ValidationError as exc: + # Permanently wrong, not transient. Raising would spend three + # attempts rediscovering that the payload is still malformed. + log.error("thumbnail job payload is invalid", extra={"payload": payload, "error": str(exc)}) + return + + capture = session.get(Capture, job.capture_id) + if capture is None: + # Deleted between enqueue and now. Retention will do this routinely + # once Phase 5 exists, and it is not a failure. + log.info("thumbnail skipped, capture is gone", extra={"capture_id": str(job.capture_id)}) + return + + settings = get_settings() + source = settings.image_root / capture.path + + if not source.is_file(): + # The file should be there: ingest writes it before committing the + # row. Its absence is a real fault, and transient causes (a mount + # that has not come back yet) are worth retrying for. + raise FileNotFoundError(f"capture file missing: {source}") + + try: + data, (width, height) = make_thumbnail(source) + except UndecodableImage as exc: + # A frame that cannot be decoded will never decode. Record it and + # finish, rather than retrying twice more to learn the same thing. + log.warning( + "capture could not be decoded, leaving it without a thumbnail", + extra={"capture_id": str(capture.id), "path": capture.path, "error": str(exc)}, + ) + return + + relative = relative_thumb_path(capture.id) + write_atomically(settings.thumb_root / relative, data) + + capture.thumb_path = relative + # Ingest reads dimensions from the JPEG header, which can be missing or + # unparseable. This is the first full decode, so fill in what it missed. + if capture.width is None or capture.height is None: + capture.width, capture.height = width, height + + session.commit() + + log.info( + "thumbnail written", + extra={"capture_id": str(capture.id), "path": relative, "bytes": len(data)}, + ) + + @handler("prune_expired_commands") def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None: """Expire commands the device never came back for. diff --git a/server/src/poorbird/worker/main.py b/server/src/poorbird/worker/main.py index 0a68662..2c1907e 100644 --- a/server/src/poorbird/worker/main.py +++ b/server/src/poorbird/worker/main.py @@ -101,6 +101,13 @@ def run() -> int: ) try: + # One job per claim, deliberately. The review suggested claiming in + # batches of 5, but this loop already runs jobs back to back without + # sleeping while the queue has work, so a batch would only save claim + # round-trips -- and it would cost crash safety. Claiming 5 marks all 5 + # 'running'; dying after the first leaves four locked by a process that + # no longer exists, invisible until requeue_stale gets to them up to 15 + # minutes later. Single claims keep exactly one job at risk. while not _stop.is_set(): try: with SessionLocal() as session: diff --git a/server/src/poorbird/worker/queue.py b/server/src/poorbird/worker/queue.py index ecdda58..5f1dbb5 100644 --- a/server/src/poorbird/worker/queue.py +++ b/server/src/poorbird/worker/queue.py @@ -76,8 +76,7 @@ def claim(session: Session) -> dict[str, Any] | None: def complete(session: Session, job_id: int) -> None: session.execute( text( - "UPDATE jobs SET status = 'done', finished_at = now(), " - "last_error = NULL WHERE id = :id" + "UPDATE jobs SET status = 'done', finished_at = now(), last_error = NULL WHERE id = :id" ), {"id": job_id}, ) diff --git a/server/tests/conftest.py b/server/tests/conftest.py index df0f4a3..916fc29 100644 --- a/server/tests/conftest.py +++ b/server/tests/conftest.py @@ -9,6 +9,10 @@ os.environ.setdefault("POORBIRD_LOG_LEVEL", "WARNING") os.environ.setdefault("POORBIRD_IMAGE_ROOT", "/tmp/poorbird-test/images") os.environ.setdefault("POORBIRD_THUMB_ROOT", "/tmp/poorbird-test/thumbs") os.environ.setdefault("POORBIRD_STATE_DIR", "/tmp/poorbird-test/state") +# Off by default: the suite fires far more requests at an endpoint than any +# camera would, and would otherwise spend its own budget and start asserting +# against 429s. tests/test_ratelimit.py turns it back on deliberately. +os.environ.setdefault("POORBIRD_RATE_LIMIT_ENABLED", "false") def database_is_reachable() -> bool: diff --git a/server/tests/test_commands_ack.py b/server/tests/test_commands_ack.py new file mode 100644 index 0000000..a41558a --- /dev/null +++ b/server/tests/test_commands_ack.py @@ -0,0 +1,224 @@ +"""POST /api/v1/commands/{id}/ack, and the full command lifecycle with it.""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +def _make_device(db, name="cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + return d, {"Authorization": f"Bearer {token}"} + + +def _cleanup(db, *devices): + for d in devices: + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def device(db): + d, auth = _make_device(db) + yield d, auth + _cleanup(db, d) + + +@pytest.fixture +def queued(db, device): + d, auth = device + cmd = DeviceCommand(device_id=d.id, type="capture_now") + db.add(cmd) + db.commit() + db.refresh(cmd) + return d, auth, cmd + + +CONDITIONS = {"reason": "heartbeat"} + + +# --- the lifecycle ---------------------------------------------------------- + + +@needs_db +def test_delivered_then_acked(client, queued, db): + """The whole round trip: queued -> delivered by heartbeat -> acked.""" + d, auth, cmd = queued + + assert cmd.delivered_at is None and cmd.acked_at is None + + envelope = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() + assert [c["id"] for c in envelope["commands"]] == [cmd.id] + + db.refresh(cmd) + assert cmd.delivered_at is not None + assert cmd.acked_at is None # delivered is not the same as done + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", + json={"status": "done", "detail": "captured 3 frames"}, + headers=auth, + ) + assert r.status_code == 204 + assert r.content == b"" + + db.refresh(cmd) + assert cmd.acked_at is not None + assert cmd.ack_status == "done" + assert cmd.result == "captured 3 frames" + + +@needs_db +@pytest.mark.parametrize("outcome", ["done", "failed", "rejected"]) +def test_every_documented_outcome_is_accepted(client, queued, db, outcome): + d, auth, cmd = queued + r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": outcome}, headers=auth) + assert r.status_code == 204 + + db.refresh(cmd) + assert cmd.ack_status == outcome + + +@needs_db +def test_an_unknown_outcome_is_422(client, queued): + d, auth, cmd = queued + r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "maybe"}, headers=auth) + assert r.status_code == 422 + + +@needs_db +def test_an_empty_detail_is_stored_as_null(client, queued, db): + """The firmware always sends the key, empty when it has nothing to say.""" + d, auth, cmd = queued + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done", "detail": ""}, headers=auth + ) + + db.refresh(cmd) + assert cmd.result is None + + +@needs_db +def test_a_command_can_be_acked_without_having_been_delivered(client, queued, db): + """Odd but harmless, and refusing it would strand a real ack if delivery + bookkeeping ever went wrong.""" + d, auth, cmd = queued + assert cmd.delivered_at is None + + assert ( + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth + ).status_code + == 204 + ) + + +# --- retries ---------------------------------------------------------------- + + +@needs_db +def test_re_acking_is_allowed_and_the_last_word_wins(client, queued, db): + """The device cannot tell a lost response from a lost request, so it + retries. Refusing the second attempt would strand a command that ran.""" + d, auth, cmd = queued + + client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "failed"}, headers=auth) + db.refresh(cmd) + first = cmd.acked_at + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", + json={"status": "done", "detail": "worked on retry"}, + headers=auth, + ) + assert r.status_code == 204 + + db.refresh(cmd) + assert cmd.ack_status == "done" + assert cmd.result == "worked on retry" + assert cmd.acked_at >= first + + +@needs_db +def test_acking_does_not_put_the_command_back_in_the_queue(client, queued, db): + d, auth, cmd = queued + client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth) + client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth) + + again = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() + assert again["commands"] == [] + + +# --- scoping ---------------------------------------------------------------- + + +@needs_db +def test_another_devices_command_is_404_not_403(client, queued, db): + """Command ids are sequential. A distinct status code would confirm that + an id exists, which is the thing worth not saying.""" + d, auth, cmd = queued + intruder, intruder_auth = _make_device(db, name="intruder") + + r = client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=intruder_auth + ) + assert r.status_code == 404 + + db.refresh(cmd) + assert cmd.acked_at is None, "an intruder must not be able to close a command" + + _cleanup(db, intruder) + + +@needs_db +def test_an_unknown_command_id_is_404(client, device): + _, auth = device + assert ( + client.post( + "/api/v1/commands/999999999/ack", json={"status": "done"}, headers=auth + ).status_code + == 404 + ) + + +@needs_db +def test_ack_requires_a_bearer_token(client, queued): + d, auth, cmd = queued + assert client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}).status_code == 401 + + +@needs_db +def test_a_disabled_device_cannot_ack(client, queued, db): + d, auth, cmd = queued + d.enabled = False + db.commit() + assert ( + client.post( + f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth + ).status_code + == 403 + ) diff --git a/server/tests/test_conditions.py b/server/tests/test_conditions.py new file mode 100644 index 0000000..bdb0281 --- /dev/null +++ b/server/tests/test_conditions.py @@ -0,0 +1,361 @@ +"""POST /api/v1/heartbeat and POST /api/v1/status. + +One body, two endpoints. The tests that matter most are the ones pinning the +difference between them, because the split exists for a reason that is not +obvious from the payload. +""" + +from __future__ import annotations + +import secrets +from datetime import UTC, datetime, timedelta + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus, Firmware + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + """A live, enrolled device, removed again afterwards.""" + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="test-cam", + token_hash=hash_credential(token), + fw_version="0.1.0", + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def firmware(db): + """Create firmware rows that are removed even when the test fails. + + Teardown has to live in a fixture, not at the end of the test body: a + failing assertion skips the rest of the function, and a leftover + is_target row then picks itself as the OTA target for every later test. + """ + created: list[Firmware] = [] + + def make(version: str, *, is_target: bool = True) -> Firmware: + row = Firmware( + version=version, + file_path=f"/srv/poorbird/fw/{version}.bin", + sha256="a" * 64, + size_bytes=1148320, + is_target=is_target, + ) + db.add(row) + db.commit() + db.refresh(row) + created.append(row) + return row + + yield make + + for row in created: + existing = db.get(Firmware, row.id) + if existing is not None: + db.delete(existing) + db.commit() + + +def body(reason: str = "periodic", **over) -> dict: + b = { + "reason": reason, + "fw_version": "0.1.0", + "config_version": 8, + "power": {"awake_ms": 91204, "boot_count": 37, "wake_cause": "radar"}, + "battery": {"valid": True, "mv": 3912, "pct": 74}, + "counters": {"captured_today": 412, "delivered_today": 407, "day_index": 20716}, + "camera": {"profile": "day", "ready": True}, + "night": {"is_night": False}, + "stream": {"active": False}, + "radar": {"baud": 256000, "uart_ok": True}, + "system": {"rssi": -61, "ip": "192.168.1.88", "free_heap": 184320}, + "time_synced": True, + "device_time": "2026-09-20T14:31:07Z", + } + b.update(over) + return b + + +# --- the split between the two endpoints ------------------------------------ + + +@needs_db +def test_heartbeat_returns_the_envelope(client, device): + _, auth = device + r = client.post("/api/v1/heartbeat", json=body(), headers=auth) + + assert r.status_code == 200 + e = r.json() + assert e["server_time"] > 1_700_000_000_000 + assert "config_version" in e + assert e["commands"] == [] + + +@needs_db +def test_status_returns_204_and_no_body(client, device): + _, auth = device + r = client.post("/api/v1/status", json=body("before_sleep"), headers=auth) + + assert r.status_code == 204 + assert r.content == b"" + + +@needs_db +def test_status_does_not_hand_out_commands(client, device, db): + """The whole reason the two endpoints exist. + + The device posts status immediately before deep sleep. Delivering commands + there would mark them delivered to a device about to be unable to run them. + """ + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="capture_now")) + db.commit() + + assert client.post("/api/v1/status", json=body("before_sleep"), headers=auth).status_code == 204 + + cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) + db.refresh(cmd) + assert cmd.delivered_at is None, "status must not claim commands" + + # ... but the next heartbeat still gets it. + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["capture_now"] + + +# --- commands --------------------------------------------------------------- + + +@needs_db +def test_heartbeat_claims_commands_and_marks_them_delivered(client, device, db): + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="reboot")) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["reboot"] + + cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) + db.refresh(cmd) + assert cmd.delivered_at is not None + + # Not handed out twice. + again = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert again["commands"] == [] + + +@needs_db +def test_expired_commands_are_not_delivered_but_are_kept(client, device, db): + """Kept so the admin UI can show that a command timed out.""" + d, auth = device + db.add( + DeviceCommand( + device_id=d.id, + type="capture_now", + expires_at=datetime.now(UTC) - timedelta(minutes=1), + ) + ) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["commands"] == [] + assert db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) is not None + + +@needs_db +def test_commands_come_back_in_creation_order(client, device, db): + d, auth = device + for t in ("wake_and_hold", "capture_now", "reboot"): + db.add(DeviceCommand(device_id=d.id, type=t)) + db.commit() # distinct created_at + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["wake_and_hold", "capture_now", "reboot"] + + +@needs_db +def test_one_devices_commands_do_not_leak_to_another(client, device, db): + d, auth = device + other = Device(device_uid=secrets.token_hex(6), name="other") + db.add(other) + db.commit() + db.add(DeviceCommand(device_id=other.id, type="reboot")) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["commands"] == [] + + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == other.id)) + db.delete(db.get(Device, other.id)) + db.commit() + + +# --- firmware target -------------------------------------------------------- + + +@needs_db +def test_firmware_key_is_absent_when_the_device_is_on_target(client, device, firmware): + """Absent, not null: present-and-different is itself the flash instruction.""" + d, auth = device + firmware("0.1.0") # same version the device reports + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert "firmware" not in e + + +@needs_db +def test_a_different_target_is_offered_with_a_relative_url(client, device, firmware): + """ota_mgr.cpp appends a non-http url to the API base, which already ends + in /api/v1 -- so this must not carry the prefix itself.""" + d, auth = device + firmware("0.2.0") + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["firmware"]["version"] == "0.2.0" + assert e["firmware"]["url"] == "/firmware/0.2.0.bin" + assert not e["firmware"]["url"].startswith("/api/v1") + assert e["firmware"]["size"] == 1148320 + + +# --- telemetry recording ---------------------------------------------------- + + +@needs_db +def test_a_row_is_appended_per_report(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + client.post("/api/v1/status", json=body("after_event"), headers=auth) + + rows = db.scalars( + select(DeviceStatus).where(DeviceStatus.device_id == d.id).order_by(DeviceStatus.at) + ).all() + assert [r.reason for r in rows] == ["periodic", "after_event"] + assert rows[0].battery_mv == 3912 + assert rows[0].rssi == -61 + assert rows[0].day_index == 20716 + assert rows[0].free_heap == 184320 + + +@needs_db +def test_unknown_fields_survive_in_raw(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(quantum_flux=42), headers=auth) + + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.raw["quantum_flux"] == 42 + + +@needs_db +def test_last_known_conditions_are_denormalised_onto_the_device(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + + db.refresh(d) + assert d.battery_mv == 3912 + assert d.battery_pct == 74 + assert d.battery_valid is True + assert d.rssi == -61 + assert d.last_seen_at is not None + + +@needs_db +def test_a_field_the_device_omits_does_not_erase_the_last_good_value(client, device, db): + """None means 'not sent', not 'zero'.""" + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + client.post("/api/v1/heartbeat", json=body(battery={}, system={}), headers=auth) + + db.refresh(d) + assert d.battery_mv == 3912 + assert d.rssi == -61 + + +@needs_db +def test_battery_valid_false_is_recorded_as_false(client, device, db): + """false means NOT MEASURED. It must reach the UI as false, not as missing.""" + d, auth = device + client.post("/api/v1/heartbeat", json=body(battery={"valid": False}), headers=auth) + + db.refresh(d) + assert d.battery_valid is False + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.battery_valid is False + + +@needs_db +def test_the_device_is_marked_asleep_when_it_says_it_is_going_quiet(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + db.refresh(d) + assert d.awake is True + + client.post("/api/v1/status", json=body("before_night_sleep"), headers=auth) + db.refresh(d) + assert d.awake is False + + +@needs_db +def test_the_devices_reported_config_version_does_not_overwrite_the_servers(client, device, db): + """The difference between the two is exactly what tells the device to + GET /config. Letting the report win would erase the instruction.""" + d, auth = device + d.config_version = 9 + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(config_version=3), headers=auth).json() + + db.refresh(d) + assert d.config_version == 9 + assert e["config_version"] == 9 + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.config_version == 3 # what the device said, kept as telemetry + + +# --- auth ------------------------------------------------------------------- + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_both_endpoints_require_a_bearer_token(client, path): + assert client.post(path, json=body()).status_code == 401 + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_a_disabled_device_is_refused(client, device, db, path): + d, auth = device + d.enabled = False + db.commit() + assert client.post(path, json=body(), headers=auth).status_code == 403 + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_an_unknown_reason_is_422(client, device, path): + _, auth = device + assert client.post(path, json=body("whenever"), headers=auth).status_code == 422 diff --git a/server/tests/test_config.py b/server/tests/test_config.py index 14192a2..005abf4 100644 --- a/server/tests/test_config.py +++ b/server/tests/test_config.py @@ -1,5 +1,9 @@ from __future__ import annotations +import pytest +from conftest import needs_db +from pydantic import ValidationError + from poorbird.config import Settings @@ -18,8 +22,9 @@ def test_every_setting_reads_from_the_environment(monkeypatch): assert s.enroll_secret_is_set -def test_database_url_is_tcp_not_a_unix_socket(): +def test_database_url_is_tcp_not_a_unix_socket(monkeypatch): """A Unix socket is the one genuinely container-hostile choice.""" + monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@127.0.0.1:5432/poorbird") s = Settings(_env_file=None) assert "@" in s.database_url and ":" in s.database_url.rpartition("@")[2] assert "/var/run/postgresql" not in s.database_url @@ -28,3 +33,98 @@ def test_database_url_is_tcp_not_a_unix_socket(): def test_enroll_secret_is_not_leaked_by_repr(): s = Settings(_env_file=None, enroll_secret="hunter2") assert "hunter2" not in repr(s) + + +# --- SEC-006: no credentials baked into code -------------------------------- + + +def test_no_database_credentials_are_baked_in(monkeypatch): + """A default URL in code is a password in code, however harmless it looks.""" + monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False) + s = Settings(_env_file=None) + assert s.database_url == "" + assert not s.database_url_is_set + + +def test_unset_database_url_fails_with_a_readable_message(monkeypatch): + """Graceful, not a SQLAlchemy URL parse error from three frames down.""" + monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False) + monkeypatch.setattr("poorbird.config.get_settings", lambda: Settings(_env_file=None)) + + import importlib + import sys + + sys.modules.pop("poorbird.db", None) + with pytest.raises(RuntimeError, match="POORBIRD_DATABASE_URL is not set"): + importlib.import_module("poorbird.db") + sys.modules.pop("poorbird.db", None) + + +def test_placeholder_database_url_is_rejected(monkeypatch): + monkeypatch.setenv( + "POORBIRD_DATABASE_URL", "postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird" + ) + with pytest.raises(ValidationError, match="placeholder"): + Settings(_env_file=None) + + +# --- SEC-001: enroll secret comes from the environment only ----------------- + + +def test_enroll_secret_has_no_value_baked_in(monkeypatch): + monkeypatch.delenv("POORBIRD_ENROLL_SECRET", raising=False) + s = Settings(_env_file=None) + assert s.enroll_secret.get_secret_value() == "" + assert not s.enroll_secret_is_set + + +def test_placeholder_enroll_secret_is_rejected(monkeypatch): + monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "CHANGE_ME") + with pytest.raises(ValidationError, match="placeholder"): + Settings(_env_file=None) + + +# --- REVIEW section 7: pool sizing ----------------------------------------- + + +@needs_db +def test_pool_settings_reach_the_engine(monkeypatch): + """A setting nothing reads is worse than no setting at all. + + worker_batch_size sat in Settings for a whole phase looking like it tuned + something while the worker claimed one job at a time regardless. So this + asserts against the pool an engine really built, rather than comparing a + literal with itself. + + The values have to differ from SQLAlchemy's own defaults (pool_size 5, + max_overflow 10) or the test cannot tell a wired setting from an ignored + one -- which is the entire failure it is here to catch. Hence 17 and 7, + and hence re-importing db.py rather than reading the module-level engine, + whose numbers happen to coincide with the library's. + """ + import importlib + import sys + + from poorbird.config import get_settings + + monkeypatch.setattr( + "poorbird.config.get_settings", + lambda: Settings( + _env_file=None, + database_url=get_settings().database_url, + db_pool_size=17, + db_max_overflow=7, + ), + ) + + sys.modules.pop("poorbird.db", None) + try: + db = importlib.import_module("poorbird.db") + assert db.engine.pool.size() == 17 + # No public accessor for this one, and leaving half the connection + # ceiling unverified is the worse trade. + assert db.engine.pool._max_overflow == 7 + finally: + # Drop the throwaway engine and let the next importer rebuild the real + # one. It never opened a connection: the pool fills lazily. + sys.modules.pop("poorbird.db", None) diff --git a/server/tests/test_device_auth.py b/server/tests/test_device_auth.py new file mode 100644 index 0000000..c211473 --- /dev/null +++ b/server/tests/test_device_auth.py @@ -0,0 +1,192 @@ +"""Device authentication plumbing (REVIEW SEC-002). + +The cases that matter most here are the two REVIEW.AI.md's reference code got +wrong: the token handed to the device must be the one the server can verify, +and re-enrollment must accept the per-device secret. +""" + +from __future__ import annotations + +import pytest +from conftest import needs_db +from fastapi import HTTPException + +from poorbird.api.deps import ( + enroll_secret_accepted, + hash_credential, + new_credential, + require_enroll_secret_configured, + verify_device_token, +) +from poorbird.config import Settings +from poorbird.models.devices import Device + +# --- credential shape ------------------------------------------------------- + + +def test_credential_is_64_hex_chars(): + """The firmware stores these in char[65]; 64 + NUL fits exactly. + + A longer credential would be silently truncated on the device and every + request after enrollment would 401. + """ + c = new_credential() + assert len(c) == 64 + assert all(ch in "0123456789abcdef" for ch in c) + assert len(c) + 1 <= 65 # app_config.h: char device_token[65] + + +def test_credentials_do_not_repeat(): + assert len({new_credential() for _ in range(100)}) == 100 + + +def test_hash_is_stable_and_not_the_input(): + c = new_credential() + assert hash_credential(c) == hash_credential(c) + assert hash_credential(c) != c + assert len(hash_credential(c)) == 64 + + +# --- the bug in REVIEW.AI.md's reference code ------------------------------- + + +def test_token_given_to_the_device_verifies_against_what_is_stored(): + """Store the hash, hand back the plaintext. + + REVIEW.AI.md's /enroll example returns ``device.token_hash`` to the device. + The device would then present the hash, the server would hash it again, and + the comparison could never match. Guard against reintroducing that. + """ + token = new_credential() + stored = hash_credential(token) + + assert hash_credential(token) == stored # what the device presents resolves + assert hash_credential(stored) != stored # handing back the hash would not + + +# --- enrollment secret ------------------------------------------------------ + + +def _settings(secret: str = "") -> Settings: + return Settings(_env_file=None, enroll_secret=secret) + + +def test_shared_bootstrap_secret_is_accepted(): + assert enroll_secret_accepted("s3cret", _settings("s3cret"), None) + + +def test_wrong_secret_is_rejected(): + assert not enroll_secret_accepted("nope", _settings("s3cret"), None) + + +def test_missing_secret_is_rejected(): + assert not enroll_secret_accepted(None, _settings("s3cret"), None) + assert not enroll_secret_accepted("", _settings("s3cret"), None) + + +def test_unset_server_secret_never_accepts_anything(): + """An unconfigured server must not treat an empty presented secret as a match.""" + assert not enroll_secret_accepted("", _settings(""), None) + assert not enroll_secret_accepted("anything", _settings(""), None) + + +def test_per_device_reenroll_secret_is_accepted(): + """The firmware swaps the shared secret for this one after first enrollment. + + Accepting only the shared secret would lock out every device that had + already enrolled -- the exact failure re-enrollment exists to prevent. + """ + per_device = new_credential() + device = Device(device_uid="a0b7651f2c3d", name="cam-1") + device.reenroll_secret_hash = hash_credential(per_device) + + assert enroll_secret_accepted(per_device, _settings("shared"), device) + # and the shared one still works as the last-resort path + assert enroll_secret_accepted("shared", _settings("shared"), device) + assert not enroll_secret_accepted("neither", _settings("shared"), device) + + +def test_one_devices_secret_cannot_enroll_another(): + mine = new_credential() + other = Device(device_uid="ffffffffffff", name="cam-2") + other.reenroll_secret_hash = hash_credential(new_credential()) + + assert not enroll_secret_accepted(mine, _settings("shared"), other) + + +def test_unconfigured_server_returns_503_not_500(): + """A 4xx would make the firmware clear a perfectly good token.""" + with pytest.raises(HTTPException) as exc: + require_enroll_secret_configured(_settings("")) + assert exc.value.status_code == 503 + + require_enroll_secret_configured(_settings("set")) # does not raise + + +# --- bearer token ----------------------------------------------------------- + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + session.rollback() + + +@pytest.fixture +def enrolled(db): + token = new_credential() + device = Device( + device_uid="dead" + new_credential()[:8], + name="test-cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(device) + db.flush() # rolled back by the db fixture; nothing is committed + yield device, token + + +@needs_db +def test_valid_bearer_token_resolves_to_its_device(db, enrolled): + device, token = enrolled + assert verify_device_token(db=db, authorization=f"Bearer {token}").id == device.id + + +@needs_db +@pytest.mark.parametrize( + "header", + [None, "", "Bearer", "Bearer ", "Basic abc", "abc", "Bearer wrong-token"], +) +def test_bad_authorization_headers_are_401(db, enrolled, header): + """401 specifically: the firmware reads it as 'clear token and re-enroll'.""" + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=header) + assert exc.value.status_code == 401 + + +@needs_db +def test_bearer_scheme_is_case_insensitive(db, enrolled): + _, token = enrolled + assert verify_device_token(db=db, authorization=f"bearer {token}") is not None + + +@needs_db +def test_disabled_device_is_403_not_401(db, enrolled): + """403 stops it re-enrolling in a loop; 401 would invite exactly that.""" + device, token = enrolled + device.enabled = False + db.flush() + + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=f"Bearer {token}") + assert exc.value.status_code == 403 + + +@needs_db +def test_401_carries_www_authenticate(db, enrolled): + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=None) + assert exc.value.headers.get("WWW-Authenticate") == "Bearer" diff --git a/server/tests/test_device_config.py b/server/tests/test_device_config.py new file mode 100644 index 0000000..47d30b7 --- /dev/null +++ b/server/tests/test_device_config.py @@ -0,0 +1,171 @@ +"""GET /api/v1/config. + +The contract is a merge contract, not a schema contract: the device applies +only the keys that are present and clamps what it does not like, so what +matters here is which keys appear and which value wins. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="poorbird-cam-1", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.delete(db.get(Device, d.id)) + db.commit() + + +@needs_db +def test_config_version_is_always_present(client, device): + """It is the only value the device compares, so it can never be missing.""" + d, auth = device + r = client.get("/api/v1/config", headers=auth) + + assert r.status_code == 200 + assert r.json()["config_version"] == d.config_version + + +@needs_db +def test_an_empty_config_still_returns_the_column_backed_keys(client, device, db): + """A device that has never been configured must still learn its name and + its intervals, which live in columns rather than in the JSONB.""" + d, auth = device + assert d.config == {} + + body = client.get("/api/v1/config", headers=auth).json() + assert body["device_name"] == "poorbird-cam-1" + assert body["heartbeat_interval_s"] == d.heartbeat_interval_s + assert body["status_interval_s"] == d.status_interval_s + + +@needs_db +def test_the_stored_document_is_returned(client, device, db): + d, auth = device + d.config = { + "frame_size": "SVGA", + "jpeg_quality": 12, + "night_behaviour": 2, + "cam_day": {"ae_level": 1, "gainceiling": 2}, + } + db.commit() + + body = client.get("/api/v1/config", headers=auth).json() + assert body["frame_size"] == "SVGA" + assert body["jpeg_quality"] == 12 + assert body["cam_day"] == {"ae_level": 1, "gainceiling": 2} + + +@needs_db +def test_a_column_wins_over_a_stale_copy_in_the_json(client, device, db): + """The column is the modelled source of truth. A leftover key in the JSONB + must not shadow it, or changing the column would not reach the device.""" + d, auth = device + d.config = {"heartbeat_interval_s": 30, "device_name": "stale-name"} + d.heartbeat_interval_s = 600 + db.commit() + + body = client.get("/api/v1/config", headers=auth).json() + assert body["heartbeat_interval_s"] == 600 + assert body["device_name"] == "poorbird-cam-1" + + +@needs_db +def test_an_operator_rename_reaches_the_device_through_config(client, device, db): + """Closes the loop left open at enrollment. + + Enrollment refuses to let a device overwrite a rename made in the admin + UI. This is the path by which that rename actually gets to the camera: + configApplyJson merges device_name like any other key (app_config.cpp:307). + """ + d, auth = device + d.name = "Feeder by the shed" + db.commit() + + assert client.get("/api/v1/config", headers=auth).json()["device_name"] == "Feeder by the shed" + + +@needs_db +def test_keys_the_server_does_not_know_are_passed_through(client, device, db): + """The firmware gains tunables faster than the server learns them, and the + device ignores what it does not recognise. Dropping them would make the + admin UI unable to push a setting until the server caught up.""" + d, auth = device + d.config = {"some_future_tunable": 7} + db.commit() + + assert client.get("/api/v1/config", headers=auth).json()["some_future_tunable"] == 7 + + +@needs_db +def test_the_read_has_no_side_effects(client, device, db): + """A GET must not record liveness; /heartbeat is what does that.""" + d, auth = device + assert d.last_seen_at is None + + client.get("/api/v1/config", headers=auth) + + db.refresh(d) + assert d.last_seen_at is None + + +@needs_db +def test_config_requires_a_bearer_token(client): + assert client.get("/api/v1/config").status_code == 401 + + +@needs_db +def test_a_disabled_device_is_refused(client, device, db): + d, auth = device + d.enabled = False + db.commit() + assert client.get("/api/v1/config", headers=auth).status_code == 403 + + +@needs_db +def test_one_device_cannot_read_anothers_config(client, device, db): + """The token identifies the device; there is no device_id parameter to + tamper with, and this pins that there never is one.""" + d, auth = device + other_token = new_credential() + other = Device( + device_uid=secrets.token_hex(6), + name="other-cam", + token_hash=hash_credential(other_token), + enabled=True, + ) + db.add(other) + db.commit() + + body = client.get("/api/v1/config", headers={"Authorization": f"Bearer {other_token}"}).json() + assert body["device_name"] == "other-cam" + + db.delete(db.get(Device, other.id)) + db.commit() diff --git a/server/tests/test_enroll.py b/server/tests/test_enroll.py new file mode 100644 index 0000000..2050799 --- /dev/null +++ b/server/tests/test_enroll.py @@ -0,0 +1,264 @@ +"""POST /api/v1/enroll (firmware/API.md, Authentication). + +The server has no enroll secret configured by default, so every test that +expects to get past the door overrides it. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, verify_device_token +from poorbird.config import Settings, get_settings +from poorbird.models.devices import Device + +SHARED = "test-bootstrap-secret" + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def uid(): + """A device_uid no other test will collide with.""" + return secrets.token_hex(6) + + +@pytest.fixture +def api(client, db): + """`client`, with an enroll secret configured and created rows cleaned up.""" + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, enroll_secret=SHARED + ) + created: list[str] = [] + + class Api: + def enroll(self, uid, secret=SHARED, **over): + created.append(uid) + body = { + "device_uid": uid, + "device_name": "poorbird-cam-1", + "hw_revision": "xiao-esp32s3-sense-ld2410", + "fw_version": "0.1.0", + "mac": "A0:B7:65:1F:2C:3D", + } + body.update(over) + headers = {"X-Enroll-Secret": secret} if secret is not None else {} + return client.post("/api/v1/enroll", json=body, headers=headers) + + def unconfigured(self): + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, enroll_secret="" + ) + + yield Api() + + client.app.dependency_overrides.clear() + for u in created: + for d in db.scalars(select(Device).where(Device.device_uid == u)): + db.delete(d) + db.commit() + + +# --- first enrollment ------------------------------------------------------- + + +@needs_db +def test_first_enrollment_returns_201_and_the_documented_shape(api, uid): + r = api.enroll(uid) + assert r.status_code == 201 + + body = r.json() + assert set(body) == { + "token", + "device_id", + "reenroll_secret", + "server_time", + "config_version", + } + assert len(body["token"]) == 64 + assert len(body["reenroll_secret"]) == 64 + assert body["token"] != body["reenroll_secret"] + assert isinstance(body["device_id"], int) + assert body["server_time"] > 1_700_000_000_000 # epoch ms, not seconds + assert body["config_version"] >= 1 + + +@needs_db +def test_the_issued_token_actually_authenticates(api, uid, db): + """The regression that REVIEW.AI.md's reference code would have shipped. + + Its /enroll hands back devices.token_hash. The device would present that, + the server would hash it again, and every request after enrollment would + 401. This is the round trip that proves it does not. + """ + token = api.enroll(uid).json()["token"] + + device = verify_device_token(db=db, authorization=f"Bearer {token}") + assert device.device_uid == uid + + +@needs_db +def test_only_hashes_are_persisted(api, uid, db): + body = api.enroll(uid).json() + device = db.scalar(select(Device).where(Device.device_uid == uid)) + + assert device.token_hash == hash_credential(body["token"]) + assert device.reenroll_secret_hash == hash_credential(body["reenroll_secret"]) + # The plaintext must appear nowhere on the row. + stored = " ".join(str(v) for v in device.__dict__.values()) + assert body["token"] not in stored + assert body["reenroll_secret"] not in stored + + +# --- re-enrollment ---------------------------------------------------------- + + +@needs_db +def test_re_enrollment_reuses_the_row_and_rotates_the_token(api, uid, db): + """API.md: a known device_uid returns the existing device, not a duplicate. + + Expected on every token rotation and after any database restore. + """ + first = api.enroll(uid).json() + second = api.enroll(uid).json() + + assert second["device_id"] == first["device_id"] + assert second["token"] != first["token"] + assert db.scalars(select(Device).where(Device.device_uid == uid)).all().__len__() == 1 + + +@needs_db +def test_the_old_token_stops_working_after_rotation(api, uid, db): + from fastapi import HTTPException + + old = api.enroll(uid).json()["token"] + new = api.enroll(uid).json()["token"] + + assert verify_device_token(db=db, authorization=f"Bearer {new}") is not None + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=f"Bearer {old}") + assert exc.value.status_code == 401 + + +@needs_db +def test_a_device_can_re_enroll_with_its_own_secret(api, uid): + """The firmware swaps the shared secret for this one after first enrollment, + so from then on it is the only credential it has.""" + per_device = api.enroll(uid).json()["reenroll_secret"] + + again = api.enroll(uid, secret=per_device) + assert again.status_code == 201 + # and it is rotated in turn, so a captured secret is good for one use + assert again.json()["reenroll_secret"] != per_device + + +@needs_db +def test_one_devices_secret_cannot_enroll_a_different_uid(api, uid): + mine = api.enroll(uid).json()["reenroll_secret"] + assert api.enroll(secrets.token_hex(6), secret=mine).status_code == 401 + + +@needs_db +def test_hardware_facts_follow_the_device(api, uid, db): + api.enroll(uid) + api.enroll(uid, fw_version="0.2.0", hw_revision="rev-b") + + device = db.scalar(select(Device).where(Device.device_uid == uid)) + db.refresh(device) + assert device.fw_version == "0.2.0" + assert device.hw_revision == "rev-b" + + +@needs_db +def test_re_enrollment_does_not_undo_an_operator_rename(api, uid, db): + """The name is an operator-facing label after first enrollment. + + A camera that re-enrolls on every token rotation must not keep reverting a + rename made in the admin UI. + """ + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.name = "Feeder by the shed" + db.commit() + + api.enroll(uid, device_name="poorbird-cam-1") + + db.refresh(device) + assert device.name == "Feeder by the shed" + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +@pytest.mark.parametrize("secret", ["wrong", "", None]) +def test_bad_or_missing_secret_is_401(api, uid, secret): + assert api.enroll(uid, secret=secret).status_code == 401 + + +@needs_db +def test_unconfigured_server_is_503_not_401(api, uid): + """A 4xx would tell the camera it is unwelcome and make it clear its token. + The server being misconfigured is not the device's fault.""" + api.unconfigured() + assert api.enroll(uid).status_code == 503 + + +@needs_db +def test_a_disabled_device_cannot_re_enroll_its_way_back_in(api, uid, db): + """Otherwise disabling a device in the admin UI would mean nothing.""" + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.enabled = False + db.commit() + + assert api.enroll(uid).status_code == 403 + + +@needs_db +def test_a_disabled_devices_token_is_not_rotated_by_the_refusal(api, uid, db): + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.enabled = False + db.commit() + before = device.token_hash + + api.enroll(uid) + + db.refresh(device) + assert device.token_hash == before + + +@needs_db +@pytest.mark.parametrize( + "bad", + [ + {"device_uid": "not-hex!"}, + {"device_uid": ""}, + {"device_name": ""}, + {"device_name": "x" * 65}, + ], +) +def test_malformed_bodies_are_422(api, uid, bad): + assert api.enroll(uid, **bad).status_code == 422 + + +@needs_db +def test_the_legacy_name_field_is_not_accepted(api, uid, client): + """REVIEW.AI.md's model calls it `name`; the firmware sends `device_name`.""" + r = client.post( + "/api/v1/enroll", + json={"device_uid": uid, "name": "cam-1"}, + headers={"X-Enroll-Secret": SHARED}, + ) + assert r.status_code == 422 diff --git a/server/tests/test_firmware.py b/server/tests/test_firmware.py new file mode 100644 index 0000000..9a1cdd3 --- /dev/null +++ b/server/tests/test_firmware.py @@ -0,0 +1,224 @@ +"""GET /api/v1/firmware/{version}.bin. + +The device checks the response before it erases a partition, so the tests +here are mostly about the headers being exactly right rather than about the +bytes. +""" + +from __future__ import annotations + +import hashlib +import secrets +from pathlib import Path + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.config import get_settings +from poorbird.models.devices import Device, Firmware + +IMAGE = b"\xe9" + secrets.token_bytes(4095) # stands in for an .bin, 4096 bytes + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def make_image(db): + """Build firmware rows with real files, and clean both up unconditionally. + + Teardown belongs here rather than at the end of a test body: a failing + assertion skips the rest of the function, and a leftover is_target row + then picks itself as the OTA target for every later test. That is exactly + how a deliberate mutation once poisoned two unrelated suites. + """ + created: list[tuple[Firmware, Path]] = [] + folder = get_settings().state_dir / "firmware" + folder.mkdir(parents=True, exist_ok=True) + + def make(version: str | None = None, *, is_target: bool = False): + version = version or f"9.{secrets.randbelow(100000)}.0" + path = folder / f"{version}.bin" + path.write_bytes(IMAGE) + row = Firmware( + version=version, + file_path=str(path), + sha256=hashlib.sha256(IMAGE).hexdigest(), + size_bytes=len(IMAGE), + is_target=is_target, + ) + db.add(row) + db.commit() + db.refresh(row) + created.append((row, path)) + return row, path + + yield make + + for row, path in created: + path.unlink(missing_ok=True) + existing = db.get(Firmware, row.id) + if existing is not None: + db.delete(existing) + db.commit() + + +@pytest.fixture +def image(make_image): + """One firmware row with a real file behind it.""" + return make_image() + + +# --- what the device needs -------------------------------------------------- + + +@needs_db +def test_the_image_comes_back_intact(client, device, image): + _, auth = device + row, _ = image + + r = client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth) + + assert r.status_code == 200 + assert r.content == IMAGE + assert hashlib.sha256(r.content).hexdigest() == row.sha256 + + +@needs_db +def test_content_length_is_present_and_exact(client, device, image): + """The device refuses a chunked response: it size-checks against the + manifest before erasing a partition (ota_mgr.cpp:111-120).""" + _, auth = device + row, _ = image + + r = client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth) + + assert "content-length" in r.headers + assert int(r.headers["content-length"]) == len(IMAGE) + assert int(r.headers["content-length"]) == row.size_bytes + assert "transfer-encoding" not in r.headers + + +@needs_db +def test_the_response_is_not_compressed(client, device, image): + """Compression would change Content-Length and the device would refuse.""" + _, auth = device + row, _ = image + + r = client.get( + f"/api/v1/firmware/{row.version}.bin", + headers={**auth, "Accept-Encoding": "gzip, deflate, br"}, + ) + + assert r.headers.get("content-encoding") in (None, "identity") + assert int(r.headers["content-length"]) == len(IMAGE) + + +@needs_db +def test_a_dotted_version_is_parsed_out_of_the_path(client, device, make_image): + """Versions are semver-ish, so the path has several dots before .bin.""" + _, auth = device + make_image("1.2.3-rc.1") + + r = client.get("/api/v1/firmware/1.2.3-rc.1.bin", headers=auth) + assert r.status_code == 200 + assert r.content == IMAGE + + +# --- the envelope names it, this serves it ---------------------------------- + + +@needs_db +def test_the_url_the_envelope_advertises_actually_resolves(client, device, db, image): + """End to end: heartbeat names a target, that URL downloads it. + + The envelope sends a relative URL because ota_mgr.cpp appends it to the + API base, which already ends in /api/v1. This proves the two halves agree. + """ + d, auth = device + row, _ = image + row.is_target = True + d.fw_version = "0.0.1" # not the target, so the key is present + db.commit() + + envelope = client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).json() + advertised = envelope["firmware"]["url"] + assert advertised == f"/firmware/{row.version}.bin" + + # What the device builds: apiBaseUrl() + url, where the base ends /api/v1. + r = client.get(f"/api/v1{advertised}", headers=auth) + assert r.status_code == 200 + assert int(r.headers["content-length"]) == envelope["firmware"]["size"] + assert hashlib.sha256(r.content).hexdigest() == envelope["firmware"]["sha256"] + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +def test_an_unknown_version_is_404(client, device): + _, auth = device + assert client.get("/api/v1/firmware/0.0.0-nope.bin", headers=auth).status_code == 404 + + +@needs_db +def test_a_row_whose_file_is_missing_is_503_not_404(client, device, image): + """The firmware exists as far as the operator is concerned; this is a + server fault worth shouting about, not a missing resource.""" + _, auth = device + row, path = image + path.unlink() + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 503 + + +@needs_db +def test_a_size_mismatch_is_caught_here_rather_than_on_the_device(client, device, db, image): + """The device would abort on the Content-Length check anyway. Failing + here turns a confusing remote abort into one clear server log line.""" + _, auth = device + row, path = image + path.write_bytes(IMAGE + b"extra") + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 503 + + +@needs_db +def test_firmware_requires_a_bearer_token(client, image): + row, _ = image + assert client.get(f"/api/v1/firmware/{row.version}.bin").status_code == 401 + + +@needs_db +def test_a_disabled_device_cannot_download(client, device, db, image): + d, auth = device + row, _ = image + d.enabled = False + db.commit() + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 403 diff --git a/server/tests/test_ingest.py b/server/tests/test_ingest.py new file mode 100644 index 0000000..48183df --- /dev/null +++ b/server/tests/test_ingest.py @@ -0,0 +1,403 @@ +"""POST /api/v1/ingest -- raw JPEG body, metadata in headers.""" + +from __future__ import annotations + +import hashlib +import io +import secrets +import struct +from pathlib import Path + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.config import get_settings +from poorbird.images import jpeg_dimensions, looks_like_jpeg +from poorbird.models.captures import Capture +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus +from poorbird.models.ops import Job + + +def make_jpeg(width: int = 800, height: int = 600, noise: bytes = b"") -> bytes: + """A byte string with a valid SOI and SOF0, enough to be parsed as a JPEG. + + Not a decodable image: nothing on the ingest path decodes one, which is + the point of parsing the header rather than pulling in Pillow. + """ + out = io.BytesIO() + out.write(b"\xff\xd8\xff") # SOI + start of the next marker + out.write(b"\xe0") # APP0 + out.write(struct.pack(">H", 16)) + out.write(b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00") + out.write(b"\xff\xc0") # SOF0 + out.write(struct.pack(">H", 17)) + out.write(b"\x08") # precision + out.write(struct.pack(">HH", height, width)) + out.write(b"\x03\x01\x11\x00\x02\x11\x01\x03\x11\x01") + out.write(b"\xff\xd9") # EOI + out.write(noise) # makes the sha256 differ between frames + return out.getvalue() + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def make_device(db): + """Devices, their captures, their frames and their jobs -- all cleaned up. + + Every device a test makes goes through here, so a test that needs a + second one does not have to hand-roll teardown and forget half of it. + """ + created: list[Device] = [] + + def make(name: str = "cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + created.append(d) + return d, {"Authorization": f"Bearer {token}"} + + yield make + + root = get_settings().image_root + for d in created: + capture_ids = [] + for cap in db.scalars(select(Capture).where(Capture.device_id == d.id)): + (root / cap.path).unlink(missing_ok=True) + capture_ids.append(str(cap.id)) + + # Ingest enqueues a thumbnail job per capture. Leaving those behind + # breaks test_queue.py, which claims from the same shared queue. + # Matched on payload so this never touches a job it did not create. + if capture_ids: + db.query(Job).filter( + Job.kind == "thumbnail", + Job.payload["capture_id"].astext.in_(capture_ids), + ).delete(synchronize_session=False) + + db.execute(Capture.__table__.delete().where(Capture.device_id == d.id)) + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + existing = db.get(Device, d.id) + if existing is not None: + db.delete(existing) + db.commit() + + +@pytest.fixture +def device(make_device): + return make_device() + + +def post(client, auth, data=None, **headers): + h = {"Content-Type": "image/jpeg", **auth} + h.update({k.replace("_", "-"): str(v) for k, v in headers.items()}) + return client.post( + "/api/v1/ingest", content=data if data is not None else make_jpeg(), headers=h + ) + + +# --- the header parser, in isolation ---------------------------------------- + + +def test_jpeg_dimensions_reads_the_header(): + assert jpeg_dimensions(make_jpeg(1600, 1200)) == (1600, 1200) + assert jpeg_dimensions(make_jpeg(320, 240)) == (320, 240) + + +def test_jpeg_dimensions_gives_up_quietly_on_rubbish(): + """None is not an error: a frame we cannot measure is still worth keeping.""" + assert jpeg_dimensions(b"\xff\xd8\xff") is None + assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x10" + b"\x00" * 14) is None + assert jpeg_dimensions(b"") is None + + +def test_jpeg_dimensions_terminates_on_hostile_input(): + """A zero-length segment must not loop forever.""" + assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x00" + b"\x41" * 100) is None + assert jpeg_dimensions(b"\xff\xd8" + b"\xff" * 5000) is None + + +def test_magic_bytes_are_what_decide_it_is_a_jpeg(): + assert looks_like_jpeg(make_jpeg()) + assert not looks_like_jpeg(b"GIF89a") + assert not looks_like_jpeg(b"") + + +# --- the happy path --------------------------------------------------------- + + +@needs_db +def test_a_frame_is_stored_and_the_envelope_comes_back(client, device, db): + d, auth = device + r = post(client, auth, X_Trigger="radar", X_Burst_Id="a0b765-3-91204", X_Burst_Index=0) + + assert r.status_code == 201 + envelope = r.json() + assert envelope["capture_id"] + assert envelope["server_time"] > 1_700_000_000_000 + assert envelope["commands"] == [] + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert str(cap.id) == envelope["capture_id"] + assert cap.trigger == "radar" + assert cap.burst_id == "a0b765-3-91204" + assert cap.width == 800 and cap.height == 600 + + +@needs_db +def test_the_bytes_land_on_disk_under_a_dated_path(client, device, db): + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + assert post(client, auth, data=body).status_code == 201 + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + # Relative to the configured root, dated by received_at (SPEC 3.3). + assert cap.path == f"{cap.received_at:%Y/%m/%d}/{cap.id}.jpg" + assert not Path(cap.path).is_absolute() + + on_disk = get_settings().image_root / cap.path + assert on_disk.is_file() + assert on_disk.read_bytes() == body + assert cap.bytes == len(body) + assert cap.sha256 == hashlib.sha256(body).hexdigest() + + +@needs_db +def test_no_part_file_is_left_behind(client, device, db): + d, auth = device + post(client, auth) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + folder = (get_settings().image_root / cap.path).parent + assert not list(folder.glob(".*.part")) + + +@needs_db +def test_ingest_delivers_commands_like_heartbeat_does(client, device, db): + """Same envelope on purpose: a capture that was going to happen anyway + also drains the queue at no extra cost (SPEC 4.1).""" + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="capture_now")) + db.commit() + + envelope = post(client, auth).json() + assert [c["type"] for c in envelope["commands"]] == ["capture_now"] + + +# --- the clock --------------------------------------------------------------- + + +@needs_db +def test_captured_at_zero_means_unsynced_not_1970(client, device, db): + """Storing an epoch date would bury the frame at the bottom of every + chronological view forever.""" + d, auth = device + post(client, auth, X_Captured_At=0) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.captured_at_device is None + assert cap.received_at is not None # server time stays authoritative + + +@needs_db +def test_a_synced_device_clock_is_recorded(client, device, db): + d, auth = device + post(client, auth, X_Captured_At=1758376267123) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.captured_at_device is not None + assert cap.captured_at_device.year == 2025 or cap.captured_at_device.year == 2026 + + +@needs_db +def test_received_at_is_server_time_regardless(client, device, db): + """SPEC C7. Even a device claiming to be in 1998.""" + d, auth = device + post(client, auth, X_Captured_At=915148800000) # 1999 + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.received_at.year >= 2026 + assert cap.path.startswith(f"{cap.received_at:%Y}") + + +# --- metadata --------------------------------------------------------------- + + +@needs_db +def test_pre_trigger_is_recorded(client, device, db): + """1 means the frame predates the trigger, out of the PSRAM ring -- often + the good one, because the bird is still arriving.""" + d, auth = device + post(client, auth, X_Pre_Trigger=1) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.pre_trigger is True + + +@needs_db +def test_radar_and_signal_metadata_are_recorded(client, device, db): + d, auth = device + post( + client, + auth, + X_Radar_State=2, + X_Radar_Distance_Cm=180, + X_Radar_Energy=77, + X_Frame_Seq=42, + X_Rssi=-61, + ) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert (cap.radar_state, cap.radar_distance_cm, cap.radar_energy) == (2, 180, 77) + assert cap.frame_seq == 42 + assert cap.rssi == -61 + + db.refresh(d) + assert d.rssi == -61 + assert d.last_seen_at is not None + + +@needs_db +def test_an_unknown_trigger_is_422(client, device): + _, auth = device + assert post(client, auth, X_Trigger="motion").status_code == 422 + + +@needs_db +def test_an_out_of_range_radar_state_is_422(client, device): + _, auth = device + assert post(client, auth, X_Radar_State=9).status_code == 422 + + +@needs_db +def test_the_trigger_defaults_when_the_header_is_absent(client, device, db): + d, auth = device + r = client.post( + "/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg", **auth} + ) + assert r.status_code == 201 + + +# --- retries ---------------------------------------------------------------- + + +@needs_db +def test_the_same_frame_twice_is_one_capture(client, device, db): + """The device retries an upload whose response was lost and cannot tell + that case from a real failure.""" + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + + first = post(client, auth, data=body).json() + second = post(client, auth, data=body).json() + + assert second["capture_id"] == first["capture_id"] + assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 1 + + +@needs_db +def test_a_retry_still_receives_pending_commands(client, device, db): + """The retry is still the device asking; it must not lose the queue.""" + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + post(client, auth, data=body) + + db.add(DeviceCommand(device_id=d.id, type="reboot")) + db.commit() + + envelope = post(client, auth, data=body).json() + assert [c["type"] for c in envelope["commands"]] == ["reboot"] + + +@needs_db +def test_different_frames_are_separate_captures(client, device, db): + """Frames in a burst differ by sensor noise alone, so they must not + collapse into one.""" + d, auth = device + post(client, auth, data=make_jpeg(noise=b"frame-one")) + post(client, auth, data=make_jpeg(noise=b"frame-two")) + + assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 2 + + +@needs_db +def test_one_devices_frame_does_not_deduplicate_against_anothers(client, device, make_device): + _, auth = device + _, other_auth = make_device("other") + + body = make_jpeg(noise=b"identical") + a = post(client, auth, data=body).json() + b = post(client, other_auth, data=body).json() + + assert a["capture_id"] != b["capture_id"] + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +def test_an_empty_body_is_400(client, device): + _, auth = device + assert post(client, auth, data=b"").status_code == 400 + + +@needs_db +def test_a_body_that_is_not_a_jpeg_is_400_not_401(client, device): + """400 specifically: a 401 would make the device clear a good token.""" + _, auth = device + r = post(client, auth, data=b"GIF89a" + b"\x00" * 100) + assert r.status_code == 400 + + +@needs_db +def test_an_oversized_body_is_413(client, device): + """Mirrors `request_body max_size 12MB` in the Caddyfile, because a limit + that only exists in the proxy is not a limit.""" + _, auth = device + assert post(client, auth, data=make_jpeg() + b"\x00" * (12 * 1024 * 1024)).status_code == 413 + + +@needs_db +def test_nothing_is_written_when_the_body_is_rejected(client, device, db): + """No row, and nothing left on disk either.""" + d, auth = device + before = set(get_settings().image_root.rglob("*.jpg")) + + assert post(client, auth, data=b"not a jpeg at all").status_code == 400 + + assert db.scalars(select(Capture).where(Capture.device_id == d.id)).all() == [] + assert set(get_settings().image_root.rglob("*.jpg")) == before + + +@needs_db +def test_ingest_requires_a_bearer_token(client): + assert ( + client.post( + "/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg"} + ).status_code + == 401 + ) + + +@needs_db +def test_a_disabled_device_cannot_ingest(client, device, db): + d, auth = device + d.enabled = False + db.commit() + assert post(client, auth).status_code == 403 diff --git a/server/tests/test_queue.py b/server/tests/test_queue.py index 0dd8a55..8ddf644 100644 --- a/server/tests/test_queue.py +++ b/server/tests/test_queue.py @@ -1,5 +1,11 @@ """Queue behaviour. Needs a real PostgreSQL: SKIP LOCKED has no equivalent anywhere else, and mocking it would test nothing. + +These share the ``jobs`` table with everything else, including /ingest, which +enqueues a thumbnail job per capture. So nothing here may assume it owns the +queue: test jobs are enqueued at a priority that puts them first, and every +claim is checked to be one of ours before anything is done to it. Acting on a +claim without that check could fail somebody else's job. """ from __future__ import annotations @@ -9,6 +15,9 @@ from conftest import needs_db pytestmark = [pytest.mark.db, needs_db] +# claim() orders by priority DESC, so this wins against anything real. +TEST_PRIORITY = 1000 + @pytest.fixture def session(): @@ -21,38 +30,56 @@ def session(): s.commit() +def claim_ours(queue, session, kind: str) -> dict: + """Claim, and insist it is the job this test enqueued.""" + claimed = queue.claim(session) + assert claimed is not None, "our own job should have been claimable" + assert claimed["kind"] == kind, f"claimed {claimed['kind']!r}, not our {kind!r}" + return claimed + + def test_claim_returns_a_queued_job_then_nothing(session): from poorbird.worker import queue - queue.enqueue(session, "test_noop", {"n": 1}) + queue.enqueue(session, "test_noop", {"n": 1}, priority=TEST_PRIORITY) session.commit() - claimed = queue.claim(session) - assert claimed is not None - assert claimed["kind"] == "test_noop" + claimed = claim_ours(queue, session, "test_noop") assert claimed["payload"] == {"n": 1} assert claimed["attempts"] == 1 queue.complete(session, claimed["id"]) - # Same job must not come back. + # Same job must not come back. Anything else that turns up belongs to + # another test, so put it back rather than stranding it in 'running' -- + # a claim that is never released is invisible until something else + # mysteriously stops being processed. again = queue.claim(session) assert again is None or again["kind"] != "test_noop" + if again is not None: + queue.fail(session, again["id"], "released by test", retry_in_s=0) def test_a_second_worker_skips_a_locked_row_instead_of_blocking(session): - """The whole point of FOR UPDATE SKIP LOCKED.""" + """The whole point of FOR UPDATE SKIP LOCKED. + + The invariant is that the second worker is not blocked by the first and + never gets the same row -- not that the queue is otherwise empty, which + is not something a shared table can promise. + """ from poorbird.db import SessionLocal from poorbird.worker import queue - queue.enqueue(session, "test_only_one") + queue.enqueue(session, "test_only_one", priority=TEST_PRIORITY) session.commit() - first = queue.claim(session) - assert first is not None + first = claim_ours(queue, session, "test_only_one") with SessionLocal() as other: - assert queue.claim(other) is None + second = queue.claim(other) + assert second is None or second["id"] != first["id"] + if second is not None: + queue.fail(other, second["id"], "released by test", retry_in_s=0) queue.complete(session, first["id"]) @@ -61,13 +88,12 @@ def test_failure_retries_until_max_attempts_then_parks(session): from poorbird.models import Job from poorbird.worker import queue - job = queue.enqueue(session, "test_doomed", max_attempts=2) + job = queue.enqueue(session, "test_doomed", max_attempts=2, priority=TEST_PRIORITY) session.commit() job_id = job.id for _ in range(2): - claimed = queue.claim(session) - assert claimed is not None + claimed = claim_ours(queue, session, "test_doomed") queue.fail(session, claimed["id"], "boom", retry_in_s=0) session.expire_all() @@ -83,10 +109,9 @@ def test_stale_running_jobs_are_reclaimed(session): from poorbird.models import Job from poorbird.worker import queue - job = queue.enqueue(session, "test_orphan") + job = queue.enqueue(session, "test_orphan", priority=TEST_PRIORITY) session.commit() - claimed = queue.claim(session) - assert claimed is not None + claim_ours(queue, session, "test_orphan") # Pretend the worker died an hour ago. session.execute( diff --git a/server/tests/test_ratelimit.py b/server/tests/test_ratelimit.py new file mode 100644 index 0000000..fa8384f --- /dev/null +++ b/server/tests/test_ratelimit.py @@ -0,0 +1,270 @@ +"""Rate limiting (REVIEW SEC-004). + +The rest of the suite runs with limiting off, so this is the one place that +turns it on and proves the buckets are actually wired to the routes. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db + +from poorbird.api import ratelimit +from poorbird.api.deps import hash_credential, new_credential +from poorbird.api.ratelimit import BUCKETS, Limit, TokenBuckets +from poorbird.config import Settings, get_settings +from poorbird.models.devices import Device, DeviceStatus + +# --- the bucket itself ------------------------------------------------------ + + +def test_a_bucket_allows_its_burst_then_refuses(): + b = TokenBuckets() + limit = Limit(capacity=3, per_second=1.0) + + assert [b.take("k", limit, now=0.0) for _ in range(3)] == [None, None, None] + assert b.take("k", limit, now=0.0) is not None + + +def test_it_says_how_long_to_wait(): + b = TokenBuckets() + limit = Limit(capacity=1, per_second=0.5) # one every two seconds + + assert b.take("k", limit, now=0.0) is None + retry = b.take("k", limit, now=0.0) + assert retry == pytest.approx(2.0) + + +def test_tokens_come_back_over_time(): + b = TokenBuckets() + limit = Limit(capacity=2, per_second=1.0) + + b.take("k", limit, now=0.0) + b.take("k", limit, now=0.0) + assert b.take("k", limit, now=0.0) is not None + + assert b.take("k", limit, now=1.0) is None # one second, one token + + +def test_a_bucket_never_fills_past_its_capacity(): + """An idle week must not buy a week's worth of burst.""" + b = TokenBuckets() + limit = Limit(capacity=2, per_second=1.0) + + b.take("k", limit, now=0.0) + for _ in range(2): + assert b.take("k", limit, now=100_000.0) is None + assert b.take("k", limit, now=100_000.0) is not None + + +def test_keys_do_not_share_an_allowance(): + b = TokenBuckets() + limit = Limit(capacity=1, per_second=1.0) + + assert b.take("a", limit, now=0.0) is None + assert b.take("b", limit, now=0.0) is None + assert b.take("a", limit, now=0.0) is not None + + +def test_the_key_table_is_bounded(): + """It is keyed partly on caller address; unbounded growth would itself be + a way to exhaust memory.""" + b = TokenBuckets(max_keys=10) + limit = Limit(capacity=1, per_second=1.0) + + for i in range(100): + b.take(f"key-{i}", limit, now=0.0) + + assert len(b._state) == 10 + + +def test_the_documented_limits_are_the_shape_they_claim(): + assert ratelimit.ENROLL.capacity == 6 + assert ratelimit.INGEST.per_second == pytest.approx(2.0) # 120/min + # Ingest must comfortably clear a radar burst of three to five frames. + assert ratelimit.INGEST.capacity >= 10 + + +# --- the client address ----------------------------------------------------- + + +class _Req: + def __init__(self, headers=None, host="127.0.0.1"): + self.headers = headers or {} + self.client = type("C", (), {"host": host})() + + +def test_the_proxy_header_wins_over_the_socket(): + """Every camera reaches the app from 127.0.0.1 via Caddy. Without this + they would all share one bucket.""" + assert ratelimit.client_address(_Req({"x-real-ip": "192.168.1.88"})) == "192.168.1.88" + + +def test_forwarded_for_is_read_as_a_fallback(): + req = _Req({"x-forwarded-for": "192.168.1.88, 10.0.0.1"}) + assert ratelimit.client_address(req) == "192.168.1.88" + + +def test_the_socket_address_is_the_last_resort(): + assert ratelimit.client_address(_Req(host="10.1.2.3")) == "10.1.2.3" + + +# --- wired to the routes ---------------------------------------------------- + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def limited(client, db): + """Turn limiting on for one test, and leave no buckets behind.""" + BUCKETS.reset() + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, + enroll_secret="test-secret", + rate_limit_enabled=True, + ) + yield + client.app.dependency_overrides.clear() + BUCKETS.reset() + + +@pytest.fixture +def make_device(db): + """Devices that are removed even when the test fails. + + Teardown belongs in a fixture: a failing assertion skips the rest of the + test body, and cleanup written down there silently never runs. + """ + created: list[Device] = [] + + def make(name: str = "cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + created.append(d) + return d, {"Authorization": f"Bearer {token}"} + + yield make + + for d in created: + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + existing = db.get(Device, d.id) + if existing is not None: + db.delete(existing) + db.commit() + + +@pytest.fixture +def device(make_device): + return make_device() + + +@needs_db +def test_enrollment_is_limited_by_address(client, limited): + """The one endpoint where a shared secret could be ground at.""" + codes = [ + client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.90"}, + ).status_code + for _ in range(ratelimit.ENROLL.capacity + 2) + ] + + assert 429 in codes, "grinding at the enroll secret must eventually be refused" + assert codes.count(401) == ratelimit.ENROLL.capacity + + +@needs_db +def test_a_429_carries_retry_after(client, limited): + for _ in range(ratelimit.ENROLL.capacity + 1): + r = client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.91"}, + ) + + assert r.status_code == 429 + assert int(r.headers["Retry-After"]) >= 1 + + +@needs_db +def test_one_address_cannot_spend_anothers_budget(client, limited): + for _ in range(ratelimit.ENROLL.capacity + 1): + client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.92"}, + ) + + other = client.post( + "/api/v1/enroll", + json={"device_uid": secrets.token_hex(6), "device_name": "cam"}, + headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.93"}, + ) + assert other.status_code == 401, "a second camera must not inherit the first's throttle" + + +@needs_db +def test_heartbeat_is_limited_per_device(client, limited, device): + _, auth = device + codes = [ + client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).status_code + for _ in range(ratelimit.CONDITIONS.capacity + 2) + ] + + assert codes[0] == 200 + assert 429 in codes + + +@needs_db +def test_one_device_cannot_spend_anothers_budget(client, limited, device, make_device): + _, auth = device + for _ in range(ratelimit.CONDITIONS.capacity + 2): + client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth) + + _, other_auth = make_device("other") + + r = client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=other_auth) + assert r.status_code == 200, "one wedged camera must not starve the others" + + +@needs_db +def test_a_throttled_request_is_429_and_never_401(client, limited, device): + """401 makes the firmware clear its token. Being busy is not a credential + problem, and throwing away a good token over it would be a real fault.""" + _, auth = device + seen = set() + for _ in range(ratelimit.CONDITIONS.capacity + 3): + seen.add( + client.post("/api/v1/status", json={"reason": "periodic"}, headers=auth).status_code + ) + + assert 429 in seen + assert 401 not in seen + + +@needs_db +def test_limiting_off_means_off(client, device): + """The default for the rest of the suite, and for local development.""" + _, auth = device + codes = [ + client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).status_code + for _ in range(ratelimit.CONDITIONS.capacity + 5) + ] + assert set(codes) == {200} diff --git a/server/tests/test_schemas.py b/server/tests/test_schemas.py new file mode 100644 index 0000000..77538c2 --- /dev/null +++ b/server/tests/test_schemas.py @@ -0,0 +1,277 @@ +"""Device API request/response shapes (REVIEW SEC-003). + +These assert against firmware/API.md and, where the two disagree, against what +firmware/src/api_client.cpp actually sends. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from poorbird.api.schemas import ( + Command, + DeviceConditions, + EnrollRequest, + Envelope, + IngestMeta, +) + +# --- enrollment ------------------------------------------------------------- + + +def test_enroll_accepts_what_the_firmware_sends(): + """Exactly the body built in api_client.cpp::enrollWith.""" + r = EnrollRequest.model_validate( + { + "device_uid": "a0b7651f2c3d", + "device_name": "poorbird-cam-1", + "hw_revision": "xiao-esp32s3-sense-ld2410", + "fw_version": "0.1.0", + "mac": "A0:B7:65:1F:2C:3D", + } + ) + assert r.device_uid == "a0b7651f2c3d" + assert r.device_name == "poorbird-cam-1" + + +def test_the_field_is_device_name_not_name(): + """REVIEW.AI.md calls it 'name'. The firmware sends 'device_name'.""" + with pytest.raises(ValidationError): + EnrollRequest.model_validate({"device_uid": "a0b7651f2c3d", "name": "cam-1"}) + + +def test_device_uid_must_be_hex(): + """It is the eFuse MAC in hex; anything else is not a device identity.""" + for bad in ["not-hex!", "zzzz", "", "ab"]: + with pytest.raises(ValidationError): + EnrollRequest.model_validate({"device_uid": bad, "device_name": "cam"}) + + +def test_oversized_fields_are_rejected_before_the_database_sees_them(): + """devices.name is String(64); a 422 beats a DataError from psycopg.""" + with pytest.raises(ValidationError): + EnrollRequest.model_validate({"device_uid": "a0b765", "device_name": "x" * 65}) + + +# --- ingest ----------------------------------------------------------------- + + +def test_ingest_trigger_enum_matches_the_database_constraint(): + for t in ("radar", "manual", "timer", "stream_grab"): + assert IngestMeta(trigger=t).trigger == t + with pytest.raises(ValidationError): + IngestMeta(trigger="motion") + + +def test_radar_fields_are_range_checked(): + IngestMeta(trigger="radar", radar_state=3, radar_energy=100) + with pytest.raises(ValidationError): + IngestMeta(trigger="radar", radar_state=4) + with pytest.raises(ValidationError): + IngestMeta(trigger="radar", radar_energy=101) + + +def test_captured_at_defaults_to_none(): + """X-Captured-At: 0 means the clock is unsynced -- NULL, not 1970.""" + assert IngestMeta(trigger="radar").captured_at is None + + +# --- conditions ------------------------------------------------------------- + + +def _example_body() -> dict: + """The status payload from firmware/API.md, verbatim.""" + return { + "reason": "periodic", + "fw_version": "0.1.0", + "hw_revision": "xiao-esp32s3-sense-ld2410", + "config_version": 8, + "power": { + "uptime_ms": 91204, + "awake_ms": 91204, + "boot_count": 37, + "wake_cause": "radar", + "last_sleep_s": 300, + "total_sleep_s": 10800, + "sleep_enabled": False, + "sleep_allowed": False, + "inhibits": "stream,upload", + }, + "battery": { + "valid": True, + "mv": 3912, + "pct": 74, + "raw_mv": 1956, + "chemistry": 1, + "low": False, + }, + "counters": { + "captured_today": 412, + "delivered_today": 407, + "failed_today": 5, + "events_today": 41, + "day_index": 20716, + "captured_boot": 88, + "delivered_boot": 88, + }, + "camera": {"frame_size": 8, "jpeg_quality": 12, "profile": "day", "ready": True}, + "night": { + "is_night": False, + "nightlight_on": False, + "behaviour": 2, + "capture_allowed": True, + }, + "stream": {"enabled": False, "active": False, "frames_sent": 0, "seconds_left": 0}, + "radar": { + "baud": 256000, + "uart_ok": True, + "out_pin": False, + "state": 0, + "moving_cm": 0, + "moving_energy": 0, + "stationary_cm": 0, + "stationary_energy": 0, + }, + "system": { + "rssi": -61, + "ip": "192.168.1.88", + "free_heap": 184320, + "free_psram": 6815744, + "ring_depth": 24, + "ring_bytes": 1179648, + }, + "time_synced": True, + "device_time": "2026-09-20T14:31:07Z", + } + + +def test_the_documented_status_payload_validates(): + c = DeviceConditions.model_validate(_example_body()) + assert c.reason == "periodic" + assert c.battery.mv == 3912 + assert c.counters.day_index == 20716 + assert c.system.free_psram == 6815744 + + +def test_reason_enum_matches_the_database_constraint(): + for r in ( + "heartbeat", + "periodic", + "after_event", + "before_sleep", + "before_night_sleep", + "on_request", + ): + assert DeviceConditions(reason=r).reason == r + with pytest.raises(ValidationError): + DeviceConditions(reason="whenever") + + +def test_unknown_firmware_fields_are_kept_not_rejected(): + """The firmware grows fields before the server learns about them. + + device_status.raw exists to keep the whole body; a 422 would take a camera + offline for reporting something new. + """ + body = _example_body() + body["quantum_flux"] = 42 + body["battery"]["future_field"] = "x" + + c = DeviceConditions.model_validate(body) + assert c.reason == "periodic" + assert c.model_dump()["quantum_flux"] == 42 + + +def test_missing_blocks_default_rather_than_failing(): + """Only `reason` is genuinely required; a minimal report still lands.""" + c = DeviceConditions(reason="before_sleep") + assert c.battery.valid is None # None = not reported, distinct from False + assert c.counters.captured_today is None + + +def test_battery_valid_false_is_preserved_as_false(): + """false means NOT MEASURED. It must not collapse into None anywhere.""" + c = DeviceConditions.model_validate({"reason": "periodic", "battery": {"valid": False}}) + assert c.battery.valid is False + + +def test_frame_size_accepts_a_name_as_well_as_an_index(): + """Names are authoritative: framesize_t indices have shifted between + driver releases, so a stored index can mean a different resolution.""" + assert ( + DeviceConditions.model_validate( + {"reason": "periodic", "camera": {"frame_size": "SVGA"}} + ).camera.frame_size + == "SVGA" + ) + assert ( + DeviceConditions.model_validate( + {"reason": "periodic", "camera": {"frame_size": 8}} + ).camera.frame_size + == 8 + ) + + +# --- envelope --------------------------------------------------------------- + + +def test_envelope_omits_firmware_when_the_device_is_on_target(): + """Present-and-different is itself the signal to flash, so absent must + mean absent -- not null.""" + e = Envelope(server_time=1758376267000, config_version=7) + assert "firmware" not in e.model_dump(exclude_none=True) + + +def test_envelope_matches_the_documented_example(): + e = Envelope( + capture_id="3f786850-e387-550f-dab8-36ed7e6dc881", + server_time=1758376267000, + config_version=7, + firmware={ + "version": "0.2.0", + "url": "/firmware/0.2.0.bin", + "sha256": "3f786850e387550fdab836ed7e6dc881de23001b" + "0" * 24, + "size": 1148320, + }, + commands=[ + Command( + id=12, + type="stream_start", + payload={"session_id": "s-88f1", "duration_s": 45, "mode": 0}, + expires_at=1758376400000, + ) + ], + ) + dumped = json.loads(e.model_dump_json(exclude_none=True)) + # Exactly the keys parseEnvelope reads, plus capture_id. + assert dumped["server_time"] == 1758376267000 + assert dumped["config_version"] == 7 + assert dumped["firmware"]["version"] == "0.2.0" + assert dumped["commands"][0]["id"] == 12 + assert dumped["commands"][0]["type"] == "stream_start" + + +def test_command_type_enum_matches_the_database_constraint(): + with pytest.raises(ValidationError): + Command(id=1, type="self_destruct") + + +def test_empty_command_list_is_the_default(): + assert Envelope(server_time=0, config_version=1).commands == [] + + +# --- contract drift --------------------------------------------------------- + + +def test_api_md_is_where_we_think_it_is(): + """If this moves, the comments above stop pointing anywhere.""" + api_md = Path(__file__).resolve().parents[2] / "firmware" / "API.md" + assert api_md.is_file(), f"contract not found at {api_md}" + text = api_md.read_text(encoding="utf-8") + # The two deviations from SPEC.md that these schemas encode. + assert "device_name" in text + assert "raw JPEG as the body" in text diff --git a/server/tests/test_thumbnails.py b/server/tests/test_thumbnails.py new file mode 100644 index 0000000..40bcd68 --- /dev/null +++ b/server/tests/test_thumbnails.py @@ -0,0 +1,326 @@ +"""The thumbnail worker job. + +Unlike the ingest path, this really decodes the frame, so these tests use +real JPEGs rather than the hand-built headers in test_ingest.py. +""" + +from __future__ import annotations + +import io +import secrets +import uuid + +import pytest +from conftest import needs_db +from PIL import Image + +from poorbird.config import get_settings +from poorbird.images import ( + THUMB_EDGE, + UndecodableImage, + make_thumbnail, + relative_thumb_path, +) +from poorbird.models.captures import Capture +from poorbird.models.devices import Device +from poorbird.worker.handlers import HANDLERS + + +def real_jpeg(width: int = 1600, height: int = 1200) -> bytes: + """An actual decodable JPEG, not just a plausible header.""" + img = Image.new("RGB", (width, height)) + for x in range(0, width, 64): # some structure, so it is not a solid block + for y in range(0, height, 64): + img.putpixel((x, y), (x % 256, y % 256, 128)) + out = io.BytesIO() + img.save(out, format="JPEG", quality=85) + return out.getvalue() + + +# --- the encoder ------------------------------------------------------------ + + +def test_the_long_edge_is_capped_and_the_aspect_ratio_is_kept(tmp_path): + source = tmp_path / "wide.jpg" + source.write_bytes(real_jpeg(1600, 1200)) + + data, original = make_thumbnail(source) + + assert original == (1600, 1200) + with Image.open(io.BytesIO(data)) as thumb: + assert max(thumb.size) == THUMB_EDGE + assert thumb.size == (400, 300) # 4:3 preserved + + +def test_a_portrait_frame_is_capped_on_its_own_long_edge(tmp_path): + source = tmp_path / "tall.jpg" + source.write_bytes(real_jpeg(600, 1200)) + + data, _ = make_thumbnail(source) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.size == (200, 400) + + +def test_a_small_frame_is_never_upscaled(tmp_path): + """Blowing a 100px frame up to 400px produces a blurry lie.""" + source = tmp_path / "small.jpg" + source.write_bytes(real_jpeg(100, 80)) + + data, original = make_thumbnail(source) + + assert original == (100, 80) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.size == (100, 80) + + +def test_the_output_is_webp(tmp_path): + source = tmp_path / "x.jpg" + source.write_bytes(real_jpeg(800, 600)) + + data, _ = make_thumbnail(source) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.format == "WEBP" + + +def test_a_thumbnail_is_much_smaller_than_its_source(tmp_path): + source = tmp_path / "x.jpg" + source.write_bytes(real_jpeg(1600, 1200)) + + data, _ = make_thumbnail(source) + assert len(data) < source.stat().st_size + + +def test_rubbish_raises_undecodable_rather_than_something_generic(tmp_path): + """The distinction matters: undecodable is permanent, so the worker must + not spend three attempts rediscovering it.""" + source = tmp_path / "not-an-image.jpg" + source.write_bytes(b"\xff\xd8\xff" + b"garbage" * 100) + + with pytest.raises(UndecodableImage): + make_thumbnail(source) + + +def test_a_truncated_jpeg_is_also_undecodable(tmp_path): + source = tmp_path / "half.jpg" + source.write_bytes(real_jpeg(1600, 1200)[:200]) + + with pytest.raises(UndecodableImage): + make_thumbnail(source) + + +def test_the_thumb_name_carries_its_size(tmp_path): + """The size is in the filename, so changing it writes a new name rather + than silently serving a different image from the old one.""" + cid = uuid.uuid4() + assert relative_thumb_path(cid) == f"{cid}_400.webp" + + +# --- the handler ------------------------------------------------------------ + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def capture(db): + """A capture with its frame genuinely on disk, cleaned up either way.""" + settings = get_settings() + device = Device(device_uid=secrets.token_hex(6), name="cam") + db.add(device) + db.commit() + db.refresh(device) + + created: list[Capture] = [] + + def make(data: bytes | None = None, *, width=None, height=None): + cid = uuid.uuid4() + relative = f"2026/09/21/{cid}.jpg" + path = settings.image_root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(real_jpeg(1600, 1200) if data is None else data) + + cap = Capture( + id=cid, + device_id=device.id, + path=relative, + sha256="0" * 64, + bytes=path.stat().st_size, + trigger="radar", + width=width, + height=height, + ) + db.add(cap) + db.commit() + db.refresh(cap) + created.append(cap) + return cap + + yield make + + for cap in created: + (settings.image_root / cap.path).unlink(missing_ok=True) + if cap.thumb_path: + (settings.thumb_root / cap.thumb_path).unlink(missing_ok=True) + db.execute(Capture.__table__.delete().where(Capture.device_id == device.id)) + db.delete(db.get(Device, device.id)) + db.commit() + + +def run_job(db, capture_id) -> None: + HANDLERS["thumbnail"](db, {"capture_id": str(capture_id)}) + + +@needs_db +def test_the_handler_writes_a_thumbnail_and_records_it(db, capture): + cap = capture() + assert cap.thumb_path is None + + run_job(db, cap.id) + + db.refresh(cap) + assert cap.thumb_path == f"{cap.id}_400.webp" + + on_disk = get_settings().thumb_root / cap.thumb_path + assert on_disk.is_file() + with Image.open(on_disk) as thumb: + assert thumb.format == "WEBP" + assert max(thumb.size) == THUMB_EDGE + + +@needs_db +def test_it_fills_in_dimensions_ingest_could_not_read(db, capture): + """Ingest reads the JPEG header, which can be absent or unparseable. + This is the first full decode, so it is the chance to fix that.""" + cap = capture(width=None, height=None) + + run_job(db, cap.id) + + db.refresh(cap) + assert (cap.width, cap.height) == (1600, 1200) + + +@needs_db +def test_it_does_not_overwrite_dimensions_ingest_already_had(db, capture): + cap = capture(width=1600, height=1200) + + run_job(db, cap.id) + + db.refresh(cap) + assert (cap.width, cap.height) == (1600, 1200) + + +@needs_db +def test_running_it_twice_is_harmless(db, capture): + """Jobs get retried, and a partially written thumbnail must not survive.""" + cap = capture() + + run_job(db, cap.id) + first = (get_settings().thumb_root / cap.thumb_path).read_bytes() + run_job(db, cap.id) + second = (get_settings().thumb_root / cap.thumb_path).read_bytes() + + assert first == second + + +@needs_db +def test_no_part_file_is_left_behind(db, capture): + cap = capture() + run_job(db, cap.id) + + assert not list(get_settings().thumb_root.glob(".*.part")) + + +@needs_db +def test_an_undecodable_frame_is_recorded_not_retried(db, capture): + """Returning rather than raising is the point: the handler contract makes + a raise mean 'retry', and this will never decode.""" + cap = capture(data=b"\xff\xd8\xff" + b"garbage" * 100) + + run_job(db, cap.id) # must not raise + + db.refresh(cap) + assert cap.thumb_path is None + + +@needs_db +def test_a_missing_source_raises_so_the_job_retries(db, capture): + """The opposite case: the file should be there, and a mount that has not + come back yet is worth retrying for.""" + cap = capture() + (get_settings().image_root / cap.path).unlink() + + with pytest.raises(FileNotFoundError): + run_job(db, cap.id) + + +@needs_db +def test_a_capture_that_has_since_been_deleted_is_not_an_error(db): + """Retention will do this routinely once Phase 5 exists.""" + run_job(db, uuid.uuid4()) # must not raise + + +@needs_db +def test_a_malformed_payload_is_recorded_not_retried(db): + """SEC-003. Raising would spend three attempts rediscovering that the + payload is still malformed.""" + HANDLERS["thumbnail"](db, {}) + HANDLERS["thumbnail"](db, {"capture_id": "not-a-uuid"}) + HANDLERS["thumbnail"](db, {"wrong_key": 1}) + + +# --- wired to ingest -------------------------------------------------------- + + +@needs_db +def test_ingest_enqueues_the_job(client, db): + """Off the request path: decoding to resize is the one genuinely + expensive part of a capture, and the device is waiting with a burst + still to upload.""" + from sqlalchemy import text + + from poorbird.api.deps import hash_credential, new_credential + + token = new_credential() + device = Device( + device_uid=secrets.token_hex(6), + name="cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(device) + db.commit() + db.refresh(device) + + r = client.post( + "/api/v1/ingest", + content=real_jpeg(800, 600), + headers={"Content-Type": "image/jpeg", "Authorization": f"Bearer {token}"}, + ) + assert r.status_code == 201 + capture_id = r.json()["capture_id"] + + queued = db.execute( + text( + "SELECT kind, status FROM jobs " + "WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid" + ), + {"cid": capture_id}, + ).first() + assert queued is not None, "ingest must queue the thumbnail" + assert queued.status == "queued" + + settings = get_settings() + cap = db.get(Capture, uuid.UUID(capture_id)) + (settings.image_root / cap.path).unlink(missing_ok=True) + db.execute( + text("DELETE FROM jobs WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid"), + {"cid": capture_id}, + ) + db.execute(Capture.__table__.delete().where(Capture.device_id == device.id)) + db.delete(db.get(Device, device.id)) + db.commit()