authentik.policies.process

authentik policy task

  1"""authentik policy task"""
  2
  3from multiprocessing import get_context
  4from multiprocessing.connection import Connection
  5from time import perf_counter
  6
  7from django.core.cache import cache
  8from django.db import DatabaseError
  9from structlog.stdlib import get_logger
 10
 11from authentik.events.models import Event, EventAction
 12from authentik.lib.config import CONFIG
 13from authentik.lib.tracing import Span, active_tracer
 14from authentik.lib.utils.errors import exception_to_dict
 15from authentik.policies.exceptions import PolicyException
 16from authentik.policies.models import PolicyBinding
 17from authentik.policies.types import CACHE_PREFIX, PolicyRequest, PolicyResult
 18
 19LOGGER = get_logger()
 20
 21FORK_CTX = get_context("fork")
 22CACHE_TIMEOUT = CONFIG.get_int("cache.timeout_policies")
 23PROCESS_CLASS = FORK_CTX.Process
 24
 25
 26def create_policy_event(
 27    binding: PolicyBinding,
 28    request: PolicyRequest,
 29    action: str,
 30    message: str,
 31    **kwargs,
 32) -> None:
 33    """Create an event with common values from a policy request and binding."""
 34    event = Event.new(
 35        action=action,
 36        message=message,
 37        **({"policy_uuid": binding.policy_id.hex} if binding.policy_id else {}),
 38        binding=binding,
 39        request=request,
 40        **kwargs,
 41    )
 42    if request.http_request:
 43        event.from_http(request.http_request, user=request.user)
 44    else:
 45        event.set_user(request.user)
 46        event.save()
 47
 48
 49def cache_key(binding: PolicyBinding, request: PolicyRequest) -> str:
 50    """Generate Cache key for policy"""
 51    prefix = f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_"
 52    if request.http_request and hasattr(request.http_request, "session"):
 53        prefix += f"_{request.http_request.session.session_key}"
 54    if request.user:
 55        prefix += f"#{request.user.pk}"
 56    return prefix
 57
 58
 59class PolicyProcess(PROCESS_CLASS):
 60    """Evaluate a single policy within a separate process"""
 61
 62    connection: Connection
 63    binding: PolicyBinding
 64    request: PolicyRequest
 65    use_cache: bool
 66
 67    def __init__(
 68        self,
 69        binding: PolicyBinding,
 70        request: PolicyRequest,
 71        connection: Connection | None,
 72        use_cache: bool = True,
 73    ):
 74        super().__init__()
 75        self.binding = binding
 76        self.request = request
 77        self.use_cache = use_cache
 78        if not isinstance(self.request, PolicyRequest):
 79            raise ValueError(f"{self.request} is not a Policy Request.")
 80        if connection:
 81            self.connection = connection
 82
 83    def create_event(self, action: str, message: str, **kwargs):
 84        """Create event with common values from `self.request` and `self.binding`."""
 85        create_policy_event(self.binding, self.request, action, message, **kwargs)
 86
 87    def execute(self) -> PolicyResult:
 88        """Run actual policy, returns result"""
 89        LOGGER.debug(
 90            "P_ENG(proc): Running policy",
 91            policy=self.binding.policy,
 92            user=self.request.user.username,
 93            # this is used for filtering in access checking where logs are sent to the admin
 94            process="PolicyProcess",
 95        )
 96        try:
 97            policy_result = self.binding.passes(self.request)
 98            # Invert result if policy.negate is set
 99            if self.binding.negate:
100                policy_result.passing = not policy_result.passing
101            if self.binding.policy and not self.request.debug and not self.binding.dry_run:
102                if self.binding.policy.execution_logging:
103                    try:
104                        self.create_event(
105                            EventAction.POLICY_EXECUTION,
106                            message="Policy Execution",
107                            result=policy_result,
108                        )
109                    except DatabaseError as exc:
110                        LOGGER.warning("Failed to log policy execution", exc=exc)
111        except PolicyException as exc:
112            # Either use passed original exception or whatever we have
113            src_exc = exc.src_exc if exc.src_exc else exc
114            # Create policy exception event, only when we're not debugging
115            if not self.request.debug:
116                self.create_event(
117                    EventAction.POLICY_EXCEPTION,
118                    message="Policy failed to execute",
119                    exception=exception_to_dict(src_exc),
120                )
121            LOGGER.debug("P_ENG(proc): error, using failure result", exc=src_exc)
122            policy_result = PolicyResult(self.binding.failure_result, str(src_exc))
123        policy_result.source_binding = self.binding
124        if self.binding.dry_run and not self.request.debug:
125            self.create_event(
126                EventAction.POLICY_EXECUTION,
127                message="Policy Execution (dry run)",
128                result=policy_result,
129                dry_run=True,
130                cached=False,
131            )
132        # Engines bypass the cache when the result depends on request context the key
133        # doesn't capture, so it mustn't be served to anyone else either
134        should_cache = self.use_cache and self.request.should_cache
135        if should_cache:
136            key = cache_key(self.binding, self.request)
137            try:
138                cache.set(key, policy_result, CACHE_TIMEOUT)
139            except DatabaseError as exc:
140                LOGGER.warning("Failed to cache policy result", exc=exc)
141        LOGGER.debug(
142            "P_ENG(proc): finished",
143            policy=self.binding.policy,
144            cached=should_cache,
145            result=policy_result,
146            # this is used for filtering in access checking where logs are sent to the admin
147            process="PolicyProcess",
148            passing=policy_result.passing,
149            user=self.request.user.username,
150        )
151        return policy_result
152
153    def profiling_wrapper(self):
154        """Run with profiling enabled"""
155        with active_tracer().start_span(
156            op="authentik.policy.process.execute",
157        ) as span:
158            span: Span
159            span.set_data("policy", self.binding.policy)
160            span.set_data("request", self.request)
161            return self.execute()
162
163    def run(self):  # pragma: no cover
164        """Task wrapper to run policy checking"""
165        result = None
166        try:
167            start = perf_counter()
168            result = self.profiling_wrapper()
169            end = perf_counter()
170            result._exec_time = max((end - start), 0)
171        except Exception as exc:  # noqa
172            LOGGER.warning("Policy failed to run", exc=exc)
173            result = PolicyResult(self.binding.failure_result, str(exc))
174            result.source_binding = self.binding
175        finally:
176            self.connection.send(result)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
FORK_CTX = <multiprocessing.context.ForkContext object>
CACHE_TIMEOUT = 300
PROCESS_CLASS = <class 'multiprocessing.context.ForkProcess'>
def create_policy_event( binding: authentik.policies.models.PolicyBinding, request: authentik.policies.types.PolicyRequest, action: str, message: str, **kwargs) -> None:
27def create_policy_event(
28    binding: PolicyBinding,
29    request: PolicyRequest,
30    action: str,
31    message: str,
32    **kwargs,
33) -> None:
34    """Create an event with common values from a policy request and binding."""
35    event = Event.new(
36        action=action,
37        message=message,
38        **({"policy_uuid": binding.policy_id.hex} if binding.policy_id else {}),
39        binding=binding,
40        request=request,
41        **kwargs,
42    )
43    if request.http_request:
44        event.from_http(request.http_request, user=request.user)
45    else:
46        event.set_user(request.user)
47        event.save()

Create an event with common values from a policy request and binding.

def cache_key( binding: authentik.policies.models.PolicyBinding, request: authentik.policies.types.PolicyRequest) -> str:
50def cache_key(binding: PolicyBinding, request: PolicyRequest) -> str:
51    """Generate Cache key for policy"""
52    prefix = f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_"
53    if request.http_request and hasattr(request.http_request, "session"):
54        prefix += f"_{request.http_request.session.session_key}"
55    if request.user:
56        prefix += f"#{request.user.pk}"
57    return prefix

Generate Cache key for policy

class PolicyProcess(multiprocessing.context.ForkProcess):
 60class PolicyProcess(PROCESS_CLASS):
 61    """Evaluate a single policy within a separate process"""
 62
 63    connection: Connection
 64    binding: PolicyBinding
 65    request: PolicyRequest
 66    use_cache: bool
 67
 68    def __init__(
 69        self,
 70        binding: PolicyBinding,
 71        request: PolicyRequest,
 72        connection: Connection | None,
 73        use_cache: bool = True,
 74    ):
 75        super().__init__()
 76        self.binding = binding
 77        self.request = request
 78        self.use_cache = use_cache
 79        if not isinstance(self.request, PolicyRequest):
 80            raise ValueError(f"{self.request} is not a Policy Request.")
 81        if connection:
 82            self.connection = connection
 83
 84    def create_event(self, action: str, message: str, **kwargs):
 85        """Create event with common values from `self.request` and `self.binding`."""
 86        create_policy_event(self.binding, self.request, action, message, **kwargs)
 87
 88    def execute(self) -> PolicyResult:
 89        """Run actual policy, returns result"""
 90        LOGGER.debug(
 91            "P_ENG(proc): Running policy",
 92            policy=self.binding.policy,
 93            user=self.request.user.username,
 94            # this is used for filtering in access checking where logs are sent to the admin
 95            process="PolicyProcess",
 96        )
 97        try:
 98            policy_result = self.binding.passes(self.request)
 99            # Invert result if policy.negate is set
100            if self.binding.negate:
101                policy_result.passing = not policy_result.passing
102            if self.binding.policy and not self.request.debug and not self.binding.dry_run:
103                if self.binding.policy.execution_logging:
104                    try:
105                        self.create_event(
106                            EventAction.POLICY_EXECUTION,
107                            message="Policy Execution",
108                            result=policy_result,
109                        )
110                    except DatabaseError as exc:
111                        LOGGER.warning("Failed to log policy execution", exc=exc)
112        except PolicyException as exc:
113            # Either use passed original exception or whatever we have
114            src_exc = exc.src_exc if exc.src_exc else exc
115            # Create policy exception event, only when we're not debugging
116            if not self.request.debug:
117                self.create_event(
118                    EventAction.POLICY_EXCEPTION,
119                    message="Policy failed to execute",
120                    exception=exception_to_dict(src_exc),
121                )
122            LOGGER.debug("P_ENG(proc): error, using failure result", exc=src_exc)
123            policy_result = PolicyResult(self.binding.failure_result, str(src_exc))
124        policy_result.source_binding = self.binding
125        if self.binding.dry_run and not self.request.debug:
126            self.create_event(
127                EventAction.POLICY_EXECUTION,
128                message="Policy Execution (dry run)",
129                result=policy_result,
130                dry_run=True,
131                cached=False,
132            )
133        # Engines bypass the cache when the result depends on request context the key
134        # doesn't capture, so it mustn't be served to anyone else either
135        should_cache = self.use_cache and self.request.should_cache
136        if should_cache:
137            key = cache_key(self.binding, self.request)
138            try:
139                cache.set(key, policy_result, CACHE_TIMEOUT)
140            except DatabaseError as exc:
141                LOGGER.warning("Failed to cache policy result", exc=exc)
142        LOGGER.debug(
143            "P_ENG(proc): finished",
144            policy=self.binding.policy,
145            cached=should_cache,
146            result=policy_result,
147            # this is used for filtering in access checking where logs are sent to the admin
148            process="PolicyProcess",
149            passing=policy_result.passing,
150            user=self.request.user.username,
151        )
152        return policy_result
153
154    def profiling_wrapper(self):
155        """Run with profiling enabled"""
156        with active_tracer().start_span(
157            op="authentik.policy.process.execute",
158        ) as span:
159            span: Span
160            span.set_data("policy", self.binding.policy)
161            span.set_data("request", self.request)
162            return self.execute()
163
164    def run(self):  # pragma: no cover
165        """Task wrapper to run policy checking"""
166        result = None
167        try:
168            start = perf_counter()
169            result = self.profiling_wrapper()
170            end = perf_counter()
171            result._exec_time = max((end - start), 0)
172        except Exception as exc:  # noqa
173            LOGGER.warning("Policy failed to run", exc=exc)
174            result = PolicyResult(self.binding.failure_result, str(exc))
175            result.source_binding = self.binding
176        finally:
177            self.connection.send(result)

Evaluate a single policy within a separate process

PolicyProcess( binding: authentik.policies.models.PolicyBinding, request: authentik.policies.types.PolicyRequest, connection: multiprocessing.connection.Connection | None, use_cache: bool = True)
68    def __init__(
69        self,
70        binding: PolicyBinding,
71        request: PolicyRequest,
72        connection: Connection | None,
73        use_cache: bool = True,
74    ):
75        super().__init__()
76        self.binding = binding
77        self.request = request
78        self.use_cache = use_cache
79        if not isinstance(self.request, PolicyRequest):
80            raise ValueError(f"{self.request} is not a Policy Request.")
81        if connection:
82            self.connection = connection
connection: multiprocessing.connection.Connection
use_cache: bool
def create_event(self, action: str, message: str, **kwargs):
84    def create_event(self, action: str, message: str, **kwargs):
85        """Create event with common values from `self.request` and `self.binding`."""
86        create_policy_event(self.binding, self.request, action, message, **kwargs)

Create event with common values from self.request and self.binding.

def execute(self) -> authentik.policies.types.PolicyResult:
 88    def execute(self) -> PolicyResult:
 89        """Run actual policy, returns result"""
 90        LOGGER.debug(
 91            "P_ENG(proc): Running policy",
 92            policy=self.binding.policy,
 93            user=self.request.user.username,
 94            # this is used for filtering in access checking where logs are sent to the admin
 95            process="PolicyProcess",
 96        )
 97        try:
 98            policy_result = self.binding.passes(self.request)
 99            # Invert result if policy.negate is set
100            if self.binding.negate:
101                policy_result.passing = not policy_result.passing
102            if self.binding.policy and not self.request.debug and not self.binding.dry_run:
103                if self.binding.policy.execution_logging:
104                    try:
105                        self.create_event(
106                            EventAction.POLICY_EXECUTION,
107                            message="Policy Execution",
108                            result=policy_result,
109                        )
110                    except DatabaseError as exc:
111                        LOGGER.warning("Failed to log policy execution", exc=exc)
112        except PolicyException as exc:
113            # Either use passed original exception or whatever we have
114            src_exc = exc.src_exc if exc.src_exc else exc
115            # Create policy exception event, only when we're not debugging
116            if not self.request.debug:
117                self.create_event(
118                    EventAction.POLICY_EXCEPTION,
119                    message="Policy failed to execute",
120                    exception=exception_to_dict(src_exc),
121                )
122            LOGGER.debug("P_ENG(proc): error, using failure result", exc=src_exc)
123            policy_result = PolicyResult(self.binding.failure_result, str(src_exc))
124        policy_result.source_binding = self.binding
125        if self.binding.dry_run and not self.request.debug:
126            self.create_event(
127                EventAction.POLICY_EXECUTION,
128                message="Policy Execution (dry run)",
129                result=policy_result,
130                dry_run=True,
131                cached=False,
132            )
133        # Engines bypass the cache when the result depends on request context the key
134        # doesn't capture, so it mustn't be served to anyone else either
135        should_cache = self.use_cache and self.request.should_cache
136        if should_cache:
137            key = cache_key(self.binding, self.request)
138            try:
139                cache.set(key, policy_result, CACHE_TIMEOUT)
140            except DatabaseError as exc:
141                LOGGER.warning("Failed to cache policy result", exc=exc)
142        LOGGER.debug(
143            "P_ENG(proc): finished",
144            policy=self.binding.policy,
145            cached=should_cache,
146            result=policy_result,
147            # this is used for filtering in access checking where logs are sent to the admin
148            process="PolicyProcess",
149            passing=policy_result.passing,
150            user=self.request.user.username,
151        )
152        return policy_result

Run actual policy, returns result

def profiling_wrapper(self):
154    def profiling_wrapper(self):
155        """Run with profiling enabled"""
156        with active_tracer().start_span(
157            op="authentik.policy.process.execute",
158        ) as span:
159            span: Span
160            span.set_data("policy", self.binding.policy)
161            span.set_data("request", self.request)
162            return self.execute()

Run with profiling enabled

def run(self):
164    def run(self):  # pragma: no cover
165        """Task wrapper to run policy checking"""
166        result = None
167        try:
168            start = perf_counter()
169            result = self.profiling_wrapper()
170            end = perf_counter()
171            result._exec_time = max((end - start), 0)
172        except Exception as exc:  # noqa
173            LOGGER.warning("Policy failed to run", exc=exc)
174            result = PolicyResult(self.binding.failure_result, str(exc))
175            result.source_binding = self.binding
176        finally:
177            self.connection.send(result)

Task wrapper to run policy checking