The user wants a "file processing pipeline" that includes three specific stages:
- Antivirus: Scanning files for malware.
- MIME: Verifying or identifying the MIME type (Content-Type) of files.
- Lifecycle: Managing the file's state (e.g., quarantined, processed, archived, deleted).
The user hasn't specified a programming language or a specific framework (like Apache Airflow, AWS Step Functions, or a simple Python script). I need to provide a comprehensive answer that likely covers the architecture and provides a concrete implementation example (probably in Python, as it's the standard for this kind of glue code).
Key Components to Design:
- Interface: What does a "File" look like in this system?
- Pipeline Pattern: Should be a Chain of Responsibility or a simple series of function calls.
- Stage 1: Antivirus: How do we do this?
- Mock implementation: Simulate scanning.
- Real-world note: Mention ClamAV.
- Stage 2: MIME detection:
- Library:
python-magic (libmagic wrapper) is the standard.
- Logic: Check if the actual content matches the extension or allowed types.
- Stage 3: Lifecycle Management:
- Logic: Based on the results of previous stages, move the file to specific folders (Clean, Quarantine, Trash).
- Orchestration: How to put it together.
Drafting the Solution (Python Context):
- Setup: Define a data class or dictionary for the
FileContext (path, metadata, scan result, mime type).
- Abstract Base Class (optional but good for structure):
PipelineStep.
- Step 1: AntivirusScanner:
- Input: File path.
- Action: Call an AV engine.
- Output: Boolean (Clean/Infected).
- Refinement: If infected, we might want to short-circuit the pipeline to quarantine immediately.
- Step 2: MimeDetector:
- Input: File path.
- Action:
python-magic.
- Validation: Is this type allowed?
- Step 3: LifecycleManager:
- Input: Results from 1 & 2.
- Action: Move file to
/clean, /quarantine, or delete.
- Main Runner: Loop through files, apply steps.
Refining the Implementation Details:
- Antivirus: I can't actually run ClamAV in the snippet, so I'll create a mock class that looks for a specific signature (e.g., "virus" in filename or content) to demonstrate logic.
- MIME: I'll use
mimetypes standard library for simplicity in a standalone example, but mention python-magic for production robustness.
- Lifecycle: Moving files using
shutil.
Structuring the Answer:
- High-Level Architecture: Explain the flow (Ingest -> Scan -> Validate -> Route).
- Prerequisites: Mention tools like ClamAV and libmagic.
- Code Implementation: A modular Python script.
- Use a class-based approach for extensibility.
- Define a
FileContext to pass data between steps.
- Explanation of each stage.
- Production considerations: Scalability, Blocking I/O, Distributed Queues (Celery/SQS).
Self-Correction during drafting:
Initial thought: Just write one big function.
Correction: That's bad practice. Use a pipeline pattern so the user can easily add steps (like "OCR" or "Metadata Extraction") later.
Initial thought: Use python-magic.
Correction: That requires system dependencies (libmagic) which might make the example hard to run immediately for the user. I'll use mimetypes from the standard library for the demo but strongly advise libmagic for real security (magic numbers).
Final Plan:
- Define
FileContext.
- Define
PipelineStep interface.
- Implement
AntivirusStep (Mock).
- Implement
MimeValidationStep.
- Implement
LifecycleStep.
- Implement the
Pipeline executor.
- Add a usage example.
Let's write the code mentally to ensure it flows.
context = FileContext(path)
step1.process(context) -> sets context.is_infected
step2.process(context) -> sets context.mime_type
step3.process(context) -> moves file based on is_infected and mime_type.
This looks solid. I will also add error handling.
Extra Credit: Mentioning "Magic Bytes". MIME type by extension is insecure. I must emphasize validating the file header (magic numbers).
Let's generate the response.
This design outlines a robust, modular file processing pipeline in Python. It uses a "Chain of Responsibility" pattern, allowing you to easily add, remove, or reorder processing steps.
Architecture Overview
- Ingestion: A file is wrapped in a
FileContext object.
- Antivirus Stage: Scans the binary for signatures (mocked here, but structured for ClamAV integration).
- MIME Stage: Inspects the file "Magic Numbers" (headers) to verify the true file type, preventing extension spoofing.
- Lifecycle Stage: Moves the file to specific directories (Quarantine, Processing, Rejected) based on the results of previous stages.
Python Implementation
You will need python-magic (a wrapper around libmagic) for accurate MIME detection.
pip install python-magic-bin # Windows
pip install python-magic # Linux/Mac (requires libmagic installed)
Here is the complete pipeline implementation:
import os
import shutil
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum, auto
import mimetypes
# Configure Logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# --- 1. Data Context ---
class FileStatus(Enum):
PENDING = auto()
INFECTED = auto()
INVALID_MIME = auto()
PROCESSED = auto()
@dataclass
class FileContext:
"""Holds the state and metadata of the file as it moves through the pipeline."""
filepath: str
status: FileStatus = FileStatus.PENDING
mime_type: str = None
reason: str = None
metadata: dict = field(default_factory=dict)
# --- 2. Pipeline Infrastructure ---
class PipelineStep(ABC):
"""Abstract base class for pipeline steps."""
@abstractmethod
def process(self, context: FileContext) -> FileContext:
pass
class FilePipeline:
"""Orchestrates the execution of steps."""
def __init__(self, steps: list[PipelineStep]):
self.steps = steps
def execute(self, context: FileContext) -> FileContext:
logger.info(f"Starting pipeline for: {context.filepath}")
for step in self.steps:
# If a step marks the file as "terminal" (e.g., Infected), we stop processing
if context.status != FileStatus.PENDING and context.status != FileStatus.PROCESSED:
logger.warning(f"Pipeline halted for {context.filepath}. Reason: {context.reason}")
break
context = step.process(context)
logger.info(f"Pipeline finished for: {context.filepath} with status {context.status.name}")
return context
# --- 3. Concrete Steps ---
class AntivirusStep(PipelineStep):
"""
Simulates an Antivirus scan.
In production, this would interface with ClamAV, VirusTotal API, or a local SDK.
"""
def __init__(self, quarantine_dir: str):
self.quarantine_dir = quarantine_dir
os.makedirs(quarantine_dir, exist_ok=True)
def process(self, context: FileContext) -> FileContext:
logger.info(f"Scanning {context.filepath} for viruses...")
# Mock Logic: Simulate detecting a virus if file contains 'eicar' or 'virus'
# In reality: clamav.scan(context.filepath)
is_malicious = False
try:
with open(context.filepath, 'rb') as f:
content = f.read()
if b'eicar' in content or b'virus' in content:
is_malicious = True
except Exception as e:
logger.error(f"Error reading file for AV scan: {e}")
is_malicious = True # Fail-safe: Treat unreadable as suspicious
if is_malicious:
context.status = FileStatus.INFECTED
context.reason = "Malware signature detected"
# Immediate lifecycle action: Move to quarantine
self._move_file(context.filepath, self.quarantine_dir)
return context
def _move_file(self, src, dest_dir):
filename = os.path.basename(src)
dest = os.path.join(dest_dir, filename)
shutil.move(src, dest)
logger.info(f"File moved to quarantine: {dest}")
class MimeValidationStep(PipelineStep):
"""
Validates file content type (MIME) against allowed types.
Uses 'magic' numbers (file headers) not just extensions.
"""
def __init__(self, allowed_mimes: list[str]):
self.allowed_mimes = allowed_mimes
def process(self, context: FileContext) -> FileContext:
# Note: In a real app, import magic library here
# import magic
# mime_type = magic.from_file(context.filepath, mime=True)
# Fallback to standard mimetypes for this demo to run without libmagic dependencies
mime_type, _ = mimetypes.guess_type(context.filepath)
context.mime_type = mime_type
logger.info(f"Detected MIME: {mime_type}")
if mime_type not in self.allowed_mimes:
context.status = FileStatus.INVALID_MIME
context.reason = f"Disallowed MIME type: {mime_type}"
else:
# If valid, mark as PROCESSED (ready for business logic)
context.status = FileStatus.PROCESSED
return context
class LifecycleManagerStep(PipelineStep):
"""
Final disposition manager. Moves files based on their status.
"""
def __init__(self, processed_dir: str, rejected_dir: str):
self.processed_dir = processed_dir
self.rejected_dir = rejected_dir
os.makedirs(processed_dir, exist_ok=True)
os.makedirs(rejected_dir, exist_ok=True)
def process(self, context: FileContext) -> FileContext:
dest = None
if context.status == FileStatus.PROCESSED:
dest = self.processed_dir
elif context.status == FileStatus.INVALID_MIME:
dest = self.rejected_dir
if dest:
filename = os.path.basename(context.filepath)
# Check if file still exists (AV might have moved it)
if os.path.exists(context.filepath):
shutil.move(context.filepath, os.path.join(dest, filename))
logger.info(f"Lifecycle: Moved {filename} to {dest}")
return context
# --- 4. Execution / Main ---
def main():
# Setup Directories
IN_DIR = "input_files"
os.makedirs(IN_DIR, exist_ok=True)
# Create dummy files for testing
with open(os.path.join(IN_DIR, "safe_document.pdf"), "w") as f:
f.write("Safe content")
with open(os.path.join(IN_DIR, "malware.exe"), "w") as f:
f.write("This contains eicar virus signature")
with open(os.path.join(IN_DIR, "fake_image.jpg"), "w") as f:
f.write("Actually a script file")
# Define the Pipeline
# Only allow PDFs and Plain Texts
pipeline = FilePipeline([
AntivirusStep(quarantine_dir="quarantine"),
MimeValidationStep(allowed_mimes=['application/pdf', 'text/plain']),
LifecycleManagerStep(processed_dir="storage", rejected_dir="rejected")
])
# Process Files
files = [os.path.join(IN_DIR, f) for f in os.listdir(IN_DIR)]
for file_path in files:
ctx = FileContext(filepath=file_path)
result = pipeline.execute(ctx)
print("-" * 30)
print(f"File: {file_path}")
print(f"Final Status: {result.status.name}")
print(f"Reason: {result.reason}")
print("-" * 30)
if __name__ == "__main__":
main()
How It Works
- Antivirus Step: This runs first. It opens the file and looks for signatures. In this code, it looks for the string "eicar" (a standard test string for AV). If found, it marks the context as
INFECTED and immediately moves the file to the quarantine folder. The pipeline checks the status before running the next step; since it is INFECTED, subsequent steps (MIME/Lifecycle) are skipped.
- MIME Step: If the file is clean, this step runs. It guesses the MIME type. We configured the pipeline to only allow PDFs and Text files.
safe_document.pdf: Passes.
fake_image.jpg: The content is text, but the extension is .jpg. The mimetypes library (or libmagic in production) detects this. If it doesn't match the allowed list, it sets status to INVALID_MIME.
- Lifecycle Step: This is the cleanup crew.
- If status is
PROCESSED (Clean + Valid MIME), it moves to storage.
- If status is
INVALID_MIME, it moves to rejected.
Production Considerations
- True Magic Numbers: For the MIME step, do not rely on
mimetypes (which checks file extensions). Use python-magic or libmagic to read the file header (first few bytes) to definitively identify the file type.
- Async Processing: File I/O is blocking. In a web server context, run this pipeline in a background worker (e.g., Celery, RQ, or Python's
concurrent.futures) so your API doesn't freeze while scanning large files.
- Antivirus Integration: For real AV scanning, integrate with ClamAV (open source) using the
clamd Python library, or use enterprise APIs like VirusTotal or CrowdStrike.
- Idempotency: Ensure that if the pipeline runs twice on the same file (e.g., a crash recovery), it handles duplicate moves gracefully (check if destination exists).