authentik.policies.tests.test_engine_filter
policy engine tests
1"""policy engine 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 TestCase 9from django.test.utils import CaptureQueriesContext 10from django.utils.timezone import now 11 12from authentik.core.models import Actor, ActorPolicyInheritance, Group, User, UserTypes 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 FilterPolicyEngine, PolicyEngine 17from authentik.policies.models import PolicyBinding, PolicyBindingModel, PolicyEngineMode 18from authentik.policies.process import cache_key 19from authentik.policies.tests.test_process import clear_policy_cache 20from authentik.policies.types import CACHE_PREFIX, PolicyRequest 21 22 23class TestFilterPolicyEngine(TestCase): 24 """FilterPolicyEngine 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_a = create_test_user() 34 self.user_b = create_test_user() 35 self.user_c = create_test_user() 36 self.user_a.groups.add(self.group_a) 37 self.user_b.groups.add(self.group_a) 38 self.user_b.groups.add(self.group_b) 39 self.users = User.objects.filter(pk__in=[self.user_a.pk, self.user_b.pk, self.user_c.pk]) 40 41 def test_multi_engine_empty(self): 42 """No bindings at all -> empty_result decides""" 43 pbm = PolicyBindingModel.objects.create() 44 engine = FilterPolicyEngine(pbm, self.users) 45 self.assertEqual( 46 set(engine.build().result.values_list("pk", flat=True)), 47 {self.user_a.pk, self.user_b.pk, self.user_c.pk}, 48 ) 49 50 engine = FilterPolicyEngine(pbm, self.users) 51 engine.empty_result = False 52 self.assertEqual(set(engine.build().result.values_list("pk", flat=True)), set()) 53 54 def test_multi_engine_static_group_any(self): 55 """MODE_ANY static group binding""" 56 pbm = PolicyBindingModel.objects.create() 57 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 58 engine = FilterPolicyEngine(pbm, self.users) 59 self.assertEqual( 60 set(engine.build().result.values_list("pk", flat=True)), 61 {self.user_a.pk, self.user_b.pk}, 62 ) 63 64 def test_multi_engine_static_group_all(self): 65 """MODE_ALL with two group bindings: only members of both pass""" 66 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 67 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 68 PolicyBinding.objects.create(target=pbm, group=self.group_b, order=1) 69 engine = FilterPolicyEngine(pbm, self.users) 70 self.assertEqual( 71 set(engine.build().result.values_list("pk", flat=True)), 72 {self.user_b.pk}, 73 ) 74 75 def test_multi_engine_static_user_binding(self): 76 """Direct user binding""" 77 pbm = PolicyBindingModel.objects.create() 78 PolicyBinding.objects.create(target=pbm, user=self.user_c, order=0) 79 engine = FilterPolicyEngine(pbm, self.users) 80 self.assertEqual( 81 set(engine.build().result.values_list("pk", flat=True)), 82 {self.user_c.pk}, 83 ) 84 85 def test_multi_engine_negate(self): 86 """Negated group binding excludes members instead of including them""" 87 pbm = PolicyBindingModel.objects.create() 88 PolicyBinding.objects.create(target=pbm, group=self.group_a, negate=True, order=0) 89 engine = FilterPolicyEngine(pbm, self.users) 90 self.assertEqual( 91 set(engine.build().result.values_list("pk", flat=True)), 92 {self.user_c.pk}, 93 ) 94 95 def test_multi_engine_group_hierarchy(self): 96 """A binding on a parent group also matches users only in a descendant group""" 97 group_parent = Group.objects.create(name=generate_id()) 98 self.group_b.parents.add(group_parent) 99 pbm = PolicyBindingModel.objects.create() 100 PolicyBinding.objects.create(target=pbm, group=group_parent, order=0) 101 engine = FilterPolicyEngine(pbm, self.users) 102 # user_b is in group_b, a descendant of group_parent 103 self.assertEqual( 104 set(engine.build().result.values_list("pk", flat=True)), 105 {self.user_b.pk}, 106 ) 107 108 def test_multi_engine_policy_fallback(self): 109 """Real Policy bindings can't be translated to SQL and fall back to per-user 110 PolicyEngine evaluation; correctness must be preserved on this slow path.""" 111 pbm = PolicyBindingModel.objects.create() 112 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 113 engine = FilterPolicyEngine(pbm, self.users) 114 self.assertEqual( 115 set(engine.build().result.values_list("pk", flat=True)), 116 {self.user_a.pk, self.user_b.pk, self.user_c.pk}, 117 ) 118 119 def test_multi_engine_dry_run(self): 120 """Dry-run bindings do not affect filtered users.""" 121 policy_false = DummyPolicy.objects.create( 122 name=generate_id(), result=False, wait_min=0, wait_max=1 123 ) 124 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 125 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 126 dry_run = PolicyBinding.objects.create( 127 target=pbm, policy=policy_false, order=1, dry_run=True 128 ) 129 130 result = FilterPolicyEngine(pbm, self.users).build().result 131 132 self.assertEqual( 133 set(result.values_list("pk", flat=True)), 134 {self.user_a.pk, self.user_b.pk}, 135 ) 136 self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run.policy_binding_uuid.hex}*")), 3) 137 138 with patch( 139 "authentik.policies.dummy.models.DummyPolicy.passes", 140 side_effect=AssertionError("cached dry-run policy should not be evaluated"), 141 ): 142 cached_result = FilterPolicyEngine(pbm, self.users).build().result 143 self.assertEqual( 144 set(cached_result.values_list("pk", flat=True)), 145 {self.user_a.pk, self.user_b.pk}, 146 ) 147 148 def test_dry_run_prefetch_only_fetches_evaluated_pairs(self): 149 """Static-failing users need only dry-run cache entries, in one bulk read.""" 150 target = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 151 PolicyBinding.objects.create(target=target, group=self.group_a, order=0) 152 enforced = PolicyBinding.objects.create(target=target, policy=self.policy_true, order=1) 153 observed = PolicyBinding.objects.create( 154 target=target, policy=self.policy_true, order=2, dry_run=True 155 ) 156 with patch("authentik.policies.engine.cache.get_many", return_value={}) as get_many: 157 FilterPolicyEngine(target, self.users).build() 158 get_many.assert_called_once() 159 expected = { 160 cache_key(binding, PolicyRequest(user)) 161 for user, bindings in ( 162 (self.user_a, [enforced, observed]), 163 (self.user_b, [enforced, observed]), 164 (self.user_c, [observed]), 165 ) 166 for binding in bindings 167 } 168 self.assertEqual(set(get_many.call_args.args[0]), expected) 169 170 def test_multi_engine_mixed_static_and_policy_mode_all_prefilters(self): 171 """MODE_ALL with a static binding and a real policy: static binding restricts 172 the candidate set before per-user policy evaluation.""" 173 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 174 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 175 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=1) 176 engine = FilterPolicyEngine(pbm, self.users) 177 self.assertEqual( 178 set(engine.build().result.values_list("pk", flat=True)), 179 {self.user_a.pk, self.user_b.pk}, 180 ) 181 182 def test_multi_engine_static_query_count_independent_of_user_count(self): 183 """Query count for the static-only path must not scale with the number of 184 bindings or users -- it must be evaluated as a single SQL filter.""" 185 pbm = PolicyBindingModel.objects.create() 186 for x in range(1000): 187 PolicyBinding.objects.create(target=pbm, order=x, group=self.group_a) 188 engine = FilterPolicyEngine(pbm, self.users) 189 with CaptureQueriesContext(connections["default"]) as ctx: 190 result = set(engine.build().result.values_list("pk", flat=True)) 191 self.assertLess(ctx.final_queries, 1000) 192 self.assertEqual(result, {self.user_a.pk, self.user_b.pk}) 193 194 def test_dynamic_path_query_count_independent_of_user_count(self): 195 """The slow (per-user Policy) path must not re-fetch bindings or re-run the 196 static-binding aggregate per user -- query count must not scale with the 197 number of candidate users. 198 199 Cache backend here is DB-backed (django_postgres_cache), so a cache *write* 200 for a never-before-seen user is itself a DB INSERT -- that's an unavoidable, 201 real cost unrelated to what this test checks. Both runs are pre-warmed first 202 so the measured query count reflects only bindings/static-aggregate fetching 203 and cache *reads*, not first-time policy evaluation writes. 204 """ 205 pbm = PolicyBindingModel.objects.create() 206 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 207 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=1) 208 209 FilterPolicyEngine(pbm, self.users).build() # warm cache for the small set 210 with CaptureQueriesContext(connections["default"]) as ctx_small: 211 list(FilterPolicyEngine(pbm, self.users).build().result) 212 baseline_queries = len(ctx_small.captured_queries) 213 214 new_pks = [] 215 for _ in range(50): 216 uid = generate_id() 217 user = User.objects.create(username=uid, name=uid, email=f"{uid}@goauthentik.io") 218 user.groups.add(self.group_a) 219 new_pks.append(user.pk) 220 larger_users = User.objects.filter( 221 pk__in=[self.user_a.pk, self.user_b.pk, self.user_c.pk] + new_pks 222 ) 223 224 FilterPolicyEngine(pbm, larger_users).build() # warm cache for the larger set 225 with CaptureQueriesContext(connections["default"]) as ctx_large: 226 list(FilterPolicyEngine(pbm, larger_users).build().result) 227 228 self.assertLessEqual( 229 len(ctx_large.captured_queries), 230 baseline_queries + 2, 231 ( 232 f"Query count grew from {baseline_queries} to " 233 f"{len(ctx_large.captured_queries)} after adding 50 users -- bindings " 234 "or the static aggregate are being re-evaluated per user." 235 ), 236 ) 237 238 def test_multi_engine_no_policy_engine_instantiated_for_static_path(self): 239 """Purely static bindings must never instantiate a per-user PolicyEngine.""" 240 pbm = PolicyBindingModel.objects.create() 241 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 242 with patch("authentik.policies.engine.PolicyEngine") as mock_engine: 243 engine = FilterPolicyEngine(pbm, self.users) 244 list(engine.build().result) 245 self.assertEqual(mock_engine.call_count, 0) 246 247 def test_negate_matches_single_user_engine(self): 248 """Cross-validate FilterPolicyEngine's negated static-binding handling against 249 the per-user PolicyEngine (the source of truth for negate semantics), across 250 group hierarchy, user bindings, and MODE_ALL/MODE_ANY combinations. 251 252 This asserts *agreement* with PolicyEngine rather than hand-computed expected 253 sets, so it can't be wrong in the same way as the implementation being tested. 254 """ 255 group_parent = Group.objects.create(name=generate_id()) 256 group_child = Group.objects.create(name=generate_id()) 257 group_child.parents.add(group_parent) 258 group_other = Group.objects.create(name=generate_id()) 259 260 user_top = create_test_user() # member of group_parent directly 261 user_leaf = create_test_user() # member of group_child only (descendant of parent) 262 user_other = create_test_user() # member of group_other only 263 user_none = create_test_user() # no groups 264 user_multi = create_test_user() # member of group_child and group_other 265 266 user_top.groups.add(group_parent) 267 user_leaf.groups.add(group_child) 268 user_other.groups.add(group_other) 269 user_multi.groups.add(group_child) 270 user_multi.groups.add(group_other) 271 272 all_users = [user_top, user_leaf, user_other, user_none, user_multi] 273 users_qs = User.objects.filter(pk__in=[u.pk for u in all_users]) 274 275 scenarios = [ 276 ( 277 "negate group (with hierarchy)", 278 PolicyEngineMode.MODE_ANY, 279 [{"group": group_parent, "negate": True}], 280 ), 281 ( 282 "negate user", 283 PolicyEngineMode.MODE_ANY, 284 [{"user": user_leaf, "negate": True}], 285 ), 286 ( 287 "MODE_ALL negate + positive", 288 PolicyEngineMode.MODE_ALL, 289 [{"group": group_parent, "negate": True}, {"group": group_other}], 290 ), 291 ( 292 "MODE_ANY negate + positive", 293 PolicyEngineMode.MODE_ANY, 294 [{"group": group_parent, "negate": True}, {"group": group_other}], 295 ), 296 ( 297 "multiple negated bindings, MODE_ALL", 298 PolicyEngineMode.MODE_ALL, 299 [ 300 {"group": group_parent, "negate": True}, 301 {"user": user_other, "negate": True}, 302 ], 303 ), 304 ( 305 "multiple negated bindings, MODE_ANY", 306 PolicyEngineMode.MODE_ANY, 307 [ 308 {"group": group_parent, "negate": True}, 309 {"user": user_other, "negate": True}, 310 ], 311 ), 312 ] 313 314 for message, mode, binding_specs in scenarios: 315 with self.subTest(message): 316 pbm = PolicyBindingModel.objects.create(policy_engine_mode=mode) 317 for idx, spec in enumerate(binding_specs): 318 PolicyBinding.objects.create(target=pbm, order=idx, **spec) 319 320 engine = FilterPolicyEngine(pbm, users_qs) 321 batch_passing = set(engine.build().result.values_list("pk", flat=True)) 322 323 for user in all_users: 324 single = PolicyEngine(pbm, user) 325 single.use_cache = False 326 expected = single.build().passing 327 self.assertEqual( 328 user.pk in batch_passing, 329 expected, 330 f"{message}: mismatch for user {user.pk}", 331 ) 332 333 def test_bulk_cache_prefetch_single_round_trip(self): 334 """The slow (per-user Policy) path must fetch cache entries via a single 335 cache.get_many() call instead of one cache.get() per (binding, user) pair.""" 336 pbm = PolicyBindingModel.objects.create() 337 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 338 339 with ( 340 patch( 341 "authentik.policies.engine.cache.get_many", wraps=cache.get_many 342 ) as mock_get_many, 343 patch("authentik.policies.engine.cache.get", wraps=cache.get) as mock_get, 344 ): 345 engine = FilterPolicyEngine(pbm, self.users) 346 result = set(engine.build().result.values_list("pk", flat=True)) 347 348 self.assertEqual(result, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 349 mock_get_many.assert_called_once() 350 mock_get.assert_not_called() 351 352 def test_multi_engine_expired_static_binding_ignored(self): 353 """An expired static binding is excluded from evaluation entirely -- it must 354 not affect users who would otherwise pass via a still-active binding.""" 355 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 356 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 357 PolicyBinding.objects.create( 358 target=pbm, 359 group=self.group_b, 360 order=1, 361 expiring=True, 362 expires=now() - timedelta(minutes=10), 363 ) 364 engine = FilterPolicyEngine(pbm, self.users) 365 self.assertEqual( 366 set(engine.build().result.values_list("pk", flat=True)), 367 {self.user_a.pk, self.user_b.pk}, 368 ) 369 370 def test_multi_engine_expired_policy_binding_ignored(self): 371 """An expired real-Policy binding is excluded from evaluation entirely, even 372 though (were it not expired) it would force MODE_ALL to fail for everyone.""" 373 policy_false = DummyPolicy.objects.create( 374 name=generate_id(), result=False, wait_min=0, wait_max=1 375 ) 376 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 377 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 378 PolicyBinding.objects.create( 379 target=pbm, 380 policy=policy_false, 381 order=1, 382 expiring=True, 383 expires=now() - timedelta(minutes=10), 384 ) 385 engine = FilterPolicyEngine(pbm, self.users) 386 self.assertEqual( 387 set(engine.build().result.values_list("pk", flat=True)), 388 {self.user_a.pk, self.user_b.pk}, 389 ) 390 391 def test_cache_reused_across_builds(self): 392 """A second FilterPolicyEngine.build() must reuse the PolicyResults cached by 393 the first build (bulk-prefetched via one cache.get_many()) instead of 394 re-evaluating the (slow, per-user) DummyPolicy again.""" 395 pbm = PolicyBindingModel.objects.create() 396 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 397 398 # First build populates the cache (real DummyPolicy evaluation happens). 399 first = set(FilterPolicyEngine(pbm, self.users).build().result.values_list("pk", flat=True)) 400 self.assertEqual(first, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 401 402 with ( 403 patch( 404 "authentik.policies.engine.cache.get_many", wraps=cache.get_many 405 ) as mock_get_many, 406 patch( 407 "authentik.policies.dummy.models.DummyPolicy.passes", 408 side_effect=AssertionError("policy should be served from cache, not re-evaluated"), 409 ), 410 ): 411 engine = FilterPolicyEngine(pbm, self.users) 412 second = set(engine.build().result.values_list("pk", flat=True)) 413 414 self.assertEqual(second, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 415 mock_get_many.assert_called_once() 416 417 def _mirror_actor(self, parent: User | None) -> Actor: 418 uid = generate_id() 419 return Actor.objects.create( 420 username=uid, 421 name=uid, 422 email=f"{uid}@goauthentik.io", 423 parent=parent, 424 policy_behavior=ActorPolicyInheritance.MIRROR, 425 type=UserTypes.SERVICE_ACCOUNT, 426 ) 427 428 def test_mirror_actor_evaluated_as_parent(self): 429 """A MIRROR actor passes iff the identity it mirrors passes, folded into the same 430 evaluation -- no per-actor PolicyEngine is spawned on the static path.""" 431 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 432 actor_c = self._mirror_actor(self.user_c) # user_c is in no group 433 users = User.objects.filter(pk__in=[actor_a.pk, actor_c.pk, self.user_a.pk, self.user_c.pk]) 434 pbm = PolicyBindingModel.objects.create() 435 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 436 437 with patch("authentik.policies.engine.PolicyEngine") as mock_engine: 438 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 439 440 # actor_a mirrors user_a (in group_a) -> passes; actor_c mirrors user_c -> denied. 441 self.assertEqual(result, {self.user_a.pk, actor_a.pk}) 442 self.assertEqual(mock_engine.call_count, 0) 443 444 def test_mirror_actor_without_parent_in_set(self): 445 """The mirrored parent need not itself be in the queryset.""" 446 actor_a = self._mirror_actor(self.user_a) 447 users = User.objects.filter(pk__in=[actor_a.pk, self.user_c.pk]) 448 pbm = PolicyBindingModel.objects.create() 449 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 450 451 engine = FilterPolicyEngine(pbm, users) 452 result = set(engine.build().result.values_list("pk", flat=True)) 453 # Only the actor passes (via user_a's membership); user_a itself is not in the result set. 454 self.assertEqual(result, {actor_a.pk}) 455 456 def test_mirror_actor_query_count_independent_of_service_accounts(self): 457 """Finding MIRROR actors must not issue a query per service account in the set.""" 458 service_accounts = [create_test_user(type=UserTypes.SERVICE_ACCOUNT).pk for _ in range(25)] 459 actor_a = self._mirror_actor(self.user_a) 460 users = User.objects.filter(pk__in=[*service_accounts, actor_a.pk]) 461 pbm = PolicyBindingModel.objects.create() 462 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 463 464 engine = FilterPolicyEngine(pbm, users) 465 with CaptureQueriesContext(connections["default"]) as ctx: 466 result = set(engine.build().result.values_list("pk", flat=True)) 467 self.assertEqual(result, {actor_a.pk}) 468 self.assertLess(len(ctx.captured_queries), 15) 469 470 def test_mirror_actor_chain(self): 471 """An actor mirroring another MIRROR actor is evaluated as the end of the chain.""" 472 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 473 actor_of_actor = self._mirror_actor(actor_a) 474 actor_c = self._mirror_actor(self.user_c) # user_c is in no group 475 users = User.objects.filter(pk__in=[actor_of_actor.pk, actor_c.pk]) 476 pbm = PolicyBindingModel.objects.create() 477 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 478 479 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 480 self.assertEqual(result, {actor_of_actor.pk}) 481 482 def test_mirror_actor_without_parent_evaluated_as_itself(self): 483 """A MIRROR actor with no parent has nothing to mirror and is evaluated as itself.""" 484 actor = self._mirror_actor(None) 485 users = User.objects.filter(pk__in=[actor.pk]) 486 pbm = PolicyBindingModel.objects.create() 487 488 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 489 self.assertEqual(result, {actor.pk}) 490 491 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 492 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 493 self.assertEqual(result, set()) 494 495 def test_mirror_actor_expired(self): 496 """An expired MIRROR actor is hidden from the default Actor manager, so it does not 497 mirror its parent and is evaluated as itself.""" 498 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 499 actor_a.expiring = True 500 actor_a.expires = now() - timedelta(minutes=10) 501 actor_a.save() 502 users = User.objects.filter(pk__in=[actor_a.pk]) 503 pbm = PolicyBindingModel.objects.create() 504 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 505 506 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 507 self.assertEqual(result, set())
24class TestFilterPolicyEngine(TestCase): 25 """FilterPolicyEngine tests""" 26 27 def setUp(self): 28 clear_policy_cache() 29 self.policy_true = DummyPolicy.objects.create( 30 name=generate_id(), result=True, wait_min=0, wait_max=1 31 ) 32 self.group_a = Group.objects.create(name=generate_id()) 33 self.group_b = Group.objects.create(name=generate_id()) 34 self.user_a = create_test_user() 35 self.user_b = create_test_user() 36 self.user_c = create_test_user() 37 self.user_a.groups.add(self.group_a) 38 self.user_b.groups.add(self.group_a) 39 self.user_b.groups.add(self.group_b) 40 self.users = User.objects.filter(pk__in=[self.user_a.pk, self.user_b.pk, self.user_c.pk]) 41 42 def test_multi_engine_empty(self): 43 """No bindings at all -> empty_result decides""" 44 pbm = PolicyBindingModel.objects.create() 45 engine = FilterPolicyEngine(pbm, self.users) 46 self.assertEqual( 47 set(engine.build().result.values_list("pk", flat=True)), 48 {self.user_a.pk, self.user_b.pk, self.user_c.pk}, 49 ) 50 51 engine = FilterPolicyEngine(pbm, self.users) 52 engine.empty_result = False 53 self.assertEqual(set(engine.build().result.values_list("pk", flat=True)), set()) 54 55 def test_multi_engine_static_group_any(self): 56 """MODE_ANY static group binding""" 57 pbm = PolicyBindingModel.objects.create() 58 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 59 engine = FilterPolicyEngine(pbm, self.users) 60 self.assertEqual( 61 set(engine.build().result.values_list("pk", flat=True)), 62 {self.user_a.pk, self.user_b.pk}, 63 ) 64 65 def test_multi_engine_static_group_all(self): 66 """MODE_ALL with two group bindings: only members of both pass""" 67 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 68 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 69 PolicyBinding.objects.create(target=pbm, group=self.group_b, order=1) 70 engine = FilterPolicyEngine(pbm, self.users) 71 self.assertEqual( 72 set(engine.build().result.values_list("pk", flat=True)), 73 {self.user_b.pk}, 74 ) 75 76 def test_multi_engine_static_user_binding(self): 77 """Direct user binding""" 78 pbm = PolicyBindingModel.objects.create() 79 PolicyBinding.objects.create(target=pbm, user=self.user_c, order=0) 80 engine = FilterPolicyEngine(pbm, self.users) 81 self.assertEqual( 82 set(engine.build().result.values_list("pk", flat=True)), 83 {self.user_c.pk}, 84 ) 85 86 def test_multi_engine_negate(self): 87 """Negated group binding excludes members instead of including them""" 88 pbm = PolicyBindingModel.objects.create() 89 PolicyBinding.objects.create(target=pbm, group=self.group_a, negate=True, order=0) 90 engine = FilterPolicyEngine(pbm, self.users) 91 self.assertEqual( 92 set(engine.build().result.values_list("pk", flat=True)), 93 {self.user_c.pk}, 94 ) 95 96 def test_multi_engine_group_hierarchy(self): 97 """A binding on a parent group also matches users only in a descendant group""" 98 group_parent = Group.objects.create(name=generate_id()) 99 self.group_b.parents.add(group_parent) 100 pbm = PolicyBindingModel.objects.create() 101 PolicyBinding.objects.create(target=pbm, group=group_parent, order=0) 102 engine = FilterPolicyEngine(pbm, self.users) 103 # user_b is in group_b, a descendant of group_parent 104 self.assertEqual( 105 set(engine.build().result.values_list("pk", flat=True)), 106 {self.user_b.pk}, 107 ) 108 109 def test_multi_engine_policy_fallback(self): 110 """Real Policy bindings can't be translated to SQL and fall back to per-user 111 PolicyEngine evaluation; correctness must be preserved on this slow path.""" 112 pbm = PolicyBindingModel.objects.create() 113 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 114 engine = FilterPolicyEngine(pbm, self.users) 115 self.assertEqual( 116 set(engine.build().result.values_list("pk", flat=True)), 117 {self.user_a.pk, self.user_b.pk, self.user_c.pk}, 118 ) 119 120 def test_multi_engine_dry_run(self): 121 """Dry-run bindings do not affect filtered users.""" 122 policy_false = DummyPolicy.objects.create( 123 name=generate_id(), result=False, wait_min=0, wait_max=1 124 ) 125 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 126 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 127 dry_run = PolicyBinding.objects.create( 128 target=pbm, policy=policy_false, order=1, dry_run=True 129 ) 130 131 result = FilterPolicyEngine(pbm, self.users).build().result 132 133 self.assertEqual( 134 set(result.values_list("pk", flat=True)), 135 {self.user_a.pk, self.user_b.pk}, 136 ) 137 self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run.policy_binding_uuid.hex}*")), 3) 138 139 with patch( 140 "authentik.policies.dummy.models.DummyPolicy.passes", 141 side_effect=AssertionError("cached dry-run policy should not be evaluated"), 142 ): 143 cached_result = FilterPolicyEngine(pbm, self.users).build().result 144 self.assertEqual( 145 set(cached_result.values_list("pk", flat=True)), 146 {self.user_a.pk, self.user_b.pk}, 147 ) 148 149 def test_dry_run_prefetch_only_fetches_evaluated_pairs(self): 150 """Static-failing users need only dry-run cache entries, in one bulk read.""" 151 target = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 152 PolicyBinding.objects.create(target=target, group=self.group_a, order=0) 153 enforced = PolicyBinding.objects.create(target=target, policy=self.policy_true, order=1) 154 observed = PolicyBinding.objects.create( 155 target=target, policy=self.policy_true, order=2, dry_run=True 156 ) 157 with patch("authentik.policies.engine.cache.get_many", return_value={}) as get_many: 158 FilterPolicyEngine(target, self.users).build() 159 get_many.assert_called_once() 160 expected = { 161 cache_key(binding, PolicyRequest(user)) 162 for user, bindings in ( 163 (self.user_a, [enforced, observed]), 164 (self.user_b, [enforced, observed]), 165 (self.user_c, [observed]), 166 ) 167 for binding in bindings 168 } 169 self.assertEqual(set(get_many.call_args.args[0]), expected) 170 171 def test_multi_engine_mixed_static_and_policy_mode_all_prefilters(self): 172 """MODE_ALL with a static binding and a real policy: static binding restricts 173 the candidate set before per-user policy evaluation.""" 174 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 175 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 176 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=1) 177 engine = FilterPolicyEngine(pbm, self.users) 178 self.assertEqual( 179 set(engine.build().result.values_list("pk", flat=True)), 180 {self.user_a.pk, self.user_b.pk}, 181 ) 182 183 def test_multi_engine_static_query_count_independent_of_user_count(self): 184 """Query count for the static-only path must not scale with the number of 185 bindings or users -- it must be evaluated as a single SQL filter.""" 186 pbm = PolicyBindingModel.objects.create() 187 for x in range(1000): 188 PolicyBinding.objects.create(target=pbm, order=x, group=self.group_a) 189 engine = FilterPolicyEngine(pbm, self.users) 190 with CaptureQueriesContext(connections["default"]) as ctx: 191 result = set(engine.build().result.values_list("pk", flat=True)) 192 self.assertLess(ctx.final_queries, 1000) 193 self.assertEqual(result, {self.user_a.pk, self.user_b.pk}) 194 195 def test_dynamic_path_query_count_independent_of_user_count(self): 196 """The slow (per-user Policy) path must not re-fetch bindings or re-run the 197 static-binding aggregate per user -- query count must not scale with the 198 number of candidate users. 199 200 Cache backend here is DB-backed (django_postgres_cache), so a cache *write* 201 for a never-before-seen user is itself a DB INSERT -- that's an unavoidable, 202 real cost unrelated to what this test checks. Both runs are pre-warmed first 203 so the measured query count reflects only bindings/static-aggregate fetching 204 and cache *reads*, not first-time policy evaluation writes. 205 """ 206 pbm = PolicyBindingModel.objects.create() 207 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 208 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=1) 209 210 FilterPolicyEngine(pbm, self.users).build() # warm cache for the small set 211 with CaptureQueriesContext(connections["default"]) as ctx_small: 212 list(FilterPolicyEngine(pbm, self.users).build().result) 213 baseline_queries = len(ctx_small.captured_queries) 214 215 new_pks = [] 216 for _ in range(50): 217 uid = generate_id() 218 user = User.objects.create(username=uid, name=uid, email=f"{uid}@goauthentik.io") 219 user.groups.add(self.group_a) 220 new_pks.append(user.pk) 221 larger_users = User.objects.filter( 222 pk__in=[self.user_a.pk, self.user_b.pk, self.user_c.pk] + new_pks 223 ) 224 225 FilterPolicyEngine(pbm, larger_users).build() # warm cache for the larger set 226 with CaptureQueriesContext(connections["default"]) as ctx_large: 227 list(FilterPolicyEngine(pbm, larger_users).build().result) 228 229 self.assertLessEqual( 230 len(ctx_large.captured_queries), 231 baseline_queries + 2, 232 ( 233 f"Query count grew from {baseline_queries} to " 234 f"{len(ctx_large.captured_queries)} after adding 50 users -- bindings " 235 "or the static aggregate are being re-evaluated per user." 236 ), 237 ) 238 239 def test_multi_engine_no_policy_engine_instantiated_for_static_path(self): 240 """Purely static bindings must never instantiate a per-user PolicyEngine.""" 241 pbm = PolicyBindingModel.objects.create() 242 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 243 with patch("authentik.policies.engine.PolicyEngine") as mock_engine: 244 engine = FilterPolicyEngine(pbm, self.users) 245 list(engine.build().result) 246 self.assertEqual(mock_engine.call_count, 0) 247 248 def test_negate_matches_single_user_engine(self): 249 """Cross-validate FilterPolicyEngine's negated static-binding handling against 250 the per-user PolicyEngine (the source of truth for negate semantics), across 251 group hierarchy, user bindings, and MODE_ALL/MODE_ANY combinations. 252 253 This asserts *agreement* with PolicyEngine rather than hand-computed expected 254 sets, so it can't be wrong in the same way as the implementation being tested. 255 """ 256 group_parent = Group.objects.create(name=generate_id()) 257 group_child = Group.objects.create(name=generate_id()) 258 group_child.parents.add(group_parent) 259 group_other = Group.objects.create(name=generate_id()) 260 261 user_top = create_test_user() # member of group_parent directly 262 user_leaf = create_test_user() # member of group_child only (descendant of parent) 263 user_other = create_test_user() # member of group_other only 264 user_none = create_test_user() # no groups 265 user_multi = create_test_user() # member of group_child and group_other 266 267 user_top.groups.add(group_parent) 268 user_leaf.groups.add(group_child) 269 user_other.groups.add(group_other) 270 user_multi.groups.add(group_child) 271 user_multi.groups.add(group_other) 272 273 all_users = [user_top, user_leaf, user_other, user_none, user_multi] 274 users_qs = User.objects.filter(pk__in=[u.pk for u in all_users]) 275 276 scenarios = [ 277 ( 278 "negate group (with hierarchy)", 279 PolicyEngineMode.MODE_ANY, 280 [{"group": group_parent, "negate": True}], 281 ), 282 ( 283 "negate user", 284 PolicyEngineMode.MODE_ANY, 285 [{"user": user_leaf, "negate": True}], 286 ), 287 ( 288 "MODE_ALL negate + positive", 289 PolicyEngineMode.MODE_ALL, 290 [{"group": group_parent, "negate": True}, {"group": group_other}], 291 ), 292 ( 293 "MODE_ANY negate + positive", 294 PolicyEngineMode.MODE_ANY, 295 [{"group": group_parent, "negate": True}, {"group": group_other}], 296 ), 297 ( 298 "multiple negated bindings, MODE_ALL", 299 PolicyEngineMode.MODE_ALL, 300 [ 301 {"group": group_parent, "negate": True}, 302 {"user": user_other, "negate": True}, 303 ], 304 ), 305 ( 306 "multiple negated bindings, MODE_ANY", 307 PolicyEngineMode.MODE_ANY, 308 [ 309 {"group": group_parent, "negate": True}, 310 {"user": user_other, "negate": True}, 311 ], 312 ), 313 ] 314 315 for message, mode, binding_specs in scenarios: 316 with self.subTest(message): 317 pbm = PolicyBindingModel.objects.create(policy_engine_mode=mode) 318 for idx, spec in enumerate(binding_specs): 319 PolicyBinding.objects.create(target=pbm, order=idx, **spec) 320 321 engine = FilterPolicyEngine(pbm, users_qs) 322 batch_passing = set(engine.build().result.values_list("pk", flat=True)) 323 324 for user in all_users: 325 single = PolicyEngine(pbm, user) 326 single.use_cache = False 327 expected = single.build().passing 328 self.assertEqual( 329 user.pk in batch_passing, 330 expected, 331 f"{message}: mismatch for user {user.pk}", 332 ) 333 334 def test_bulk_cache_prefetch_single_round_trip(self): 335 """The slow (per-user Policy) path must fetch cache entries via a single 336 cache.get_many() call instead of one cache.get() per (binding, user) pair.""" 337 pbm = PolicyBindingModel.objects.create() 338 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 339 340 with ( 341 patch( 342 "authentik.policies.engine.cache.get_many", wraps=cache.get_many 343 ) as mock_get_many, 344 patch("authentik.policies.engine.cache.get", wraps=cache.get) as mock_get, 345 ): 346 engine = FilterPolicyEngine(pbm, self.users) 347 result = set(engine.build().result.values_list("pk", flat=True)) 348 349 self.assertEqual(result, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 350 mock_get_many.assert_called_once() 351 mock_get.assert_not_called() 352 353 def test_multi_engine_expired_static_binding_ignored(self): 354 """An expired static binding is excluded from evaluation entirely -- it must 355 not affect users who would otherwise pass via a still-active binding.""" 356 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 357 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 358 PolicyBinding.objects.create( 359 target=pbm, 360 group=self.group_b, 361 order=1, 362 expiring=True, 363 expires=now() - timedelta(minutes=10), 364 ) 365 engine = FilterPolicyEngine(pbm, self.users) 366 self.assertEqual( 367 set(engine.build().result.values_list("pk", flat=True)), 368 {self.user_a.pk, self.user_b.pk}, 369 ) 370 371 def test_multi_engine_expired_policy_binding_ignored(self): 372 """An expired real-Policy binding is excluded from evaluation entirely, even 373 though (were it not expired) it would force MODE_ALL to fail for everyone.""" 374 policy_false = DummyPolicy.objects.create( 375 name=generate_id(), result=False, wait_min=0, wait_max=1 376 ) 377 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 378 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 379 PolicyBinding.objects.create( 380 target=pbm, 381 policy=policy_false, 382 order=1, 383 expiring=True, 384 expires=now() - timedelta(minutes=10), 385 ) 386 engine = FilterPolicyEngine(pbm, self.users) 387 self.assertEqual( 388 set(engine.build().result.values_list("pk", flat=True)), 389 {self.user_a.pk, self.user_b.pk}, 390 ) 391 392 def test_cache_reused_across_builds(self): 393 """A second FilterPolicyEngine.build() must reuse the PolicyResults cached by 394 the first build (bulk-prefetched via one cache.get_many()) instead of 395 re-evaluating the (slow, per-user) DummyPolicy again.""" 396 pbm = PolicyBindingModel.objects.create() 397 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 398 399 # First build populates the cache (real DummyPolicy evaluation happens). 400 first = set(FilterPolicyEngine(pbm, self.users).build().result.values_list("pk", flat=True)) 401 self.assertEqual(first, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 402 403 with ( 404 patch( 405 "authentik.policies.engine.cache.get_many", wraps=cache.get_many 406 ) as mock_get_many, 407 patch( 408 "authentik.policies.dummy.models.DummyPolicy.passes", 409 side_effect=AssertionError("policy should be served from cache, not re-evaluated"), 410 ), 411 ): 412 engine = FilterPolicyEngine(pbm, self.users) 413 second = set(engine.build().result.values_list("pk", flat=True)) 414 415 self.assertEqual(second, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 416 mock_get_many.assert_called_once() 417 418 def _mirror_actor(self, parent: User | None) -> Actor: 419 uid = generate_id() 420 return Actor.objects.create( 421 username=uid, 422 name=uid, 423 email=f"{uid}@goauthentik.io", 424 parent=parent, 425 policy_behavior=ActorPolicyInheritance.MIRROR, 426 type=UserTypes.SERVICE_ACCOUNT, 427 ) 428 429 def test_mirror_actor_evaluated_as_parent(self): 430 """A MIRROR actor passes iff the identity it mirrors passes, folded into the same 431 evaluation -- no per-actor PolicyEngine is spawned on the static path.""" 432 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 433 actor_c = self._mirror_actor(self.user_c) # user_c is in no group 434 users = User.objects.filter(pk__in=[actor_a.pk, actor_c.pk, self.user_a.pk, self.user_c.pk]) 435 pbm = PolicyBindingModel.objects.create() 436 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 437 438 with patch("authentik.policies.engine.PolicyEngine") as mock_engine: 439 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 440 441 # actor_a mirrors user_a (in group_a) -> passes; actor_c mirrors user_c -> denied. 442 self.assertEqual(result, {self.user_a.pk, actor_a.pk}) 443 self.assertEqual(mock_engine.call_count, 0) 444 445 def test_mirror_actor_without_parent_in_set(self): 446 """The mirrored parent need not itself be in the queryset.""" 447 actor_a = self._mirror_actor(self.user_a) 448 users = User.objects.filter(pk__in=[actor_a.pk, self.user_c.pk]) 449 pbm = PolicyBindingModel.objects.create() 450 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 451 452 engine = FilterPolicyEngine(pbm, users) 453 result = set(engine.build().result.values_list("pk", flat=True)) 454 # Only the actor passes (via user_a's membership); user_a itself is not in the result set. 455 self.assertEqual(result, {actor_a.pk}) 456 457 def test_mirror_actor_query_count_independent_of_service_accounts(self): 458 """Finding MIRROR actors must not issue a query per service account in the set.""" 459 service_accounts = [create_test_user(type=UserTypes.SERVICE_ACCOUNT).pk for _ in range(25)] 460 actor_a = self._mirror_actor(self.user_a) 461 users = User.objects.filter(pk__in=[*service_accounts, actor_a.pk]) 462 pbm = PolicyBindingModel.objects.create() 463 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 464 465 engine = FilterPolicyEngine(pbm, users) 466 with CaptureQueriesContext(connections["default"]) as ctx: 467 result = set(engine.build().result.values_list("pk", flat=True)) 468 self.assertEqual(result, {actor_a.pk}) 469 self.assertLess(len(ctx.captured_queries), 15) 470 471 def test_mirror_actor_chain(self): 472 """An actor mirroring another MIRROR actor is evaluated as the end of the chain.""" 473 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 474 actor_of_actor = self._mirror_actor(actor_a) 475 actor_c = self._mirror_actor(self.user_c) # user_c is in no group 476 users = User.objects.filter(pk__in=[actor_of_actor.pk, actor_c.pk]) 477 pbm = PolicyBindingModel.objects.create() 478 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 479 480 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 481 self.assertEqual(result, {actor_of_actor.pk}) 482 483 def test_mirror_actor_without_parent_evaluated_as_itself(self): 484 """A MIRROR actor with no parent has nothing to mirror and is evaluated as itself.""" 485 actor = self._mirror_actor(None) 486 users = User.objects.filter(pk__in=[actor.pk]) 487 pbm = PolicyBindingModel.objects.create() 488 489 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 490 self.assertEqual(result, {actor.pk}) 491 492 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 493 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 494 self.assertEqual(result, set()) 495 496 def test_mirror_actor_expired(self): 497 """An expired MIRROR actor is hidden from the default Actor manager, so it does not 498 mirror its parent and is evaluated as itself.""" 499 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 500 actor_a.expiring = True 501 actor_a.expires = now() - timedelta(minutes=10) 502 actor_a.save() 503 users = User.objects.filter(pk__in=[actor_a.pk]) 504 pbm = PolicyBindingModel.objects.create() 505 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 506 507 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 508 self.assertEqual(result, set())
FilterPolicyEngine tests
27 def setUp(self): 28 clear_policy_cache() 29 self.policy_true = DummyPolicy.objects.create( 30 name=generate_id(), result=True, wait_min=0, wait_max=1 31 ) 32 self.group_a = Group.objects.create(name=generate_id()) 33 self.group_b = Group.objects.create(name=generate_id()) 34 self.user_a = create_test_user() 35 self.user_b = create_test_user() 36 self.user_c = create_test_user() 37 self.user_a.groups.add(self.group_a) 38 self.user_b.groups.add(self.group_a) 39 self.user_b.groups.add(self.group_b) 40 self.users = User.objects.filter(pk__in=[self.user_a.pk, self.user_b.pk, self.user_c.pk])
Hook method for setting up the test fixture before exercising it.
42 def test_multi_engine_empty(self): 43 """No bindings at all -> empty_result decides""" 44 pbm = PolicyBindingModel.objects.create() 45 engine = FilterPolicyEngine(pbm, self.users) 46 self.assertEqual( 47 set(engine.build().result.values_list("pk", flat=True)), 48 {self.user_a.pk, self.user_b.pk, self.user_c.pk}, 49 ) 50 51 engine = FilterPolicyEngine(pbm, self.users) 52 engine.empty_result = False 53 self.assertEqual(set(engine.build().result.values_list("pk", flat=True)), set())
No bindings at all -> empty_result decides
55 def test_multi_engine_static_group_any(self): 56 """MODE_ANY static group binding""" 57 pbm = PolicyBindingModel.objects.create() 58 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 59 engine = FilterPolicyEngine(pbm, self.users) 60 self.assertEqual( 61 set(engine.build().result.values_list("pk", flat=True)), 62 {self.user_a.pk, self.user_b.pk}, 63 )
MODE_ANY static group binding
65 def test_multi_engine_static_group_all(self): 66 """MODE_ALL with two group bindings: only members of both pass""" 67 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 68 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 69 PolicyBinding.objects.create(target=pbm, group=self.group_b, order=1) 70 engine = FilterPolicyEngine(pbm, self.users) 71 self.assertEqual( 72 set(engine.build().result.values_list("pk", flat=True)), 73 {self.user_b.pk}, 74 )
MODE_ALL with two group bindings: only members of both pass
76 def test_multi_engine_static_user_binding(self): 77 """Direct user binding""" 78 pbm = PolicyBindingModel.objects.create() 79 PolicyBinding.objects.create(target=pbm, user=self.user_c, order=0) 80 engine = FilterPolicyEngine(pbm, self.users) 81 self.assertEqual( 82 set(engine.build().result.values_list("pk", flat=True)), 83 {self.user_c.pk}, 84 )
Direct user binding
86 def test_multi_engine_negate(self): 87 """Negated group binding excludes members instead of including them""" 88 pbm = PolicyBindingModel.objects.create() 89 PolicyBinding.objects.create(target=pbm, group=self.group_a, negate=True, order=0) 90 engine = FilterPolicyEngine(pbm, self.users) 91 self.assertEqual( 92 set(engine.build().result.values_list("pk", flat=True)), 93 {self.user_c.pk}, 94 )
Negated group binding excludes members instead of including them
96 def test_multi_engine_group_hierarchy(self): 97 """A binding on a parent group also matches users only in a descendant group""" 98 group_parent = Group.objects.create(name=generate_id()) 99 self.group_b.parents.add(group_parent) 100 pbm = PolicyBindingModel.objects.create() 101 PolicyBinding.objects.create(target=pbm, group=group_parent, order=0) 102 engine = FilterPolicyEngine(pbm, self.users) 103 # user_b is in group_b, a descendant of group_parent 104 self.assertEqual( 105 set(engine.build().result.values_list("pk", flat=True)), 106 {self.user_b.pk}, 107 )
A binding on a parent group also matches users only in a descendant group
109 def test_multi_engine_policy_fallback(self): 110 """Real Policy bindings can't be translated to SQL and fall back to per-user 111 PolicyEngine evaluation; correctness must be preserved on this slow path.""" 112 pbm = PolicyBindingModel.objects.create() 113 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 114 engine = FilterPolicyEngine(pbm, self.users) 115 self.assertEqual( 116 set(engine.build().result.values_list("pk", flat=True)), 117 {self.user_a.pk, self.user_b.pk, self.user_c.pk}, 118 )
Real Policy bindings can't be translated to SQL and fall back to per-user PolicyEngine evaluation; correctness must be preserved on this slow path.
120 def test_multi_engine_dry_run(self): 121 """Dry-run bindings do not affect filtered users.""" 122 policy_false = DummyPolicy.objects.create( 123 name=generate_id(), result=False, wait_min=0, wait_max=1 124 ) 125 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 126 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 127 dry_run = PolicyBinding.objects.create( 128 target=pbm, policy=policy_false, order=1, dry_run=True 129 ) 130 131 result = FilterPolicyEngine(pbm, self.users).build().result 132 133 self.assertEqual( 134 set(result.values_list("pk", flat=True)), 135 {self.user_a.pk, self.user_b.pk}, 136 ) 137 self.assertEqual(len(cache.keys(f"{CACHE_PREFIX}{dry_run.policy_binding_uuid.hex}*")), 3) 138 139 with patch( 140 "authentik.policies.dummy.models.DummyPolicy.passes", 141 side_effect=AssertionError("cached dry-run policy should not be evaluated"), 142 ): 143 cached_result = FilterPolicyEngine(pbm, self.users).build().result 144 self.assertEqual( 145 set(cached_result.values_list("pk", flat=True)), 146 {self.user_a.pk, self.user_b.pk}, 147 )
Dry-run bindings do not affect filtered users.
149 def test_dry_run_prefetch_only_fetches_evaluated_pairs(self): 150 """Static-failing users need only dry-run cache entries, in one bulk read.""" 151 target = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 152 PolicyBinding.objects.create(target=target, group=self.group_a, order=0) 153 enforced = PolicyBinding.objects.create(target=target, policy=self.policy_true, order=1) 154 observed = PolicyBinding.objects.create( 155 target=target, policy=self.policy_true, order=2, dry_run=True 156 ) 157 with patch("authentik.policies.engine.cache.get_many", return_value={}) as get_many: 158 FilterPolicyEngine(target, self.users).build() 159 get_many.assert_called_once() 160 expected = { 161 cache_key(binding, PolicyRequest(user)) 162 for user, bindings in ( 163 (self.user_a, [enforced, observed]), 164 (self.user_b, [enforced, observed]), 165 (self.user_c, [observed]), 166 ) 167 for binding in bindings 168 } 169 self.assertEqual(set(get_many.call_args.args[0]), expected)
Static-failing users need only dry-run cache entries, in one bulk read.
171 def test_multi_engine_mixed_static_and_policy_mode_all_prefilters(self): 172 """MODE_ALL with a static binding and a real policy: static binding restricts 173 the candidate set before per-user policy evaluation.""" 174 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 175 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 176 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=1) 177 engine = FilterPolicyEngine(pbm, self.users) 178 self.assertEqual( 179 set(engine.build().result.values_list("pk", flat=True)), 180 {self.user_a.pk, self.user_b.pk}, 181 )
MODE_ALL with a static binding and a real policy: static binding restricts the candidate set before per-user policy evaluation.
183 def test_multi_engine_static_query_count_independent_of_user_count(self): 184 """Query count for the static-only path must not scale with the number of 185 bindings or users -- it must be evaluated as a single SQL filter.""" 186 pbm = PolicyBindingModel.objects.create() 187 for x in range(1000): 188 PolicyBinding.objects.create(target=pbm, order=x, group=self.group_a) 189 engine = FilterPolicyEngine(pbm, self.users) 190 with CaptureQueriesContext(connections["default"]) as ctx: 191 result = set(engine.build().result.values_list("pk", flat=True)) 192 self.assertLess(ctx.final_queries, 1000) 193 self.assertEqual(result, {self.user_a.pk, self.user_b.pk})
Query count for the static-only path must not scale with the number of bindings or users -- it must be evaluated as a single SQL filter.
195 def test_dynamic_path_query_count_independent_of_user_count(self): 196 """The slow (per-user Policy) path must not re-fetch bindings or re-run the 197 static-binding aggregate per user -- query count must not scale with the 198 number of candidate users. 199 200 Cache backend here is DB-backed (django_postgres_cache), so a cache *write* 201 for a never-before-seen user is itself a DB INSERT -- that's an unavoidable, 202 real cost unrelated to what this test checks. Both runs are pre-warmed first 203 so the measured query count reflects only bindings/static-aggregate fetching 204 and cache *reads*, not first-time policy evaluation writes. 205 """ 206 pbm = PolicyBindingModel.objects.create() 207 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 208 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=1) 209 210 FilterPolicyEngine(pbm, self.users).build() # warm cache for the small set 211 with CaptureQueriesContext(connections["default"]) as ctx_small: 212 list(FilterPolicyEngine(pbm, self.users).build().result) 213 baseline_queries = len(ctx_small.captured_queries) 214 215 new_pks = [] 216 for _ in range(50): 217 uid = generate_id() 218 user = User.objects.create(username=uid, name=uid, email=f"{uid}@goauthentik.io") 219 user.groups.add(self.group_a) 220 new_pks.append(user.pk) 221 larger_users = User.objects.filter( 222 pk__in=[self.user_a.pk, self.user_b.pk, self.user_c.pk] + new_pks 223 ) 224 225 FilterPolicyEngine(pbm, larger_users).build() # warm cache for the larger set 226 with CaptureQueriesContext(connections["default"]) as ctx_large: 227 list(FilterPolicyEngine(pbm, larger_users).build().result) 228 229 self.assertLessEqual( 230 len(ctx_large.captured_queries), 231 baseline_queries + 2, 232 ( 233 f"Query count grew from {baseline_queries} to " 234 f"{len(ctx_large.captured_queries)} after adding 50 users -- bindings " 235 "or the static aggregate are being re-evaluated per user." 236 ), 237 )
The slow (per-user Policy) path must not re-fetch bindings or re-run the static-binding aggregate per user -- query count must not scale with the number of candidate users.
Cache backend here is DB-backed (django_postgres_cache), so a cache write for a never-before-seen user is itself a DB INSERT -- that's an unavoidable, real cost unrelated to what this test checks. Both runs are pre-warmed first so the measured query count reflects only bindings/static-aggregate fetching and cache reads, not first-time policy evaluation writes.
239 def test_multi_engine_no_policy_engine_instantiated_for_static_path(self): 240 """Purely static bindings must never instantiate a per-user PolicyEngine.""" 241 pbm = PolicyBindingModel.objects.create() 242 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 243 with patch("authentik.policies.engine.PolicyEngine") as mock_engine: 244 engine = FilterPolicyEngine(pbm, self.users) 245 list(engine.build().result) 246 self.assertEqual(mock_engine.call_count, 0)
Purely static bindings must never instantiate a per-user PolicyEngine.
248 def test_negate_matches_single_user_engine(self): 249 """Cross-validate FilterPolicyEngine's negated static-binding handling against 250 the per-user PolicyEngine (the source of truth for negate semantics), across 251 group hierarchy, user bindings, and MODE_ALL/MODE_ANY combinations. 252 253 This asserts *agreement* with PolicyEngine rather than hand-computed expected 254 sets, so it can't be wrong in the same way as the implementation being tested. 255 """ 256 group_parent = Group.objects.create(name=generate_id()) 257 group_child = Group.objects.create(name=generate_id()) 258 group_child.parents.add(group_parent) 259 group_other = Group.objects.create(name=generate_id()) 260 261 user_top = create_test_user() # member of group_parent directly 262 user_leaf = create_test_user() # member of group_child only (descendant of parent) 263 user_other = create_test_user() # member of group_other only 264 user_none = create_test_user() # no groups 265 user_multi = create_test_user() # member of group_child and group_other 266 267 user_top.groups.add(group_parent) 268 user_leaf.groups.add(group_child) 269 user_other.groups.add(group_other) 270 user_multi.groups.add(group_child) 271 user_multi.groups.add(group_other) 272 273 all_users = [user_top, user_leaf, user_other, user_none, user_multi] 274 users_qs = User.objects.filter(pk__in=[u.pk for u in all_users]) 275 276 scenarios = [ 277 ( 278 "negate group (with hierarchy)", 279 PolicyEngineMode.MODE_ANY, 280 [{"group": group_parent, "negate": True}], 281 ), 282 ( 283 "negate user", 284 PolicyEngineMode.MODE_ANY, 285 [{"user": user_leaf, "negate": True}], 286 ), 287 ( 288 "MODE_ALL negate + positive", 289 PolicyEngineMode.MODE_ALL, 290 [{"group": group_parent, "negate": True}, {"group": group_other}], 291 ), 292 ( 293 "MODE_ANY negate + positive", 294 PolicyEngineMode.MODE_ANY, 295 [{"group": group_parent, "negate": True}, {"group": group_other}], 296 ), 297 ( 298 "multiple negated bindings, MODE_ALL", 299 PolicyEngineMode.MODE_ALL, 300 [ 301 {"group": group_parent, "negate": True}, 302 {"user": user_other, "negate": True}, 303 ], 304 ), 305 ( 306 "multiple negated bindings, MODE_ANY", 307 PolicyEngineMode.MODE_ANY, 308 [ 309 {"group": group_parent, "negate": True}, 310 {"user": user_other, "negate": True}, 311 ], 312 ), 313 ] 314 315 for message, mode, binding_specs in scenarios: 316 with self.subTest(message): 317 pbm = PolicyBindingModel.objects.create(policy_engine_mode=mode) 318 for idx, spec in enumerate(binding_specs): 319 PolicyBinding.objects.create(target=pbm, order=idx, **spec) 320 321 engine = FilterPolicyEngine(pbm, users_qs) 322 batch_passing = set(engine.build().result.values_list("pk", flat=True)) 323 324 for user in all_users: 325 single = PolicyEngine(pbm, user) 326 single.use_cache = False 327 expected = single.build().passing 328 self.assertEqual( 329 user.pk in batch_passing, 330 expected, 331 f"{message}: mismatch for user {user.pk}", 332 )
Cross-validate FilterPolicyEngine's negated static-binding handling against the per-user PolicyEngine (the source of truth for negate semantics), across group hierarchy, user bindings, and MODE_ALL/MODE_ANY combinations.
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.
334 def test_bulk_cache_prefetch_single_round_trip(self): 335 """The slow (per-user Policy) path must fetch cache entries via a single 336 cache.get_many() call instead of one cache.get() per (binding, user) pair.""" 337 pbm = PolicyBindingModel.objects.create() 338 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 339 340 with ( 341 patch( 342 "authentik.policies.engine.cache.get_many", wraps=cache.get_many 343 ) as mock_get_many, 344 patch("authentik.policies.engine.cache.get", wraps=cache.get) as mock_get, 345 ): 346 engine = FilterPolicyEngine(pbm, self.users) 347 result = set(engine.build().result.values_list("pk", flat=True)) 348 349 self.assertEqual(result, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 350 mock_get_many.assert_called_once() 351 mock_get.assert_not_called()
The slow (per-user Policy) path must fetch cache entries via a single cache.get_many() call instead of one cache.get() per (binding, user) pair.
353 def test_multi_engine_expired_static_binding_ignored(self): 354 """An expired static binding is excluded from evaluation entirely -- it must 355 not affect users who would otherwise pass via a still-active binding.""" 356 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 357 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 358 PolicyBinding.objects.create( 359 target=pbm, 360 group=self.group_b, 361 order=1, 362 expiring=True, 363 expires=now() - timedelta(minutes=10), 364 ) 365 engine = FilterPolicyEngine(pbm, self.users) 366 self.assertEqual( 367 set(engine.build().result.values_list("pk", flat=True)), 368 {self.user_a.pk, self.user_b.pk}, 369 )
An expired static binding is excluded from evaluation entirely -- it must not affect users who would otherwise pass via a still-active binding.
371 def test_multi_engine_expired_policy_binding_ignored(self): 372 """An expired real-Policy binding is excluded from evaluation entirely, even 373 though (were it not expired) it would force MODE_ALL to fail for everyone.""" 374 policy_false = DummyPolicy.objects.create( 375 name=generate_id(), result=False, wait_min=0, wait_max=1 376 ) 377 pbm = PolicyBindingModel.objects.create(policy_engine_mode=PolicyEngineMode.MODE_ALL) 378 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 379 PolicyBinding.objects.create( 380 target=pbm, 381 policy=policy_false, 382 order=1, 383 expiring=True, 384 expires=now() - timedelta(minutes=10), 385 ) 386 engine = FilterPolicyEngine(pbm, self.users) 387 self.assertEqual( 388 set(engine.build().result.values_list("pk", flat=True)), 389 {self.user_a.pk, self.user_b.pk}, 390 )
An expired real-Policy binding is excluded from evaluation entirely, even though (were it not expired) it would force MODE_ALL to fail for everyone.
392 def test_cache_reused_across_builds(self): 393 """A second FilterPolicyEngine.build() must reuse the PolicyResults cached by 394 the first build (bulk-prefetched via one cache.get_many()) instead of 395 re-evaluating the (slow, per-user) DummyPolicy again.""" 396 pbm = PolicyBindingModel.objects.create() 397 PolicyBinding.objects.create(target=pbm, policy=self.policy_true, order=0) 398 399 # First build populates the cache (real DummyPolicy evaluation happens). 400 first = set(FilterPolicyEngine(pbm, self.users).build().result.values_list("pk", flat=True)) 401 self.assertEqual(first, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 402 403 with ( 404 patch( 405 "authentik.policies.engine.cache.get_many", wraps=cache.get_many 406 ) as mock_get_many, 407 patch( 408 "authentik.policies.dummy.models.DummyPolicy.passes", 409 side_effect=AssertionError("policy should be served from cache, not re-evaluated"), 410 ), 411 ): 412 engine = FilterPolicyEngine(pbm, self.users) 413 second = set(engine.build().result.values_list("pk", flat=True)) 414 415 self.assertEqual(second, {self.user_a.pk, self.user_b.pk, self.user_c.pk}) 416 mock_get_many.assert_called_once()
A second FilterPolicyEngine.build() must reuse the PolicyResults cached by the first build (bulk-prefetched via one cache.get_many()) instead of re-evaluating the (slow, per-user) DummyPolicy again.
429 def test_mirror_actor_evaluated_as_parent(self): 430 """A MIRROR actor passes iff the identity it mirrors passes, folded into the same 431 evaluation -- no per-actor PolicyEngine is spawned on the static path.""" 432 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 433 actor_c = self._mirror_actor(self.user_c) # user_c is in no group 434 users = User.objects.filter(pk__in=[actor_a.pk, actor_c.pk, self.user_a.pk, self.user_c.pk]) 435 pbm = PolicyBindingModel.objects.create() 436 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 437 438 with patch("authentik.policies.engine.PolicyEngine") as mock_engine: 439 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 440 441 # actor_a mirrors user_a (in group_a) -> passes; actor_c mirrors user_c -> denied. 442 self.assertEqual(result, {self.user_a.pk, actor_a.pk}) 443 self.assertEqual(mock_engine.call_count, 0)
A MIRROR actor passes iff the identity it mirrors passes, folded into the same evaluation -- no per-actor PolicyEngine is spawned on the static path.
445 def test_mirror_actor_without_parent_in_set(self): 446 """The mirrored parent need not itself be in the queryset.""" 447 actor_a = self._mirror_actor(self.user_a) 448 users = User.objects.filter(pk__in=[actor_a.pk, self.user_c.pk]) 449 pbm = PolicyBindingModel.objects.create() 450 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 451 452 engine = FilterPolicyEngine(pbm, users) 453 result = set(engine.build().result.values_list("pk", flat=True)) 454 # Only the actor passes (via user_a's membership); user_a itself is not in the result set. 455 self.assertEqual(result, {actor_a.pk})
The mirrored parent need not itself be in the queryset.
457 def test_mirror_actor_query_count_independent_of_service_accounts(self): 458 """Finding MIRROR actors must not issue a query per service account in the set.""" 459 service_accounts = [create_test_user(type=UserTypes.SERVICE_ACCOUNT).pk for _ in range(25)] 460 actor_a = self._mirror_actor(self.user_a) 461 users = User.objects.filter(pk__in=[*service_accounts, actor_a.pk]) 462 pbm = PolicyBindingModel.objects.create() 463 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 464 465 engine = FilterPolicyEngine(pbm, users) 466 with CaptureQueriesContext(connections["default"]) as ctx: 467 result = set(engine.build().result.values_list("pk", flat=True)) 468 self.assertEqual(result, {actor_a.pk}) 469 self.assertLess(len(ctx.captured_queries), 15)
Finding MIRROR actors must not issue a query per service account in the set.
471 def test_mirror_actor_chain(self): 472 """An actor mirroring another MIRROR actor is evaluated as the end of the chain.""" 473 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 474 actor_of_actor = self._mirror_actor(actor_a) 475 actor_c = self._mirror_actor(self.user_c) # user_c is in no group 476 users = User.objects.filter(pk__in=[actor_of_actor.pk, actor_c.pk]) 477 pbm = PolicyBindingModel.objects.create() 478 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 479 480 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 481 self.assertEqual(result, {actor_of_actor.pk})
An actor mirroring another MIRROR actor is evaluated as the end of the chain.
483 def test_mirror_actor_without_parent_evaluated_as_itself(self): 484 """A MIRROR actor with no parent has nothing to mirror and is evaluated as itself.""" 485 actor = self._mirror_actor(None) 486 users = User.objects.filter(pk__in=[actor.pk]) 487 pbm = PolicyBindingModel.objects.create() 488 489 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 490 self.assertEqual(result, {actor.pk}) 491 492 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 493 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 494 self.assertEqual(result, set())
A MIRROR actor with no parent has nothing to mirror and is evaluated as itself.
496 def test_mirror_actor_expired(self): 497 """An expired MIRROR actor is hidden from the default Actor manager, so it does not 498 mirror its parent and is evaluated as itself.""" 499 actor_a = self._mirror_actor(self.user_a) # user_a is in group_a 500 actor_a.expiring = True 501 actor_a.expires = now() - timedelta(minutes=10) 502 actor_a.save() 503 users = User.objects.filter(pk__in=[actor_a.pk]) 504 pbm = PolicyBindingModel.objects.create() 505 PolicyBinding.objects.create(target=pbm, group=self.group_a, order=0) 506 507 result = set(FilterPolicyEngine(pbm, users).build().result.values_list("pk", flat=True)) 508 self.assertEqual(result, set())
An expired MIRROR actor is hidden from the default Actor manager, so it does not mirror its parent and is evaluated as itself.