Generating signed URL specifications
I'm thinking about signed URLs and how they work for both PUT and GET requests. They should have a limited time frame, restricted headers, content length, and a checksum. I want to include the client flow while ensuring they meet requirements like streaming, AV scanning, and MIME validation. Security is on my mind too, so I need to consider authentication and authorization, quotas, rate limiting, encryption, logs, and audits. I'll also create a simple schema for these.Proposing system architecture
I'm thinking about a proposed architecture that includes an API service and object storage using S3 buckets, specifically for uploads-staging and uploads-clean, both private. There'll be an AV scanning service triggered by an object-created event that streams the object to the scanner, checks for infections, and either moves cleaned files to the clean bucket or sends infected files to quarantine. I also want to ensure MIME validation at the upload initiation and scan time, potentially calculating a file hash too. The client can use pre-signed URLs for multipart uploads.Defining upload and download processes
I'm considering the process for uploads and downloads. For uploads, the POST /uploads/initiate will return an UploadId and URLs for each part, or we could use S3 multipart with pre-signed URLs, while ensuring we don't exceed the maximum size allowed through policy conditions. For downloads, the API will generate a time-limited pre-signed GET for objects in the clean bucket, including a Content-Disposition header. Additionally, I want to implement a lifecycle policy where staging objects will expire quickly.Detailing retention and scanning processes
I'm outlining the lifecycle of my storage. Quarantine objects should expire after 24 hours or hold for review, while clean objects will follow retention policies based on tenants, using S3 lifecycle rules or scheduled jobs to mark them as deleted, updating DB metadata accordingly. For the data model, I plan to create a files table that captures various attributes like status, size, MIME types, and a metadata field. I'll also need to address implementation details, suggesting Go or Node, with libraries such as AWS SDK and ClamAV for streaming scanning without storing full files.Outlining the file upload service
I’m laying out the steps for a file upload service using pre-signed POST policies to enforce content length and type, though I know content-type isn’t entirely trustworthy. For uploads up to 5GB, clients will get a pre-signed PUT directly to the staging bucket. After the upload, an event triggers an AV scanning worker, updating the status accordingly. Clients can request a download if the file is clean, and I want to utilize S3 lifecycle rules for old file deletions. I'll include considerations for security, concurrency, and pseudo code examples, aiming for clear guidance in TypeScript/Node.
Below is a reference design you can implement as-is on any cloud with object storage; examples use AWS S3, Node.js/TypeScript, ClamAV (clamd INSTREAM), and event-driven scanning. The same pattern maps to GCS/Azure Blob.
1) Architecture (streaming + scan + validate + lifecycle + signed URLs)
Components
- Upload API (stateless): auth, policy checks, creates file records, issues signed URLs, and issues download URLs for clean files.
- Object Storage (S3):
uploads-staging bucket (private): newly uploaded, untrusted
uploads-clean bucket (private): only scanned + validated files
uploads-quarantine bucket (private): infected/suspicious (optional)
- Metadata DB (Postgres/DynamoDB): file status + ownership + expiry + hashes
- Scanner Worker (autoscaled): triggered on new object in staging, performs:
- streaming AV scan (no full file buffering on disk)
- MIME sniffing via magic bytes
- optional checksum verification and file-type rules
- promote to clean or quarantine
- Lifecycle: bucket lifecycle rules + periodic reconciler job to keep DB in sync.
High-level flow
- Client calls
POST /v1/files:initiate with {filename, size, declaredMime, sha256?}.
- API returns a pre-signed upload URL to
uploads-staging (PUT or multipart) + fileId.
- Client uploads directly to S3 (streaming from client to S3).
- S3 “ObjectCreated” event triggers scanner worker.
- Worker streams S3 object → clamd
INSTREAM, also reads first bytes for MIME sniff, decides:
- CLEAN: copy to
uploads-clean, tag, update DB status CLEAN, delete from staging
- INFECTED/REJECTED: move to quarantine or delete; update DB
- Client requests
GET /v1/files/{id}:downloadUrl → API returns a pre-signed GET only if status is CLEAN and not expired.
2) Data model (minimal)
files
id (UUID)
tenantId, ownerId
originalName
declaredMime, detectedMime
sizeBytes
sha256 (optional but recommended)
status ENUM: INITIATED | UPLOADING | UPLOADED | SCANNING | CLEAN | REJECTED | INFECTED | EXPIRED | DELETED
stagingKey, cleanKey
createdAt, expiresAt
reason (text, for rejection/infection)
3) API surface
Initiate upload (signed URL)
POST /v1/files:initiate
{
"filename": "invoice.pdf",
"sizeBytes": 123456,
"declaredMime": "application/pdf",
"sha256": "optional-hex"
}
Response (single PUT):
{
"fileId": "uuid",
"status": "INITIATED",
"upload": {
"method": "PUT",
"url": "https://s3...presigned...",
"headers": {
"Content-Type": "application/pdf"
},
"expiresInSeconds": 900
}
}
Notes:
- For large files, return multipart instructions (uploadId + per-part signed URLs).
- Enforce max size and allowed types at initiation.
Complete (optional)
If you don’t want to rely solely on S3 events, client can call:
POST /v1/files/{id}:complete
API can HeadObject stagingKey and mark UPLOADED.
Poll status
GET /v1/files/{id} → returns status and metadata.
Download URL (signed GET)
GET /v1/files/{id}:downloadUrl
Only returns a URL if status == CLEAN and not expired.
4) MIME validation (don’t trust Content-Type)
Policy:
- Maintain an allow-list of detected types (from magic bytes), e.g.
application/pdf, image/png, image/jpeg.
- Optionally also check extension/declared MIME for consistency, but final decision is magic-byte detection.
Implementation:
- Read the first ~4–16KB of the object stream (or do a range GET) and detect with libmagic or
file-type.
Rules:
- Reject if
detectedMime not in allow-list.
- Reject “polyglots”/archives if you don’t support them.
- Optionally cap image dimensions / PDF page count, etc. (type-specific validation).
5) AV scanning (streaming)
Use clamd and its INSTREAM command so you can stream bytes without fully storing the file locally.
Worker steps:
GetObject from staging bucket → stream
- Tee/peek first bytes → detect MIME
- Pipe the stream to clamd
INSTREAM
- If clean + MIME allowed → promote to clean bucket
- Else → quarantine/delete + mark status
Promotion strategy:
- Prefer
CopyObject from staging → clean (server-side copy), then delete staging.
- If you need to rewrite metadata/tags, use CopyObject with
MetadataDirective: REPLACE.
6) Lifecycle management
Bucket lifecycle rules
uploads-staging: expire objects after e.g. 1 day (in case scanning fails)
uploads-quarantine: expire after e.g. 14 days (or keep for forensics)
uploads-clean: expire based on your product needs (e.g. 30/90/365 days)
You can drive lifecycle by object tags, e.g.:
state=staging|clean|quarantine
tenantId=...
expiresAt=YYYY-MM-DD (note: S3 lifecycle can’t natively parse arbitrary dates; typically you use “days since creation” or per-prefix rules, or a scheduled deleter.)
DB lifecycle
- A daily job marks expired records, attempts deletes, and reconciles with storage (idempotent).
7) Signed URLs (upload + download)
Upload signing guidelines
- Keep expiry short (5–15 min).
- Bind to a specific key (random UUID-based), never user-provided paths.
- Enforce
Content-Length bounds where possible (presigned POST policies can enforce; PUT is trickier—use API-side size validation + event-time checks).
- Require checksum headers if your storage supports it (S3 supports checksum headers; or verify post-upload).
Download signing guidelines
- Only for
CLEAN objects.
- Add
ResponseContentDisposition=attachment; filename="..." to prevent inline execution in browsers.
- Keep expiry short (e.g. 60–300s) for sensitive content.
8) Minimal TypeScript snippets (AWS S3 + presigned URLs)
Generate a pre-signed PUT for staging upload
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const s3 = new S3Client({ region: process.env.AWS_REGION });
export async function createUploadUrl(params: {
bucket: string;
key: string;
contentType: string;
expiresInSeconds?: number;
}) {
const cmd = new PutObjectCommand({
Bucket: params.bucket,
Key: params.key,
ContentType: params.contentType,
// Optional: ServerSideEncryption: "aws:kms", SSEKMSKeyId: "...",
// Optional: Metadata: { fileId: "...", tenantId: "..." }
});
const url = await getSignedUrl(s3, cmd, { expiresIn: params.expiresInSeconds ?? 900 });
return url;
}
Generate a pre-signed GET for clean download
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
export async function createDownloadUrl(params: {
bucket: string;
key: string;
filename: string;
}) {
const cmd = new GetObjectCommand({
Bucket: params.bucket,
Key: params.key,
ResponseContentDisposition: `attachment; filename="${params.filename.replace(/"/g, "")}"`,
});
return getSignedUrl(s3, cmd, { expiresIn: 120 });
}
9) Scanner worker: streaming to clamd (outline)
Key idea: S3.GetObject().Body is a readable stream. Feed it into clamd INSTREAM (TCP).
Pseudo-outline:
// 1) GetObject stream from staging
// 2) Read small prefix for MIME sniff (range GET is even cleaner)
// 3) Stream entire object to clamd INSTREAM
// 4) Decide promote/quarantine + update DB
If you want, tell me your runtime (Node/Go/Python) and environment (ECS/K8s/Lambda), and I’ll provide a concrete worker implementation for clamd INSTREAM plus MIME sniffing.
10) Security / correctness checklist
- AuthZ: every file row tied to
tenantId + ownerId
- Random object keys (no user-controlled paths)
- Encrypt at rest (SSE-KMS) and in transit (TLS)
- Limit file sizes and rate-limit initiation endpoints
- Store and verify checksums (sha256) for integrity
- Never serve unscanned files; staging bucket is private, no public ACLs
- Prevent HTML/script inline execution: force attachment disposition on downloads
- Audit log: upload initiated, upload completed, scan result, download URL issued
If you answer these, I can tailor the exact implementation (including multipart upload + OpenAPI spec + Terraform):
- Cloud/provider (AWS/GCP/Azure)
- Preferred language/runtime (Node/Go/Python; Lambda vs containers)
- Allowed file types + max size
- Do you need resumable uploads (multipart) and client-side checksum?