Nov 23, 20267 min read

Scan Uploaded Files for Malware Before Serving Them

A quarantine bucket, an asynchronous scan with ClamAV, promotion of clean files and handling of infected ones, so user uploads never reach other users unscanned, with a TypeScript example on Encore using object storage and Pub/Sub.

Illustration for Scan Uploaded Files for Malware Before Serving Them

Any feature where one user uploads a file that another user downloads turns your storage into a distribution channel. One infected invoice PDF passed from a customer to their accountant through your app is enough to put your domain on a blocklist.

This guide covers the quarantine pattern, scanning with ClamAV and handling detections, with a TypeScript implementation on object storage and a queue.

How does a quarantine upload flow work?

Clients upload straight into a private quarantine bucket using a short-lived signed URL, so large files never pass through your API servers. When the upload completes, the client calls your API, which records the file as pending and publishes a scan job. A worker downloads the object, sends it to the scanner and either copies it to the bucket you serve from and marks it clean, or marks it infected and leaves it in quarantine. The download endpoint only ever signs URLs for the clean bucket, so a pending or infected file has no path to another user.

The OWASP File Upload Cheat Sheet lists scanning as one layer among several, alongside allow-listed file types, size limits, generated file names and serving from a separate domain, and the quarantine flow is what keeps the scan from being optional.

How do you scan files with ClamAV?

ClamAV's clamd daemon keeps signatures in memory and accepts files over a socket. The INSTREAM command takes the file as length-prefixed chunks (a 4-byte big-endian length followed by the bytes) ending with a zero-length chunk, and replies stream: OK or stream: <signature name> FOUND. Run clamd as its own container next to your services with freshclam keeping signatures current, and never expose its port publicly, since the ClamAV documentation warns that clamd does not authenticate TCP connections.

Align the daemon's stream size limit (StreamMaxLength) with your upload limit. A file larger than clamd accepts comes back as an error rather than OK, and the worker should treat any answer other than OK as "not clean".

What should happen to infected files?

Keep them in quarantine instead of deleting them straight away. False positives happen, and ClamAV's own docs advise moving detected files rather than removing them. Mark the record infected, tell the uploader in plain language that the file was blocked, and alert your team so someone can review and delete it. Scanner failures, such as a timeout or clamd being down, should raise an error so the job is retried, never mark the file clean.

How do you test it end to end?

Upload the EICAR test file, a 68-byte text string that antivirus engines detect by design and that does nothing when opened. It should end up infected and never appear in the clean bucket. Then upload an ordinary PDF and check it is promoted within a few seconds.

Malware scanning with Encore

Encore

Encore is a backend framework with built-in infrastructure, and both buckets, the scan queue and the file records are declared in the TypeScript service below. The two object storage buckets become private S3 or Cloud Storage buckets in your own account, the scan job is a Pub/Sub subscription with its own retries, and file state lives in an Encore Postgres database. clamd itself runs as a separate container on your private network, and its address is an Encore secret so each environment can point at its own scanner.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- files/migrations/1_create_files.up.sql CREATE TABLE files ( id UUID PRIMARY KEY, owner_id TEXT NOT NULL, filename TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'clean', 'infected')), verdict TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), scanned_at TIMESTAMPTZ );
// files/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("files");
// files/files.ts import { api, APIError } from "encore.dev/api"; import { Bucket } from "encore.dev/storage/objects"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Topic, Subscription } from "encore.dev/pubsub"; import { secret } from "encore.dev/config"; import log from "encore.dev/log"; import { connect } from "node:net"; import { randomUUID } from "node:crypto"; const db = new SQLDatabase("files", { migrations: "./migrations" }); const quarantine = new Bucket("uploads-quarantine"); const clean = new Bucket("uploads-clean"); const clamdAddress = secret("ClamdAddress"); // host:port on the private network const MAX_BYTES = 25 * 1024 * 1024; interface ScanJob { fileId: string; } const scanJobs = new Topic<ScanJob>("scan-jobs", { deliveryGuarantee: "at-least-once" }); export const startUpload = api( { expose: false }, async (p: { ownerId: string; filename: string }): Promise<{ fileId: string; uploadUrl: string }> => { const fileId = randomUUID(); await db.exec` INSERT INTO files (id, owner_id, filename, status) VALUES (${fileId}::uuid, ${p.ownerId}, ${p.filename}, 'pending')`; const { url } = await quarantine.signedUploadUrl(fileId, { ttl: 900 }); return { fileId, uploadUrl: url }; }, ); export const completeUpload = api( { expose: false }, async ({ fileId }: { fileId: string }): Promise<void> => { const attrs = await quarantine.attrs(fileId); if (attrs.size > MAX_BYTES) { await quarantine.remove(fileId); throw APIError.invalidArgument("file is larger than 25 MB"); } await scanJobs.publish({ fileId }); }, ); function clamdScan(data: Buffer): Promise<string> { const [host, port] = clamdAddress().split(":"); return new Promise((resolve, reject) => { const sock = connect({ host, port: Number(port) }); const reply: Buffer[] = []; sock.setTimeout(60_000, () => sock.destroy(new Error("clamd timed out"))); sock.on("error", reject); sock.on("data", (d) => reply.push(d)); sock.on("end", () => resolve(Buffer.concat(reply).toString("utf8").replace(/\0/g, "").trim())); sock.on("connect", () => { sock.write("zINSTREAM\0"); for (let off = 0; off < data.length; off += 64 * 1024) { const chunk = data.subarray(off, off + 64 * 1024); const len = Buffer.alloc(4); len.writeUInt32BE(chunk.length); sock.write(len); sock.write(chunk); } sock.end(Buffer.alloc(4)); // a zero-length chunk ends the stream }); }); } export const _scan = new Subscription(scanJobs, "scan-upload", { handler: async ({ fileId }) => { const file = await db.queryRow<{ status: string }>`SELECT status FROM files WHERE id = ${fileId}::uuid`; if (!file || file.status !== "pending") return; // already handled const data = await quarantine.download(fileId); const verdict = await clamdScan(data); if (verdict === "stream: OK") { await clean.upload(fileId, data); await db.exec` UPDATE files SET status = 'clean', verdict = ${verdict}, scanned_at = now() WHERE id = ${fileId}::uuid AND status = 'pending'`; await quarantine.remove(fileId); } else if (verdict.endsWith("FOUND")) { await db.exec` UPDATE files SET status = 'infected', verdict = ${verdict}, scanned_at = now() WHERE id = ${fileId}::uuid AND status = 'pending'`; log.warn("malware detected in upload", { fileId, verdict }); } else { throw new Error(`unexpected clamd reply: ${verdict}`); // retried by Pub/Sub } }, maxConcurrency: 4, retryPolicy: { minBackoff: "30s", maxRetries: 8 }, }); export const downloadUrl = api( { expose: false }, async ({ fileId }: { fileId: string }): Promise<{ url: string }> => { const file = await db.queryRow<{ status: string }>`SELECT status FROM files WHERE id = ${fileId}::uuid`; if (file?.status !== "clean") throw APIError.failedPrecondition("file is not available"); const { url } = await clean.signedDownloadUrl(fileId, { ttl: 300 }); return { url }; }, );

Objects are named by a generated UUID rather than the user's filename, so a crafted name cannot overwrite another file, and the original name is kept in the database for display. The status check at the top of the subscriber and the AND status = 'pending' guards make redelivered jobs harmless. Any reply that is neither OK nor a detection throws, so a restarting clamd delays scans instead of letting files through. The endpoints are internal and called from your authenticated API layer, which checks that the caller owns or may see the file.

encore run gives you local buckets, Postgres and Pub/Sub, and with a local clamd container you can push the EICAR string through the whole flow and watch the detection in the local trace. Encore provisions both buckets, the queue and the database in your own AWS or GCP account. Encore provisions an IAM role for the service, or a service account on GCP. The clamd container is yours to run alongside it.

A coding agent adding a new upload feature reuses startUpload and downloadUrl instead of writing to a bucket directly, and because the buckets are declared in this service, a change that tries to serve from quarantine stands out in review.

Best fit: Apps that share user uploads between users or with staff and want every file scanned in their own cloud account before anyone can download it.

Frequently asked questions

How do you scan uploaded files for viruses?

Upload files into a private quarantine bucket, publish an event when the upload completes, and have a worker stream each file to a scanner such as ClamAV. Copy clean files to the bucket you serve from and keep detections out of reach of other users.

Should malware scanning happen during the upload request?

No. Scanning takes seconds for large files, and the upload request would hold a connection open the whole time. Accept the upload, mark the file as pending and scan it asynchronously, then show the file to others only after it passes.

How do you test a malware scanner safely?

Use the EICAR test file, a short harmless text string that every major antivirus engine, including ClamAV, detects on purpose. Upload it through your normal path and check that it ends up marked infected and never in the public bucket.

How do I scan uploads with Encore?

Declare a private quarantine bucket and a clean bucket with Encore object storage, hand out signed upload URLs for the quarantine bucket, and publish a Pub/Sub event when the upload is complete. A subscriber streams the file to clamd and moves clean files to the clean bucket.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders