authentik.rbac.tests.test_permission_check_coverage

Endpoints run the check functions they offer

 1"""Endpoints run the check functions they offer"""
 2
 3from rest_framework.status import HTTP_200_OK
 4from rest_framework.test import APITestCase
 5
 6from authentik.api.v3.urls import router
 7from authentik.core.tests.utils import create_test_user
 8from authentik.lib.generators import generate_id
 9from authentik.rbac.apps import EnableCustomPermissions
10from authentik.rbac.endpoints import RBAC_FUNC_NARROW_LIST, Endpoints
11from authentik.rbac.models import PermissionCheck, Role
12
13DENY = "def has_permission(request):\n    return False"
14FAIL_LIST = "def narrow_list(request, queryset):\n    raise ValueError"
15FAIL_ALTER = "def alter_response(request, data):\n    raise ValueError"
16
17
18class TestPermissionCheckCoverage(APITestCase):
19    """Probe every list endpoint: a denying has_permission and a failing narrow_list
20    must turn a visible list into a 403, and a failing alter_response into a 500."""
21
22    def setUp(self):
23        EnableCustomPermissions.set(True)
24
25    def test_lists(self):
26        user = create_test_user()
27        role = Role.objects.create(name=generate_id())
28        user.roles.add(role)
29        self.client.force_login(user)
30        viewsets = {prefix: viewset for prefix, viewset, basename in router.registry}
31        check = PermissionCheck.objects.create(name=generate_id(), expression=DENY, endpoints=[])
32        unreachable = []
33        probed = []
34        for endpoint in Endpoints.hookable().values():
35            prefix, action = endpoint.id.rsplit(":", 1)
36            model = getattr(getattr(viewsets.get(prefix), "queryset", None), "model", None)
37            if action != "list" or model is None:
38                continue
39            role.assign_perms(f"{model._meta.app_label}.view_{model._meta.model_name}")
40            url = f"/api/v3/{prefix}/"
41            check.endpoints = []
42            check.save()
43            if self.client.get(url).status_code != HTTP_200_OK:
44                unreachable.append(endpoint.id)
45                continue
46            probes = {DENY: 403, FAIL_ALTER: 500}
47            if RBAC_FUNC_NARROW_LIST in endpoint.functions:
48                probes[FAIL_LIST] = 403
49            for expression, status in probes.items():
50                check.expression = expression
51                check.endpoints = [endpoint.id]
52                check.save()
53                response = self.client.get(url)
54                self.assertEqual(response.status_code, status, (endpoint.id, expression))
55            probed.append(endpoint.id)
56        self.assertGreater(len(probed), 100, unreachable)
DENY = 'def has_permission(request):\n return False'
FAIL_LIST = 'def narrow_list(request, queryset):\n raise ValueError'
FAIL_ALTER = 'def alter_response(request, data):\n raise ValueError'
class TestPermissionCheckCoverage(rest_framework.test.APITestCase):
19class TestPermissionCheckCoverage(APITestCase):
20    """Probe every list endpoint: a denying has_permission and a failing narrow_list
21    must turn a visible list into a 403, and a failing alter_response into a 500."""
22
23    def setUp(self):
24        EnableCustomPermissions.set(True)
25
26    def test_lists(self):
27        user = create_test_user()
28        role = Role.objects.create(name=generate_id())
29        user.roles.add(role)
30        self.client.force_login(user)
31        viewsets = {prefix: viewset for prefix, viewset, basename in router.registry}
32        check = PermissionCheck.objects.create(name=generate_id(), expression=DENY, endpoints=[])
33        unreachable = []
34        probed = []
35        for endpoint in Endpoints.hookable().values():
36            prefix, action = endpoint.id.rsplit(":", 1)
37            model = getattr(getattr(viewsets.get(prefix), "queryset", None), "model", None)
38            if action != "list" or model is None:
39                continue
40            role.assign_perms(f"{model._meta.app_label}.view_{model._meta.model_name}")
41            url = f"/api/v3/{prefix}/"
42            check.endpoints = []
43            check.save()
44            if self.client.get(url).status_code != HTTP_200_OK:
45                unreachable.append(endpoint.id)
46                continue
47            probes = {DENY: 403, FAIL_ALTER: 500}
48            if RBAC_FUNC_NARROW_LIST in endpoint.functions:
49                probes[FAIL_LIST] = 403
50            for expression, status in probes.items():
51                check.expression = expression
52                check.endpoints = [endpoint.id]
53                check.save()
54                response = self.client.get(url)
55                self.assertEqual(response.status_code, status, (endpoint.id, expression))
56            probed.append(endpoint.id)
57        self.assertGreater(len(probed), 100, unreachable)

Probe every list endpoint: a denying has_permission and a failing narrow_list must turn a visible list into a 403, and a failing alter_response into a 500.

def setUp(self):
23    def setUp(self):
24        EnableCustomPermissions.set(True)

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

def test_lists(self):
26    def test_lists(self):
27        user = create_test_user()
28        role = Role.objects.create(name=generate_id())
29        user.roles.add(role)
30        self.client.force_login(user)
31        viewsets = {prefix: viewset for prefix, viewset, basename in router.registry}
32        check = PermissionCheck.objects.create(name=generate_id(), expression=DENY, endpoints=[])
33        unreachable = []
34        probed = []
35        for endpoint in Endpoints.hookable().values():
36            prefix, action = endpoint.id.rsplit(":", 1)
37            model = getattr(getattr(viewsets.get(prefix), "queryset", None), "model", None)
38            if action != "list" or model is None:
39                continue
40            role.assign_perms(f"{model._meta.app_label}.view_{model._meta.model_name}")
41            url = f"/api/v3/{prefix}/"
42            check.endpoints = []
43            check.save()
44            if self.client.get(url).status_code != HTTP_200_OK:
45                unreachable.append(endpoint.id)
46                continue
47            probes = {DENY: 403, FAIL_ALTER: 500}
48            if RBAC_FUNC_NARROW_LIST in endpoint.functions:
49                probes[FAIL_LIST] = 403
50            for expression, status in probes.items():
51                check.expression = expression
52                check.endpoints = [endpoint.id]
53                check.save()
54                response = self.client.get(url)
55                self.assertEqual(response.status_code, status, (endpoint.id, expression))
56            probed.append(endpoint.id)
57        self.assertGreater(len(probed), 100, unreachable)