-
Notifications
You must be signed in to change notification settings - Fork 7
✨(feature): Image proxy for CSP compliance and privacy protection #398
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mosa-riel
wants to merge
8
commits into
suitenumerique:main
Choose a base branch
from
mosacloud:feat/image-proxy-simple
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b8be53f
feat(backend): add simple image proxy without caching
mosa-riel aebc575
chore: regenerate poetry.lock with beautifulsoup4
mosa-riel 5cada17
fix(backend): correct image proxy API routing and URL generation
mosa-riel 76276cc
refactor(backend): use env vars for image proxy config and fix import…
mosa-riel d604e76
fix(backend): correct inline image URL rewriting for CID attachments
mosa-riel ea63279
feat: improve image loading performance with lazy loading, HTTP/2, an…
mosa-riel 6f22e9b
security: add SSRF protection and harden image proxy
mosa-riel 894d12a
fix: replace imghdr with python-magic for Python 3.13 compatibility
mosa-riel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| """API ViewSet for proxying external images.""" | ||
|
|
||
| import logging | ||
| from urllib.parse import unquote | ||
|
|
||
| import requests | ||
| from django.conf import settings | ||
| from django.http import HttpResponse | ||
| from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema | ||
| from rest_framework import status | ||
| from rest_framework.decorators import action | ||
| from rest_framework.response import Response | ||
| from rest_framework.viewsets import ViewSet | ||
|
|
||
| from core import models | ||
| from core.api import permissions | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ImageProxyViewSet(ViewSet): | ||
| """ | ||
| ViewSet for proxying external images to protect user privacy. | ||
| Images are fetched on-demand from external sources and served through | ||
| the application. This prevents tracking pixels from leaking user IP | ||
| addresses and browsing behavior to external servers. | ||
| """ | ||
|
|
||
| permission_classes = [permissions.IsAuthenticated] | ||
|
|
||
| @extend_schema( | ||
| description="""Proxy an external image through the server. | ||
| This endpoint fetches images from external sources and serves them | ||
| through the application to protect user privacy. Requires the | ||
| PROXY_EXTERNAL_IMAGES environment variable to be set to true. | ||
| """, | ||
| parameters=[ | ||
| OpenApiParameter( | ||
| name="mailbox_id", | ||
| type=str, | ||
| location=OpenApiParameter.PATH, | ||
| description="ID of the mailbox", | ||
| required=True, | ||
| ), | ||
| OpenApiParameter( | ||
| name="url", | ||
| type=str, | ||
| location=OpenApiParameter.QUERY, | ||
| description="The external image URL to proxy", | ||
| required=True, | ||
| ), | ||
| ], | ||
| responses={ | ||
| 200: OpenApiResponse(description="Image content"), | ||
| 400: OpenApiResponse(description="Invalid request"), | ||
| 403: OpenApiResponse(description="Forbidden"), | ||
| 413: OpenApiResponse(description="Image too large"), | ||
| 502: OpenApiResponse(description="Failed to fetch external image"), | ||
| }, | ||
| ) | ||
| def list(self, request, mailbox_id=None): | ||
| """Proxy an external image through the server.""" | ||
| try: | ||
| mailbox = models.Mailbox.objects.get(pk=mailbox_id) | ||
| except models.Mailbox.DoesNotExist: | ||
| return Response( | ||
| {"error": "Mailbox not found"}, status=status.HTTP_404_NOT_FOUND | ||
| ) | ||
|
|
||
| if not mailbox.accesses.filter(user=request.user).exists(): | ||
| return Response( | ||
| {"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN | ||
| ) | ||
|
|
||
| if not settings.PROXY_EXTERNAL_IMAGES: | ||
| return Response( | ||
| {"error": "Image proxy not enabled"}, | ||
| status=status.HTTP_403_FORBIDDEN, | ||
| ) | ||
|
|
||
| url = request.query_params.get("url") | ||
| if not url: | ||
| return Response( | ||
| {"error": "Missing url parameter"}, status=status.HTTP_400_BAD_REQUEST | ||
| ) | ||
|
|
||
| url = unquote(url) | ||
|
|
||
| max_size = settings.PROXY_MAX_IMAGE_SIZE_MB * 1024 * 1024 | ||
|
|
||
| try: | ||
| response = requests.get( | ||
| url, | ||
| timeout=10, | ||
| stream=True, | ||
| headers={"User-Agent": "Messages-ImageProxy/1.0"}, | ||
| ) | ||
| response.raise_for_status() | ||
|
|
||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| content_type = response.headers.get("content-type", "") | ||
| if not content_type.startswith("image/"): | ||
| return Response( | ||
| {"error": "Not an image"}, status=status.HTTP_400_BAD_REQUEST | ||
| ) | ||
|
|
||
| content_length = int(response.headers.get("content-length", 0)) | ||
| if content_length > max_size: | ||
| return Response( | ||
| {"error": "Image too large"}, | ||
| status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, | ||
| ) | ||
|
|
||
| image_content = response.content | ||
| if len(image_content) > max_size: | ||
| return Response( | ||
| {"error": "Image too large"}, | ||
| status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ) | ||
|
|
||
| return HttpResponse( | ||
| image_content, | ||
| content_type=content_type, | ||
| headers={ | ||
| "Cache-Control": "public, max-age=2592000", | ||
| "X-Proxied-From": url, | ||
| }, | ||
| ) | ||
|
|
||
| except requests.RequestException as e: | ||
| logger.warning("Failed to fetch external image from %s: %s", url, e) | ||
| return Response( | ||
| {"error": "Failed to fetch image"}, status=status.HTTP_502_BAD_GATEWAY | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add 404 response to OpenAPI schema.
The implementation returns 404 when the mailbox is not found (lines 70-72), but this response code is not documented in the OpenAPI schema.
Apply this diff:
responses={ + 404: OpenApiResponse(description="Mailbox not found"), },📝 Committable suggestion
🤖 Prompt for AI Agents