authentik.admin.files.backends.tests.test_s3_backend

  1from unittest import skipUnless
  2from unittest.mock import Mock, patch
  3from urllib.parse import parse_qs, urlsplit
  4
  5from botocore.exceptions import UnsupportedSignatureVersionError
  6from django.test import TestCase
  7
  8from authentik.admin.files.backends.s3 import S3Backend
  9from authentik.admin.files.tests.utils import FileTestS3BackendMixin, s3_test_server_available
 10from authentik.admin.files.usage import FileUsage
 11from authentik.lib.config import CONFIG
 12
 13
 14class TestS3BackendClientCache(TestCase):
 15    """Test S3 client caching."""
 16
 17    @CONFIG.patch("storage.s3.access_key", "accessKey1")
 18    @CONFIG.patch("storage.s3.secret_key", "secretKey1")
 19    @CONFIG.patch("storage.s3.use_ssl", "true")
 20    def test_client_reuses_boto_client(self):
 21        """Test repeated client access reuses the same boto client."""
 22        with patch("boto3.Session") as session_cls:
 23            session = session_cls.return_value
 24            client = Mock()
 25            session.client.return_value = client
 26
 27            backend = S3Backend(FileUsage.MEDIA)
 28
 29            self.assertIs(backend.client, client)
 30            self.assertIs(backend.client, client)
 31            session.client.assert_called_once()
 32            self.assertIs(session.client.call_args.kwargs["use_ssl"], True)
 33
 34    @CONFIG.patch("storage.s3.access_key", "accessKey1")
 35    @CONFIG.patch("storage.s3.secret_key", "secretKey1")
 36    def test_client_refreshes_when_config_changes(self):
 37        """Test client cache is invalidated when S3 client config changes."""
 38        with CONFIG.patch("storage.s3.endpoint", "https://s3-1.example.com"):
 39            with patch("boto3.Session") as session_cls:
 40                session = session_cls.return_value
 41                first_client = Mock()
 42                second_client = Mock()
 43                session.client.side_effect = [first_client, second_client]
 44
 45                backend = S3Backend(FileUsage.MEDIA)
 46
 47                self.assertIs(backend.client, first_client)
 48                with CONFIG.patch("storage.s3.endpoint", "https://s3-2.example.com"):
 49                    self.assertIs(backend.client, second_client)
 50                self.assertEqual(session.client.call_count, 2)
 51
 52
 53@skipUnless(s3_test_server_available(), "S3 test server not available")
 54class TestS3Backend(FileTestS3BackendMixin, TestCase):
 55    """Test S3 backend functionality"""
 56
 57    def setUp(self):
 58        super().setUp()
 59
 60    def test_base_path(self):
 61        """Test base_path property generates correct S3 key prefix"""
 62        expected = "media/public"
 63        self.assertEqual(self.media_s3_backend.base_path, expected)
 64
 65    def test_supports_file_path_s3(self):
 66        """Test supports_file_path returns True for s3 backend"""
 67        self.assertTrue(self.media_s3_backend.supports_file("path/to/any-file.png"))
 68        self.assertTrue(self.media_s3_backend.supports_file("any-file.png"))
 69
 70    def test_list_files(self):
 71        """Test list_files returns relative paths"""
 72        self.media_s3_backend.client.put_object(
 73            Bucket=self.media_s3_bucket_name,
 74            Key="media/public/file1.png",
 75            Body=b"test content",
 76            ACL="private",
 77        )
 78        self.media_s3_backend.client.put_object(
 79            Bucket=self.media_s3_bucket_name,
 80            Key="media/other/file1.png",
 81            Body=b"test content",
 82            ACL="private",
 83        )
 84
 85        files = list(self.media_s3_backend.list_files())
 86
 87        self.assertEqual(len(files), 1)
 88        self.assertIn("file1.png", files)
 89
 90    def test_list_files_empty(self):
 91        """Test list_files with no files"""
 92        files = list(self.media_s3_backend.list_files())
 93
 94        self.assertEqual(len(files), 0)
 95
 96    def test_save_file(self):
 97        """Test save_file uploads to S3"""
 98        content = b"test file content"
 99        self.media_s3_backend.save_file("test.png", content)
100
101    def test_save_file_stream(self):
102        """Test save_file_stream uploads to S3 using context manager"""
103        with self.media_s3_backend.save_file_stream("test.csv") as f:
104            f.write(b"header1,header2\n")
105            f.write(b"value1,value2\n")
106
107    def test_delete_file(self):
108        """Test delete_file removes from S3"""
109        self.media_s3_backend.client.put_object(
110            Bucket=self.media_s3_bucket_name,
111            Key="media/public/test.png",
112            Body=b"test content",
113            ACL="private",
114        )
115        self.media_s3_backend.delete_file("test.png")
116
117    @CONFIG.patch("storage.s3.secure_urls", True)
118    @CONFIG.patch("storage.s3.custom_domain", None)
119    def test_file_url_basic(self):
120        """Test file_url generates presigned URL with AWS signature format"""
121        url = self.media_s3_backend.file_url("test.png")
122
123        self.assertIn("X-Amz-Algorithm=AWS4-HMAC-SHA256", url)
124        self.assertIn("X-Amz-Signature=", url)
125        self.assertIn("test.png", url)
126
127    def test_client_signature_version_default_v4(self):
128        """Test S3 client defaults to v4 signature when not configured."""
129        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3v4")
130
131    @CONFIG.patch("storage.s3.signature_version", "s3")
132    def test_client_signature_version_global_override(self):
133        """Test S3 client respects globally configured signature version."""
134        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3")
135
136    @CONFIG.patch("storage.s3.signature_version", "s3v4")
137    @CONFIG.patch("storage.media.s3.signature_version", "s3")
138    def test_client_signature_version_media_override(self):
139        """Test usage-specific signature version takes precedence over global."""
140        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3")
141
142    @CONFIG.patch("storage.media.s3.signature_version", "not-a-real-signature")
143    def test_client_signature_version_unsupported(self):
144        """Test unsupported signature version raises botocore error."""
145        with self.assertRaises(UnsupportedSignatureVersionError):
146            self.media_s3_backend.file_url("test.png", use_cache=False)
147
148    @CONFIG.patch("storage.s3.bucket_name", "test-bucket")
149    def test_file_exists_true(self):
150        """Test file_exists returns True for existing file"""
151        self.media_s3_backend.client.put_object(
152            Bucket=self.media_s3_bucket_name,
153            Key="media/public/test.png",
154            Body=b"test content",
155            ACL="private",
156        )
157
158        exists = self.media_s3_backend.file_exists("test.png")
159
160        self.assertTrue(exists)
161
162    @CONFIG.patch("storage.s3.bucket_name", "test-bucket")
163    def test_file_exists_false(self):
164        """Test file_exists returns False for non-existent file"""
165        exists = self.media_s3_backend.file_exists("nonexistent.png")
166
167        self.assertFalse(exists)
168
169    def test_allowed_usages(self):
170        """Test that S3Backend supports all usage types"""
171        self.assertEqual(self.media_s3_backend.allowed_usages, list(FileUsage))
172
173    def test_reports_usage(self):
174        """Test S3Backend with REPORTS usage"""
175        self.assertEqual(self.reports_s3_backend.usage, FileUsage.REPORTS)
176        self.assertEqual(self.reports_s3_backend.base_path, "reports/public")
177
178    @CONFIG.patch("storage.s3.secure_urls", True)
179    @CONFIG.patch("storage.s3.addressing_style", "path")
180    def test_file_url_custom_domain_with_bucket_no_duplicate(self):
181        """Test file_url doesn't duplicate bucket name when custom_domain includes bucket.
182
183        Regression test for https://github.com/goauthentik/authentik/issues/19521
184
185        When using:
186        - Path-style addressing (bucket name goes in URL path, not subdomain)
187        - Custom domain that includes the bucket name (e.g., s3.example.com/bucket-name)
188
189        The bucket name should NOT appear twice in the final URL.
190
191        Example of the bug:
192        - custom_domain = "s3.example.com/authentik-media"
193        - boto3 presigned URL = "http://s3.example.com/authentik-media/media/public/file.png?..."
194        - Buggy result = "https://s3.example.com/authentik-media/authentik-media/media/public/file.png?..."
195        """
196        bucket_name = self.media_s3_bucket_name
197
198        # Custom domain includes the bucket name
199        custom_domain = f"localhost:8020/{bucket_name}"
200
201        with CONFIG.patch("storage.media.s3.custom_domain", custom_domain):
202            url = self.media_s3_backend.file_url("application-icons/test.svg", use_cache=False)
203
204        # The bucket name should appear exactly once in the URL path, not twice
205        bucket_occurrences = url.count(bucket_name)
206        self.assertEqual(
207            bucket_occurrences,
208            1,
209            f"Bucket name '{bucket_name}' appears {bucket_occurrences} times in URL, expected 1. "
210            f"URL: {url}",
211        )
212
213    @CONFIG.patch("storage.s3.secure_urls", False)
214    @CONFIG.patch("storage.s3.addressing_style", "path")
215    def test_file_url_custom_domain_resigns_for_custom_host(self):
216        """Test presigned URLs are signed for the custom domain host.
217
218        Host-changing custom domains must produce a signature query string for
219        the public host, not reuse the internal endpoint signature.
220        """
221        bucket_name = self.media_s3_bucket_name
222        key_name = "application-icons/test.svg"
223        custom_domain = f"files.example.test:8020/{bucket_name}"
224
225        endpoint_signed_url = self.media_s3_backend.client.generate_presigned_url(
226            "get_object",
227            Params={
228                "Bucket": bucket_name,
229                "Key": f"{self.media_s3_backend.base_path}/{key_name}",
230            },
231            ExpiresIn=900,
232            HttpMethod="GET",
233        )
234
235        with CONFIG.patch("storage.media.s3.custom_domain", custom_domain):
236            custom_url = self.media_s3_backend.file_url(key_name, use_cache=False)
237
238        endpoint_parts = urlsplit(endpoint_signed_url)
239        custom_parts = urlsplit(custom_url)
240
241        self.assertEqual(custom_parts.scheme, "http")
242        self.assertEqual(custom_parts.netloc, "files.example.test:8020")
243        self.assertEqual(parse_qs(custom_parts.query)["X-Amz-SignedHeaders"], ["host"])
244        self.assertNotEqual(
245            custom_parts.query,
246            endpoint_parts.query,
247            "Custom-domain URLs must be signed for the public host, not reuse the endpoint "
248            "signature query string.",
249        )
250
251    def test_themed_urls_without_theme_variable(self):
252        """Test themed_urls returns None when filename has no %(theme)s"""
253        result = self.media_s3_backend.themed_urls("logo.png")
254        self.assertIsNone(result)
255
256    def test_themed_urls_with_theme_variable(self):
257        """Test themed_urls returns dict of presigned URLs for each theme"""
258        result = self.media_s3_backend.themed_urls("logo-%(theme)s.png")
259
260        self.assertIsInstance(result, dict)
261        self.assertIn("light", result)
262        self.assertIn("dark", result)
263
264        # Check URLs are valid presigned URLs with correct file paths
265        self.assertIn("logo-light.png", result["light"])
266        self.assertIn("logo-dark.png", result["dark"])
267        self.assertIn("X-Amz-Signature=", result["light"])
268        self.assertIn("X-Amz-Signature=", result["dark"])
269
270    def test_themed_urls_multiple_theme_variables(self):
271        """Test themed_urls with multiple %(theme)s in path"""
272        result = self.media_s3_backend.themed_urls("%(theme)s/logo-%(theme)s.svg")
273
274        self.assertIsInstance(result, dict)
275        self.assertIn("light/logo-light.svg", result["light"])
276        self.assertIn("dark/logo-dark.svg", result["dark"])
277
278    def test_save_file_sets_content_type_svg(self):
279        """Test save_file sets correct ContentType for SVG files"""
280        self.media_s3_backend.save_file("test.svg", b"<svg></svg>")
281
282        response = self.media_s3_backend.client.head_object(
283            Bucket=self.media_s3_bucket_name,
284            Key="media/public/test.svg",
285        )
286        self.assertEqual(response["ContentType"], "image/svg+xml")
287
288    def test_save_file_sets_content_type_png(self):
289        """Test save_file sets correct ContentType for PNG files"""
290        self.media_s3_backend.save_file("test.png", b"\x89PNG\r\n\x1a\n")
291
292        response = self.media_s3_backend.client.head_object(
293            Bucket=self.media_s3_bucket_name,
294            Key="media/public/test.png",
295        )
296        self.assertEqual(response["ContentType"], "image/png")
297
298    def test_save_file_stream_sets_content_type(self):
299        """Test save_file_stream sets correct ContentType"""
300        with self.media_s3_backend.save_file_stream("test.css") as f:
301            f.write(b"body { color: red; }")
302
303        response = self.media_s3_backend.client.head_object(
304            Bucket=self.media_s3_bucket_name,
305            Key="media/public/test.css",
306        )
307        self.assertEqual(response["ContentType"], "text/css")
308
309    def test_save_file_unknown_extension_octet_stream(self):
310        """Test save_file sets octet-stream for unknown extensions"""
311        self.media_s3_backend.save_file("test.unknownext123", b"data")
312
313        response = self.media_s3_backend.client.head_object(
314            Bucket=self.media_s3_bucket_name,
315            Key="media/public/test.unknownext123",
316        )
317        self.assertEqual(response["ContentType"], "application/octet-stream")
class TestS3BackendClientCache(django.test.testcases.TestCase):
15class TestS3BackendClientCache(TestCase):
16    """Test S3 client caching."""
17
18    @CONFIG.patch("storage.s3.access_key", "accessKey1")
19    @CONFIG.patch("storage.s3.secret_key", "secretKey1")
20    @CONFIG.patch("storage.s3.use_ssl", "true")
21    def test_client_reuses_boto_client(self):
22        """Test repeated client access reuses the same boto client."""
23        with patch("boto3.Session") as session_cls:
24            session = session_cls.return_value
25            client = Mock()
26            session.client.return_value = client
27
28            backend = S3Backend(FileUsage.MEDIA)
29
30            self.assertIs(backend.client, client)
31            self.assertIs(backend.client, client)
32            session.client.assert_called_once()
33            self.assertIs(session.client.call_args.kwargs["use_ssl"], True)
34
35    @CONFIG.patch("storage.s3.access_key", "accessKey1")
36    @CONFIG.patch("storage.s3.secret_key", "secretKey1")
37    def test_client_refreshes_when_config_changes(self):
38        """Test client cache is invalidated when S3 client config changes."""
39        with CONFIG.patch("storage.s3.endpoint", "https://s3-1.example.com"):
40            with patch("boto3.Session") as session_cls:
41                session = session_cls.return_value
42                first_client = Mock()
43                second_client = Mock()
44                session.client.side_effect = [first_client, second_client]
45
46                backend = S3Backend(FileUsage.MEDIA)
47
48                self.assertIs(backend.client, first_client)
49                with CONFIG.patch("storage.s3.endpoint", "https://s3-2.example.com"):
50                    self.assertIs(backend.client, second_client)
51                self.assertEqual(session.client.call_count, 2)

Test S3 client caching.

@CONFIG.patch('storage.s3.access_key', 'accessKey1')
@CONFIG.patch('storage.s3.secret_key', 'secretKey1')
@CONFIG.patch('storage.s3.use_ssl', 'true')
def test_client_reuses_boto_client(self):
18    @CONFIG.patch("storage.s3.access_key", "accessKey1")
19    @CONFIG.patch("storage.s3.secret_key", "secretKey1")
20    @CONFIG.patch("storage.s3.use_ssl", "true")
21    def test_client_reuses_boto_client(self):
22        """Test repeated client access reuses the same boto client."""
23        with patch("boto3.Session") as session_cls:
24            session = session_cls.return_value
25            client = Mock()
26            session.client.return_value = client
27
28            backend = S3Backend(FileUsage.MEDIA)
29
30            self.assertIs(backend.client, client)
31            self.assertIs(backend.client, client)
32            session.client.assert_called_once()
33            self.assertIs(session.client.call_args.kwargs["use_ssl"], True)

Test repeated client access reuses the same boto client.

@CONFIG.patch('storage.s3.access_key', 'accessKey1')
@CONFIG.patch('storage.s3.secret_key', 'secretKey1')
def test_client_refreshes_when_config_changes(self):
35    @CONFIG.patch("storage.s3.access_key", "accessKey1")
36    @CONFIG.patch("storage.s3.secret_key", "secretKey1")
37    def test_client_refreshes_when_config_changes(self):
38        """Test client cache is invalidated when S3 client config changes."""
39        with CONFIG.patch("storage.s3.endpoint", "https://s3-1.example.com"):
40            with patch("boto3.Session") as session_cls:
41                session = session_cls.return_value
42                first_client = Mock()
43                second_client = Mock()
44                session.client.side_effect = [first_client, second_client]
45
46                backend = S3Backend(FileUsage.MEDIA)
47
48                self.assertIs(backend.client, first_client)
49                with CONFIG.patch("storage.s3.endpoint", "https://s3-2.example.com"):
50                    self.assertIs(backend.client, second_client)
51                self.assertEqual(session.client.call_count, 2)

Test client cache is invalidated when S3 client config changes.

@skipUnless(s3_test_server_available(), 'S3 test server not available')
class TestS3Backend(authentik.admin.files.tests.utils.FileTestS3BackendMixin, django.test.testcases.TestCase):
 54@skipUnless(s3_test_server_available(), "S3 test server not available")
 55class TestS3Backend(FileTestS3BackendMixin, TestCase):
 56    """Test S3 backend functionality"""
 57
 58    def setUp(self):
 59        super().setUp()
 60
 61    def test_base_path(self):
 62        """Test base_path property generates correct S3 key prefix"""
 63        expected = "media/public"
 64        self.assertEqual(self.media_s3_backend.base_path, expected)
 65
 66    def test_supports_file_path_s3(self):
 67        """Test supports_file_path returns True for s3 backend"""
 68        self.assertTrue(self.media_s3_backend.supports_file("path/to/any-file.png"))
 69        self.assertTrue(self.media_s3_backend.supports_file("any-file.png"))
 70
 71    def test_list_files(self):
 72        """Test list_files returns relative paths"""
 73        self.media_s3_backend.client.put_object(
 74            Bucket=self.media_s3_bucket_name,
 75            Key="media/public/file1.png",
 76            Body=b"test content",
 77            ACL="private",
 78        )
 79        self.media_s3_backend.client.put_object(
 80            Bucket=self.media_s3_bucket_name,
 81            Key="media/other/file1.png",
 82            Body=b"test content",
 83            ACL="private",
 84        )
 85
 86        files = list(self.media_s3_backend.list_files())
 87
 88        self.assertEqual(len(files), 1)
 89        self.assertIn("file1.png", files)
 90
 91    def test_list_files_empty(self):
 92        """Test list_files with no files"""
 93        files = list(self.media_s3_backend.list_files())
 94
 95        self.assertEqual(len(files), 0)
 96
 97    def test_save_file(self):
 98        """Test save_file uploads to S3"""
 99        content = b"test file content"
100        self.media_s3_backend.save_file("test.png", content)
101
102    def test_save_file_stream(self):
103        """Test save_file_stream uploads to S3 using context manager"""
104        with self.media_s3_backend.save_file_stream("test.csv") as f:
105            f.write(b"header1,header2\n")
106            f.write(b"value1,value2\n")
107
108    def test_delete_file(self):
109        """Test delete_file removes from S3"""
110        self.media_s3_backend.client.put_object(
111            Bucket=self.media_s3_bucket_name,
112            Key="media/public/test.png",
113            Body=b"test content",
114            ACL="private",
115        )
116        self.media_s3_backend.delete_file("test.png")
117
118    @CONFIG.patch("storage.s3.secure_urls", True)
119    @CONFIG.patch("storage.s3.custom_domain", None)
120    def test_file_url_basic(self):
121        """Test file_url generates presigned URL with AWS signature format"""
122        url = self.media_s3_backend.file_url("test.png")
123
124        self.assertIn("X-Amz-Algorithm=AWS4-HMAC-SHA256", url)
125        self.assertIn("X-Amz-Signature=", url)
126        self.assertIn("test.png", url)
127
128    def test_client_signature_version_default_v4(self):
129        """Test S3 client defaults to v4 signature when not configured."""
130        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3v4")
131
132    @CONFIG.patch("storage.s3.signature_version", "s3")
133    def test_client_signature_version_global_override(self):
134        """Test S3 client respects globally configured signature version."""
135        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3")
136
137    @CONFIG.patch("storage.s3.signature_version", "s3v4")
138    @CONFIG.patch("storage.media.s3.signature_version", "s3")
139    def test_client_signature_version_media_override(self):
140        """Test usage-specific signature version takes precedence over global."""
141        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3")
142
143    @CONFIG.patch("storage.media.s3.signature_version", "not-a-real-signature")
144    def test_client_signature_version_unsupported(self):
145        """Test unsupported signature version raises botocore error."""
146        with self.assertRaises(UnsupportedSignatureVersionError):
147            self.media_s3_backend.file_url("test.png", use_cache=False)
148
149    @CONFIG.patch("storage.s3.bucket_name", "test-bucket")
150    def test_file_exists_true(self):
151        """Test file_exists returns True for existing file"""
152        self.media_s3_backend.client.put_object(
153            Bucket=self.media_s3_bucket_name,
154            Key="media/public/test.png",
155            Body=b"test content",
156            ACL="private",
157        )
158
159        exists = self.media_s3_backend.file_exists("test.png")
160
161        self.assertTrue(exists)
162
163    @CONFIG.patch("storage.s3.bucket_name", "test-bucket")
164    def test_file_exists_false(self):
165        """Test file_exists returns False for non-existent file"""
166        exists = self.media_s3_backend.file_exists("nonexistent.png")
167
168        self.assertFalse(exists)
169
170    def test_allowed_usages(self):
171        """Test that S3Backend supports all usage types"""
172        self.assertEqual(self.media_s3_backend.allowed_usages, list(FileUsage))
173
174    def test_reports_usage(self):
175        """Test S3Backend with REPORTS usage"""
176        self.assertEqual(self.reports_s3_backend.usage, FileUsage.REPORTS)
177        self.assertEqual(self.reports_s3_backend.base_path, "reports/public")
178
179    @CONFIG.patch("storage.s3.secure_urls", True)
180    @CONFIG.patch("storage.s3.addressing_style", "path")
181    def test_file_url_custom_domain_with_bucket_no_duplicate(self):
182        """Test file_url doesn't duplicate bucket name when custom_domain includes bucket.
183
184        Regression test for https://github.com/goauthentik/authentik/issues/19521
185
186        When using:
187        - Path-style addressing (bucket name goes in URL path, not subdomain)
188        - Custom domain that includes the bucket name (e.g., s3.example.com/bucket-name)
189
190        The bucket name should NOT appear twice in the final URL.
191
192        Example of the bug:
193        - custom_domain = "s3.example.com/authentik-media"
194        - boto3 presigned URL = "http://s3.example.com/authentik-media/media/public/file.png?..."
195        - Buggy result = "https://s3.example.com/authentik-media/authentik-media/media/public/file.png?..."
196        """
197        bucket_name = self.media_s3_bucket_name
198
199        # Custom domain includes the bucket name
200        custom_domain = f"localhost:8020/{bucket_name}"
201
202        with CONFIG.patch("storage.media.s3.custom_domain", custom_domain):
203            url = self.media_s3_backend.file_url("application-icons/test.svg", use_cache=False)
204
205        # The bucket name should appear exactly once in the URL path, not twice
206        bucket_occurrences = url.count(bucket_name)
207        self.assertEqual(
208            bucket_occurrences,
209            1,
210            f"Bucket name '{bucket_name}' appears {bucket_occurrences} times in URL, expected 1. "
211            f"URL: {url}",
212        )
213
214    @CONFIG.patch("storage.s3.secure_urls", False)
215    @CONFIG.patch("storage.s3.addressing_style", "path")
216    def test_file_url_custom_domain_resigns_for_custom_host(self):
217        """Test presigned URLs are signed for the custom domain host.
218
219        Host-changing custom domains must produce a signature query string for
220        the public host, not reuse the internal endpoint signature.
221        """
222        bucket_name = self.media_s3_bucket_name
223        key_name = "application-icons/test.svg"
224        custom_domain = f"files.example.test:8020/{bucket_name}"
225
226        endpoint_signed_url = self.media_s3_backend.client.generate_presigned_url(
227            "get_object",
228            Params={
229                "Bucket": bucket_name,
230                "Key": f"{self.media_s3_backend.base_path}/{key_name}",
231            },
232            ExpiresIn=900,
233            HttpMethod="GET",
234        )
235
236        with CONFIG.patch("storage.media.s3.custom_domain", custom_domain):
237            custom_url = self.media_s3_backend.file_url(key_name, use_cache=False)
238
239        endpoint_parts = urlsplit(endpoint_signed_url)
240        custom_parts = urlsplit(custom_url)
241
242        self.assertEqual(custom_parts.scheme, "http")
243        self.assertEqual(custom_parts.netloc, "files.example.test:8020")
244        self.assertEqual(parse_qs(custom_parts.query)["X-Amz-SignedHeaders"], ["host"])
245        self.assertNotEqual(
246            custom_parts.query,
247            endpoint_parts.query,
248            "Custom-domain URLs must be signed for the public host, not reuse the endpoint "
249            "signature query string.",
250        )
251
252    def test_themed_urls_without_theme_variable(self):
253        """Test themed_urls returns None when filename has no %(theme)s"""
254        result = self.media_s3_backend.themed_urls("logo.png")
255        self.assertIsNone(result)
256
257    def test_themed_urls_with_theme_variable(self):
258        """Test themed_urls returns dict of presigned URLs for each theme"""
259        result = self.media_s3_backend.themed_urls("logo-%(theme)s.png")
260
261        self.assertIsInstance(result, dict)
262        self.assertIn("light", result)
263        self.assertIn("dark", result)
264
265        # Check URLs are valid presigned URLs with correct file paths
266        self.assertIn("logo-light.png", result["light"])
267        self.assertIn("logo-dark.png", result["dark"])
268        self.assertIn("X-Amz-Signature=", result["light"])
269        self.assertIn("X-Amz-Signature=", result["dark"])
270
271    def test_themed_urls_multiple_theme_variables(self):
272        """Test themed_urls with multiple %(theme)s in path"""
273        result = self.media_s3_backend.themed_urls("%(theme)s/logo-%(theme)s.svg")
274
275        self.assertIsInstance(result, dict)
276        self.assertIn("light/logo-light.svg", result["light"])
277        self.assertIn("dark/logo-dark.svg", result["dark"])
278
279    def test_save_file_sets_content_type_svg(self):
280        """Test save_file sets correct ContentType for SVG files"""
281        self.media_s3_backend.save_file("test.svg", b"<svg></svg>")
282
283        response = self.media_s3_backend.client.head_object(
284            Bucket=self.media_s3_bucket_name,
285            Key="media/public/test.svg",
286        )
287        self.assertEqual(response["ContentType"], "image/svg+xml")
288
289    def test_save_file_sets_content_type_png(self):
290        """Test save_file sets correct ContentType for PNG files"""
291        self.media_s3_backend.save_file("test.png", b"\x89PNG\r\n\x1a\n")
292
293        response = self.media_s3_backend.client.head_object(
294            Bucket=self.media_s3_bucket_name,
295            Key="media/public/test.png",
296        )
297        self.assertEqual(response["ContentType"], "image/png")
298
299    def test_save_file_stream_sets_content_type(self):
300        """Test save_file_stream sets correct ContentType"""
301        with self.media_s3_backend.save_file_stream("test.css") as f:
302            f.write(b"body { color: red; }")
303
304        response = self.media_s3_backend.client.head_object(
305            Bucket=self.media_s3_bucket_name,
306            Key="media/public/test.css",
307        )
308        self.assertEqual(response["ContentType"], "text/css")
309
310    def test_save_file_unknown_extension_octet_stream(self):
311        """Test save_file sets octet-stream for unknown extensions"""
312        self.media_s3_backend.save_file("test.unknownext123", b"data")
313
314        response = self.media_s3_backend.client.head_object(
315            Bucket=self.media_s3_bucket_name,
316            Key="media/public/test.unknownext123",
317        )
318        self.assertEqual(response["ContentType"], "application/octet-stream")

Test S3 backend functionality

def setUp(self):
58    def setUp(self):
59        super().setUp()

Hook method for setting up the test fixture before exercising it.

def test_base_path(self):
61    def test_base_path(self):
62        """Test base_path property generates correct S3 key prefix"""
63        expected = "media/public"
64        self.assertEqual(self.media_s3_backend.base_path, expected)

Test base_path property generates correct S3 key prefix

def test_supports_file_path_s3(self):
66    def test_supports_file_path_s3(self):
67        """Test supports_file_path returns True for s3 backend"""
68        self.assertTrue(self.media_s3_backend.supports_file("path/to/any-file.png"))
69        self.assertTrue(self.media_s3_backend.supports_file("any-file.png"))

Test supports_file_path returns True for s3 backend

def test_list_files(self):
71    def test_list_files(self):
72        """Test list_files returns relative paths"""
73        self.media_s3_backend.client.put_object(
74            Bucket=self.media_s3_bucket_name,
75            Key="media/public/file1.png",
76            Body=b"test content",
77            ACL="private",
78        )
79        self.media_s3_backend.client.put_object(
80            Bucket=self.media_s3_bucket_name,
81            Key="media/other/file1.png",
82            Body=b"test content",
83            ACL="private",
84        )
85
86        files = list(self.media_s3_backend.list_files())
87
88        self.assertEqual(len(files), 1)
89        self.assertIn("file1.png", files)

Test list_files returns relative paths

def test_list_files_empty(self):
91    def test_list_files_empty(self):
92        """Test list_files with no files"""
93        files = list(self.media_s3_backend.list_files())
94
95        self.assertEqual(len(files), 0)

Test list_files with no files

def test_save_file(self):
 97    def test_save_file(self):
 98        """Test save_file uploads to S3"""
 99        content = b"test file content"
100        self.media_s3_backend.save_file("test.png", content)

Test save_file uploads to S3

def test_save_file_stream(self):
102    def test_save_file_stream(self):
103        """Test save_file_stream uploads to S3 using context manager"""
104        with self.media_s3_backend.save_file_stream("test.csv") as f:
105            f.write(b"header1,header2\n")
106            f.write(b"value1,value2\n")

Test save_file_stream uploads to S3 using context manager

def test_delete_file(self):
108    def test_delete_file(self):
109        """Test delete_file removes from S3"""
110        self.media_s3_backend.client.put_object(
111            Bucket=self.media_s3_bucket_name,
112            Key="media/public/test.png",
113            Body=b"test content",
114            ACL="private",
115        )
116        self.media_s3_backend.delete_file("test.png")

Test delete_file removes from S3

@CONFIG.patch('storage.s3.secure_urls', True)
@CONFIG.patch('storage.s3.custom_domain', None)
def test_file_url_basic(self):
118    @CONFIG.patch("storage.s3.secure_urls", True)
119    @CONFIG.patch("storage.s3.custom_domain", None)
120    def test_file_url_basic(self):
121        """Test file_url generates presigned URL with AWS signature format"""
122        url = self.media_s3_backend.file_url("test.png")
123
124        self.assertIn("X-Amz-Algorithm=AWS4-HMAC-SHA256", url)
125        self.assertIn("X-Amz-Signature=", url)
126        self.assertIn("test.png", url)

Test file_url generates presigned URL with AWS signature format

def test_client_signature_version_default_v4(self):
128    def test_client_signature_version_default_v4(self):
129        """Test S3 client defaults to v4 signature when not configured."""
130        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3v4")

Test S3 client defaults to v4 signature when not configured.

@CONFIG.patch('storage.s3.signature_version', 's3')
def test_client_signature_version_global_override(self):
132    @CONFIG.patch("storage.s3.signature_version", "s3")
133    def test_client_signature_version_global_override(self):
134        """Test S3 client respects globally configured signature version."""
135        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3")

Test S3 client respects globally configured signature version.

@CONFIG.patch('storage.s3.signature_version', 's3v4')
@CONFIG.patch('storage.media.s3.signature_version', 's3')
def test_client_signature_version_media_override(self):
137    @CONFIG.patch("storage.s3.signature_version", "s3v4")
138    @CONFIG.patch("storage.media.s3.signature_version", "s3")
139    def test_client_signature_version_media_override(self):
140        """Test usage-specific signature version takes precedence over global."""
141        self.assertEqual(self.media_s3_backend.client.meta.config.signature_version, "s3")

Test usage-specific signature version takes precedence over global.

@CONFIG.patch('storage.media.s3.signature_version', 'not-a-real-signature')
def test_client_signature_version_unsupported(self):
143    @CONFIG.patch("storage.media.s3.signature_version", "not-a-real-signature")
144    def test_client_signature_version_unsupported(self):
145        """Test unsupported signature version raises botocore error."""
146        with self.assertRaises(UnsupportedSignatureVersionError):
147            self.media_s3_backend.file_url("test.png", use_cache=False)

Test unsupported signature version raises botocore error.

@CONFIG.patch('storage.s3.bucket_name', 'test-bucket')
def test_file_exists_true(self):
149    @CONFIG.patch("storage.s3.bucket_name", "test-bucket")
150    def test_file_exists_true(self):
151        """Test file_exists returns True for existing file"""
152        self.media_s3_backend.client.put_object(
153            Bucket=self.media_s3_bucket_name,
154            Key="media/public/test.png",
155            Body=b"test content",
156            ACL="private",
157        )
158
159        exists = self.media_s3_backend.file_exists("test.png")
160
161        self.assertTrue(exists)

Test file_exists returns True for existing file

@CONFIG.patch('storage.s3.bucket_name', 'test-bucket')
def test_file_exists_false(self):
163    @CONFIG.patch("storage.s3.bucket_name", "test-bucket")
164    def test_file_exists_false(self):
165        """Test file_exists returns False for non-existent file"""
166        exists = self.media_s3_backend.file_exists("nonexistent.png")
167
168        self.assertFalse(exists)

Test file_exists returns False for non-existent file

def test_allowed_usages(self):
170    def test_allowed_usages(self):
171        """Test that S3Backend supports all usage types"""
172        self.assertEqual(self.media_s3_backend.allowed_usages, list(FileUsage))

Test that S3Backend supports all usage types

def test_reports_usage(self):
174    def test_reports_usage(self):
175        """Test S3Backend with REPORTS usage"""
176        self.assertEqual(self.reports_s3_backend.usage, FileUsage.REPORTS)
177        self.assertEqual(self.reports_s3_backend.base_path, "reports/public")

Test S3Backend with REPORTS usage

@CONFIG.patch('storage.s3.secure_urls', True)
@CONFIG.patch('storage.s3.addressing_style', 'path')
def test_file_url_custom_domain_with_bucket_no_duplicate(self):
179    @CONFIG.patch("storage.s3.secure_urls", True)
180    @CONFIG.patch("storage.s3.addressing_style", "path")
181    def test_file_url_custom_domain_with_bucket_no_duplicate(self):
182        """Test file_url doesn't duplicate bucket name when custom_domain includes bucket.
183
184        Regression test for https://github.com/goauthentik/authentik/issues/19521
185
186        When using:
187        - Path-style addressing (bucket name goes in URL path, not subdomain)
188        - Custom domain that includes the bucket name (e.g., s3.example.com/bucket-name)
189
190        The bucket name should NOT appear twice in the final URL.
191
192        Example of the bug:
193        - custom_domain = "s3.example.com/authentik-media"
194        - boto3 presigned URL = "http://s3.example.com/authentik-media/media/public/file.png?..."
195        - Buggy result = "https://s3.example.com/authentik-media/authentik-media/media/public/file.png?..."
196        """
197        bucket_name = self.media_s3_bucket_name
198
199        # Custom domain includes the bucket name
200        custom_domain = f"localhost:8020/{bucket_name}"
201
202        with CONFIG.patch("storage.media.s3.custom_domain", custom_domain):
203            url = self.media_s3_backend.file_url("application-icons/test.svg", use_cache=False)
204
205        # The bucket name should appear exactly once in the URL path, not twice
206        bucket_occurrences = url.count(bucket_name)
207        self.assertEqual(
208            bucket_occurrences,
209            1,
210            f"Bucket name '{bucket_name}' appears {bucket_occurrences} times in URL, expected 1. "
211            f"URL: {url}",
212        )

Test file_url doesn't duplicate bucket name when custom_domain includes bucket.

Regression test for https://github.com/goauthentik/authentik/issues/19521

When using:

  • Path-style addressing (bucket name goes in URL path, not subdomain)
  • Custom domain that includes the bucket name (e.g., s3.example.com/bucket-name)

The bucket name should NOT appear twice in the final URL.

Example of the bug:

  • custom_domain = "s3.example.com/authentik-media"
  • boto3 presigned URL = "http://s3.example.com/authentik-media/media/public/file.png?..."
  • Buggy result = "https://s3.example.com/authentik-media/authentik-media/media/public/file.png?..."
@CONFIG.patch('storage.s3.secure_urls', False)
@CONFIG.patch('storage.s3.addressing_style', 'path')
def test_file_url_custom_domain_resigns_for_custom_host(self):
214    @CONFIG.patch("storage.s3.secure_urls", False)
215    @CONFIG.patch("storage.s3.addressing_style", "path")
216    def test_file_url_custom_domain_resigns_for_custom_host(self):
217        """Test presigned URLs are signed for the custom domain host.
218
219        Host-changing custom domains must produce a signature query string for
220        the public host, not reuse the internal endpoint signature.
221        """
222        bucket_name = self.media_s3_bucket_name
223        key_name = "application-icons/test.svg"
224        custom_domain = f"files.example.test:8020/{bucket_name}"
225
226        endpoint_signed_url = self.media_s3_backend.client.generate_presigned_url(
227            "get_object",
228            Params={
229                "Bucket": bucket_name,
230                "Key": f"{self.media_s3_backend.base_path}/{key_name}",
231            },
232            ExpiresIn=900,
233            HttpMethod="GET",
234        )
235
236        with CONFIG.patch("storage.media.s3.custom_domain", custom_domain):
237            custom_url = self.media_s3_backend.file_url(key_name, use_cache=False)
238
239        endpoint_parts = urlsplit(endpoint_signed_url)
240        custom_parts = urlsplit(custom_url)
241
242        self.assertEqual(custom_parts.scheme, "http")
243        self.assertEqual(custom_parts.netloc, "files.example.test:8020")
244        self.assertEqual(parse_qs(custom_parts.query)["X-Amz-SignedHeaders"], ["host"])
245        self.assertNotEqual(
246            custom_parts.query,
247            endpoint_parts.query,
248            "Custom-domain URLs must be signed for the public host, not reuse the endpoint "
249            "signature query string.",
250        )

Test presigned URLs are signed for the custom domain host.

Host-changing custom domains must produce a signature query string for the public host, not reuse the internal endpoint signature.

def test_themed_urls_without_theme_variable(self):
252    def test_themed_urls_without_theme_variable(self):
253        """Test themed_urls returns None when filename has no %(theme)s"""
254        result = self.media_s3_backend.themed_urls("logo.png")
255        self.assertIsNone(result)

Test themed_urls returns None when filename has no %(theme)s

def test_themed_urls_with_theme_variable(self):
257    def test_themed_urls_with_theme_variable(self):
258        """Test themed_urls returns dict of presigned URLs for each theme"""
259        result = self.media_s3_backend.themed_urls("logo-%(theme)s.png")
260
261        self.assertIsInstance(result, dict)
262        self.assertIn("light", result)
263        self.assertIn("dark", result)
264
265        # Check URLs are valid presigned URLs with correct file paths
266        self.assertIn("logo-light.png", result["light"])
267        self.assertIn("logo-dark.png", result["dark"])
268        self.assertIn("X-Amz-Signature=", result["light"])
269        self.assertIn("X-Amz-Signature=", result["dark"])

Test themed_urls returns dict of presigned URLs for each theme

def test_themed_urls_multiple_theme_variables(self):
271    def test_themed_urls_multiple_theme_variables(self):
272        """Test themed_urls with multiple %(theme)s in path"""
273        result = self.media_s3_backend.themed_urls("%(theme)s/logo-%(theme)s.svg")
274
275        self.assertIsInstance(result, dict)
276        self.assertIn("light/logo-light.svg", result["light"])
277        self.assertIn("dark/logo-dark.svg", result["dark"])

Test themed_urls with multiple %(theme)s in path

def test_save_file_sets_content_type_svg(self):
279    def test_save_file_sets_content_type_svg(self):
280        """Test save_file sets correct ContentType for SVG files"""
281        self.media_s3_backend.save_file("test.svg", b"<svg></svg>")
282
283        response = self.media_s3_backend.client.head_object(
284            Bucket=self.media_s3_bucket_name,
285            Key="media/public/test.svg",
286        )
287        self.assertEqual(response["ContentType"], "image/svg+xml")

Test save_file sets correct ContentType for SVG files

def test_save_file_sets_content_type_png(self):
289    def test_save_file_sets_content_type_png(self):
290        """Test save_file sets correct ContentType for PNG files"""
291        self.media_s3_backend.save_file("test.png", b"\x89PNG\r\n\x1a\n")
292
293        response = self.media_s3_backend.client.head_object(
294            Bucket=self.media_s3_bucket_name,
295            Key="media/public/test.png",
296        )
297        self.assertEqual(response["ContentType"], "image/png")

Test save_file sets correct ContentType for PNG files

def test_save_file_stream_sets_content_type(self):
299    def test_save_file_stream_sets_content_type(self):
300        """Test save_file_stream sets correct ContentType"""
301        with self.media_s3_backend.save_file_stream("test.css") as f:
302            f.write(b"body { color: red; }")
303
304        response = self.media_s3_backend.client.head_object(
305            Bucket=self.media_s3_bucket_name,
306            Key="media/public/test.css",
307        )
308        self.assertEqual(response["ContentType"], "text/css")

Test save_file_stream sets correct ContentType

def test_save_file_unknown_extension_octet_stream(self):
310    def test_save_file_unknown_extension_octet_stream(self):
311        """Test save_file sets octet-stream for unknown extensions"""
312        self.media_s3_backend.save_file("test.unknownext123", b"data")
313
314        response = self.media_s3_backend.client.head_object(
315            Bucket=self.media_s3_bucket_name,
316            Key="media/public/test.unknownext123",
317        )
318        self.assertEqual(response["ContentType"], "application/octet-stream")

Test save_file sets octet-stream for unknown extensions