authentik.policies.tests.test_engine_list

ListPolicyEngine tests

  1"""ListPolicyEngine tests"""
  2
  3from datetime import timedelta
  4from unittest.mock import patch
  5
  6from django.core.cache import cache
  7from django.db import connections
  8from django.test import RequestFactory, TestCase
  9from django.test.utils import CaptureQueriesContext
 10from django.utils.timezone import now
 11
 12from authentik.core.models import Group
 13from authentik.core.tests.utils import create_test_user
 14from authentik.lib.generators import generate_id
 15from authentik.policies.dummy.models import DummyPolicy
 16from authentik.policies.engine import ListPolicyEngine, PolicyEngine
 17from authentik.policies.models import PolicyBinding, PolicyBindingModel, PolicyEngineMode
 18from authentik.policies.tests.test_process import clear_policy_cache
 19from authentik.policies.types import CACHE_PREFIX
 20
 21
 22class TestListPolicyEngine(TestCase):
 23    """ListPolicyEngine tests"""
 24
 25    def setUp(self):
 26        clear_policy_cache()
 27        self.policy_true = DummyPolicy.objects.create(
 28            name=generate_id(), result=True, wait_min=0, wait_max=1
 29        )
 30        self.group_a = Group.objects.create(name=generate_id())
 31        self.group_b = Group.objects.create(name=generate_id())
 32        self.user = create_test_user()
 33        self.user.groups.add(self.group_a)
 34        self.obj_a = PolicyBindingModel.objects.create()
 35        self.obj_b = PolicyBindingModel.objects.create()
 36        self.obj_c = PolicyBindingModel.objects.create()
 37        self.objs = PolicyBindingModel.objects.filter(
 38            pk__in=[self.obj_a.pk, self.obj_b.pk, self.obj_c.pk]
 39        )
 40
 41    def test_list_engine_empty(self):
 42        """No bindings at all on any object -> empty_result decides"""
 43        engine = ListPolicyEngine(self.objs, self.user)
 44        self.assertEqual(
 45            set(engine.build().result.values_list("pk", flat=True)),
 46            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
 47        )
 48
 49        engine = ListPolicyEngine(self.objs, self.user)
 50        engine.empty_result = False
 51        self.assertEqual(set(engine.build().result.values_list("pk", flat=True)), set())
 52
 53    def test_list_engine_static_group_any(self):
 54        """MODE_ANY static group binding, evaluated independently per object"""
 55        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
 56        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
 57        engine = ListPolicyEngine(self.objs, self.user)
 58        self.assertEqual(
 59            set(engine.build().result.values_list("pk", flat=True)),
 60            {self.obj_a.pk, self.obj_c.pk},
 61        )
 62
 63    def test_list_engine_static_group_all(self):
 64        """MODE_ALL with two group bindings on one object: only passes if user is in both"""
 65        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
 66        self.obj_a.save()
 67        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
 68        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=1)
 69        engine = ListPolicyEngine(self.objs, self.user)
 70        self.assertEqual(
 71            set(engine.build().result.values_list("pk", flat=True)),
 72            {self.obj_b.pk, self.obj_c.pk},
 73        )
 74
 75    def test_list_engine_static_user_binding(self):
 76        """Direct user binding"""
 77        other_user = create_test_user()
 78        PolicyBinding.objects.create(target=self.obj_a, user=self.user, order=0)
 79        PolicyBinding.objects.create(target=self.obj_b, user=other_user, order=0)
 80        engine = ListPolicyEngine(self.objs, self.user)
 81        self.assertEqual(
 82            set(engine.build().result.values_list("pk", flat=True)),
 83            {self.obj_a.pk, self.obj_c.pk},
 84        )
 85
 86    def test_list_engine_negate(self):
 87        """Negated group binding excludes members instead of including them"""
 88        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, negate=True, order=0)
 89        engine = ListPolicyEngine(self.objs, self.user)
 90        self.assertEqual(
 91            set(engine.build().result.values_list("pk", flat=True)),
 92            {self.obj_b.pk, self.obj_c.pk},
 93        )
 94
 95    def test_list_engine_group_hierarchy(self):
 96        """A binding on a parent group also matches a user only in a descendant group"""
 97        group_parent = Group.objects.create(name=generate_id())
 98        self.group_a.parents.add(group_parent)
 99        PolicyBinding.objects.create(target=self.obj_a, group=group_parent, order=0)
100        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
101        engine = ListPolicyEngine(self.objs, self.user)
102        self.assertEqual(
103            set(engine.build().result.values_list("pk", flat=True)),
104            {self.obj_a.pk, self.obj_c.pk},
105        )
106
107    def test_list_engine_policy_fallback(self):
108        """Real Policy bindings on different objects fall back to per-object evaluation
109        and are evaluated independently."""
110        policy_false = DummyPolicy.objects.create(
111            name=generate_id(), result=False, wait_min=0, wait_max=1
112        )
113        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=0)
114        PolicyBinding.objects.create(target=self.obj_b, policy=policy_false, order=0)
115        engine = ListPolicyEngine(self.objs, self.user)
116        self.assertEqual(
117            set(engine.build().result.values_list("pk", flat=True)),
118            {self.obj_a.pk, self.obj_c.pk},
119        )
120
121    def test_list_engine_dry_run(self):
122        """Dry-run bindings do not affect the objects returned by the list engine."""
123        policy_false = DummyPolicy.objects.create(
124            name=generate_id(), result=False, wait_min=0, wait_max=1
125        )
126        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
127        self.obj_a.save()
128        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=0)
129        dry_run_a = PolicyBinding.objects.create(
130            target=self.obj_a, policy=policy_false, order=1, dry_run=True
131        )
132        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
133        dry_run_b = PolicyBinding.objects.create(
134            target=self.obj_b, policy=self.policy_true, order=1, dry_run=True
135        )
136
137        result = ListPolicyEngine(self.objs, self.user).build().result
138
139        self.assertEqual(
140            set(result.values_list("pk", flat=True)),
141            {self.obj_c.pk},
142        )
143        self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run_a.policy_binding_uuid.hex}*")), 1)
144        self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run_b.policy_binding_uuid.hex}*")), 1)
145
146        with patch(
147            "authentik.policies.dummy.models.DummyPolicy.passes",
148            side_effect=AssertionError("cached dry-run policies should not be evaluated"),
149        ):
150            cached_result = ListPolicyEngine(self.objs, self.user).build().result
151        self.assertEqual(
152            set(cached_result.values_list("pk", flat=True)),
153            {self.obj_c.pk},
154        )
155
156    def test_list_engine_mode_all_static_prefilter_skips_dynamic(self):
157        """MODE_ALL: a failing static binding must skip dynamic evaluation for that
158        object entirely."""
159        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
160        self.obj_a.save()
161        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=0)
162        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=1)
163        with patch(
164            "authentik.policies.dummy.models.DummyPolicy.passes",
165            side_effect=AssertionError("dynamic policy should not be evaluated"),
166        ):
167            engine = ListPolicyEngine(self.objs, self.user)
168            result = set(engine.build().result.values_list("pk", flat=True))
169        self.assertEqual(result, {self.obj_b.pk, self.obj_c.pk})
170
171    def test_list_engine_mode_all_mixed_passes(self):
172        """MODE_ALL with a passing static binding and a passing dynamic binding passes overall"""
173        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
174        self.obj_a.save()
175        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
176        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=1)
177        engine = ListPolicyEngine(self.objs, self.user)
178        self.assertEqual(
179            set(engine.build().result.values_list("pk", flat=True)),
180            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
181        )
182
183    def test_list_engine_expired_static_binding_ignored(self):
184        """An expired static binding is excluded from evaluation entirely"""
185        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
186        self.obj_a.save()
187        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
188        PolicyBinding.objects.create(
189            target=self.obj_a,
190            group=self.group_b,
191            order=1,
192            expiring=True,
193            expires=now() - timedelta(minutes=10),
194        )
195        engine = ListPolicyEngine(self.objs, self.user)
196        self.assertEqual(
197            set(engine.build().result.values_list("pk", flat=True)),
198            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
199        )
200
201    def test_list_engine_expired_policy_binding_ignored(self):
202        """An expired real-Policy binding is excluded from evaluation entirely, even
203        though (were it not expired) it would force MODE_ALL to fail."""
204        policy_false = DummyPolicy.objects.create(
205            name=generate_id(), result=False, wait_min=0, wait_max=1
206        )
207        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
208        self.obj_a.save()
209        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
210        PolicyBinding.objects.create(
211            target=self.obj_a,
212            policy=policy_false,
213            order=1,
214            expiring=True,
215            expires=now() - timedelta(minutes=10),
216        )
217        engine = ListPolicyEngine(self.objs, self.user)
218        self.assertEqual(
219            set(engine.build().result.values_list("pk", flat=True)),
220            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
221        )
222
223    def test_list_engine_static_query_count_independent_of_object_count(self):
224        """Query count for the static-only path must not scale with the number of
225        objects."""
226        objs = [PolicyBindingModel.objects.create() for _ in range(50)]
227        for obj in objs:
228            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
229        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
230        engine = ListPolicyEngine(qs, self.user)
231        with CaptureQueriesContext(connections["default"]) as ctx:
232            result = set(engine.build().result.values_list("pk", flat=True))
233        self.assertLess(ctx.final_queries, 20)
234        self.assertEqual(result, {o.pk for o in objs})
235
236    def test_list_engine_dynamic_query_count_independent_of_object_count(self):
237        """The slow (per-object Policy) path must not re-fetch bindings, the static
238        aggregate, the cache, or the polymorphic `policy`/`target` FKs per object --
239        query count must stay O(1) regardless of the number of objects."""
240        small_objs = [PolicyBindingModel.objects.create() for _ in range(3)]
241        for obj in small_objs:
242            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
243            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=1)
244        small_qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in small_objs])
245
246        ListPolicyEngine(small_qs, self.user).build()  # warm cache
247        with CaptureQueriesContext(connections["default"]) as ctx_small:
248            list(ListPolicyEngine(small_qs, self.user).build().result)
249        baseline_queries = len(ctx_small.captured_queries)
250
251        extra_objs = [PolicyBindingModel.objects.create() for _ in range(50)]
252        for obj in extra_objs:
253            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
254            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=1)
255        large_qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in small_objs + extra_objs])
256
257        ListPolicyEngine(large_qs, self.user).build()  # warm cache
258        with CaptureQueriesContext(connections["default"]) as ctx_large:
259            list(ListPolicyEngine(large_qs, self.user).build().result)
260
261        self.assertLessEqual(
262            len(ctx_large.captured_queries),
263            baseline_queries + 2,
264            (
265                f"Query count grew from {baseline_queries} to "
266                f"{len(ctx_large.captured_queries)} after adding {len(extra_objs)} objects "
267                "-- bindings/cache/static-resolution/FK lookups are being repeated per object."
268            ),
269        )
270
271    def test_list_engine_no_policy_engine_instantiated_for_static_path(self):
272        """Purely static bindings must never instantiate a per-object PolicyEngine."""
273        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
274        with patch("authentik.policies.engine.PolicyEngine") as mock_engine:
275            engine = ListPolicyEngine(self.objs, self.user)
276            list(engine.build().result)
277        self.assertEqual(mock_engine.call_count, 0)
278
279    def test_list_engine_bulk_cache_prefetch_single_round_trip(self):
280        """The slow (per-object Policy) path must fetch cache entries via a single
281        cache.get_many() call instead of one cache.get() per (binding, object) pair."""
282        objs = [PolicyBindingModel.objects.create() for _ in range(3)]
283        for obj in objs:
284            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=0)
285        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
286
287        with (
288            patch(
289                "authentik.policies.engine.cache.get_many", wraps=cache.get_many
290            ) as mock_get_many,
291            patch("authentik.policies.engine.cache.get", wraps=cache.get) as mock_get,
292        ):
293            engine = ListPolicyEngine(qs, self.user)
294            result = set(engine.build().result.values_list("pk", flat=True))
295
296        self.assertEqual(result, {o.pk for o in objs})
297        mock_get_many.assert_called_once()
298        mock_get.assert_not_called()
299
300    def test_list_engine_cache_reused_across_builds(self):
301        """A second ListPolicyEngine.build() must reuse the PolicyResults cached by the
302        first build (bulk-prefetched via one cache.get_many()) instead of re-evaluating
303        the (slow, per-object) DummyPolicy again."""
304        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=0)
305
306        first = set(
307            ListPolicyEngine(self.objs, self.user).build().result.values_list("pk", flat=True)
308        )
309        self.assertEqual(first, {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk})
310
311        with (
312            patch(
313                "authentik.policies.engine.cache.get_many", wraps=cache.get_many
314            ) as mock_get_many,
315            patch(
316                "authentik.policies.dummy.models.DummyPolicy.passes",
317                side_effect=AssertionError("policy should be served from cache, not re-evaluated"),
318            ),
319        ):
320            engine = ListPolicyEngine(self.objs, self.user)
321            second = set(engine.build().result.values_list("pk", flat=True))
322
323        self.assertEqual(second, {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk})
324        mock_get_many.assert_called_once()
325
326    def test_list_engine_http_request_enriched_once(self):
327        """set_http_request() (context/geoip enrichment) must be called exactly once
328        per build(), not once per object -- the fixed user/http_request means one
329        enriched PolicyRequest can be reused across every object."""
330        objs = [PolicyBindingModel.objects.create() for _ in range(5)]
331        for obj in objs:
332            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=0)
333        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
334        http_request = RequestFactory().get("/")
335        http_request.user = self.user
336
337        with patch(
338            "authentik.policies.engine.PolicyRequest.set_http_request", autospec=True
339        ) as mock_set:
340            engine = ListPolicyEngine(qs, self.user, http_request)
341            engine.build()
342        mock_set.assert_called_once()
343
344    def test_list_engine_matches_single_object_engine(self):
345        """Cross-validate ListPolicyEngine's static-binding handling (negate, group
346        hierarchy, MODE_ALL/MODE_ANY) against the per-object PolicyEngine (the source
347        of truth), for a fixed user across a batch of objects.
348
349        This asserts *agreement* with PolicyEngine rather than hand-computed expected
350        sets, so it can't be wrong in the same way as the implementation being tested.
351        """
352        group_parent = Group.objects.create(name=generate_id())
353        group_child = Group.objects.create(name=generate_id())
354        group_child.parents.add(group_parent)
355        group_other = Group.objects.create(name=generate_id())
356
357        user = create_test_user()
358        user.groups.add(group_child)
359
360        scenarios = [
361            (
362                "negate group (with hierarchy)",
363                PolicyEngineMode.MODE_ANY,
364                [{"group": group_parent, "negate": True}],
365            ),
366            (
367                "negate user",
368                PolicyEngineMode.MODE_ANY,
369                [{"user": user, "negate": True}],
370            ),
371            (
372                "MODE_ALL negate + positive",
373                PolicyEngineMode.MODE_ALL,
374                [{"group": group_parent, "negate": True}, {"group": group_other}],
375            ),
376            (
377                "MODE_ANY negate + positive",
378                PolicyEngineMode.MODE_ANY,
379                [{"group": group_parent, "negate": True}, {"group": group_other}],
380            ),
381            (
382                "multiple negated bindings, MODE_ALL",
383                PolicyEngineMode.MODE_ALL,
384                [
385                    {"group": group_parent, "negate": True},
386                    {"user": user, "negate": True},
387                ],
388            ),
389        ]
390
391        objs = []
392        for message, mode, binding_specs in scenarios:
393            pbm = PolicyBindingModel.objects.create(policy_engine_mode=mode)
394            for idx, spec in enumerate(binding_specs):
395                PolicyBinding.objects.create(target=pbm, order=idx, **spec)
396            objs.append((message, pbm))
397
398        qs = PolicyBindingModel.objects.filter(pk__in=[pbm.pk for _, pbm in objs])
399        engine = ListPolicyEngine(qs, user)
400        batch_passing = set(engine.build().result.values_list("pk", flat=True))
401
402        for message, pbm in objs:
403            with self.subTest(message):
404                single = PolicyEngine(pbm, user)
405                single.use_cache = False
406                expected = single.build().passing
407                self.assertEqual(
408                    pbm.pk in batch_passing,
409                    expected,
410                    f"{message}: mismatch",
411                )
class TestListPolicyEngine(django.test.testcases.TestCase):
 23class TestListPolicyEngine(TestCase):
 24    """ListPolicyEngine tests"""
 25
 26    def setUp(self):
 27        clear_policy_cache()
 28        self.policy_true = DummyPolicy.objects.create(
 29            name=generate_id(), result=True, wait_min=0, wait_max=1
 30        )
 31        self.group_a = Group.objects.create(name=generate_id())
 32        self.group_b = Group.objects.create(name=generate_id())
 33        self.user = create_test_user()
 34        self.user.groups.add(self.group_a)
 35        self.obj_a = PolicyBindingModel.objects.create()
 36        self.obj_b = PolicyBindingModel.objects.create()
 37        self.obj_c = PolicyBindingModel.objects.create()
 38        self.objs = PolicyBindingModel.objects.filter(
 39            pk__in=[self.obj_a.pk, self.obj_b.pk, self.obj_c.pk]
 40        )
 41
 42    def test_list_engine_empty(self):
 43        """No bindings at all on any object -> empty_result decides"""
 44        engine = ListPolicyEngine(self.objs, self.user)
 45        self.assertEqual(
 46            set(engine.build().result.values_list("pk", flat=True)),
 47            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
 48        )
 49
 50        engine = ListPolicyEngine(self.objs, self.user)
 51        engine.empty_result = False
 52        self.assertEqual(set(engine.build().result.values_list("pk", flat=True)), set())
 53
 54    def test_list_engine_static_group_any(self):
 55        """MODE_ANY static group binding, evaluated independently per object"""
 56        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
 57        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
 58        engine = ListPolicyEngine(self.objs, self.user)
 59        self.assertEqual(
 60            set(engine.build().result.values_list("pk", flat=True)),
 61            {self.obj_a.pk, self.obj_c.pk},
 62        )
 63
 64    def test_list_engine_static_group_all(self):
 65        """MODE_ALL with two group bindings on one object: only passes if user is in both"""
 66        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
 67        self.obj_a.save()
 68        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
 69        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=1)
 70        engine = ListPolicyEngine(self.objs, self.user)
 71        self.assertEqual(
 72            set(engine.build().result.values_list("pk", flat=True)),
 73            {self.obj_b.pk, self.obj_c.pk},
 74        )
 75
 76    def test_list_engine_static_user_binding(self):
 77        """Direct user binding"""
 78        other_user = create_test_user()
 79        PolicyBinding.objects.create(target=self.obj_a, user=self.user, order=0)
 80        PolicyBinding.objects.create(target=self.obj_b, user=other_user, order=0)
 81        engine = ListPolicyEngine(self.objs, self.user)
 82        self.assertEqual(
 83            set(engine.build().result.values_list("pk", flat=True)),
 84            {self.obj_a.pk, self.obj_c.pk},
 85        )
 86
 87    def test_list_engine_negate(self):
 88        """Negated group binding excludes members instead of including them"""
 89        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, negate=True, order=0)
 90        engine = ListPolicyEngine(self.objs, self.user)
 91        self.assertEqual(
 92            set(engine.build().result.values_list("pk", flat=True)),
 93            {self.obj_b.pk, self.obj_c.pk},
 94        )
 95
 96    def test_list_engine_group_hierarchy(self):
 97        """A binding on a parent group also matches a user only in a descendant group"""
 98        group_parent = Group.objects.create(name=generate_id())
 99        self.group_a.parents.add(group_parent)
100        PolicyBinding.objects.create(target=self.obj_a, group=group_parent, order=0)
101        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
102        engine = ListPolicyEngine(self.objs, self.user)
103        self.assertEqual(
104            set(engine.build().result.values_list("pk", flat=True)),
105            {self.obj_a.pk, self.obj_c.pk},
106        )
107
108    def test_list_engine_policy_fallback(self):
109        """Real Policy bindings on different objects fall back to per-object evaluation
110        and are evaluated independently."""
111        policy_false = DummyPolicy.objects.create(
112            name=generate_id(), result=False, wait_min=0, wait_max=1
113        )
114        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=0)
115        PolicyBinding.objects.create(target=self.obj_b, policy=policy_false, order=0)
116        engine = ListPolicyEngine(self.objs, self.user)
117        self.assertEqual(
118            set(engine.build().result.values_list("pk", flat=True)),
119            {self.obj_a.pk, self.obj_c.pk},
120        )
121
122    def test_list_engine_dry_run(self):
123        """Dry-run bindings do not affect the objects returned by the list engine."""
124        policy_false = DummyPolicy.objects.create(
125            name=generate_id(), result=False, wait_min=0, wait_max=1
126        )
127        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
128        self.obj_a.save()
129        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=0)
130        dry_run_a = PolicyBinding.objects.create(
131            target=self.obj_a, policy=policy_false, order=1, dry_run=True
132        )
133        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
134        dry_run_b = PolicyBinding.objects.create(
135            target=self.obj_b, policy=self.policy_true, order=1, dry_run=True
136        )
137
138        result = ListPolicyEngine(self.objs, self.user).build().result
139
140        self.assertEqual(
141            set(result.values_list("pk", flat=True)),
142            {self.obj_c.pk},
143        )
144        self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run_a.policy_binding_uuid.hex}*")), 1)
145        self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run_b.policy_binding_uuid.hex}*")), 1)
146
147        with patch(
148            "authentik.policies.dummy.models.DummyPolicy.passes",
149            side_effect=AssertionError("cached dry-run policies should not be evaluated"),
150        ):
151            cached_result = ListPolicyEngine(self.objs, self.user).build().result
152        self.assertEqual(
153            set(cached_result.values_list("pk", flat=True)),
154            {self.obj_c.pk},
155        )
156
157    def test_list_engine_mode_all_static_prefilter_skips_dynamic(self):
158        """MODE_ALL: a failing static binding must skip dynamic evaluation for that
159        object entirely."""
160        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
161        self.obj_a.save()
162        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=0)
163        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=1)
164        with patch(
165            "authentik.policies.dummy.models.DummyPolicy.passes",
166            side_effect=AssertionError("dynamic policy should not be evaluated"),
167        ):
168            engine = ListPolicyEngine(self.objs, self.user)
169            result = set(engine.build().result.values_list("pk", flat=True))
170        self.assertEqual(result, {self.obj_b.pk, self.obj_c.pk})
171
172    def test_list_engine_mode_all_mixed_passes(self):
173        """MODE_ALL with a passing static binding and a passing dynamic binding passes overall"""
174        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
175        self.obj_a.save()
176        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
177        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=1)
178        engine = ListPolicyEngine(self.objs, self.user)
179        self.assertEqual(
180            set(engine.build().result.values_list("pk", flat=True)),
181            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
182        )
183
184    def test_list_engine_expired_static_binding_ignored(self):
185        """An expired static binding is excluded from evaluation entirely"""
186        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
187        self.obj_a.save()
188        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
189        PolicyBinding.objects.create(
190            target=self.obj_a,
191            group=self.group_b,
192            order=1,
193            expiring=True,
194            expires=now() - timedelta(minutes=10),
195        )
196        engine = ListPolicyEngine(self.objs, self.user)
197        self.assertEqual(
198            set(engine.build().result.values_list("pk", flat=True)),
199            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
200        )
201
202    def test_list_engine_expired_policy_binding_ignored(self):
203        """An expired real-Policy binding is excluded from evaluation entirely, even
204        though (were it not expired) it would force MODE_ALL to fail."""
205        policy_false = DummyPolicy.objects.create(
206            name=generate_id(), result=False, wait_min=0, wait_max=1
207        )
208        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
209        self.obj_a.save()
210        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
211        PolicyBinding.objects.create(
212            target=self.obj_a,
213            policy=policy_false,
214            order=1,
215            expiring=True,
216            expires=now() - timedelta(minutes=10),
217        )
218        engine = ListPolicyEngine(self.objs, self.user)
219        self.assertEqual(
220            set(engine.build().result.values_list("pk", flat=True)),
221            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
222        )
223
224    def test_list_engine_static_query_count_independent_of_object_count(self):
225        """Query count for the static-only path must not scale with the number of
226        objects."""
227        objs = [PolicyBindingModel.objects.create() for _ in range(50)]
228        for obj in objs:
229            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
230        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
231        engine = ListPolicyEngine(qs, self.user)
232        with CaptureQueriesContext(connections["default"]) as ctx:
233            result = set(engine.build().result.values_list("pk", flat=True))
234        self.assertLess(ctx.final_queries, 20)
235        self.assertEqual(result, {o.pk for o in objs})
236
237    def test_list_engine_dynamic_query_count_independent_of_object_count(self):
238        """The slow (per-object Policy) path must not re-fetch bindings, the static
239        aggregate, the cache, or the polymorphic `policy`/`target` FKs per object --
240        query count must stay O(1) regardless of the number of objects."""
241        small_objs = [PolicyBindingModel.objects.create() for _ in range(3)]
242        for obj in small_objs:
243            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
244            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=1)
245        small_qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in small_objs])
246
247        ListPolicyEngine(small_qs, self.user).build()  # warm cache
248        with CaptureQueriesContext(connections["default"]) as ctx_small:
249            list(ListPolicyEngine(small_qs, self.user).build().result)
250        baseline_queries = len(ctx_small.captured_queries)
251
252        extra_objs = [PolicyBindingModel.objects.create() for _ in range(50)]
253        for obj in extra_objs:
254            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
255            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=1)
256        large_qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in small_objs + extra_objs])
257
258        ListPolicyEngine(large_qs, self.user).build()  # warm cache
259        with CaptureQueriesContext(connections["default"]) as ctx_large:
260            list(ListPolicyEngine(large_qs, self.user).build().result)
261
262        self.assertLessEqual(
263            len(ctx_large.captured_queries),
264            baseline_queries + 2,
265            (
266                f"Query count grew from {baseline_queries} to "
267                f"{len(ctx_large.captured_queries)} after adding {len(extra_objs)} objects "
268                "-- bindings/cache/static-resolution/FK lookups are being repeated per object."
269            ),
270        )
271
272    def test_list_engine_no_policy_engine_instantiated_for_static_path(self):
273        """Purely static bindings must never instantiate a per-object PolicyEngine."""
274        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
275        with patch("authentik.policies.engine.PolicyEngine") as mock_engine:
276            engine = ListPolicyEngine(self.objs, self.user)
277            list(engine.build().result)
278        self.assertEqual(mock_engine.call_count, 0)
279
280    def test_list_engine_bulk_cache_prefetch_single_round_trip(self):
281        """The slow (per-object Policy) path must fetch cache entries via a single
282        cache.get_many() call instead of one cache.get() per (binding, object) pair."""
283        objs = [PolicyBindingModel.objects.create() for _ in range(3)]
284        for obj in objs:
285            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=0)
286        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
287
288        with (
289            patch(
290                "authentik.policies.engine.cache.get_many", wraps=cache.get_many
291            ) as mock_get_many,
292            patch("authentik.policies.engine.cache.get", wraps=cache.get) as mock_get,
293        ):
294            engine = ListPolicyEngine(qs, self.user)
295            result = set(engine.build().result.values_list("pk", flat=True))
296
297        self.assertEqual(result, {o.pk for o in objs})
298        mock_get_many.assert_called_once()
299        mock_get.assert_not_called()
300
301    def test_list_engine_cache_reused_across_builds(self):
302        """A second ListPolicyEngine.build() must reuse the PolicyResults cached by the
303        first build (bulk-prefetched via one cache.get_many()) instead of re-evaluating
304        the (slow, per-object) DummyPolicy again."""
305        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=0)
306
307        first = set(
308            ListPolicyEngine(self.objs, self.user).build().result.values_list("pk", flat=True)
309        )
310        self.assertEqual(first, {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk})
311
312        with (
313            patch(
314                "authentik.policies.engine.cache.get_many", wraps=cache.get_many
315            ) as mock_get_many,
316            patch(
317                "authentik.policies.dummy.models.DummyPolicy.passes",
318                side_effect=AssertionError("policy should be served from cache, not re-evaluated"),
319            ),
320        ):
321            engine = ListPolicyEngine(self.objs, self.user)
322            second = set(engine.build().result.values_list("pk", flat=True))
323
324        self.assertEqual(second, {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk})
325        mock_get_many.assert_called_once()
326
327    def test_list_engine_http_request_enriched_once(self):
328        """set_http_request() (context/geoip enrichment) must be called exactly once
329        per build(), not once per object -- the fixed user/http_request means one
330        enriched PolicyRequest can be reused across every object."""
331        objs = [PolicyBindingModel.objects.create() for _ in range(5)]
332        for obj in objs:
333            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=0)
334        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
335        http_request = RequestFactory().get("/")
336        http_request.user = self.user
337
338        with patch(
339            "authentik.policies.engine.PolicyRequest.set_http_request", autospec=True
340        ) as mock_set:
341            engine = ListPolicyEngine(qs, self.user, http_request)
342            engine.build()
343        mock_set.assert_called_once()
344
345    def test_list_engine_matches_single_object_engine(self):
346        """Cross-validate ListPolicyEngine's static-binding handling (negate, group
347        hierarchy, MODE_ALL/MODE_ANY) against the per-object PolicyEngine (the source
348        of truth), for a fixed user across a batch of objects.
349
350        This asserts *agreement* with PolicyEngine rather than hand-computed expected
351        sets, so it can't be wrong in the same way as the implementation being tested.
352        """
353        group_parent = Group.objects.create(name=generate_id())
354        group_child = Group.objects.create(name=generate_id())
355        group_child.parents.add(group_parent)
356        group_other = Group.objects.create(name=generate_id())
357
358        user = create_test_user()
359        user.groups.add(group_child)
360
361        scenarios = [
362            (
363                "negate group (with hierarchy)",
364                PolicyEngineMode.MODE_ANY,
365                [{"group": group_parent, "negate": True}],
366            ),
367            (
368                "negate user",
369                PolicyEngineMode.MODE_ANY,
370                [{"user": user, "negate": True}],
371            ),
372            (
373                "MODE_ALL negate + positive",
374                PolicyEngineMode.MODE_ALL,
375                [{"group": group_parent, "negate": True}, {"group": group_other}],
376            ),
377            (
378                "MODE_ANY negate + positive",
379                PolicyEngineMode.MODE_ANY,
380                [{"group": group_parent, "negate": True}, {"group": group_other}],
381            ),
382            (
383                "multiple negated bindings, MODE_ALL",
384                PolicyEngineMode.MODE_ALL,
385                [
386                    {"group": group_parent, "negate": True},
387                    {"user": user, "negate": True},
388                ],
389            ),
390        ]
391
392        objs = []
393        for message, mode, binding_specs in scenarios:
394            pbm = PolicyBindingModel.objects.create(policy_engine_mode=mode)
395            for idx, spec in enumerate(binding_specs):
396                PolicyBinding.objects.create(target=pbm, order=idx, **spec)
397            objs.append((message, pbm))
398
399        qs = PolicyBindingModel.objects.filter(pk__in=[pbm.pk for _, pbm in objs])
400        engine = ListPolicyEngine(qs, user)
401        batch_passing = set(engine.build().result.values_list("pk", flat=True))
402
403        for message, pbm in objs:
404            with self.subTest(message):
405                single = PolicyEngine(pbm, user)
406                single.use_cache = False
407                expected = single.build().passing
408                self.assertEqual(
409                    pbm.pk in batch_passing,
410                    expected,
411                    f"{message}: mismatch",
412                )

ListPolicyEngine tests

def setUp(self):
26    def setUp(self):
27        clear_policy_cache()
28        self.policy_true = DummyPolicy.objects.create(
29            name=generate_id(), result=True, wait_min=0, wait_max=1
30        )
31        self.group_a = Group.objects.create(name=generate_id())
32        self.group_b = Group.objects.create(name=generate_id())
33        self.user = create_test_user()
34        self.user.groups.add(self.group_a)
35        self.obj_a = PolicyBindingModel.objects.create()
36        self.obj_b = PolicyBindingModel.objects.create()
37        self.obj_c = PolicyBindingModel.objects.create()
38        self.objs = PolicyBindingModel.objects.filter(
39            pk__in=[self.obj_a.pk, self.obj_b.pk, self.obj_c.pk]
40        )

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

def test_list_engine_empty(self):
42    def test_list_engine_empty(self):
43        """No bindings at all on any object -> empty_result decides"""
44        engine = ListPolicyEngine(self.objs, self.user)
45        self.assertEqual(
46            set(engine.build().result.values_list("pk", flat=True)),
47            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
48        )
49
50        engine = ListPolicyEngine(self.objs, self.user)
51        engine.empty_result = False
52        self.assertEqual(set(engine.build().result.values_list("pk", flat=True)), set())

No bindings at all on any object -> empty_result decides

def test_list_engine_static_group_any(self):
54    def test_list_engine_static_group_any(self):
55        """MODE_ANY static group binding, evaluated independently per object"""
56        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
57        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
58        engine = ListPolicyEngine(self.objs, self.user)
59        self.assertEqual(
60            set(engine.build().result.values_list("pk", flat=True)),
61            {self.obj_a.pk, self.obj_c.pk},
62        )

MODE_ANY static group binding, evaluated independently per object

def test_list_engine_static_group_all(self):
64    def test_list_engine_static_group_all(self):
65        """MODE_ALL with two group bindings on one object: only passes if user is in both"""
66        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
67        self.obj_a.save()
68        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
69        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=1)
70        engine = ListPolicyEngine(self.objs, self.user)
71        self.assertEqual(
72            set(engine.build().result.values_list("pk", flat=True)),
73            {self.obj_b.pk, self.obj_c.pk},
74        )

MODE_ALL with two group bindings on one object: only passes if user is in both

def test_list_engine_static_user_binding(self):
76    def test_list_engine_static_user_binding(self):
77        """Direct user binding"""
78        other_user = create_test_user()
79        PolicyBinding.objects.create(target=self.obj_a, user=self.user, order=0)
80        PolicyBinding.objects.create(target=self.obj_b, user=other_user, order=0)
81        engine = ListPolicyEngine(self.objs, self.user)
82        self.assertEqual(
83            set(engine.build().result.values_list("pk", flat=True)),
84            {self.obj_a.pk, self.obj_c.pk},
85        )

Direct user binding

def test_list_engine_negate(self):
87    def test_list_engine_negate(self):
88        """Negated group binding excludes members instead of including them"""
89        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, negate=True, order=0)
90        engine = ListPolicyEngine(self.objs, self.user)
91        self.assertEqual(
92            set(engine.build().result.values_list("pk", flat=True)),
93            {self.obj_b.pk, self.obj_c.pk},
94        )

Negated group binding excludes members instead of including them

def test_list_engine_group_hierarchy(self):
 96    def test_list_engine_group_hierarchy(self):
 97        """A binding on a parent group also matches a user only in a descendant group"""
 98        group_parent = Group.objects.create(name=generate_id())
 99        self.group_a.parents.add(group_parent)
100        PolicyBinding.objects.create(target=self.obj_a, group=group_parent, order=0)
101        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
102        engine = ListPolicyEngine(self.objs, self.user)
103        self.assertEqual(
104            set(engine.build().result.values_list("pk", flat=True)),
105            {self.obj_a.pk, self.obj_c.pk},
106        )

A binding on a parent group also matches a user only in a descendant group

def test_list_engine_policy_fallback(self):
108    def test_list_engine_policy_fallback(self):
109        """Real Policy bindings on different objects fall back to per-object evaluation
110        and are evaluated independently."""
111        policy_false = DummyPolicy.objects.create(
112            name=generate_id(), result=False, wait_min=0, wait_max=1
113        )
114        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=0)
115        PolicyBinding.objects.create(target=self.obj_b, policy=policy_false, order=0)
116        engine = ListPolicyEngine(self.objs, self.user)
117        self.assertEqual(
118            set(engine.build().result.values_list("pk", flat=True)),
119            {self.obj_a.pk, self.obj_c.pk},
120        )

Real Policy bindings on different objects fall back to per-object evaluation and are evaluated independently.

def test_list_engine_dry_run(self):
122    def test_list_engine_dry_run(self):
123        """Dry-run bindings do not affect the objects returned by the list engine."""
124        policy_false = DummyPolicy.objects.create(
125            name=generate_id(), result=False, wait_min=0, wait_max=1
126        )
127        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
128        self.obj_a.save()
129        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=0)
130        dry_run_a = PolicyBinding.objects.create(
131            target=self.obj_a, policy=policy_false, order=1, dry_run=True
132        )
133        PolicyBinding.objects.create(target=self.obj_b, group=self.group_b, order=0)
134        dry_run_b = PolicyBinding.objects.create(
135            target=self.obj_b, policy=self.policy_true, order=1, dry_run=True
136        )
137
138        result = ListPolicyEngine(self.objs, self.user).build().result
139
140        self.assertEqual(
141            set(result.values_list("pk", flat=True)),
142            {self.obj_c.pk},
143        )
144        self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run_a.policy_binding_uuid.hex}*")), 1)
145        self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run_b.policy_binding_uuid.hex}*")), 1)
146
147        with patch(
148            "authentik.policies.dummy.models.DummyPolicy.passes",
149            side_effect=AssertionError("cached dry-run policies should not be evaluated"),
150        ):
151            cached_result = ListPolicyEngine(self.objs, self.user).build().result
152        self.assertEqual(
153            set(cached_result.values_list("pk", flat=True)),
154            {self.obj_c.pk},
155        )

Dry-run bindings do not affect the objects returned by the list engine.

def test_list_engine_mode_all_static_prefilter_skips_dynamic(self):
157    def test_list_engine_mode_all_static_prefilter_skips_dynamic(self):
158        """MODE_ALL: a failing static binding must skip dynamic evaluation for that
159        object entirely."""
160        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
161        self.obj_a.save()
162        PolicyBinding.objects.create(target=self.obj_a, group=self.group_b, order=0)
163        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=1)
164        with patch(
165            "authentik.policies.dummy.models.DummyPolicy.passes",
166            side_effect=AssertionError("dynamic policy should not be evaluated"),
167        ):
168            engine = ListPolicyEngine(self.objs, self.user)
169            result = set(engine.build().result.values_list("pk", flat=True))
170        self.assertEqual(result, {self.obj_b.pk, self.obj_c.pk})

MODE_ALL: a failing static binding must skip dynamic evaluation for that object entirely.

def test_list_engine_mode_all_mixed_passes(self):
172    def test_list_engine_mode_all_mixed_passes(self):
173        """MODE_ALL with a passing static binding and a passing dynamic binding passes overall"""
174        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
175        self.obj_a.save()
176        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
177        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=1)
178        engine = ListPolicyEngine(self.objs, self.user)
179        self.assertEqual(
180            set(engine.build().result.values_list("pk", flat=True)),
181            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
182        )

MODE_ALL with a passing static binding and a passing dynamic binding passes overall

def test_list_engine_expired_static_binding_ignored(self):
184    def test_list_engine_expired_static_binding_ignored(self):
185        """An expired static binding is excluded from evaluation entirely"""
186        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
187        self.obj_a.save()
188        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
189        PolicyBinding.objects.create(
190            target=self.obj_a,
191            group=self.group_b,
192            order=1,
193            expiring=True,
194            expires=now() - timedelta(minutes=10),
195        )
196        engine = ListPolicyEngine(self.objs, self.user)
197        self.assertEqual(
198            set(engine.build().result.values_list("pk", flat=True)),
199            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
200        )

An expired static binding is excluded from evaluation entirely

def test_list_engine_expired_policy_binding_ignored(self):
202    def test_list_engine_expired_policy_binding_ignored(self):
203        """An expired real-Policy binding is excluded from evaluation entirely, even
204        though (were it not expired) it would force MODE_ALL to fail."""
205        policy_false = DummyPolicy.objects.create(
206            name=generate_id(), result=False, wait_min=0, wait_max=1
207        )
208        self.obj_a.policy_engine_mode = PolicyEngineMode.MODE_ALL
209        self.obj_a.save()
210        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
211        PolicyBinding.objects.create(
212            target=self.obj_a,
213            policy=policy_false,
214            order=1,
215            expiring=True,
216            expires=now() - timedelta(minutes=10),
217        )
218        engine = ListPolicyEngine(self.objs, self.user)
219        self.assertEqual(
220            set(engine.build().result.values_list("pk", flat=True)),
221            {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk},
222        )

An expired real-Policy binding is excluded from evaluation entirely, even though (were it not expired) it would force MODE_ALL to fail.

def test_list_engine_static_query_count_independent_of_object_count(self):
224    def test_list_engine_static_query_count_independent_of_object_count(self):
225        """Query count for the static-only path must not scale with the number of
226        objects."""
227        objs = [PolicyBindingModel.objects.create() for _ in range(50)]
228        for obj in objs:
229            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
230        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
231        engine = ListPolicyEngine(qs, self.user)
232        with CaptureQueriesContext(connections["default"]) as ctx:
233            result = set(engine.build().result.values_list("pk", flat=True))
234        self.assertLess(ctx.final_queries, 20)
235        self.assertEqual(result, {o.pk for o in objs})

Query count for the static-only path must not scale with the number of objects.

def test_list_engine_dynamic_query_count_independent_of_object_count(self):
237    def test_list_engine_dynamic_query_count_independent_of_object_count(self):
238        """The slow (per-object Policy) path must not re-fetch bindings, the static
239        aggregate, the cache, or the polymorphic `policy`/`target` FKs per object --
240        query count must stay O(1) regardless of the number of objects."""
241        small_objs = [PolicyBindingModel.objects.create() for _ in range(3)]
242        for obj in small_objs:
243            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
244            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=1)
245        small_qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in small_objs])
246
247        ListPolicyEngine(small_qs, self.user).build()  # warm cache
248        with CaptureQueriesContext(connections["default"]) as ctx_small:
249            list(ListPolicyEngine(small_qs, self.user).build().result)
250        baseline_queries = len(ctx_small.captured_queries)
251
252        extra_objs = [PolicyBindingModel.objects.create() for _ in range(50)]
253        for obj in extra_objs:
254            PolicyBinding.objects.create(target=obj, group=self.group_a, order=0)
255            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=1)
256        large_qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in small_objs + extra_objs])
257
258        ListPolicyEngine(large_qs, self.user).build()  # warm cache
259        with CaptureQueriesContext(connections["default"]) as ctx_large:
260            list(ListPolicyEngine(large_qs, self.user).build().result)
261
262        self.assertLessEqual(
263            len(ctx_large.captured_queries),
264            baseline_queries + 2,
265            (
266                f"Query count grew from {baseline_queries} to "
267                f"{len(ctx_large.captured_queries)} after adding {len(extra_objs)} objects "
268                "-- bindings/cache/static-resolution/FK lookups are being repeated per object."
269            ),
270        )

The slow (per-object Policy) path must not re-fetch bindings, the static aggregate, the cache, or the polymorphic policy/target FKs per object -- query count must stay O(1) regardless of the number of objects.

def test_list_engine_no_policy_engine_instantiated_for_static_path(self):
272    def test_list_engine_no_policy_engine_instantiated_for_static_path(self):
273        """Purely static bindings must never instantiate a per-object PolicyEngine."""
274        PolicyBinding.objects.create(target=self.obj_a, group=self.group_a, order=0)
275        with patch("authentik.policies.engine.PolicyEngine") as mock_engine:
276            engine = ListPolicyEngine(self.objs, self.user)
277            list(engine.build().result)
278        self.assertEqual(mock_engine.call_count, 0)

Purely static bindings must never instantiate a per-object PolicyEngine.

def test_list_engine_bulk_cache_prefetch_single_round_trip(self):
280    def test_list_engine_bulk_cache_prefetch_single_round_trip(self):
281        """The slow (per-object Policy) path must fetch cache entries via a single
282        cache.get_many() call instead of one cache.get() per (binding, object) pair."""
283        objs = [PolicyBindingModel.objects.create() for _ in range(3)]
284        for obj in objs:
285            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=0)
286        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
287
288        with (
289            patch(
290                "authentik.policies.engine.cache.get_many", wraps=cache.get_many
291            ) as mock_get_many,
292            patch("authentik.policies.engine.cache.get", wraps=cache.get) as mock_get,
293        ):
294            engine = ListPolicyEngine(qs, self.user)
295            result = set(engine.build().result.values_list("pk", flat=True))
296
297        self.assertEqual(result, {o.pk for o in objs})
298        mock_get_many.assert_called_once()
299        mock_get.assert_not_called()

The slow (per-object Policy) path must fetch cache entries via a single cache.get_many() call instead of one cache.get() per (binding, object) pair.

def test_list_engine_cache_reused_across_builds(self):
301    def test_list_engine_cache_reused_across_builds(self):
302        """A second ListPolicyEngine.build() must reuse the PolicyResults cached by the
303        first build (bulk-prefetched via one cache.get_many()) instead of re-evaluating
304        the (slow, per-object) DummyPolicy again."""
305        PolicyBinding.objects.create(target=self.obj_a, policy=self.policy_true, order=0)
306
307        first = set(
308            ListPolicyEngine(self.objs, self.user).build().result.values_list("pk", flat=True)
309        )
310        self.assertEqual(first, {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk})
311
312        with (
313            patch(
314                "authentik.policies.engine.cache.get_many", wraps=cache.get_many
315            ) as mock_get_many,
316            patch(
317                "authentik.policies.dummy.models.DummyPolicy.passes",
318                side_effect=AssertionError("policy should be served from cache, not re-evaluated"),
319            ),
320        ):
321            engine = ListPolicyEngine(self.objs, self.user)
322            second = set(engine.build().result.values_list("pk", flat=True))
323
324        self.assertEqual(second, {self.obj_a.pk, self.obj_b.pk, self.obj_c.pk})
325        mock_get_many.assert_called_once()

A second ListPolicyEngine.build() must reuse the PolicyResults cached by the first build (bulk-prefetched via one cache.get_many()) instead of re-evaluating the (slow, per-object) DummyPolicy again.

def test_list_engine_http_request_enriched_once(self):
327    def test_list_engine_http_request_enriched_once(self):
328        """set_http_request() (context/geoip enrichment) must be called exactly once
329        per build(), not once per object -- the fixed user/http_request means one
330        enriched PolicyRequest can be reused across every object."""
331        objs = [PolicyBindingModel.objects.create() for _ in range(5)]
332        for obj in objs:
333            PolicyBinding.objects.create(target=obj, policy=self.policy_true, order=0)
334        qs = PolicyBindingModel.objects.filter(pk__in=[o.pk for o in objs])
335        http_request = RequestFactory().get("/")
336        http_request.user = self.user
337
338        with patch(
339            "authentik.policies.engine.PolicyRequest.set_http_request", autospec=True
340        ) as mock_set:
341            engine = ListPolicyEngine(qs, self.user, http_request)
342            engine.build()
343        mock_set.assert_called_once()

set_http_request() (context/geoip enrichment) must be called exactly once per build(), not once per object -- the fixed user/http_request means one enriched PolicyRequest can be reused across every object.

def test_list_engine_matches_single_object_engine(self):
345    def test_list_engine_matches_single_object_engine(self):
346        """Cross-validate ListPolicyEngine's static-binding handling (negate, group
347        hierarchy, MODE_ALL/MODE_ANY) against the per-object PolicyEngine (the source
348        of truth), for a fixed user across a batch of objects.
349
350        This asserts *agreement* with PolicyEngine rather than hand-computed expected
351        sets, so it can't be wrong in the same way as the implementation being tested.
352        """
353        group_parent = Group.objects.create(name=generate_id())
354        group_child = Group.objects.create(name=generate_id())
355        group_child.parents.add(group_parent)
356        group_other = Group.objects.create(name=generate_id())
357
358        user = create_test_user()
359        user.groups.add(group_child)
360
361        scenarios = [
362            (
363                "negate group (with hierarchy)",
364                PolicyEngineMode.MODE_ANY,
365                [{"group": group_parent, "negate": True}],
366            ),
367            (
368                "negate user",
369                PolicyEngineMode.MODE_ANY,
370                [{"user": user, "negate": True}],
371            ),
372            (
373                "MODE_ALL negate + positive",
374                PolicyEngineMode.MODE_ALL,
375                [{"group": group_parent, "negate": True}, {"group": group_other}],
376            ),
377            (
378                "MODE_ANY negate + positive",
379                PolicyEngineMode.MODE_ANY,
380                [{"group": group_parent, "negate": True}, {"group": group_other}],
381            ),
382            (
383                "multiple negated bindings, MODE_ALL",
384                PolicyEngineMode.MODE_ALL,
385                [
386                    {"group": group_parent, "negate": True},
387                    {"user": user, "negate": True},
388                ],
389            ),
390        ]
391
392        objs = []
393        for message, mode, binding_specs in scenarios:
394            pbm = PolicyBindingModel.objects.create(policy_engine_mode=mode)
395            for idx, spec in enumerate(binding_specs):
396                PolicyBinding.objects.create(target=pbm, order=idx, **spec)
397            objs.append((message, pbm))
398
399        qs = PolicyBindingModel.objects.filter(pk__in=[pbm.pk for _, pbm in objs])
400        engine = ListPolicyEngine(qs, user)
401        batch_passing = set(engine.build().result.values_list("pk", flat=True))
402
403        for message, pbm in objs:
404            with self.subTest(message):
405                single = PolicyEngine(pbm, user)
406                single.use_cache = False
407                expected = single.build().passing
408                self.assertEqual(
409                    pbm.pk in batch_passing,
410                    expected,
411                    f"{message}: mismatch",
412                )

Cross-validate ListPolicyEngine's static-binding handling (negate, group hierarchy, MODE_ALL/MODE_ANY) against the per-object PolicyEngine (the source of truth), for a fixed user across a batch of objects.

This asserts agreement with PolicyEngine rather than hand-computed expected sets, so it can't be wrong in the same way as the implementation being tested.