Browser-to-Storage Uploads: Private Buckets, Webhooks, Thumbnails, and Virus Scans
Short answer: use a short-lived presigned upload for the browser, keep the bucket private, and let a verified object-created event drive virus scanning and thumbnail work. Do not make the browser wait for either job. Th
Short answer: use a short-lived presigned upload for the browser, keep the bucket private, and let a verified object-created event drive virus scanning and thumbnail work. Do not make the browser wait for either job.
That shape fits a media receipt system where the original file matters for audit. Large-file throughput is the deciding constraint. A receipt that uploads successfully but gets lost, replaced, or marked βsafeβ before inspection is an operational failure, not a UI bug.
The useful mental model is a small state machine: created, uploaded, scanned, derived, and rejected. The object store owns bytes. The application owns intent and state. Workers own processing. Keeping those responsibilities separate removes a lot of glue from the critical upload path.
How should browser uploads trigger private-bucket processing?
The browser should ask the application for an upload grant. The application should create a random object key, bind it to a receipt record, and return a presigned URL plus the expected content constraints. The browser then sends the file directly to storage. A storage event, or a webhook adapter for that event, starts processing after the object exists. This keeps the application out of the byte path, which matters for receipts arriving from unreliable connections and for large files that would otherwise consume application bandwidth, request workers, proxy buffers, and temporary disk at the same time. The grant endpoint still has work to do: it authenticates the caller, checks the receipt's ownership, chooses the key, and records the constraints that later verification must enforce. A direct upload is not an anonymous upload; it is a narrowly scoped capability issued by the application.
The callback is not proof that the file is safe. It is proof that a storage-side event was received. Verify the callback's authentication, check that the object key belongs to a pending receipt, and fetch metadata from storage before changing application state. Never trust a filename or MIME type supplied by the browser as a security decision.
The original stays private. Public access belongs on a separately generated derivative, if the product needs it, and that derivative should not be created until policy allows it.
Here is the smallest application-side sketch. The storage provider is intentionally abstract; the routes below are application routes, not claims about a particular provider.
type UploadGrant = {
receiptId: string;
objectKey: string;
putUrl: string;
expiresAt: string;
};
async function requestUpload(file: File): Promise<UploadGrant> {
const response = await fetch("/api/receipts/upload-grant", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
filename: file.name,
contentType: file.type,
size: file.size,
}),
});
if (!response.ok) throw new Error(`grant failed: ${response.status}`);
return response.json() as Promise<UploadGrant>;
}
async function uploadReceipt(file: File): Promise<string> {
const grant = await requestUpload(file);
const upload = await fetch(grant.putUrl, {
method: "PUT",
headers: { "content-type": file.type || "application/octet-stream" },
body: file,
});
if (!upload.ok) throw new Error(`upload failed: ${upload.status}`);
return grant.receiptId;
}
For a truly large file, use the storage service's multipart upload protocol instead of buffering the file through your application. The important property is the same: parts go from browser to storage, and the application records completion only after the service confirms the assembled object. A retry must reuse the receipt's upload session or safely abandon it; blindly starting a new object on every retry creates orphaned bytes.
The event-driven pipeline
An object-created event should enqueue a small, durable job. It should not run thumbnail generation inline inside the webhook request. Return quickly after accepting a valid event, then let a worker claim the job with a lease or an equivalent visibility timeout.
The worker sequence is deliberately boring:
- Load the receipt record and compare its object key with the event key.
- Read size and content metadata from storage.
- Inspect the file type from its bytes, not only its extension.
- Run the virus scanner in an isolated worker.
- Mark the original
scannedonly on a clean result. - Generate thumbnails from the original into a separate derived prefix.
- Record derivative metadata and publish a safe application status.
The event can arrive twice. It can also arrive after the client has timed out and retried the upload request. Idempotency belongs at every boundary. A unique key such as (eventId, objectKey, version) is useful when the provider supplies a stable event identifier. If it does not, make the receipt state transition conditional and treat an already-completed transition as success. In practice, I would write down the recovery story before writing the handler: if the process dies after claimEvent but before enqueue, the claim needs an expiry or a repair job; if the queue delivers the job twice, the scan result must be safe to write twice; if a worker dies while producing a derivative, the next attempt needs a temporary key and an atomic publish step. Those details are less exciting than a demo, but they decide whether an audit trail still makes sense after a bad night.
Duplicates are normal.
type ReceiptState = "created" | "uploaded" | "scanned" | "derived" | "rejected";
type ObjectEvent = {
id: string;
bucket: string;
key: string;
};
async function handleObjectEvent(event: ObjectEvent): Promise<void> {
await verifyWebhookSignature();
const receipt = await db.receipts.findByObjectKey(event.bucket, event.key);
if (!receipt) return; // Ignore objects that this application did not create.
const claimed = await db.receipts.claimEvent({
receiptId: receipt.id,
eventId: event.id,
allowedStates: ["created", "uploaded"],
});
if (!claimed) return; // Duplicate or a state transition already in progress.
const metadata = await objectStore.head(event.bucket, event.key);
await db.receipts.markUploaded(receipt.id, metadata.size);
await jobs.enqueue({ type: "scan-receipt", receiptId: receipt.id });
}
This is where many βworkingβ demos become expensive. A webhook retry that creates a second scan is wasteful. A thumbnail worker that writes to the original key can destroy the audit artifact. A queue message that is acknowledged before the state transition is committed can lose the job. Use conditional writes, separate prefixes, and acknowledge only after the durable handoff.
Security controls for receipt files
A private bucket is necessary, but it is not the entire upload policy. Apply a server-side allowlist for file types, impose a size limit before issuing the grant, generate storage keys rather than accepting user paths, and keep the original outside any directly served public prefix. OWASP's file upload guidance also calls for defense in depth: authorization, content validation, safe storage, and malware analysis all have distinct jobs.
The presigned URL should expire quickly and should be scoped to one object key. It should not grant listing, deletion, or reads of neighboring objects. CORS should allow only the browser origins that need this flow. These settings are deployment policy, so test them in the same environment as the application; a permissive local setup can hide a production failure.
Scanning changes the user experience. Show βuploaded, pending inspection,β not βready.β If the scanner rejects a file, retain enough audit metadata to explain the decision, but do not serve the original to ordinary users. If a receipt must be reviewed by an authorized operator, expose that through an authenticated application path with an explicit audit trail.
No scanner is a substitute for isolation. Limit worker permissions, cap decompression expansion, set CPU and wall-clock budgets, and discard temporary workspaces after each job. The exact values depend on file formats and workload; Iβm not sure there is a useful universal timeout for every media pipeline, so measure the distribution of your own files and set an operational ceiling from it.
What I would measure before scaling it
For large-file throughput, measure the path that moves bytes, not just the API response time. Track upload completion rate, time from first byte to object-created event, queue age, scan duration, thumbnail duration, retry counts, orphaned multipart uploads, and bytes stored per receipt. Break the measurements down by file size and network region. An average upload time can look fine while the largest files quietly dominate queue age and user complaints.
I would also run failure tests. Kill the browser after the final part. Deliver the same event twice. Delay the webhook. Send a valid image with a misleading extension. Expire the grant halfway through an upload. Make thumbnail generation fail after the clean scan. Each test should end in a visible, recoverable receipt state rather than an ambiguous spinner.
Keep the browser contract small: grant, upload, poll or subscribe for status. The processing contract should be internal and versioned. If the thumbnail recipe changes, write a new derivative key and preserve the original; do not reinterpret the audit file in place.
The catch is that this architecture is not suitable when you need synchronous transformations before the client can continue, or when your storage service cannot provide the event and multipart semantics you need. In those cases, a managed upload gateway or a simpler application-mediated upload may be easier to operate, even though it adds a byte-moving hop. Stick with the simpler path when files are small, the audit requirement is weak, and the extra worker fleet would cost more engineering attention than it saves.
For a media receipt workflow, the decision rule is straightforward: direct upload for throughput, private originals for audit, verified events for coordination, and asynchronous scanning before any derivative becomes usable. Start with those invariants. Then benchmark the largest files and the worst retries, because that is where the design earns its keep.
References
- OWASP File Upload Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
- DigitalOcean Spaces documentation: https://docs.digitalocean.com/products/spaces/
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.