import asyncio
import logging
import magic
import os
import shutil
import subprocess
import tempfile
import uuid
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
from pathlib import Path
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class FileProcessingError(Exception):
"""Custom exception for pipeline failures."""
pass
class FileProcessor:
"""
A robust file processing pipeline with:
- MIME type detection and validation (using python-magic).
- Antivirus scanning (using ClamAV via subprocess).
- Lifecycle management (storage with TTL, quarantine, and cleanup).
Dependencies (install via pip):
- python-magic-bin (or libmagic on Linux)
- ClamAV (system install: apt install clamav clamav-daemon; freshclam)
Usage:
processor = FileProcessor(
allowed_mimes=['image/jpeg', 'application/pdf'],
storage_dir='/tmp/file_storage',
quarantine_dir='/tmp/quarantine',
ttl_days=30
)
result = await processor.process_file(file_bytes, 'example.jpg', 'image/jpeg')
"""
def __init__(
self,
allowed_mimes: List[str],
storage_dir: str = "/tmp/file_storage",
quarantine_dir: str = "/tmp/quarantine",
ttl_days: int = 30,
av_clamscan_path: str = "clamscan",
av_clamdscan_path: Optional[str] = None, # For daemon mode: clamdscan --fdpass
):
self.allowed_mimes = set(allowed_mimes)
self.storage_dir = Path(storage_dir)
self.quarantine_dir = Path(quarantine_dir)
self.ttl_days = timedelta(days=ttl_days)
self.av_clamscan_path = Path(av_clamscan_path)
self.av_clamdscan_path = Path(av_clamdscan_path) if av_clamdscan_path else None
# Ensure directories exist
self.storage_dir.mkdir(parents=True, exist_ok=True)
self.quarantine_dir.mkdir(parents=True, exist_ok=True)
# In-memory lifecycle registry (use Redis/DB for production)
self.lifecycle: Dict[str, Dict] = {} # {file_id: {'path': str, 'mime': str, 'expires': datetime, 'quarantined': bool}}
async def process_file(
self,
file_bytes: bytes,
filename: str,
claimed_mime: Optional[str] = None,
) -> Dict:
"""
Main pipeline: MIME -> AV -> Lifecycle.
Returns: {'file_id': str, 'storage_path': str, 'mime': str, 'expires': datetime}
Raises: FileProcessingError on failure.
"""
file_id = str(uuid.uuid4())
logger.info(f"Processing file {filename} (ID: {file_id})")
# Step 1: MIME Detection & Validation (in-memory, fast)
detected_mime = magic.from_buffer(file_bytes, mime=True)
logger.info(f"Detected MIME: {detected_mime} (claimed: {claimed_mime})")
if detected_mime not in self.allowed_mimes:
await self._quarantine(file_bytes, filename, file_id, "Invalid MIME type")
raise FileProcessingError(f"Invalid MIME type: {detected_mime}")
if claimed_mime and detected_mime != claimed_mime:
await self._quarantine(file_bytes, filename, file_id, "MIME mismatch")
raise FileProcessingError(f"MIME mismatch: {claimed_mime} != {detected_mime}")
# Step 2: Antivirus Scan (requires temp file)
with tempfile.NamedTemporaryFile(delete=False, suffix=Path(filename).suffix) as tmp_file:
tmp_path = tmp_file.name
tmp_file.write(file_bytes)
tmp_file.flush()
os.fsync(tmp_file.fileno())
try:
scan_result = await self._scan_av(tmp_path)
if scan_result["infected"]:
await self._quarantine(file_bytes, filename, file_id, "Virus detected")
raise FileProcessingError(f"File infected: {scan_result['details']}")
finally:
os.unlink(tmp_path)
# Step 3: Storage & Lifecycle Management
storage_path = await self._store(file_bytes, filename, file_id, detected_mime)
expires = datetime.now() + self.ttl_days
self._register_lifecycle(file_id, storage_path, detected_mime, expires)
logger.info(f"File {file_id} processed successfully. Expires: {expires}")
return {
"file_id": file_id,
"storage_path": str(storage_path),
"mime": detected_mime,
"expires": expires.isoformat(),
}
async def _scan_av(self, file_path: str) -> Dict[str, any]:
"""Scan with ClamAV (supports both clamscan and clamdscan)."""
if self.av_clamdscan_path and self.av_clamdscan_path.exists():
cmd = [str(self.av_clamdscan_path), "--no-summary", "--infected", file_path]
else:
cmd = [str(self.av_clamscan_path), "--no-summary", "--infected", file_path]
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
return {
"infected": proc.returncode != 0,
"details": stdout.decode().strip() or stderr.decode().strip(),
}
async def _store(self, file_bytes: bytes, filename: str, file_id: str, mime: str) -> Path:
"""Store file with unique name."""
safe_name = f"{file_id}_{Path(filename).name}"
storage_path = self.storage_dir / safe_name
with open(storage_path, "wb") as f:
f.write(file_bytes)
return storage_path
async def _quarantine(self, file_bytes: bytes, filename: str, file_id: str, reason: str):
"""Move to quarantine for review."""
safe_name = f"{file_id}_{Path(filename).name}"
quat_path = self.quarantine_dir / safe_name
with open(quat_path, "wb") as f:
f.write(file_bytes)
self._register_lifecycle(file_id, str(quat_path), "application/quarantined", datetime.now(), True)
logger.warning(f"Quarantined {file_id}: {reason}")
def _register_lifecycle(self, file_id: str, path: str, mime: str, expires: datetime, quarantined: bool = False):
"""Register file in lifecycle (in-memory; use DB in prod)."""
self.lifecycle[file_id] = {
"path": path,
"mime": mime,
"expires": expires,
"quarantined": quarantined,
}
async def cleanup_expired(self):
"""Async cleanup of expired files (call periodically, e.g., via cron)."""
now = datetime.now()
expired = []
for file_id, info in list(self.lifecycle.items()):
if now > info["expires"]:
path = Path(info["path"])
if path.exists():
path.unlink()
logger.info(f"Cleaned expired file: {file_id}")
expired.append(file_id)
for file_id in expired:
del self.lifecycle[file_id]
# Example usage (async main)
async def main():
processor = FileProcessor(
allowed_mimes=["image/jpeg", "image/png", "application/pdf"],
ttl_days=7
)
# Simulate file bytes
with open("example.jpg", "rb") as f: # Replace with real file
file_bytes = f.read()
try:
result = await processor.process_file(file_bytes, "example.jpg", "image/jpeg")
print("Success:", result)
# Cleanup demo
await processor.cleanup_expired()
except FileProcessingError as e:
print("Failed:", str(e))
if __name__ == "__main__":
asyncio.run(main())
Key Features
- Modular & Async: Handles large files efficiently; AV scan is subprocess-based for safety.
- MIME: Detects real type (
python-magic), validates against allowlist, checks claimed MIME.
- Antivirus: Uses
clamscan (standalone) or clamdscan (daemon for speed). Quarantines infected files.
- Lifecycle: Stores with UUID, TTL-based expiration, in-memory registry (extend to Redis/Postgres), auto-cleanup task.
- Security: Temp files auto-delete, safe naming, quarantine on failure.
- Production Notes:
- Run ClamAV daemon (
freshclam for updates).
- Scale with queues (Celery/RabbitMQ) for high throughput.
- Add rate limiting, size limits (<100MB).
- Streaming support: Modify for
aiofiles if needed.
- Metrics: Integrate Prometheus for scan times.
This pipeline is secure, scalable, and ready to deploy! Test with EICAR test virus for AV. 🚀