The user wants a "safe upload pipeline" that includes:
- Streaming: Handling large files without buffering the whole thing in memory.
- AV Scan: Checking for viruses/malware.
- MIME: Validating the actual file type (not just trusting the extension).
- Lifecycle: Managing the file from temporary storage to permanent storage (and potentially cleanup).
I need to provide a conceptual design and code examples to illustrate these components. Since no specific language was requested, I will use Python (Flask/FastAPI style) or Node.js as they are common for this, but Python offers a clearer library ecosystem for AV scanning (Clamd) and MIME typing (python-magic). I'll stick to Python for the implementation examples but explain the architecture generally.
Architecture Overview:
- Client: Sends
multipart/form-data.
- Server (Ingress): Receives stream.
- Validation Layer: Checks MIME type (Magic bytes).
- Quarantine/Temp Storage: Stream to disk (not memory).
- Scanning Layer: Asynchronous AV scan.
- Promotion Layer: Move to permanent storage if clean.
- Cleanup Layer: Cron job or TTL for temp files.
Step-by-Step Implementation Plan:
-
Streaming (The Foundation):
- Don't use
request.files['file'].read(). That loads into RAM.
- Use
shutil.copyfileobj or streaming saver libraries (like werkzeug FileStorage).
- Destination: A "Quarantine" or "Temp" bucket/folder.
-
MIME Validation (The Gatekeeper):
- Crucial Security Principle: Never trust
Content-Type header.
- Use "Magic Numbers" (libmagic).
- Ideally, check this during stream or immediately after landing in temp. Checking during stream is complex (need to buffer the header), so usually, we stream to temp, then check magic bytes, then decide whether to proceed to AV.
- Refinement: To be truly safe, check MIME before AV scanning to save resources on obvious junk.
-
AV Scanning (The Inspector):
- Tool: ClamAV is the industry standard for open-source implementation.
- Integration:
clamd python library or using the clamdscan binary.
- Mechanism: The file sits in the temp folder. We trigger a scan.
- Result: "FOUND" (Virus) -> Delete. "OK" -> Promote.
-
Lifecycle Management (The Organizer):
- States:
UPLOADING (Streaming to temp)
QUARANTINE (Awaiting scan)
PROCESSING (Scanning)
CLEAN (Ready for use)
INFECTED (Flagged for deletion)
- Storage: Local Disk vs. S3/Object Storage. I should design for Object Storage (S3) as it's modern standard, but Local Disk is easier for code examples. I'll stick to Local Disk for simplicity but mention S3.
Drafting the Code Structure (Python/Flask context):
Refining the "Safe" Aspect:
- Filename Sanitization: Never use the user's filename on the server. Use UUIDs.
- Permissions: Temp folders should not be executable.
- Size Limits: Enforce
Content-Length or limit stream size.
Reviewing the "Lifecycle" Request:
- This implies long-term management. I should mention TTL (Time To Live) for failed uploads or temporary files that never got processed.
Structure of the Response:
- Architectural Diagram (Text-based): Visualizing the flow.
- Security Prerequisites: Size limits, Nonces, etc.
- Implementation Phase 1: Streaming & Storage (Quarantine).
- Implementation Phase 2: MIME Validation (Magic Bytes).
- Implementation Phase 3: AV Scanning.
- Implementation Phase 4: Promotion & Lifecycle.
- Code Example (Python).
Self-Correction/Double Check:
- MIME check:
python-magic requires libmagic installed. filetype is pure Python. filetype might be easier for a snippet, but magic is more robust. I'll use a generic verify_mime function logic.
- Streaming: In Flask,
request.files['file'].save(path) handles streaming automatically. In FastAPI, UploadFile uses spooled temp file. I need to make sure I explicitly show how to stream to disk to avoid RAM bloat.
- ClamAV: Needs to be running as a daemon (
clamd) for performance, otherwise clamdscan startup time kills latency.
Let's write the Python code. I will simulate the AV scan part so the code is runnable without installing ClamAV, but explain how to hook it up.
Final Plan:
- Architecture: Quarantine -> Validate -> Scan -> Promote.
- Tech Stack: Python (FastAPI/Flask style) + ClamAV + Filetype lib.
- Key Constraints: No RAM buffering, UUID filenames, strict MIME allow-list.
Let's assemble.
Designing a secure file upload pipeline requires a "Zero Trust" approach. You cannot trust the file extension, the MIME type sent by the client, or the file content itself until it has been validated and sanitized.
Here is a comprehensive design and implementation strategy for a safe upload pipeline.
The Architecture: "The Airlock"
Do not write files directly to their final destination. All files must enter an "Airlock" (a temporary quarantine zone) where they undergo inspection. Only after passing all checks are they promoted to permanent storage.
The Stages:
- Ingress (Streaming): Receive the file without loading it entirely into RAM.
- Quarantine: Store temporarily with a random UUID filename.
- Validation: Check Magic Bytes (MIME) and structural integrity.
- Sanitization (AV Scan): Scan for malware.
- Promotion: Move to final storage (S3, Azure Blob, etc.).
- Lifecycle: Enforce retention policies.
1. Streaming & Validation (Python Implementation)
We will use Python with FastAPI (for async streaming) and python-magic (for MIME detection) to demonstrate.
Prerequisites
pip install fastapi uvicorn python-magic clamd # libmagic must be installed on OS
The Pipeline Code
import os
import shutil
import uuid
import magic # python-magic
import clamd # Requires clamav daemon running
from fastapi import FastAPI, UploadFile, HTTPException, status
from pathlib import Path
# Configuration
UPLOAD_DIR = "uploads"
QUARANTINE_DIR = "quarantine"
ALLOWED_MIME_TYPES = {"image/jpeg", "image/png", "application/pdf"}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
# Ensure directories exist
Path(UPLOAD_DIR).mkdir(exist_ok=True)
Path(QUARANTINE_DIR).mkdir(exist_ok=True)
app = FastAPI()
# --- 1. STREAMING & SIZE ENFORCEMENT ---
async def stream_to_quarantine(file: UploadFile) -> tuple[str, Path]:
"""
Streams file to a temporary quarantine folder using a UUID filename.
Prevents memory overflow and filename collisions.
"""
# Generate a safe, unique ID for the filename to prevent
# Path Traversal attacks (e.g., "../../../evil.sh")
safe_filename = f"{uuid.uuid4()}"
quarantine_path = Path(QUARANTINE_DIR) / safe_filename
# Stream the file in chunks to disk
real_size = 0
try:
with open(quarantine_path, "wb") as buffer:
while True:
chunk = await file.read(65536) # 64KB chunks
if not chunk:
break
real_size += len(chunk)
# Enforce size limit DURING upload, not after
if real_size > MAX_FILE_SIZE:
buffer.close()
os.remove(quarantine_path)
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail="File exceeds size limit"
)
buffer.write(chunk)
except Exception as e:
if quarantine_path.exists():
os.remove(quarantine_path)
raise e
return safe_filename, quarantine_path
# --- 2. MIME VALIDATION (MAGIC BYTES) ---
def validate_mime_type(file_path: Path) -> str:
"""
Reads the 'Magic Bytes' (first few bytes) of the file to determine
the REAL type, ignoring the file extension and client-provided headers.
"""
try:
# Read first 2048 bytes to guess the type
initial_bytes = file_path.read_bytes(2048)
detected_type = magic.from_buffer(initial_bytes, mime=True)
if detected_type not in ALLOWED_MIME_TYPES:
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
detail=f"File type {detected_type} is not allowed."
)
return detected_type
except Exception as e:
raise HTTPException(status_code=400, detail="Could not determine file type.")
# --- 3. AV SCANNING ---
def scan_for_viruses(file_path: Path):
"""
Connects to a local ClamAV daemon to scan the file.
In production, this might be an AWS S3 Scan or a dedicated microservice.
"""
try:
# Assuming ClamAV is running on localhost
cd = clamd.ClamdUnixSocket()
# Scan the specific file
scan_result = cd.scan(str(file_path))
# Parse result: {'path': ('FOUND', 'VirusName')} or {'path': ('OK', None)}
status_key = list(scan_result.keys())[0]
result, virus_name = scan_result[status_key]
if result == "FOUND":
# LOG THE VIRUS DETAILS SECURELY
print(f"SECURITY ALERT: Virus detected: {virus_name} in {file_path}")
# Delete the infected file immediately
os.remove(file_path)
raise HTTPException(status_code=400, detail="File infected.")
except clamd.ClamdError as e:
# If the scanner is down, fail safe (deny upload)
print(f"AV Connection Error: {e}")
raise HTTPException(status_code=503, detail="Antivirus service unavailable.")
# --- PIPELINE ORCHESTRATION ---
@app.post("/upload")
async def upload_file(file: UploadFile):
q_path = None
try:
# Step 1: Stream to Quarantine
uid, q_path = await stream_to_quarantine(file)
# Step 2: MIME Check (White-listing)
mime_type = validate_mime_type(q_path)
# Step 3: AV Scan
scan_for_viruses(q_path)
# Step 4: Promotion
# Determine final extension based on MIME, not user input
ext_map = {"image/jpeg": ".jpg", "image/png": ".png", "application/pdf": ".pdf"}
final_name = f"{uid}{ext_map[mime_type]}"
final_path = Path(UPLOAD_DIR) / final_name
# Atomic move (assuming same filesystem)
os.rename(q_path, final_path)
return {"status": "success", "filename": final_name}
except HTTPException as e:
# Clean up quarantine if validation fails
if q_path and q_path.exists():
os.remove(q_path)
raise e
2. Lifecycle Management
Files accumulate and can become a security risk or a cost burden. You need a lifecycle policy.
Retention Policies (TTL)
You should implement a "Janitor" service (a Cron job or a Lambda function) that runs periodically.
- Incomplete Uploads: Files stuck in
/quarantine older than 24 hours (indicating a failed upload process) should be deleted.
- Temporary Shares: If your app generates "expiring links," ensure the underlying file is deleted when the link expires.
Implementation Example (Bash/Cron)
# Run daily to clean up files older than 7 days in quarantine
find /app/quarantine/ -type f -mtime +7 -delete
3. Infrastructure Security Layers
The code is not enough. The infrastructure hosting these files must be hardened.
-
Storage Isolation:
- Store uploads on a separate volume or bucket (e.g., do not store user uploads on the
C:/ or / drive of your OS).
- If the drive fills up due to an attack, the OS and application should remain operational.
-
Disable Execution:
- Linux: Mount the upload directory with
noexec flag in /etc/fstab. This prevents binaries from being executed even if they are uploaded.
- S3/Cloud Storage: Ensure bucket policies prevent public writing and enable "S3 Object Lock" (WORM) for compliance if needed.
-
Serving Files (Download):
- Never use
send_file(filename) directly if the filename comes from user input.
- Use X-Sendfile (Nginx/Apache) or pre-signed URLs (S3).
- Set Content-Disposition: attachment to force download rather than execution in the browser.
- Strip executable MIME types and serve everything as
application/octet-stream if possible.
Summary of the Pipeline Flow
- Request: User sends file.
- Stream: Server chunks data to
/quarantine/{uuid}.
- MIME: Server reads magic bytes. If not JPG/PNG/PDF -> DELETE & BLOCK.
- AV: Server asks ClamAV to check file. If
FOUND -> DELETE & BLOCK.
- Promote: Move file to
/uploads/{uuid}.jpg.
- Cleanup: A separate process deletes files in
/uploads after 30 days (based on your policy).