The demo now picks a committed text fixture that only claims to be a photo, asserts on camera that nothing was posted to /api/analyze, and keeps manual entry in the same scene. The builder requires that caption to have painted and records image_ingress_refusal in the manifest; the threat model names each implemented control, its module, and the tests that enforce it.
15 KiB
Photo Data-Flow Threat Model — End-to-End Photo Path
- Status: Accepted
- Issue: #20 — Write the end-to-end photo data-flow threat model
- Parent epic: #5 — Clinical safety, privacy & security
- Milestone: M1 — Sovereign Photo Intelligence
- Date: 2026-10-10
- Scope: Every byte of a user's photo from capture to deletion on the
/api/analyzepath, plus the logs, exports, and consent records that touch it.
Why this exists
Photo-first logging asks a user to hand Timmy an image of the most private output their body produces. That image is sensitive medical-adjacent data by default, so the data-flow boundaries must be explicit before any private beta, and every abuse case that is not yet fully mitigated must name an owner and a tracked remediation ticket. This model covers the browser, the API, the model worker, transient buffers, the training opt-in store, logs, exports, and deletion.
Product boundary (unchanged by this model)
Timmy is non-diagnostic. AI may suggest only visible Bristol form, broad color, and image quality; every suggestion stays provisional until the user confirms or corrects it. Timmy must never diagnose disease, identify bleeding conclusively, infer pain, urgency, fever, or vomiting, or clear a food. Symptoms stay user-entered, and journal save is a separate decision from training contribution. Deterministic red-flag escalation runs on user-reported answers and is never model-gated or model-suppressible.
No real medical images are ever added to this repository, its fixtures, its tests, or its Git history. Every fixture used in the photo path is synthetic.
Data-flow diagram
flowchart TD
Browser["Browser — camera or gallery pick, in-memory draft only"]
APIIngress["API ingress — server.mjs /api/analyze"]
TransientBuffers["Transient buffers — bounded body bytes, decode canvas"]
ModelWorker["Model worker — self-hosted vision, private loopback only"]
OptInStore["Training opt-in store — consented contributions only"]
Logs["Sanitized logs — counts and reasons, never bytes or base64"]
Exports["Exports — user-initiated JSON portability"]
Deletion["Deletion — withdrawal, purge, and tombstones"]
Browser -->|"image bytes plus explicit consent"| APIIngress
APIIngress -->|"length, dimension, and rate limits first"| TransientBuffers
TransientBuffers -->|"re-encoded baseline JPEG, metadata stripped"| ModelWorker
ModelWorker -->|"observable fields only — image dropped, never persisted"| APIIngress
APIIngress -->|"no image bytes"| Logs
Browser --> Exports
OptInStore --> Deletion
TransientBuffers --> Deletion
Logs --> Deletion
Trust boundaries
| # | Boundary | Trust posture |
|---|---|---|
| B1 | Browser to API ingress | Hostile network. Treat every upload as hostile and sensitive: sniff content, cap size and dimensions, rate-limit the client, and never trust the filename or declared MIME type. |
| B2 | API ingress to model worker | Private loopback only. The worker is never exposed publicly and never receives a user identity. |
| B3 | Model worker to provider or hosted profile | Disabled by default. When enabled, the operator carries the decision, the image is the only payload, and no ledger, symptom, or session data travels with it. |
| B4 | App process to logs | One-way and lossy: counts, reasons, and durations leave; bytes, base64, filenames, and symptom text do not. |
| B5 | App process to consent records | Contribution requires its own opt-in with a versioned receipt; journal save never implies contribution. |
| B6 | Host to operator | The operator can reach data the app holds. Least privilege, documented purge, and no image bytes in operator-facing logs. |
Components
C1 — Browser
Holds the captured image as an in-memory draft and renders the consent prompt. A photo awaiting consent is deliberately not written to storage, so it cannot survive the tab by accident, and the service worker never caches analysis requests or image bodies. Lifetime: until the tab closes, consent is refused, or the draft is cleared.
C2 — API ingress
server.mjs /api/analyze is the only door for image bytes. It owns content sniffing, dimension and body caps, re-encode, metadata stripping, rate control, and the sanitized error vocabulary. Lifetimes are per request: nothing about an image is written to disk.
C3 — Model worker
A self-hosted vision process bound to private loopback. It receives the re-encoded image and returns schema-constrained observable fields or an abstention. It returns no free text, and its output is provisional until the user confirms it.
C4 — Transient buffers
Request body buffer, decode canvas, and the re-encode pipe. These are the moments the image exists in readable form; they are bounded, per request, and dropped when the request ends, on success or failure alike.
C5 — Training opt-in store
Only images and labels a user explicitly contributed, each with consent version, receipt, and provenance. This store is not on the logging path: an ordinary journal save never reaches it.
C6 — Sanitized logs
Operational logs for health, latency, abstention, and failure. They carry counts, reason codes, and durations; they never carry image bytes, base64, the original filename, or user symptom text.
C7 — Exports
User-initiated JSON portability of the user's own ledger. Exports are generated on request, are not written server-side, and deliberately exclude photo bytes.
C8 — Deletion
Withdrawal, purge, and tombstones. Deletion is addressable by contribution ID so it can reach derived artifacts, and a tombstone records that deletion happened without keeping what was deleted.
Threat register
Each entry names the abuse case, the mitigation that is already committed or queued, the owning role, the tracked ticket that will prove the mitigation, and the artifact that will count as evidence.
T1 — Replay and re-submission
- Scenario: An attacker replays a captured upload to exhaust inference capacity, correlate timing with a user session, or force repeated provider work from one image.
- Impact: Denial of service for real users, cost amplification on hosted profiles, and weak linkage between a session and its image bytes.
- Mitigation: Per-client fixed-window rate control on
/api/analyzethat fails with429andRetry-Afterbefore any provider work, opaque client identity held server-side rather than in the image payload, and no retention of over-limit payloads. - Owner: Timmy (ingress, area/backend)
- Testable follow-up: #16
- Evidence: An ingress test that drives the limiter past its window and asserts a rejected request never reaches the provider, with a separate assertion that no over-limit payload is retained.
T2 — Oversized input
- Scenario: A decompression bomb, an enormous dimension count, or a multi-hundred-megabyte body arrives to consume worker memory, block the queue, or stall the request path indefinitely.
- Impact: Worker exhaustion and queue starvation that degrade logging availability, up to a full outage of photo analysis.
- Mitigation: Decoded-body, per-dimension, and timeout caps enforced before any provider or worker work; a bounded inference queue with cancellation and an overload fallback that returns the manual path instead of hanging.
- Owner: Timmy (ingress, area/backend)
- Testable follow-up: #17
- Evidence: A queue-full and body-timeout test proving the request is rejected inside its budget and that the manual Bristol path remains one action away, per the acceptance criteria of #17.
T3 — Metadata leakage
- Scenario: An uploaded photo carries EXIF, GPS, device identifiers, XMP, or PNG text chunks; or a failure path echoes base64 image bytes into an error message or a log line.
- Impact: Location and device deanonymization, plus durable copies of the image outside the intended boundary, including in logs.
- Mitigation: Content sniffing independent of filename and MIME, safe re-encode to baseline JPEG with a fixed argv, metadata dropped by construction, polyglot and malformed inputs rejected, and a fixed sanitized error vocabulary with no bytes, no base64, and no stack traces.
- Owner: Timmy (ingress, area/backend)
- Testable follow-up: #16
- Evidence: A re-encode test asserting EXIF, GPS, XMP, and PNG text chunks are absent from the accepted bytes, paired with a log-scan test asserting no image bytes or base64 appear in request or error logs.
T4 — Dataset poisoning
- Scenario: Mislabeled, duplicated, or adversarially crafted contributions enter the training corpus and shift the classifier toward a wrong or unsafe behavior, including teaching it to call a not-stool image a stool form.
- Impact: Silent accuracy loss that is invisible in aggregate metrics and could undermine abstention exactly where the product must fail closed.
- Mitigation: Immutable provenance per contribution, contributor-level splits so a single contributor cannot straddle train and evaluation, a reviewer and adjudication tool for form, color, quality, and exclusions, and a published dataset card with the labeling guide and split policy.
- Owner: Privacy reviewer (human gate), with Timmy as release authority
- Testable follow-up: #29
- Evidence: The contributor-held-out evaluation harness and calibration report, with the reviewer and adjudication tool as the labeling control.
T5 — Unauthorized training
- Scenario: A journal save is silently treated as consent, an image is trained on without a receipt, or a withdrawal fails to reach a derived artifact so contribution survives deletion.
- Impact: Use of private data without consent, which breaks the product promise and the beta consent gate, and is irreversible once a model is trained.
- Mitigation: Contribution is a separate opt-in decision with a versioned consent receipt shown before the data moves; journal save defaults to no contribution; withdrawal is addressable by contribution ID and reaches every derived artifact; journal saving never requires contribution.
- Owner: Privacy reviewer (human gate)
- Testable follow-up: #24
- Evidence: An opt-in and withdrawal test proving journal save contributes nothing by default, that the consent version and receipt are shown before contribution, and that a withdrawal removes every derived artifact by contribution ID, with tombstone handling from #25.
T6 — Operator access
- Scenario: The host operator — or anyone who reaches the host with the operator's privilege — reads image bytes, symptom text, or consent records from process memory, on-disk state, backups, or logs.
- Impact: A single privileged reader can deanonymize a user's most private log, and an undocumented backup can outlive a deletion request.
- Mitigation: Least-privilege host access, worker bound to private loopback with no public exposure, no image bytes or base64 in operator-facing logs, documented backup and rollback boundaries, and a purge procedure that names every place an image can exist.
- Owner: Operator (host owner), with Timmy as release authority
- Testable follow-up: #39
- Evidence: The production topology, secrets, backup, and rollback runbook, exercised against the deletion path so that purge reaches memory, temporary files, logs, and backups, with observability from #41 confirming no bytes reach the metrics surface.
Ingress controls implemented for #16
/api/analyze is the only route that accepts image bytes, and every limit below is decided inside
server.mjs before analyzePhoto runs, so a refusal never costs a provider call.
| Control | Where | Behaviour |
|---|---|---|
| Per-caller request budget | src/rate-limit.js |
Sliding window, 12 requests per 60s by default (TIMMY_ANALYZE_RATE_LIMIT, TIMMY_ANALYZE_RATE_WINDOW_MS); refusal is 429 with Retry-After. The key is a salted SHA-256 of the socket address held in process memory only — no address, no identity, no bytes are stored. |
| Body ceiling and deadline | src/http-body.js |
6 MB ceiling and a 15s deadline (TIMMY_BODY_TIMEOUT_MS); 413 and 408 respectively, and the half-read socket is dropped after the refusal is written. |
| Container sniffing | src/image-ingress.js |
The declared data-URL MIME is treated as a claim, never evidence: JPEG/PNG/WebP is decided from magic bytes, and a mismatch is refused. |
| Polyglot / trailing payloads | src/image-ingress.js |
The container is walked to its own end marker (PNG IEND, JPEG EOI, RIFF length); anything appended after the image is refused instead of forwarded. |
| Embedded metadata | src/image-ingress.js |
JPEG APP1/APP13/COM segments and PNG eXIf/tEXt/zTXt/iTXt/tIME chunks are refused. The app's own upload is a canvas re-encode (JPEG q0.7, longest edge 1200px) and carries none, so the accepted path is already metadata-free. |
| Pixel limits | src/image-ingress.js |
Dimensions are read from the header (PNG IHDR, JPEG SOF, WebP VP8X/VP8/VP8L) and refused above a 4096px edge or 16 megapixels, so a decode bomb never reaches the worker. |
| Log hygiene | server.mjs |
Refusal copy is fixed prose; no request body, image bytes, hash, or address is written to a log or returned in an error. |
Residual, and not claimed as solved here: the server refuses metadata-bearing or mismatched containers rather than transcoding them itself, so a client that cannot produce a clean re-encode must use the app's capture path. PNG chunk CRCs are not validated (structure is), and the request budget is per process, not per cluster.
Accepted residual risks
- Host compromise. Data in a running process can be read by a sufficiently privileged attacker. This is accepted for the private beta and bounded by least privilege plus the purge procedure in #39; it is not claimed as eliminated.
- Model accuracy. The photo prefill remains blocked behind abstention and specialist-model evidence. A wrong or confident suggestion is treated as a user-correction problem, and the user remains the author of every saved entry, per #32 and the calibration work in #4.
- Provider profiles. A hosted OpenAI-compatible profile moves the image off-host by definition. It stays opt-in, operator-controlled, and off by default, with readiness reporting before it is offered, per #19.
Verification
- This document is enforced by
tests/threat-model.test.js, which asserts that the diagram covers every byte-bearing component, that each required abuse case is a numbered threat with an owner and a tracked follow-up ticket, and that the model keeps the non-diagnostic boundary and ships no real medical images. - The test runs in
npm testand therefore inside the CI quality gate and the release build, so the threat model cannot silently drift from the code it describes. - The ingress controls above are enforced by
tests/image-ingress.test.js,tests/rate-limit.test.js,tests/http-body.test.js, andtests/analyze-ingress.acceptance.test.js, which runs the shipping server against synthetic bytes and a counting provider stub;tests/ingress-capture.acceptance.mjsproves the same refusal in the running app. All of them run innpm testor the browser gate, so a regression fails the release instead of a promise. - Boundary and boundary-adjacent claims are reviewed by the clinical and privacy gate (#22, #23) before beta; this model does not move that gate, it feeds it.