Files
poorBird/server/REVIEW.md
T
tom 7aeb1ff0ce Add review files
Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-09-21 01:58:59 +02:00

733 lines
21 KiB
Markdown

# Code Review: poorBird Server (feature/UI_Basic_implementation)
**Reviewer:** Mistral Vibe
**Date:** 2026-09-21
**Branch:** feature/UI_Basic_implementation
**Commit:** 5d16ded (Server: verify Phase 1 end to end against PostgreSQL 17)
**Version:** 0.1.0
---
## Executive Summary
**Important Note:** This branch (`feature/UI_Basic_implementation`) currently contains **ONLY server code** (Phase 1) - **no UI implementation exists yet**. The branch name indicates it's **prepared for UI development** (Phase 3), but the UI itself is not implemented.
The server infrastructure is **architecturally excellent** and **UI-ready**. All foundational work for Phase 3 (WebUI) is in place. The code quality is very high, documentation is outstanding, but **critical security issues must be fixed before UI development begins**.
| Category | Rating | Priority | Notes |
|----------|--------|----------|-------|
| **Architecture** | 5/5 | Low | UI-ready foundation |
| **Security** | 2/5 | **High** | **Must fix before Phase 3** |
| **Performance** | 4/5 | Medium | Good for current scale |
| **Code Quality** | 5/5 | Low | Excellent |
| **UI Readiness** | 4/5 | Medium | Infrastructure ready, UI missing |
| **Test Coverage** | 5/5 | Low | 12/12 tests passing |
---
## Branch Status
### Current State
- **Branch Name:** feature/UI_Basic_implementation
- **Actual Content:** Server code only (identical to feature/Server_Basic_implementation)
- **Commit:** 5d16ded
- **Phase:** 1 (Server Foundation) - **UI Phase (3) not started**
### Interpretation
This branch appears to be a **preparation branch** for UI development. It contains:
- ✅ Complete server foundation (Phase 1)
- ✅ All infrastructure needed for UI (Phase 3)
- ❌ No actual UI code (React/TS/Vite)
- ⏳ UI endpoints not implemented (Phase 3 task)
**Recommendation:** Either rename the branch to reflect its actual content, or start UI implementation.
---
## 1. Architecture Analysis - UI Perspective
### What's Already UI-Ready
#### ✅ **API Infrastructure for UI**
- FastAPI app with proper lifespan management
- API versioning (`/api/v1/` prefix)
- Health endpoints for UI monitoring
- CORS-ready (needs configuration)
#### ✅ **Data Models for UI**
- `captures` table with all UI-needed fields
- `observations` table for species data
- `taxa` table for taxonomy autocomplete
- `tags` table for categorization
- `devices` table with status for device list
- `device_status` for time-series data
#### ✅ **Storage for UI**
- `image_root` and `thumb_root` configured
- Image path structure: `/srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg`
- Thumbnails: `_400.webp` suffix
- Auth-checked image serving planned (app authorizes, Caddy serves)
#### ✅ **Authentication Infrastructure**
- `users` table with roles (admin, editor, viewer)
- `sessions` table for session management
- Argon2id password hashing planned
- RBAC ready (SPEC 3.1)
#### ✅ **Deployment for UI**
- Caddy reverse proxy with TLS (DNS-01)
- Static file serving via Caddy
- systemd units for API and worker
### What's Missing for UI
#### ❌ **No UI Code**
- No React/TypeScript code
- No Vite configuration
- No frontend build process
- No UI dependency management
#### ❌ **No UI Endpoints**
- No gallery API endpoints
- No observation management endpoints
- No settings endpoints
- No user management endpoints
#### ❌ **No Authentication Implementation**
- No session cookie handling
- No login/logout endpoints
- No password hashing implementation
- No CSRF protection
#### ❌ **No UI-Specific Configuration**
- No frontend build directory
- No static asset configuration
- No theme settings implementation
---
## 2. Security Analysis - Critical for UI
### 🔴 CRITICAL Issues (Must Fix Before Phase 3 / UI Development)
#### 1. **Enroll Secret in Plaintext (CRITICAL)**
- **Location:** config.py:53, .env files, systemd EnvironmentFile
- **Issue:** Shared bootstrap secret stored in plaintext
- **Risk:** Filesystem access = complete device spoofing
- **UI Impact:** If UI exposes device management, this is catastrophic
- **Solution:**
- Use HashiCorp Vault or AWS Secrets Manager
- Or: Only accept via CLI, never store in files
- Set file permissions to 600
- **Priority:** **CRITICAL - Block Phase 3**
#### 2. **No Request Authentication (CRITICAL)**
- **Location:** All API endpoints
- **Issue:** No authentication for any endpoint
- **Risk:** Anyone can send device commands, access admin functions
- **UI Impact:** UI would be completely insecure
- **Solution:**
- Device auth: X-Enroll-Secret header validation
- User auth: Session cookies with CSRF protection
- Admin auth: API keys or JWT
- **Priority:** **CRITICAL - Block Phase 3**
#### 3. **No Input Validation (CRITICAL for UI)**
- **Location:** queue.py, future UI endpoints
- **Issue:** No validation of user input
- **Risk:** SQL injection, XSS, malicious data
- **UI Impact:** High - UI accepts user input
- **Solution:** Pydantic models for ALL requests
- **Priority:** **CRITICAL - Block Phase 3**
#### 4. **No Rate Limiting (HIGH for UI)**
- **Location:** API layer
- **Issue:** No protection against DoS/brute force
- **Risk:** UI endpoints can be flooded
- **Solution:** slowapi middleware, 100 req/min/IP
- **Priority:** **HIGH - Fix Before Phase 3**
### 🟡 HIGH Priority Issues (Fix Before Phase 3)
#### 5. **No CORS Configuration**
- **Issue:** No CORS headers
- **Risk:** UI cannot make requests if on different origin
- **Solution:** Add CORS middleware with specific origins
- **Priority:** HIGH
#### 6. **No CSRF Protection**
- **Issue:** Required for WebUI forms
- **Risk:** Cross-site request forgery attacks
- **Solution:** CSRF tokens for all mutating requests
- **Priority:** HIGH
#### 7. **No Session Management**
- **Issue:** sessions table exists but not used
- **Risk:** Cannot implement user authentication
- **Solution:** Implement session cookie handling
- **Priority:** HIGH
#### 8. **Database URL with Credentials in Defaults**
- **Location:** config.py:30
- **Issue:** Plaintext credentials in default value
- **Risk:** Accidental commit of credentials
- **Solution:** Set default to empty string
- **Priority:** HIGH
### 🟡 MEDIUM Priority Issues
#### 9. **No Password Hashing Implementation**
- **Issue:** password_hash column exists but no hashing code
- **Solution:** Implement Argon2id hashing (planned per SPEC)
- **Priority:** MEDIUM
#### 10. **No Image Upload Validation**
- **Issue:** Images not validated before saving
- **Risk:** Malicious file uploads
- **Solution:** Validate file type, size, dimensions
- **Priority:** MEDIUM
---
## 3. UI-Specific Analysis
### 3.1 What's Prepared for UI
#### ✅ **Data Model**
```
Captures (1:n) Observations
- UUID primary key (good for URLs)
- path, thumb_path
- sha256 (for deduplication)
- trigger, burst_id, burst_index
- pre_trigger flag
- radar data (distance, energy)
- battery, rssi, temp
- kept, reviewed flags
- received_at (authoritative timestamp)
Observations
- capture_id (FK)
- taxon_id (FK to Taxa)
- source (human/model)
- model_version, confidence, bbox (for ML)
- age, sex, behaviour, certainty
- notes
Taxa
- scientific_name, name_de, name_en
- gbif_key, family, order
- is_local_common (for autocomplete ranking)
Tags
- label, colour
- Many-to-many with captures
Devices
- device_uid (MAC-based identity)
- config (JSONB - all device settings)
- status fields (battery, rssi, etc.)
- commands queue
- reenroll_secret_hash
```
**Rating:** 5/5 - Excellent data model for UI
#### ✅ **Storage Structure**
- `/srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg`
- `/srv/poorbird/thumbs/<uuid>_400.webp`
- Single source of truth: `image_root` in config
**Rating:** 5/5 - Well-designed for UI consumption
#### ✅ **Authentication Model**
- Users: admin, editor, viewer roles
- Sessions: for persistent login
- TOTP 2FA: optional (SPEC Q14)
- Argon2id: for password hashing
**Rating:** 4/5 - Good foundation, needs implementation
### 3.2 What Needs to Be Built for UI
#### 📋 **Phase 3 Tasks (from TODO.md)**
**Frontend:**
- [ ] React + TS + Vite + TanStack Query/Router
- [ ] Virtualised gallery grid with filters
- [ ] Observation editor
- [ ] Taxon autocomplete
- [ ] Tags, favourite/reject, review flag
- [ ] Three themes (light, dark, blue)
- [ ] Auth: session cookies, CSRF, RBAC
**Backend (UI Endpoints):**
- [ ] Gallery API (list, filter, paginate)
- [ ] Observation CRUD
- [ ] Taxa search/autocomplete
- [ ] Tag management
- [ ] User management
- [ ] Settings management
- [ ] Auth endpoints (login, logout, register)
**Security:**
- [ ] Session cookie implementation
- [ ] CSRF protection
- [ ] Password hashing (Argon2id)
- [ ] Audit logging
- [ ] Image upload validation
### 3.3 UI Technology Stack (Planned)
| Component | Technology | Status |
|-----------|------------|--------|
| Frontend Framework | React + TypeScript | Not started |
| Build Tool | Vite | Not started |
| State Management | TanStack Query | Not started |
| Routing | TanStack Router | Not started |
| Styling | CSS Custom Properties | Not started |
| Theming | Design tokens → CSS vars | Not started |
| Backend | FastAPI | Phase 1 complete |
| Auth | Session cookies + CSRF | Not started |
| 2FA | TOTP (optional) | Not started |
---
## 4. Performance Analysis - UI Considerations
### Current Configuration
| Component | Setting | UI Impact | Rating |
|-----------|---------|-----------|--------|
| DB Connection Pool | 5 | May limit concurrent UI requests | 3/5 |
| Worker Poll Interval | 2s | Affected by background jobs only | 4/5 |
| Sync SQLAlchemy | Enabled | Blocks event loop under load | 4/5 |
| Image Storage | Date-based directories | Good for organization | 5/5 |
### Expected UI Load
- **Gallery View:** 20-50 images per page, paginated
- **Search/Filter:** 100-500ms per query (with indexes)
- **Image Upload:** ~200-500KB per image
- **Thumbnail Generation:** 100-300ms per image (Phase 2)
- **Concurrent Users:** 1-5 typical, 10 peak
### Performance Recommendations for UI
#### 1. **Database Optimization**
```python
# Current: 5 connections
# Recommended for UI: 15-20 connections
db_pool_size: int = 15
# Add timeouts
pool_recycle=3600 # Recycle after 1 hour
pool_timeout=30 # Timeout after 30 seconds
connect_timeout=10
```
#### 2. **API Performance**
- **Pagination:** All list endpoints should be paginated
- **Caching:** Cache gallery queries, taxon lists
- **Lazy Loading:** Images should load as user scrolls
- **Compression:** Enable gzip for API responses
#### 3. **Image Handling**
- **Thumbnails:** Pre-generate on ingest (Phase 2)
- **Lazy Load:** Only load visible images
- **Progressive Loading:** Show low-res first, then high-res
- **CDN:** Consider for production (not needed for LAN-only)
#### 4. **Frontend Performance**
- **Code Splitting:** Split React bundles
- **Tree Shaking:** Remove unused code
- **Image Optimization:** WebP format for thumbnails
- **Bundle Analysis:** Track bundle size
---
## 5. Data Model Analysis - UI Perspective
### ✅ Excellent Decisions
#### 1. **Captures with UUID Primary Key**
- **Benefit:** Safe for URLs, distributed systems
- **UI Usage:** `/gallery/{capture_id}` URLs
- **Rating:** 5/5
#### 2. **Observations 1:n to Captures**
- **Benefit:** One photo can have multiple species
- **UI Usage:** Multiple birds in one photo
- **Rating:** 5/5
#### 3. **Human vs Model Observations**
- **Benefit:** Same table, different source
- **UI Usage:** Human labels + future ML predictions
- **Rating:** 5/5
#### 4. **JSONB for Device Config**
- **Benefit:** Flexible, future-proof
- **UI Usage:** Device settings form
- **Rating:** 5/5
#### 5. **battery_valid Flag**
- **Important:** false = **not measured**, not empty
- **UI Requirement:** Display as "N/A", never as low battery alarm
- **Rating:** 5/5
### ⚠️ Potential Issues
#### 1. **No Index on sha256**
- **Issue:** Deduplication queries may be slow
- **Solution:** Add unique index on sha256
- **Priority:** MEDIUM
#### 2. **No Index on burst_id**
- **Issue:** Burst grouping queries may be slow
- **Check:** Already has index (ix_captures_burst)
- **Status:** ✅ Already indexed
#### 3. **Daily Counters in RTC Memory**
- **Important:** Counters reset on power loss
- **UI Display:** Show as "gap" between captured and delivered
- **Rating:** 4/5 - Good design, UI must understand
---
## 6. UI Implementation Recommendations
### 6.1 Frontend Structure
```
webui/
├── src/
│ ├── components/
│ │ ├── Gallery/
│ │ │ ├── GalleryGrid.tsx
│ │ │ ├── ImageCard.tsx
│ │ │ └── Filters.tsx
│ │ ├── Observation/
│ │ │ ├── ObservationEditor.tsx
│ │ │ └── TaxonAutocomplete.tsx
│ │ ├── Settings/
│ │ │ └── DeviceSettings.tsx
│ │ └── Common/
│ │ ├── ThemeToggle.tsx
│ │ ├── LanguageToggle.tsx
│ │ └── Layout.tsx
│ ├── hooks/
│ │ ├── useGallery.ts
│ │ ├── useObservations.ts
│ │ └── useAuth.ts
│ ├── store/
│ │ ├── gallerySlice.ts
│ │ └── authSlice.ts
│ ├── utils/
│ │ └── api.ts (axios/fetch wrapper)
│ ├── styles/
│ │ ├── theme.css
│ │ └── global.css
│ ├── App.tsx
│ └── main.tsx
├── public/
│ └── index.html
├── vite.config.ts
├── package.json
└── tsconfig.json
```
### 6.2 Backend Endpoints Needed for UI
#### Gallery
- `GET /api/v1/captures` - Paginated list with filters
- `GET /api/v1/captures/{id}` - Single capture with observations
- `GET /api/v1/captures/{id}/image` - Full image (auth-checked)
- `GET /api/v1/captures/{id}/thumb` - Thumbnail (auth-checked)
#### Observations
- `POST /api/v1/captures/{id}/observations` - Add observation
- `PUT /api/v1/observations/{id}` - Update observation
- `DELETE /api/v1/observations/{id}` - Delete observation
#### Taxonomy
- `GET /api/v1/taxa` - Search with pagination
- `GET /api/v1/taxa/autocomplete` - Autocomplete endpoint
#### Tags
- `GET /api/v1/tags` - List all tags
- `POST /api/v1/tags` - Create tag (admin only)
#### Devices
- `GET /api/v1/devices` - List devices with status
- `GET /api/v1/devices/{id}` - Device details
- `PUT /api/v1/devices/{id}/settings` - Update settings
#### Users
- `POST /api/v1/auth/login` - Login
- `POST /api/v1/auth/logout` - Logout
- `GET /api/v1/users/me` - Current user
### 6.3 UI-Specific Security
#### Authentication Flow
```
1. POST /api/v1/auth/login (username, password)
→ Returns session cookie
2. All authenticated requests include session cookie
3. CSRF token in forms (for POST/PUT/DELETE)
4. Role-based access control (RBAC):
- viewer: Read-only
- editor: Read + Write (observations, tags)
- admin: Full access (devices, users, settings)
```
#### Image Security
- **Never** serve images directly from filesystem
- **Always** check authorization in app first
- **Then** have Caddy serve the bytes
- **URLs** should be unguessable (UUID-based)
---
## 7. Deployment Analysis - UI Impact
### ✅ Current Deployment (UI-Ready)
- **Reverse Proxy:** Caddy with TLS (DNS-01)
- **Static Files:** Caddy can serve built React app
- **API:** FastAPI behind Caddy
- **Images:** Auth-checked handoff to Caddy
### 📋 UI Deployment Tasks
#### Caddy Configuration
```caddyfile
# Current (API only)
:8080 {
reverse_proxy /api/* 127.0.0.1:8090
}
# Needed for UI
:80 {
# Serve static UI files
root * /srv/poorbird/webui
try_files {path} /index.html
# API reverse proxy
handle_path /api/* {
reverse_proxy 127.0.0.1:8090
}
# Image serving (auth-checked)
handle_path /images/* {
reverse_proxy 127.0.0.1:8090
}
}
```
#### systemd Unit for UI
- **Not needed:** Static files served by Caddy
- **Build process:** Should be part of deployment
- **Location:** `/srv/poorbird/webui`
---
## 8. Test Analysis - UI Considerations
### Current Tests
- **12/12 tests passing** (server only)
- All tests require PostgreSQL 17
- Integration tests for queue, schema, config, health
### Missing UI Tests
#### Unit Tests (Frontend)
- Component rendering tests
- Hook tests
- Utility function tests
- **Tool:** Jest + React Testing Library
#### Integration Tests (API)
- UI endpoint tests
- Authentication tests
- Authorization tests
- **Tool:** pytest + httpx
#### E2E Tests
- User flows: login → gallery → edit → logout
- **Tool:** Playwright or Cypress
### Test Environment for UI
- **Frontend:** Node.js 18+
- **Testing:** Jest, React Testing Library, Playwright
- **CI/CD:** GitHub Actions or similar
---
## 9. Recommended Implementation Order
### Phase 3: WebUI (Estimated: 3-4 weeks)
#### Week 1: Authentication & Foundation
1. [ ] Implement session management
2. [ ] Add CORS configuration
3. [ ] Add CSRF protection
4. [ ] Implement password hashing (Argon2id)
5. [ ] Create auth endpoints (login, logout, me)
6. [ ] Setup React + Vite project
7. [ ] Create basic layout and routing
#### Week 2: Gallery & Viewing
1. [ ] Implement gallery API endpoints
2. [ ] Create Gallery component
3. [ ] Add pagination
4. [ ] Implement ImageCard component
5. [ ] Add date/taxon/device filters
6. [ ] Setup image lazy loading
#### Week 3: Editing & Management
1. [ ] Implement observation CRUD endpoints
2. [ ] Create ObservationEditor
3. [ ] Add TaxonAutocomplete
4. [ ] Implement tag management
5. [ ] Add device list and status view
6. [ ] Create settings pages
#### Week 4: Polish & Testing
1. [ ] Implement theme switching
2. [ ] Add language support
3. [ ] Write frontend tests
4. [ ] Write E2E tests
5. [ ] Performance optimization
6. [ ] Security audit
### Dependencies
- **Phase 2 must be complete** (device endpoints)
- **Security issues must be fixed** (CRITICAL items)
- **Authentication must work** before UI can be used
---
## 10. Architecture Rating
| Criterion | Rating | Notes |
|-----------|--------|-------|
| **Scalability** | 4/5 | Good for 10 cameras, may need optimization for 100+ |
| **Maintainability** | 5/5 | Very clean code, excellent docs |
| **Security** | 2/5 | **Critical issues block Phase 3** |
| **Performance** | 4/5 | Good for current scale |
| **UI Readiness** | 4/5 | Infrastructure ready, UI missing |
| **Code Quality** | 5/5 | Excellent |
| **Test Coverage** | 5/5 | Server: 12/12 passing |
| **Documentation** | 5/5 | Outstanding |
### SPEC Compliance
| Requirement | Status | Rating |
|-------------|--------|--------|
| Native Deployment | ✅ | 5/5 |
| Container-Ready | ✅ | 5/5 |
| PostgreSQL | ✅ | 5/5 |
| Job Queue without Redis | ✅ | 5/5 |
| FastAPI | ✅ | 5/5 |
| PostgreSQL 17 Support | ✅ | 5/5 |
| **UI Infrastructure** | ⚠️ | **4/5 (Ready, not implemented)** |
| Device Contract | ❌ | Not implemented (Phase 2) |
| Auth System | ❌ | Not implemented (Phase 2) |
---
## 11. Conclusion & Recommendations
### What's Excellent
1. ✅ **Architecture** - UI-ready foundation
2. ✅ **Data Model** - Perfect for gallery and observations
3. ✅ **Storage** - Well-designed for images and thumbnails
4. ✅ **Deployment** - Caddy + systemd ready for UI
5. ✅ **Tests** - Complete server test coverage
### What's Missing (But Prepared For)
1. ❌ **UI Code** - React/TS/Vite project not started
2. ❌ **UI Endpoints** - Gallery, observation, auth endpoints missing
3. ❌ **Authentication** - Session management not implemented
4. ❌ **Authorization** - RBAC not enforced
### Critical Blockers for Phase 3
1. 🔴 **Enroll Secret in Plaintext** - Must fix
2. 🔴 **No Request Authentication** - Must fix
3. 🔴 **No Input Validation** - Must fix
4. 🔴 **No Rate Limiting** - Must fix
5. 🟡 **No CORS Configuration** - Must fix
6. 🟡 **No CSRF Protection** - Must fix
### Summary
The `feature/UI_Basic_implementation` branch is **misnamed** - it contains only server code (Phase 1), not UI code. However, the server is **perfectly prepared** for UI development (Phase 3).
**The server infrastructure is production-ready for UI development, but critical security issues must be fixed first.**
### Overall Rating
- **Code Quality:** 5/5 - Excellent
- **Architecture:** 5/5 - Excellent (UI-ready)
- **Security:** 2/5 - **Critical (blocking)**
- **Performance:** 4/5 - Good
- **UI Readiness:** 4/5 - Infrastructure ready
- **Test Coverage:** 5/5 - Excellent (server)
---
## 12. Quick Start: UI Implementation
### Prerequisites
1. Fix CRITICAL security issues (enroll secret, authentication)
2. Complete Phase 2 (device endpoints)
3. Setup Node.js 18+ and npm
### Setup
```bash
# Create webui directory
mkdir -p webui
cd webui
# Initialize Vite + React + TypeScript
npm create vite@latest . -- --template react-ts
# Install dependencies
npm install @tanstack/react-query @tanstack/react-router axios
npm install --save-dev @types/react @types/node
# Install Vite plugins
npm install vite-plugin-svgr @svgr/core
# Setup project structure (see Section 6.1)
```
### First Endpoints to Implement
```python
# server/src/poorbird/api/routes/gallery.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Optional
from datetime import date
router = APIRouter(prefix="/api/v1/captures", tags=["gallery"])
@router.get("/")
async def list_captures(
page: int = 1,
limit: int = 20,
device_id: Optional[int] = None,
taxon_id: Optional[int] = None,
date_from: Optional[date] = None,
date_to: Optional[date] = None,
kept: Optional[bool] = None,
reviewed: Optional[bool] = None,
):
"""List captures with pagination and filters."""
# Implementation here
pass
```
---
*Review created by Mistral Vibe on 2026-09-21. Based on commit 5d16ded.*