Give uploads one path end to end, and serve /uploads/ from Garage first
Frontend: src/uploads.js is the one way to store or show a file (uploadFile, ACCEPT, kindOf, isUploadUrl, tagFor, mediaSize). Chat, the box editor, canvas drops and the background editor all use it; views/home3/upload.js and the chat store's own axios call are gone. Backend: POST /api/uploads (was /messages/upload) is a thin wrapper over services.Uploads.Save, which owns validation, naming and storage. The three per-extension maps are now one UploadTypes table, and a refused file is an *UploadError whose message is safe to show. nginx now fetches /uploads/ from Garage first and falls back to the volume on a 404 or any 5xx, so the bucket is the source of truth and deleting a file in garage-webui unpublishes it, while a Garage outage still only affects bucket-only files. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -62,7 +62,7 @@ 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.
|
||||
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth 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.
|
||||
|
||||
@@ -77,12 +77,13 @@ 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`), upload storage (`file_store.go`: Garage bucket with disk fallback), 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`), uploads (`uploads.go`: validation, naming, Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more
|
||||
|
||||
## Frontend Structure
|
||||
|
||||
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
|
||||
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
|
||||
- `src/uploads.js` — storing and showing uploaded files: `uploadFile(file)` → public `/uploads/...` URL, `ACCEPT` for file pickers, `kindOf`/`tagFor`/`isUploadUrl`/`mediaSize`. Every upload goes through it
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices
|
||||
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). `/stp` is `views/home3/Home3.vue`: a canvas of admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type. The canvas (`views/home3/BoxCanvas.vue`) is reusable per page key: the landing page (`/`) is one too, and admin-created `Page`s (e.g. shrines) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional `Background`, set from the canvas's Background button and painted by `DefaultLayout`. See "The /stp canvas" in `vue/README.md`
|
||||
- `src/components/` — reusable UI components
|
||||
|
||||
+20
-17
@@ -101,12 +101,13 @@ 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: disk first, then the bucket.** `/uploads/<f>` 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`,
|
||||
- **Uploads: the bucket first, then disk.** `/uploads/<f>` is fetched from
|
||||
Garage's website endpoint and, if Garage has no such file or is down, from
|
||||
the shared `uploads` volume (`@uploads_disk`). 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.
|
||||
cannot execute anything on our origin. The bucket is the source of truth;
|
||||
a Garage outage only affects files that exist nowhere else. See "Garage"
|
||||
in §7.
|
||||
- **Rate limits** — see §6.
|
||||
|
||||
---
|
||||
@@ -415,7 +416,7 @@ rate"_. Anything beyond the burst gets an immediate **503**.
|
||||
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
|
||||
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
|
||||
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
|
||||
| `upload` | 30/min | 20 | `/api/messages/upload` | Uploads hit disk; bounds how fast one IP fills the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. |
|
||||
| `upload` | 30/min | 20 | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. |
|
||||
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
|
||||
|
||||
The WebSocket endpoint is deliberately unlimited: a socket is one long-lived
|
||||
@@ -529,14 +530,15 @@ 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:
|
||||
**Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket,
|
||||
with the `uploads` volume as a safety net. 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.
|
||||
- nginx serves `/uploads/` from Garage and falls back to the volume when
|
||||
Garage has no such file or is unreachable, and it boots without the
|
||||
`garage` container.
|
||||
|
||||
Turning it on:
|
||||
|
||||
@@ -554,7 +556,8 @@ Turning it on:
|
||||
`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):
|
||||
Moving the old files in (so they show in garage-webui, and so the bucket
|
||||
holds everything):
|
||||
|
||||
```
|
||||
export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env)
|
||||
@@ -566,10 +569,10 @@ docker run --rm --network web_server_app-network \
|
||||
--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.
|
||||
The copies left on the volume are then only a fallback for when Garage is
|
||||
down, and the rollback. One catch: a file deleted in garage-webui is still
|
||||
served from its disk copy, if it has one. Once the bucket has been trusted for
|
||||
a while, remove everything but `private/` from the volume.
|
||||
|
||||
**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;
|
||||
@@ -629,7 +632,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 `/uploads/` location blocks (with `@uploads_bucket`) are still written twice** — once in
|
||||
4. **The `/uploads/` location blocks (with `@uploads_disk`) 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
|
||||
|
||||
+11
-7
@@ -172,7 +172,7 @@ for the things GraphQL cannot do:
|
||||
| --- | --- |
|
||||
| `/auth/*` | cookie handling and the status-code-only admin probe |
|
||||
| `/spotify/callback` | OAuth providers redirect a *browser* here |
|
||||
| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
||||
| `/uploads`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
||||
| `/notes/*path` | streams a file download, not JSON |
|
||||
| `/ws` | WebSocket upgrade |
|
||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||
@@ -226,12 +226,16 @@ 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).
|
||||
- **uploads.go** — every stored file. `Uploads.Save(ctx, fileHeader, private)`
|
||||
validates against `UploadTypes` (extension, stored Content-Type, content
|
||||
sniff) and `MaxUploadSize`, names the file randomly, stores it and returns
|
||||
its `/uploads/...` URL; an `*UploadError` is the uploader's fault and safe
|
||||
to show them. Public files go to the Garage bucket wrapped in
|
||||
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or
|
||||
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
|
||||
(nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket
|
||||
first and disk second, so either store's files work at the same URL. A new
|
||||
handler that takes a file calls `store.Uploads.Save`.
|
||||
- **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
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"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 (and, through it, the canvas editors).
|
||||
//
|
||||
// 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. 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{
|
||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
|
||||
".mp4": true, ".webm": true, ".mp3": true, ".ogg": true,
|
||||
".pdf": true, ".txt": true,
|
||||
}
|
||||
|
||||
// extensionToMIMEPrefix cross-checks the sniffed content type against the
|
||||
// claimed extension, to stop e.g. HTML being served from a .png URL.
|
||||
//
|
||||
// The audio extensions (.mp3, .ogg) and .gif are deliberately absent:
|
||||
// http.DetectContentType's answers for them are unreliable enough to reject
|
||||
// legitimate files, so a missing entry means "extension allowed, content not
|
||||
// verified".
|
||||
var extensionToMIMEPrefix = map[string]string{
|
||||
".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/",
|
||||
".mp4": "video/", ".webm": "video/",
|
||||
".pdf": "application/pdf", ".txt": "text/",
|
||||
}
|
||||
|
||||
// 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/"
|
||||
privateUploadDir = "/backend/uploads/private/"
|
||||
)
|
||||
|
||||
// UploadMessageFile backs POST /messages/upload (login required) and returns
|
||||
// the URL of the stored file, which the client then sends over the WebSocket
|
||||
// as a message's fileUrl.
|
||||
//
|
||||
// The multipart form takes an optional "private" field: "true" stores the file
|
||||
// under /uploads/private/ for use as a private message's attachment. That is
|
||||
// admin-only, because private messages themselves are — an attachment URL
|
||||
// leaking out is the same disclosure as the message leaking out.
|
||||
func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
private := ctx.PostForm("private") == "true"
|
||||
if private && !requestIsAdmin(ctx) {
|
||||
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
||||
return
|
||||
}
|
||||
|
||||
const maxSize = 10 << 20 // 10MB
|
||||
if file.Size > maxSize {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
|
||||
return
|
||||
}
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(file.Filename))
|
||||
if !allowedExtensions[ext] {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file type not allowed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate actual content type matches extension
|
||||
f, err := file.Open()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
return
|
||||
}
|
||||
// 512 bytes is exactly what http.DetectContentType inspects; reading more
|
||||
// would be wasted. A single Read may return fewer bytes than asked for,
|
||||
// which is fine — sniffing works on a short prefix — so only a read that
|
||||
// produced nothing at all is an error.
|
||||
buf := make([]byte, 512)
|
||||
n, err := f.Read(buf)
|
||||
f.Close()
|
||||
if err != nil && n == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file content"})
|
||||
return
|
||||
}
|
||||
detectedType := http.DetectContentType(buf[:n])
|
||||
|
||||
expectedPrefix, ok := extensionToMIMEPrefix[ext]
|
||||
if ok && !strings.HasPrefix(detectedType, expectedPrefix) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file content does not match extension"})
|
||||
return
|
||||
}
|
||||
|
||||
// The uploaded name is discarded entirely in favour of 16 random bytes
|
||||
// from crypto/rand. That kills path traversal and collisions in one go,
|
||||
// and makes the resulting URL unguessable. Only the extension is carried
|
||||
// over, and it has already been checked against the allow-list.
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"})
|
||||
return
|
||||
}
|
||||
filename := hex.EncodeToString(b) + ext
|
||||
|
||||
// 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.
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
return
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
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}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
|
||||
}
|
||||
|
||||
// requestIsAdmin reports whether the caller's access token carries admin=true.
|
||||
//
|
||||
// This route sits in the `protected` group, which runs AuthMiddlewear but not
|
||||
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
|
||||
// public attachments — so the admin check is made here from the same
|
||||
// "userClaims" value AdminMiddleware would have read.
|
||||
func requestIsAdmin(ctx *gin.Context) bool {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
mapClaims, ok := claims.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
|
||||
return ok && admin
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Upload backs POST /uploads (login required): the one endpoint the frontend
|
||||
// stores a file through (vue/src/uploads.js). Multipart form:
|
||||
//
|
||||
// file the file (required)
|
||||
// private "true" to store it as an admin-only chat attachment
|
||||
//
|
||||
// It answers {"url": "/uploads/<name>"}, or {"error": "..."} with 400 when
|
||||
// the file was refused (wrong type, too large) and 500 when storing failed.
|
||||
// Validation, naming and storage are all services.Uploads.Save; this handler
|
||||
// only reads the form and decides who may use `private`.
|
||||
//
|
||||
// `private` is admin-only because private messages themselves are: an
|
||||
// attachment URL leaking out is the same disclosure as the message leaking.
|
||||
func (store *Store) Upload(ctx *gin.Context) {
|
||||
private := ctx.PostForm("private") == "true"
|
||||
if private && !requestIsAdmin(ctx) {
|
||||
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
||||
return
|
||||
}
|
||||
|
||||
url, err := store.Uploads.Save(ctx.Request.Context(), file, private)
|
||||
var rejected *services.UploadError
|
||||
switch {
|
||||
case errors.As(err, &rejected):
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": rejected.Message})
|
||||
case err != nil:
|
||||
log.Printf("[upload] storing %s failed: %v", file.Filename, err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
default:
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": url})
|
||||
}
|
||||
}
|
||||
|
||||
// requestIsAdmin reports whether the caller's access token carries admin=true.
|
||||
//
|
||||
// This route sits in the `protected` group, which runs AuthMiddlewear but not
|
||||
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
|
||||
// public attachments — so the admin check is made here from the same
|
||||
// "userClaims" value AdminMiddleware would have read.
|
||||
func requestIsAdmin(ctx *gin.Context) bool {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
mapClaims, ok := claims.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
|
||||
return ok && admin
|
||||
}
|
||||
@@ -14,23 +14,21 @@ import (
|
||||
|
||||
// What is deliberately NOT covered here, and why:
|
||||
//
|
||||
// - Every handler method (Login, UploadMessageFile, the radio file movers,
|
||||
// - Every handler method (Login, Upload, the radio file movers,
|
||||
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
|
||||
// multipart request, the container's /backend/... directories, or a paid
|
||||
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
|
||||
// CI.
|
||||
// - The radio/chat upload filename sanitisation itself. It is written inline
|
||||
// inside the handler bodies rather than in a helper, so testing it would
|
||||
// mean either driving a full multipart upload against the real upload
|
||||
// directories or refactoring production code. Neither was in scope, so the
|
||||
// part that *is* extractable — the extension allow-lists those handlers
|
||||
// gate on — is covered as a table contract below instead.
|
||||
// - The radio upload's filename sanitisation. It is written inline in the
|
||||
// handler, so only the extension allow-list it gates on is covered, as a
|
||||
// table contract below. (The site's general uploads — validation, naming,
|
||||
// storage — are services.Uploads, tested in services/uploads_test.go.)
|
||||
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
|
||||
// reach the database on the refresh path.
|
||||
//
|
||||
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
|
||||
// three shared caches, the admin claim check on the upload trust boundary, and
|
||||
// the upload allow-list tables.
|
||||
// the radio allow-list.
|
||||
|
||||
// --- Spotify OAuth CSRF nonces -------------------------------------------
|
||||
|
||||
@@ -253,68 +251,20 @@ func TestRequestIsAdmin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The allow-list tables are the upload trust boundary's data. Testing them as
|
||||
// data catches the realistic failure: someone adding an executable or markup
|
||||
// extension, or adding an extension to the MIME map without allowing it (which
|
||||
// would be dead configuration).
|
||||
func TestUploadAllowLists(t *testing.T) {
|
||||
t.Run("dangerous extensions stay off the chat allow-list", func(t *testing.T) {
|
||||
// Served by nginx from a public directory with no auth, so anything
|
||||
// the browser will execute or render as markup must not be storable.
|
||||
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".php", ".exe", ".sh", ".xml", ""} {
|
||||
if allowedExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed chat upload extension", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allow-list keys are lower-cased with a leading dot", func(t *testing.T) {
|
||||
// The handlers look up strings.ToLower(filepath.Ext(...)), so a key in
|
||||
// The radio allow-list is the radio upload's trust boundary. Testing it as
|
||||
// data catches the realistic failure: someone adding a non-audio or malformed
|
||||
// extension.
|
||||
func TestRadioAllowList(t *testing.T) {
|
||||
for ext := range allowedAudioExtensions {
|
||||
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
|
||||
// any other shape is unreachable.
|
||||
for _, m := range []map[string]bool{allowedExtensions, allowedAudioExtensions} {
|
||||
for ext := range m {
|
||||
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
|
||||
t.Errorf("malformed allow-list key %q", ext)
|
||||
}
|
||||
}
|
||||
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
|
||||
t.Errorf("malformed allow-list key %q", ext)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("every MIME-checked extension is also allowed", func(t *testing.T) {
|
||||
for ext := range extensionToMIMEPrefix {
|
||||
if !allowedExtensions[ext] {
|
||||
t.Errorf("%q has a MIME prefix but is not an allowed extension, so the check never runs", ext)
|
||||
}
|
||||
}
|
||||
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
|
||||
if allowedAudioExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed radio upload extension", ext)
|
||||
}
|
||||
})
|
||||
|
||||
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
|
||||
// start rejecting legitimate uploads.
|
||||
for _, ext := range []string{".mp3", ".ogg"} {
|
||||
if _, ok := extensionToMIMEPrefix[ext]; ok {
|
||||
t.Errorf("%q should not be MIME-checked", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("radio allow-list is audio only", func(t *testing.T) {
|
||||
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
|
||||
if allowedAudioExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed radio upload extension", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,11 +38,9 @@ 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
|
||||
// Stores uploaded files and says where they are served
|
||||
// (services.Uploads.Save). Used by the Upload handler.
|
||||
Uploads *services.Uploads
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
|
||||
+8
-8
@@ -128,11 +128,11 @@ 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.
|
||||
// UPLOADS
|
||||
// Public uploads go to the Garage bucket (and to the shared `uploads`
|
||||
// volume when Garage refuses a write, or when S3_ENDPOINT is unset);
|
||||
// private ones to the volume. See services/uploads.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"
|
||||
@@ -142,13 +142,13 @@ func main() {
|
||||
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)
|
||||
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
|
||||
|
||||
// 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, Files: files}
|
||||
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, Uploads: uploads}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
@@ -189,7 +189,7 @@ func main() {
|
||||
// /ws is deliberately outside the protected group: chat is public, and
|
||||
// the handler checks the cookies itself to decide admin privileges.
|
||||
r.GET("/ws", store.ConnectWebSocket)
|
||||
protected.POST("/messages/upload", store.UploadMessageFile)
|
||||
protected.POST("/uploads", store.Upload)
|
||||
|
||||
// NOTES
|
||||
admin.GET("/notes/*path", store.GetNoteFile)
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
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/<name>: 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}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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"
|
||||
)
|
||||
|
||||
// Uploaded files: everything the site stores from a user and serves back at
|
||||
// /uploads/. One entry point for any handler that takes a file:
|
||||
//
|
||||
// url, err := store.Uploads.Save(ctx, fileHeader, private)
|
||||
//
|
||||
// Save validates the file against UploadTypes and MaxUploadSize, gives it a
|
||||
// random name, stores it, and returns the URL to put in the page. An
|
||||
// *UploadError is the uploader's fault and its message is safe to show them;
|
||||
// any other error is ours (log it, answer 500).
|
||||
//
|
||||
// WHERE FILES GO
|
||||
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
|
||||
// the `uploads` volume as a fallback for when Garage refuses a write. nginx
|
||||
// mirrors that: /uploads/<name> is fetched from the bucket first and the
|
||||
// volume second (nginx.conf.template), so the URL is the same wherever the
|
||||
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
|
||||
// the only store.
|
||||
// Private files (admin-only chat attachments) always go to the volume, under
|
||||
// /uploads/private/, which nginx gates behind an admin check. nginx can't
|
||||
// sign S3 requests, so it has no way to gate a bucket.
|
||||
//
|
||||
// Everything public is reachable by anyone who has the URL, with no login.
|
||||
// That is why the type checks below are strict, and why names are random.
|
||||
|
||||
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
|
||||
// disk or the bucket; nginx rate-limits the route as well.
|
||||
const MaxUploadSize = 10 << 20 // 10MB
|
||||
|
||||
// UploadType describes one allowed file extension.
|
||||
type UploadType struct {
|
||||
// ContentType is stored with the file and served back with it. Garage
|
||||
// returns exactly this, and the browser renders by it: nginx adds
|
||||
// `nosniff`, so a wrong type means the file doesn't display.
|
||||
ContentType string
|
||||
// SniffPrefix is what http.DetectContentType must report for the file's
|
||||
// first 512 bytes, so that e.g. HTML can't be uploaded as a .png. Empty
|
||||
// means "not checked": DetectContentType is too unreliable for audio and
|
||||
// gif files, and checking would reject legitimate ones.
|
||||
SniffPrefix string
|
||||
}
|
||||
|
||||
// UploadTypes is the allow-list, keyed by lower-cased extension with its dot.
|
||||
// Nothing a browser would execute or render as markup (.html, .svg, .js, ...)
|
||||
// may ever be added: these files are served from our own origin. The
|
||||
// frontend's file pickers (vue/src/uploads.js, ACCEPT) list the same types.
|
||||
var UploadTypes = map[string]UploadType{
|
||||
".jpg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
|
||||
".jpeg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
|
||||
".png": {ContentType: "image/png", SniffPrefix: "image/"},
|
||||
".gif": {ContentType: "image/gif"},
|
||||
".webp": {ContentType: "image/webp", SniffPrefix: "image/"},
|
||||
".mp4": {ContentType: "video/mp4", SniffPrefix: "video/"},
|
||||
".webm": {ContentType: "video/webm", SniffPrefix: "video/"},
|
||||
".mp3": {ContentType: "audio/mpeg"},
|
||||
".ogg": {ContentType: "audio/ogg"},
|
||||
".pdf": {ContentType: "application/pdf", SniffPrefix: "application/pdf"},
|
||||
".txt": {ContentType: "text/plain; charset=utf-8", SniffPrefix: "text/"},
|
||||
}
|
||||
|
||||
// UploadError is a rejected upload: the uploader's mistake, with a message
|
||||
// meant for them. The handler answers 400 with it.
|
||||
type UploadError struct{ Message string }
|
||||
|
||||
func (e *UploadError) Error() string { return e.Message }
|
||||
|
||||
var (
|
||||
ErrUploadTooLarge = &UploadError{"file too large (the limit is 10MB)"}
|
||||
ErrUploadType = &UploadError{"file type not allowed"}
|
||||
ErrUploadContent = &UploadError{"file content does not match extension"}
|
||||
ErrUploadUnreadable = &UploadError{"failed to read file content"}
|
||||
)
|
||||
|
||||
// Uploads stores files. Build it with NewUploads.
|
||||
type Uploads struct {
|
||||
public FileStore
|
||||
private FileStore
|
||||
}
|
||||
|
||||
// URL prefixes the files are served under; nginx owns both paths.
|
||||
const (
|
||||
publicURLPrefix = "/uploads/"
|
||||
privateURLPrefix = "/uploads/private/"
|
||||
)
|
||||
|
||||
// NewUploads picks the stores. publicDir and privateDir are directories on the
|
||||
// shared `uploads` volume (/backend/uploads/ and its private/ subdirectory in
|
||||
// the container).
|
||||
//
|
||||
// With no S3 endpoint the public store is the volume alone, the behaviour
|
||||
// before Garage. An endpoint with missing credentials is a configuration
|
||||
// mistake: it is logged and the volume is used rather than failing every
|
||||
// upload.
|
||||
func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
|
||||
disk := DiskFileStore{Dir: publicDir}
|
||||
u := &Uploads{public: disk, private: DiskFileStore{Dir: privateDir}}
|
||||
|
||||
switch {
|
||||
case cfg.Endpoint == "":
|
||||
log.Printf("[upload] S3_ENDPOINT unset; storing uploads on disk in %s", publicDir)
|
||||
case 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", publicDir)
|
||||
default:
|
||||
log.Printf("[upload] storing uploads in bucket %s at %s (disk fallback: %s)", cfg.Bucket, cfg.Endpoint, publicDir)
|
||||
u.public = FallbackFileStore{Primary: NewS3FileStore(cfg), Fallback: disk}
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// Save validates and stores one uploaded file and returns its URL
|
||||
// (/uploads/<name>, or /uploads/private/<name>). Authorisation is the
|
||||
// caller's job: only an admin may save a private file.
|
||||
func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bool) (string, error) {
|
||||
if fh.Size > MaxUploadSize {
|
||||
return "", ErrUploadTooLarge
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(fh.Filename))
|
||||
kind, ok := UploadTypes[ext]
|
||||
if !ok {
|
||||
return "", ErrUploadType
|
||||
}
|
||||
|
||||
f, err := fh.Open()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("opening upload: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if kind.SniffPrefix != "" {
|
||||
// 512 bytes is all http.DetectContentType looks at. A short read is
|
||||
// fine; sniffing works on a prefix, so only an empty file is an error.
|
||||
buf := make([]byte, 512)
|
||||
n, err := io.ReadFull(f, buf)
|
||||
if n == 0 {
|
||||
return "", ErrUploadUnreadable
|
||||
}
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
return "", fmt.Errorf("reading upload: %w", err)
|
||||
}
|
||||
if !strings.HasPrefix(http.DetectContentType(buf[:n]), kind.SniffPrefix) {
|
||||
return "", ErrUploadContent
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return "", fmt.Errorf("rewinding upload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The uploaded name is thrown away for 16 random bytes. That rules out
|
||||
// path traversal and collisions in one go, and makes the URL unguessable.
|
||||
// Only the extension survives, and it is on the allow-list.
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generating filename: %w", err)
|
||||
}
|
||||
name := hex.EncodeToString(b) + ext
|
||||
|
||||
store, prefix := u.public, publicURLPrefix
|
||||
if private {
|
||||
store, prefix = u.private, privateURLPrefix
|
||||
}
|
||||
if err := store.Put(ctx, name, kind.ContentType, f, fh.Size); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return prefix + name, nil
|
||||
}
|
||||
|
||||
// ---- Stores ----------------------------------------------------------------
|
||||
|
||||
// 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, creating it if needed.
|
||||
type DiskFileStore struct{ Dir string }
|
||||
|
||||
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
|
||||
// 0755 and 0644 so nginx, a different user, can reach and read the files.
|
||||
if err := os.MkdirAll(d.Dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
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()
|
||||
|
||||
_, 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 (nginx
|
||||
// looks in both places), 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)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Covered here: the type table (the upload trust boundary's data), Save's
|
||||
// validation, naming and routing, which store NewUploads picks, and the
|
||||
// fallback — including against a real S3 client talking to a server that
|
||||
// refuses the write, since "Garage said no" is the case it exists for.
|
||||
//
|
||||
// Not covered: a successful PutObject against Garage. That needs the garage
|
||||
// container; it is checked by hand in the stack (DEPLOYMENT.md, "Garage").
|
||||
|
||||
// fileHeader builds the *multipart.FileHeader a handler would get from
|
||||
// ctx.FormFile, by round-tripping a real multipart body.
|
||||
func fileHeader(t *testing.T, name string, content []byte) *multipart.FileHeader {
|
||||
t.Helper()
|
||||
var body bytes.Buffer
|
||||
w := multipart.NewWriter(&body)
|
||||
part, _ := w.CreateFormFile("file", name)
|
||||
part.Write(content)
|
||||
w.Close()
|
||||
form, err := multipart.NewReader(&body, w.Boundary()).ReadForm(32 << 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { form.RemoveAll() })
|
||||
return form.File["file"][0]
|
||||
}
|
||||
|
||||
func pngBytes() []byte {
|
||||
var b bytes.Buffer
|
||||
png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 2, 2)))
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// recordingStore remembers what it was asked to store.
|
||||
type recordingStore struct {
|
||||
key, contentType string
|
||||
body []byte
|
||||
}
|
||||
|
||||
func (r *recordingStore) Put(_ context.Context, key, contentType string, rd io.ReadSeeker, _ int64) error {
|
||||
r.key, r.contentType = key, contentType
|
||||
r.body, _ = io.ReadAll(rd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestUploadTypes(t *testing.T) {
|
||||
t.Run("nothing executable or markup is allowed", func(t *testing.T) {
|
||||
// Served from our own origin with no login, so anything a browser
|
||||
// would run or render as a page must never be storable.
|
||||
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".mjs", ".php", ".exe", ".sh", ".xml", ".xhtml", ""} {
|
||||
if _, ok := UploadTypes[ext]; ok {
|
||||
t.Errorf("%q must not be an allowed upload type", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for ext, kind := range UploadTypes {
|
||||
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
|
||||
t.Errorf("key %q: Save looks up the lower-cased extension with its dot, so this is unreachable", ext)
|
||||
}
|
||||
if kind.ContentType == "" {
|
||||
// Stored and served as-is; under nosniff an empty type renders nothing.
|
||||
t.Errorf("%q has no ContentType", ext)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("audio and gif are not sniffed", func(t *testing.T) {
|
||||
// DetectContentType misreads these; checking them would reject
|
||||
// legitimate files.
|
||||
for _, ext := range []string{".mp3", ".ogg", ".gif"} {
|
||||
if UploadTypes[ext].SniffPrefix != "" {
|
||||
t.Errorf("%q should not be content-checked", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestUploadsSave(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
public, private := &recordingStore{}, &recordingStore{}
|
||||
u := &Uploads{public: public, private: private}
|
||||
|
||||
t.Run("public file", func(t *testing.T) {
|
||||
img := pngBytes()
|
||||
url, err := u.Save(ctx, fileHeader(t, "Holiday Photo.PNG", img), false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The name is replaced by 32 hex chars; the lower-cased extension stays.
|
||||
if !strings.HasPrefix(url, "/uploads/") || len(strings.TrimPrefix(url, "/uploads/")) != 32+len(".png") || !strings.HasSuffix(url, ".png") {
|
||||
t.Errorf("url = %q, want /uploads/<32 hex>.png", url)
|
||||
}
|
||||
if public.key != strings.TrimPrefix(url, "/uploads/") || public.contentType != "image/png" {
|
||||
t.Errorf("stored as %q (%q)", public.key, public.contentType)
|
||||
}
|
||||
// The whole file, not just what was left after sniffing.
|
||||
if !bytes.Equal(public.body, img) {
|
||||
t.Errorf("stored %d bytes, want %d", len(public.body), len(img))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("private file goes to the private store", func(t *testing.T) {
|
||||
url, err := u.Save(ctx, fileHeader(t, "note.txt", []byte("hello")), true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(url, "/uploads/private/") || private.key == "" {
|
||||
t.Errorf("url = %q, private store got %q", url, private.key)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rejections", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
file string
|
||||
content []byte
|
||||
want error
|
||||
}{
|
||||
{"disallowed type", "page.html", []byte("<html></html>"), ErrUploadType},
|
||||
{"markup dressed as an image", "evil.png", []byte("<html><script>alert(1)</script></html>"), ErrUploadContent},
|
||||
{"empty sniffed file", "empty.png", nil, ErrUploadUnreadable},
|
||||
{"too large", "big.mp3", make([]byte, MaxUploadSize+1), ErrUploadTooLarge},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
_, err := u.Save(ctx, fileHeader(t, c.file, c.content), false)
|
||||
if !errors.Is(err, c.want) {
|
||||
t.Errorf("err = %v, want %v", err, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewUploads(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
if _, ok := NewUploads(S3Config{}, dir, dir).public.(DiskFileStore); !ok {
|
||||
t.Error("no S3 endpoint should mean the disk store")
|
||||
}
|
||||
if _, ok := NewUploads(S3Config{Endpoint: "http://garage:3900", Bucket: "uploads"}, dir, dir).public.(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"}
|
||||
u := NewUploads(full, dir, dir)
|
||||
if _, ok := u.public.(FallbackFileStore); !ok {
|
||||
t.Error("a full S3 config should mean the bucket with a disk fallback")
|
||||
}
|
||||
if _, ok := u.private.(DiskFileStore); !ok {
|
||||
t.Error("private files must always stay on disk")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskFileStorePut(t *testing.T) {
|
||||
// A directory that doesn't exist yet: the private one is created on demand.
|
||||
dir := filepath.Join(t.TempDir(), "private")
|
||||
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++
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
u := NewUploads(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir, filepath.Join(dir, "private"))
|
||||
|
||||
img := pngBytes()
|
||||
url, err := u.Save(context.Background(), fileHeader(t, "pic.png", img), false)
|
||||
if err != nil {
|
||||
t.Fatalf("Save should succeed through the fallback, got %v", err)
|
||||
}
|
||||
if hits == 0 {
|
||||
t.Fatal("the bucket was never tried")
|
||||
}
|
||||
// The whole file, not just what the S3 attempt left unread: this is what
|
||||
// the rewind in FallbackFileStore is for.
|
||||
got, err := os.ReadFile(filepath.Join(dir, strings.TrimPrefix(url, "/uploads/")))
|
||||
if err != nil || !bytes.Equal(got, img) {
|
||||
t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(img))
|
||||
}
|
||||
}
|
||||
+7
-6
@@ -66,9 +66,9 @@ volumes:
|
||||
# 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. 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.
|
||||
# private attachments (always), the uploads from before the bucket, and any
|
||||
# upload the backend wrote here because Garage refused it. nginx serves
|
||||
# /uploads/ from the bucket first and only then from here.
|
||||
uploads:
|
||||
# Garage object store — PERSISTENT, both. garage_meta is the metadata DB
|
||||
# (buckets, keys, the object index, the cluster layout); garage_data is the
|
||||
@@ -629,15 +629,16 @@ services:
|
||||
|
||||
# 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
|
||||
# serves /uploads/ from it anonymously on :3902, falling back to 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.
|
||||
# crash-looping garage only makes bucket-only files 404 (everything on the
|
||||
# volume is still served), 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
|
||||
|
||||
+2
-2
@@ -25,8 +25,8 @@
|
||||
# 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.
|
||||
# 5. Opens the bucket on the website endpoint, which is what nginx serves
|
||||
# /uploads/ from, anonymously.
|
||||
#
|
||||
# ENV / .env
|
||||
# S3_ACCESS_KEY_ID required; "GK" + 24 hex chars
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@
|
||||
# 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: "<bucket><root_domain>", so nginx's /uploads/ fallback
|
||||
# Host header: "<bucket><root_domain>", so nginx's /uploads/ location
|
||||
# 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.
|
||||
|
||||
+31
-24
@@ -298,37 +298,44 @@ http {
|
||||
# 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.
|
||||
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the
|
||||
# Garage bucket's website endpoint, which serves the bucket
|
||||
# anonymously and picks it by the Host header (garage/garage.toml:
|
||||
# s3_web); the bucket is reachable only over app-network, so this is
|
||||
# the only public way in. If Garage has no such file, or is down, the
|
||||
# request falls through to the shared `uploads` volume
|
||||
# (@uploads_disk), which holds uploads from before Garage and anything
|
||||
# the backend wrote there because Garage refused it
|
||||
# (backend/services/uploads.go). So the bucket is the source of truth
|
||||
# — deleting a file in garage-webui unpublishes it unless a disk copy
|
||||
# exists — while a Garage outage only costs files that are nowhere
|
||||
# else.
|
||||
# proxy_connect_timeout 2s - Garage is on the same bridge network,
|
||||
# so a slow connect means it is down; fall back quickly rather
|
||||
# than after the 60s default.
|
||||
# proxy_intercept_errors + error_page - Garage's 404 and any 5xx
|
||||
# (including nginx's own 502 when the garage container doesn't
|
||||
# exist) become a look at the disk instead.
|
||||
# Range requests pass through either way, so video seeks.
|
||||
# @uploads_disk sees the URI after the rewrite (/<name>), hence
|
||||
# `root /uploads`. The headers are repeated, not inherited: a named
|
||||
# location is its own location.
|
||||
location /uploads/ {
|
||||
root /;
|
||||
try_files $uri @uploads_bucket;
|
||||
rewrite ^/uploads/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_garage_web;
|
||||
proxy_set_header Host uploads.web.garage;
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_intercept_errors on;
|
||||
error_page 404 500 502 503 504 = @uploads_disk;
|
||||
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;
|
||||
location @uploads_disk {
|
||||
root /uploads;
|
||||
try_files $uri =404;
|
||||
include /etc/nginx/security_headers.conf;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Content-Disposition "inline" always;
|
||||
|
||||
@@ -47,24 +47,27 @@
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
# The /uploads/ blocks (and @uploads_bucket) are the production ones MINUS
|
||||
# The /uploads/ blocks (and @uploads_disk) 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/ {
|
||||
root /;
|
||||
try_files $uri @uploads_bucket;
|
||||
rewrite ^/uploads/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_garage_web;
|
||||
proxy_set_header Host uploads.web.garage;
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_intercept_errors on;
|
||||
error_page 404 500 502 503 504 = @uploads_disk;
|
||||
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;
|
||||
location @uploads_disk {
|
||||
root /uploads;
|
||||
try_files $uri =404;
|
||||
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;
|
||||
|
||||
@@ -83,8 +83,8 @@
|
||||
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
|
||||
# Garage: its website endpoint (where /uploads/ is served from; see the
|
||||
# /uploads/ 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;
|
||||
@@ -115,7 +115,7 @@
|
||||
# breaking auth behind TLS termination.
|
||||
#
|
||||
# Ordering matters: nginx picks the longest matching prefix location,
|
||||
# so the specific /ws, /auth/login and /messages/upload blocks (and
|
||||
# so the specific /ws, /auth/login and /uploads blocks (and
|
||||
# production's /graphql block in nginx.conf.template) win over the
|
||||
# catch-all <PREFIX>/ block regardless of file order.
|
||||
location $BACKEND_ENDPOINT {
|
||||
@@ -154,7 +154,7 @@
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
location $BACKEND_ENDPOINT/uploads {
|
||||
limit_req zone=upload burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
|
||||
+23
-2
@@ -141,10 +141,31 @@ passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
|
||||
| --- | --- |
|
||||
| reading or writing the site's data model | `gql()`, from a store |
|
||||
| doing list/create/update/delete on one GraphQL type | a store built with `createCrudStore()` |
|
||||
| calling a backend REST route (uploads, admin tooling, OAuth start) | `api` |
|
||||
| storing a file, or showing one that was stored | `uploadFile()` and friends from `@/uploads` |
|
||||
| calling a backend REST route (admin tooling, OAuth start) | `api` |
|
||||
| reading the Python service's NDJSON streams | `views/hotels/hotelsStream.js` — incremental `fetch`, not `api` |
|
||||
| probing `/radio/stream` | bare `axios.head` — it is Icecast, not the API |
|
||||
|
||||
### Uploading files
|
||||
|
||||
`src/uploads.js` is the one way to store a file:
|
||||
|
||||
```js
|
||||
import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
|
||||
|
||||
// <input type="file" :accept="ACCEPT.images" @change="onPick">
|
||||
const url = await uploadFile(file); // "/uploads/3f9c….png", public and permanent
|
||||
```
|
||||
|
||||
It posts to `/api/uploads`; the backend (`backend/services/uploads.go`) owns
|
||||
the allowed types, the 10MB limit and the file name, and stores the file in
|
||||
Garage. A refused file rejects with an `ApiError` whose message can be shown
|
||||
as-is. `kindOf(url)` says image/video/audio/file, `tagFor(url)` gives the
|
||||
markup for a box, `isUploadUrl(url)` checks a URL from someone else before
|
||||
rendering it, and `mediaSize(file)` reads an image or video's dimensions.
|
||||
`{ private: true }` (admin only) is for private chat attachments; never use
|
||||
it for anything shown in a canvas box, whose sandboxed frame has no cookie.
|
||||
|
||||
New views should not call `gql()` or `axios` directly (a few small admin forms
|
||||
still call `gql()` for a one-off mutation). A view that needs data gets a
|
||||
store; a view that needs a REST route calls `api`.
|
||||
@@ -255,7 +276,7 @@ renders any page's boxes.
|
||||
`<body>`.
|
||||
Image and video files dropped onto the canvas in edit mode are uploaded and
|
||||
each becomes an unframed box at the drop point. "Insert upload" stores a
|
||||
file through the chat's public upload endpoint and puts an `<img>`/`<video>`
|
||||
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
|
||||
tag for it at the cursor. Starter HTML is in `templates.js`; links in a box
|
||||
need `target="_top"` or `_blank` (the Link templates set it), or they open
|
||||
inside the frame. A canvas given a `starter` has an import button in edit
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useMessagesStore } from "@/stores/messages";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import Link from "@/components/text/Link.vue";
|
||||
import { ACCEPT, isUploadUrl, kindOf } from "@/uploads";
|
||||
|
||||
const messagesStore = useMessagesStore();
|
||||
const authStore = useAuthStore();
|
||||
@@ -116,28 +117,8 @@ async function onFileSelected(e) {
|
||||
fileInput.value.value = "";
|
||||
}
|
||||
|
||||
function isImageUrl(url) {
|
||||
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
|
||||
}
|
||||
|
||||
function isVideoUrl(url) {
|
||||
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
||||
}
|
||||
|
||||
// Public attachments live under /uploads/; attachments on private messages are
|
||||
// written under /uploads/private/, which nginx gates behind an admin check.
|
||||
const UPLOAD_PREFIXES = ["/uploads/", "/uploads/private/"];
|
||||
|
||||
/** Only render attachments the backend served from its own upload directory —
|
||||
* the fileUrl arrives over the socket and is otherwise attacker-controlled.
|
||||
* A strict prefix allowlist, so absolute ("https://evil/uploads/x") and
|
||||
* protocol-relative ("//evil/uploads/x") URLs are rejected; "..", which could
|
||||
* otherwise escape the directory, is rejected outright. */
|
||||
function isSafeFileUrl(url) {
|
||||
if (typeof url !== "string") return false;
|
||||
if (url.includes("..")) return false;
|
||||
return UPLOAD_PREFIXES.some((prefix) => url.startsWith(prefix));
|
||||
}
|
||||
// Attachments are rendered only if isUploadUrl() accepts them: the fileUrl
|
||||
// arrives over the socket and is otherwise attacker-controlled.
|
||||
|
||||
// NOTE: a module-level /g regex carries `lastIndex` between calls. It is safe
|
||||
// here only because parseMessageParts() below always runs exec() to completion
|
||||
@@ -262,21 +243,28 @@ onUnmounted(() => {
|
||||
>
|
||||
<span v-else>{{ part.value }}</span>
|
||||
</template>
|
||||
<template v-if="message.fileUrl && isSafeFileUrl(message.fileUrl)">
|
||||
<template v-if="isUploadUrl(message.fileUrl)">
|
||||
<img
|
||||
v-if="isImageUrl(message.fileUrl)"
|
||||
v-if="kindOf(message.fileUrl) === 'image'"
|
||||
:src="message.fileUrl"
|
||||
alt="Uploaded image"
|
||||
loading="lazy"
|
||||
class="w-full max-w-full rounded block"
|
||||
/>
|
||||
<video
|
||||
v-else-if="isVideoUrl(message.fileUrl)"
|
||||
v-else-if="kindOf(message.fileUrl) === 'video'"
|
||||
:src="message.fileUrl"
|
||||
controls
|
||||
preload="none"
|
||||
class="w-full max-w-full max-h-48 rounded block"
|
||||
/>
|
||||
<audio
|
||||
v-else-if="kindOf(message.fileUrl) === 'audio'"
|
||||
:src="message.fileUrl"
|
||||
controls
|
||||
preload="none"
|
||||
class="w-full max-w-full block"
|
||||
/>
|
||||
<Link
|
||||
v-else
|
||||
bare
|
||||
@@ -299,6 +287,7 @@ onUnmounted(() => {
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
:accept="ACCEPT.any"
|
||||
class="hidden"
|
||||
@change="onFileSelected"
|
||||
/>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
import { defineStore } from "pinia";
|
||||
import { ref, computed } from "vue";
|
||||
import axios from "axios";
|
||||
import { uploadFile } from "@/uploads";
|
||||
|
||||
/**
|
||||
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
|
||||
@@ -133,21 +133,17 @@ export const useMessagesStore = defineStore("messages", () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST a file to the REST upload endpoint, then send its returned URL over
|
||||
* the socket as a normal message. Two steps because the socket carries JSON
|
||||
* text only. Errors surface via `lastError`.
|
||||
* Store a file (uploads.js), then send its URL over the socket as a normal
|
||||
* message. Two steps because the socket carries JSON text only. Errors
|
||||
* surface via `lastError`.
|
||||
*
|
||||
* `private` is sent with the upload as well as with the message: the backend
|
||||
* stores private attachments under /uploads/private/, which nginx gates
|
||||
* behind an admin check.
|
||||
* `private` goes to both: the upload is stored under /uploads/private/,
|
||||
* which nginx gates behind an admin check, and the message is marked
|
||||
* private. The two must agree.
|
||||
*/
|
||||
async function uploadAndSendFile(file, isPrivate = false) {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("private", isPrivate ? "true" : "false");
|
||||
const res = await axios.post("/api/messages/upload", formData);
|
||||
const { url } = res.data;
|
||||
const url = await uploadFile(file, { private: isPrivate });
|
||||
if (!socket.value || !isConnected.value) return;
|
||||
socket.value.send(
|
||||
JSON.stringify({ text: "", fileUrl: url, private: isPrivate }),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Uploaded files: the one module to use whenever the frontend stores a file
|
||||
* or shows one it stored.
|
||||
*
|
||||
* import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
|
||||
*
|
||||
* <input type="file" :accept="ACCEPT.images" @change="…">
|
||||
* const url = await uploadFile(file); // "/uploads/3f9c….png"
|
||||
* kindOf(url) // "image"
|
||||
*
|
||||
* Files go to POST /api/uploads (backend/handlers/handle_upload.go). The
|
||||
* backend decides everything that matters: the allowed types and the 10MB
|
||||
* limit (backend/services/uploads.go, UploadTypes), the random file name, and
|
||||
* where it is stored (the Garage bucket, falling back to disk). The URL it
|
||||
* returns is permanent and public — anyone with it can load the file, no login
|
||||
* — so never upload something that shouldn't be public unless it is a private
|
||||
* chat attachment (`{ private: true }`, admin only).
|
||||
*
|
||||
* A refused file (wrong type, too large) rejects with an ApiError whose
|
||||
* `message` is the backend's sentence, ready to show the user.
|
||||
*/
|
||||
import { api } from "@/api";
|
||||
|
||||
/**
|
||||
* `accept` values for file pickers, matching what the backend allows. They
|
||||
* only steer the picker; the backend enforces the real list.
|
||||
*/
|
||||
export const ACCEPT = {
|
||||
images: "image/jpeg,image/png,image/gif,image/webp",
|
||||
media: "image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,audio/mpeg,audio/ogg",
|
||||
any: "image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,audio/mpeg,audio/ogg,application/pdf,text/plain",
|
||||
};
|
||||
|
||||
/**
|
||||
* Store one file; resolves to its URL.
|
||||
*
|
||||
* @param {File} file
|
||||
* @param {object} [options]
|
||||
* @param {boolean} [options.private] admin-only: store it under
|
||||
* /uploads/private/, readable only by admins. Never use it for anything
|
||||
* shown inside a canvas box — a box's sandboxed frame loads without the
|
||||
* login cookie, so the file would not load.
|
||||
* @returns {Promise<string>} "/uploads/<name>" or "/uploads/private/<name>"
|
||||
*/
|
||||
export async function uploadFile(file, { private: isPrivate = false } = {}) {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
if (isPrivate) body.append("private", "true");
|
||||
const { url } = await api.post("/uploads", body, { fallback: `Upload of ${file.name} failed` });
|
||||
return url;
|
||||
}
|
||||
|
||||
/** What a stored file is, from its URL: "image", "video", "audio" or "file". */
|
||||
export function kindOf(url) {
|
||||
if (/\.(jpe?g|png|gif|webp)$/i.test(url)) return "image";
|
||||
if (/\.(mp4|webm)$/i.test(url)) return "video";
|
||||
if (/\.(mp3|ogg)$/i.test(url)) return "audio";
|
||||
return "file";
|
||||
}
|
||||
|
||||
export const isImage = (url) => kindOf(url) === "image";
|
||||
export const isVideo = (url) => kindOf(url) === "video";
|
||||
|
||||
/**
|
||||
* Whether a URL is one of our own uploads. Use it before rendering a URL that
|
||||
* came from somebody else (a chat message's fileUrl arrives over the socket
|
||||
* and is otherwise attacker-controlled). A strict prefix check, so absolute
|
||||
* ("https://evil/uploads/x") and protocol-relative ("//evil/uploads/x") URLs
|
||||
* fail, and ".." is refused outright.
|
||||
*/
|
||||
export function isUploadUrl(url) {
|
||||
return typeof url === "string" && !url.includes("..") && url.startsWith("/uploads/");
|
||||
}
|
||||
|
||||
/** The markup a stored file is shown with in a box's HTML, by kind. */
|
||||
export function tagFor(url) {
|
||||
switch (kindOf(url)) {
|
||||
case "image":
|
||||
return `<img src="${url}" alt="">`;
|
||||
case "video":
|
||||
return `<video src="${url}" controls loop muted></video>`;
|
||||
case "audio":
|
||||
return `<audio src="${url}" controls></audio>`;
|
||||
default:
|
||||
return `<a href="${url}" target="_blank">${url.split("/").pop()}</a>`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Natural size of an image or video File, or null if it can't be read. */
|
||||
export function mediaSize(file) {
|
||||
return new Promise((resolve) => {
|
||||
const src = URL.createObjectURL(file);
|
||||
const done = (size) => {
|
||||
URL.revokeObjectURL(src);
|
||||
resolve(size);
|
||||
};
|
||||
if (file.type.startsWith("video/")) {
|
||||
const v = document.createElement("video");
|
||||
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
|
||||
v.onerror = () => done(null);
|
||||
v.src = src;
|
||||
} else {
|
||||
const img = new Image();
|
||||
img.onload = () => done({ w: img.naturalWidth, h: img.naturalHeight });
|
||||
img.onerror = () => done(null);
|
||||
img.src = src;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { FITS, useBackgroundStore } from "@/stores/background";
|
||||
import { uploadFile, isImage } from "./upload";
|
||||
import { ACCEPT, uploadFile, isImage } from "@/uploads";
|
||||
import OverlayShell from "@/components/util/OverlayShell.vue";
|
||||
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
|
||||
|
||||
@@ -133,7 +133,7 @@ async function confirmReset() {
|
||||
<span class="row">
|
||||
<label class="bar-btn upload">
|
||||
{{ busy ? "Working…" : "Upload image…" }}
|
||||
<input type="file" accept="image/*" hidden :disabled="busy" @change="upload($event.target.files[0])" />
|
||||
<input type="file" :accept="ACCEPT.images" hidden :disabled="busy" @change="upload($event.target.files[0])" />
|
||||
</label>
|
||||
<span class="hint">or drop one on this panel</span>
|
||||
</span>
|
||||
|
||||
@@ -39,7 +39,7 @@ import HtmlBox from "./HtmlBox.vue";
|
||||
import WidgetBox from "./WidgetBox.vue";
|
||||
import { WIDGETS } from "./widgetRegistry";
|
||||
import { TEMPLATES, imageHtml, videoHtml } from "./templates";
|
||||
import { mediaSize, uploadFile } from "./upload";
|
||||
import { mediaSize, uploadFile } from "@/uploads";
|
||||
|
||||
const props = defineProps({
|
||||
page: { type: String, required: true },
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
* the panel. Saving every keystroke would push half-written markup to
|
||||
* every visitor; leaving is the point it is finished.
|
||||
*
|
||||
* "Insert upload" uploads a file (upload.js) and puts a tag for it at the
|
||||
* "Insert upload" uploads a file (@/uploads) and puts a tag for it at the
|
||||
* cursor — the way to add pictures to an existing box, e.g. a gallery.
|
||||
*
|
||||
* The panel is teleported to <body>, so it is fixed to the window whatever
|
||||
@@ -21,7 +21,7 @@
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useBoxesStore } from "@/stores/boxes";
|
||||
import { tagFor, uploadFile } from "./upload";
|
||||
import { ACCEPT, tagFor, uploadFile } from "@/uploads";
|
||||
import CodeEditor from "./CodeEditor.vue";
|
||||
import { WIDGETS } from "./widgetRegistry";
|
||||
import OverlayShell from "@/components/util/OverlayShell.vue";
|
||||
@@ -194,7 +194,7 @@ function close() {
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
accept="image/*,video/mp4,video/webm,audio/mpeg,audio/ogg"
|
||||
:accept="ACCEPT.media"
|
||||
hidden
|
||||
@change="upload"
|
||||
/>
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
/**
|
||||
* Uploading a file for use in a box: stores it through the chat's upload
|
||||
* endpoint (public, unguessable URLs under /uploads/) and says what markup
|
||||
* shows it. Used by BoxEditor's "Insert upload" and by dropping files onto
|
||||
* the canvas in edit mode.
|
||||
*
|
||||
* Never the private upload directory: that one is behind a cookie check, and
|
||||
* a box's sandboxed frame loads as an opaque origin, so its requests may not
|
||||
* carry the cookie.
|
||||
*/
|
||||
import { api } from "@/api";
|
||||
|
||||
/** Upload one file; resolves to its URL. Throws an ApiError on failure. */
|
||||
export async function uploadFile(file) {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
const { url } = await api.post("/messages/upload", body, { fallback: `Upload of ${file.name} failed` });
|
||||
return url;
|
||||
}
|
||||
|
||||
export const isImage = (url) => /\.(jpe?g|png|gif|webp)$/i.test(url);
|
||||
export const isVideo = (url) => /\.(mp4|webm)$/i.test(url);
|
||||
|
||||
/** The markup an uploaded file is shown with, by type. Anything else (a PDF,
|
||||
* a text file) becomes a link. */
|
||||
export function tagFor(url) {
|
||||
if (isImage(url)) return `<img src="${url}" alt="">`;
|
||||
if (isVideo(url)) return `<video src="${url}" controls loop muted></video>`;
|
||||
if (/\.(mp3|ogg)$/i.test(url)) return `<audio src="${url}" controls></audio>`;
|
||||
return `<a href="${url}" target="_blank">${url.split("/").pop()}</a>`;
|
||||
}
|
||||
|
||||
/** Natural size of an image or video file, or null if it can't be read. */
|
||||
export function mediaSize(file) {
|
||||
return new Promise((resolve) => {
|
||||
const src = URL.createObjectURL(file);
|
||||
const done = (size) => {
|
||||
URL.revokeObjectURL(src);
|
||||
resolve(size);
|
||||
};
|
||||
if (file.type.startsWith("video/")) {
|
||||
const v = document.createElement("video");
|
||||
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
|
||||
v.onerror = () => done(null);
|
||||
v.src = src;
|
||||
} else {
|
||||
const img = new Image();
|
||||
img.onload = () => done({ w: img.naturalWidth, h: img.naturalHeight });
|
||||
img.onerror = () => done(null);
|
||||
img.src = src;
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user