From f7e1675e9cab83c0d6b8c07558d5ac0f576768f4 Mon Sep 17 00:00:00 2001 From: poorBoy Date: Mon, 21 Sep 2026 11:55:28 +0200 Subject: [PATCH] Add REVIEW.md and REVIEW.AI.md for Server branch Review files for feature/Server_Basic_implementation: - REVIEW.md: Human-readable code review (German) - REVIEW.AI.md: AI-optimized reviewer guide (English) Based on analysis of commit 142b476. Includes: - Phase 1 completion assessment - Security analysis (SEC-001 through SEC-009) - Architecture decisions documentation - Data model analysis - Phase 2 implementation guide with code examples - Deployment analysis Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- server/REVIEW.AI.md | 1301 +++++++++++++++++++++++++++++++++++++++++++ server/REVIEW.md | 596 ++++++++++++++++++++ 2 files changed, 1897 insertions(+) create mode 100644 server/REVIEW.AI.md create mode 100644 server/REVIEW.md diff --git a/server/REVIEW.AI.md b/server/REVIEW.AI.md new file mode 100644 index 0000000..c5b06f2 --- /dev/null +++ b/server/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/server/REVIEW.md b/server/REVIEW.md new file mode 100644 index 0000000..f4a5699 --- /dev/null +++ b/server/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.*