Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix CVE-2026-23499

Mikail Kocakb3cb27b3fe96
diff --git a/saleor/core/error_codes.py b/saleor/core/error_codes.py
index 2da539ae14..f397956fe4 100644
--- a/saleor/core/error_codes.py
+++ b/saleor/core/error_codes.py
@@ -29,6 +29,8 @@ class TranslationErrorCode(Enum):
class UploadErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
+ INVALID_FILE_TYPE = "invalid_file_type"
+ UNSUPPORTED_MIME_TYPE = "unsupported_mime_type"
class CoreErrorCode(Enum):
diff --git a/saleor/core/management/commands/remove_invalid_files.py b/saleor/core/management/commands/remove_invalid_files.py
new file mode 100644
index 0000000000..bf99e7013b
--- /dev/null
+++ b/saleor/core/management/commands/remove_invalid_files.py
@@ -0,0 +1,198 @@
+"""Remove files with invalid/dangerous MIME types from storage.
+
+This command scans specific directories in storage for files with invalid
+MIME types. By default, it runs in dry-run mode showing what would be deleted
+without actually removing files.
+"""
+
+import os
+
+from django.conf import settings
+from django.core.files.storage import default_storage
+from django.core.management.base import BaseCommand
+
+from ....graphql.core.validators.file import detect_mime_type
+
+
+class Command(BaseCommand):
+ help = "Removes files with invalid/dangerous MIME types from storage."
+
+ # Directories to scan for invalid files
+ DIRECTORIES_TO_SCAN = [
+ "file_upload/", # Files uploaded via FileUpload mutation
+ "digital_contents/", # Files uploaded via DigitalContentCreate mutation
+ ]
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--apply",
+ action="store_true",
+ help=(
+ "Apply the changes and delete invalid files. "
+ "Without this flag, the command runs in dry-run mode."
+ ),
+ )
+
+ def handle(self, **options):
+ is_dry_run = not options.get("apply", False)
+
+ if is_dry_run:
+ self.stdout.write(
+ self.style.WARNING(
+ "Running in DRY-RUN mode. No files will be deleted. "
+ "Use --apply to actually delete files."
+ )
+ )
+
+ total_checked = 0
+ total_invalid = 0
+
+ for directory in self.DIRECTORIES_TO_SCAN:
+ self.stdout.write(f"\nScanning directory: {directory}")
+ checked, invalid = self._scan_directory(directory, is_dry_run)
+ total_checked += checked
+ total_invalid += invalid
+
+ # Summary
+ self.stdout.write("\n" + "=" * 60)
+ self.stdout.write(f"Total files checked: {total_checked}")
+ self.stdout.write(
+ self.style.ERROR(f"Total invalid files found: {total_invalid}")
+ )
+
+ if is_dry_run and total_invalid > 0:
+ self.stdout.write(
+ self.style.WARNING(
+ "\nReview the list of files above. "
+ "If it looks correct, rerun with --apply to delete them."
+ )
+ )
+ elif total_invalid > 0:
+ self.stdout.write(self.style.SUCCESS("\nInvalid files have been deleted."))
+ else:
+ self.stdout.write(self.style.SUCCESS("\nNo invalid files found."))
+
+ def _scan_directory(self, directory, is_dry_run):
+ """Scan a directory for files with invalid mime types."""
+ checked = 0
+ invalid = 0
+
+ try:
+ # List all files in the directory
+ directories, files = default_storage.listdir(directory)
+ except FileNotFoundError:
+ self.stdout.write(self.style.WARNING(f" Directory not found: {directory}"))
+ return 0, 0
+
+ # Process files in current directory
+ for filename in files:
+ file_path = os.path.join(directory, filename)
+ checked += 1
+
+ if self._is_invalid_file(file_path):
+ invalid += 1
+ self._handle_invalid_file(file_path, is_dry_run)
+
+ # Recursively scan subdirectories
+ for subdir in directories:
+ subdir_path = os.path.join(directory, subdir)
+ sub_checked, sub_invalid = self._scan_directory(subdir_path, is_dry_run)
+ checked += sub_checked
+ invalid += sub_invalid
+
+ return checked, invalid
+
+ def _is_invalid_file(self, file_path):
+ """Check if file has invalid mime type by reading actual file content."""
+ if not file_path:
+ return False
+
+ if not default_storage.exists(file_path):
+ return False
+
+ if self._has_no_extension(file_path):
+ return True
+
+ # verify file extension to prevent unnecessary file reads
+ if not self._has_allowed_extension(file_path):
+ return True
+
+ return self._verify_file_content(file_path)
+
+ def _has_no_extension(self, file_path):
+ """Check if file has no extension."""
+ _, ext = os.path.splitext(file_path)
+ return not ext.lower()
+
+ def _has_allowed_extension(self, file_path):
+ """Check if file extension is in allowed list."""
+ _, ext = os.path.splitext(file_path)
+ ext = ext.lower()
+
+ for _mime_type, extensions in settings.ALLOWED_MIME_TYPES.items():
+ if ext in extensions:
+ return True
+ return False
+
+ def _verify_file_content(self, file_path):
+ """Verify file content matches allowed MIME types."""
+ try:
+ with default_storage.open(file_path, "rb") as file:
+ try:
+ actual_mime_type = detect_mime_type(file)
+
+ if not self._is_mime_type_allowed(actual_mime_type):
+ self.stdout.write(
+ self.style.WARNING(
+ f" File {file_path} has mime type {actual_mime_type} "
+ f"not in allowed list"
+ )
+ )
+ return True
+
+ if not self._extension_matches_mime_type(
+ file_path, actual_mime_type
+ ):
+ _, ext = os.path.splitext(file_path)
+ self.stdout.write(
+ self.style.WARNING(
+ f" File {file_path} has extension {ext.lower()} but actual "
+ f"mime type is {actual_mime_type}"
+ )
+ )
+ return True
+
+ return False
+ except Exception:
+ return True
+ except Exception as e:
+ self.stdout.write(
+ self.style.WARNING(f" Failed to read file {file_path}: {str(e)}")
+ )
+ return False
+
+ def _is_mime_type_allowed(self, mime_type):
+ """Check if MIME type is in allowed list."""
+ return mime_type in settings.ALLOWED_MIME_TYPES
+
+ def _extension_matches_mime_type(self, file_path, mime_type):
+ """Check if file extension matches the detected MIME type."""
+ _, ext = os.path.splitext(file_path)
+ ext = ext.lower()
+ expected_extensions = settings.ALLOWED_MIME_TYPES.get(mime_type, [])
+ return ext in expected_extensions
+
+ def _handle_invalid_file(self, file_path, is_dry_run):
+ """Handle an invalid file - log or delete based on mode."""
+ if is_dry_run:
+ self.stdout.write(self.style.WARNING(f" Would delete: {file_path}"))
+ else:
+ self.stdout.write(f" Deleting: {file_path}")
+ try:
+ if default_storage.exists(file_path):
+ default_storage.delete(file_path)
+ self.stdout.write(self.style.SUCCESS(" ✓ Deleted successfully"))
+ else:
+ self.stdout.write(self.style.WARNING(" ⚠ File does not exist"))
+ except Exception as e:
+ self.stdout.write(self.style.ERROR(f" ✗ Failed to delete: {str(e)}"))
diff --git a/saleor/core/tests/test_view.py b/saleor/core/tests/test_view.py
index 7d8f873c3c..e99a9e656e 100644
--- a/saleor/core/tests/test_view.py
+++ b/saleor/core/tests/test_view.py
@@ -1,7 +1,27 @@
+import functools
+from pathlib import Path
+
import jwt
+import pytest
+from django.http import FileResponse, Http404
+from django.test import RequestFactory
from jwt import PyJWK
from ..jwt_manager import get_jwt_manager
+from ..views import serve_media_view
+
+
+def dummy_media_file_request(media_root: str):
+ # Create a dummy empty image file
+ filename = "image.png"
+ (file := (Path(media_root) / filename)).touch(mode=0o600, exist_ok=False)
+
+ # Return HTTP request to that file
+ yield RequestFactory().get(f"/media/{filename}")
+
+ # Delete
+ file.unlink(missing_ok=False)
def test_jwks_can_be_used_to_decode_saleor_token(client):
@@ -16,3 +36,49 @@ def test_jwks_can_be_used_to_decode_saleor_token(client):
# then
jwt.decode(token, PyJWK.from_dict(key, algorithm="RS256").key, algorithms=["RS256"])
+
+
+def test_serve_media_view_serves_as_attachment(
+ settings, media_root: str, dummy_media_file_request
+):
+ """Ensure the view returns ``Content-Disposition: attachment``."""
+
+ settings.DEBUG = True
+ send_request = functools.partial(
+ serve_media_view,
+ dummy_media_file_request,
+ document_root=media_root,
+ )
+
+ # Should add the header when the file is found
+ response = send_request(path="image.png")
+ assert isinstance(response, FileResponse)
+ assert response.headers["Content-Disposition"] == "attachment"
+
+ # Shouldn't add the header when not found, it should just raise
+ with pytest.raises(Http404):
+ send_request(path="image2.png")
+
+
+def test_serve_media_view_serves_only_when_debug_mode(
+ settings, media_root: str, dummy_media_file_request
+):
+ """Ensure the view only serves content when DEBUG=True."""
+
+ send_request = functools.partial(
+ serve_media_view,
+ dummy_media_file_request,
+ path="image.png",
+ document_root=media_root,
+ )
+
+ # Ensure when DEBUG=True, it should serve the files
+ settings.DEBUG = True
+ response = send_request()
+ assert isinstance(response, FileResponse)
+ assert response.status_code == 200
+
+ # When DEBUG=False, it should just return HTTP 404
+ settings.DEBUG = False
+ with pytest.raises(Http404):
+ response = send_request()
diff --git a/saleor/core/views.py b/saleor/core/views.py
index 2cb38fa176..3e8812b087 100644
--- a/saleor/core/views.py
+++ b/saleor/core/views.py
@@ -1,10 +1,15 @@
+import logging
import os
-from django.http import JsonResponse
+from django.conf import settings
+from django.http import FileResponse, Http404, HttpRequest, HttpResponse, JsonResponse
from django.template.response import TemplateResponse
+from django.views.static import serve
from .jwt_manager import get_jwt_manager
+logger = logging.getLogger(__name__)
+
def home(request):
storefront_url = os.environ.get("STOREFRONT_URL", "")
@@ -18,3 +23,39 @@ def home(request):
def jwks(request):
return JsonResponse(get_jwt_manager().get_jwks())
+
+
+def serve_media_view(
+ request: HttpRequest, *args, **kwargs
+) -> HttpResponse | FileResponse:
+ """Serve media files and other user-uploaded media files from local storage.
+
+ WARNING: just like Django's built-in ``django.views.static.serve()`` view:
+ this view is not suitable for production use. This view is only meant
+ for development purposes and convenience, as well as to show how
+ production workloads are expected to behave.
+
+ Learn more about static views: https://docs.djangoproject.com/en/5.2/howto/static-files/#serving-static-files-during-development
+
+ This view wraps ``django.views.static.serve()`` in order to add
+ a ``Content-Disposition: attachment`` header due to not exposing a setting to
+ control the response headers.
+
+ This is not intended to protect users in production workloads, instead users
+ should configure their servers (CDN or reverse-proxy) to host the media files
+ and to return the ``Content-Disposition: attachment`` header; this only for
+ demonstrating the expected behavior.
+ """
+
+ # Not allowed when DEBUG=False
+ if not settings.DEBUG:
+ raise Http404
+
+ response: HttpResponse | FileResponse = serve(request, *args, **kwargs)
+
+ # When serving files, force clients to download the file instead of Django's
+ # default value 'Content-Disposition: inline' which indicates to the clients
+ # that they can display the value.
+ if isinstance(response, FileResponse):
+ response.headers["Content-Disposition"] = "attachment"
+ return response
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index b682b6b769..3869fd6e6c 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -21,6 +21,7 @@ from graphene.types.mutation import MutationOptions
from graphql.error import GraphQLError
from ...core.db.connection import allow_writer
+from ...core.error_codes import UploadErrorCode
from ...core.exceptions import PermissionDenied
from ...core.utils import metadata_manager
from ...core.utils.events import call_event
@@ -58,6 +59,7 @@ from .utils import (
snake_to_camel_case,
)
from .utils.error_codes import get_error_code_from_error
+from .validators.file import validate_upload_file
MISSING_NODE_ERROR_MESSAGE_PREFIX = "Couldn't resolve to a node:"
@@ -1205,6 +1207,8 @@ class FileUpload(BaseMutation):
if not file_data.file:
raise ValidationError("Received an empty file.")
+ validate_upload_file(file_data, UploadErrorCode, "file")
+
# add unique text fragment to the file name to prevent file overriding
file_name, format = os.path.splitext(file_data.name or "")
diff --git a/saleor/graphql/core/tests/test_file_upload.py b/saleor/graphql/core/tests/test_file_upload.py
index 44b3bd5512..cfbaf62bcf 100644
--- a/saleor/graphql/core/tests/test_file_upload.py
+++ b/saleor/graphql/core/tests/test_file_upload.py
@@ -1,8 +1,11 @@
import os
+from unittest.mock import patch
from urllib.parse import urlparse
from django.core.files.storage import default_storage
+from django.core.files.uploadedfile import SimpleUploadedFile
+from ....core.error_codes import UploadErrorCode
from ....product.tests.utils import create_image
from ...tests.utils import (
assert_no_permission,
@@ -19,16 +22,21 @@ mutation fileUpload($file: Upload!) {
}
errors {
code
+ field
}
}
}
"""
-def test_file_upload_by_staff(staff_api_client, site_settings, media_root):
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_by_staff(
+ from_buffer_mock, staff_api_client, site_settings, media_root
+):
# given
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
- variables = {"image": image_name}
+ variables = {"file": image_name}
body = get_multipart_request_body(
FILE_UPLOAD_MUTATION, variables, image_file, image_name
)
@@ -51,10 +59,12 @@ def test_file_upload_by_staff(staff_api_client, site_settings, media_root):
assert default_storage.exists(file_path.lstrip("/media"))
-def test_file_upload_by_customer(user_api_client, media_root):
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_by_customer(from_buffer_mock, user_api_client, media_root):
# given
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
- variables = {"image": image_name}
+ variables = {"file": image_name}
body = get_multipart_request_body(
FILE_UPLOAD_MUTATION, variables, image_file, image_name
)
@@ -66,10 +76,12 @@ def test_file_upload_by_customer(user_api_client, media_root):
assert_no_permission(response)
-def test_file_upload_by_app(app_api_client, media_root):
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_by_app(from_buffer_mock, app_api_client, media_root):
# given
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
- variables = {"image": image_name}
+ variables = {"file": image_name}
body = get_multipart_request_body(
FILE_UPLOAD_MUTATION, variables, image_file, image_name
)
@@ -92,10 +104,12 @@ def test_file_upload_by_app(app_api_client, media_root):
assert default_storage.exists(file_path.lstrip("/media"))
-def test_file_upload_by_superuser(superuser_api_client, media_root):
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_by_superuser(from_buffer_mock, superuser_api_client, media_root):
# given
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
- variables = {"image": image_name}
+ variables = {"file": image_name}
body = get_multipart_request_body(
FILE_UPLOAD_MUTATION, variables, image_file, image_name
)
@@ -118,10 +132,12 @@ def test_file_upload_by_superuser(superuser_api_client, media_root):
assert default_storage.exists(file_path.lstrip("/media"))
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
def test_file_upload_file_with_the_same_name_already_exists(
- staff_api_client, media_root
+ from_buffer_mock, staff_api_client, media_root
):
# given
+ from_buffer_mock.return_value = "image/jpeg"
image_file1, image_name1 = create_image()
path = default_storage.save(image_file1._name, image_file1)
@@ -130,7 +146,7 @@ def test_file_upload_file_with_the_same_name_already_exists(
assert image_name == image_name1
assert image_file._name == image_file1._name
- variables = {"image": image_name}
+ variables = {"file": image_name}
body = get_multipart_request_body(
FILE_UPLOAD_MUTATION, variables, image_file, image_name
)
@@ -151,10 +167,14 @@ def test_file_upload_file_with_the_same_name_already_exists(
assert default_storage.exists(file_url.replace("https://example.com/media/", ""))
-def test_file_upload_file_name_with_space(staff_api_client, media_root):
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_file_name_with_space(
+ from_buffer_mock, staff_api_client, media_root
+):
# given
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image("file name with spaces")
- variables = {"image": image_name}
+ variables = {"file": image_name}
body = get_multipart_request_body(
FILE_UPLOAD_MUTATION, variables, image_file, image_name
)
@@ -178,10 +198,14 @@ def test_file_upload_file_name_with_space(staff_api_client, media_root):
assert default_storage.exists(file_path.lstrip("/media"))
-def test_file_upload_file_name_with_encoded_value(staff_api_client, media_root):
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_file_name_with_encoded_value(
+ from_buffer_mock, staff_api_client, media_root
+):
# given
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image("file%20name")
- variables = {"image": image_name}
+ variables = {"file": image_name}
body = get_multipart_request_body(
FILE_UPLOAD_MUTATION, variables, image_file, image_name
)
@@ -202,3 +226,57 @@ def test_file_upload_file_name_with_encoded_value(staff_api_client, media_root):
assert file_path.startswith(f"/media/file_upload/{file_name}")
assert file_path.endswith(format)
assert default_storage.exists(file_path.lstrip("/media"))
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_invalid_mime_type(from_buffer_mock, staff_api_client, media_root):
+ # given
+ from_buffer_mock.return_value = "application/x-msdownload"
+ exe_file = SimpleUploadedFile(
+ "malicious.exe",
+ b"fake executable content",
+ content_type="application/x-msdownload",
+ )
+ variables = {"file": "malicious.exe"}
+ body = get_multipart_request_body(
+ FILE_UPLOAD_MUTATION, variables, exe_file, "malicious.exe"
+ )
+
+ # when
+ response = staff_api_client.post_multipart(body)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["fileUpload"]
+ errors = data["errors"]
+
+ assert errors
+ assert len(errors) == 1
+ assert errors[0]["code"] == UploadErrorCode.UNSUPPORTED_MIME_TYPE.name
+ assert errors[0]["field"] == "file"
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_file_upload_invalid_extension(from_buffer_mock, staff_api_client, media_root):
+ # given
+ from_buffer_mock.return_value = "image/jpeg"
+ exe_file = SimpleUploadedFile(
+ "test.png", b"fake jpeg content", content_type="image/jpeg"
+ )
+ variables = {"file": "test.png"}
+ body = get_multipart_request_body(
+ FILE_UPLOAD_MUTATION, variables, exe_file, "test.png"
+ )
+
+ # when
+ response = staff_api_client.post_multipart(body)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["fileUpload"]
+ errors = data["errors"]
+
+ assert errors
+ assert len(errors) == 1
+ assert errors[0]["code"] == UploadErrorCode.INVALID_FILE_TYPE.name
+ assert errors[0]["field"] == "file"
diff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.py
index 449e331efe..4ddef80c78 100644
--- a/saleor/graphql/core/tests/test_file_validation.py
+++ b/saleor/graphql/core/tests/test_file_validation.py
@@ -6,13 +6,16 @@ from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image
+from ....core.error_codes import UploadErrorCode
from ....product.error_codes import ProductErrorCode
from ..validators.file import (
clean_image_file,
+ detect_mime_type,
is_image_mimetype,
is_image_url,
is_supported_image_mimetype,
is_valid_image_content_type,
+ validate_upload_file,
)
@@ -294,3 +297,141 @@ def test_is_image_url(url, is_valid):
# then
assert result is is_valid
+
+
+ ("filename", "mime_type"),
+ [
+ ("test.jpg", "image/jpeg"),
+ ("test.jpeg", "image/jpeg"),
+ ("test.JPG", "image/jpeg"), # case insensitive
+ ("test.png", "image/png"),
+ ("test.gif", "image/gif"),
+ ("test.webp", "image/webp"),
+ ("file.txt", "text/plain"),
+ ("data.csv", "text/csv"),
+ ("video.mp4", "video/mp4"),
+ ("video.webm", "video/webm"),
+ ("audio.mp3", "audio/mpeg"),
+ ("audio.m4a", "audio/mp4"),
+ ],
+)
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_validate_upload_file_valid_files(from_buffer_mock, filename, mime_type):
+ # given
+ from_buffer_mock.return_value = mime_type
+ file_data = SimpleUploadedFile(filename, b"content", content_type=mime_type)
+
+ # when & then
+ validate_upload_file(file_data, UploadErrorCode, "file")
+
+
+ ("filename", "detected_mime_type"),
+ [
+ # Unsupported mime types
+ ("test.html", "text/html"),
+ ("test.svg", "image/svg+xml"),
+ ("archive.zip", "application/zip"),
+ ("archive.rar", "application/x-rar-compressed"),
+ ("test.js", "application/javascript"),
+ ("test.xml", "application/xml"),
+ ("archive.tar.gz", "application/gzip"),
+ ],
+)
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_validate_upload_file_unsupported_mime_type(
+ from_buffer_mock, filename, detected_mime_type
+):
+ # given
+ from_buffer_mock.return_value = detected_mime_type
+ file_data = SimpleUploadedFile(filename, b"content", content_type="image/jpeg")
+
+ # when
+ with pytest.raises(ValidationError) as exc:
+ validate_upload_file(file_data, UploadErrorCode, "file")
+
+ # then
+ assert exc.value.args[0]["file"].code == UploadErrorCode.UNSUPPORTED_MIME_TYPE.value
+
+
+ ("filename", "detected_mime_type"),
+ [
+ # Extension mismatch - actual content doesn't match extension
+ ("test.png", "image/jpeg"),
+ ("test.jpg", "image/png"),
+ ("test.pdf", "image/jpeg"),
+ # Missing extension
+ ("test", "image/jpeg"),
+ ("data", "text/csv"),
+ ],
+)
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_validate_upload_file_invalid_file_type(
+ from_buffer_mock, filename, detected_mime_type
+):
+ # given
+ from_buffer_mock.return_value = detected_mime_type
+ file_data = SimpleUploadedFile(filename, b"content", content_type="image/jpeg")
+
+ # when
+ with pytest.raises(ValidationError) as exc:
+ validate_upload_file(file_data, UploadErrorCode, "file")
+
+ # then
+ assert exc.value.args[0]["file"].code == UploadErrorCode.INVALID_FILE_TYPE.value
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_validate_upload_file_detects_spoofed_content_type(from_buffer_mock):
+ """Test that actual file content is checked, not content_type header.
+
+ This verifies the security fix: an attacker cannot upload malicious HTML
+ by setting content_type header to image/jpeg if the actual file is HTML.
+ """
+ # given - attacker tries to upload HTML with fake image content_type header
+ from_buffer_mock.return_value = "text/html" # actual content is HTML
+ file_data = SimpleUploadedFile(
+ "malicious.html",
+ b"<html><script>alert('XSS')</script></html>",
+ content_type="image/jpeg", # spoofed content type
+ )
+
+ # when
+ with pytest.raises(ValidationError) as exc:
+ validate_upload_file(file_data, UploadErrorCode, "file")
+
+ # then - should be rejected based on actual content, not header
+ assert exc.value.args[0]["file"].code == UploadErrorCode.UNSUPPORTED_MIME_TYPE.value
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_detect_mime_type_success(from_buffer_mock):
+ # given
+ from_buffer_mock.return_value = "image/jpeg"
+ file_data = SimpleUploadedFile("test.jpg", b"content", content_type="image/jpeg")
+
+ # when
+ mime_type = detect_mime_type(file_data)
+
+ # then
+ assert mime_type == "image/jpeg"
+ from_buffer_mock.assert_called_once()
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_detect_mime_type_reads_file_content(from_buffer_mock):
+ # given
+ from_buffer_mock.return_value = "image/png"
+ file_data = SimpleUploadedFile(
+ "test.jpg", b"PNG_CONTENT", content_type="image/jpeg"
+ )
+
+ # when
+ mime_type = detect_mime_type(file_data)
+
+ # then
+ assert mime_type == "image/png"
+ # Verify magic was called with actual file content, not headers
+ from_buffer_mock.assert_called_once_with(b"PNG_CONTENT", mime=True)
diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.py
index 50c4132d8f..c9b9dea18d 100644
--- a/saleor/graphql/core/validators/file.py
+++ b/saleor/graphql/core/validators/file.py
@@ -1,7 +1,11 @@
+import logging
import mimetypes
import os
+import magic
+from django.conf import settings
from django.core.exceptions import ValidationError
+from django.core.files.uploadedfile import UploadedFile
from PIL import Image, UnidentifiedImageError
from ....thumbnail import MIME_TYPE_TO_PIL_IDENTIFIER
@@ -10,6 +14,79 @@ from ..utils import add_hash_to_file_name
Image.init()
+logger = logging.getLogger(__name__)
+
+
+def validate_upload_file(
+ file_data: UploadedFile, error_class, error_field_name: str
+) -> None:
+ """Validate uploaded file. Validate the mime type and file extension.
+
+ Raises ValidationError if file is invalid.
+ """
+ # Detect actual mime type from file content using magic bytes
+ # (not from content_type attribute which can be more easily spoofed)
+ mime_type = detect_mime_type(file_data)
+
+ if mime_type not in settings.ALLOWED_MIME_TYPES:
+ logger.info(
+ "Upload for file type %s was blocked due to not being a permitted file "
+ "type. Hint: this behavior can be modified via the "
+ "`UPLOAD_ADDITIONAL_ALLOWED_MIME_TYPES` environment variable.",
+ mime_type,
+ )
+ raise ValidationError(
+ {
+ error_field_name: ValidationError(
+ "File type not permitted. Contact your administrator or support "
+ f"team to enable support for `{mime_type}` file type.",
+ code=error_class.UNSUPPORTED_MIME_TYPE.value,
+ )
+ }
+ )
+
+ # Validate file extension matches content type
+ file_name = file_data.name or ""
+ file_ext = os.path.splitext(file_name)[1].lower()
+
+ if file_ext:
+ expected_extensions = settings.ALLOWED_MIME_TYPES.get(mime_type, [])
+ if file_ext not in expected_extensions:
+ logger.info(
+ "Upload for file was blocked due to file extension '%s' not matching "
+ "content type '%s'. Expected one of: %s.",
+ file_ext,
+ mime_type,
+ ", ".join(expected_extensions),
+ )
+ raise ValidationError(
+ {
+ error_field_name: ValidationError(
+ f"File extension '{file_ext}' does not match content type "
+ f"'{mime_type}'. "
+ f"Expected one of: {', '.join(expected_extensions)}.",
+ code=error_class.INVALID_FILE_TYPE.value,
+ )
+ }
+ )
+ if not file_ext:
+ raise ValidationError(
+ {
+ error_field_name: ValidationError(
+ "Lack of file extension.",
+ code=error_class.INVALID_FILE_TYPE.value,
+ )
+ }
+ )
+
+
+def detect_mime_type(file_data) -> str:
+ """Detect MIME type from file content using magic bytes."""
+ file_data.seek(0)
+ mime_type = magic.from_buffer(file_data.read(2048), mime=True)
+ file_data.seek(0)
+ return mime_type
+
def is_image_mimetype(mimetype: str) -> bool:
"""Check if mimetype is image."""
diff --git a/saleor/graphql/product/mutations/digital_contents.py b/saleor/graphql/product/mutations/digital_contents.py
index 2cf18bb393..032b37e9ed 100644
--- a/saleor/graphql/product/mutations/digital_contents.py
+++ b/saleor/graphql/product/mutations/digital_contents.py
@@ -11,6 +11,7 @@ from ...core.context import ChannelContext, disallow_replica_in_context
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.mutations import BaseMutation, DeprecatedModelMutation
from ...core.types import BaseInputObjectType, NonNullList, ProductError, Upload
+from ...core.validators.file import validate_upload_file
from ...meta.inputs import MetadataInput, MetadataInputDescription
from ..types import DigitalContent, DigitalContentUrl, ProductVariant
@@ -125,6 +126,10 @@ class DigitalContentCreate(BaseMutation):
clean_input = cls.clean_input(info, input, variant)
content_data = info.context.FILES.get(clean_input["content_file"])
+
+ if content_data:
+ validate_upload_file(content_data, ProductErrorCode, "content_file")
+
digital_content = models.DigitalContent(content_file=content_data)
digital_content.use_default_settings = clean_input.get(
"use_default_settings", False
diff --git a/saleor/graphql/product/tests/test_digital_content.py b/saleor/graphql/product/tests/test_digital_content.py
index 96dce4252c..f909763fa3 100644
--- a/saleor/graphql/product/tests/test_digital_content.py
+++ b/saleor/graphql/product/tests/test_digital_content.py
@@ -1,6 +1,7 @@
from unittest.mock import patch
import graphene
+from django.core.files.uploadedfile import SimpleUploadedFile
from ....product.error_codes import ProductErrorCode
from ....product.models import DigitalContent, ProductVariant
@@ -116,19 +117,56 @@ def test_digital_content_query_with_invalid_object_type(
assert content["data"]["digitalContent"] is None
-def test_digital_content_create_mutation_custom_settings(
- monkeypatch, staff_api_client, variant, permission_manage_products, media_root
-):
- query = """
+DIGITAL_CONTENT_CREATE_MUTATION = """
mutation createDigitalContent($variant: ID!,
$input: DigitalContentUploadInput!) {
digitalContentCreate(variantId: $variant, input: $input) {
variant {
id
}
+ errors {
+ code
+ field
+ }
}
}
- """
+"""
+
+DIGITAL_CONTENT_CREATE_WITH_METADATA_MUTATION = """
+ mutation createDigitalContent($variant: ID!,
+ $input: DigitalContentUploadInput!) {
+ digitalContentCreate(variantId: $variant, input: $input) {
+ variant {
+ id
+ }
+ content {
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
+ }
+ }
+ }
+"""
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_digital_content_create_mutation_custom_settings(
+ from_buffer_mock,
+ monkeypatch,
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ media_root,
+):
+ query = DIGITAL_CONTENT_CREATE_MUTATION
+
+ # Mock magic to detect actual content as JPEG
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
url_valid_days = 3
@@ -158,19 +196,19 @@ def test_digital_content_create_mutation_custom_settings(
assert not variant.digital_content.use_default_settings
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
def test_digital_content_create_mutation_default_settings(
- monkeypatch, staff_api_client, variant, permission_manage_products, media_root
+ from_buffer_mock,
+ monkeypatch,
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ media_root,
):
- query = """
- mutation digitalCreate($variant: ID!,
- $input: DigitalContentUploadInput!) {
- digitalContentCreate(variantId: $variant, input: $input) {
- variant {
- id
- }
- }
- }
- """
+ query = DIGITAL_CONTENT_CREATE_MUTATION
+
+ # Mock magic to detect actual content as JPEG
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
@@ -189,30 +227,20 @@ def test_digital_content_create_mutation_default_settings(
assert variant.digital_content.use_default_settings
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
def test_digital_content_create_mutation_with_metadata(
- monkeypatch, staff_api_client, variant, permission_manage_products, media_root
+ from_buffer_mock,
+ monkeypatch,
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ media_root,
):
# given
- query = """
- mutation createDigitalContent($variant: ID!,
- $input: DigitalContentUploadInput!) {
- digitalContentCreate(variantId: $variant, input: $input) {
- variant {
- id
- }
- content {
- metadata {
- key
- value
- }
- privateMetadata {
- key
- value
- }
- }
- }
- }
- """
+ query = DIGITAL_CONTENT_CREATE_WITH_METADATA_MUTATION
+
+ # Mock magic to detect actual content as JPEG
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
url_valid_days = 3
@@ -247,19 +275,19 @@ def test_digital_content_create_mutation_with_metadata(
assert variant.digital_content.private_metadata == {metadata_key: metadata_value}
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
def test_digital_content_create_mutation_removes_old_content(
- monkeypatch, staff_api_client, variant, permission_manage_products, media_root
+ from_buffer_mock,
+ monkeypatch,
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ media_root,
):
- query = """
- mutation digitalCreate($variant: ID!,
- $input: DigitalContentUploadInput!) {
- digitalContentCreate(variantId: $variant, input: $input) {
- variant {
- id
- }
- }
- }
- """
+ query = DIGITAL_CONTENT_CREATE_MUTATION
+
+ # Mock magic to detect actual content as JPEG
+ from_buffer_mock.return_value = "image/jpeg"
image_file, image_name = create_image()
@@ -280,7 +308,89 @@ def test_digital_content_create_mutation_removes_old_content(
variant.refresh_from_db()
assert variant.digital_content.content_file
assert variant.digital_content.use_default_settings
- assert not DigitalContent.objects.filter(id=d_content.id).exists()
+ assert not DigitalContent.objects.filter(id=d_content.pk).exists()
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_digital_content_create_mutation_invalid_mime_type(
+ from_buffer_mock, staff_api_client, variant, permission_manage_products
+):
+ # given
+ query = DIGITAL_CONTENT_CREATE_MUTATION
+
+ # Mock magic to detect actual content as executable
+ from_buffer_mock.return_value = "application/x-msdownload"
+
+ exe_file = SimpleUploadedFile(
+ "malicious.exe",
+ b"fake executable content",
+ content_type="application/x-msdownload",
+ )
+
+ variables = {
+ "variant": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "input": {
+ "useDefaultSettings": True,
+ "contentFile": "malicious.exe",
+ },
+ }
+
+ body = get_multipart_request_body(query, variables, exe_file, "malicious.exe")
+
+ # when
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["digitalContentCreate"]
+ errors = data["errors"]
+
+ assert errors
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.UNSUPPORTED_MIME_TYPE.name
+ assert errors[0]["field"] == "contentFile"
+
+
+@patch("saleor.graphql.core.validators.file.magic.from_buffer")
+def test_digital_content_create_mutation_invalid_extension(
+ from_buffer_mock, staff_api_client, variant, permission_manage_products
+):
+ # given
+ query = DIGITAL_CONTENT_CREATE_MUTATION
+
+ # Mock magic to detect actual content as JPEG (mismatches .png extension)
+ from_buffer_mock.return_value = "image/jpeg"
+
+ invalid_file = SimpleUploadedFile(
+ "test.png", b"fake jpeg content", content_type="image/jpeg"
+ )
+
+ variables = {
+ "variant": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "input": {
+ "useDefaultSettings": True,
+ "contentFile": "test.png",
+ },
+ }
+
+ body = get_multipart_request_body(query, variables, invalid_file, "test.png")
+
+ # when
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["digitalContentCreate"]
+ errors = data["errors"]
+
+ assert errors
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.INVALID_FILE_TYPE.name
+ assert errors[0]["field"] == "contentFile"
DIGITAL_CONTENT_DELETE_MUTATION = """
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 0bb53f1681..4935a1fd13 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -21280,6 +21280,8 @@ enum ProductErrorCode @doc(category: "Products") {
PRODUCT_NOT_ASSIGNED_TO_CHANNEL
UNSUPPORTED_MEDIA_PROVIDER
PREORDER_VARIANT_CANNOT_BE_DEACTIVATED
+ INVALID_FILE_TYPE
+ UNSUPPORTED_MIME_TYPE
}
input ProductAttributeAssignInput @doc(category: "Products") {
@@ -28013,6 +28015,8 @@ type UploadError {
enum UploadErrorCode {
GRAPHQL_ERROR
+ INVALID_FILE_TYPE
+ UNSUPPORTED_MIME_TYPE
}
"""
diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.py
index 3a9bf66bc7..3bc292d4d9 100644
--- a/saleor/product/error_codes.py
+++ b/saleor/product/error_codes.py
@@ -22,6 +22,8 @@ class ProductErrorCode(Enum):
PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"
UNSUPPORTED_MEDIA_PROVIDER = "unsupported_media_provider"
PREORDER_VARIANT_CANNOT_BE_DEACTIVATED = "preorder_variant_cannot_be_deactivated"
+ INVALID_FILE_TYPE = "invalid_file_type"
+ UNSUPPORTED_MIME_TYPE = "unsupported_mime_type"
class CollectionErrorCode(Enum):
diff --git a/saleor/settings.py b/saleor/settings.py
index fb7c7ab8b6..0c339b3017 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -1,5 +1,6 @@
import datetime
import importlib.metadata
+import json
import logging
import os
import os.path
@@ -1151,6 +1152,47 @@ EDITOR_JS_LISTS_MAX_DEPTH = int(os.environ.get("EDITOR_JS_LISTS_MAX_DEPTH", 10))
HTML_CLEANER_PREFS = HtmlCleanerSettings.parse()
+# File upload settings
+# Allowed mime types for file uploads (safe, non-executable formats)
+# Dict structure: {<mime-type>: [<extensions>]}
+ALLOWED_MIME_TYPES = {
+ "image/avif": [".avif"],
+ "image/bmp": [".bmp"],
+ "image/gif": [".gif"],
+ "image/jpeg": [".jpg", ".jpeg", ".jpe", ".jfif"],
+ "image/png": [".png"],
+ "image/tiff": [".tiff", ".tif"],
+ "image/webp": [".webp"],
+ # Documents
+ "application/msword": [".doc"],
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
+ ".docx"
+ ],
+ "application/vnd.ms-excel": [".xls"],
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [".xlsx"],
+ "application/vnd.ms-powerpoint": [".ppt"],
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
+ ".pptx"
+ ],
+ # Videos
+ "video/mp4": [".mp4"],
+ "video/webm": [".webm"],
+ "video/ogg": [".ogv", ".ogg"],
+ "video/quicktime": [".mov"],
+ # Audio
+ "audio/mpeg": [".mp3", ".mpeg"],
+ "audio/mp4": [".m4a"],
+ "audio/webm": [".weba"],
+ "audio/ogg": [".oga", ".ogg"],
+ "audio/wav": [".wav"],
+ # Text (plain only)
+ "text/plain": [".txt"],
+ "text/csv": [".csv"],
+}
+ALLOWED_MIME_TYPES.update(
+ json.loads(os.environ.get("UPLOAD_ADDITIONAL_ALLOWED_MIME_TYPES", "{}"))
+)
+
# Library `google-i18n-address` use `AddressValidationMetadata` form Google to provide address validation rules.
# Patch `i18n` module to allows to override the default address rules.
i18n_rules_override()
diff --git a/saleor/urls.py b/saleor/urls.py
index fd77704009..e879248ecd 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -4,7 +4,7 @@ from django.contrib.staticfiles.views import serve
from django.urls import re_path
from django.views.decorators.csrf import csrf_exempt
-from .core.views import jwks
+from .core.views import jwks, serve_media_view
from .graphql.api import backend, schema
from .graphql.views import GraphQLView
from .plugins.views import (
@@ -56,7 +56,9 @@ urlpatterns = [
if settings.DEBUG:
from .core import views
- urlpatterns += static("/media/", document_root=settings.MEDIA_ROOT) + [
+ urlpatterns += static(
+ "/media/", view=serve_media_view, document_root=settings.MEDIA_ROOT
+ ) + [
re_path(r"^static/(?P<path>.*)$", serve),
re_path(r"^$", views.home, name="home"),
]