The user wants a secure attachment viewer design.
Key requirements:
Sanitization: Handling potentially malicious content (XSS, etc.) within files.
Media Proxies: Preventing direct access to storage, hiding URLs, and potentially resizing/transcoding.
Keys/Access Control: Ensuring only authorized users can view attachments.
Target Audience/Context: Likely a software engineer or system architect looking for a conceptual design and implementation strategy for a web application. The tone should be professional, technical, and security-focused.
Core Components to Cover:
Architecture Overview: How the pieces fit together.
Access Control (The "Keys"): Authentication and authorization.
The Proxy Layer (The "Media Proxy"): Serving the content safely.
Sanitization (The "Cleaner"): Processing uploads and downloads.
Client-Side Viewer: Displaying content safely.
Drafting the Design - Section by Section:
Introduction: Acknowledge the importance (OWASP Top 10 stuff).
Access Control (Keys & Tokens):
Problem: Direct links (S3 buckets) leak. If someone gets the URL, they have access forever.
Solution: Signed URLs or Short-lived Tokens.
Mechanism:
User requests file -> Backend checks permissions -> Backend generates a signed URL (expiry 5 mins) or a session token.
Let's go with a "Reference ID" approach where the proxy validates a specific token.
The Media Proxy (The Middleman):
Why? To hide the source storage (S3, Azure Blob) and to enforce the "Keys".
Functionality:
Intercepts request.
Validates Token.
Fetches from Storage.
(Optional but good) Transcoding/Resizing.
Security Headers: CSP, Content-Disposition, etc.
Sanitization (The heavy lifting):
Two stages: Upload (Don't let bad stuff in) and Download/Display (Don't let bad stuff execute).
File Type Validation: Magic bytes, not just extensions.
Image Stripping: EXIF data (GPS location) needs to go. exiftool or imagemagick.
Document Sanitization (PDF/Office): This is hard.
PDF: Use a viewer that renders to canvas (no JS execution) or sanitize tools.
Office: Convert to PDF or use Google Docs viewer (privacy risk) or Office Online (expensive) or self-hosted LibreOffice conversion.
Video/Audio: Transcoding is best to remove metadata.
Client-Side Isolation (Sandboxing):
Even if sanitization fails, how do we prevent XSS?
Iframe: Use the sandbox attribute.
CSP: Content Security Policy is crucial.
Separate Domain: Serve attachments from cdn.example.com or static.example.com (not www.example.com) so cookies aren't sent and DOM access is blocked by Same-Origin Policy.
Summary/Architecture Diagram (Mental):
User -> API (Auth) -> Signed URL -> Proxy (Validation + Sanitize) -> Storage.
Refining the Details:
Sanitization: I should emphasize "Polyglot files" (files that are valid images and valid scripts).
Proxy: Mention caching.
Keys: JWT or Opaque tokens.
Structure of the Response:
High-Level Architecture: The flow.
Component 1: Authorization (The Keys): Short-lived access.
Component 2: The Media Proxy: The gateway.
Component 3: Sanitization Pipeline: The cleaning crew (Upload vs Download).
Component 4: Client-Side Isolation: The sandbox.
Technology Stack Recommendations.
Self-Correction/Review during drafting:
Initial thought: Just strip EXIF on upload.
Correction: What if the user wants the original? Maybe stripping on download (on-the-fly) is better for fidelity, but slower. For a "secure viewer," on-the-fly stripping is usually preferred for privacy, or store a "dirty" original and a "clean" viewable version. Let's suggest storing a clean viewable version for performance.
PDFs: Serving raw PDFs is dangerous (JS in PDFs). Using a JS-based PDF renderer (like PDF.js) is safer because it renders to canvas and doesn't execute embedded scripts.
Final Polish:
Organize with clear headings, bullet points for readability, and a concluding summary. Use bold text for emphasis. (e.g., Magic Bytes, Sandbox).
Let's write the response following this structure.
Designing a secure attachment viewer requires a defense-in-depth approach. You cannot trust the file uploader, the file itself, or the network.
Here is a comprehensive design for a Secure Attachment Viewer system, broken down into four layers: Access Control, The Proxy Layer, Sanitization, and Client-Side Isolation.
1. High-Level Architecture
Instead of giving the client a direct link to storage (e.g., an S3 URL), all traffic must route through your application backend.
The Flow:
Client requests a specific attachment ID via an API call.
Auth Service verifies the user has permission to view this specific attachment.
Key Manager issues a short-lived, single-use signed URL or token.
Media Proxy uses the token to fetch the blob from private storage.
Sanitization Engine strips metadata and dangerous content.
Client renders the blob inside a sandboxed iframe.
2. Layer 1: Access Control & Key Management
Never use static URLs for sensitive assets. Use "Valet Key" patterns.
Reference by ID: The client never knows the file path or filename. They only know the database UUID (e.g., GET /attachments/550e8400-e29b...).
Authorization Logic: Before returning any data, check if current_user.id == attachment.owner_id (or role-based permissions).
Signed URLs (The Keys):
If offloading serving to cloud storage (like S3), generate a Pre-Signed URL that expires in 60 seconds.
Constraint: Ensure the signature logic binds the user's session or IP address to the URL to prevent sharing the link.
3. Layer 2: The Media Proxy
This is your first line of defense against malicious files and data leakage.
Why use a proxy?
Hiding Source: It masks the origin bucket URL.
Content Disposition: It forces the browser to handle the file correctly (e.g., preventing a download vs. display mismatch).
Virus Scanning: You can stream the file through a scanner (like ClamAV) before the proxy finishes the response.
Proxy Logic:
Receive request -> Validate Auth Token.
Fetch stream from Private Object Storage (S3/Google Cloud).
Enforce MIME types: Do not trust the file extension. Use libmagic to detect the true file type.
Security Check: If the file is malware.exe but named image.jpg, reject it immediately.
Data must be cleaned both when it enters (Ingestion) and when it leaves (Serving).
A. Ingestion (Upload Time)
Re-encoding: For images, do not store the original user bytes. Use ImageMagick or Libvips to read the image and save it as a fresh PNG/WebP. This strips all malicious code hidden in compression layers or comments.
PDF Handling: PDFs are dangerous (they can contain JavaScript). Convert uploaded PDFs to a safe format (like PDF/A) or rasterize the first page to an image for the preview.
B. On-Demand Sanitization (View Time)
If you must serve HTML or PDFs (which are active content):
HTML: Use a library like DOMPurify to strip scripts.
PDF: Serve using a specialized "PDF Viewer" microservice that renders the PDF to HTML/Canvas on the server side (using something like pdf2htmlEX) so the client receives only safe HTML/CSS, not a binary executable PDF.
5. Layer 4: Client-Side Isolation (The Viewer)
Even with sanitization, assume the file might try to execute a "Zero-Day" exploit in the browser. You must contain the blast radius.
A. The Sandbox Domain
Do not serve user attachments on the same domain as your application (e.g., app.com).
Use a separate subdomain: cdn-sandbox.app.com.
Cookie Scope: Set cookies on app.com with the Secure and HttpOnly flags. The sandbox domain should not have access to these session cookies.
B. The Iframe Sandbox
Display the attachment in an <iframe> with strict attributes:
html
<iframe
src="https://cdn-sandbox.app.com/viewer/uuid"
sandbox="allow-same-origin allow-scripts"
<!-- Note: Do NOT allow popups, forms, or top-navigation -->
referrerpolicy="no-referrer"
></iframe>
sandbox attribute: By default, this disables plugins (Flash/Java), forms, and navigation of the parent window.
Content Security Policy (CSP): Apply a strict CSP to the sandboxed page.
6. Implementation Guide (Tech Stack Agnostic)
Here is a logical sequence for building this feature:
Step 1: Storage Configuration
Create a private bucket (S3/GCS).
Block all public access.
Step 2: Ingestion Service (Lambda/Background Worker)
User uploads to a temporary "Quarantine" bucket.
Trigger function:
Check MIME type.
Scan with Antivirus.
Re-encode image (stripping EXIF).
Move to "Clean" private bucket.
Store metadata (size, mime, hash) in Database.
Step 3: The Proxy Endpoint (Node/Python/Go)
python
# Pseudo-code for the proxy
def get_attachment(request, attachment_id):
user = request.user
attachment = db.get(attachment_id)
# 1. Check Keys/Perms
if attachment.owner != user.id:
return 403
# 2. Generate Signed URL (valid for 30s)
signed_url = s3_client.generate_presigned_url(
Bucket='clean-bucket',
Key=attachment.storage_key,
ExpiresIn=30
)
# 3. Proxy the stream
response = requests.get(signed_url, stream=True)
# 4. Force Headers
headers = {
'Content-Type': attachment.mime_type, # Verified mime type
'X-Content-Type-Options': 'nosniff',
'Content-Security-Policy': "default-src 'self'"
}
return Response(response.iter_content(), headers=headers)
Step 4: Frontend Viewer
Create a generic viewer component.
Images: Render inside a div with background-image. This prevents drag-and-drop exploits compared to an <img> tag.
PDFs: Use a library like PDF.js running strictly inside the sandboxed iframe.
Summary Checklist
Storage: Private by default.
Keys: Short-lived, signed URLs.
Sanitization: Re-encode images on upload; strip EXIF.
Proxy: Verify MIME type, set nosniff headers.
Isolation: Serve on a sandbox subdomain with strict CSP.