authentik.core.tests.test_applications_api

Test Applications API

  1"""Test Applications API"""
  2
  3from json import loads
  4from unittest.mock import patch
  5
  6from django.db import connection
  7from django.test.utils import CaptureQueriesContext
  8from django.urls import reverse
  9from rest_framework.response import Response
 10from rest_framework.test import APITestCase
 11
 12from authentik.admin.files.manager import get_file_manager
 13from authentik.admin.files.usage import FileUsage
 14from authentik.core.models import Application, PropertyMapping
 15from authentik.core.tests.utils import (
 16    create_test_admin_user,
 17    create_test_flow,
 18    create_test_user,
 19)
 20from authentik.flows.signals import delete_cache_prefix
 21from authentik.lib.generators import generate_id
 22from authentik.policies.dummy.models import DummyPolicy
 23from authentik.policies.models import PolicyBinding
 24from authentik.policies.types import CACHE_PREFIX
 25from authentik.providers.ldap.models import LDAPProvider
 26from authentik.providers.oauth2.models import OAuth2Provider, RedirectURI, RedirectURIMatchingMode
 27from authentik.providers.proxy.models import ProxyProvider
 28from authentik.providers.saml.models import SAMLProvider
 29from authentik.providers.scim.models import SCIMProvider
 30
 31
 32class TestApplicationsAPI(APITestCase):
 33    """Test applications API"""
 34
 35    def setUp(self) -> None:
 36        self.user = create_test_admin_user()
 37        self.provider = OAuth2Provider.objects.create(
 38            name="test",
 39            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://some-other-domain")],
 40            authorization_flow=create_test_flow(),
 41        )
 42        self.allowed: Application = Application.objects.create(
 43            name="allowed",
 44            slug="allowed",
 45            meta_launch_url="https://goauthentik.io/%(username)s",
 46            open_in_new_tab=True,
 47            provider=self.provider,
 48        )
 49        self.denied = Application.objects.create(name="denied", slug="denied")
 50        PolicyBinding.objects.create(
 51            target=self.denied,
 52            policy=DummyPolicy.objects.create(name="deny", result=False, wait_min=1, wait_max=2),
 53            order=0,
 54        )
 55
 56    def test_formatted_launch_url(self):
 57        """Test formatted launch URL"""
 58        self.client.force_login(self.user)
 59        self.assertEqual(
 60            self.client.patch(
 61                reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug}),
 62                {"meta_launch_url": "https://%(username)s-test.test.goauthentik.io/%(username)s"},
 63            ).status_code,
 64            200,
 65        )
 66        self.allowed.refresh_from_db()
 67        self.assertEqual(
 68            self.allowed.get_launch_url(self.user),
 69            f"https://{self.user.username}-test.test.goauthentik.io/{self.user.username}",
 70        )
 71
 72    def test_relative_launch_url(self):
 73        """Test launch URL as a path relative to the current host"""
 74        self.client.force_login(self.user)
 75        url = reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug})
 76        for launch_url in ["/app/", "/app/%(username)s?a=b#c"]:
 77            with self.subTest(launch_url=launch_url):
 78                response = self.client.patch(url, {"meta_launch_url": launch_url})
 79                self.assertEqual(response.status_code, 200, response.content)
 80        self.allowed.refresh_from_db()
 81        self.assertEqual(self.allowed.get_launch_url(self.user), f"/app/{self.user.username}?a=b#c")
 82        for launch_url in [
 83            "//example.com/app/",
 84            "/\\example.com/app/",
 85            "/app /",
 86            "app/",
 87            "javascript:alert(1)",
 88        ]:
 89            with self.subTest(launch_url=launch_url):
 90                response = self.client.patch(url, {"meta_launch_url": launch_url})
 91                self.assertEqual(response.status_code, 400, response.content)
 92
 93    def test_formatted_launch_url_percent_encoding(self):
 94        """Only placeholders and `%%` are formatted, percent-encoding is kept as is rather than
 95        being filled with the whole user"""
 96        self.allowed.meta_launch_url = "https://goauthentik.io/%(username)s/Joe%27s?q=a%20b%%2F%"
 97        self.assertEqual(
 98            self.allowed.get_launch_url(self.user),
 99            f"https://goauthentik.io/{self.user.username}/Joe%27s?q=a%20b%2F%",
100        )
101        self.allowed.meta_launch_url = "https://goauthentik.io/Joe%27s"
102        self.assertEqual(self.allowed.get_launch_url(self.user), "https://goauthentik.io/Joe%27s")
103
104    def test_check_access(self):
105        """Test check_access operation"""
106        self.client.force_login(self.user)
107        response = self.client.get(
108            reverse(
109                "authentik_api:application-check-access",
110                kwargs={"slug": self.allowed.slug},
111            )
112        )
113        self.assertEqual(response.status_code, 200)
114        body = loads(response.content.decode())
115        self.assertEqual(body["passing"], True)
116        self.assertEqual(body["messages"], [])
117        self.assertEqual(len(body["log_messages"]), 0)
118        response = self.client.get(
119            reverse(
120                "authentik_api:application-check-access",
121                kwargs={"slug": self.denied.slug},
122            )
123        )
124        self.assertEqual(response.status_code, 200)
125        body = loads(response.content.decode())
126        self.assertEqual(body["passing"], False)
127        self.assertEqual(body["messages"], ["dummy"])
128
129    def test_list_accessible(self):
130        """Test listing applications the user passes policies for"""
131        self.client.force_login(self.user)
132        response = self.client.get(reverse("authentik_api:application-accessible"))
133        self.assertJSONEqual(
134            response.content.decode(),
135            {
136                "autocomplete": {},
137                "pagination": {
138                    "next": 0,
139                    "previous": 0,
140                    "count": 2,
141                    "current": 1,
142                    "total_pages": 1,
143                    "start_index": 1,
144                    "end_index": 2,
145                },
146                "results": [
147                    {
148                        "pk": str(self.allowed.pk),
149                        "name": "allowed",
150                        "slug": "allowed",
151                        "pbm_uuid": str(self.allowed.pbm_uuid),
152                        "group": "",
153                        "provider": self.provider.pk,
154                        "provider_obj": {
155                            "assigned_application_name": "allowed",
156                            "assigned_application_slug": "allowed",
157                            "assigned_backchannel_application_name": None,
158                            "assigned_backchannel_application_slug": None,
159                            "authentication_flow": None,
160                            "invalidation_flow": None,
161                            "authorization_flow": str(self.provider.authorization_flow.pk),
162                            "component": "ak-provider-oauth2-form",
163                            "meta_model_name": "authentik_providers_oauth2.oauth2provider",
164                            "name": self.provider.name,
165                            "pk": self.provider.pk,
166                            "property_mappings": [],
167                            "verbose_name": "OAuth2/OpenID Provider",
168                            "verbose_name_plural": "OAuth2/OpenID Providers",
169                        },
170                        "backchannel_providers": [],
171                        "backchannel_providers_obj": [],
172                        "launch_url": f"https://goauthentik.io/{self.user.username}",
173                        "meta_launch_url": "https://goauthentik.io/%(username)s",
174                        "open_in_new_tab": True,
175                        "meta_icon": "",
176                        "meta_icon_url": None,
177                        "meta_icon_themed_urls": None,
178                        "meta_description": "",
179                        "meta_hide": False,
180                        "meta_publisher": "",
181                        "policy_engine_mode": "any",
182                    },
183                ],
184            },
185        )
186
187    def test_list_rbac(self):
188        """Test listing applications the user has RBAC permissions for"""
189        self.client.force_login(self.user)
190        response = self.client.get(reverse("authentik_api:application-list"))
191        self.assertJSONEqual(
192            response.content.decode(),
193            {
194                "autocomplete": {},
195                "pagination": {
196                    "next": 0,
197                    "previous": 0,
198                    "count": 2,
199                    "current": 1,
200                    "total_pages": 1,
201                    "start_index": 1,
202                    "end_index": 2,
203                },
204                "results": [
205                    {
206                        "pk": str(self.allowed.pk),
207                        "name": "allowed",
208                        "slug": "allowed",
209                        "group": "",
210                        "pbm_uuid": str(self.allowed.pbm_uuid),
211                        "provider": self.provider.pk,
212                        "provider_obj": {
213                            "assigned_application_name": "allowed",
214                            "assigned_application_slug": "allowed",
215                            "assigned_backchannel_application_name": None,
216                            "assigned_backchannel_application_slug": None,
217                            "authentication_flow": None,
218                            "invalidation_flow": None,
219                            "authorization_flow": str(self.provider.authorization_flow.pk),
220                            "component": "ak-provider-oauth2-form",
221                            "meta_model_name": "authentik_providers_oauth2.oauth2provider",
222                            "name": self.provider.name,
223                            "pk": self.provider.pk,
224                            "property_mappings": [],
225                            "verbose_name": "OAuth2/OpenID Provider",
226                            "verbose_name_plural": "OAuth2/OpenID Providers",
227                        },
228                        "backchannel_providers": [],
229                        "backchannel_providers_obj": [],
230                        "launch_url": f"https://goauthentik.io/{self.user.username}",
231                        "meta_launch_url": "https://goauthentik.io/%(username)s",
232                        "open_in_new_tab": True,
233                        "meta_icon": "",
234                        "meta_icon_url": None,
235                        "meta_icon_themed_urls": None,
236                        "meta_description": "",
237                        "meta_hide": False,
238                        "meta_publisher": "",
239                        "policy_engine_mode": "any",
240                    },
241                    {
242                        "launch_url": None,
243                        "meta_description": "",
244                        "meta_hide": False,
245                        "meta_icon": "",
246                        "meta_icon_url": None,
247                        "meta_icon_themed_urls": None,
248                        "meta_launch_url": "",
249                        "open_in_new_tab": False,
250                        "meta_publisher": "",
251                        "group": "",
252                        "name": "denied",
253                        "pbm_uuid": str(self.denied.pbm_uuid),
254                        "pk": str(self.denied.pk),
255                        "policy_engine_mode": "any",
256                        "provider": None,
257                        "provider_obj": None,
258                        "backchannel_providers": [],
259                        "backchannel_providers_obj": [],
260                        "slug": "denied",
261                    },
262                ],
263            },
264        )
265
266    def test_list_plain_launch_url(self):
267        """A launch URL without placeholders is not formatted, so listing it does not serialize
268        the requesting user, whose avatar lookup can make an HTTP request"""
269        self.allowed.meta_launch_url = "https://goauthentik.io"
270        self.allowed.save()
271        self.client.force_login(self.user)
272        with patch("authentik.core.api.users.get_avatar") as get_avatar:
273            response = self.client.get(reverse("authentik_api:application-list"))
274        self.assertEqual(response.status_code, 200)
275        self.assertEqual(response.json()["results"][0]["launch_url"], "https://goauthentik.io")
276        get_avatar.assert_not_called()
277
278    def test_update_provider(self):
279        """Changing an application's provider returns the new provider"""
280        self.client.force_login(self.user)
281        url = reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug})
282        provider = SAMLProvider.objects.create(name=generate_id())
283        response = self.client.patch(url, {"provider": provider.pk})
284        self.assertEqual(response.status_code, 200)
285        self.assertEqual(response.json()["provider_obj"]["pk"], provider.pk)
286        self.assertEqual(response.json()["provider_obj"]["component"], "ak-provider-saml-form")
287        response = self.client.patch(url, {"provider": None}, format="json")
288        self.assertEqual(response.status_code, 200)
289        self.assertIsNone(response.json()["provider_obj"])
290
291    def test_with_provider_combined(self):
292        """with_provider() can be called again, and after lookups through the provider"""
293        provider = SAMLProvider.objects.create(name=generate_id())
294        app = Application.objects.create(name=generate_id(), slug=generate_id(), provider=provider)
295        app = (
296            Application.objects.prefetch_related("provider__property_mappings")
297            .with_provider()
298            .with_provider()
299            .get(pk=app.pk)
300        )
301        with self.assertNumQueries(0):
302            self.assertEqual(app.get_provider(), provider)
303            self.assertEqual(list(app.get_provider().property_mappings.all()), [])
304
305    def test_list_rbac_ignores_policies(self):
306        """RBAC access and policy access are separate: the list only checks
307        permissions, @accessible only checks policies"""
308        user = create_test_user()
309        user.assign_perms_to_managed_role("authentik_core.view_application", self.denied)
310        self.client.force_login(user)
311        response = self.client.get(reverse("authentik_api:application-list"))
312        self.assertEqual(response.status_code, 200)
313        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.denied.slug])
314        response = self.client.get(reverse("authentik_api:application-accessible"))
315        self.assertEqual(response.status_code, 200)
316        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.allowed.slug])
317
318    def test_list_accessible_for_user(self):
319        """for_user requires the view_user_applications permission on that user"""
320        user = create_test_user()
321        PolicyBinding.objects.create(target=self.allowed, user=user, order=0)
322        url = reverse("authentik_api:application-accessible") + f"?for_user={user.pk}"
323        self.client.force_login(create_test_user())
324        response = self.client.get(url)
325        self.assertEqual(response.status_code, 400)
326        self.client.force_login(self.user)
327        response = self.client.get(url)
328        self.assertEqual(response.status_code, 200)
329        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.allowed.slug])
330        self.assertEqual(
331            response.json()["results"][0]["launch_url"], f"https://goauthentik.io/{user.username}"
332        )
333
334    def test_get_provider(self):
335        """Ensure that proxy providers (at the time of writing that is the only provider
336        that inherits from another proxy type (OAuth) instead of inheriting from the root
337        provider class) is correctly looked up and selected from the database"""
338        slug = generate_id()
339        provider = ProxyProvider.objects.create(name=generate_id())
340        Application.objects.create(
341            name=generate_id(),
342            slug=slug,
343            provider=provider,
344        )
345        self.assertEqual(Application.objects.get(slug=slug).get_provider(), provider)
346        self.assertEqual(
347            Application.objects.with_provider().get(slug=slug).get_provider(), provider
348        )
349
350        slug = generate_id()
351        provider = SAMLProvider.objects.create(name=generate_id())
352        Application.objects.create(
353            name=generate_id(),
354            slug=slug,
355            provider=provider,
356        )
357        self.assertEqual(Application.objects.get(slug=slug).get_provider(), provider)
358        self.assertEqual(
359            Application.objects.with_provider().get(slug=slug).get_provider(), provider
360        )
361
362    def test_create_application_with_reserved_slug(self):
363        """Test creating an application with a reserved slug"""
364        self.client.force_login(self.user)
365        response = self.client.post(
366            reverse("authentik_api:application-list"),
367            {
368                "name": "Test Application",
369                "slug": Application.reserved_slugs[0],
370            },
371        )
372        self.assertEqual(response.status_code, 400)
373        self.assertIn("slug", response.data)
374        self.assertIn("reserved", response.data["slug"][0])
375
376    def test_update_application_with_reserved_slug(self):
377        """Test updating an application to use a reserved slug"""
378        self.client.force_login(self.user)
379        app = Application.objects.create(
380            name="Test Application",
381            slug="valid-slug",
382        )
383
384        response = self.client.patch(
385            reverse("authentik_api:application-detail", kwargs={"slug": app.slug}),
386            {
387                "slug": Application.reserved_slugs[0],
388            },
389        )
390        self.assertEqual(response.status_code, 400)
391        self.assertIn("slug", response.data)
392        self.assertIn("reserved", response.data["slug"][0])
393
394    def _create_applications(self, count: int, allowed_user, denied_user) -> list[Application]:
395        """Applications with each provider type and a backchannel provider, every other one
396        bound to `allowed_user` and the rest to `denied_user`"""
397        flow = create_test_flow()
398        mapping = PropertyMapping.objects.create(name=generate_id(), expression="return {}")
399        apps = []
400        for index in range(count):
401            model = (OAuth2Provider, SAMLProvider, ProxyProvider, LDAPProvider)[index % 4]
402            provider = model.objects.create(name=generate_id(), authorization_flow=flow)
403            provider.property_mappings.add(mapping)
404            app = Application.objects.create(
405                name=generate_id(),
406                slug=generate_id(),
407                provider=provider,
408                meta_launch_url="https://goauthentik.io",
409                meta_icon=f"{generate_id()}{'-%(theme)s' if index % 3 == 0 else ''}.svg",
410            )
411            backchannel = SCIMProvider.objects.create(
412                name=generate_id(), url="https://goauthentik.io", token=generate_id()
413            )
414            backchannel.property_mappings.add(mapping)
415            app.backchannel_providers.add(backchannel)
416            PolicyBinding.objects.create(
417                target=app, user=allowed_user if index % 2 else denied_user, order=0
418            )
419            apps.append(app)
420        return apps
421
422    def _get_queries(self, url: str, cached=False) -> tuple[Response, CaptureQueriesContext]:
423        """Request `url` twice and capture the queries of the second request, as the first one
424        after a change also loads the session and brand. Unless `cached`, both requests evaluate
425        policies; with it, the second request reads the user's application list that the first
426        one cached."""
427        delete_cache_prefix(f"{CACHE_PREFIX}*")
428        self.assertEqual(self.client.get(url).status_code, 200)
429        if not cached:
430            delete_cache_prefix(f"{CACHE_PREFIX}*")
431        with CaptureQueriesContext(connection) as captured:
432            response = self.client.get(url)
433        self.assertEqual(response.status_code, 200)
434        return response, captured
435
436    def _assert_serialized(self, results: list[dict], apps: list[Application]):
437        """`results` are exactly `apps`. Icons have the URLs the file manager gives them, and
438        providers are serialized as their concrete type, with their applications"""
439        by_slug = {app["slug"]: app for app in results}
440        self.assertCountEqual(by_slug, [app.slug for app in apps])
441        files = get_file_manager(FileUsage.MEDIA)
442        for app in apps:
443            provider = app.provider
444            backchannel = SCIMProvider.objects.get(backchannel_application=app)
445            data = by_slug[app.slug]
446            self.assertEqual(data["meta_icon_url"], files.file_url(app.meta_icon))
447            self.assertEqual(data["meta_icon_themed_urls"], files.themed_urls(app.meta_icon))
448            self.assertEqual(data["provider_obj"]["component"], provider.component)
449            self.assertEqual(data["provider_obj"]["assigned_application_slug"], app.slug)
450            self.assertEqual(
451                data["provider_obj"]["property_mappings"],
452                [str(pk) for pk in provider.property_mappings.values_list("pk", flat=True)],
453            )
454            self.assertEqual(data["backchannel_providers"], [backchannel.pk])
455            self.assertEqual(len(data["backchannel_providers_obj"]), 1)
456            self.assertEqual(
457                data["backchannel_providers_obj"][0]["component"], backchannel.component
458            )
459            self.assertEqual(
460                data["backchannel_providers_obj"][0]["assigned_backchannel_application_slug"],
461                app.slug,
462            )
463            self.assertIsNone(data["backchannel_providers_obj"][0]["assigned_application_slug"])
464            self.assertEqual(
465                data["backchannel_providers_obj"][0]["property_mappings"],
466                [str(pk) for pk in backchannel.property_mappings.values_list("pk", flat=True)],
467            )
468
469    def test_list_queries(self):
470        """Listing applications loads providers in their own queries: joining every provider
471        subclass into the application query made a statement Postgres took over 100ms to plan.
472        The number of queries does not grow with the number of applications."""
473        Application.objects.all().delete()
474        denied_user = create_test_user()
475        apps = self._create_applications(4, self.user, denied_user)
476        self.client.force_login(self.user)
477        url = reverse("authentik_api:application-list")
478        response, small = self._get_queries(url)
479        for query in small.captured_queries:
480            sql = query["sql"]
481            self.assertFalse(
482                'FROM "authentik_core_application"' in sql and "authentik_core_provider" in sql,
483                "The application query joins providers",
484            )
485        self._assert_serialized(response.json()["results"], apps)
486
487        apps += self._create_applications(8, self.user, denied_user)
488        response, large = self._get_queries(url)
489        self._assert_serialized(response.json()["results"], apps)
490        self.assertEqual(len(large), len(small))
491
492    def test_list_accessible_queries(self):
493        """@accessible returns exactly the applications whose policies the user passes, whether
494        it evaluates policies or reads the user's application list from the cache, and the number
495        of queries does not grow with the number of applications."""
496        Application.objects.all().delete()
497        user = create_test_user()
498        allowed = self._create_applications(4, user, self.user)[1::2]
499        self.client.force_login(user)
500        url = reverse("authentik_api:application-accessible") + "?only_with_launch_url=true"
501        small = {}
502        for cached in (False, True):
503            response, small[cached] = self._get_queries(url, cached)
504            self._assert_serialized(response.json()["results"], allowed)
505
506        allowed += self._create_applications(8, user, self.user)[1::2]
507        for cached in (False, True):
508            response, large = self._get_queries(url, cached)
509            self._assert_serialized(response.json()["results"], allowed)
510            self.assertEqual(len(large), len(small[cached]))
class TestApplicationsAPI(rest_framework.test.APITestCase):
 33class TestApplicationsAPI(APITestCase):
 34    """Test applications API"""
 35
 36    def setUp(self) -> None:
 37        self.user = create_test_admin_user()
 38        self.provider = OAuth2Provider.objects.create(
 39            name="test",
 40            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://some-other-domain")],
 41            authorization_flow=create_test_flow(),
 42        )
 43        self.allowed: Application = Application.objects.create(
 44            name="allowed",
 45            slug="allowed",
 46            meta_launch_url="https://goauthentik.io/%(username)s",
 47            open_in_new_tab=True,
 48            provider=self.provider,
 49        )
 50        self.denied = Application.objects.create(name="denied", slug="denied")
 51        PolicyBinding.objects.create(
 52            target=self.denied,
 53            policy=DummyPolicy.objects.create(name="deny", result=False, wait_min=1, wait_max=2),
 54            order=0,
 55        )
 56
 57    def test_formatted_launch_url(self):
 58        """Test formatted launch URL"""
 59        self.client.force_login(self.user)
 60        self.assertEqual(
 61            self.client.patch(
 62                reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug}),
 63                {"meta_launch_url": "https://%(username)s-test.test.goauthentik.io/%(username)s"},
 64            ).status_code,
 65            200,
 66        )
 67        self.allowed.refresh_from_db()
 68        self.assertEqual(
 69            self.allowed.get_launch_url(self.user),
 70            f"https://{self.user.username}-test.test.goauthentik.io/{self.user.username}",
 71        )
 72
 73    def test_relative_launch_url(self):
 74        """Test launch URL as a path relative to the current host"""
 75        self.client.force_login(self.user)
 76        url = reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug})
 77        for launch_url in ["/app/", "/app/%(username)s?a=b#c"]:
 78            with self.subTest(launch_url=launch_url):
 79                response = self.client.patch(url, {"meta_launch_url": launch_url})
 80                self.assertEqual(response.status_code, 200, response.content)
 81        self.allowed.refresh_from_db()
 82        self.assertEqual(self.allowed.get_launch_url(self.user), f"/app/{self.user.username}?a=b#c")
 83        for launch_url in [
 84            "//example.com/app/",
 85            "/\\example.com/app/",
 86            "/app /",
 87            "app/",
 88            "javascript:alert(1)",
 89        ]:
 90            with self.subTest(launch_url=launch_url):
 91                response = self.client.patch(url, {"meta_launch_url": launch_url})
 92                self.assertEqual(response.status_code, 400, response.content)
 93
 94    def test_formatted_launch_url_percent_encoding(self):
 95        """Only placeholders and `%%` are formatted, percent-encoding is kept as is rather than
 96        being filled with the whole user"""
 97        self.allowed.meta_launch_url = "https://goauthentik.io/%(username)s/Joe%27s?q=a%20b%%2F%"
 98        self.assertEqual(
 99            self.allowed.get_launch_url(self.user),
100            f"https://goauthentik.io/{self.user.username}/Joe%27s?q=a%20b%2F%",
101        )
102        self.allowed.meta_launch_url = "https://goauthentik.io/Joe%27s"
103        self.assertEqual(self.allowed.get_launch_url(self.user), "https://goauthentik.io/Joe%27s")
104
105    def test_check_access(self):
106        """Test check_access operation"""
107        self.client.force_login(self.user)
108        response = self.client.get(
109            reverse(
110                "authentik_api:application-check-access",
111                kwargs={"slug": self.allowed.slug},
112            )
113        )
114        self.assertEqual(response.status_code, 200)
115        body = loads(response.content.decode())
116        self.assertEqual(body["passing"], True)
117        self.assertEqual(body["messages"], [])
118        self.assertEqual(len(body["log_messages"]), 0)
119        response = self.client.get(
120            reverse(
121                "authentik_api:application-check-access",
122                kwargs={"slug": self.denied.slug},
123            )
124        )
125        self.assertEqual(response.status_code, 200)
126        body = loads(response.content.decode())
127        self.assertEqual(body["passing"], False)
128        self.assertEqual(body["messages"], ["dummy"])
129
130    def test_list_accessible(self):
131        """Test listing applications the user passes policies for"""
132        self.client.force_login(self.user)
133        response = self.client.get(reverse("authentik_api:application-accessible"))
134        self.assertJSONEqual(
135            response.content.decode(),
136            {
137                "autocomplete": {},
138                "pagination": {
139                    "next": 0,
140                    "previous": 0,
141                    "count": 2,
142                    "current": 1,
143                    "total_pages": 1,
144                    "start_index": 1,
145                    "end_index": 2,
146                },
147                "results": [
148                    {
149                        "pk": str(self.allowed.pk),
150                        "name": "allowed",
151                        "slug": "allowed",
152                        "pbm_uuid": str(self.allowed.pbm_uuid),
153                        "group": "",
154                        "provider": self.provider.pk,
155                        "provider_obj": {
156                            "assigned_application_name": "allowed",
157                            "assigned_application_slug": "allowed",
158                            "assigned_backchannel_application_name": None,
159                            "assigned_backchannel_application_slug": None,
160                            "authentication_flow": None,
161                            "invalidation_flow": None,
162                            "authorization_flow": str(self.provider.authorization_flow.pk),
163                            "component": "ak-provider-oauth2-form",
164                            "meta_model_name": "authentik_providers_oauth2.oauth2provider",
165                            "name": self.provider.name,
166                            "pk": self.provider.pk,
167                            "property_mappings": [],
168                            "verbose_name": "OAuth2/OpenID Provider",
169                            "verbose_name_plural": "OAuth2/OpenID Providers",
170                        },
171                        "backchannel_providers": [],
172                        "backchannel_providers_obj": [],
173                        "launch_url": f"https://goauthentik.io/{self.user.username}",
174                        "meta_launch_url": "https://goauthentik.io/%(username)s",
175                        "open_in_new_tab": True,
176                        "meta_icon": "",
177                        "meta_icon_url": None,
178                        "meta_icon_themed_urls": None,
179                        "meta_description": "",
180                        "meta_hide": False,
181                        "meta_publisher": "",
182                        "policy_engine_mode": "any",
183                    },
184                ],
185            },
186        )
187
188    def test_list_rbac(self):
189        """Test listing applications the user has RBAC permissions for"""
190        self.client.force_login(self.user)
191        response = self.client.get(reverse("authentik_api:application-list"))
192        self.assertJSONEqual(
193            response.content.decode(),
194            {
195                "autocomplete": {},
196                "pagination": {
197                    "next": 0,
198                    "previous": 0,
199                    "count": 2,
200                    "current": 1,
201                    "total_pages": 1,
202                    "start_index": 1,
203                    "end_index": 2,
204                },
205                "results": [
206                    {
207                        "pk": str(self.allowed.pk),
208                        "name": "allowed",
209                        "slug": "allowed",
210                        "group": "",
211                        "pbm_uuid": str(self.allowed.pbm_uuid),
212                        "provider": self.provider.pk,
213                        "provider_obj": {
214                            "assigned_application_name": "allowed",
215                            "assigned_application_slug": "allowed",
216                            "assigned_backchannel_application_name": None,
217                            "assigned_backchannel_application_slug": None,
218                            "authentication_flow": None,
219                            "invalidation_flow": None,
220                            "authorization_flow": str(self.provider.authorization_flow.pk),
221                            "component": "ak-provider-oauth2-form",
222                            "meta_model_name": "authentik_providers_oauth2.oauth2provider",
223                            "name": self.provider.name,
224                            "pk": self.provider.pk,
225                            "property_mappings": [],
226                            "verbose_name": "OAuth2/OpenID Provider",
227                            "verbose_name_plural": "OAuth2/OpenID Providers",
228                        },
229                        "backchannel_providers": [],
230                        "backchannel_providers_obj": [],
231                        "launch_url": f"https://goauthentik.io/{self.user.username}",
232                        "meta_launch_url": "https://goauthentik.io/%(username)s",
233                        "open_in_new_tab": True,
234                        "meta_icon": "",
235                        "meta_icon_url": None,
236                        "meta_icon_themed_urls": None,
237                        "meta_description": "",
238                        "meta_hide": False,
239                        "meta_publisher": "",
240                        "policy_engine_mode": "any",
241                    },
242                    {
243                        "launch_url": None,
244                        "meta_description": "",
245                        "meta_hide": False,
246                        "meta_icon": "",
247                        "meta_icon_url": None,
248                        "meta_icon_themed_urls": None,
249                        "meta_launch_url": "",
250                        "open_in_new_tab": False,
251                        "meta_publisher": "",
252                        "group": "",
253                        "name": "denied",
254                        "pbm_uuid": str(self.denied.pbm_uuid),
255                        "pk": str(self.denied.pk),
256                        "policy_engine_mode": "any",
257                        "provider": None,
258                        "provider_obj": None,
259                        "backchannel_providers": [],
260                        "backchannel_providers_obj": [],
261                        "slug": "denied",
262                    },
263                ],
264            },
265        )
266
267    def test_list_plain_launch_url(self):
268        """A launch URL without placeholders is not formatted, so listing it does not serialize
269        the requesting user, whose avatar lookup can make an HTTP request"""
270        self.allowed.meta_launch_url = "https://goauthentik.io"
271        self.allowed.save()
272        self.client.force_login(self.user)
273        with patch("authentik.core.api.users.get_avatar") as get_avatar:
274            response = self.client.get(reverse("authentik_api:application-list"))
275        self.assertEqual(response.status_code, 200)
276        self.assertEqual(response.json()["results"][0]["launch_url"], "https://goauthentik.io")
277        get_avatar.assert_not_called()
278
279    def test_update_provider(self):
280        """Changing an application's provider returns the new provider"""
281        self.client.force_login(self.user)
282        url = reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug})
283        provider = SAMLProvider.objects.create(name=generate_id())
284        response = self.client.patch(url, {"provider": provider.pk})
285        self.assertEqual(response.status_code, 200)
286        self.assertEqual(response.json()["provider_obj"]["pk"], provider.pk)
287        self.assertEqual(response.json()["provider_obj"]["component"], "ak-provider-saml-form")
288        response = self.client.patch(url, {"provider": None}, format="json")
289        self.assertEqual(response.status_code, 200)
290        self.assertIsNone(response.json()["provider_obj"])
291
292    def test_with_provider_combined(self):
293        """with_provider() can be called again, and after lookups through the provider"""
294        provider = SAMLProvider.objects.create(name=generate_id())
295        app = Application.objects.create(name=generate_id(), slug=generate_id(), provider=provider)
296        app = (
297            Application.objects.prefetch_related("provider__property_mappings")
298            .with_provider()
299            .with_provider()
300            .get(pk=app.pk)
301        )
302        with self.assertNumQueries(0):
303            self.assertEqual(app.get_provider(), provider)
304            self.assertEqual(list(app.get_provider().property_mappings.all()), [])
305
306    def test_list_rbac_ignores_policies(self):
307        """RBAC access and policy access are separate: the list only checks
308        permissions, @accessible only checks policies"""
309        user = create_test_user()
310        user.assign_perms_to_managed_role("authentik_core.view_application", self.denied)
311        self.client.force_login(user)
312        response = self.client.get(reverse("authentik_api:application-list"))
313        self.assertEqual(response.status_code, 200)
314        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.denied.slug])
315        response = self.client.get(reverse("authentik_api:application-accessible"))
316        self.assertEqual(response.status_code, 200)
317        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.allowed.slug])
318
319    def test_list_accessible_for_user(self):
320        """for_user requires the view_user_applications permission on that user"""
321        user = create_test_user()
322        PolicyBinding.objects.create(target=self.allowed, user=user, order=0)
323        url = reverse("authentik_api:application-accessible") + f"?for_user={user.pk}"
324        self.client.force_login(create_test_user())
325        response = self.client.get(url)
326        self.assertEqual(response.status_code, 400)
327        self.client.force_login(self.user)
328        response = self.client.get(url)
329        self.assertEqual(response.status_code, 200)
330        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.allowed.slug])
331        self.assertEqual(
332            response.json()["results"][0]["launch_url"], f"https://goauthentik.io/{user.username}"
333        )
334
335    def test_get_provider(self):
336        """Ensure that proxy providers (at the time of writing that is the only provider
337        that inherits from another proxy type (OAuth) instead of inheriting from the root
338        provider class) is correctly looked up and selected from the database"""
339        slug = generate_id()
340        provider = ProxyProvider.objects.create(name=generate_id())
341        Application.objects.create(
342            name=generate_id(),
343            slug=slug,
344            provider=provider,
345        )
346        self.assertEqual(Application.objects.get(slug=slug).get_provider(), provider)
347        self.assertEqual(
348            Application.objects.with_provider().get(slug=slug).get_provider(), provider
349        )
350
351        slug = generate_id()
352        provider = SAMLProvider.objects.create(name=generate_id())
353        Application.objects.create(
354            name=generate_id(),
355            slug=slug,
356            provider=provider,
357        )
358        self.assertEqual(Application.objects.get(slug=slug).get_provider(), provider)
359        self.assertEqual(
360            Application.objects.with_provider().get(slug=slug).get_provider(), provider
361        )
362
363    def test_create_application_with_reserved_slug(self):
364        """Test creating an application with a reserved slug"""
365        self.client.force_login(self.user)
366        response = self.client.post(
367            reverse("authentik_api:application-list"),
368            {
369                "name": "Test Application",
370                "slug": Application.reserved_slugs[0],
371            },
372        )
373        self.assertEqual(response.status_code, 400)
374        self.assertIn("slug", response.data)
375        self.assertIn("reserved", response.data["slug"][0])
376
377    def test_update_application_with_reserved_slug(self):
378        """Test updating an application to use a reserved slug"""
379        self.client.force_login(self.user)
380        app = Application.objects.create(
381            name="Test Application",
382            slug="valid-slug",
383        )
384
385        response = self.client.patch(
386            reverse("authentik_api:application-detail", kwargs={"slug": app.slug}),
387            {
388                "slug": Application.reserved_slugs[0],
389            },
390        )
391        self.assertEqual(response.status_code, 400)
392        self.assertIn("slug", response.data)
393        self.assertIn("reserved", response.data["slug"][0])
394
395    def _create_applications(self, count: int, allowed_user, denied_user) -> list[Application]:
396        """Applications with each provider type and a backchannel provider, every other one
397        bound to `allowed_user` and the rest to `denied_user`"""
398        flow = create_test_flow()
399        mapping = PropertyMapping.objects.create(name=generate_id(), expression="return {}")
400        apps = []
401        for index in range(count):
402            model = (OAuth2Provider, SAMLProvider, ProxyProvider, LDAPProvider)[index % 4]
403            provider = model.objects.create(name=generate_id(), authorization_flow=flow)
404            provider.property_mappings.add(mapping)
405            app = Application.objects.create(
406                name=generate_id(),
407                slug=generate_id(),
408                provider=provider,
409                meta_launch_url="https://goauthentik.io",
410                meta_icon=f"{generate_id()}{'-%(theme)s' if index % 3 == 0 else ''}.svg",
411            )
412            backchannel = SCIMProvider.objects.create(
413                name=generate_id(), url="https://goauthentik.io", token=generate_id()
414            )
415            backchannel.property_mappings.add(mapping)
416            app.backchannel_providers.add(backchannel)
417            PolicyBinding.objects.create(
418                target=app, user=allowed_user if index % 2 else denied_user, order=0
419            )
420            apps.append(app)
421        return apps
422
423    def _get_queries(self, url: str, cached=False) -> tuple[Response, CaptureQueriesContext]:
424        """Request `url` twice and capture the queries of the second request, as the first one
425        after a change also loads the session and brand. Unless `cached`, both requests evaluate
426        policies; with it, the second request reads the user's application list that the first
427        one cached."""
428        delete_cache_prefix(f"{CACHE_PREFIX}*")
429        self.assertEqual(self.client.get(url).status_code, 200)
430        if not cached:
431            delete_cache_prefix(f"{CACHE_PREFIX}*")
432        with CaptureQueriesContext(connection) as captured:
433            response = self.client.get(url)
434        self.assertEqual(response.status_code, 200)
435        return response, captured
436
437    def _assert_serialized(self, results: list[dict], apps: list[Application]):
438        """`results` are exactly `apps`. Icons have the URLs the file manager gives them, and
439        providers are serialized as their concrete type, with their applications"""
440        by_slug = {app["slug"]: app for app in results}
441        self.assertCountEqual(by_slug, [app.slug for app in apps])
442        files = get_file_manager(FileUsage.MEDIA)
443        for app in apps:
444            provider = app.provider
445            backchannel = SCIMProvider.objects.get(backchannel_application=app)
446            data = by_slug[app.slug]
447            self.assertEqual(data["meta_icon_url"], files.file_url(app.meta_icon))
448            self.assertEqual(data["meta_icon_themed_urls"], files.themed_urls(app.meta_icon))
449            self.assertEqual(data["provider_obj"]["component"], provider.component)
450            self.assertEqual(data["provider_obj"]["assigned_application_slug"], app.slug)
451            self.assertEqual(
452                data["provider_obj"]["property_mappings"],
453                [str(pk) for pk in provider.property_mappings.values_list("pk", flat=True)],
454            )
455            self.assertEqual(data["backchannel_providers"], [backchannel.pk])
456            self.assertEqual(len(data["backchannel_providers_obj"]), 1)
457            self.assertEqual(
458                data["backchannel_providers_obj"][0]["component"], backchannel.component
459            )
460            self.assertEqual(
461                data["backchannel_providers_obj"][0]["assigned_backchannel_application_slug"],
462                app.slug,
463            )
464            self.assertIsNone(data["backchannel_providers_obj"][0]["assigned_application_slug"])
465            self.assertEqual(
466                data["backchannel_providers_obj"][0]["property_mappings"],
467                [str(pk) for pk in backchannel.property_mappings.values_list("pk", flat=True)],
468            )
469
470    def test_list_queries(self):
471        """Listing applications loads providers in their own queries: joining every provider
472        subclass into the application query made a statement Postgres took over 100ms to plan.
473        The number of queries does not grow with the number of applications."""
474        Application.objects.all().delete()
475        denied_user = create_test_user()
476        apps = self._create_applications(4, self.user, denied_user)
477        self.client.force_login(self.user)
478        url = reverse("authentik_api:application-list")
479        response, small = self._get_queries(url)
480        for query in small.captured_queries:
481            sql = query["sql"]
482            self.assertFalse(
483                'FROM "authentik_core_application"' in sql and "authentik_core_provider" in sql,
484                "The application query joins providers",
485            )
486        self._assert_serialized(response.json()["results"], apps)
487
488        apps += self._create_applications(8, self.user, denied_user)
489        response, large = self._get_queries(url)
490        self._assert_serialized(response.json()["results"], apps)
491        self.assertEqual(len(large), len(small))
492
493    def test_list_accessible_queries(self):
494        """@accessible returns exactly the applications whose policies the user passes, whether
495        it evaluates policies or reads the user's application list from the cache, and the number
496        of queries does not grow with the number of applications."""
497        Application.objects.all().delete()
498        user = create_test_user()
499        allowed = self._create_applications(4, user, self.user)[1::2]
500        self.client.force_login(user)
501        url = reverse("authentik_api:application-accessible") + "?only_with_launch_url=true"
502        small = {}
503        for cached in (False, True):
504            response, small[cached] = self._get_queries(url, cached)
505            self._assert_serialized(response.json()["results"], allowed)
506
507        allowed += self._create_applications(8, user, self.user)[1::2]
508        for cached in (False, True):
509            response, large = self._get_queries(url, cached)
510            self._assert_serialized(response.json()["results"], allowed)
511            self.assertEqual(len(large), len(small[cached]))

Test applications API

def setUp(self) -> None:
36    def setUp(self) -> None:
37        self.user = create_test_admin_user()
38        self.provider = OAuth2Provider.objects.create(
39            name="test",
40            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://some-other-domain")],
41            authorization_flow=create_test_flow(),
42        )
43        self.allowed: Application = Application.objects.create(
44            name="allowed",
45            slug="allowed",
46            meta_launch_url="https://goauthentik.io/%(username)s",
47            open_in_new_tab=True,
48            provider=self.provider,
49        )
50        self.denied = Application.objects.create(name="denied", slug="denied")
51        PolicyBinding.objects.create(
52            target=self.denied,
53            policy=DummyPolicy.objects.create(name="deny", result=False, wait_min=1, wait_max=2),
54            order=0,
55        )

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

def test_formatted_launch_url(self):
57    def test_formatted_launch_url(self):
58        """Test formatted launch URL"""
59        self.client.force_login(self.user)
60        self.assertEqual(
61            self.client.patch(
62                reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug}),
63                {"meta_launch_url": "https://%(username)s-test.test.goauthentik.io/%(username)s"},
64            ).status_code,
65            200,
66        )
67        self.allowed.refresh_from_db()
68        self.assertEqual(
69            self.allowed.get_launch_url(self.user),
70            f"https://{self.user.username}-test.test.goauthentik.io/{self.user.username}",
71        )

Test formatted launch URL

def test_relative_launch_url(self):
73    def test_relative_launch_url(self):
74        """Test launch URL as a path relative to the current host"""
75        self.client.force_login(self.user)
76        url = reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug})
77        for launch_url in ["/app/", "/app/%(username)s?a=b#c"]:
78            with self.subTest(launch_url=launch_url):
79                response = self.client.patch(url, {"meta_launch_url": launch_url})
80                self.assertEqual(response.status_code, 200, response.content)
81        self.allowed.refresh_from_db()
82        self.assertEqual(self.allowed.get_launch_url(self.user), f"/app/{self.user.username}?a=b#c")
83        for launch_url in [
84            "//example.com/app/",
85            "/\\example.com/app/",
86            "/app /",
87            "app/",
88            "javascript:alert(1)",
89        ]:
90            with self.subTest(launch_url=launch_url):
91                response = self.client.patch(url, {"meta_launch_url": launch_url})
92                self.assertEqual(response.status_code, 400, response.content)

Test launch URL as a path relative to the current host

def test_formatted_launch_url_percent_encoding(self):
 94    def test_formatted_launch_url_percent_encoding(self):
 95        """Only placeholders and `%%` are formatted, percent-encoding is kept as is rather than
 96        being filled with the whole user"""
 97        self.allowed.meta_launch_url = "https://goauthentik.io/%(username)s/Joe%27s?q=a%20b%%2F%"
 98        self.assertEqual(
 99            self.allowed.get_launch_url(self.user),
100            f"https://goauthentik.io/{self.user.username}/Joe%27s?q=a%20b%2F%",
101        )
102        self.allowed.meta_launch_url = "https://goauthentik.io/Joe%27s"
103        self.assertEqual(self.allowed.get_launch_url(self.user), "https://goauthentik.io/Joe%27s")

Only placeholders and %% are formatted, percent-encoding is kept as is rather than being filled with the whole user

def test_check_access(self):
105    def test_check_access(self):
106        """Test check_access operation"""
107        self.client.force_login(self.user)
108        response = self.client.get(
109            reverse(
110                "authentik_api:application-check-access",
111                kwargs={"slug": self.allowed.slug},
112            )
113        )
114        self.assertEqual(response.status_code, 200)
115        body = loads(response.content.decode())
116        self.assertEqual(body["passing"], True)
117        self.assertEqual(body["messages"], [])
118        self.assertEqual(len(body["log_messages"]), 0)
119        response = self.client.get(
120            reverse(
121                "authentik_api:application-check-access",
122                kwargs={"slug": self.denied.slug},
123            )
124        )
125        self.assertEqual(response.status_code, 200)
126        body = loads(response.content.decode())
127        self.assertEqual(body["passing"], False)
128        self.assertEqual(body["messages"], ["dummy"])

Test check_access operation

def test_list_accessible(self):
130    def test_list_accessible(self):
131        """Test listing applications the user passes policies for"""
132        self.client.force_login(self.user)
133        response = self.client.get(reverse("authentik_api:application-accessible"))
134        self.assertJSONEqual(
135            response.content.decode(),
136            {
137                "autocomplete": {},
138                "pagination": {
139                    "next": 0,
140                    "previous": 0,
141                    "count": 2,
142                    "current": 1,
143                    "total_pages": 1,
144                    "start_index": 1,
145                    "end_index": 2,
146                },
147                "results": [
148                    {
149                        "pk": str(self.allowed.pk),
150                        "name": "allowed",
151                        "slug": "allowed",
152                        "pbm_uuid": str(self.allowed.pbm_uuid),
153                        "group": "",
154                        "provider": self.provider.pk,
155                        "provider_obj": {
156                            "assigned_application_name": "allowed",
157                            "assigned_application_slug": "allowed",
158                            "assigned_backchannel_application_name": None,
159                            "assigned_backchannel_application_slug": None,
160                            "authentication_flow": None,
161                            "invalidation_flow": None,
162                            "authorization_flow": str(self.provider.authorization_flow.pk),
163                            "component": "ak-provider-oauth2-form",
164                            "meta_model_name": "authentik_providers_oauth2.oauth2provider",
165                            "name": self.provider.name,
166                            "pk": self.provider.pk,
167                            "property_mappings": [],
168                            "verbose_name": "OAuth2/OpenID Provider",
169                            "verbose_name_plural": "OAuth2/OpenID Providers",
170                        },
171                        "backchannel_providers": [],
172                        "backchannel_providers_obj": [],
173                        "launch_url": f"https://goauthentik.io/{self.user.username}",
174                        "meta_launch_url": "https://goauthentik.io/%(username)s",
175                        "open_in_new_tab": True,
176                        "meta_icon": "",
177                        "meta_icon_url": None,
178                        "meta_icon_themed_urls": None,
179                        "meta_description": "",
180                        "meta_hide": False,
181                        "meta_publisher": "",
182                        "policy_engine_mode": "any",
183                    },
184                ],
185            },
186        )

Test listing applications the user passes policies for

def test_list_rbac(self):
188    def test_list_rbac(self):
189        """Test listing applications the user has RBAC permissions for"""
190        self.client.force_login(self.user)
191        response = self.client.get(reverse("authentik_api:application-list"))
192        self.assertJSONEqual(
193            response.content.decode(),
194            {
195                "autocomplete": {},
196                "pagination": {
197                    "next": 0,
198                    "previous": 0,
199                    "count": 2,
200                    "current": 1,
201                    "total_pages": 1,
202                    "start_index": 1,
203                    "end_index": 2,
204                },
205                "results": [
206                    {
207                        "pk": str(self.allowed.pk),
208                        "name": "allowed",
209                        "slug": "allowed",
210                        "group": "",
211                        "pbm_uuid": str(self.allowed.pbm_uuid),
212                        "provider": self.provider.pk,
213                        "provider_obj": {
214                            "assigned_application_name": "allowed",
215                            "assigned_application_slug": "allowed",
216                            "assigned_backchannel_application_name": None,
217                            "assigned_backchannel_application_slug": None,
218                            "authentication_flow": None,
219                            "invalidation_flow": None,
220                            "authorization_flow": str(self.provider.authorization_flow.pk),
221                            "component": "ak-provider-oauth2-form",
222                            "meta_model_name": "authentik_providers_oauth2.oauth2provider",
223                            "name": self.provider.name,
224                            "pk": self.provider.pk,
225                            "property_mappings": [],
226                            "verbose_name": "OAuth2/OpenID Provider",
227                            "verbose_name_plural": "OAuth2/OpenID Providers",
228                        },
229                        "backchannel_providers": [],
230                        "backchannel_providers_obj": [],
231                        "launch_url": f"https://goauthentik.io/{self.user.username}",
232                        "meta_launch_url": "https://goauthentik.io/%(username)s",
233                        "open_in_new_tab": True,
234                        "meta_icon": "",
235                        "meta_icon_url": None,
236                        "meta_icon_themed_urls": None,
237                        "meta_description": "",
238                        "meta_hide": False,
239                        "meta_publisher": "",
240                        "policy_engine_mode": "any",
241                    },
242                    {
243                        "launch_url": None,
244                        "meta_description": "",
245                        "meta_hide": False,
246                        "meta_icon": "",
247                        "meta_icon_url": None,
248                        "meta_icon_themed_urls": None,
249                        "meta_launch_url": "",
250                        "open_in_new_tab": False,
251                        "meta_publisher": "",
252                        "group": "",
253                        "name": "denied",
254                        "pbm_uuid": str(self.denied.pbm_uuid),
255                        "pk": str(self.denied.pk),
256                        "policy_engine_mode": "any",
257                        "provider": None,
258                        "provider_obj": None,
259                        "backchannel_providers": [],
260                        "backchannel_providers_obj": [],
261                        "slug": "denied",
262                    },
263                ],
264            },
265        )

Test listing applications the user has RBAC permissions for

def test_list_plain_launch_url(self):
267    def test_list_plain_launch_url(self):
268        """A launch URL without placeholders is not formatted, so listing it does not serialize
269        the requesting user, whose avatar lookup can make an HTTP request"""
270        self.allowed.meta_launch_url = "https://goauthentik.io"
271        self.allowed.save()
272        self.client.force_login(self.user)
273        with patch("authentik.core.api.users.get_avatar") as get_avatar:
274            response = self.client.get(reverse("authentik_api:application-list"))
275        self.assertEqual(response.status_code, 200)
276        self.assertEqual(response.json()["results"][0]["launch_url"], "https://goauthentik.io")
277        get_avatar.assert_not_called()

A launch URL without placeholders is not formatted, so listing it does not serialize the requesting user, whose avatar lookup can make an HTTP request

def test_update_provider(self):
279    def test_update_provider(self):
280        """Changing an application's provider returns the new provider"""
281        self.client.force_login(self.user)
282        url = reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug})
283        provider = SAMLProvider.objects.create(name=generate_id())
284        response = self.client.patch(url, {"provider": provider.pk})
285        self.assertEqual(response.status_code, 200)
286        self.assertEqual(response.json()["provider_obj"]["pk"], provider.pk)
287        self.assertEqual(response.json()["provider_obj"]["component"], "ak-provider-saml-form")
288        response = self.client.patch(url, {"provider": None}, format="json")
289        self.assertEqual(response.status_code, 200)
290        self.assertIsNone(response.json()["provider_obj"])

Changing an application's provider returns the new provider

def test_with_provider_combined(self):
292    def test_with_provider_combined(self):
293        """with_provider() can be called again, and after lookups through the provider"""
294        provider = SAMLProvider.objects.create(name=generate_id())
295        app = Application.objects.create(name=generate_id(), slug=generate_id(), provider=provider)
296        app = (
297            Application.objects.prefetch_related("provider__property_mappings")
298            .with_provider()
299            .with_provider()
300            .get(pk=app.pk)
301        )
302        with self.assertNumQueries(0):
303            self.assertEqual(app.get_provider(), provider)
304            self.assertEqual(list(app.get_provider().property_mappings.all()), [])

with_provider() can be called again, and after lookups through the provider

def test_list_rbac_ignores_policies(self):
306    def test_list_rbac_ignores_policies(self):
307        """RBAC access and policy access are separate: the list only checks
308        permissions, @accessible only checks policies"""
309        user = create_test_user()
310        user.assign_perms_to_managed_role("authentik_core.view_application", self.denied)
311        self.client.force_login(user)
312        response = self.client.get(reverse("authentik_api:application-list"))
313        self.assertEqual(response.status_code, 200)
314        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.denied.slug])
315        response = self.client.get(reverse("authentik_api:application-accessible"))
316        self.assertEqual(response.status_code, 200)
317        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.allowed.slug])

RBAC access and policy access are separate: the list only checks permissions, @accessible only checks policies

def test_list_accessible_for_user(self):
319    def test_list_accessible_for_user(self):
320        """for_user requires the view_user_applications permission on that user"""
321        user = create_test_user()
322        PolicyBinding.objects.create(target=self.allowed, user=user, order=0)
323        url = reverse("authentik_api:application-accessible") + f"?for_user={user.pk}"
324        self.client.force_login(create_test_user())
325        response = self.client.get(url)
326        self.assertEqual(response.status_code, 400)
327        self.client.force_login(self.user)
328        response = self.client.get(url)
329        self.assertEqual(response.status_code, 200)
330        self.assertEqual([app["slug"] for app in response.json()["results"]], [self.allowed.slug])
331        self.assertEqual(
332            response.json()["results"][0]["launch_url"], f"https://goauthentik.io/{user.username}"
333        )

for_user requires the view_user_applications permission on that user

def test_get_provider(self):
335    def test_get_provider(self):
336        """Ensure that proxy providers (at the time of writing that is the only provider
337        that inherits from another proxy type (OAuth) instead of inheriting from the root
338        provider class) is correctly looked up and selected from the database"""
339        slug = generate_id()
340        provider = ProxyProvider.objects.create(name=generate_id())
341        Application.objects.create(
342            name=generate_id(),
343            slug=slug,
344            provider=provider,
345        )
346        self.assertEqual(Application.objects.get(slug=slug).get_provider(), provider)
347        self.assertEqual(
348            Application.objects.with_provider().get(slug=slug).get_provider(), provider
349        )
350
351        slug = generate_id()
352        provider = SAMLProvider.objects.create(name=generate_id())
353        Application.objects.create(
354            name=generate_id(),
355            slug=slug,
356            provider=provider,
357        )
358        self.assertEqual(Application.objects.get(slug=slug).get_provider(), provider)
359        self.assertEqual(
360            Application.objects.with_provider().get(slug=slug).get_provider(), provider
361        )

Ensure that proxy providers (at the time of writing that is the only provider that inherits from another proxy type (OAuth) instead of inheriting from the root provider class) is correctly looked up and selected from the database

def test_create_application_with_reserved_slug(self):
363    def test_create_application_with_reserved_slug(self):
364        """Test creating an application with a reserved slug"""
365        self.client.force_login(self.user)
366        response = self.client.post(
367            reverse("authentik_api:application-list"),
368            {
369                "name": "Test Application",
370                "slug": Application.reserved_slugs[0],
371            },
372        )
373        self.assertEqual(response.status_code, 400)
374        self.assertIn("slug", response.data)
375        self.assertIn("reserved", response.data["slug"][0])

Test creating an application with a reserved slug

def test_update_application_with_reserved_slug(self):
377    def test_update_application_with_reserved_slug(self):
378        """Test updating an application to use a reserved slug"""
379        self.client.force_login(self.user)
380        app = Application.objects.create(
381            name="Test Application",
382            slug="valid-slug",
383        )
384
385        response = self.client.patch(
386            reverse("authentik_api:application-detail", kwargs={"slug": app.slug}),
387            {
388                "slug": Application.reserved_slugs[0],
389            },
390        )
391        self.assertEqual(response.status_code, 400)
392        self.assertIn("slug", response.data)
393        self.assertIn("reserved", response.data["slug"][0])

Test updating an application to use a reserved slug

def test_list_queries(self):
470    def test_list_queries(self):
471        """Listing applications loads providers in their own queries: joining every provider
472        subclass into the application query made a statement Postgres took over 100ms to plan.
473        The number of queries does not grow with the number of applications."""
474        Application.objects.all().delete()
475        denied_user = create_test_user()
476        apps = self._create_applications(4, self.user, denied_user)
477        self.client.force_login(self.user)
478        url = reverse("authentik_api:application-list")
479        response, small = self._get_queries(url)
480        for query in small.captured_queries:
481            sql = query["sql"]
482            self.assertFalse(
483                'FROM "authentik_core_application"' in sql and "authentik_core_provider" in sql,
484                "The application query joins providers",
485            )
486        self._assert_serialized(response.json()["results"], apps)
487
488        apps += self._create_applications(8, self.user, denied_user)
489        response, large = self._get_queries(url)
490        self._assert_serialized(response.json()["results"], apps)
491        self.assertEqual(len(large), len(small))

Listing applications loads providers in their own queries: joining every provider subclass into the application query made a statement Postgres took over 100ms to plan. The number of queries does not grow with the number of applications.

def test_list_accessible_queries(self):
493    def test_list_accessible_queries(self):
494        """@accessible returns exactly the applications whose policies the user passes, whether
495        it evaluates policies or reads the user's application list from the cache, and the number
496        of queries does not grow with the number of applications."""
497        Application.objects.all().delete()
498        user = create_test_user()
499        allowed = self._create_applications(4, user, self.user)[1::2]
500        self.client.force_login(user)
501        url = reverse("authentik_api:application-accessible") + "?only_with_launch_url=true"
502        small = {}
503        for cached in (False, True):
504            response, small[cached] = self._get_queries(url, cached)
505            self._assert_serialized(response.json()["results"], allowed)
506
507        allowed += self._create_applications(8, user, self.user)[1::2]
508        for cached in (False, True):
509            response, large = self._get_queries(url, cached)
510            self._assert_serialized(response.json()["results"], allowed)
511            self.assertEqual(len(large), len(small[cached]))

@accessible returns exactly the applications whose policies the user passes, whether it evaluates policies or reads the user's application list from the cache, and the number of queries does not grow with the number of applications.