authentik.policies.engine
authentik policy engine
1"""authentik policy engine""" 2 3from collections import defaultdict 4from collections.abc import Iterable 5from copy import copy 6from multiprocessing import Pipe, current_process 7from multiprocessing.connection import Connection 8 9from django.core.cache import cache 10from django.db.models import Q, QuerySet 11from django.http import HttpRequest 12from django.utils.timezone import now 13from structlog.stdlib import BoundLogger, get_logger 14 15from authentik.core.models import Actor, ActorPolicyInheritance, Group, User, UserTypes 16from authentik.events.models import EventAction 17from authentik.lib.tracing import active_tracer 18from authentik.lib.utils.reflection import class_to_path 19from authentik.policies.apps import HIST_POLICIES_ENGINE_TOTAL_TIME, HIST_POLICIES_EXECUTION_TIME 20from authentik.policies.exceptions import PolicyEngineException 21from authentik.policies.models import Policy, PolicyBinding, PolicyBindingModel, PolicyEngineMode 22from authentik.policies.process import PolicyProcess, cache_key, create_policy_event 23from authentik.policies.types import PolicyRequest, PolicyResult 24 25CURRENT_PROCESS = current_process() 26 27# Actors are always service accounts, so a cheap type check keeps the hot policy path free of an 28# extra query for ordinary (human) users. 29_ACTOR_USER_TYPES = frozenset({UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT}) 30 31 32def _get_mirror_parent(user: User) -> User | None: 33 """Return the parent a MIRROR actor mirrors its policy from, or None. 34 35 An actor with ``policy_behavior == MIRROR`` is evaluated as its parent: it passes a policy 36 exactly when the parent does. Detection resolves the multi-table-inheritance child, memoized 37 on the user instance. 38 """ 39 if getattr(user, "type", None) not in _ACTOR_USER_TYPES: 40 return None 41 if "_actor" not in user.__dict__: 42 user.__dict__["_actor"] = Actor.objects.filter(pk=user.pk).first() 43 actor: Actor | None = user.__dict__["_actor"] 44 if actor and actor.policy_behavior == ActorPolicyInheritance.MIRROR and actor.parent_id: 45 return actor.parent 46 return None 47 48 49def effective_policy_user(user: User) -> User: 50 """Follow MIRROR actors up to the identity whose policy result they mirror.""" 51 seen = {user.pk} 52 while (parent := _get_mirror_parent(user)) is not None and parent.pk not in seen: 53 seen.add(parent.pk) 54 user = parent 55 return user 56 57 58class PolicyProcessInfo: 59 """Dataclass to hold all information and communication channels to a process""" 60 61 process: PolicyProcess 62 connection: Connection 63 result: PolicyResult | None 64 binding: PolicyBinding 65 66 def __init__(self, process: PolicyProcess, connection: Connection, binding: PolicyBinding): 67 self.process = process 68 self.connection = connection 69 self.binding = binding 70 self.result = None 71 72 73class _PolicyEngineBase: 74 """State and evaluation helpers shared between `PolicyEngine` (single user) and 75 `FilterPolicyEngine` (queryset of users). 76 77 Kept as composition rather than one engine subclassing the other: their 78 constructors and `build()` semantics are fundamentally different (one user vs 79 a queryset of users), so only the genuinely shared pieces live here. 80 """ 81 82 logger: BoundLogger 83 mode: PolicyEngineMode 84 # Allow objects with no policies attached to pass 85 empty_result: bool 86 use_cache: bool 87 88 def _init_defaults(self, pbm: PolicyBindingModel): 89 self.logger = get_logger().bind() 90 self.mode = pbm.policy_engine_mode 91 # For backwards compatibility, set empty_result to true 92 # objects with no policies attached will pass. 93 self.empty_result = True 94 self.use_cache = True 95 96 @staticmethod 97 def _bindings_for(pbm: PolicyBindingModel) -> QuerySet[PolicyBinding]: 98 # purposefully not selecting policy as a related field due to inheritance 99 return ( 100 PolicyBinding.objects.filter(target=pbm, enabled=True) 101 .select_related("user", "group") 102 .order_by("order") 103 ) 104 105 @staticmethod 106 def _select_policies[B: Iterable[PolicyBinding]](bindings: B) -> B: 107 """Load all bound policies in their concrete type with a single query, instead of 108 `binding.policy` lazily querying each one with all subclass joins""" 109 policy_pks = {b.policy_id for b in bindings if b.policy_id} 110 # An empty pk__in still compiles the whole subclass join before Django skips the query 111 if not policy_pks: 112 return bindings 113 policies = Policy.objects.filter(pk__in=policy_pks).select_subclasses().in_bulk() 114 for binding in bindings: 115 if binding.policy_id: 116 binding.policy = policies[binding.policy_id] 117 return bindings 118 119 @staticmethod 120 def _check_policy_type(binding: PolicyBinding): 121 """Check policy type, make sure it's not the root class as that has no logic implemented""" 122 if binding.policy is not None and binding.policy.__class__ == Policy: 123 raise PolicyEngineException(f"Policy '{binding.policy}' is root type") 124 125 def _cached_result( 126 self, 127 binding: PolicyBinding, 128 request: PolicyRequest, 129 prefetched_cache: dict[str, PolicyResult] | None, 130 ) -> PolicyResult | None: 131 """Look up a cached PolicyResult for (binding, request.user). 132 133 Served from `prefetched_cache` when supplied (a single bulk cache.get_many() 134 result, see `FilterPolicyEngine._prefetch_cache`), otherwise via an individual 135 cache.get() round trip -- the same cost a standalone `PolicyEngine` always paid. 136 """ 137 if not self.use_cache: 138 return None 139 key = cache_key(binding, request) 140 if prefetched_cache is not None: 141 cached_policy = prefetched_cache.get(key) 142 else: 143 # It's a bit silly to time this, but 144 with HIST_POLICIES_EXECUTION_TIME.labels( 145 binding_order=binding.order, 146 binding_target_type=binding.target_type, 147 binding_target_name=binding.target_name, 148 object_type=class_to_path(request.obj.__class__) if request.obj else "", 149 mode="cache_retrieve", 150 ).time(): 151 cached_policy = cache.get(key, None) 152 if cached_policy is not None: 153 self.logger.debug( 154 "P_ENG: Taking result from cache", 155 binding=binding, 156 cache_key=key, 157 request=request, 158 ) 159 return cached_policy 160 161 def _evaluate_dynamic_bindings( 162 self, 163 policy_bindings: list[PolicyBinding], 164 request: PolicyRequest, 165 prefetched_cache: dict[str, PolicyResult] | None = None, 166 ) -> list[PolicyResult]: 167 """Evaluate `policy_bindings` (bindings with a real Policy attached) against a 168 single PolicyRequest.""" 169 results: list[PolicyResult | None] = [None] * len(policy_bindings) 170 pending: list[tuple[int, PolicyProcessInfo]] = [] 171 for idx, binding in enumerate(policy_bindings): 172 self._check_policy_type(binding) 173 cached = self._cached_result(binding, request, prefetched_cache) 174 if cached is not None: 175 results[idx] = cached 176 if binding.dry_run and not request.debug: 177 create_policy_event( 178 binding, 179 request, 180 EventAction.POLICY_EXECUTION, 181 message="Policy Execution (dry run)", 182 result=cached, 183 dry_run=True, 184 cached=True, 185 ) 186 continue 187 self.logger.debug("P_ENG: Evaluating policy", binding=binding, request=request) 188 our_end, task_end = Pipe(False) 189 task = PolicyProcess(binding, request, task_end, use_cache=self.use_cache) 190 task.daemon = False 191 self.logger.debug("P_ENG: Starting Process", binding=binding, request=request) 192 if not CURRENT_PROCESS._config.get("daemon"): 193 task.run() 194 else: 195 task.start() 196 pending.append( 197 (idx, PolicyProcessInfo(process=task, connection=our_end, binding=binding)) 198 ) 199 for idx, proc_info in pending: 200 if proc_info.process.is_alive(): 201 proc_info.process.join(proc_info.binding.timeout) 202 result = proc_info.connection.recv() 203 if result is not None and result._exec_time: 204 HIST_POLICIES_EXECUTION_TIME.labels( 205 binding_order=proc_info.binding.order, 206 binding_target_type=proc_info.binding.target_type, 207 binding_target_name=proc_info.binding.target_name, 208 object_type=class_to_path(request.obj.__class__) if request.obj else "", 209 mode="execute_process", 210 ).observe(result._exec_time) 211 results[idx] = result 212 return results 213 214 @staticmethod 215 def _report_static_dry_run( 216 binding: PolicyBinding, request: PolicyRequest, result: PolicyResult 217 ) -> PolicyResult: 218 """Record an uncached user/group observation without contributing to enforcement.""" 219 result.source_binding = binding 220 if not request.debug: 221 create_policy_event( 222 binding, 223 request, 224 EventAction.POLICY_EXECUTION, 225 message="Policy Execution (dry run)", 226 result=result, 227 dry_run=True, 228 cached=False, 229 ) 230 return result 231 232 @staticmethod 233 def _combine_results( 234 mode: PolicyEngineMode, empty_result: bool, all_results: list[PolicyResult] 235 ) -> PolicyResult: 236 """Combine per-binding PolicyResults into one overall PolicyResult.""" 237 effective_results = [ 238 result 239 for result in all_results 240 if not result.source_binding or not result.source_binding.dry_run 241 ] 242 passing = empty_result if not effective_results else False 243 if mode == PolicyEngineMode.MODE_ALL and effective_results: 244 passing = all(x.passing for x in effective_results) 245 if mode == PolicyEngineMode.MODE_ANY and effective_results: 246 passing = any(x.passing for x in effective_results) 247 result = PolicyResult(passing) 248 result.source_results = all_results 249 result.messages = tuple(y for x in effective_results for y in x.messages) 250 return result 251 252 253class PolicyEngine[T: PolicyBindingModel](_PolicyEngineBase): 254 """Orchestrate policy checking, launch tasks and return result""" 255 256 request: PolicyRequest 257 258 def __init__(self, pbm: T, user: User, request: HttpRequest = None): 259 self._init_defaults(pbm) 260 if not isinstance(pbm, PolicyBindingModel): # pragma: no cover 261 raise PolicyEngineException(f"{pbm} is not instance of PolicyBindingModel") 262 if not user: 263 raise PolicyEngineException("User must be set") 264 user = effective_policy_user(user) 265 self.__pbm = pbm 266 self.request = PolicyRequest(user) 267 self.request.obj = pbm 268 if request: 269 self.request.set_http_request(request) 270 self.__binding_results: list[PolicyResult] = [] 271 self.__static_result: PolicyResult | None = None 272 273 def bindings(self) -> QuerySet[PolicyBinding] | Iterable[PolicyBinding]: 274 """Make sure all Policies are their respective classes""" 275 return self._bindings_for(self.__pbm) 276 277 def compute_static_bindings(self, bindings: QuerySet[PolicyBinding]): 278 """Check static bindings if possible""" 279 # Evaluated in Python on the bindings queryset, which is fetched (and cached) for the 280 # dynamic bindings anyway, so this costs at most one group lookup instead of an 281 # aggregate query that is expensive to build 282 static = [ 283 binding 284 for binding in bindings 285 if (binding.group_id or binding.user_id) 286 and not binding.policy_id 287 and not binding.dry_run 288 ] 289 if not static: 290 # If we didn't find any static bindings, do nothing 291 return 292 matched_bindings = {"total": len(static)} 293 if self.request.user.pk: 294 group_pks = set() 295 if any(binding.group_id for binding in static): 296 group_pks = set(self.request.user.all_groups().values_list("pk", flat=True)) 297 matched_bindings["passing"] = sum( 298 1 299 for binding in static 300 if (binding.user_id == self.request.user.pk or binding.group_id in group_pks) 301 != binding.negate 302 and (not binding.expiring or binding.expires >= now()) 303 ) 304 passing = False 305 self.logger.debug("P_ENG: Found static bindings", **matched_bindings) 306 if self.mode == PolicyEngineMode.MODE_ANY: 307 if matched_bindings.get("passing", 0) > 0: 308 # Any passing static binding -> passing 309 passing = True 310 elif self.mode == PolicyEngineMode.MODE_ALL: 311 if matched_bindings.get("passing", 0) == matched_bindings["total"]: 312 # All static bindings are passing -> passing 313 passing = True 314 elif matched_bindings["total"] > 0 and matched_bindings.get("passing", 0) < 1: 315 # No matching static bindings but at least one is configured -> not passing 316 passing = False 317 self.__static_result = PolicyResult(passing) 318 319 def build(self) -> PolicyEngine: 320 """Build wrapper which monitors performance""" 321 with ( 322 active_tracer().start_span( 323 op="authentik.policy.engine.build", 324 name=class_to_path(self.__pbm.__class__), 325 ) as span, 326 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 327 obj_type=class_to_path(self.__pbm.__class__), 328 obj_pk=str(self.__pbm.pk), 329 ).time(), 330 ): 331 span.set_data("pbm", self.__pbm) 332 span.set_data("request", self.request) 333 bindings = self.bindings() 334 policy_bindings = bindings 335 if isinstance(bindings, QuerySet): 336 self._select_policies(bindings) 337 self.compute_static_bindings(bindings) 338 policy_bindings = [x for x in bindings if x.policy] 339 self.__binding_results = self._evaluate_dynamic_bindings( 340 list(policy_bindings), self.request 341 ) 342 if isinstance(bindings, QuerySet): 343 for binding in bindings: 344 if binding.dry_run and not binding.policy_id: 345 result = binding.passes(self.request) 346 if binding.negate: 347 result.passing = not result.passing 348 self.__binding_results.append( 349 self._report_static_dry_run(binding, self.request, result) 350 ) 351 return self 352 353 @property 354 def result(self) -> PolicyResult: 355 """Get policy-checking result""" 356 all_results = list(self.__binding_results) 357 if self.__static_result is not None: 358 all_results.append(self.__static_result) 359 return self._combine_results(self.mode, self.empty_result, all_results) 360 361 @property 362 def passing(self) -> bool: 363 """Only get true/false if user passes""" 364 return self.result.passing 365 366 367class FilterPolicyEngine[T: PolicyBindingModel](_PolicyEngineBase): 368 """Check a QuerySet of users against a single PolicyBindingModel efficiently.""" 369 370 def __init__(self, pbm: T, users: QuerySet[User], request: HttpRequest = None): 371 self._init_defaults(pbm) 372 self.__pbm = pbm 373 self.__users = users 374 self.__original_users = users 375 self.__mirror_of: dict = {} 376 self.__http_request = request 377 self.__result: QuerySet[User] | None = None 378 379 def bindings(self) -> QuerySet[PolicyBinding]: 380 """Get enabled bindings for the bound PBM""" 381 return self._bindings_for(self.__pbm) 382 383 def _substitute_mirror_actors(self): 384 """Swap MIRROR actors in the user set for the identity they mirror, so they are 385 evaluated in the same pass as everyone else (`_finalize` maps the verdict back). Only 386 service accounts can be actors, so the scan is a cheap, targeted query, and parents that 387 are shared across actors are evaluated once. 388 """ 389 actors = Actor.objects.filter( 390 pk__in=self.__original_users.filter(type__in=_ACTOR_USER_TYPES).values("pk"), 391 policy_behavior=ActorPolicyInheritance.MIRROR, 392 parent_id__isnull=False, 393 ).select_related("parent") 394 for actor in actors: 395 # Seed the per-instance memo that _get_mirror_parent() uses 396 actor.__dict__["_actor"] = actor 397 effective = effective_policy_user(actor) 398 if effective.pk != actor.pk: 399 self.__mirror_of[actor.pk] = effective 400 if not self.__mirror_of: 401 return 402 parent_pks = {parent.pk for parent in self.__mirror_of.values()} 403 self.__users = User.objects.filter( 404 Q(pk__in=self.__original_users.exclude(pk__in=self.__mirror_of.keys()).values("pk")) 405 | Q(pk__in=parent_pks) 406 ) 407 408 def build(self) -> FilterPolicyEngine: 409 """Evaluate bindings against the user queryset""" 410 with ( 411 active_tracer().start_span( 412 op="authentik.policy.engine_filter.build", 413 name=class_to_path(self.__pbm.__class__), 414 ), 415 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 416 obj_type=class_to_path(self.__pbm.__class__), 417 obj_pk=str(self.__pbm.pk), 418 ).time(), 419 ): 420 self._substitute_mirror_actors() 421 bindings = self._select_policies(list(self.bindings())) 422 for binding in bindings: 423 self._check_policy_type(binding) 424 425 if not bindings: 426 self.__result = self.__users if self.empty_result else self.__users.none() 427 return self._finalize() 428 429 dynamic_bindings = [binding for binding in bindings if binding.policy_id is not None] 430 dry_run_bindings = [binding for binding in dynamic_bindings if binding.dry_run] 431 # Static observations use one SQL membership query per binding, rather 432 # than a group lookup per user. They never affect the candidate set. 433 for binding in bindings: 434 if not binding.dry_run or binding.policy_id: 435 continue 436 matching_pks = set( 437 self._filter_static( 438 self.__users, [binding], PolicyEngineMode.MODE_ALL 439 ).values_list("pk", flat=True) 440 ) 441 for user in self.__users: 442 request = PolicyRequest(user) 443 request.obj = self.__pbm 444 if self.__http_request: 445 request.set_http_request(self.__http_request) 446 self._report_static_dry_run( 447 binding, request, PolicyResult(user.pk in matching_pks) 448 ) 449 static_bindings = [ 450 binding 451 for binding in bindings 452 if not binding.dry_run 453 and binding.policy_id is None 454 and (binding.group_id or binding.user_id) 455 ] 456 457 if not dynamic_bindings: 458 # Static enforcement stays in SQL; dry-run observations were reported above. 459 if not static_bindings: 460 self.__result = self.__users if self.empty_result else self.__users.none() 461 else: 462 self.__result = self._filter_static(self.__users, static_bindings, self.mode) 463 return self._finalize() 464 465 # Slow path: real Policy objects can't be translated to SQL and need 466 # per-user evaluation. Pre-compute the static verdict ONCE via SQL (reused 467 # per user as a set-membership check) instead of re-running an aggregate 468 # query per user, and shrink the candidate set first when MODE_ALL allows 469 # it (a static-failing user can never satisfy MODE_ALL overall). 470 static_passing_pks = None 471 if static_bindings: 472 static_passing_pks = set( 473 self._filter_static(self.__users, static_bindings, self.mode).values_list( 474 "pk", flat=True 475 ) 476 ) 477 478 candidates = self.__users 479 dry_run_only_users = [] 480 if self.mode == PolicyEngineMode.MODE_ALL and static_bindings: 481 candidates = candidates.filter(pk__in=static_passing_pks) 482 if dry_run_bindings: 483 dry_run_only_users = list(self.__users.exclude(pk__in=static_passing_pks)) 484 candidates = list(candidates) 485 486 prefetched_cache = self._prefetch_cache( 487 candidates, dynamic_bindings, dry_run_only_users, dry_run_bindings 488 ) 489 490 passing_pks = [] 491 for user in candidates: 492 request = PolicyRequest(user) 493 request.obj = self.__pbm 494 if self.__http_request: 495 request.set_http_request(self.__http_request) 496 all_results = self._evaluate_dynamic_bindings( 497 dynamic_bindings, request, prefetched_cache 498 ) 499 if static_passing_pks is not None: 500 all_results.append(PolicyResult(user.pk in static_passing_pks)) 501 if self._combine_results(self.mode, self.empty_result, all_results).passing: 502 passing_pks.append(user.pk) 503 for user in dry_run_only_users: 504 request = PolicyRequest(user) 505 request.obj = self.__pbm 506 if self.__http_request: 507 request.set_http_request(self.__http_request) 508 self._evaluate_dynamic_bindings(dry_run_bindings, request, prefetched_cache) 509 self.__result = self.__users.filter(pk__in=passing_pks) 510 return self._finalize() 511 512 def _finalize(self) -> FilterPolicyEngine: 513 """Map the effective-user verdicts back onto the original user set. 514 515 `build()` evaluated the substituted set (parents standing in for their MIRROR actors), so 516 a substituted actor passes iff the identity it mirrors passes. No-op when nothing was 517 substituted -- `self.__result` already refers to the original users. 518 """ 519 if not self.__mirror_of: 520 return self 521 passing = set(self.__result.values_list("pk", flat=True)) 522 final_pks = { 523 pk 524 for pk in self.__original_users.values_list("pk", flat=True) 525 if (self.__mirror_of[pk].pk if pk in self.__mirror_of else pk) in passing 526 } 527 self.__result = self.__original_users.filter(pk__in=final_pks) 528 return self 529 530 def _prefetch_cache( 531 self, 532 candidates: list[User], 533 dynamic_bindings: list[PolicyBinding], 534 dry_run_only_users: list[User] | None = None, 535 dry_run_bindings: list[PolicyBinding] | None = None, 536 ) -> dict[str, PolicyResult]: 537 """Bulk-fetch cached PolicyResults for every (dynamic binding, candidate) pair 538 with a single cache.get_many() call. 539 540 Without this, each candidate's `_evaluate_dynamic_bindings` call would do its 541 own cache.get() per binding -- N candidates x M dynamic bindings individual 542 round trips to the cache backend collapse into one. 543 """ 544 if not self.use_cache: 545 return {} 546 keys = [] 547 for users, bindings in ( 548 (candidates, dynamic_bindings), 549 (dry_run_only_users or [], dry_run_bindings or []), 550 ): 551 for user in users: 552 # Cache keys don't need context-processor enrichment (geoip etc.). 553 request = PolicyRequest(user) 554 request.http_request = self.__http_request 555 for binding in bindings: 556 keys.append(cache_key(binding, request)) 557 if not keys: 558 return {} 559 with HIST_POLICIES_EXECUTION_TIME.labels( 560 binding_order=-1, 561 binding_target_type="bulk", 562 binding_target_name="", 563 object_type=class_to_path(self.__pbm.__class__), 564 mode="cache_retrieve_bulk", 565 ).time(): 566 return cache.get_many(keys) 567 568 @property 569 def result(self) -> QuerySet[User]: 570 """Get the subset of the user queryset that passes""" 571 return self.__result 572 573 def _filter_static( 574 self, base: QuerySet[User], bindings: list[PolicyBinding], mode: PolicyEngineMode 575 ) -> QuerySet[User]: 576 """Apply static (group/user) bindings to `base` using SQL only.""" 577 if mode == PolicyEngineMode.MODE_ALL: 578 qs = base 579 for binding in bindings: 580 qs = qs.filter(self._binding_to_q(binding)) 581 # Chained filters can produce duplicates if the same row satisfies multiple 582 # JOINs trivially; .distinct() guarantees uniqueness. 583 return qs.distinct() 584 585 # MODE_ANY (and any unknown mode) -> OR-combine per-binding Q 586 combined = self._binding_to_q(bindings[0]) 587 for binding in bindings[1:]: 588 combined |= self._binding_to_q(binding) 589 return base.filter(combined).distinct() 590 591 def _binding_to_q(self, binding: PolicyBinding) -> Q: 592 """Translate a single static PolicyBinding into a Q expression matching users 593 for whom the binding "passes" (per `PolicyEngine.compute_static_bindings`).""" 594 if binding.user_id: 595 match = Q(pk=binding.user_id) 596 else: 597 # Group binding: match users in the bound group OR any descendant. 598 # "binding.group in user.all_groups()" is equivalent to 599 # "user is in binding.group.with_descendants()". 600 descendants = Group.objects.filter(pk=binding.group_id).with_descendants() 601 match = Q(groups__in=descendants) 602 if binding.negate: 603 match = ~match 604 return match 605 606 607class ListPolicyEngine[T: PolicyBindingModel](_PolicyEngineBase): 608 """Check a single user against a QuerySet of PolicyBindingModels efficiently.""" 609 610 def __init__(self, objs: QuerySet[T], user: User, request: HttpRequest = None): 611 self.logger = get_logger().bind() 612 self.empty_result = True 613 self.use_cache = True 614 self.__objs = objs 615 self.__user = effective_policy_user(user) 616 self.__http_request = request 617 self.__result: QuerySet[T] | None = None 618 619 def build(self) -> ListPolicyEngine[T]: 620 """Evaluate the user against every object in the queryset""" 621 with ( 622 active_tracer().start_span( 623 op="authentik.policy.engine_list.build", 624 name=class_to_path(self.__objs.model), 625 ), 626 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 627 obj_type=class_to_path(self.__objs.model), 628 obj_pk="bulk", 629 ).time(), 630 ): 631 objs = list(self.__objs) 632 if not objs: 633 self.__result = self.__objs 634 return self 635 636 obj_by_pk = {obj.pk: obj for obj in objs} 637 # PolicyBinding.target is a FK to the PolicyBindingModel base table's own 638 # pk (pbm_uuid), which can diverge from a subclass's own `.pk` if that 639 # subclass declares its own primary key. 640 target_field = PolicyBinding._meta.get_field("target").target_field.attname 641 pk_by_target_key = {getattr(obj, target_field): obj.pk for obj in objs} 642 643 bindings_by_target = defaultdict(list) 644 bindings = list( 645 PolicyBinding.objects.filter(target__in=pk_by_target_key.keys(), enabled=True) 646 .select_related("user", "group") 647 .order_by("target", "order") 648 ) 649 self._select_policies(bindings) 650 for binding in bindings: 651 pk = pk_by_target_key[binding.target_id] 652 binding.target = obj_by_pk[pk] 653 self._check_policy_type(binding) 654 bindings_by_target[pk].append(binding) 655 656 # Objects with no bindings at all pass if empty_result, same convention 657 # as PolicyEngine/FilterPolicyEngine. 658 passing_pks = ( 659 {pk for pk in obj_by_pk if pk not in bindings_by_target} 660 if self.empty_result 661 else set() 662 ) 663 if not bindings_by_target: 664 self.__result = self.__objs.filter(pk__in=passing_pks) 665 return self 666 667 # The user is fixed here (unlike FilterPolicyEngine, which varies the 668 # user), so static bindings are resolved with one all_groups() lookup 669 user_group_pks = ( 670 set(self.__user.all_groups().values_list("pk", flat=True)) 671 if self.__user.pk 672 else set() 673 ) 674 675 static_results: dict = {} 676 dynamic_by_target: dict = {} 677 for pk, obj_bindings in bindings_by_target.items(): 678 mode = obj_by_pk[pk].policy_engine_mode 679 static_bindings = [ 680 binding 681 for binding in obj_bindings 682 if not binding.dry_run 683 and binding.policy_id is None 684 and (binding.group_id or binding.user_id) 685 ] 686 dynamic_bindings = [ 687 binding for binding in obj_bindings if binding.policy_id is not None 688 ] 689 if static_bindings: 690 static_results[pk] = self._combine_results( 691 mode, 692 self.empty_result, 693 [ 694 self._static_binding_result(binding, user_group_pks) 695 for binding in static_bindings 696 ], 697 ) 698 # MODE_ALL: effective dynamic bindings cannot change a failed static 699 # verdict, but dry-run bindings still need to execute. 700 if ( 701 mode == PolicyEngineMode.MODE_ALL 702 and pk in static_results 703 and not static_results[pk].passing 704 ): 705 dynamic_bindings = [binding for binding in dynamic_bindings if binding.dry_run] 706 if dynamic_bindings: 707 dynamic_by_target[pk] = dynamic_bindings 708 709 all_dynamic_bindings = [ 710 binding for bindings in dynamic_by_target.values() for binding in bindings 711 ] 712 713 request = PolicyRequest(self.__user) 714 if self.__http_request: 715 request.set_http_request(self.__http_request) 716 prefetched_cache = self._prefetch_cache(request, all_dynamic_bindings) 717 718 for pk in bindings_by_target: 719 mode = obj_by_pk[pk].policy_engine_mode 720 all_results = [] 721 request.obj = obj_by_pk[pk] 722 for binding in bindings_by_target[pk]: 723 if binding.dry_run and not binding.policy_id: 724 all_results.append( 725 self._report_static_dry_run( 726 binding, 727 request, 728 self._static_binding_result(binding, user_group_pks), 729 ) 730 ) 731 if pk in dynamic_by_target: 732 all_results.extend( 733 self._evaluate_dynamic_bindings( 734 dynamic_by_target[pk], copy(request), prefetched_cache 735 ) 736 ) 737 if pk in static_results: 738 all_results.append(static_results[pk]) 739 if self._combine_results(mode, self.empty_result, all_results).passing: 740 passing_pks.add(pk) 741 742 self.__result = self.__objs.filter(pk__in=passing_pks) 743 return self 744 745 def _static_binding_result(self, binding: PolicyBinding, user_group_pks: set) -> PolicyResult: 746 """Evaluate a single static (group/user) binding against the fixed user""" 747 if binding.user_id: 748 match = binding.user_id == self.__user.pk 749 else: 750 match = binding.group_id in user_group_pks 751 if binding.negate: 752 match = not match 753 return PolicyResult(match) 754 755 def _prefetch_cache( 756 self, request: PolicyRequest, dynamic_bindings: list[PolicyBinding] 757 ) -> dict[str, PolicyResult]: 758 """Bulk-fetch cached PolicyResults for every dynamic binding across every 759 object with a single cache.get_many() call.""" 760 if not self.use_cache or not dynamic_bindings: 761 return {} 762 keys = [cache_key(binding, request) for binding in dynamic_bindings] 763 with HIST_POLICIES_EXECUTION_TIME.labels( 764 binding_order=-1, 765 binding_target_type="bulk", 766 binding_target_name="", 767 object_type=class_to_path(self.__objs.model), 768 mode="cache_retrieve_bulk", 769 ).time(): 770 return cache.get_many(keys) 771 772 @property 773 def result(self) -> QuerySet[T]: 774 """Get the subset of the object queryset that the user passes""" 775 return self.__result
50def effective_policy_user(user: User) -> User: 51 """Follow MIRROR actors up to the identity whose policy result they mirror.""" 52 seen = {user.pk} 53 while (parent := _get_mirror_parent(user)) is not None and parent.pk not in seen: 54 seen.add(parent.pk) 55 user = parent 56 return user
Follow MIRROR actors up to the identity whose policy result they mirror.
59class PolicyProcessInfo: 60 """Dataclass to hold all information and communication channels to a process""" 61 62 process: PolicyProcess 63 connection: Connection 64 result: PolicyResult | None 65 binding: PolicyBinding 66 67 def __init__(self, process: PolicyProcess, connection: Connection, binding: PolicyBinding): 68 self.process = process 69 self.connection = connection 70 self.binding = binding 71 self.result = None
Dataclass to hold all information and communication channels to a process
254class PolicyEngine[T: PolicyBindingModel](_PolicyEngineBase): 255 """Orchestrate policy checking, launch tasks and return result""" 256 257 request: PolicyRequest 258 259 def __init__(self, pbm: T, user: User, request: HttpRequest = None): 260 self._init_defaults(pbm) 261 if not isinstance(pbm, PolicyBindingModel): # pragma: no cover 262 raise PolicyEngineException(f"{pbm} is not instance of PolicyBindingModel") 263 if not user: 264 raise PolicyEngineException("User must be set") 265 user = effective_policy_user(user) 266 self.__pbm = pbm 267 self.request = PolicyRequest(user) 268 self.request.obj = pbm 269 if request: 270 self.request.set_http_request(request) 271 self.__binding_results: list[PolicyResult] = [] 272 self.__static_result: PolicyResult | None = None 273 274 def bindings(self) -> QuerySet[PolicyBinding] | Iterable[PolicyBinding]: 275 """Make sure all Policies are their respective classes""" 276 return self._bindings_for(self.__pbm) 277 278 def compute_static_bindings(self, bindings: QuerySet[PolicyBinding]): 279 """Check static bindings if possible""" 280 # Evaluated in Python on the bindings queryset, which is fetched (and cached) for the 281 # dynamic bindings anyway, so this costs at most one group lookup instead of an 282 # aggregate query that is expensive to build 283 static = [ 284 binding 285 for binding in bindings 286 if (binding.group_id or binding.user_id) 287 and not binding.policy_id 288 and not binding.dry_run 289 ] 290 if not static: 291 # If we didn't find any static bindings, do nothing 292 return 293 matched_bindings = {"total": len(static)} 294 if self.request.user.pk: 295 group_pks = set() 296 if any(binding.group_id for binding in static): 297 group_pks = set(self.request.user.all_groups().values_list("pk", flat=True)) 298 matched_bindings["passing"] = sum( 299 1 300 for binding in static 301 if (binding.user_id == self.request.user.pk or binding.group_id in group_pks) 302 != binding.negate 303 and (not binding.expiring or binding.expires >= now()) 304 ) 305 passing = False 306 self.logger.debug("P_ENG: Found static bindings", **matched_bindings) 307 if self.mode == PolicyEngineMode.MODE_ANY: 308 if matched_bindings.get("passing", 0) > 0: 309 # Any passing static binding -> passing 310 passing = True 311 elif self.mode == PolicyEngineMode.MODE_ALL: 312 if matched_bindings.get("passing", 0) == matched_bindings["total"]: 313 # All static bindings are passing -> passing 314 passing = True 315 elif matched_bindings["total"] > 0 and matched_bindings.get("passing", 0) < 1: 316 # No matching static bindings but at least one is configured -> not passing 317 passing = False 318 self.__static_result = PolicyResult(passing) 319 320 def build(self) -> PolicyEngine: 321 """Build wrapper which monitors performance""" 322 with ( 323 active_tracer().start_span( 324 op="authentik.policy.engine.build", 325 name=class_to_path(self.__pbm.__class__), 326 ) as span, 327 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 328 obj_type=class_to_path(self.__pbm.__class__), 329 obj_pk=str(self.__pbm.pk), 330 ).time(), 331 ): 332 span.set_data("pbm", self.__pbm) 333 span.set_data("request", self.request) 334 bindings = self.bindings() 335 policy_bindings = bindings 336 if isinstance(bindings, QuerySet): 337 self._select_policies(bindings) 338 self.compute_static_bindings(bindings) 339 policy_bindings = [x for x in bindings if x.policy] 340 self.__binding_results = self._evaluate_dynamic_bindings( 341 list(policy_bindings), self.request 342 ) 343 if isinstance(bindings, QuerySet): 344 for binding in bindings: 345 if binding.dry_run and not binding.policy_id: 346 result = binding.passes(self.request) 347 if binding.negate: 348 result.passing = not result.passing 349 self.__binding_results.append( 350 self._report_static_dry_run(binding, self.request, result) 351 ) 352 return self 353 354 @property 355 def result(self) -> PolicyResult: 356 """Get policy-checking result""" 357 all_results = list(self.__binding_results) 358 if self.__static_result is not None: 359 all_results.append(self.__static_result) 360 return self._combine_results(self.mode, self.empty_result, all_results) 361 362 @property 363 def passing(self) -> bool: 364 """Only get true/false if user passes""" 365 return self.result.passing
Orchestrate policy checking, launch tasks and return result
259 def __init__(self, pbm: T, user: User, request: HttpRequest = None): 260 self._init_defaults(pbm) 261 if not isinstance(pbm, PolicyBindingModel): # pragma: no cover 262 raise PolicyEngineException(f"{pbm} is not instance of PolicyBindingModel") 263 if not user: 264 raise PolicyEngineException("User must be set") 265 user = effective_policy_user(user) 266 self.__pbm = pbm 267 self.request = PolicyRequest(user) 268 self.request.obj = pbm 269 if request: 270 self.request.set_http_request(request) 271 self.__binding_results: list[PolicyResult] = [] 272 self.__static_result: PolicyResult | None = None
274 def bindings(self) -> QuerySet[PolicyBinding] | Iterable[PolicyBinding]: 275 """Make sure all Policies are their respective classes""" 276 return self._bindings_for(self.__pbm)
Make sure all Policies are their respective classes
278 def compute_static_bindings(self, bindings: QuerySet[PolicyBinding]): 279 """Check static bindings if possible""" 280 # Evaluated in Python on the bindings queryset, which is fetched (and cached) for the 281 # dynamic bindings anyway, so this costs at most one group lookup instead of an 282 # aggregate query that is expensive to build 283 static = [ 284 binding 285 for binding in bindings 286 if (binding.group_id or binding.user_id) 287 and not binding.policy_id 288 and not binding.dry_run 289 ] 290 if not static: 291 # If we didn't find any static bindings, do nothing 292 return 293 matched_bindings = {"total": len(static)} 294 if self.request.user.pk: 295 group_pks = set() 296 if any(binding.group_id for binding in static): 297 group_pks = set(self.request.user.all_groups().values_list("pk", flat=True)) 298 matched_bindings["passing"] = sum( 299 1 300 for binding in static 301 if (binding.user_id == self.request.user.pk or binding.group_id in group_pks) 302 != binding.negate 303 and (not binding.expiring or binding.expires >= now()) 304 ) 305 passing = False 306 self.logger.debug("P_ENG: Found static bindings", **matched_bindings) 307 if self.mode == PolicyEngineMode.MODE_ANY: 308 if matched_bindings.get("passing", 0) > 0: 309 # Any passing static binding -> passing 310 passing = True 311 elif self.mode == PolicyEngineMode.MODE_ALL: 312 if matched_bindings.get("passing", 0) == matched_bindings["total"]: 313 # All static bindings are passing -> passing 314 passing = True 315 elif matched_bindings["total"] > 0 and matched_bindings.get("passing", 0) < 1: 316 # No matching static bindings but at least one is configured -> not passing 317 passing = False 318 self.__static_result = PolicyResult(passing)
Check static bindings if possible
320 def build(self) -> PolicyEngine: 321 """Build wrapper which monitors performance""" 322 with ( 323 active_tracer().start_span( 324 op="authentik.policy.engine.build", 325 name=class_to_path(self.__pbm.__class__), 326 ) as span, 327 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 328 obj_type=class_to_path(self.__pbm.__class__), 329 obj_pk=str(self.__pbm.pk), 330 ).time(), 331 ): 332 span.set_data("pbm", self.__pbm) 333 span.set_data("request", self.request) 334 bindings = self.bindings() 335 policy_bindings = bindings 336 if isinstance(bindings, QuerySet): 337 self._select_policies(bindings) 338 self.compute_static_bindings(bindings) 339 policy_bindings = [x for x in bindings if x.policy] 340 self.__binding_results = self._evaluate_dynamic_bindings( 341 list(policy_bindings), self.request 342 ) 343 if isinstance(bindings, QuerySet): 344 for binding in bindings: 345 if binding.dry_run and not binding.policy_id: 346 result = binding.passes(self.request) 347 if binding.negate: 348 result.passing = not result.passing 349 self.__binding_results.append( 350 self._report_static_dry_run(binding, self.request, result) 351 ) 352 return self
Build wrapper which monitors performance
354 @property 355 def result(self) -> PolicyResult: 356 """Get policy-checking result""" 357 all_results = list(self.__binding_results) 358 if self.__static_result is not None: 359 all_results.append(self.__static_result) 360 return self._combine_results(self.mode, self.empty_result, all_results)
Get policy-checking result
362 @property 363 def passing(self) -> bool: 364 """Only get true/false if user passes""" 365 return self.result.passing
Only get true/false if user passes
Inherited Members
368class FilterPolicyEngine[T: PolicyBindingModel](_PolicyEngineBase): 369 """Check a QuerySet of users against a single PolicyBindingModel efficiently.""" 370 371 def __init__(self, pbm: T, users: QuerySet[User], request: HttpRequest = None): 372 self._init_defaults(pbm) 373 self.__pbm = pbm 374 self.__users = users 375 self.__original_users = users 376 self.__mirror_of: dict = {} 377 self.__http_request = request 378 self.__result: QuerySet[User] | None = None 379 380 def bindings(self) -> QuerySet[PolicyBinding]: 381 """Get enabled bindings for the bound PBM""" 382 return self._bindings_for(self.__pbm) 383 384 def _substitute_mirror_actors(self): 385 """Swap MIRROR actors in the user set for the identity they mirror, so they are 386 evaluated in the same pass as everyone else (`_finalize` maps the verdict back). Only 387 service accounts can be actors, so the scan is a cheap, targeted query, and parents that 388 are shared across actors are evaluated once. 389 """ 390 actors = Actor.objects.filter( 391 pk__in=self.__original_users.filter(type__in=_ACTOR_USER_TYPES).values("pk"), 392 policy_behavior=ActorPolicyInheritance.MIRROR, 393 parent_id__isnull=False, 394 ).select_related("parent") 395 for actor in actors: 396 # Seed the per-instance memo that _get_mirror_parent() uses 397 actor.__dict__["_actor"] = actor 398 effective = effective_policy_user(actor) 399 if effective.pk != actor.pk: 400 self.__mirror_of[actor.pk] = effective 401 if not self.__mirror_of: 402 return 403 parent_pks = {parent.pk for parent in self.__mirror_of.values()} 404 self.__users = User.objects.filter( 405 Q(pk__in=self.__original_users.exclude(pk__in=self.__mirror_of.keys()).values("pk")) 406 | Q(pk__in=parent_pks) 407 ) 408 409 def build(self) -> FilterPolicyEngine: 410 """Evaluate bindings against the user queryset""" 411 with ( 412 active_tracer().start_span( 413 op="authentik.policy.engine_filter.build", 414 name=class_to_path(self.__pbm.__class__), 415 ), 416 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 417 obj_type=class_to_path(self.__pbm.__class__), 418 obj_pk=str(self.__pbm.pk), 419 ).time(), 420 ): 421 self._substitute_mirror_actors() 422 bindings = self._select_policies(list(self.bindings())) 423 for binding in bindings: 424 self._check_policy_type(binding) 425 426 if not bindings: 427 self.__result = self.__users if self.empty_result else self.__users.none() 428 return self._finalize() 429 430 dynamic_bindings = [binding for binding in bindings if binding.policy_id is not None] 431 dry_run_bindings = [binding for binding in dynamic_bindings if binding.dry_run] 432 # Static observations use one SQL membership query per binding, rather 433 # than a group lookup per user. They never affect the candidate set. 434 for binding in bindings: 435 if not binding.dry_run or binding.policy_id: 436 continue 437 matching_pks = set( 438 self._filter_static( 439 self.__users, [binding], PolicyEngineMode.MODE_ALL 440 ).values_list("pk", flat=True) 441 ) 442 for user in self.__users: 443 request = PolicyRequest(user) 444 request.obj = self.__pbm 445 if self.__http_request: 446 request.set_http_request(self.__http_request) 447 self._report_static_dry_run( 448 binding, request, PolicyResult(user.pk in matching_pks) 449 ) 450 static_bindings = [ 451 binding 452 for binding in bindings 453 if not binding.dry_run 454 and binding.policy_id is None 455 and (binding.group_id or binding.user_id) 456 ] 457 458 if not dynamic_bindings: 459 # Static enforcement stays in SQL; dry-run observations were reported above. 460 if not static_bindings: 461 self.__result = self.__users if self.empty_result else self.__users.none() 462 else: 463 self.__result = self._filter_static(self.__users, static_bindings, self.mode) 464 return self._finalize() 465 466 # Slow path: real Policy objects can't be translated to SQL and need 467 # per-user evaluation. Pre-compute the static verdict ONCE via SQL (reused 468 # per user as a set-membership check) instead of re-running an aggregate 469 # query per user, and shrink the candidate set first when MODE_ALL allows 470 # it (a static-failing user can never satisfy MODE_ALL overall). 471 static_passing_pks = None 472 if static_bindings: 473 static_passing_pks = set( 474 self._filter_static(self.__users, static_bindings, self.mode).values_list( 475 "pk", flat=True 476 ) 477 ) 478 479 candidates = self.__users 480 dry_run_only_users = [] 481 if self.mode == PolicyEngineMode.MODE_ALL and static_bindings: 482 candidates = candidates.filter(pk__in=static_passing_pks) 483 if dry_run_bindings: 484 dry_run_only_users = list(self.__users.exclude(pk__in=static_passing_pks)) 485 candidates = list(candidates) 486 487 prefetched_cache = self._prefetch_cache( 488 candidates, dynamic_bindings, dry_run_only_users, dry_run_bindings 489 ) 490 491 passing_pks = [] 492 for user in candidates: 493 request = PolicyRequest(user) 494 request.obj = self.__pbm 495 if self.__http_request: 496 request.set_http_request(self.__http_request) 497 all_results = self._evaluate_dynamic_bindings( 498 dynamic_bindings, request, prefetched_cache 499 ) 500 if static_passing_pks is not None: 501 all_results.append(PolicyResult(user.pk in static_passing_pks)) 502 if self._combine_results(self.mode, self.empty_result, all_results).passing: 503 passing_pks.append(user.pk) 504 for user in dry_run_only_users: 505 request = PolicyRequest(user) 506 request.obj = self.__pbm 507 if self.__http_request: 508 request.set_http_request(self.__http_request) 509 self._evaluate_dynamic_bindings(dry_run_bindings, request, prefetched_cache) 510 self.__result = self.__users.filter(pk__in=passing_pks) 511 return self._finalize() 512 513 def _finalize(self) -> FilterPolicyEngine: 514 """Map the effective-user verdicts back onto the original user set. 515 516 `build()` evaluated the substituted set (parents standing in for their MIRROR actors), so 517 a substituted actor passes iff the identity it mirrors passes. No-op when nothing was 518 substituted -- `self.__result` already refers to the original users. 519 """ 520 if not self.__mirror_of: 521 return self 522 passing = set(self.__result.values_list("pk", flat=True)) 523 final_pks = { 524 pk 525 for pk in self.__original_users.values_list("pk", flat=True) 526 if (self.__mirror_of[pk].pk if pk in self.__mirror_of else pk) in passing 527 } 528 self.__result = self.__original_users.filter(pk__in=final_pks) 529 return self 530 531 def _prefetch_cache( 532 self, 533 candidates: list[User], 534 dynamic_bindings: list[PolicyBinding], 535 dry_run_only_users: list[User] | None = None, 536 dry_run_bindings: list[PolicyBinding] | None = None, 537 ) -> dict[str, PolicyResult]: 538 """Bulk-fetch cached PolicyResults for every (dynamic binding, candidate) pair 539 with a single cache.get_many() call. 540 541 Without this, each candidate's `_evaluate_dynamic_bindings` call would do its 542 own cache.get() per binding -- N candidates x M dynamic bindings individual 543 round trips to the cache backend collapse into one. 544 """ 545 if not self.use_cache: 546 return {} 547 keys = [] 548 for users, bindings in ( 549 (candidates, dynamic_bindings), 550 (dry_run_only_users or [], dry_run_bindings or []), 551 ): 552 for user in users: 553 # Cache keys don't need context-processor enrichment (geoip etc.). 554 request = PolicyRequest(user) 555 request.http_request = self.__http_request 556 for binding in bindings: 557 keys.append(cache_key(binding, request)) 558 if not keys: 559 return {} 560 with HIST_POLICIES_EXECUTION_TIME.labels( 561 binding_order=-1, 562 binding_target_type="bulk", 563 binding_target_name="", 564 object_type=class_to_path(self.__pbm.__class__), 565 mode="cache_retrieve_bulk", 566 ).time(): 567 return cache.get_many(keys) 568 569 @property 570 def result(self) -> QuerySet[User]: 571 """Get the subset of the user queryset that passes""" 572 return self.__result 573 574 def _filter_static( 575 self, base: QuerySet[User], bindings: list[PolicyBinding], mode: PolicyEngineMode 576 ) -> QuerySet[User]: 577 """Apply static (group/user) bindings to `base` using SQL only.""" 578 if mode == PolicyEngineMode.MODE_ALL: 579 qs = base 580 for binding in bindings: 581 qs = qs.filter(self._binding_to_q(binding)) 582 # Chained filters can produce duplicates if the same row satisfies multiple 583 # JOINs trivially; .distinct() guarantees uniqueness. 584 return qs.distinct() 585 586 # MODE_ANY (and any unknown mode) -> OR-combine per-binding Q 587 combined = self._binding_to_q(bindings[0]) 588 for binding in bindings[1:]: 589 combined |= self._binding_to_q(binding) 590 return base.filter(combined).distinct() 591 592 def _binding_to_q(self, binding: PolicyBinding) -> Q: 593 """Translate a single static PolicyBinding into a Q expression matching users 594 for whom the binding "passes" (per `PolicyEngine.compute_static_bindings`).""" 595 if binding.user_id: 596 match = Q(pk=binding.user_id) 597 else: 598 # Group binding: match users in the bound group OR any descendant. 599 # "binding.group in user.all_groups()" is equivalent to 600 # "user is in binding.group.with_descendants()". 601 descendants = Group.objects.filter(pk=binding.group_id).with_descendants() 602 match = Q(groups__in=descendants) 603 if binding.negate: 604 match = ~match 605 return match
Check a QuerySet of users against a single PolicyBindingModel efficiently.
371 def __init__(self, pbm: T, users: QuerySet[User], request: HttpRequest = None): 372 self._init_defaults(pbm) 373 self.__pbm = pbm 374 self.__users = users 375 self.__original_users = users 376 self.__mirror_of: dict = {} 377 self.__http_request = request 378 self.__result: QuerySet[User] | None = None
380 def bindings(self) -> QuerySet[PolicyBinding]: 381 """Get enabled bindings for the bound PBM""" 382 return self._bindings_for(self.__pbm)
Get enabled bindings for the bound PBM
409 def build(self) -> FilterPolicyEngine: 410 """Evaluate bindings against the user queryset""" 411 with ( 412 active_tracer().start_span( 413 op="authentik.policy.engine_filter.build", 414 name=class_to_path(self.__pbm.__class__), 415 ), 416 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 417 obj_type=class_to_path(self.__pbm.__class__), 418 obj_pk=str(self.__pbm.pk), 419 ).time(), 420 ): 421 self._substitute_mirror_actors() 422 bindings = self._select_policies(list(self.bindings())) 423 for binding in bindings: 424 self._check_policy_type(binding) 425 426 if not bindings: 427 self.__result = self.__users if self.empty_result else self.__users.none() 428 return self._finalize() 429 430 dynamic_bindings = [binding for binding in bindings if binding.policy_id is not None] 431 dry_run_bindings = [binding for binding in dynamic_bindings if binding.dry_run] 432 # Static observations use one SQL membership query per binding, rather 433 # than a group lookup per user. They never affect the candidate set. 434 for binding in bindings: 435 if not binding.dry_run or binding.policy_id: 436 continue 437 matching_pks = set( 438 self._filter_static( 439 self.__users, [binding], PolicyEngineMode.MODE_ALL 440 ).values_list("pk", flat=True) 441 ) 442 for user in self.__users: 443 request = PolicyRequest(user) 444 request.obj = self.__pbm 445 if self.__http_request: 446 request.set_http_request(self.__http_request) 447 self._report_static_dry_run( 448 binding, request, PolicyResult(user.pk in matching_pks) 449 ) 450 static_bindings = [ 451 binding 452 for binding in bindings 453 if not binding.dry_run 454 and binding.policy_id is None 455 and (binding.group_id or binding.user_id) 456 ] 457 458 if not dynamic_bindings: 459 # Static enforcement stays in SQL; dry-run observations were reported above. 460 if not static_bindings: 461 self.__result = self.__users if self.empty_result else self.__users.none() 462 else: 463 self.__result = self._filter_static(self.__users, static_bindings, self.mode) 464 return self._finalize() 465 466 # Slow path: real Policy objects can't be translated to SQL and need 467 # per-user evaluation. Pre-compute the static verdict ONCE via SQL (reused 468 # per user as a set-membership check) instead of re-running an aggregate 469 # query per user, and shrink the candidate set first when MODE_ALL allows 470 # it (a static-failing user can never satisfy MODE_ALL overall). 471 static_passing_pks = None 472 if static_bindings: 473 static_passing_pks = set( 474 self._filter_static(self.__users, static_bindings, self.mode).values_list( 475 "pk", flat=True 476 ) 477 ) 478 479 candidates = self.__users 480 dry_run_only_users = [] 481 if self.mode == PolicyEngineMode.MODE_ALL and static_bindings: 482 candidates = candidates.filter(pk__in=static_passing_pks) 483 if dry_run_bindings: 484 dry_run_only_users = list(self.__users.exclude(pk__in=static_passing_pks)) 485 candidates = list(candidates) 486 487 prefetched_cache = self._prefetch_cache( 488 candidates, dynamic_bindings, dry_run_only_users, dry_run_bindings 489 ) 490 491 passing_pks = [] 492 for user in candidates: 493 request = PolicyRequest(user) 494 request.obj = self.__pbm 495 if self.__http_request: 496 request.set_http_request(self.__http_request) 497 all_results = self._evaluate_dynamic_bindings( 498 dynamic_bindings, request, prefetched_cache 499 ) 500 if static_passing_pks is not None: 501 all_results.append(PolicyResult(user.pk in static_passing_pks)) 502 if self._combine_results(self.mode, self.empty_result, all_results).passing: 503 passing_pks.append(user.pk) 504 for user in dry_run_only_users: 505 request = PolicyRequest(user) 506 request.obj = self.__pbm 507 if self.__http_request: 508 request.set_http_request(self.__http_request) 509 self._evaluate_dynamic_bindings(dry_run_bindings, request, prefetched_cache) 510 self.__result = self.__users.filter(pk__in=passing_pks) 511 return self._finalize()
Evaluate bindings against the user queryset
569 @property 570 def result(self) -> QuerySet[User]: 571 """Get the subset of the user queryset that passes""" 572 return self.__result
Get the subset of the user queryset that passes
Inherited Members
608class ListPolicyEngine[T: PolicyBindingModel](_PolicyEngineBase): 609 """Check a single user against a QuerySet of PolicyBindingModels efficiently.""" 610 611 def __init__(self, objs: QuerySet[T], user: User, request: HttpRequest = None): 612 self.logger = get_logger().bind() 613 self.empty_result = True 614 self.use_cache = True 615 self.__objs = objs 616 self.__user = effective_policy_user(user) 617 self.__http_request = request 618 self.__result: QuerySet[T] | None = None 619 620 def build(self) -> ListPolicyEngine[T]: 621 """Evaluate the user against every object in the queryset""" 622 with ( 623 active_tracer().start_span( 624 op="authentik.policy.engine_list.build", 625 name=class_to_path(self.__objs.model), 626 ), 627 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 628 obj_type=class_to_path(self.__objs.model), 629 obj_pk="bulk", 630 ).time(), 631 ): 632 objs = list(self.__objs) 633 if not objs: 634 self.__result = self.__objs 635 return self 636 637 obj_by_pk = {obj.pk: obj for obj in objs} 638 # PolicyBinding.target is a FK to the PolicyBindingModel base table's own 639 # pk (pbm_uuid), which can diverge from a subclass's own `.pk` if that 640 # subclass declares its own primary key. 641 target_field = PolicyBinding._meta.get_field("target").target_field.attname 642 pk_by_target_key = {getattr(obj, target_field): obj.pk for obj in objs} 643 644 bindings_by_target = defaultdict(list) 645 bindings = list( 646 PolicyBinding.objects.filter(target__in=pk_by_target_key.keys(), enabled=True) 647 .select_related("user", "group") 648 .order_by("target", "order") 649 ) 650 self._select_policies(bindings) 651 for binding in bindings: 652 pk = pk_by_target_key[binding.target_id] 653 binding.target = obj_by_pk[pk] 654 self._check_policy_type(binding) 655 bindings_by_target[pk].append(binding) 656 657 # Objects with no bindings at all pass if empty_result, same convention 658 # as PolicyEngine/FilterPolicyEngine. 659 passing_pks = ( 660 {pk for pk in obj_by_pk if pk not in bindings_by_target} 661 if self.empty_result 662 else set() 663 ) 664 if not bindings_by_target: 665 self.__result = self.__objs.filter(pk__in=passing_pks) 666 return self 667 668 # The user is fixed here (unlike FilterPolicyEngine, which varies the 669 # user), so static bindings are resolved with one all_groups() lookup 670 user_group_pks = ( 671 set(self.__user.all_groups().values_list("pk", flat=True)) 672 if self.__user.pk 673 else set() 674 ) 675 676 static_results: dict = {} 677 dynamic_by_target: dict = {} 678 for pk, obj_bindings in bindings_by_target.items(): 679 mode = obj_by_pk[pk].policy_engine_mode 680 static_bindings = [ 681 binding 682 for binding in obj_bindings 683 if not binding.dry_run 684 and binding.policy_id is None 685 and (binding.group_id or binding.user_id) 686 ] 687 dynamic_bindings = [ 688 binding for binding in obj_bindings if binding.policy_id is not None 689 ] 690 if static_bindings: 691 static_results[pk] = self._combine_results( 692 mode, 693 self.empty_result, 694 [ 695 self._static_binding_result(binding, user_group_pks) 696 for binding in static_bindings 697 ], 698 ) 699 # MODE_ALL: effective dynamic bindings cannot change a failed static 700 # verdict, but dry-run bindings still need to execute. 701 if ( 702 mode == PolicyEngineMode.MODE_ALL 703 and pk in static_results 704 and not static_results[pk].passing 705 ): 706 dynamic_bindings = [binding for binding in dynamic_bindings if binding.dry_run] 707 if dynamic_bindings: 708 dynamic_by_target[pk] = dynamic_bindings 709 710 all_dynamic_bindings = [ 711 binding for bindings in dynamic_by_target.values() for binding in bindings 712 ] 713 714 request = PolicyRequest(self.__user) 715 if self.__http_request: 716 request.set_http_request(self.__http_request) 717 prefetched_cache = self._prefetch_cache(request, all_dynamic_bindings) 718 719 for pk in bindings_by_target: 720 mode = obj_by_pk[pk].policy_engine_mode 721 all_results = [] 722 request.obj = obj_by_pk[pk] 723 for binding in bindings_by_target[pk]: 724 if binding.dry_run and not binding.policy_id: 725 all_results.append( 726 self._report_static_dry_run( 727 binding, 728 request, 729 self._static_binding_result(binding, user_group_pks), 730 ) 731 ) 732 if pk in dynamic_by_target: 733 all_results.extend( 734 self._evaluate_dynamic_bindings( 735 dynamic_by_target[pk], copy(request), prefetched_cache 736 ) 737 ) 738 if pk in static_results: 739 all_results.append(static_results[pk]) 740 if self._combine_results(mode, self.empty_result, all_results).passing: 741 passing_pks.add(pk) 742 743 self.__result = self.__objs.filter(pk__in=passing_pks) 744 return self 745 746 def _static_binding_result(self, binding: PolicyBinding, user_group_pks: set) -> PolicyResult: 747 """Evaluate a single static (group/user) binding against the fixed user""" 748 if binding.user_id: 749 match = binding.user_id == self.__user.pk 750 else: 751 match = binding.group_id in user_group_pks 752 if binding.negate: 753 match = not match 754 return PolicyResult(match) 755 756 def _prefetch_cache( 757 self, request: PolicyRequest, dynamic_bindings: list[PolicyBinding] 758 ) -> dict[str, PolicyResult]: 759 """Bulk-fetch cached PolicyResults for every dynamic binding across every 760 object with a single cache.get_many() call.""" 761 if not self.use_cache or not dynamic_bindings: 762 return {} 763 keys = [cache_key(binding, request) for binding in dynamic_bindings] 764 with HIST_POLICIES_EXECUTION_TIME.labels( 765 binding_order=-1, 766 binding_target_type="bulk", 767 binding_target_name="", 768 object_type=class_to_path(self.__objs.model), 769 mode="cache_retrieve_bulk", 770 ).time(): 771 return cache.get_many(keys) 772 773 @property 774 def result(self) -> QuerySet[T]: 775 """Get the subset of the object queryset that the user passes""" 776 return self.__result
Check a single user against a QuerySet of PolicyBindingModels efficiently.
611 def __init__(self, objs: QuerySet[T], user: User, request: HttpRequest = None): 612 self.logger = get_logger().bind() 613 self.empty_result = True 614 self.use_cache = True 615 self.__objs = objs 616 self.__user = effective_policy_user(user) 617 self.__http_request = request 618 self.__result: QuerySet[T] | None = None
620 def build(self) -> ListPolicyEngine[T]: 621 """Evaluate the user against every object in the queryset""" 622 with ( 623 active_tracer().start_span( 624 op="authentik.policy.engine_list.build", 625 name=class_to_path(self.__objs.model), 626 ), 627 HIST_POLICIES_ENGINE_TOTAL_TIME.labels( 628 obj_type=class_to_path(self.__objs.model), 629 obj_pk="bulk", 630 ).time(), 631 ): 632 objs = list(self.__objs) 633 if not objs: 634 self.__result = self.__objs 635 return self 636 637 obj_by_pk = {obj.pk: obj for obj in objs} 638 # PolicyBinding.target is a FK to the PolicyBindingModel base table's own 639 # pk (pbm_uuid), which can diverge from a subclass's own `.pk` if that 640 # subclass declares its own primary key. 641 target_field = PolicyBinding._meta.get_field("target").target_field.attname 642 pk_by_target_key = {getattr(obj, target_field): obj.pk for obj in objs} 643 644 bindings_by_target = defaultdict(list) 645 bindings = list( 646 PolicyBinding.objects.filter(target__in=pk_by_target_key.keys(), enabled=True) 647 .select_related("user", "group") 648 .order_by("target", "order") 649 ) 650 self._select_policies(bindings) 651 for binding in bindings: 652 pk = pk_by_target_key[binding.target_id] 653 binding.target = obj_by_pk[pk] 654 self._check_policy_type(binding) 655 bindings_by_target[pk].append(binding) 656 657 # Objects with no bindings at all pass if empty_result, same convention 658 # as PolicyEngine/FilterPolicyEngine. 659 passing_pks = ( 660 {pk for pk in obj_by_pk if pk not in bindings_by_target} 661 if self.empty_result 662 else set() 663 ) 664 if not bindings_by_target: 665 self.__result = self.__objs.filter(pk__in=passing_pks) 666 return self 667 668 # The user is fixed here (unlike FilterPolicyEngine, which varies the 669 # user), so static bindings are resolved with one all_groups() lookup 670 user_group_pks = ( 671 set(self.__user.all_groups().values_list("pk", flat=True)) 672 if self.__user.pk 673 else set() 674 ) 675 676 static_results: dict = {} 677 dynamic_by_target: dict = {} 678 for pk, obj_bindings in bindings_by_target.items(): 679 mode = obj_by_pk[pk].policy_engine_mode 680 static_bindings = [ 681 binding 682 for binding in obj_bindings 683 if not binding.dry_run 684 and binding.policy_id is None 685 and (binding.group_id or binding.user_id) 686 ] 687 dynamic_bindings = [ 688 binding for binding in obj_bindings if binding.policy_id is not None 689 ] 690 if static_bindings: 691 static_results[pk] = self._combine_results( 692 mode, 693 self.empty_result, 694 [ 695 self._static_binding_result(binding, user_group_pks) 696 for binding in static_bindings 697 ], 698 ) 699 # MODE_ALL: effective dynamic bindings cannot change a failed static 700 # verdict, but dry-run bindings still need to execute. 701 if ( 702 mode == PolicyEngineMode.MODE_ALL 703 and pk in static_results 704 and not static_results[pk].passing 705 ): 706 dynamic_bindings = [binding for binding in dynamic_bindings if binding.dry_run] 707 if dynamic_bindings: 708 dynamic_by_target[pk] = dynamic_bindings 709 710 all_dynamic_bindings = [ 711 binding for bindings in dynamic_by_target.values() for binding in bindings 712 ] 713 714 request = PolicyRequest(self.__user) 715 if self.__http_request: 716 request.set_http_request(self.__http_request) 717 prefetched_cache = self._prefetch_cache(request, all_dynamic_bindings) 718 719 for pk in bindings_by_target: 720 mode = obj_by_pk[pk].policy_engine_mode 721 all_results = [] 722 request.obj = obj_by_pk[pk] 723 for binding in bindings_by_target[pk]: 724 if binding.dry_run and not binding.policy_id: 725 all_results.append( 726 self._report_static_dry_run( 727 binding, 728 request, 729 self._static_binding_result(binding, user_group_pks), 730 ) 731 ) 732 if pk in dynamic_by_target: 733 all_results.extend( 734 self._evaluate_dynamic_bindings( 735 dynamic_by_target[pk], copy(request), prefetched_cache 736 ) 737 ) 738 if pk in static_results: 739 all_results.append(static_results[pk]) 740 if self._combine_results(mode, self.empty_result, all_results).passing: 741 passing_pks.add(pk) 742 743 self.__result = self.__objs.filter(pk__in=passing_pks) 744 return self
Evaluate the user against every object in the queryset
773 @property 774 def result(self) -> QuerySet[T]: 775 """Get the subset of the object queryset that the user passes""" 776 return self.__result
Get the subset of the object queryset that the user passes