authentik.core.tests.test_users_avatars

Test Users Avatars

  1"""Test Users Avatars"""
  2
  3from datetime import timedelta
  4from hashlib import md5
  5from json import loads
  6
  7from django.core.cache import cache
  8from django.urls.base import reverse
  9from django.utils.timezone import now
 10from django_postgres_cache.models import CacheEntry
 11from requests_mock import Mocker
 12from rest_framework.test import APITestCase
 13
 14from authentik.admin.utils import get_system_settings
 15from authentik.core.models import User
 16from authentik.core.tests.utils import create_test_admin_user
 17from authentik.lib.avatars import AVATAR_STATUS_TTL_SECONDS
 18
 19
 20class TestUsersAvatars(APITestCase):
 21    """Test Users avatars"""
 22
 23    def setUp(self) -> None:
 24        self.admin = create_test_admin_user()
 25        self.user = User.objects.create(username="test-user")
 26
 27    def set_avatar_mode(self, mode: str):
 28        """Set the avatar mode on the current system settings."""
 29        settings = get_system_settings()
 30        settings.avatars = mode
 31        settings.save()
 32
 33    def test_avatars_none(self):
 34        """Test avatars none"""
 35        self.set_avatar_mode("none")
 36        self.client.force_login(self.admin)
 37        response = self.client.get(reverse("authentik_api:user-me"))
 38        self.assertEqual(response.status_code, 200)
 39        body = loads(response.content.decode())
 40        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")
 41
 42    def test_avatars_gravatar(self):
 43        """Test avatars gravatar"""
 44        self.set_avatar_mode("gravatar")
 45        self.admin.email = "static@t.goauthentik.io"
 46        self.admin.save()
 47        self.client.force_login(self.admin)
 48        with Mocker() as mocker:
 49            mocker.head(
 50                (
 51                    "https://www.gravatar.com/avatar/76eb3c74c8beb6faa037f1b6e2ecb3e252bdac"
 52                    "6cf71fb567ae36025a9d4ea86b?size=158&rating=g&default=404"
 53                ),
 54                text="foo",
 55                headers={"Content-Type": "image/png"},
 56            )
 57            response = self.client.get(reverse("authentik_api:user-me"))
 58        self.assertEqual(response.status_code, 200)
 59        body = loads(response.content.decode())
 60        self.assertIn("gravatar", body["user"]["avatar"])
 61
 62    def test_avatars_initials(self):
 63        """Test avatars initials"""
 64        self.set_avatar_mode("initials")
 65        self.client.force_login(self.admin)
 66        response = self.client.get(reverse("authentik_api:user-me"))
 67        self.assertEqual(response.status_code, 200)
 68        body = loads(response.content.decode())
 69        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
 70
 71    def test_avatars_custom(self):
 72        """Test avatars custom"""
 73        self.set_avatar_mode("foo://%(username)s")
 74        self.client.force_login(self.admin)
 75        response = self.client.get(reverse("authentik_api:user-me"))
 76        self.assertEqual(response.status_code, 200)
 77        body = loads(response.content.decode())
 78        self.assertEqual(body["user"]["avatar"], f"foo://{self.admin.username}")
 79
 80    def test_avatars_attributes(self):
 81        """Test avatars attributes"""
 82        self.set_avatar_mode("attributes.foo.avatar")
 83        self.admin.attributes = {"foo": {"avatar": "bar"}}
 84        self.admin.save()
 85        self.client.force_login(self.admin)
 86        response = self.client.get(reverse("authentik_api:user-me"))
 87        self.assertEqual(response.status_code, 200)
 88        body = loads(response.content.decode())
 89        self.assertEqual(body["user"]["avatar"], "bar")
 90
 91    def test_avatars_fallback(self):
 92        """Test fallback"""
 93        self.set_avatar_mode("attributes.foo.avatar,initials")
 94        self.client.force_login(self.admin)
 95        response = self.client.get(reverse("authentik_api:user-me"))
 96        self.assertEqual(response.status_code, 200)
 97        body = loads(response.content.decode())
 98        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
 99
100    def test_avatars_custom_content_type_valid(self):
101        """Test custom avatar URL with valid image Content-Type"""
102        cache.clear()
103        self.set_avatar_mode("https://example.com/avatar/%(username)s")
104        self.client.force_login(self.admin)
105        with Mocker() as mocker:
106            mocker.head(
107                f"https://example.com/avatar/{self.admin.username}",
108                headers={"Content-Type": "image/png"},
109            )
110            response = self.client.get(reverse("authentik_api:user-me"))
111        self.assertEqual(response.status_code, 200)
112        body = loads(response.content.decode())
113        self.assertEqual(
114            body["user"]["avatar"], f"https://example.com/avatar/{self.admin.username}"
115        )
116
117    def test_avatars_custom_url_encoded(self):
118        """Test custom avatar URL with percent-encoded characters"""
119        cache.clear()
120        avatar_url = (
121            "https://example.com/avatar%2Ffoo.png?"
122            "next=https%3A%2F%2Fcdn.example.com%2Favatar.png"
123        )
124        self.set_avatar_mode(avatar_url)
125        self.client.force_login(self.admin)
126        with Mocker() as mocker:
127            mocker.head(
128                avatar_url,
129                headers={"Content-Type": "image/png"},
130            )
131            response = self.client.get(reverse("authentik_api:user-me"))
132        self.assertEqual(response.status_code, 200)
133        body = loads(response.content.decode())
134        self.assertEqual(body["user"]["avatar"], avatar_url)
135
136    def test_avatars_custom_content_type_invalid(self):
137        """Test custom avatar URL with invalid Content-Type falls back"""
138        cache.clear()
139        self.set_avatar_mode("https://example.com/avatar/%(username)s,initials")
140        self.client.force_login(self.admin)
141        with Mocker() as mocker:
142            mocker.head(
143                f"https://example.com/avatar/{self.admin.username}",
144                headers={"Content-Type": "text/html"},
145            )
146            response = self.client.get(reverse("authentik_api:user-me"))
147        self.assertEqual(response.status_code, 200)
148        body = loads(response.content.decode())
149        # Should fallback to initials since Content-Type is not image/*
150        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
151
152    def test_avatars_custom_content_type_missing(self):
153        """Test custom avatar URL with missing Content-Type header falls back"""
154        cache.clear()
155        self.set_avatar_mode("https://example.com/avatar/%(username)s,initials")
156        self.client.force_login(self.admin)
157        with Mocker() as mocker:
158            mocker.head(
159                f"https://example.com/avatar/{self.admin.username}",
160                headers={},
161            )
162            response = self.client.get(reverse("authentik_api:user-me"))
163        self.assertEqual(response.status_code, 200)
164        body = loads(response.content.decode())
165        # Should fallback to initials since Content-Type header is missing
166        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
167
168    def test_avatars_custom_404_cached(self):
169        """Test that 404 responses are cached with TTL"""
170        cache.clear()
171        self.set_avatar_mode("https://example.com/avatar/%(username)s")
172        self.client.force_login(self.admin)
173        with Mocker() as mocker:
174            mocker.head(
175                f"https://example.com/avatar/{self.admin.username}",
176                status_code=404,
177            )
178            response = self.client.get(reverse("authentik_api:user-me"))
179        self.assertEqual(response.status_code, 200)
180        body = loads(response.content.decode())
181        # Should fallback to default avatar
182        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")
183
184        # Verify cache was set with the expected structure
185        from hashlib import md5
186
187        mail_hash = md5(self.admin.email.lower().encode("utf-8"), usedforsecurity=False).hexdigest()
188        cache_key = f"goauthentik.io/lib/avatars/example.com/{mail_hash}"
189        self.assertIsNone(cache.get(cache_key))
190        # Verify TTL was set (cache entry exists)
191        self.assertTrue(cache.has_key(cache_key))
192
193    def test_avatars_cache_hit_keeps_ttl(self):
194        """Test that a cache hit keeps the avatar TTL instead of shortening it to the default"""
195        cache.clear()
196        self.set_avatar_mode("https://example.com/avatar/%(username)s")
197        self.client.force_login(self.admin)
198        with Mocker() as mocker:
199            mocker.head(
200                f"https://example.com/avatar/{self.admin.username}",
201                headers={"Content-Type": "image/png"},
202            )
203            # The first request fills the cache, the second one hits it
204            for _ in range(2):
205                response = self.client.get(reverse("authentik_api:user-me"))
206                self.assertEqual(response.status_code, 200)
207            self.assertEqual(mocker.call_count, 1)
208
209        mail_hash = md5(self.admin.email.lower().encode("utf-8"), usedforsecurity=False).hexdigest()
210        cache_key = cache.make_key(f"goauthentik.io/lib/avatars/example.com/{mail_hash}")
211        entry = CacheEntry.objects.get(cache_key=cache_key)
212        self.assertGreater(entry.expires - now(), timedelta(seconds=AVATAR_STATUS_TTL_SECONDS - 60))
213
214    def test_avatars_custom_redirect(self):
215        """Test custom avatar URL follows redirects"""
216        cache.clear()
217        self.set_avatar_mode("https://example.com/avatar/%(username)s")
218        self.client.force_login(self.admin)
219        with Mocker() as mocker:
220            # Mock a redirect
221            mocker.head(
222                f"https://example.com/avatar/{self.admin.username}",
223                status_code=302,
224                headers={"Location": "https://cdn.example.com/final-avatar.png"},
225            )
226            mocker.head(
227                "https://cdn.example.com/final-avatar.png",
228                headers={"Content-Type": "image/png"},
229            )
230            response = self.client.get(reverse("authentik_api:user-me"))
231        self.assertEqual(response.status_code, 200)
232        body = loads(response.content.decode())
233        # Should return the original URL (not the redirect destination)
234        self.assertEqual(
235            body["user"]["avatar"], f"https://example.com/avatar/{self.admin.username}"
236        )
237
238    def test_avatars_hostname_availability_cache(self):
239        """Test that hostname availability is cached when domain fails"""
240        from requests.exceptions import Timeout
241
242        cache.clear()
243        self.set_avatar_mode("https://failing.example.com/avatar/%(username)s,initials")
244        self.client.force_login(self.admin)
245
246        with Mocker() as mocker:
247            # First request times out
248            mocker.head(
249                f"https://failing.example.com/avatar/{self.admin.username}",
250                exc=Timeout("Connection timeout"),
251            )
252            response = self.client.get(reverse("authentik_api:user-me"))
253
254        self.assertEqual(response.status_code, 200)
255        body = loads(response.content.decode())
256        # Should fallback to initials
257        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
258
259        # Verify hostname is marked as unavailable
260        cache_key_hostname = "goauthentik.io/lib/avatars/failing.example.com/available"
261        self.assertFalse(cache.get(cache_key_hostname, True))
262
263        # Second request should not even try to fetch (hostname cached as unavailable)
264        with Mocker() as mocker:
265            # This should NOT be called due to hostname cache
266            mocker.head(
267                f"https://failing.example.com/avatar/{self.admin.username}",
268                headers={"Content-Type": "image/png"},
269            )
270            response = self.client.get(reverse("authentik_api:user-me"))
271
272        self.assertEqual(response.status_code, 200)
273        body = loads(response.content.decode())
274        # Should still fallback to initials without making a request
275        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
276        # Verify no request was made (request_history should be empty)
277        self.assertEqual(len(mocker.request_history), 0)
278
279    def test_avatars_gravatar_uses_url_validation(self):
280        """Test that Gravatar now uses avatar_mode_url validation (regression test)"""
281        cache.clear()
282        self.set_avatar_mode("gravatar")
283        self.admin.email = "test@example.com"
284        self.admin.save()
285        self.client.force_login(self.admin)
286
287        with Mocker() as mocker:
288            # Mock Gravatar to return non-image content
289            from hashlib import sha256
290
291            mail_hash = sha256(self.admin.email.lower().encode("utf-8")).hexdigest()
292            gravatar_url = (
293                f"https://www.gravatar.com/avatar/{mail_hash}?size=158&rating=g&default=404"
294            )
295
296            mocker.head(
297                gravatar_url,
298                headers={"Content-Type": "text/html"},
299            )
300            response = self.client.get(reverse("authentik_api:user-me"))
301
302        self.assertEqual(response.status_code, 200)
303        body = loads(response.content.decode())
304        # Should fallback to default avatar since Content-Type is not image/*
305        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")
class TestUsersAvatars(rest_framework.test.APITestCase):
 21class TestUsersAvatars(APITestCase):
 22    """Test Users avatars"""
 23
 24    def setUp(self) -> None:
 25        self.admin = create_test_admin_user()
 26        self.user = User.objects.create(username="test-user")
 27
 28    def set_avatar_mode(self, mode: str):
 29        """Set the avatar mode on the current system settings."""
 30        settings = get_system_settings()
 31        settings.avatars = mode
 32        settings.save()
 33
 34    def test_avatars_none(self):
 35        """Test avatars none"""
 36        self.set_avatar_mode("none")
 37        self.client.force_login(self.admin)
 38        response = self.client.get(reverse("authentik_api:user-me"))
 39        self.assertEqual(response.status_code, 200)
 40        body = loads(response.content.decode())
 41        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")
 42
 43    def test_avatars_gravatar(self):
 44        """Test avatars gravatar"""
 45        self.set_avatar_mode("gravatar")
 46        self.admin.email = "static@t.goauthentik.io"
 47        self.admin.save()
 48        self.client.force_login(self.admin)
 49        with Mocker() as mocker:
 50            mocker.head(
 51                (
 52                    "https://www.gravatar.com/avatar/76eb3c74c8beb6faa037f1b6e2ecb3e252bdac"
 53                    "6cf71fb567ae36025a9d4ea86b?size=158&rating=g&default=404"
 54                ),
 55                text="foo",
 56                headers={"Content-Type": "image/png"},
 57            )
 58            response = self.client.get(reverse("authentik_api:user-me"))
 59        self.assertEqual(response.status_code, 200)
 60        body = loads(response.content.decode())
 61        self.assertIn("gravatar", body["user"]["avatar"])
 62
 63    def test_avatars_initials(self):
 64        """Test avatars initials"""
 65        self.set_avatar_mode("initials")
 66        self.client.force_login(self.admin)
 67        response = self.client.get(reverse("authentik_api:user-me"))
 68        self.assertEqual(response.status_code, 200)
 69        body = loads(response.content.decode())
 70        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
 71
 72    def test_avatars_custom(self):
 73        """Test avatars custom"""
 74        self.set_avatar_mode("foo://%(username)s")
 75        self.client.force_login(self.admin)
 76        response = self.client.get(reverse("authentik_api:user-me"))
 77        self.assertEqual(response.status_code, 200)
 78        body = loads(response.content.decode())
 79        self.assertEqual(body["user"]["avatar"], f"foo://{self.admin.username}")
 80
 81    def test_avatars_attributes(self):
 82        """Test avatars attributes"""
 83        self.set_avatar_mode("attributes.foo.avatar")
 84        self.admin.attributes = {"foo": {"avatar": "bar"}}
 85        self.admin.save()
 86        self.client.force_login(self.admin)
 87        response = self.client.get(reverse("authentik_api:user-me"))
 88        self.assertEqual(response.status_code, 200)
 89        body = loads(response.content.decode())
 90        self.assertEqual(body["user"]["avatar"], "bar")
 91
 92    def test_avatars_fallback(self):
 93        """Test fallback"""
 94        self.set_avatar_mode("attributes.foo.avatar,initials")
 95        self.client.force_login(self.admin)
 96        response = self.client.get(reverse("authentik_api:user-me"))
 97        self.assertEqual(response.status_code, 200)
 98        body = loads(response.content.decode())
 99        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
100
101    def test_avatars_custom_content_type_valid(self):
102        """Test custom avatar URL with valid image Content-Type"""
103        cache.clear()
104        self.set_avatar_mode("https://example.com/avatar/%(username)s")
105        self.client.force_login(self.admin)
106        with Mocker() as mocker:
107            mocker.head(
108                f"https://example.com/avatar/{self.admin.username}",
109                headers={"Content-Type": "image/png"},
110            )
111            response = self.client.get(reverse("authentik_api:user-me"))
112        self.assertEqual(response.status_code, 200)
113        body = loads(response.content.decode())
114        self.assertEqual(
115            body["user"]["avatar"], f"https://example.com/avatar/{self.admin.username}"
116        )
117
118    def test_avatars_custom_url_encoded(self):
119        """Test custom avatar URL with percent-encoded characters"""
120        cache.clear()
121        avatar_url = (
122            "https://example.com/avatar%2Ffoo.png?"
123            "next=https%3A%2F%2Fcdn.example.com%2Favatar.png"
124        )
125        self.set_avatar_mode(avatar_url)
126        self.client.force_login(self.admin)
127        with Mocker() as mocker:
128            mocker.head(
129                avatar_url,
130                headers={"Content-Type": "image/png"},
131            )
132            response = self.client.get(reverse("authentik_api:user-me"))
133        self.assertEqual(response.status_code, 200)
134        body = loads(response.content.decode())
135        self.assertEqual(body["user"]["avatar"], avatar_url)
136
137    def test_avatars_custom_content_type_invalid(self):
138        """Test custom avatar URL with invalid Content-Type falls back"""
139        cache.clear()
140        self.set_avatar_mode("https://example.com/avatar/%(username)s,initials")
141        self.client.force_login(self.admin)
142        with Mocker() as mocker:
143            mocker.head(
144                f"https://example.com/avatar/{self.admin.username}",
145                headers={"Content-Type": "text/html"},
146            )
147            response = self.client.get(reverse("authentik_api:user-me"))
148        self.assertEqual(response.status_code, 200)
149        body = loads(response.content.decode())
150        # Should fallback to initials since Content-Type is not image/*
151        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
152
153    def test_avatars_custom_content_type_missing(self):
154        """Test custom avatar URL with missing Content-Type header falls back"""
155        cache.clear()
156        self.set_avatar_mode("https://example.com/avatar/%(username)s,initials")
157        self.client.force_login(self.admin)
158        with Mocker() as mocker:
159            mocker.head(
160                f"https://example.com/avatar/{self.admin.username}",
161                headers={},
162            )
163            response = self.client.get(reverse("authentik_api:user-me"))
164        self.assertEqual(response.status_code, 200)
165        body = loads(response.content.decode())
166        # Should fallback to initials since Content-Type header is missing
167        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
168
169    def test_avatars_custom_404_cached(self):
170        """Test that 404 responses are cached with TTL"""
171        cache.clear()
172        self.set_avatar_mode("https://example.com/avatar/%(username)s")
173        self.client.force_login(self.admin)
174        with Mocker() as mocker:
175            mocker.head(
176                f"https://example.com/avatar/{self.admin.username}",
177                status_code=404,
178            )
179            response = self.client.get(reverse("authentik_api:user-me"))
180        self.assertEqual(response.status_code, 200)
181        body = loads(response.content.decode())
182        # Should fallback to default avatar
183        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")
184
185        # Verify cache was set with the expected structure
186        from hashlib import md5
187
188        mail_hash = md5(self.admin.email.lower().encode("utf-8"), usedforsecurity=False).hexdigest()
189        cache_key = f"goauthentik.io/lib/avatars/example.com/{mail_hash}"
190        self.assertIsNone(cache.get(cache_key))
191        # Verify TTL was set (cache entry exists)
192        self.assertTrue(cache.has_key(cache_key))
193
194    def test_avatars_cache_hit_keeps_ttl(self):
195        """Test that a cache hit keeps the avatar TTL instead of shortening it to the default"""
196        cache.clear()
197        self.set_avatar_mode("https://example.com/avatar/%(username)s")
198        self.client.force_login(self.admin)
199        with Mocker() as mocker:
200            mocker.head(
201                f"https://example.com/avatar/{self.admin.username}",
202                headers={"Content-Type": "image/png"},
203            )
204            # The first request fills the cache, the second one hits it
205            for _ in range(2):
206                response = self.client.get(reverse("authentik_api:user-me"))
207                self.assertEqual(response.status_code, 200)
208            self.assertEqual(mocker.call_count, 1)
209
210        mail_hash = md5(self.admin.email.lower().encode("utf-8"), usedforsecurity=False).hexdigest()
211        cache_key = cache.make_key(f"goauthentik.io/lib/avatars/example.com/{mail_hash}")
212        entry = CacheEntry.objects.get(cache_key=cache_key)
213        self.assertGreater(entry.expires - now(), timedelta(seconds=AVATAR_STATUS_TTL_SECONDS - 60))
214
215    def test_avatars_custom_redirect(self):
216        """Test custom avatar URL follows redirects"""
217        cache.clear()
218        self.set_avatar_mode("https://example.com/avatar/%(username)s")
219        self.client.force_login(self.admin)
220        with Mocker() as mocker:
221            # Mock a redirect
222            mocker.head(
223                f"https://example.com/avatar/{self.admin.username}",
224                status_code=302,
225                headers={"Location": "https://cdn.example.com/final-avatar.png"},
226            )
227            mocker.head(
228                "https://cdn.example.com/final-avatar.png",
229                headers={"Content-Type": "image/png"},
230            )
231            response = self.client.get(reverse("authentik_api:user-me"))
232        self.assertEqual(response.status_code, 200)
233        body = loads(response.content.decode())
234        # Should return the original URL (not the redirect destination)
235        self.assertEqual(
236            body["user"]["avatar"], f"https://example.com/avatar/{self.admin.username}"
237        )
238
239    def test_avatars_hostname_availability_cache(self):
240        """Test that hostname availability is cached when domain fails"""
241        from requests.exceptions import Timeout
242
243        cache.clear()
244        self.set_avatar_mode("https://failing.example.com/avatar/%(username)s,initials")
245        self.client.force_login(self.admin)
246
247        with Mocker() as mocker:
248            # First request times out
249            mocker.head(
250                f"https://failing.example.com/avatar/{self.admin.username}",
251                exc=Timeout("Connection timeout"),
252            )
253            response = self.client.get(reverse("authentik_api:user-me"))
254
255        self.assertEqual(response.status_code, 200)
256        body = loads(response.content.decode())
257        # Should fallback to initials
258        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
259
260        # Verify hostname is marked as unavailable
261        cache_key_hostname = "goauthentik.io/lib/avatars/failing.example.com/available"
262        self.assertFalse(cache.get(cache_key_hostname, True))
263
264        # Second request should not even try to fetch (hostname cached as unavailable)
265        with Mocker() as mocker:
266            # This should NOT be called due to hostname cache
267            mocker.head(
268                f"https://failing.example.com/avatar/{self.admin.username}",
269                headers={"Content-Type": "image/png"},
270            )
271            response = self.client.get(reverse("authentik_api:user-me"))
272
273        self.assertEqual(response.status_code, 200)
274        body = loads(response.content.decode())
275        # Should still fallback to initials without making a request
276        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
277        # Verify no request was made (request_history should be empty)
278        self.assertEqual(len(mocker.request_history), 0)
279
280    def test_avatars_gravatar_uses_url_validation(self):
281        """Test that Gravatar now uses avatar_mode_url validation (regression test)"""
282        cache.clear()
283        self.set_avatar_mode("gravatar")
284        self.admin.email = "test@example.com"
285        self.admin.save()
286        self.client.force_login(self.admin)
287
288        with Mocker() as mocker:
289            # Mock Gravatar to return non-image content
290            from hashlib import sha256
291
292            mail_hash = sha256(self.admin.email.lower().encode("utf-8")).hexdigest()
293            gravatar_url = (
294                f"https://www.gravatar.com/avatar/{mail_hash}?size=158&rating=g&default=404"
295            )
296
297            mocker.head(
298                gravatar_url,
299                headers={"Content-Type": "text/html"},
300            )
301            response = self.client.get(reverse("authentik_api:user-me"))
302
303        self.assertEqual(response.status_code, 200)
304        body = loads(response.content.decode())
305        # Should fallback to default avatar since Content-Type is not image/*
306        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")

Test Users avatars

def setUp(self) -> None:
24    def setUp(self) -> None:
25        self.admin = create_test_admin_user()
26        self.user = User.objects.create(username="test-user")

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

def set_avatar_mode(self, mode: str):
28    def set_avatar_mode(self, mode: str):
29        """Set the avatar mode on the current system settings."""
30        settings = get_system_settings()
31        settings.avatars = mode
32        settings.save()

Set the avatar mode on the current system settings.

def test_avatars_none(self):
34    def test_avatars_none(self):
35        """Test avatars none"""
36        self.set_avatar_mode("none")
37        self.client.force_login(self.admin)
38        response = self.client.get(reverse("authentik_api:user-me"))
39        self.assertEqual(response.status_code, 200)
40        body = loads(response.content.decode())
41        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")

Test avatars none

def test_avatars_gravatar(self):
43    def test_avatars_gravatar(self):
44        """Test avatars gravatar"""
45        self.set_avatar_mode("gravatar")
46        self.admin.email = "static@t.goauthentik.io"
47        self.admin.save()
48        self.client.force_login(self.admin)
49        with Mocker() as mocker:
50            mocker.head(
51                (
52                    "https://www.gravatar.com/avatar/76eb3c74c8beb6faa037f1b6e2ecb3e252bdac"
53                    "6cf71fb567ae36025a9d4ea86b?size=158&rating=g&default=404"
54                ),
55                text="foo",
56                headers={"Content-Type": "image/png"},
57            )
58            response = self.client.get(reverse("authentik_api:user-me"))
59        self.assertEqual(response.status_code, 200)
60        body = loads(response.content.decode())
61        self.assertIn("gravatar", body["user"]["avatar"])

Test avatars gravatar

def test_avatars_initials(self):
63    def test_avatars_initials(self):
64        """Test avatars initials"""
65        self.set_avatar_mode("initials")
66        self.client.force_login(self.admin)
67        response = self.client.get(reverse("authentik_api:user-me"))
68        self.assertEqual(response.status_code, 200)
69        body = loads(response.content.decode())
70        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])

Test avatars initials

def test_avatars_custom(self):
72    def test_avatars_custom(self):
73        """Test avatars custom"""
74        self.set_avatar_mode("foo://%(username)s")
75        self.client.force_login(self.admin)
76        response = self.client.get(reverse("authentik_api:user-me"))
77        self.assertEqual(response.status_code, 200)
78        body = loads(response.content.decode())
79        self.assertEqual(body["user"]["avatar"], f"foo://{self.admin.username}")

Test avatars custom

def test_avatars_attributes(self):
81    def test_avatars_attributes(self):
82        """Test avatars attributes"""
83        self.set_avatar_mode("attributes.foo.avatar")
84        self.admin.attributes = {"foo": {"avatar": "bar"}}
85        self.admin.save()
86        self.client.force_login(self.admin)
87        response = self.client.get(reverse("authentik_api:user-me"))
88        self.assertEqual(response.status_code, 200)
89        body = loads(response.content.decode())
90        self.assertEqual(body["user"]["avatar"], "bar")

Test avatars attributes

def test_avatars_fallback(self):
92    def test_avatars_fallback(self):
93        """Test fallback"""
94        self.set_avatar_mode("attributes.foo.avatar,initials")
95        self.client.force_login(self.admin)
96        response = self.client.get(reverse("authentik_api:user-me"))
97        self.assertEqual(response.status_code, 200)
98        body = loads(response.content.decode())
99        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])

Test fallback

def test_avatars_custom_content_type_valid(self):
101    def test_avatars_custom_content_type_valid(self):
102        """Test custom avatar URL with valid image Content-Type"""
103        cache.clear()
104        self.set_avatar_mode("https://example.com/avatar/%(username)s")
105        self.client.force_login(self.admin)
106        with Mocker() as mocker:
107            mocker.head(
108                f"https://example.com/avatar/{self.admin.username}",
109                headers={"Content-Type": "image/png"},
110            )
111            response = self.client.get(reverse("authentik_api:user-me"))
112        self.assertEqual(response.status_code, 200)
113        body = loads(response.content.decode())
114        self.assertEqual(
115            body["user"]["avatar"], f"https://example.com/avatar/{self.admin.username}"
116        )

Test custom avatar URL with valid image Content-Type

def test_avatars_custom_url_encoded(self):
118    def test_avatars_custom_url_encoded(self):
119        """Test custom avatar URL with percent-encoded characters"""
120        cache.clear()
121        avatar_url = (
122            "https://example.com/avatar%2Ffoo.png?"
123            "next=https%3A%2F%2Fcdn.example.com%2Favatar.png"
124        )
125        self.set_avatar_mode(avatar_url)
126        self.client.force_login(self.admin)
127        with Mocker() as mocker:
128            mocker.head(
129                avatar_url,
130                headers={"Content-Type": "image/png"},
131            )
132            response = self.client.get(reverse("authentik_api:user-me"))
133        self.assertEqual(response.status_code, 200)
134        body = loads(response.content.decode())
135        self.assertEqual(body["user"]["avatar"], avatar_url)

Test custom avatar URL with percent-encoded characters

def test_avatars_custom_content_type_invalid(self):
137    def test_avatars_custom_content_type_invalid(self):
138        """Test custom avatar URL with invalid Content-Type falls back"""
139        cache.clear()
140        self.set_avatar_mode("https://example.com/avatar/%(username)s,initials")
141        self.client.force_login(self.admin)
142        with Mocker() as mocker:
143            mocker.head(
144                f"https://example.com/avatar/{self.admin.username}",
145                headers={"Content-Type": "text/html"},
146            )
147            response = self.client.get(reverse("authentik_api:user-me"))
148        self.assertEqual(response.status_code, 200)
149        body = loads(response.content.decode())
150        # Should fallback to initials since Content-Type is not image/*
151        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])

Test custom avatar URL with invalid Content-Type falls back

def test_avatars_custom_content_type_missing(self):
153    def test_avatars_custom_content_type_missing(self):
154        """Test custom avatar URL with missing Content-Type header falls back"""
155        cache.clear()
156        self.set_avatar_mode("https://example.com/avatar/%(username)s,initials")
157        self.client.force_login(self.admin)
158        with Mocker() as mocker:
159            mocker.head(
160                f"https://example.com/avatar/{self.admin.username}",
161                headers={},
162            )
163            response = self.client.get(reverse("authentik_api:user-me"))
164        self.assertEqual(response.status_code, 200)
165        body = loads(response.content.decode())
166        # Should fallback to initials since Content-Type header is missing
167        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])

Test custom avatar URL with missing Content-Type header falls back

def test_avatars_custom_404_cached(self):
169    def test_avatars_custom_404_cached(self):
170        """Test that 404 responses are cached with TTL"""
171        cache.clear()
172        self.set_avatar_mode("https://example.com/avatar/%(username)s")
173        self.client.force_login(self.admin)
174        with Mocker() as mocker:
175            mocker.head(
176                f"https://example.com/avatar/{self.admin.username}",
177                status_code=404,
178            )
179            response = self.client.get(reverse("authentik_api:user-me"))
180        self.assertEqual(response.status_code, 200)
181        body = loads(response.content.decode())
182        # Should fallback to default avatar
183        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")
184
185        # Verify cache was set with the expected structure
186        from hashlib import md5
187
188        mail_hash = md5(self.admin.email.lower().encode("utf-8"), usedforsecurity=False).hexdigest()
189        cache_key = f"goauthentik.io/lib/avatars/example.com/{mail_hash}"
190        self.assertIsNone(cache.get(cache_key))
191        # Verify TTL was set (cache entry exists)
192        self.assertTrue(cache.has_key(cache_key))

Test that 404 responses are cached with TTL

def test_avatars_cache_hit_keeps_ttl(self):
194    def test_avatars_cache_hit_keeps_ttl(self):
195        """Test that a cache hit keeps the avatar TTL instead of shortening it to the default"""
196        cache.clear()
197        self.set_avatar_mode("https://example.com/avatar/%(username)s")
198        self.client.force_login(self.admin)
199        with Mocker() as mocker:
200            mocker.head(
201                f"https://example.com/avatar/{self.admin.username}",
202                headers={"Content-Type": "image/png"},
203            )
204            # The first request fills the cache, the second one hits it
205            for _ in range(2):
206                response = self.client.get(reverse("authentik_api:user-me"))
207                self.assertEqual(response.status_code, 200)
208            self.assertEqual(mocker.call_count, 1)
209
210        mail_hash = md5(self.admin.email.lower().encode("utf-8"), usedforsecurity=False).hexdigest()
211        cache_key = cache.make_key(f"goauthentik.io/lib/avatars/example.com/{mail_hash}")
212        entry = CacheEntry.objects.get(cache_key=cache_key)
213        self.assertGreater(entry.expires - now(), timedelta(seconds=AVATAR_STATUS_TTL_SECONDS - 60))

Test that a cache hit keeps the avatar TTL instead of shortening it to the default

def test_avatars_custom_redirect(self):
215    def test_avatars_custom_redirect(self):
216        """Test custom avatar URL follows redirects"""
217        cache.clear()
218        self.set_avatar_mode("https://example.com/avatar/%(username)s")
219        self.client.force_login(self.admin)
220        with Mocker() as mocker:
221            # Mock a redirect
222            mocker.head(
223                f"https://example.com/avatar/{self.admin.username}",
224                status_code=302,
225                headers={"Location": "https://cdn.example.com/final-avatar.png"},
226            )
227            mocker.head(
228                "https://cdn.example.com/final-avatar.png",
229                headers={"Content-Type": "image/png"},
230            )
231            response = self.client.get(reverse("authentik_api:user-me"))
232        self.assertEqual(response.status_code, 200)
233        body = loads(response.content.decode())
234        # Should return the original URL (not the redirect destination)
235        self.assertEqual(
236            body["user"]["avatar"], f"https://example.com/avatar/{self.admin.username}"
237        )

Test custom avatar URL follows redirects

def test_avatars_hostname_availability_cache(self):
239    def test_avatars_hostname_availability_cache(self):
240        """Test that hostname availability is cached when domain fails"""
241        from requests.exceptions import Timeout
242
243        cache.clear()
244        self.set_avatar_mode("https://failing.example.com/avatar/%(username)s,initials")
245        self.client.force_login(self.admin)
246
247        with Mocker() as mocker:
248            # First request times out
249            mocker.head(
250                f"https://failing.example.com/avatar/{self.admin.username}",
251                exc=Timeout("Connection timeout"),
252            )
253            response = self.client.get(reverse("authentik_api:user-me"))
254
255        self.assertEqual(response.status_code, 200)
256        body = loads(response.content.decode())
257        # Should fallback to initials
258        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
259
260        # Verify hostname is marked as unavailable
261        cache_key_hostname = "goauthentik.io/lib/avatars/failing.example.com/available"
262        self.assertFalse(cache.get(cache_key_hostname, True))
263
264        # Second request should not even try to fetch (hostname cached as unavailable)
265        with Mocker() as mocker:
266            # This should NOT be called due to hostname cache
267            mocker.head(
268                f"https://failing.example.com/avatar/{self.admin.username}",
269                headers={"Content-Type": "image/png"},
270            )
271            response = self.client.get(reverse("authentik_api:user-me"))
272
273        self.assertEqual(response.status_code, 200)
274        body = loads(response.content.decode())
275        # Should still fallback to initials without making a request
276        self.assertIn("data:image/svg+xml;base64,", body["user"]["avatar"])
277        # Verify no request was made (request_history should be empty)
278        self.assertEqual(len(mocker.request_history), 0)

Test that hostname availability is cached when domain fails

def test_avatars_gravatar_uses_url_validation(self):
280    def test_avatars_gravatar_uses_url_validation(self):
281        """Test that Gravatar now uses avatar_mode_url validation (regression test)"""
282        cache.clear()
283        self.set_avatar_mode("gravatar")
284        self.admin.email = "test@example.com"
285        self.admin.save()
286        self.client.force_login(self.admin)
287
288        with Mocker() as mocker:
289            # Mock Gravatar to return non-image content
290            from hashlib import sha256
291
292            mail_hash = sha256(self.admin.email.lower().encode("utf-8")).hexdigest()
293            gravatar_url = (
294                f"https://www.gravatar.com/avatar/{mail_hash}?size=158&rating=g&default=404"
295            )
296
297            mocker.head(
298                gravatar_url,
299                headers={"Content-Type": "text/html"},
300            )
301            response = self.client.get(reverse("authentik_api:user-me"))
302
303        self.assertEqual(response.status_code, 200)
304        body = loads(response.content.decode())
305        # Should fallback to default avatar since Content-Type is not image/*
306        self.assertEqual(body["user"]["avatar"], "/static/dist/assets/images/user_default.png")

Test that Gravatar now uses avatar_mode_url validation (regression test)