fabi 31faccfdf8 fix(audit-4): refuse undecodable images at admission, stop retrying permanent failures
Fourth round: reject at the door what the worker can only fail on, and stop
retrying errors that cannot succeed — while keeping IoError retryable so ENOSPC
still gets another attempt.

Squashed from 2 commits, original messages preserved below.

──────── fix(upload): refuse undecodable images at the door, and stop retrying them

Two halves of the same complaint: an oversized photo was accepted with a 201 and
then silently soft-deleted minutes later, after the worker had burned six seconds
of backoff re-reaching a conclusion it could not change.

Admission. The compression budget now runs at upload time, against the header
only, so a guest is told immediately and told why:

  "Bild hat zu viele Bildpunkte (ca. 99 Megapixel) und kann nicht verarbeitet
   werden. Bitte verkleinere es und lade es erneut hoch."

instead of watching the photo vanish behind a vague "could not be processed" —
which arrived only if they happened to still be on the feed with that card
loaded. Nothing is stored, so there is no row to soft-delete and no orphan for
the sweep to reclaim.

Admission and the worker share ONE function (`decoder_within_budget`), so they
cannot drift apart and start disagreeing about what is acceptable — a photo
accepted at the door and rejected by the worker would be worse than either
behaviour alone. The worker keeps its own check: the backfill decodes files that
predate this check, and defence in depth is the whole reason the budget exists.

Retries. The loop retried every failure, including ones that are a property of
the input. An image over the budget, a corrupt file, an unsupported format: each
fails identically on all three attempts, so the only effect was 2s + 4s of sleep
and three near-identical warnings before the same outcome. `is_permanent_image_error`
classifies the `ImageError` variants that cannot change between attempts — Limits,
Unsupported, Decoding — and the loop gives up on those at once. `IoError` is
deliberately excluded: an ENOSPC while writing a derivative is exactly the
transient case the retry exists for, and misclassifying it would turn a blip back
into the data loss round 1 fixed. Measured: retry log lines went from 3 per
oversized upload to 0.

Tests: unit tests for both sides of the classifier (a Limits error is permanent, a
missing file is not) and for admission agreeing with the decoder on accept AND
reject. The e2e spec is rewritten for the new contract — 400 with an actionable
message, nothing stored, backend alive after a burst of four — plus a mirror
asserting an ordinary photo still uploads and processes, since a budget that
rejected everything would satisfy the other two.

──────── fix(upload): narrow the admission check to the memory budget only

The admission check I just added rejected ANY image the decoder couldn't build —
corrupt, truncated, or unsupported, not only over-budget. That broke two
adversarial tests, and they were right to break.

07-adversarial/file-upload-attacks pins, deliberately, that acceptance follows the
MAGIC BYTES: a payload whose first three bytes are a JPEG header is accepted
regardless of what follows, because the security property under test is that the
client-declared Content-Type has no influence. Both failing cases upload 1024
bytes of JPEG magic followed by zeros. Rejecting those at admission is a
different, broader contract than the one asked for, and rewriting an adversarial
test to match new behaviour is precisely the thing that needs justifying rather
than doing quietly.

So admission now checks only what it was meant to: `exceeds_decode_budget`
returns true solely for `ImageError::Limits`. A corrupt file goes to the
compression worker exactly as before — which handles it gracefully and, since the
retry classifier in the previous commit, no longer burns backoff on it. The
resource guard is the part that had to move earlier; nothing else did.

Tests: the size agreement between admission and the worker is still asserted in
both directions, plus a new one writing a magic-bytes-only stub and asserting
admission accepts it WHILE the worker still rejects it — pinning the boundary
between the two checks so a future widening fails here rather than in the
adversarial suite.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 07:55:56 +02:00

EventSnap

A private, QR-code-accessed photo & video sharing platform for weddings, birthdays, and personal events — built for guests, run by you.


What is EventSnap?

At private events, photos and videos are scattered across dozens of guests' phones and never truly shared. Existing solutions (WhatsApp groups, Google Photos) require accounts, expose personal data, and lack event-specific social features.

EventSnap gives every guest instant, frictionless access to a shared, living gallery — no app store, no email, no password.

A guest scans the QR code on their way in, types their name, and is immediately part of a shared moment. They upload, react, and comment throughout the day. After the event, the host releases the gallery — every guest walks away with a beautiful offline HTML keepsake and the full archive.

Project type: Mobile-first PWA — runs in any browser, no installation required.
Scale: Personal / private use — one event at a time, ~100 guests, ~1,000 files.


Features

MVP

Area Feature
Onboarding QR code join flow, name-only registration, persistent JWT + recovery PIN, 30-day sessions
Uploads Photo & video from library or live camera, client-side IndexedDB queue, per-file progress & retry, captions + #hashtags
Processing Lossless server-side compression, feed preview generation, ffmpeg video thumbnails
Feed Chronological grid, real-time SSE updates, hashtag filtering, likes & comments
Host Dashboard Ban/unban guests, delete content, promote to host, lock event, release gallery for export
Admin Dashboard All host permissions + configure limits, rates, quota tolerance, disk usage widget
Export On-demand ZIP (full-quality originals) + self-contained offline Memories.html viewer

Planned (v1.x)

  • Individual file download button
  • Low-disk alert (< 10 GB free)
  • Event banner / cover image
  • Chunked resumable upload for large videos
  • Host-curated story highlights
  • Slideshow / presentation mode

Tech Stack

Layer Technology
Frontend SvelteKit + TypeScript
Styling Tailwind CSS v4
Backend Rust + Axum
Async Tokio
Database PostgreSQL 16 via SQLx (compile-time query checking)
Auth Custom JWT (jsonwebtoken) + bcrypt PINs
Image processing image crate + oxipng (lossless compression)
Video processing ffmpeg via tokio::process::Command
File storage Local disk (/media/)
Real-time Axum SSE + tokio::sync::broadcast
Export async-zip (streaming ZIP) + minijinja (HTML bundle)
Rate limiting tower-governor (token-bucket, DB-configurable)
Reverse proxy Caddy 2 (automatic HTTPS via Let's Encrypt)
Containers Docker + Docker Compose
Infrastructure Hetzner CX33 (4 vCPU, 8 GB RAM, 80 GB SSD)

Repository Structure

eventsnap/
├── backend/          # Rust + Axum API server
│   ├── src/
│   ├── Cargo.toml
│   └── Dockerfile
├── frontend/         # SvelteKit PWA
│   ├── src/
│   ├── svelte.config.js
│   └── Dockerfile
├── docker-compose.yml
├── docker-compose.dev.yml   # opt-in dev overlay (publishes Postgres on the host)
├── Caddyfile
└── .env.example

Getting Started

Prerequisites

  • Docker (includes Compose plugin)
  • A domain name with an A record pointing to your server

Deploy on a fresh VPS

# 1. Clone the repository (into a lowercase dir, matching the paths used below)
git clone https://git.mc02.dev/fabi/EventSnap.git eventsnap
cd eventsnap

# 2. Configure environment
cp .env.example .env
nano .env   # set DOMAIN, JWT_SECRET, ADMIN_PASSWORD_HASH, EVENT_NAME, etc.

# 3. Start the stack
docker compose up -d

Caddy automatically obtains a Let's Encrypt certificate on first start. The app is live at https://DOMAIN within ~30 seconds.

If the site never comes up: with APP_ENV=production the backend refuses to boot while JWT_SECRET/ADMIN_PASSWORD_HASH still hold the .env.example placeholders (this is deliberate — a publicly-known signing key is worse than downtime). Caddy then waits on the unhealthy app container and never serves. Check docker compose logs app — a "Refusing to start … placeholder …" line means you skipped step 2. Rotate the secrets (see below) and restart.

Production note: docker compose up -d does not expose the database — Postgres is reachable only on the internal Docker network. For local development where you need host access to Postgres, opt into the dev overlay explicitly:

docker compose -f docker-compose.yml -f docker-compose.dev.yml up

Updating an existing deployment

docker compose up -d alone will NOT deploy your changes. app and frontend are build: services with no published image tag, and Compose has no source-change detection: if an image with that name already exists it is reused. After a git pull the command reports Container … Running, changes nothing, and exits 0 — so a deploy that shipped nothing looks exactly like a successful one. --build is what makes it real.

cd /path/to/eventsnap

# 1. Back up first — migrations run automatically on boot and are not reversible in place.
#    (See "Backup" below; the database dump is the one that matters here.)

# 2. Fetch the new code.
git pull

# 3. Rebuild and restart the application services. --build is NOT optional.
docker compose up -d --build

# 4. Apply any Caddyfile change. Step 3 does NOT do this — see the warning below.
docker compose up -d --force-recreate caddy

# 5. Confirm the app came back up. Anything other than "ok" means check the logs.
curl -fsS https://DOMAIN/health && echo

# 6. Confirm a NEW image was actually built. Note the IMAGE ID before you start and
#    compare — it must have changed. (Ignore the CREATED column; it reports the base
#    layer's age, not this build's.) An unchanged ID means step 3 ran without --build
#    and you are still serving the old code.
docker compose images app frontend

Migrations are applied by the backend on startup, so step 3 covers them. If app stays unhealthy afterwards, docker compose logs app will name the failing migration — and note that a migration applied by a newer build is not removed by checking out an older commit, so rolling back code without restoring the database snapshot from step 1 leaves the schema ahead of the binary and the app refusing to boot.

Why step 4 exists. --build only rebuilds services that have a build: section, and caddy is a pinned upstream image. Compose decides whether to recreate a container from its config hash, which covers the mount specification (./Caddyfile:/etc/caddy/Caddyfile:ro) but not the file's contents — so a git pull that changes ./Caddyfile produces no delta, Compose reports Running, and Caddy keeps serving its old config indefinitely. Exit code 0 throughout.

That is not hypothetical: the fix that made the keepsake download work on iOS (137c4ee) touched the Caddyfile and four e2e files and nothing else, so all of its production effect lives in that one file. Without step 4 you deploy it, watch both image IDs change, and iOS downloads stay broken.

--force-recreate rather than restart or caddy reload: the bind mount is resolved to an inode when the container is created, and git pull replaces the file instead of editing it in place, so the container can still be bound to the old, now-unlinked inode. A restart then re-reads the stale content. Recreating the container re-resolves the path.

db is never touched, and recreating caddy does not disturb the caddy_data volume, so the TLS certificate and all data volumes survive.

Generate required secrets

# JWT secret (64 random bytes)
openssl rand -hex 64

# Admin password hash (bcrypt, cost 12)
htpasswd -bnBC 12 "" yourpassword | tr -d ':\n'

Environment Variables

See .env.example for the full list with descriptions and defaults. Key variables:

Variable Description
DOMAIN Public domain for TLS (e.g. my-wedding.example.com)
JWT_SECRET 64-byte random hex string for signing JWTs
ADMIN_PASSWORD_HASH bcrypt hash of the admin dashboard password
EVENT_NAME Display name shown to guests
EVENT_SLUG URL-safe event identifier
DATABASE_URL PostgreSQL connection string

Docker Compose Stack

┌─────────────────────────────────────┐
│  Caddy :80 / :443 (TLS termination) │
└────────────┬────────────────────────┘
             │
    ┌────────┴────────┐
    │                 │
┌───▼────┐      ┌─────▼──────┐
│  app   │      │  frontend  │
│ :3000  │      │   :3001    │
│ (Rust) │      │(SvelteKit) │
└───┬────┘      └────────────┘
    │
┌───▼────┐
│   db   │
│ :5432  │
│(Postgres)│
└────────┘
  • /api/* → Rust backend
  • Everything else → SvelteKit frontend (adapter-node)
  • Named volumes: postgres_data, media_data, exports_data, caddy_data

Media is not served as static files. Every image goes through a visibility-checked alias (/api/v1/upload/{id}/{preview,display,thumbnail,original}) so a host takedown or a ban actually revokes access to the bytes.


Backup

There are three things to back up, and they live in three different places. DATABASE_URL and the container paths (/media, /exports) are meaningful only inside the compose network — they are not host paths, and DATABASE_URL is never exported into an operator's shell — so every command below runs through docker compose from the repo directory.

# 1. Database snapshot. Runs pg_dump inside the db container (the app image has no
#    postgres client), reading credentials from the compose environment.
mkdir -p ./backups
docker compose exec -T db \
  sh -c 'pg_dump -U "$POSTGRES_USER" "$POSTGRES_DB"' \
  | gzip > ./backups/db_$(date +%Y-%m-%d).sql.gz

# 2. Uploaded media (originals + derivatives) out of the named volume.
#    NOTE the mountpoint is /src, not /media: if the volume is ever empty, Docker
#    pre-populates a fresh mount from the image's own directory, and alpine ships a
#    /media containing cdrom/floppy/usb. Mounting somewhere the image has nothing
#    avoids silently tarring (and polluting the volume with) those.
docker run --rm \
  -v eventsnap_media_data:/src:ro -v "$PWD/backups":/backup \
  alpine tar czf /backup/media_$(date +%Y-%m-%d).tar.gz -C /src .

# 3. Export archives — a SEPARATE volume (see the security note below).
docker run --rm \
  -v eventsnap_exports_data:/src:ro -v "$PWD/backups":/backup \
  alpine tar czf /backup/exports_$(date +%Y-%m-%d).tar.gz -C /src .

# Weekly offsite sync of the three artefacts above.
rsync -az ./backups/ user@storagebox.example.com:backup/eventsnap/

Volume names are prefixed with the compose project name — eventsnap_ if you run from a directory called eventsnap. Confirm yours with docker volume ls.

Exports are deliberately NOT under /media. They live on their own exports_data volume (EXPORT_PATH=/exports) because a keepsake archive contains every photo in the event; keeping it outside the media tree is what stops it being reachable except through the ticket-gated download handler. Backing up only the media volume therefore loses every generated keepsake.


Running the backend test suite

cd backend

# The DB-backed integration tests (backend/tests/) need a live Postgres. `#[sqlx::test]` creates a
# throwaway database per test and runs backend/migrations/ into it — it does NOT touch this one's data.
docker run -d --name eventsnap-test-pg -p 55433:5432 \
  -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=eventsnap postgres:16-alpine

export DATABASE_URL=postgres://postgres:postgres@localhost:55433/eventsnap
cargo test        # 44 unit + 12 DB-backed
cargo clippy --all-targets -- -D warnings

cargo test requires DATABASE_URL — without it the integration tests panic rather than skip. That is deliberate. The riskiest code in this repo is SQL (the export epoch state machine, the atomic quota increment, the FOR SHARE upload lock), and for a long time not one line of it was executed by cargo test — every backend test was a pure-function test, so the tests clustered tightly around the code that could not break and stopped exactly where it started to. Tests that silently skip when the database is absent recreate that hole; they were meant to be a gate.

Running the E2E test suite

Playwright-based end-to-end tests live in e2e/. They spin up an isolated docker-compose stack (Postgres on :55432, Caddy on :3101) and exercise the SvelteKit frontend against the real Rust backend with rate limits disabled.

cd e2e
npm install
npm run install:browsers      # one-time
npm run stack:up              # bring up the test stack
npm run test:e2e              # full Phase 1 suite on chromium-desktop
npm run test:e2e:smoke        # cross-UA matrix (chromium, samsung-internet, webkit, firefox, …)
npm run stack:down            # tear it down

See e2e/README.md for the full UA matrix, Samsung Internet escalation tiers, and the Phase 2/3 roadmap.

CI runs this on every PR — see .github/workflows/e2e.yml (desktop and mobile projects), plus checks.yml for cargo test/clippy, the frontend unit tests, svelte-check and the e2e typecheck, and audit.yml for dependency advisories.

Playwright runs with retries: 0, including in CI. This repo's real bugs are races, and from the outside a race is indistinguishable from a flake — so a retry silently resolves that ambiguity in favour of "flake" every time. A flake here is a bug report; treat it as one.


Development Roadmap

Done:

  • Project blueprint & architecture
  • Monorepo scaffold (backend/, frontend/, Docker Compose)
  • DB schema + SQLx migrations (8 migrations through compression status + case-insensitive unique names)
  • Auth flow (join, JWT, 4-digit PIN with bcrypt + 3-attempt/15-min lockout, admin login)
  • Upload pipeline (multipart → compression worker via tokio::sync::Semaphore → SSE broadcast)
  • Client upload queue (IndexedDB, progress, retry, rate-limit auto-resume)
  • Gallery feed (list + grid toggle, SSE live updates, hashtag chips, in-memory search + autocomplete)
  • Camera capture (getUserMedia with front/back toggle, photo + MediaRecorder video)
  • Host Dashboard (event lock, gallery release, ban modal with hide-uploads choice, promote/demote, user search)
  • Admin Dashboard with inner tabs (Stats, Config, Export, Nutzer)
  • Export engine: streaming ZIP + SvelteKit-static HTML viewer (see docs/CONCEPT_HTML_VIEWER.md)
  • Custom rate limiter (per-endpoint, hot-reloadable from config table)
  • Mobile-first redesign (bottom nav + FAB, see docs/CONCEPT_MOBILE_UI.md)

Open:

  • Dynamic per-user storage quota enforcement (formula in PROJECT.md §12; only tracking exists today)
  • Own-upload deletion UI in the lightbox (backend route exists)
  • SSE delta-fetch on foreground reconnect (scaffolded in sse.ts, not wired)
  • Live diashow / slideshow mode — see docs/CONCEPT_DIASHOW.md
  • Individual file download button per post
  • Low-disk alert (< 10 GB free)
  • Event banner / cover image
  • Chunked resumable upload for files > 100 MB
  • Shared Tailwind config between main app and export-viewer
  • End-to-end test event (10+ real devices on cellular)

See docs/FEATURES.md for the up-to-date capability matrix by role. Speculative / v2+ ideas live in docs/IDEAS.md.


License

Private project — all rights reserved.

Description
A private, QR-code-accessed photo & video sharing platform for weddings, birthdays, and personal events — built for guests, run by you.
Readme 3.6 MiB
Languages
TypeScript 35.2%
Rust 31.6%
Svelte 21.9%
HTML 5.8%
JavaScript 3.3%
Other 2.2%