To implement secure file uploads, authorize every operation within a verified tenant, validate uploaded bytes, and quarantine files before release. Keep storage private and issue short-lived access only after server-side permission checks.
For a SaaS product, tenant isolation must cover metadata, storage, and background jobs. Start with one complete upload-to-download path, then apply the same boundary to listing, deletion, and cleanup.
Key Takeaways
- Derive tenant scope from validated membership or service delegation, never an untrusted header alone.
- Treat uploaded content as untrusted until validation and scanning succeed.
- Authorize every file operation, including background processing and URL generation.
1. Define the Threats and Upload Architecture
Your threat model should cover malicious documents, disguised executables, decompression bombs, storage exhaustion, and cross-tenant access. Also consider a legitimate member who can upload files but lacks permission to delete them.
OWASP’s File Upload Cheat Sheet recommends layered controls because extension checks or antivirus alone can’t protect the whole workflow.
A practical flow is: client -> authorized API -> private quarantine -> validation and scanning -> approved private object -> authorized download.

Store a metadata record containing the tenant ID, file ID, storage key, object version, uploader, detected type, byte count, and approval status. Keep the original filename only as display metadata.
Direct-to-storage uploads reduce application bandwidth. Proxying uploads through your backend provides tighter control over incoming bytes but consumes application capacity. Both designs still need server-side authorization and validation.
2. Authorize Every Operation Within Its Tenant
Establish trusted context
Authenticate the caller, resolve the requested workspace, and validate active membership or service delegation. Then create an immutable context containing the tenant, actor, and permissions.
Keep roles on tenant memberships. An administrator in one workspace might have read-only access in another.

Downstream code must require this context. Missing context or failed policy evaluation must deny access, rather than fall back to an unrestricted query.
Scope reads and mutations before execution
Use one enforcement pattern: require_permission(ctx, action); find_file(tenant_id=ctx.tenant_id, file_id=request.file_id).
Apply that boundary consistently across operations.
| Operation | Required enforcement |
|---|---|
| Upload | Require upload permission; assign the tenant server-side; validate the destination folder within it. |
| Download | Require read permission; retrieve tenant-scoped metadata; allow only approved content. |
| List | Require list permission; scope results, counts, search, and pagination to the tenant. |
| Delete | Require delete permission; locate the tenant-scoped record before changing metadata or storage. |
For an authenticated caller, return 404 when the scoped file doesn’t exist. Never sign or delete an object key supplied directly by the client.
Database row-level security can add protection, but it doesn’t replace action permissions. Include tenant scope in cache keys and validate referenced folders too.
3. Validate Content and Enforce Limits
Validate actual bytes, not browser claims
Allow only file types your product needs. Check extensions, detected content, and structural validity together. The browser’s Content-Type and filename are untrusted inputs; a matching file signature alone doesn’t prove safety either.
Generate an opaque storage key server-side. Never concatenate a submitted filename into a filesystem path or object key. For display names, remove path components and control characters, limit length, and escape them in the interface.
Apply validation to the stored object, not just an initial byte sample. Run parsers with restricted privileges and resource limits because malformed files can exploit the validator itself.
Bound storage and processing costs
Define per-file limits, tenant storage quotas, and request-rate limits separately. Apply tenant-wide allowances so creating more users or API keys doesn’t multiply capacity.
Reserve quota atomically before authorizing an upload. Account for pending reservations, then reconcile against the actual stored size. Release reservations after rejection or expiration.
Enforce byte limits while streaming where possible. A declared content length isn’t sufficient. With direct uploads, use storage-enforced limits where supported and independently validate the stored object’s size before acceptance.
If the storage mechanism can’t enforce the required incoming limit, proxy the upload. Archives also need limits on expanded size, entry count, and nesting, or your product should reject them.
4. Quarantine and Scan Before Release
Keep unapproved files inaccessible
Upload into a private quarantine location that ordinary download credentials can’t read. After upload, your backend should retrieve the actual object’s metadata instead of trusting a client “complete” message.
A worker then performs validation and malware scanning. Scanner errors, timeouts, and unavailable results must leave the file inaccessible. Tell users whether processing is pending or rejected without exposing internal scanner details.
For supported document types, OWASP’s malicious-file guidance describes additional checks for embedded code and image sanitization.
Approve the exact bytes scanned
An upload URL might remain usable after scanning. Therefore, scanning a mutable object and later serving its latest contents creates an overwrite race.
Pin approval to an immutable object version, or promote the exact scanned version into protected final storage. Never release a mutable upload key.
Give scanning workers narrow, tenant-scoped system authority. User-delegated jobs must reevaluate membership and permissions when they execute. Carry trusted tenant and actor information in job records, and scope retry identifiers to the tenant.
5. Keep Storage Private and Serve Files Safely
Limit signed URLs and encryption access
Disable public object access and separate application, scanner, and cleanup permissions. OWASP’s unrestricted-upload guidance explains why unvalidated content mustn’t become available to others.
After authorization, bind an upload URL to one server-generated quarantine key and one operation. Bind a download URL to the approved object version. Choose the shortest expiration that supports the workflow.
Treat signed URLs as bearer credentials. Exclude them from logs and analytics because possession grants temporary access.
Require TLS for transfers and encryption at rest. Separate key-management permissions from routine file access. Per-tenant keys can support stronger separation, but they add rotation and recovery work.
Control browser interpretation
For general downloads, return Content-Disposition: attachment with a safely encoded filename. Set a server-selected content type and X-Content-Type-Options: nosniff.
If previews are necessary, host untrusted content on a separate origin without application cookies. Restrict active formats such as HTML and SVG, and process previews independently.
Authorize before issuing each download URL. However, membership revocation won’t necessarily invalidate an already issued URL. Proxy downloads through an authorization layer when immediate revocation matters.
Also isolate any CDN or application cache by tenant and access policy; a private origin doesn’t make shared caching safe automatically.
6. Make Cleanup and Audit Logging Reliable
Deny access before asynchronous deletion
Mark a file unavailable before enqueueing physical deletion. Use durable job delivery or an outbox so a committed database change can’t silently lose its cleanup task.
Make deletion idempotent, and clean up associated previews and retained versions according to your retention policy.
Also expire abandoned uploads, stale quota reservations, failed-processing files, and incomplete multipart uploads. Reconcile storage against metadata to find orphaned objects. Define how legal holds and backups affect deletion rather than promising immediate removal of every copy.
Record outcomes with trusted context
Capture upload authorization, rejection, scan decisions, download-link issuance, deletion, and privileged support access.
Include the verified tenant, actor or service identity, action, file ID, outcome, timestamp, and correlation ID. Never record credentials, signed URLs, or file contents.
Distinguish “download URL issued” from “file downloaded.” Storage access events can provide delivery evidence that application logs lack. Protect audit queries and exports with tenant-scoped authorization too.
7. Test Cross-Tenant Access and Failure Paths
Create two test tenants with distinct files. Include one user who belongs to both but has different permissions. Use known foreign file IDs because unguessable identifiers don’t prove isolation.
OWASP’s malicious-upload testing guide provides a starting point for testing content attacks.
Add these regression cases:
- Request another tenant’s upload destination, file, listing, download URL, or deletion, then assert no disclosure or mutation.
- Override tenant headers, submit foreign folder references, and send mixed-tenant bulk requests; none should escape the authorized scope.
- Remove membership before user-delegated jobs run, omit tenant context, and interrupt policy evaluation; each path must deny access.
- Exercise oversized streams, spoofed file types, scanner failures, URL replay, overwrite attempts, and simultaneous quota reservations.
Assert side effects as well as HTTP responses. A denied request mustn’t enqueue deletion, change quotas, or issue a usable URL.
Run positive tests alongside denials. Valid uploads and authorized downloads must still work.
Frequently Asked Questions
Are signed upload URLs single-use?
Don’t assume so. Depending on the storage service, a URL can remain reusable until expiration. Random keys, immutable approved versions, and short validity periods reduce exposure. Track completion server-side, but remember that an application flag alone doesn’t invalidate storage credentials.
Does each tenant need a separate bucket?
No. Shared private storage can work with tenant-scoped metadata and controlled access. Separate buckets or accounts provide additional boundaries but increase operational work. Choose according to isolation requirements and team capacity; neither design removes application authorization.
Build One Enforced File Boundary
Reliable uploads depend on consistent authorization across the entire file lifecycle. Private storage and scanning help only when metadata, workers, and download paths preserve the same tenant boundary.
Implement one complete path before adding bulk operations or previews. Keep its cross-tenant denial tests in the deployment pipeline so new features can’t bypass the controls that protect existing files.