Skip to content

Latest commit

 

History

History
551 lines (451 loc) · 25.5 KB

ARCHITECTURE.md

File metadata and controls

551 lines (451 loc) · 25.5 KB

TrustFrame — Architecture Documentation

Generated by TrustFrame_Architecture_Review.ipynb
Role: Principal Software Architect + Production Reliability Review
Scope: Full 14-day POC codebase review


Table of Contents

  1. Project Overview
  2. High-Level Architecture
  3. Repository Structure
  4. Execution Entry Points
  5. Configuration and Environment
  6. Source Code Module Analysis
  7. End-to-End Workflow Trace
  8. Subsystems and Interface Contracts
  9. State Model
  10. Failure Modes and Reliability Analysis
  11. Data Flow and Persistence
  12. Security and Access Boundaries
  13. Observability and Operations
  14. Test Strategy and Quality Signals
  15. Virtual Environment Setup and How to Run
  16. End-to-End Operational Runbook
  17. Risks, Gaps, and Recommendations
  18. Executive Summary for New Joiners

1. Project Overview

TrustFrame is a mobile-first evidence capture platform for recording and preserving photo/video evidence of civil incidents with tamper-evident chain-of-custody. Built as a 14-day POC for DreamzTech Solutions, targeting B2C events.

Attribute Value
Client DreamzTech Solutions
Timeline 14-day POC
Target Users Citizens, field officers
Core Value Frictionless capture + cryptographic tamper evidence
Phase 2 (deferred) AI analysis, blockchain anchoring, deepfake detection, C2PA

2. High-Level Architecture

Browser (React SPA)
  └─ LandingPage / CapturePage / TagEventPage / EvidenceReportPage / AdminPage
  └─ SessionContext (localStorage session state)
  └─ api.js (Axios, 60s timeout, /api/* proxy)
         │
         ▼ HTTP
Reverse Proxy (nginx :80 prod / Vite :5173 dev)
  └─ /api/* → FastAPI backend :8000
  └─ /static/* → StaticFiles uploads
         │
         ▼
FastAPI Backend :8000
  ├─ /api/session → sessions.py
  ├─ /api/events  → events.py
  ├─ /api/uploads → uploads.py ──→ storage.py (aiofiles streaming)
  ├─ /api/reports → reports.py      hashing.py (SHA-256)
  ├─ /api/admin   → admin.py        report_tokens.py
  └─ /static/uploads → StaticFiles
         │
         ▼
SQLAlchemy ORM
  ├─ SQLite (dev: ./trustframe_dev.db)
  └─ PostgreSQL 16 (prod: Docker named volume pgdata)

File System
  └─ uploads/images/{uuid}.jpg
  └─ uploads/videos/{uuid}.mp4

Technology Stack:

Layer Technology Version
Frontend framework React 18
Frontend build Vite 5
HTTP client Axios latest
Backend framework FastAPI latest
ORM SQLAlchemy 2.0
DB migrations Alembic latest
Dev DB SQLite built-in
Prod DB PostgreSQL 16-alpine
File I/O aiofiles latest
Hashing hashlib (stdlib) Python 3.11+
Tokens secrets (stdlib) Python 3.11+
QR codes qrcode[pil] latest
Rate limiting slowapi 0.1.9
Container Docker Compose v2
Prod web server nginx alpine

3. Repository Structure

trustframe/
├── backend/
│   ├── app/
│   │   ├── main.py              # FastAPI app factory + startup
│   │   ├── config.py            # Pydantic-settings env config
│   │   ├── database.py          # SQLAlchemy engine + session
│   │   ├── models/              # 5 ORM models
│   │   │   ├── user_session.py
│   │   │   ├── event_channel.py
│   │   │   ├── media_asset.py
│   │   │   ├── custody_event.py
│   │   │   └── evidence_report.py
│   │   ├── routers/             # 5 API routers
│   │   │   ├── sessions.py
│   │   │   ├── events.py
│   │   │   ├── uploads.py       # Core pipeline
│   │   │   ├── reports.py
│   │   │   └── admin.py
│   │   ├── services/            # 4 domain services
│   │   │   ├── hashing.py
│   │   │   ├── storage.py
│   │   │   ├── qr_generator.py
│   │   │   └── report_tokens.py
│   │   └── schemas/             # Pydantic v2 request/response
│   ├── tests/
│   │   ├── conftest.py          # SQLite in-memory test fixtures
│   │   ├── test_hashing.py      # 7 unit tests
│   │   ├── test_tokens.py       # 9 unit tests
│   │   └── test_custody.py      # 4 integration tests
│   ├── migrations/
│   │   ├── alembic.ini          # ⚠️ hardcoded PostgreSQL URL
│   │   └── versions/001_initial.py
│   ├── Dockerfile
│   ├── requirements.txt
│   └── .env                     # local dev config
├── frontend/
│   ├── src/
│   │   ├── main.jsx
│   │   ├── App.jsx              # Route definitions
│   │   ├── context/
│   │   │   └── SessionContext.jsx
│   │   ├── services/
│   │   │   └── api.js
│   │   ├── pages/
│   │   │   ├── LandingPage.jsx
│   │   │   ├── CapturePage.jsx  # GPS + upload
│   │   │   ├── TagEventPage.jsx
│   │   │   ├── EvidenceReportPage.jsx
│   │   │   └── AdminPage.jsx
│   │   └── components/
│   │       ├── CreateEventModal.jsx
│   │       └── UploadProgress.jsx
│   ├── vite.config.js           # Dev proxy config
│   ├── nginx.conf               # Production nginx config
│   └── Dockerfile
├── docker-compose.yml
├── Scope.txt
└── ARCHITECTURE.md              # ← this file

4. Execution Entry Points

Entry Point Command Init Sequence
Backend server uvicorn app.main:app --reload --port 8000 Load settings → create_all() → makedirs(uploads) → register middleware → mount StaticFiles → register routers
Frontend dev npm run dev (from frontend/) Vite reads .env → starts HMR server :5173 → proxies /api/* and /static/* to localhost:8000
Tests pytest tests/ -v (from backend/) conftest.py overrides DATABASE_URL → SQLite in-memory engine → StaticPool → creates tables → per-test transaction rollback
Alembic alembic upgrade head (from backend/) Reads alembic.ini (⚠️ hardcoded PostgreSQL URL) → runs DDL migrations

5. Configuration and Environment

All configuration is in backend/.env and loaded by backend/app/config.py (pydantic-settings).

Variable Default Required Notes
DATABASE_URL — Yes sqlite:///./trustframe_dev.db for dev; PostgreSQL URL for prod
SECRET_KEY — Yes Loaded but currently unused in code paths
REPORT_TOKEN_SECRET — Yes Loaded but currently unused; intended for future HMAC signing
UPLOAD_DIR ./uploads No Relative to working directory; /app/uploads in Docker
MAX_UPLOAD_SIZE_MB 500 No Client and server enforced file size limit
CORS_ORIGINS ["http://localhost:3000","http://localhost:5173"] No JSON array string; parsed by cors_origins_list property
ADMIN_SECRET — Yes Compared against X-Admin-Secret header; use strong random value
APP_URL http://localhost:5173 No Used to build report URLs and QR code URLs

6. Source Code Module Analysis

File Type Role
backend/app/main.py RUNTIME-CRITICAL FastAPI app factory. CORS, rate limiter, static files, 5 routers. Runs create_all() at startup.
backend/app/config.py RUNTIME-CRITICAL Pydantic-settings; singleton settings imported everywhere.
backend/app/database.py RUNTIME-CRITICAL SQLAlchemy engine (dialect-aware). get_db() FastAPI dependency.
backend/app/models/user_session.py RUNTIME-CRITICAL UserSession: anonymous user identity anchor.
backend/app/models/event_channel.py RUNTIME-CRITICAL EventChannel: named incident container with 8-char QR-based code.
backend/app/models/media_asset.py RUNTIME-CRITICAL MediaAsset: central entity with all provenance metadata.
backend/app/models/custody_event.py RUNTIME-CRITICAL CustodyEvent: append-only provenance ledger (4 event types).
backend/app/models/evidence_report.py RUNTIME-CRITICAL EvidenceReport: 1:1 with MediaAsset; holds report token + view count.
backend/app/routers/uploads.py RUNTIME-CRITICAL Core pipeline: stream → SHA-256 → MediaAsset + CustodyEvent + EvidenceReport atomically.
backend/app/routers/reports.py RUNTIME-CRITICAL Report serving: token lookup, view_count++, REPORT_VIEWED custody event, filtered response.
backend/app/routers/sessions.py RUNTIME-CRITICAL Session creation; returns UUID.
backend/app/routers/events.py RUNTIME-CRITICAL Event CRUD + QR PNG generation.
backend/app/routers/admin.py RUNTIME-CRITICAL Read-only admin views; X-Admin-Secret auth.
backend/app/services/hashing.py RUNTIME-CRITICAL compute_sha256(), compute_session_integrity_hash(). Pure functions, fully tested.
backend/app/services/storage.py RUNTIME-CRITICAL LocalStorage.save(): async streaming + MIME-based subfolder routing.
backend/app/services/qr_generator.py RUNTIME-CRITICAL generate_qr_png(url) → PNG bytes.
backend/app/services/report_tokens.py RUNTIME-CRITICAL generate_report_token() (256-bit entropy), verify_report_token().
backend/tests/conftest.py TEST-ONLY SQLite in-memory engine; transaction-rollback db fixture; TestClient client fixture.
backend/tests/test_hashing.py TEST-ONLY 7 unit tests for hashing functions.
backend/tests/test_tokens.py TEST-ONLY 9 unit tests for token generation and validation.
backend/tests/test_custody.py TEST-ONLY 4 ORM-level custody event integration tests.
backend/migrations/versions/001_initial.py BUILD-TIME Alembic DDL migration; uses PostgreSQL JSONB (⚠️ ORM uses JSON).
frontend/src/App.jsx RUNTIME-CRITICAL React Router v6 route tree; SessionProvider wrapper.
frontend/src/context/SessionContext.jsx RUNTIME-CRITICAL Session state; localStorage persistence; startSession() / clearSession().
frontend/src/services/api.js RUNTIME-CRITICAL All Axios API calls; 60s timeout; admin header injection.
frontend/src/pages/CapturePage.jsx RUNTIME-CRITICAL GPS, file selection, validation, upload + progress navigation.
frontend/src/pages/TagEventPage.jsx RUNTIME-CRITICAL Post-upload event association; create event modal; skip option.
frontend/src/pages/EvidenceReportPage.jsx RUNTIME-CRITICAL Report display: hash, GPS, device info, custody chain, share button.
frontend/vite.config.js BUILD-TIME Dev proxy: /api/* and /static/* → localhost:8000.
frontend/nginx.conf BUILD-TIME (PROD) Production proxy; SPA try_files fallback.
docker-compose.yml BUILD-TIME (INFRA) 3 services: db, backend, frontend. Named volumes: pgdata, uploads.

7. End-to-End Workflow Trace

  1. App Open → Session Start: Browser checks localStorage. If absent → name/phone form → POST /api/session/start → UserSession row → session_id stored in localStorage.

  2. QR Entry (alternate): QR code encodes APP_URL?event_id=<code>. LandingPage reads param → passes presetEventId to CapturePage.

  3. GPS Acquisition: navigator.geolocation.getCurrentPosition({enableHighAccuracy:true, timeout:10000}). Failure → null GPS (capture still allowed). GPS is client-reported; not server-verified.

  4. File Selection and Validation: Two inputs: live camera (capture=environment) and gallery. Frontend validates MIME type (image/* or video/*) and file size (≤ MAX_UPLOAD_SIZE_MB × 1024²).

  5. Upload and Provenance Recording:

    • POST /api/uploads (multipart: file + session_id + GPS + client_timestamp + device_info)
    • Backend: validate session → validate MIME → LocalStorage.save() (stream + SHA-256) → compute_session_integrity_hash() → INSERT MediaAsset → INSERT CustodyEvent(UPLOAD) → INSERT EvidenceReport
    • Returns: {asset_id, sha256_hash, report_token, report_url}
  6. Event Tagging (optional): PATCH /api/uploads/{id}/event {event_code} → sets event_channel_id FK → INSERT CustodyEvent(EVENT_TAGGED).

  7. Report Viewing: GET /api/reports/{token} → token lookup → view_count++ → INSERT CustodyEvent(REPORT_VIEWED) → return ReportResponse (REPORT_VIEWED excluded from public custody_chain).

  8. Admin Monitoring: GET /api/admin/stats|uploads|events|reports with X-Admin-Secret header.


8. Subsystems and Interface Contracts

Subsystem HTTP Surface Auth Key Behavior
Session Management POST /api/session/start None Creates anonymous UserSession; returns UUID
Event Management GET/POST /api/events, /events/{code}, /events/{code}/qrcode session_id in POST body 8-char cryptographically random event codes; QR PNG returned as bytes
Upload & Provenance POST /api/uploads, PATCH /api/uploads/{id}/event session_id in form Core pipeline; atomic create MediaAsset + CustodyEvent + EvidenceReport
Evidence Reports GET /api/reports/{token} Token in URL (bearer) Token lookup; side-effects: view_count++, REPORT_VIEWED event
Admin API GET /api/admin/* X-Admin-Secret header Read-only; no pagination; full data dumps
File Storage Internal (StaticFiles for reads) None Streams to images/ or videos/; returns relative path
Custody Ledger Internal None Append-only by convention; 4 event types; filtered on read

9. State Model

UserSession States

Anonymous → (POST /api/session/start) → Active → (clearSession) → Anonymous
Session persists across page reloads via localStorage. No expiry.

MediaAsset Lifecycle

Uploading → Persisted → (optional) Tagged → Reported
Asset metadata is immutable after creation (no UPDATE endpoints). Event association is the only post-creation mutation.

CustodyEvent Types (append-only)

  1. UPLOAD — written at upload time
  2. REPORT_GENERATED — written at upload time (alongside UPLOAD)
  3. EVENT_TAGGED — written when PATCH /api/uploads/{id}/event called
  4. REPORT_VIEWED — written on every GET /api/reports/{token}; excluded from public chain

10. Failure Modes and Reliability Analysis

ID Severity Failure Status
FM-01 HIGH Orphaned file if DB write fails after disk save NOT MITIGATED
FM-02 HIGH EvidenceReport INSERT fails after MediaAsset INSERT NOT MITIGATED
FM-03 HIGH alembic upgrade head fails in local dev (hardcoded PostgreSQL URL) NOT MITIGATED
FM-04 HIGH StaticFiles fails at startup if uploads/ doesn't exist MITIGATED (os.makedirs in main.py)
FM-05 MEDIUM Migration JSONB vs ORM JSON divergence COSMETIC MISMATCH ONLY
FM-06 MEDIUM REPORT_VIEWED events accumulate unboundedly NOT MITIGATED
FM-07 MEDIUM Report URLs become stale on APP_URL change NOT MITIGATED
FM-08 MEDIUM No rate limits applied despite slowapi being initialized NOT MITIGATED
FM-09 LOW Session ID is client-supplied — no ownership verification BY DESIGN (POC)
FM-10 LOW GPS coordinates entirely client-reported BY DESIGN (documented)
FM-11 LOW Admin secret uses plain string comparison (timing attack) NOT MITIGATED
FM-12 LOW File MIME type from Content-Type header (not magic bytes) NOT MITIGATED

11. Data Flow and Persistence

Database Tables

Table Primary Key Key Fields Relationships
user_sessions UUID display_name, phone_number, user_agent, timestamps → media_assets (1:N), → event_channels (1:N)
event_channels UUID event_code (8-char, UNIQUE, INDEX), name, GPS fields ← user_sessions, → media_assets (1:N)
media_assets UUID storage_path (UNIQUE), sha256_hash, server_timestamp_utc, GPS fields, device_info, session_integrity_hash, file_size_bytes, mime_type ← user_sessions, ← event_channels, → custody_events (1:N), → evidence_reports (1:1)
custody_events UUID media_asset_id (FK, INDEX), event_type, timestamp_utc, metadata (JSON) ← media_assets
evidence_reports UUID media_asset_id (FK, UNIQUE), report_url_token (UNIQUE, INDEX), view_count ← media_assets (1:1)

File System Layout

uploads/
  images/    ← MIME starts with image/  (JPEG, PNG, HEIC, etc.)
  videos/    ← MIME starts with video/  (MP4, MOV, etc.)

Served via GET /static/uploads/{path}. Never automatically deleted.


12. Security and Access Boundaries

Trust Levels

Principal How Identified What They Can Do
Anonymous User None Create sessions; view public QR codes
Session Bearer session_id UUID in form Upload files; create/list events
Report Token Bearer 256-bit URL token View single evidence report + metadata
Admin X-Admin-Secret header Read all data (no write operations)

Key Security Findings

OWASP Category Finding Severity Status
A01 Broken Access Control Admin uses plain string compare (not hmac.compare_digest) MEDIUM Not mitigated
A01 Broken Access Control session_id is client-supplied (no ownership proof) LOW By design (POC)
A04 Insecure Design GPS, device info, client_timestamp are entirely client-reported MEDIUM Documented in Scope.txt
A04 Insecure Design File type validated from Content-Type header (not magic bytes) MEDIUM Not mitigated
A05 Misconfiguration SECRET_KEY and REPORT_TOKEN_SECRET loaded but unused LOW Dead config
A08 Data Integrity sha256_hash not re-verified when file is served LOW Not implemented
A09 Security Logging No structured logging or security event log MEDIUM Not implemented

13. Observability and Operations

Category Item Present
Health Check GET /health endpoint ✅ Yes
Health Check Docker compose healthcheck (backend + db) ✅ Yes
Logging Structured JSON logging ❌ No
Logging Security event logging ❌ No
Metrics Prometheus metrics ❌ No
Rate Limiting Functional rate limit decorators ❌ No (slowapi initialized but unused)
Tracing OpenTelemetry / distributed tracing ❌ No
Alerting Any alerting system ❌ No
Admin Visibility Stats + entity list endpoints ✅ Yes
Disk Monitoring Upload directory size monitoring ❌ No
DB Backup Automated backup ❌ No
Auto-restart Docker compose restart: unless-stopped ✅ Yes

14. Test Strategy and Quality Signals

Current status: 20/20 tests passing

Module Coverage Notes
hashing.py 🟢 HIGH 7 tests, all edge cases covered
report_tokens.py 🟢 HIGH 9 tests including entropy and format validation
custody_events ORM 🟡 MEDIUM 4 DB-level tests
All API routers 🔴 NONE Zero HTTP-level tests
storage.py 🔴 NONE Streaming logic untested
Frontend (all) 🔴 NONE No tests of any kind
Alembic migrations 🔴 NONE Not validated against any DB

Recommended additions:

  1. HTTP-level pytest tests for POST /api/uploads, GET /api/reports/{token}, admin auth
  2. Storage service tests (mock aiofiles, test MIME routing, max size enforcement)
  3. Frontend: Vitest + React Testing Library for SessionContext, api.js, CapturePage validation
  4. CI: GitHub Actions pytest gate on every PR

15. Virtual Environment Setup and How to Run

Option A — Local Development

Backend:

cd backend
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows: .venv\Scripts\Activate.ps1
pip install -r requirements.txt
cp .env.example .env  # or create .env manually (see Section 5)
uvicorn app.main:app --reload --port 8000

Frontend:

cd frontend
npm install
# Create frontend/.env with: VITE_API_URL=
npm run dev

Tests:

cd backend
pytest tests/ -v

Option B — Docker Compose

# 1. Create root .env with DATABASE_URL, ADMIN_SECRET, APP_URL, etc.
docker compose up --build

# 2. Run DB migrations (required for PostgreSQL)
docker compose exec backend alembic upgrade head

# 3. Verify
curl http://localhost/health

16. End-to-End Operational Runbook

RB-01: Capture Evidence

  1. Open app / scan QR code → create session
  2. Allow GPS → select file (camera or gallery)
  3. Wait for upload → tag event (optional)
  4. Share report URL from EvidenceReportPage

RB-02: Verify File Integrity

sha256sum downloaded_file.jpg
# Windows: Get-FileHash downloaded_file.jpg -Algorithm SHA256
# Compare with hash shown on evidence report

RB-03: Admin Monitoring

curl -H "X-Admin-Secret: <secret>" http://<HOST>/api/admin/stats
curl -H "X-Admin-Secret: <secret>" http://<HOST>/api/admin/uploads

RB-04: Troubleshoot Uploads

Symptom Likely Cause Resolution
422 Missing form fields Check request format
413 File too large Increase MAX_UPLOAD_SIZE_MB
404 on session Invalid session_id Re-run POST /api/session/start
500 DB/disk failure Check docker compose logs -f backend

RB-05: DB Maintenance

docker compose exec db pg_dump -U trustframe trustframe_db > backup_$(date +%Y%m%d).sql
docker compose exec backend alembic upgrade head
docker compose exec db psql -U trustframe -d trustframe_db

17. Risks, Gaps, and Recommendations

ID Priority Category Risk Effort
R-01 🔴 CRITICAL Infrastructure No CI/CD pipeline LOW (1-2 days)
R-02 🔴 CRITICAL Data Integrity No transactional guarantee on upload (orphaned files) LOW (4-6 hours)
R-03 🔴 CRITICAL Deployment alembic.ini hardcodes PostgreSQL URL TRIVIAL (<1 hour)
R-04 🔴 CRITICAL Testing Zero HTTP-level tests for core pipelines LOW (1 day)
R-05 🟠 HIGH Security No rate limiting on any endpoint TRIVIAL (<1 hour)
R-06 🟠 HIGH Security File type validated from Content-Type header only LOW (3-4 hours)
R-07 🟠 HIGH Operations No disk monitoring or retention policy MEDIUM (1-2 days)
R-08 🟠 HIGH Security ADMIN_SECRET is weak default test-admin TRIVIAL (<5 min)
R-09 🟡 MEDIUM Architecture Report URL staleness on APP_URL change LOW (2-3 hours)
R-10 🟡 MEDIUM Architecture No database backup strategy MEDIUM (1 day)
R-11 🟡 MEDIUM Architecture create_all() + Alembic dual schema management LOW (4-6 hours)
R-12 🟡 MEDIUM Testing No frontend tests MEDIUM (2-3 days)
R-13 🟢 LOW Security SHA-256 not re-verified on serve MEDIUM (1-2 days)
R-14 🟢 LOW Architecture REPORT_VIEWED events accumulate without bound TRIVIAL (<2 hours)
R-15 🟢 LOW Future Phase 2 architecture extensions needed HIGH (weeks/feature)

Prioritized Action Plan

Immediate (before any external access):

  • R-08: Rotate ADMIN_SECRET
  • R-05: Add @limiter.limit() to upload and session endpoints
  • R-03: Fix alembic.ini DATABASE_URL

Short term (pre-pilot):

  • R-02: Transactional upload with file cleanup on failure
  • R-04: HTTP-level pytest tests
  • R-01: GitHub Actions CI
  • R-06: File magic byte validation

Medium term (pre-production):

  • R-11, R-07, R-10, R-12, R-09

18. Executive Summary for New Joiners

What Is It?

A mobile-first evidence capture platform where any person can record and preserve photo/video evidence with tamper-evident chain-of-custody. No account required — frictionless by design.

The Three Most Important Files

  1. backend/app/routers/uploads.py — Core pipeline (everything: file save, hash, custody, report)
  2. backend/app/models/ — Complete data model
  3. frontend/src/pages/CapturePage.jsx — User-facing heart of the product

The Three Most Critical Gaps

  1. No CI/CD — All deploys are manual with no automated verification gate
  2. No transactional upload — File on disk but DB fails → inconsistent state with no cleanup
  3. No rate limiting — Upload endpoint is unguarded against abuse

How to Contribute

  1. Clone + run backend (uvicorn app.main:app --reload) and frontend (npm run dev)
  2. Run pytest tests/ -v — all 20 tests should pass
  3. For API changes: update Pydantic schemas, check http://localhost:8000/docs
  4. For DB changes: create Alembic migration (alembic revision --autogenerate -m "description")
  5. See Section 17 for prioritized improvements backlog

Where to Find Things

Need Look In
Product scope Scope.txt
API docs http://localhost:8000/docs
Data model backend/app/models/
Environment variables backend/app/config.py + backend/.env
Core business logic backend/app/routers/uploads.py
UI pages frontend/src/pages/
Tests backend/tests/
Setup instructions Section 15 of this document
Known risks Section 17 of this document