File Upload/Download Security Best Practices

Complete guide for securing file operations in web applications

Playwright + AI Test Automation Masterclass with TypeScript

Overview

File operations present significant security challenges in web applications. This guide outlines best practices to secure file upload and download functionality while maintaining testability for automation tools like Playwright, Selenium, and Cypress.

  • Rate limit upload and download endpoints
  • Restrict file size on client and server
  • Allow only safe file types
  • Scan uploads for malware
  • Store files outside web root
  • Set Content-Disposition headers
  • Log all upload/download activity
  • Use HTTPS for all file transfers

File Upload Security

Client-Side Protections

Restrict File Types

Use the accept attribute on file input elements

accept=".pdf,.txt,.png,.jpg,.csv"

⚠️ Client-side restrictions can be bypassed

File Size Limits

Validate file size using JavaScript

const maxSize = 2 * 1024 * 1024; // 2MB
if (file.size > maxSize) {
  // Show error
}

Visual Feedback

  • Progress indicators for uploads
  • Clear error messages
  • Preview functionality

Server-Side Protections

Limit upload frequency per user/IP to prevent DoS attacks

@limiter.limit("10 per hour")

Verify MIME type and extension using libraries like Python's magic

import magic
file_mime = magic.from_buffer(file.read(1024), mime=True)
if file_mime not in ALLOWED_MIMES:
    return "Invalid file type", 400

Use functions like secure_filename() to sanitize filenames

from werkzeug.utils import secure_filename
safe_name = secure_filename(file.filename)

File Download Security

Rate Limiting Downloads

Prevent scraping and bandwidth abuse:

@limiter.limit("30 per minute")

Content Headers

Use proper headers for security:

Content-Disposition: attachment
X-Content-Type-Options: nosniff

Access Control & Logging

  • Validate user permissions before serving files
  • Use signed URLs with expiration
  • Log all download activity
  • Monitor for unusual patterns

Storage Considerations

Storage Location

Store files outside web root, use separate volumes or cloud storage

Access Control

Implement proper permissions and use non-predictable URLs

Metadata Management

Store file metadata in database, don't rely on filesystem

Critical Security Reminders