diff --git a/.env.example b/.env.example index 9cce303..071bc1b 100644 --- a/.env.example +++ b/.env.example @@ -253,3 +253,31 @@ TRACKER_TZ=Europe/London # TfL Unified API key (500 req/min); used by the Python hotel finder TFL_APP_KEY= + +# --- Garage object store (public /uploads/) ----------------------------------- +# See garage/garage.toml and DEPLOYMENT.md ("Garage"). Everything here is +# optional for the site to run: with S3_ENDPOINT blank the backend keeps +# writing uploads to the `uploads` volume exactly as before. +# +# Garage's own secrets, passed to the garage and garage-webui containers. +# Generate each with `openssl rand -hex 32`. The RPC secret must never change +# once the node has data; the admin token unlocks garage-webui's whole API. +GARAGE_RPC_SECRET= +GARAGE_ADMIN_TOKEN= +# The backend's S3 access, imported into Garage by garage/bootstrap.sh. +# Garage only accepts this shape: +# S3_ACCESS_KEY_ID "GK" + 24 hex (echo GK$(openssl rand -hex 12)) +# S3_SECRET_ACCESS_KEY 64 hex (openssl rand -hex 32) +S3_ACCESS_KEY_ID= +S3_SECRET_ACCESS_KEY= +# Blank keeps uploads on disk. Set to http://garage:3900 (after running +# garage/bootstrap.sh) to store new public uploads in the bucket; recreate the +# backend after changing it. If a write to Garage fails the backend logs it and +# writes to disk instead, and nginx serves the file from there. +S3_ENDPOINT= +# Optional; these defaults match garage.toml and bootstrap.sh. +S3_REGION=garage +S3_BUCKET=uploads +# Optional, bootstrap.sh only: the node's capacity in the layout. With one node +# it only has to be non-zero; it is not a quota. Default 20G. +GARAGE_CAPACITY= diff --git a/CLAUDE.md b/CLAUDE.md index 714247f..e596286 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,6 +62,8 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun **Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`. +**Uploads / Garage** (`garage/`): public uploads (`POST /api/messages/upload`, used by chat and the canvas editors) go to an S3 bucket in a self-hosted Garage container once `S3_ENDPOINT` is set in `.env`, and to the `uploads` volume until then — or whenever Garage refuses a write (`backend/services/file_store.go`). nginx serves `/uploads/` from the volume first and Garage's anonymous website endpoint second, so old URLs keep working and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7. + **Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. ## Backend Structure @@ -75,7 +77,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun - `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit - `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background) - `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns) -- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), the `.env` registry (`env_manager.go`), DB seeding. There is no Claude client in Go any more +- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), upload storage (`file_store.go`: Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more ## Frontend Structure diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 613fbc5..ffb3cab 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -69,6 +69,8 @@ backend icecast2 gitea sb sb-pub python | | | cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) | | dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no | | traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no | +| garage (S3 object store) | `garage` | 3900 S3, 3902 web, 3903 admin | none directly; `/uploads/` falls back to its web endpoint for files not on the volume | no | +| garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by nginx `auth_request`) | no | Container names come from `.env`, and nginx builds its upstreams from the same variables. **Renaming a `*_HOST` value renames the container and repoints nginx @@ -86,7 +88,7 @@ in one step — never change one without the other.** - **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with `resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a backend down (502s until it appears) instead of refusing to start. -- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/radio/admin/` and `/uploads/private/` are +- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure redirects to the SPA login. Most of these services have no auth of their own at that path; the job and activity trackers also check the session themselves. Their carve-outs, which a session @@ -99,9 +101,12 @@ in one step — never change one without the other.** them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the comment above `location /notes/` in `nginx_routes.conf.template`. -- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads` - volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so - user-supplied files cannot execute anything on our origin. +- **Uploads: disk first, then the bucket.** `/uploads/` is looked for on + the shared `uploads` volume and, if it is not there, fetched from Garage's + website endpoint (`@uploads_bucket`). Both paths add `nosniff`, + `Content-Disposition: inline` and a deny-all CSP, so user-supplied files + cannot execute anything on our origin. Disk first means Garage being down + only affects files that exist nowhere else; see "Garage" in §7. - **Rate limits** — see §6. --- @@ -326,7 +331,9 @@ Setup, once: | Volume | Holds | Losing it means | | ---------- | ----------------------------------------------------- | -------------------------------------------------- | | `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata | -| `uploads` | User-uploaded files (backend writes, nginx serves) | All uploaded images | +| `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files | +| `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) | +| `garage_data` | The bucket's object bytes | Every upload stored in Garage | | `vue_dist` | The built SPA | Nothing — rebuilt on next deploy | **Bind mounts** — live in the repo checkout on the host, survive everything short @@ -522,6 +529,63 @@ manually before Gitea will start: docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB" ``` +**Garage (the `/uploads/` bucket).** Public uploads can live in a Garage +bucket instead of the `uploads` volume. It is opt-in and every step can be +undone; nothing breaks while Garage is down or not set up: + +- the backend writes to disk until `S3_ENDPOINT` is set, and falls back to + disk (with a log line) whenever Garage refuses a write; +- nginx serves `/uploads/` from the volume first and asks Garage only for + files that are not there, and it boots without the `garage` container. + +Turning it on: + +1. Fill in `GARAGE_RPC_SECRET`, `GARAGE_ADMIN_TOKEN`, `S3_ACCESS_KEY_ID` and + `S3_SECRET_ACCESS_KEY` in `.env` **before** the deploy that adds the + containers (otherwise `garage` crash-loops on a blank secret until they + are set; nothing else is affected). `.env.example` says how to generate + each. +2. Deploy, then `garage/bootstrap.sh` (idempotent; it creates the layout, the + `uploads` bucket and the backend's key, and opens the bucket to the + website endpoint). +3. Set `S3_ENDPOINT=http://garage:3900` and `docker compose up -d backend`. + The backend logs `[upload] storing uploads in bucket uploads ...` on start. +4. Check: upload something through a canvas page or chat, then + `docker compose exec garage /garage bucket info uploads` shows the object + count going up, and the returned `/uploads/...` URL loads. + +Moving the old files in (optional — they are served from the volume anyway): + +``` +export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env) +docker run --rm --network web_server_app-network \ + -v web_server_uploads:/data:ro \ + -e AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY_ID" -e AWS_SECRET_ACCESS_KEY="$S3_SECRET_ACCESS_KEY" \ + -e AWS_DEFAULT_REGION=garage \ + amazon/aws-cli:2.38.0 s3 sync /data s3://uploads --exclude 'private/*' \ + --endpoint-url http://garage:3900 +``` + +The copies on the volume keep winning (disk first) until they are deleted, +which is also the rollback: leave them until the bucket has been trusted for a +while, then remove everything but `private/` from the volume. Until then, +deleting a file in garage-webui does not unpublish it if a disk copy exists. + +**Rollback:** blank `S3_ENDPOINT` and `docker compose up -d backend`. Files +written to the bucket in the meantime stay reachable as long as `garage` runs; +to drop Garage entirely, first copy them back +(`aws s3 sync s3://uploads /data` with the volume mounted read-write). + +**Managing files:** garage-webui at `/garage/` (site admin login). Files +uploaded there are public at `/uploads/` and skip the backend's type +checks; keep them under a prefix such as `media/`. Uploads through it are +capped at 2G by nginx. + +**Backups:** Garage here is one node on the same disk — it is not a backup. +Back up `garage_meta` and `garage_data` together (meta without data, or the +reverse, is useless); Garage also snapshots its metadata every 6h inside +`garage_meta`. + **Set up the CI runner on a fresh host:** ``` @@ -565,7 +629,7 @@ Documented, not fixed — each would change deploy behaviour. mounted to the same in-container path as the real wrapper. It is currently shadowed by an explicit file mount — fragile. Deleting it would be safe but is a file removal. -4. **The two `/uploads/` location blocks are still written twice** — once in +4. **The `/uploads/` location blocks (with `@uploads_bucket`) are still written twice** — once in `nginx.conf.template` and once in `nginx_dev_common.conf.template` — because production adds security headers inside an auth-gated block. Every other proxied route lives once in `nginx_routes.conf.template`, which both diff --git a/backend/README.md b/backend/README.md index 30aae45..0494534 100644 --- a/backend/README.md +++ b/backend/README.md @@ -226,6 +226,12 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends. (Steam). - **python_call.go** — `CallPython`, the one way to reach the Python service's internal routes. See [Calling the Python service](#calling-the-python-service). +- **file_store.go** — where public uploads are written. `NewUploadStore` + returns the disk store (`/backend/uploads/`) when `S3_ENDPOINT` is unset, + and otherwise the Garage bucket wrapped in `FallbackFileStore`, which logs + a failed S3 write and retries on disk. nginx serves `/uploads/` from disk + first and the bucket second, so either store's files work at the same URL. + Private attachments always stay on disk (nginx cannot gate a bucket). - **notes.go** — path-traversal-safe file lookup for the notes directory. - **seed.go** — dev-only test data. Creates an admin with the password `password`, so it must never run in production (`SEED_DB=true` is set only diff --git a/backend/go.mod b/backend/go.mod index 526a11f..b9a6c49 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -4,6 +4,9 @@ go 1.26 require ( github.com/99designs/gqlgen v0.17.95 + github.com/aws/aws-sdk-go-v2 v1.47.3 + github.com/aws/aws-sdk-go-v2/credentials v1.20.9 + github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 github.com/gin-gonic/gin v1.11.0 github.com/golang-jwt/jwt/v5 v5.3.0 github.com/gorilla/websocket v1.5.3 @@ -18,6 +21,15 @@ require ( require ( github.com/agnivade/levenshtein v1.2.1 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect + github.com/aws/smithy-go v1.28.5 // indirect github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect diff --git a/backend/go.sum b/backend/go.sum index 0970d2e..216c574 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -39,6 +39,30 @@ github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KO github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU= github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= +github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk= +github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ= +github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0= +github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys= +github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k= +github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= diff --git a/backend/graph/page_helpers.go b/backend/graph/page_helpers.go index 1d18c07..3e32206 100644 --- a/backend/graph/page_helpers.go +++ b/backend/graph/page_helpers.go @@ -32,7 +32,7 @@ var reservedFirstSegments = map[string]bool{ "automata": true, "hotels": true, "api": true, "py": true, "radio": true, "gitea": true, "notes": true, "sb": true, "jobs": true, "tracker": true, "usaco": true, "uploads": true, "img": true, "fonts": true, "pdf": true, - "sound": true, "assets": true, "internal": true, + "sound": true, "assets": true, "internal": true, "dozzle": true, "garage": true, } func validPageKey(key string) bool { diff --git a/backend/handlers/handle_message_upload.go b/backend/handlers/handle_message_upload.go index a5dd0bc..49bb21f 100644 --- a/backend/handlers/handle_message_upload.go +++ b/backend/handlers/handle_message_upload.go @@ -3,24 +3,28 @@ package handlers import ( "crypto/rand" "encoding/hex" - "io" + "log" "net/http" "os" "path/filepath" "strings" + "adam-french.co.uk/backend/services" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v5" ) -// Attachment upload for the chat. +// Attachment upload for the chat (and, through it, the canvas editors). // -// Files land in one of two directories. /backend/uploads/ is served by nginx -// at /uploads/ with no authentication, so anything written there is publicly -// reachable by URL — which is why the extension and content checks below -// matter. /backend/uploads/private/ holds attachments for private (admin-only) +// Files land in one of two places. Public files go to Store.Files: the Garage +// bucket when S3_ENDPOINT is configured, /backend/uploads/ otherwise (see +// services/file_store.go). Either way nginx serves them at /uploads/ with no +// authentication, so anything stored is publicly reachable by URL — which is +// why the extension and content checks below matter. +// /backend/uploads/private/ holds attachments for private (admin-only) // messages and is served at /uploads/private/ behind an nginx auth_request -// gate; only an admin may upload there. +// gate; only an admin may upload there. Private files always stay on disk: +// nginx cannot sign S3 requests, so it has no way to gate a bucket. // allowedExtensions is the upload allow-list, keyed by lower-cased extension. var allowedExtensions = map[string]bool{ @@ -42,10 +46,23 @@ var extensionToMIMEPrefix = map[string]string{ ".pdf": "application/pdf", ".txt": "text/", } -// publicUploadDir and privateUploadDir are the two destinations; the private -// one is created on demand because nothing else guarantees it exists. +// extensionContentType is the Content-Type a file is stored with. It comes +// from the (already allow-listed) extension rather than from sniffing, +// because sniffing is unreliable for exactly the audio and gif files the +// table above leaves unverified. It matters for the bucket: Garage serves +// back the stored type, where nginx serving from disk inferred its own. +var extensionContentType = map[string]string{ + ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp", + ".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg", ".ogg": "audio/ogg", + ".pdf": "application/pdf", ".txt": "text/plain; charset=utf-8", +} + +// PublicUploadDir and privateUploadDir are the two directories on the shared +// `uploads` volume; the private one is created on demand because nothing else +// guarantees it exists. PublicUploadDir is exported for main, which hands it +// to services.NewUploadStore as the disk store (or the bucket's fallback). const ( - publicUploadDir = "/backend/uploads/" + PublicUploadDir = "/backend/uploads/" privateUploadDir = "/backend/uploads/private/" ) @@ -118,20 +135,6 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) { } filename := hex.EncodeToString(b) + ext - uploadDir := publicUploadDir - urlPrefix := "/uploads/" - if private { - uploadDir = privateUploadDir - urlPrefix = "/uploads/private/" - // 0755 so nginx (a different user) can traverse the directory to - // serve the files once its auth_request gate has approved. - if err := os.MkdirAll(uploadDir, 0755); err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"}) - return - } - } - dest := filepath.Join(uploadDir, filename) - // Reopened rather than rewound: the earlier handle was closed after // sniffing, and multipart files may be backed by either memory or a temp // file, so a fresh reader is the simplest correct option. @@ -142,14 +145,28 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) { } defer src.Close() - out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"}) - return + var dest services.FileStore + urlPrefix := "/uploads/" + if private { + urlPrefix = "/uploads/private/" + // 0755 so nginx (a different user) can traverse the directory to + // serve the files once its auth_request gate has approved. + if err := os.MkdirAll(privateUploadDir, 0755); err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"}) + return + } + dest = services.DiskFileStore{Dir: privateUploadDir} + } else { + dest = store.Files + // A Store built without one (the tests, mostly) keeps the old + // behaviour rather than panicking. + if dest == nil { + dest = services.DiskFileStore{Dir: PublicUploadDir} + } } - defer out.Close() - if _, err := io.Copy(out, src); err != nil { + if err := dest.Put(ctx.Request.Context(), filename, extensionContentType[ext], src, file.Size); err != nil { + log.Printf("[upload] storing %s failed: %v", filename, err) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"}) return } diff --git a/backend/handlers/handlers_pure_test.go b/backend/handlers/handlers_pure_test.go index bf4b459..670406d 100644 --- a/backend/handlers/handlers_pure_test.go +++ b/backend/handlers/handlers_pure_test.go @@ -288,6 +288,17 @@ func TestUploadAllowLists(t *testing.T) { } }) + t.Run("every allowed extension has a stored Content-Type", func(t *testing.T) { + // Garage serves back the type the upload was stored with; a missing + // entry would store an empty type and the browser would be left to + // guess under nosniff — i.e. refuse to render it. + for ext := range allowedExtensions { + if extensionContentType[ext] == "" { + t.Errorf("%q is allowed but has no Content-Type", ext) + } + } + }) + t.Run("audio extensions are content-unverified by design", func(t *testing.T) { // http.DetectContentType is unreliable for these, so a missing entry // means "extension allowed, content not verified". Adding one would diff --git a/backend/handlers/store.go b/backend/handlers/store.go index 400f6dc..bfa38a6 100644 --- a/backend/handlers/store.go +++ b/backend/handlers/store.go @@ -38,6 +38,12 @@ type Store struct { // services.CallPython: reading a rowing display photo (handle_rowing.go). PythonURL string + // Where public uploads are stored: the Garage bucket with a disk + // fallback, or the disk alone when S3 is not configured + // (services.NewUploadStore). nil means the disk, so a Store built in a + // test needs no setup. + Files services.FileStore + // Cached "recently played" tracks, refreshed at most once a minute by the // GraphQL spotifyRecent resolver. A pointer to a slice so that nil can // mean "never fetched" distinctly from "fetched, empty". diff --git a/backend/main.go b/backend/main.go index 07d141f..ac14300 100644 --- a/backend/main.go +++ b/backend/main.go @@ -128,11 +128,27 @@ func main() { } pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort) + // UPLOAD STORAGE + // Public uploads go to the Garage bucket once S3_ENDPOINT is set, and to + // the shared `uploads` volume until then (and whenever Garage refuses a + // write). See services/file_store.go. Region and bucket default to what + // garage/garage.toml and garage/bootstrap.sh set up. + s3Region := os.Getenv("S3_REGION") + if s3Region == "" { + s3Region = "garage" + } + s3Bucket := os.Getenv("S3_BUCKET") + if s3Bucket == "" { + s3Bucket = "uploads" + } + s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")} + files := services.NewUploadStore(s3Config, handlers.PublicUploadDir) + // 5 login attempts per IP per minute, applied by both the REST handler // and the GraphQL login mutation. Nginx rate-limits the login route too. loginLimiter := services.NewRateLimiter(5, time.Minute) - store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL} + store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Files: files} // Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in // the Gin context, so the order in the admin group matters. diff --git a/backend/services/file_store.go b/backend/services/file_store.go new file mode 100644 index 0000000..c87b5ef --- /dev/null +++ b/backend/services/file_store.go @@ -0,0 +1,146 @@ +package services + +import ( + "context" + "fmt" + "io" + "log" + "os" + "path/filepath" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +// Where uploaded files are written. The upload handler +// (handlers/handle_message_upload.go) validates a file and picks its name; a +// FileStore only stores the bytes under that name. +// +// Public uploads go to the Garage bucket when S3_ENDPOINT is set, and to the +// local `uploads` volume otherwise. Either way they are served at +// /uploads/: nginx looks on the volume first and falls back to the +// bucket (see the /uploads/ location in nginx.conf.template). That ordering +// is what makes every failure here survivable: if Garage is down or +// misconfigured, FallbackFileStore writes to disk instead, and nginx finds +// the file there without anyone having to know which store took it. + +// FileStore stores one file under key. r is a ReadSeeker because the S3 +// client must hash the body before sending it over plain HTTP, and because +// FallbackFileStore rewinds it to retry; a multipart.File satisfies it. +type FileStore interface { + Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error +} + +// DiskFileStore writes files into Dir, which must exist. +type DiskFileStore struct{ Dir string } + +func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error { + // 0644 so nginx, a different user, can read what the backend wrote. + out, err := os.OpenFile(filepath.Join(d.Dir, key), os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return err + } + if _, err := io.Copy(out, r); err != nil { + out.Close() + return err + } + return out.Close() +} + +// S3FileStore writes files into one bucket of an S3-compatible server. +type S3FileStore struct { + client *s3.Client + bucket string +} + +// S3Config is the S3_* block of .env. +type S3Config struct { + Endpoint string // e.g. http://garage:3900 + Region string // must match garage.toml's s3_region + Bucket string + AccessKeyID string + SecretAccessKey string +} + +// s3Timeout bounds one upload. Uploads are capped at 10MB and Garage is on +// the same Docker network, so anything near this is a hang, and the fallback +// to disk is better than holding the request open. +const s3Timeout = 30 * time.Second + +func NewS3FileStore(cfg S3Config) *S3FileStore { + client := s3.New(s3.Options{ + BaseEndpoint: aws.String(cfg.Endpoint), + Region: cfg.Region, + Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""), + // Garage addresses buckets by path (/bucket/key); virtual-host style + // would need a DNS name per bucket. + UsePathStyle: true, + // Recent SDKs add CRC32 checksums to every PUT by default. Only send + // them where S3 requires them, which is what third-party servers + // handle reliably. + RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, + ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, + }) + return &S3FileStore{client: client, bucket: cfg.Bucket} +} + +func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error { + ctx, cancel := context.WithTimeout(ctx, s3Timeout) + defer cancel() + + // ContentType matters: Garage serves back exactly what is stored here, + // and nginx no longer infers a type from the extension for files it + // fetches from the bucket. + _, err := s.client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + Body: r, + ContentLength: aws.Int64(size), + ContentType: aws.String(contentType), + }) + if err != nil { + return fmt.Errorf("s3 put %s/%s: %w", s.bucket, key, err) + } + return nil +} + +// FallbackFileStore tries Primary and, if that fails, logs it and writes to +// Fallback instead. The upload still succeeds and its URL still works, so a +// Garage outage costs a log line rather than broken uploads. +type FallbackFileStore struct { + Primary FileStore + Fallback FileStore +} + +func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error { + err := f.Primary.Put(ctx, key, contentType, r, size) + if err == nil { + return nil + } + log.Printf("[upload] primary store failed, writing %s to fallback: %v", key, err) + if _, seekErr := r.Seek(0, io.SeekStart); seekErr != nil { + return fmt.Errorf("rewinding for fallback after %v: %w", err, seekErr) + } + return f.Fallback.Put(ctx, key, contentType, r, size) +} + +// NewUploadStore picks the store for public uploads. With no S3 endpoint +// configured it is the disk alone, exactly the behaviour before Garage, so +// deploying this code changes nothing until .env opts in. An endpoint with +// missing credentials is a configuration mistake: it is logged and the disk +// is used rather than failing every upload. +func NewUploadStore(cfg S3Config, diskDir string) FileStore { + disk := DiskFileStore{Dir: diskDir} + if cfg.Endpoint == "" { + log.Printf("[upload] S3_ENDPOINT unset; storing uploads on disk in %s", diskDir) + return disk + } + if cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" || cfg.Bucket == "" { + log.Printf("[upload] S3_ENDPOINT is set but S3_BUCKET or the S3 key is missing; storing uploads on disk in %s", diskDir) + return disk + } + log.Printf("[upload] storing uploads in bucket %s at %s (disk fallback: %s)", cfg.Bucket, cfg.Endpoint, diskDir) + return FallbackFileStore{Primary: NewS3FileStore(cfg), Fallback: disk} +} diff --git a/backend/services/file_store_test.go b/backend/services/file_store_test.go new file mode 100644 index 0000000..651afe8 --- /dev/null +++ b/backend/services/file_store_test.go @@ -0,0 +1,77 @@ +package services + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +// Covered here: which store NewUploadStore picks, the disk store, and the +// fallback path — including against a real S3 client talking to a server +// that refuses the write, since "Garage said no" is the case the fallback +// exists for. +// +// Not covered: a successful PutObject against Garage. That needs the garage +// container; it is checked by hand in the stack (see DEPLOYMENT.md, "Garage"). + +func TestNewUploadStore(t *testing.T) { + dir := t.TempDir() + + if _, ok := NewUploadStore(S3Config{}, dir).(DiskFileStore); !ok { + t.Error("no S3 endpoint should mean the disk store") + } + if _, ok := NewUploadStore(S3Config{Endpoint: "http://garage:3900", Bucket: "uploads"}, dir).(DiskFileStore); !ok { + t.Error("an endpoint without credentials should fall back to the disk store") + } + full := S3Config{Endpoint: "http://garage:3900", Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"} + if _, ok := NewUploadStore(full, dir).(FallbackFileStore); !ok { + t.Error("a full S3 config should mean the bucket with a disk fallback") + } +} + +func TestDiskFileStorePut(t *testing.T) { + dir := t.TempDir() + body := []byte("hello") + if err := (DiskFileStore{Dir: dir}).Put(context.Background(), "a.txt", "text/plain", bytes.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(dir, "a.txt")) + if err != nil || !bytes.Equal(got, body) { + t.Fatalf("read back %q, %v; want %q", got, err, body) + } +} + +func TestFallbackWhenBucketRefuses(t *testing.T) { + // 403 rather than 500: the SDK retries 5xx with backoff, which would only + // make the test slow. Either way PutObject returns an error. + var hits int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits++ + // Drain the body so a test failure can't be a half-read request. + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusForbidden) + })) + defer srv.Close() + + dir := t.TempDir() + store := NewUploadStore(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir) + + body := bytes.Repeat([]byte("x"), 4096) + if err := store.Put(context.Background(), "f.bin", "application/octet-stream", bytes.NewReader(body), int64(len(body))); err != nil { + t.Fatalf("Put should succeed through the fallback, got %v", err) + } + if hits == 0 { + t.Fatal("the bucket was never tried") + } + // The whole file, not just what was left after the S3 attempt read it: + // this is what the rewind in FallbackFileStore is for. + got, err := os.ReadFile(filepath.Join(dir, "f.bin")) + if err != nil || !bytes.Equal(got, body) { + t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(body)) + } +} diff --git a/docker-compose.yml b/docker-compose.yml index ab91647..666624e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -65,8 +65,17 @@ volumes: dbdata: # File upload — PERSISTENT. Written by the backend at /backend/uploads, # served read-only by nginx at /uploads/. Shared so nginx can serve user - # uploads without proxying through the Go process. + # uploads without proxying through the Go process. Since Garage, it holds + # the uploads from before the bucket, private attachments (always), and any + # upload the backend wrote here because Garage refused it; nginx looks here + # first and only then in the bucket. uploads: + # Garage object store — PERSISTENT, both. garage_meta is the metadata DB + # (buckets, keys, the object index, the cluster layout); garage_data is the + # object bytes. Lose meta and the bytes in data are unreadable, so back up + # the two together. A fresh pair needs garage/bootstrap.sh run once. + garage_meta: + garage_data: # Vue build — EPHEMERAL in spirit but a named volume for handoff: the # one-shot `vue` container writes the built SPA here and exits; nginx mounts # it at /etc/nginx/html and serves it. Repopulated on every rebuild. @@ -618,6 +627,74 @@ services: volumes: - /var/run/docker.sock:/var/run/docker.sock:ro + # S3-compatible object store holding public uploads (the `uploads` bucket). + # The backend writes to it on :3900 once S3_ENDPOINT is set in .env; nginx + # reads it anonymously on :3902 for /uploads/ files not found on the + # `uploads` volume; garage-webui manages it via :3903. Nothing is published + # to the host. Config is garage/garage.toml (no secrets in it); the two + # secrets come from .env through the explicit list below. + # + # Nothing depends on this container being up. nginx is deliberately NOT + # given it in depends_on: its upstream is a variable, so a missing or + # crash-looping garage costs a 502 on bucket-only files, never nginx's + # boot; and the backend falls back to the volume when a write fails. + # + # FIRST RUN: garage/bootstrap.sh (layout, bucket, key, website access). + # The image is FROM scratch — no shell, so no in-container init script and + # a healthcheck that calls the binary itself. + garage: + image: dxflrs/garage:v2.4.1 + container_name: garage + restart: always + networks: + - app-network + environment: + - GARAGE_RPC_SECRET=${GARAGE_RPC_SECRET} + - GARAGE_ADMIN_TOKEN=${GARAGE_ADMIN_TOKEN} + volumes: + - ./garage/garage.toml:/etc/garage.toml:ro + - garage_meta:/var/lib/garage/meta + - garage_data:/var/lib/garage/data + healthcheck: + test: ["CMD", "/garage", "status"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 10s + + # Admin web UI for Garage, served at /garage/ behind the nginx admin gate. + # Manages buckets and keys, and browses/uploads/deletes objects. Its own + # login (AUTH_USER_PASS) is left unset because nginx's auth_request already + # requires the site admin — and it holds the admin token, so never publish + # its port. It reads the s3/web settings from garage.toml; the token comes + # from .env instead, since the file has none. + # + # Files uploaded here land in the PUBLIC bucket and are served at + # /uploads/ with none of the backend's checks. Put hand-managed media + # under a prefix (e.g. media/) so it can't collide with the backend's + # random hex names. + garage-webui: + image: khairul169/garage-webui:1.1.0 + container_name: garage-webui + restart: always + depends_on: + - garage + networks: + - app-network + environment: + - BASE_PATH=/garage + - API_BASE_URL=http://garage:3903 + - API_ADMIN_KEY=${GARAGE_ADMIN_TOKEN} + - S3_ENDPOINT_URL=http://garage:3900 + - S3_REGION=garage + # The image has no /tmp, and Go spools any multipart upload over 32MB to + # a temp file there, so without this every large upload fails with + # "open /tmp/multipart-…: no such file or directory". + tmpfs: + - /tmp + volumes: + - ./garage/garage.toml:/etc/garage.toml:ro + # Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI # server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to # main, executed by the act_runner that lives outside docker (gitea-runner/). diff --git a/garage/bootstrap.sh b/garage/bootstrap.sh new file mode 100755 index 0000000..e8cec7e --- /dev/null +++ b/garage/bootstrap.sh @@ -0,0 +1,109 @@ +#!/bin/sh +# ============================================================================= +# One-time setup of the `garage` container. Run from the repo root, on the +# host, once the container is up: +# +# garage/bootstrap.sh +# +# Idempotent: every step checks before acting, so re-running it is harmless. +# Garage keeps all of this in the garage_meta volume, so it is only needed on +# a fresh volume — once on stpvm, and again whenever a dev stack starts from +# nothing. +# +# WHY A HOST SCRIPT +# The dxflrs/garage image is FROM scratch: a single binary, no shell. There +# is nothing to run an init script with inside it, so this drives the +# binary through `docker compose exec`. +# +# WHAT IT DOES +# 1. Gives the single node a role in the cluster layout. Until it has one, +# Garage accepts connections but refuses to store anything. +# 2. Creates the bucket (S3_BUCKET, default `uploads`). +# 3. Imports the backend's access key from .env (S3_ACCESS_KEY_ID / +# S3_SECRET_ACCESS_KEY). Importing rather than letting Garage generate +# one keeps .env the single source of truth: a wiped volume comes back +# with the same credentials and the backend needs no change. +# 4. Grants that key read+write on the bucket. garage-webui also browses +# with it: it borrows the first key that has access to a bucket. +# 5. Opens the bucket on the website endpoint, which is what nginx's +# /uploads/ fallback reads from, anonymously. +# +# ENV / .env +# S3_ACCESS_KEY_ID required; "GK" + 24 hex chars +# S3_SECRET_ACCESS_KEY required; 64 hex chars +# S3_BUCKET optional, default uploads +# GARAGE_CAPACITY optional, default 20G. Only weights data placement +# between nodes; with one node it is no quota. +# COMPOSE optional, default `docker compose`. Set it to add +# the dev override, e.g. +# COMPOSE="docker compose -f docker-compose.yml -f docker-compose.dev.yml" +# ============================================================================= +set -eu + +COMPOSE=${COMPOSE:-docker compose} + +# Read one KEY=value from .env without sourcing it: .env is not guaranteed to +# be valid shell (unquoted spaces, `$` in secrets). A value already in the +# environment wins, so the script also runs without a .env. +envval() { + eval "current=\${$1:-}" + if [ -n "$current" ]; then + printf '%s' "$current" + return + fi + [ -f .env ] || return 0 + grep -E "^$1=" .env | tail -n 1 | cut -d= -f2- | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'$/\1/" +} + +garage() { + $COMPOSE exec -T garage /garage "$@" +} + +KEY_ID=$(envval S3_ACCESS_KEY_ID) +SECRET=$(envval S3_SECRET_ACCESS_KEY) +BUCKET=$(envval S3_BUCKET) +BUCKET=${BUCKET:-uploads} +CAPACITY=$(envval GARAGE_CAPACITY) +CAPACITY=${CAPACITY:-20G} +KEY_NAME=site-backend + +# Garage rejects other shapes at import time with a less helpful message. +if ! printf '%s' "$KEY_ID" | grep -Eq '^GK[0-9a-f]{24}$'; then + echo "S3_ACCESS_KEY_ID must be GK followed by 24 hex chars (try: echo GK\$(openssl rand -hex 12))" >&2 + exit 1 +fi +if ! printf '%s' "$SECRET" | grep -Eq '^[0-9a-f]{64}$'; then + echo "S3_SECRET_ACCESS_KEY must be 64 hex chars (try: openssl rand -hex 32)" >&2 + exit 1 +fi + +# 1. Layout. `node id -q` prints "@"; the id is what +# `layout assign` takes. +if garage layout show 2>/dev/null | grep -q "No nodes currently have a role"; then + NODE_ID=$(garage node id -q 2>/dev/null | cut -d@ -f1) + echo "Assigning node $(printf '%s' "$NODE_ID" | cut -c1-16) (capacity $CAPACITY)" + garage layout assign -z dc1 -c "$CAPACITY" "$NODE_ID" + garage layout apply --version 1 +else + echo "Layout already applied" +fi + +# 2. Bucket. +if garage bucket info "$BUCKET" >/dev/null 2>&1; then + echo "Bucket $BUCKET exists" +else + garage bucket create "$BUCKET" +fi + +# 3. Key. +if garage key info "$KEY_ID" >/dev/null 2>&1; then + echo "Key $KEY_ID exists" +else + garage key import -n "$KEY_NAME" --yes "$KEY_ID" "$SECRET" +fi + +# 4 and 5 are idempotent in Garage itself. +garage bucket allow --read --write "$BUCKET" --key "$KEY_ID" +garage bucket website --allow "$BUCKET" + +echo "Garage ready: bucket $BUCKET, key $KEY_ID" diff --git a/garage/garage.toml b/garage/garage.toml new file mode 100644 index 0000000..79ad487 --- /dev/null +++ b/garage/garage.toml @@ -0,0 +1,51 @@ +# ============================================================================= +# Garage — the S3-compatible object store behind /uploads/. +# +# One node, one copy of everything (replication_factor = 1): this is storage +# on the same disk as the rest of the site, not a resilience layer, so the +# garage_meta and garage_data volumes still need backing up like the others. +# +# NO SECRETS IN THIS FILE. It is committed and mounted read-only into both +# `garage` and `garage-webui`. rpc_secret and admin_token come from the +# GARAGE_RPC_SECRET and GARAGE_ADMIN_TOKEN environment variables, which Garage +# reads in place of the config keys. +# +# Binds are 0.0.0.0 rather than Garage's usual [::]: containers on a bridge +# network without IPv6 may refuse an IPv6 bind. None of these ports is +# published to the host; everything reaches them over app-network. +# +# PORTS +# 3900 S3 API. The backend writes uploads here (signed with the key that +# garage/bootstrap.sh imports); garage-webui browses through it. +# 3901 RPC between Garage nodes. Only this node talks to itself. +# 3902 Website endpoint. Serves a bucket ANONYMOUSLY, choosing it from the +# Host header: "", so nginx's /uploads/ fallback +# sends `Host: uploads.web.garage`. Only buckets that bootstrap.sh +# opened with `garage bucket website --allow` are served. +# 3903 Admin API, used by garage-webui and authenticated by admin_token. +# ============================================================================= +metadata_dir = "/var/lib/garage/meta" +data_dir = "/var/lib/garage/data" +db_engine = "lmdb" +# LMDB can be left unreadable by a crash mid-write; a periodic snapshot of +# the metadata is what `garage meta` restores from. +metadata_auto_snapshot_interval = "6h" + +replication_factor = 1 + +rpc_bind_addr = "0.0.0.0:3901" +rpc_public_addr = "127.0.0.1:3901" + +[s3_api] +api_bind_addr = "0.0.0.0:3900" +# Any string works; it only has to match what clients sign with (S3_REGION). +s3_region = "garage" +root_domain = ".s3.garage" + +[s3_web] +bind_addr = "0.0.0.0:3902" +root_domain = ".web.garage" +index = "index.html" + +[admin] +api_bind_addr = "0.0.0.0:3903" diff --git a/nginx/nginx.conf.template b/nginx/nginx.conf.template index 7f6ecee..88edd00 100644 --- a/nginx/nginx.conf.template +++ b/nginx/nginx.conf.template @@ -291,14 +291,44 @@ http { add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always; } - # User-uploaded files, served straight off the shared `uploads` volume - # so the Go process never has to stream them. Because these are - # attacker-supplied bytes on our own origin, three headers neutralise - # them: nosniff stops content-type guessing, Content-Disposition inline - # keeps them from being treated as downloads, and the locked-down CSP - # means even an uploaded .html can run no script and load no resource. + # User-uploaded files, served by nginx so the Go process never has to + # stream them. Because these are attacker-supplied bytes on our own + # origin, three headers neutralise them: nosniff stops content-type + # guessing, Content-Disposition inline keeps them from being treated + # as downloads, and the locked-down CSP means even an uploaded .html + # can run no script and load no resource. + # + # TWO PLACES, DISK FIRST. A file is looked for on the shared `uploads` + # volume and, only if it is not there, fetched from the Garage bucket + # (@uploads_bucket). Disk first is deliberate: everything uploaded + # before Garage, and anything the backend wrote to disk because Garage + # refused it (services/file_store.go), is served exactly as before + # with Garage not involved at all — Garage being down can only affect + # files that exist nowhere else. The cost is shadowing: a file present + # in both is served from disk, so deleting it in the bucket alone does + # nothing until the disk copy goes too. + # `root /` rather than `alias`: the volume is mounted at /uploads, so + # the URI already is the path, and try_files is unreliable with alias. location /uploads/ { - alias /uploads/; + root /; + try_files $uri @uploads_bucket; + include /etc/nginx/security_headers.conf; + add_header X-Content-Type-Options nosniff always; + add_header Content-Disposition "inline" always; + add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always; + } + + # Garage's website endpoint, which serves the bucket anonymously and + # picks it from the Host header (garage/garage.toml: s3_web). The + # bucket is reachable only over app-network, so this location is the + # only public way in. Range requests pass through, so video seeks. + # The headers are repeated, not inherited: a named location is its own + # location. If the garage container is absent the variable upstream + # fails per request (502) — nginx itself still starts. + location @uploads_bucket { + rewrite ^/uploads/(.*)$ /$1 break; + proxy_pass $upstream_garage_web; + proxy_set_header Host uploads.web.garage; include /etc/nginx/security_headers.conf; add_header X-Content-Type-Options nosniff always; add_header Content-Disposition "inline" always; diff --git a/nginx/nginx_dev_common.conf.template b/nginx/nginx_dev_common.conf.template index 0d0a67b..c30a534 100644 --- a/nginx/nginx_dev_common.conf.template +++ b/nginx/nginx_dev_common.conf.template @@ -47,14 +47,24 @@ add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always; } - # Both /uploads/ blocks are the production ones MINUS + # The /uploads/ blocks (and @uploads_bucket) are the production ones MINUS # `include security_headers.conf`: that file carries HSTS, which must # never be sent from localhost. That one line is why they are not in # the shared route table (see WHAT DOES NOT in # nginx_routes.conf.template). Keep the rest in step with # nginx.conf.template. location /uploads/ { - alias /uploads/; + root /; + try_files $uri @uploads_bucket; + add_header X-Content-Type-Options nosniff always; + add_header Content-Disposition "inline" always; + add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always; + } + + location @uploads_bucket { + rewrite ^/uploads/(.*)$ /$1 break; + proxy_pass $upstream_garage_web; + proxy_set_header Host uploads.web.garage; add_header X-Content-Type-Options nosniff always; add_header Content-Disposition "inline" always; add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always; diff --git a/nginx/nginx_routes.conf.template b/nginx/nginx_routes.conf.template index 7fca9fb..2ad4408 100644 --- a/nginx/nginx_routes.conf.template +++ b/nginx/nginx_routes.conf.template @@ -83,6 +83,11 @@ set $upstream_usaco http://usaco:8080; # And the Dozzle log viewer's. set $upstream_dozzle http://dozzle:8080; + # Garage: its website endpoint (the /uploads/ bucket fallback, used by + # the @uploads_bucket location in nginx.conf.template and + # nginx_dev_common.conf.template) and the garage-webui admin UI. + set $upstream_garage_web http://garage:3902; + set $upstream_garage_webui http://garage-webui:3909; # ---- Backend API ----------------------------------------------------- # Two patterns repeat through every proxied location below: @@ -199,6 +204,31 @@ proxy_set_header X-Forwarded-Proto $scheme; } + # garage-webui: buckets, keys and a file browser for the Garage object + # store. It holds Garage's admin token, so it sits behind the admin + # `auth_request` like /dozzle/, and its own login is left unset (one + # login, not two). No prefix-strip rewrite: BASE_PATH=/garage makes it + # serve under the prefix itself. The body limit is lifted past the + # server-wide 50M so videos can be uploaded through it, and request + # buffering is off so a large upload streams through instead of + # landing on nginx's disk first. + location = /garage { + return 301 /garage/; + } + + location /garage/ { + auth_request /internal/auth/admin-validate; + error_page 401 403 = @auth_denied; + client_max_body_size 2G; + proxy_request_buffering off; + proxy_pass $upstream_garage_webui; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + # The icecast ADMIN UI (/radio/admin/*) is a full station-control # surface — kick sources, change metadata — protected only by the # icecast admin password, and it was reachable from the public @@ -502,7 +532,7 @@ return 301 /jobs/job-capture.user.js; } - # ---- Admin gate (/sb/, /jobs/, /tracker/, /radio/admin/, /uploads/private/) ---- + # ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/, /uploads/private/) ---- # (/uploads/private/ is declared in the including template, not here; # it points at the two locations below by name.) # `auth_request` makes nginx fire a subrequest here before serving the @@ -518,8 +548,18 @@ # not coming. # Cookie $http_cookie - the whole point: forward the session # cookie so the backend can validate it. + # client_max_body_size 0 - the subrequest is checked against THIS + # location's limit using the original + # request's Content-Length, so without it + # a gated location with a higher limit + # (/garage/, 2G) 413s inside the auth + # check and the user sees a 500. Safe: + # the location is internal and never + # reads a body; the real limit is the + # gated location's own. location = /internal/auth/admin-validate { internal; + client_max_body_size 0; rewrite ^ /auth/validate-admin break; proxy_pass $upstream_backend; proxy_pass_request_body off;