Skip to content

S3 Presigned URL Security Flaws: Preventing Storage Abuse

Why naive AWS S3 PutObject presigned URLs allow unconstrained file uploads, cross-tenant file overwrites, and how to enforce cryptographic POST policies.

S3 Presigned URL Security Flaws: Preventing Storage Abuse

Most engineering teams adopt direct-to-S3 client uploads to solve a practical infrastructure problem: streaming multi-megabyte user files through application servers consumes memory, monopolizes Node.js worker threads, and triggers serverless gateway payload limits. Because AWS S3 documentation provides simple examples generating temporary upload tickets with getSignedUrl(s3, PutObjectCommand), teams assume the cloud provider cryptographically validates upload size and content integrity.

In reality, standard PutObject presigned URLs do not sign the HTTP Content-Length header unless the backend computes and signs an exact byte count in advance. Because client-side file picker checks can be bypassed with a single curl command, an attacker can reuse a 5MB avatar upload ticket to stream 50 gigabytes of arbitrary binary data directly into your bucket. Enforcing strict Presigned POST policy conditions, randomized UUID key isolation, and automatic multipart lifecycle pruning is essential to protect application runway and customer data.


Quick Production S3 Upload Triage Checklist

If your application permits users to upload files directly to cloud storage, execute this four-point security audit:

  1. Replace PutObject with S3 Presigned POST: Migrate upload ticket endpoints from getSignedUrl to createPresignedPost using @aws-sdk/s3-presigned-post. This allows the server to declare cryptographic content-length-range bounds evaluated directly by S3.
  2. Isolate Keys Behind Server-Validated Tenant Prefixes: Never accept destination filenames from client requests. Format all S3 keys on the server as tenants/{tenantId}/uploads/{crypto.randomUUID()}.
  3. Configure S3 Lifecycle Rule to Abort Incomplete Multipart Uploads: Add a bucket lifecycle rule with AbortIncompleteMultipartUpload set to 1 day to clean up abandoned multipart chunks that silently accumulate storage charges.
  4. Force Attachment Content-Disposition and Block Public ACLs: Set Content-Disposition: attachment on user uploads and enable S3 Block Public Access to prevent Stored Cross-Site Scripting (XSS) via uploaded SVG or HTML files.

The Core Vulnerability: PutObject vs Presigned POST Policies

The primary architectural flaw in most direct-to-S3 implementations is using PutObjectCommand via @aws-sdk/s3-request-presigner instead of an S3 Presigned POST policy. A presigned PUT generates an authenticated query string that grants temporary write permission to a single S3 key, but it cannot enforce upload payload size bounds or validate MIME headers against server-side policies.

                           THE UNBOUNDED PUTOBJECT ATTACK VECTOR
                           
  Client Browser (Legitimate)                     Application Server (Node.js)              AWS S3 Bucket
  ┌────────────────────────────────────┐          ┌───────────────────────────────┐         ┌─────────────────────────┐
  │ Requests upload for 2MB avatar.png │ ───────> │ getSignedUrl(PutObjectCommand)│         │                         │
  │ JS validates: file.size < 5MB      │          │ (Signs key: uploads/avatar)   │         │                         │
  └────────────────────────────────────┘          └───────────────────────────────┘         │                         │
                                                                 │                          │                         │
                                                                 ▼                          │                         │
  Attacker Intercepts Signed URL:                  Returns Presigned PUT URL ──────────────>│                         │
  ┌────────────────────────────────────┐                         │                          │                         │
  │ curl -X PUT --data-binary 50GB.dat │ ──────────────────────────────────────────────────>│ Accepts entire 50GB     │
  │ (Strips client-side JS validation) │                                                    │ (No Content-Length lock)│
  └────────────────────────────────────┘                                                    │ $3,400 Monthly S3 Bill  │

When a frontend requests an upload ticket, standard scaffolding code routinely generates an unconstrained PUT URL:

// ❌ VULNERABLE PATTERN: Unconstrained PutObject presigned URL
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

export async function getUploadUrl(filename: string, contentType: string) {
  const s3 = new S3Client({ region: process.env.AWS_REGION });

  // Flaw 1: filename is unvalidated and user-controlled
  // Flaw 2: ContentType is not cryptographically bound
  // Flaw 3: Zero byte-range ceiling enforced
  const command = new PutObjectCommand({
    Bucket: process.env.UPLOAD_BUCKET_NAME,
    Key: `uploads/${filename}`,
    ContentType: contentType,
  });

  return await getSignedUrl(s3, command, { expiresIn: 3600 });
}

Once the client receives this URL, AWS S3 authenticates the request using HMAC signatures embedded in query parameters (X-Amz-Signature). However, because Content-Length was not part of the signed headers list, S3 accepts any payload size up to 5 terabytes.

An attacker simply runs a standard terminal command:

# Uploading a 20GB zero-byte file through your 5MB avatar endpoint
curl -X PUT \
  -H "Content-Type: image/png" \
  --data-binary "@/tmp/20gb_payload.dat" \
  "https://example.com/uploads/avatar.png?X-Amz-Algorithm=..."

S3 streams all 20 gigabytes into your bucket. If your application triggers automated asynchronous processing (such as image resizing via AWS Lambda or document ingestion in a vector database), that 20GB file triggers downstream compute timeouts, out-of-memory crashes, and cascading worker failure.


Pitfall 2: Predictable Keys and Cross-Tenant Overwrite IDOR

Predictable S3 object keys allow malicious users to overwrite other tenants’ documents by exploiting Insecure Direct Object References (IDOR) during presigned URL generation. If your application names upload keys based on client input or predictable sequence IDs, any authenticated user can request a valid write ticket for an existing asset owned by another customer.

Consider an invoicing platform that stores generated receipts at receipts/{companyId}/{invoiceNumber}.pdf. If the endpoint that dispenses upload URLs accepts the filename directly from the request body:

// ❌ VULNERABLE IDOR ENDPOINT: POST /api/invoices/upload-signed-url
export async function POST(req: Request) {
  const session = await auth();
  if (!session) return new Response('Unauthorized', { status: 401 });

  const { targetPath } = await req.json();

  // Attack: Malicious user passes targetPath = "receipts/company_999/invoice_001.pdf"
  const s3 = new S3Client({ region: 'us-east-1' });
  const command = new PutObjectCommand({
    Bucket: 'enterprise-invoices',
    Key: targetPath, // Direct object injection allows cross-tenant overwriting
  });

  const url = await getSignedUrl(s3, command, { expiresIn: 300 });
  return Response.json({ url });
}

Because S3 PutObject overwrites existing keys by default when versioning is disabled, the attacker’s payload replaces Company 999’s audit-critical legal invoice. If S3 Bucket Versioning is enabled, the original version is preserved under a non-current version ID, but the latest pointer still serves the attacker’s tampered file to auditors and accounting pipelines.

The Key Path Rules

  1. Never trust client-provided filenames: Strip paths, extensions, and special characters. Store the original client filename in database metadata, not the S3 key.
  2. Inject cryptographic UUIDs: Format keys using server-generated high-entropy identifiers: tenants/{tenantId}/documents/{crypto.randomUUID()}.
  3. Strict Path Scoping: Enforce server-side checks ensuring the tenant prefix matches the cryptographically verified session token before generating the AWS signature, as detailed in our guide on Next.js Server Actions Multi-Tenant Security.

Architectural Comparison: Direct-to-S3 Upload Strategies

Direct client uploads require balancing security posture, latency overhead, and infrastructure complexity. The following benchmark highlights the trade-offs between standard PUT, Presigned POST, and traditional API proxying:

Upload MechanismPayload Size EnforcementMIME Integrity LockServer Memory OverheadImplementation ComplexityAttack Blast Radius
Naive PutObject (getSignedUrl)None (Client-side only)Weak (Client spoofable)Zero (Direct to S3)Low (5 lines of code)Severe (Unbounded storage, overwrites)
S3 Presigned POST (createPresignedPost)Strict Byte RangeCryptographic MatchZero (Direct to S3)Medium (Form data parsing)Minimal (Bounded, isolated keys)
API Server Streaming ProxyStrict (Node.js stream limit)Strict (Magic byte check)High (Buffers saturate RAM)High (Worker threads needed)Low (Proxy acts as airgap)
Cloudflare R2 Direct WorkerStrict (Edge runtime check)Strict (Header validation)Minimal (Edge streaming)Medium (Cloudflare Bindings)Low (Zero egress fee architecture)

The Secure Pattern: S3 Presigned POST with Policy Conditions

The industry-standard solution for client uploads is createPresignedPost from @aws-sdk/s3-presigned-post. Instead of generating an unconstrained query string, this method produces a signed policy document containing precise cryptographic conditions that AWS S3 evaluates before accepting raw byte streams.

// src/lib/s3-upload.ts - Hardened Presigned POST Ticket Generator
import { S3Client } from '@aws-sdk/client-s3';
import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
import crypto from 'node:crypto';

const s3Client = new S3Client({
  region: process.env.AWS_REGION!,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
});

interface GenerateUploadParams {
  tenantId: string;
  expectedMimeType: string;
}

const ALLOWED_MIME_TYPES = [
  'image/png',
  'image/jpeg',
  'image/webp',
  'application/pdf',
];

export async function generateSecureUploadTicket({
  tenantId,
  expectedMimeType,
}: GenerateUploadParams) {
  // 1. Validate MIME against strict server-side whitelist
  if (!ALLOWED_MIME_TYPES.includes(expectedMimeType)) {
    throw new Error('Unsupported content type');
  }

  // 2. Enforce unpredictable, tenant-isolated key paths
  const fileId = crypto.randomUUID();
  const fileKey = `tenants/${tenantId}/uploads/${fileId}`;

  // 3. Define cryptographic policy conditions
  const MIN_BYTES = 1024; // 1 KB
  const MAX_BYTES = 10 * 1024 * 1024; // 10 MB strict ceiling

  const presignedPost = await createPresignedPost(s3Client, {
    Bucket: process.env.UPLOAD_BUCKET_NAME!,
    Key: fileKey,
    Conditions: [
      // Enforce file size bounds at the AWS edge layer
      ['content-length-range', MIN_BYTES, MAX_BYTES],
      // Lock exact content-type header
      ['eq', '$Content-Type', expectedMimeType],
      // Lock exact S3 key so client cannot alter destination
      ['eq', '$key', fileKey],
      // Forbid public access control escalation
      ['eq', '$x-amz-acl', 'private'],
    ],
    Fields: {
      'Content-Type': expectedMimeType,
      'x-amz-acl': 'private',
    },
    Expires: 300, // 5 minutes TTL
  });

  return {
    uploadUrl: presignedPost.url,
    fields: presignedPost.fields,
    fileKey,
  };
}

Client Execution via Multipart FormData

Because Presigned POST uses HTTP POST multipart/form-data instead of PUT, the frontend appends the cryptographically signed fields to a FormData payload before attaching the raw file:

// frontend/upload-handler.ts - Client-Side Multipart Uploader
async function uploadFile(file: File, ticket: any) {
  const formData = new FormData();

  // AWS requires all signed policy fields to appear BEFORE the file entry
  Object.entries(ticket.fields).forEach(([key, value]) => {
    formData.append(key, value as string);
  });

  // Attach raw file last
  formData.append('file', file);

  const response = await fetch(ticket.uploadUrl, {
    method: 'POST',
    body: formData,
  });

  if (!response.ok) {
    // S3 returns an XML error with code 'EntityTooLarge' if > 10MB
    throw new Error(`Upload failed with status ${response.status}`);
  }

  return ticket.fileKey;
}

If an attacker attempts to post an 11MB file, S3 evaluates the content-length-range policy before storing bytes, aborts the request, and returns an immediate EntityTooLarge error. Your application servers never spend a single CPU cycle processing invalid data.


Pitfall 3: Incomplete Multipart Uploads and Silent Bill Inflation

Incomplete multipart uploads represent one of the most common silent AWS cost traps for fast-moving startups. When users upload files larger than 100MB, tools like the AWS S3 Transfer Manager split files into multiple 5MB chunks and upload them concurrently.

If a user closes their laptop, loses connectivity, or aborts the upload, S3 stores every uploaded chunk permanently while awaiting the final CompleteMultipartUpload API call. Because these chunks are not listed under normal ListObjectsV2 queries, developers assume the bucket is clean. Over time, these orphaned parts quietly consume terabytes of billable S3 Standard tier allocation.

                   ORPHAN MULTIPART CHUNK ACCUMULATION
                   
  Client Browser (Uploads 500MB Video)              AWS S3 Bucket Storage
  ┌────────────────────────────────────┐            ┌─────────────────────────────────────────┐
  │ Part 1 (5MB)  ──> Uploaded         │ ─────────> │ Stored in S3 (Billable S3 Standard Rate)│
  │ Part 2 (5MB)  ──> Uploaded         │ ─────────> │ Stored in S3 (Billable S3 Standard Rate)│
  │ Part 3 (5MB)  ──> Dropped Network  │            │                                         │
  │ (User closes tab; upload aborts)   │            │ [ Chunks never complete, hidden from UI]│
  └────────────────────────────────────┘            │ [ Billed every month until rule wipes ] │
                                                    └─────────────────────────────────────────┘

The Remediation: S3 Lifecycle Cleanup Rule

To eliminate orphan chunks automatically, add an explicit AWS S3 Lifecycle Configuration rule targeting incomplete multipart uploads:

{
  "Rules": [
    {
      "ID": "AbortIncompleteUploadsAfter24Hours",
      "Status": "Enabled",
      "Filter": {},
      "AbortIncompleteMultipartUpload": {
        "DaysAfterInitiation": 1
      }
    }
  ]
}

Setting this to one day ensures that genuine multi-hour uploads complete smoothly, while dropped connections or abandoned streams are automatically wiped from your bill within 24 hours. To prevent unexpected egress fees when your application downloads S3 assets, review our audit on AWS NAT Gateway Billing Traps.


Pitfall 4: Stored XSS and Content-Type Confusion

Allowing users to upload files that are served directly from an S3 bucket or custom CDN domain introduces severe Stored Cross-Site Scripting (XSS) risks if the server trusts client-provided file extensions.

If an attacker uploads an SVG or HTML file disguised as an image containing embedded <script> tags, serving the object with Content-Type: image/svg+xml without a restrictive Content-Security-Policy allows any user opening the file URL to execute JavaScript under your domain context. The script accesses localStorage, reads active session cookies, and compromises customer accounts.

Defensive Mitigations

  1. Force Attachment Downloads: For user-generated files that do not need in-browser rendering, set Content-Disposition: attachment; filename="clean_filename.pdf" in the presigned POST fields.
  2. Strict S3 Block Public Access: Ensure your upload bucket has BlockPublicAcls and BlockPublicPolicy enabled. All downloads must flow through an authenticated CDN or signed download URL.
  3. Magic Byte Verification: When an upload completes, trigger an asynchronous background worker that reads the first 512 bytes of the file to verify binary magic numbers before marking the file as active in your database.

Production S3 Upload Security Checklist

Before shipping direct-to-S3 uploads to production, audit your implementation against this architectural checklist:

  • S3 Presigned POST: Replaced unconstrained PutObject links with createPresignedPost enforcing cryptographic content-length-range bounds.
  • Tenant Path Isolation: All object keys are prefixed with server-validated tenant IDs (tenants/{tenantId}/...) and randomized UUIDs.
  • MIME Whitelisting: Client-supplied content types are validated against an allowlist on the backend before the signed policy is minted.
  • Lifecycle Auto-Abort: Configured an S3 Lifecycle Rule with AbortIncompleteMultipartUpload set to 1 day.
  • Block Public Access: Bucket-level “Block Public Access” is 100% active; zero objects can be set to public ACLs.
  • Content-Disposition Headers: Configured Content-Disposition: attachment on all non-image asset downloads to eliminate Stored XSS vectors.
  • Short Expiration Windows: Set presigned POST expiration (Expires) to 300 seconds (5 minutes) or less.

When bootstrapping an MVP, direct-to-storage architecture is the most cost-effective way to scale file processing without overloading web servers. But handing the browser direct write access requires cryptographic boundaries. Lock down byte ranges, isolate keys, and let AWS S3 handle the enforcement. For broader security protections across your stack, explore 5 Critical Security Boundaries in Rapid MVPs.

You can benchmark your edge endpoints and application latency using our Free GEO Checker & AI Readiness Scanner or review developer utilities in Diagnostic Tools.

If your team is managing cloud infrastructure security, S3 storage sprawl, or serverless boundary hardening, our senior practice provides comprehensive repository diagnostics. Explore our 48-Hour Codebase Audit or contact our engineering desk to schedule an architecture review.

Written By

Marcus Vance

Principal Systems Architect

Systems engineer focusing on distributed backends, database concurrency, and application security. Specializes in high-throughput PostgreSQL concurrency, serverless connection pooling, and infrastructure hardening.

Practice: Vexn • Focus: Deep Engineering, Infrastructure & Security
Frequently Asked Questions
Why is getSignedUrl with PutObject insecure for direct user uploads?
AWS S3 PutObject presigned URLs generated via getSignedUrl cannot cryptographically enforce upload payload size bounds or bind client-submitted MIME types. A malicious client can reuse the signed URL to stream multi-gigabyte payloads or executable HTML/SVG scripts directly into your bucket.
How does createPresignedPost prevent unconstrained file size uploads in AWS S3?
S3 Presigned POST requests evaluate policy conditions on AWS servers before accepting request bytes. By declaring a content-length-range condition (such as 1048576 to 10485760 bytes), S3 immediately rejects any payload exceeding the ceiling with an HTTP 400 Bad Request error before data persistence.
How do attackers overwrite files belonging to other tenants using presigned URLs?
When backends generate upload URLs using predictable object keys (such as avatars/user-123.png) without validating that the authenticated session owns the target directory path, an attacker can supply an arbitrary victim's file key and overwrite critical assets.
What causes silent AWS S3 storage bills from abandoned direct client uploads?
Clients using multipart presigned uploads that fail midway or get abandoned leave uncompleted parts stored in the S3 bucket indefinitely. Without an explicit S3 Lifecycle rule configured with AbortIncompleteMultipartUpload, AWS continues billing for those orphan storage chunks every month.
Need an Architectural Audit?

Have our team inspect your AI-generated codebase.

48-hour turnaround with direct pull requests fixing security and scale bottlenecks.

Request Audit