Accepting and serving user uploads safely from a private bucket
uploadsobject-storages3streamingcontent-dispositionnosniffcorsthumbnailsretention
TLDR lets users attach any file type up to 500 MB to posts. Files live in a private Linode bucket and every byte is streamed back through the PHP API. This article covers the whole pipeline: why a streaming proxy instead of pre-signed redirects, how to serve arbitrary uploads without creating an XSS hole, how size limits stack, and how deletion, thumbnails and avatars fit in. Bucket and endpoint specifics are in Linode (Akamai) Object Storage.
Storage and serving
- Upload:
POST /uploadvalidates, then streams the file to the bucket with a server-side PutObject. Stream from the temp file (CURLOPT_UPLOAD+CURLOPT_INFILE), neverfile_get_contents: buffering a 500 MB file fatals PHP. SigV4 withUNSIGNED-PAYLOADlets you sign without hashing the body. - Names:
time()_<random hex>.<ext>, unique per upload. The response returnshttps://api.tldrnerd.com/uploads/<name>, the same URL shape as before the migration, so no stored content needed rewriting. - Serve:
GET /uploads/{filename}presigns a GET server-side and streams the body through Slim (fopenon the presigned URL into a stream). The bucket stays private and presigned URLs never leave the server. - Why not redirect to a presigned URL: the Chicago endpoint cannot set bucket CORS, and Flutter web's CanvasKit renderer refuses cross-origin images without CORS. The API already carries CORS. (The original plan, presigned GET/PUT direct to the bucket with expiry rounded to a stable window for caching, was abandoned for this reason.)
- Cache:
Cache-Control: public, max-age=31536000, immutable. Names are unique, so after the first load the server is out of the data path. - Cutover detail: Apache had an
Alias /uploadsto a local directory; removing it let/uploads/*fall through to the framework route. Migration copied all files and verified MD5s (71/71).
Allowing any file type without XSS
The first design stored uploads as <random>.tldr behind a download endpoint, to stop Apache from
executing uploaded PHP. Moving storage to a bucket made uploaded code inert data, so the whitelist
was dropped. What keeps it safe:
- Always send X-Content-Type-Options: nosniff.
- Inline-render only a small known set (jpg, jpeg, png, gif, webp, pdf, txt, json, stl). Everything
else is application/octet-stream with Content-Disposition: attachment. That is what prevents an
uploaded HTML or SVG from running script on the API's origin.
- Sanitize the stored extension ([a-z0-9], max 16 chars); extension-less files (Makefile) are
stored without a trailing dot.
- Optional ?name=<original> restores the original filename on download; sanitize it (printable
ASCII, no quote, backslash or slash). Browsers ignore the download attribute cross-origin, so
the header is what names the file.
- Path parameters: reject / \ .. and apply basename() before touching any path.
Size limits stack
A 500 MB limit needs all of: nginx client_max_body_size (default 1M per site, here 512M), PHP
upload_max_filesize and post_max_size (512M), and the app's own check. A status endpoint tells
clients the current limit; clients must call it with auth, see
API authorization from the verified identity (and the holes it closes). A flag file (.uploads_disabled) is a kill switch; exclude
it from rsync --delete deploys or every deploy re-enables uploads.
Deletion and retention
- An immediate purge on delete broke the 6-second undo (images gone before undo could restore them).
- Now delete only tombstones the row (
deleted = 1,deleted_at = NOW()). A nightly cron purges bucket objects referenced by posts deleted more than 90 days ago, setsimages_purged = 1, keeps the tiny row (a hard delete would cascade through ~10 tables), usesflockagainst overlap, and only marks a row purged when every object deletion succeeded. - Upload URLs are not indexed in any table; the cron finds them by regex in post bodies. Anything not referenced from a body (avatars) is never touched by it.
- There is deliberately no delete route for uploads. One-off removals run PHP on the server with the S3 client so credentials never leave the box.
Thumbnails on demand
GET /thumbs/{filename} (public) returns a 168 px center-crop square WebP (q82, alpha kept),
generated with GD on first request and stored back to the bucket as thumbs/<file>.webp, then
served immutable. Fixed size only, no caller-chosen dimensions (no resize DoS). 404 for non-raster
types, undecodable images, sources over 40 MB or 40 megapixels. Measured on the 1 GB server: a
140 KB PNG becomes 2.7 KB in 20 to 60 ms. The retention cron deletes the thumb with the original,
best effort.
Avatars
POST /users/{u}/avatar (POST because PHP only fills $_FILES on POST), self or admin only,
finfo check for png/jpeg/webp/gif, 2 MB cap. Object name avatar-<user>-<16 hex>.<ext>, new for
every upload so immutable caching stays correct; the previous object is deleted best effort (only
ever keys starting avatar-). The client crops to a 512x512 PNG before upload with an
InteractiveViewer inside a RepaintBoundary and toImage(), no plugin.
See also
- Linode (Akamai) Object Storage
- Resizing uploaded photos on the server (PHP GD)
- Zero layout shift for network images in Flutter (dimensions in the URL)
- Writing a production smoke test that tells you why it failed
Linked from
- Changing a production MariaDB safely (schema, data fixes, id generation)
- Full-screen image viewer with zoom and save-to-gallery in Flutter (no plugins)
- Making a Flutter app an Android share target (native, no plugin)
- PHP's uppercase-S TLS downgrade (CVE-2026-128064) and proving it on the wire
- TLDR platform architecture (tldrnerd.com)
- Upload links for people without an account (getting a full-quality video from a friend)
- Writing a production smoke test that tells you why it failed
- Zero layout shift for network images in Flutter (dimensions in the URL)