authentik.lib.expression.evaluator

authentik expression policy evaluator

  1"""authentik expression policy evaluator"""
  2
  3import re
  4import socket
  5from ipaddress import ip_address, ip_network
  6from smtplib import SMTPException
  7from textwrap import indent
  8from types import CodeType
  9from typing import TYPE_CHECKING, Any
 10
 11from cachetools import TLRUCache, cached
 12from django.core.exceptions import FieldError
 13from django.db.models import Model
 14from django.http import HttpRequest
 15from django.utils.functional import SimpleLazyObject
 16from django.utils.text import slugify
 17from django.utils.timezone import now
 18from guardian.shortcuts import get_anonymous_user
 19from rest_framework.serializers import ValidationError
 20from structlog.stdlib import get_logger
 21
 22from authentik.core.models import User
 23from authentik.events.models import Event
 24from authentik.lib.expression.exceptions import ControlFlowException
 25from authentik.lib.tracing import Span, active_tracer
 26from authentik.lib.utils.dict import get_path_from_dict
 27from authentik.lib.utils.email import Address, normalize_addresses
 28from authentik.lib.utils.http import get_http_session
 29from authentik.lib.utils.time import timedelta_from_string
 30from authentik.policies.models import Policy, PolicyBinding
 31from authentik.policies.process import PolicyProcess
 32from authentik.policies.types import PolicyRequest, PolicyResult
 33from authentik.policies.utils import delete_none_values
 34from authentik.providers.oauth2.id_token import IDToken
 35from authentik.providers.oauth2.models import AccessToken, OAuth2Provider
 36from authentik.stages.authenticator import devices_for_user
 37from authentik.stages.email.utils import TemplateEmailMessage
 38
 39if TYPE_CHECKING:
 40    from authentik.stages.email.models import EmailStage
 41
 42LOGGER = get_logger()
 43
 44ARG_SANITIZE = re.compile(r"[:.-]")
 45
 46
 47def sanitize_arg(arg_name: str) -> str:
 48    return re.sub(ARG_SANITIZE, "_", slugify(arg_name))
 49
 50
 51class BaseEvaluator:
 52    """Validate and evaluate python-based expressions"""
 53
 54    # Globals that can be used by function
 55    _globals: dict[str, Any]
 56    # Context passed as locals to exec()
 57    _context: dict[str, Any]
 58
 59    # Filename used for exec
 60    _filename: str
 61
 62    def __init__(self, filename: str | None = None):
 63        self._filename = filename if filename else "BaseEvaluator"
 64        # update website/docs/expressions/reference/_objects.mdx
 65        # update website/docs/expressions/reference/_functions.mdx
 66        self._globals = {
 67            "ak_call_policy": self.expr_func_call_policy,
 68            "ak_create_event": self.expr_event_create,
 69            "ak_create_jwt": self.expr_create_jwt,
 70            "ak_create_jwt_raw": self.expr_create_jwt_raw,
 71            "ak_is_group_member": BaseEvaluator.expr_is_group_member,
 72            "ak_logger": get_logger(self._filename).bind(),
 73            "ak_send_email": self.expr_send_email,
 74            "ak_user_by": BaseEvaluator.expr_user_by,
 75            "ak_user_has_authenticator": BaseEvaluator.expr_func_user_has_authenticator,
 76            "ak_obj_attr": BaseEvaluator.expr_obj_attr,
 77            "ip_address": ip_address,
 78            "ip_network": ip_network,
 79            "list_flatten": BaseEvaluator.expr_flatten,
 80            "regex_match": BaseEvaluator.expr_regex_match,
 81            "regex_replace": BaseEvaluator.expr_regex_replace,
 82            "requests": SimpleLazyObject(get_http_session),
 83            "resolve_dns": BaseEvaluator.expr_resolve_dns,
 84            "reverse_dns": BaseEvaluator.expr_reverse_dns,
 85            "slugify": slugify,
 86            "delete_none_values": delete_none_values,
 87        }
 88        self._context = {}
 89
 90    @cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
 91    @staticmethod
 92    def expr_resolve_dns(host: str, ip_version: int | None = None) -> list[str]:
 93        """Resolve host to a list of IPv4 and/or IPv6 addresses."""
 94        # Although it seems to be fine (raising OSError), docs warn
 95        # against passing `None` for both the host and the port
 96        # https://docs.python.org/3/library/socket.html#socket.getaddrinfo
 97        host = host or ""
 98
 99        ip_list = []
100
101        family = 0
102        if ip_version == 4:  # noqa: PLR2004
103            family = socket.AF_INET
104        if ip_version == 6:  # noqa: PLR2004
105            family = socket.AF_INET6
106
107        try:
108            for ip_addr in socket.getaddrinfo(host, None, family=family):
109                ip_list.append(str(ip_addr[4][0]))
110        except OSError:
111            pass
112        return list(set(ip_list))
113
114    @cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
115    @staticmethod
116    def expr_reverse_dns(ip_addr: str) -> str:
117        """Perform a reverse DNS lookup."""
118        try:
119            return socket.getfqdn(ip_addr)
120        except OSError:
121            return ip_addr
122
123    @staticmethod
124    def expr_flatten(value: list[Any] | Any) -> Any | None:
125        """Flatten `value` if its a list"""
126        if isinstance(value, list):
127            if len(value) < 1:
128                return None
129            return value[0]
130        return value
131
132    @staticmethod
133    def expr_regex_match(value: Any, regex: str) -> bool:
134        """Expression Filter to run re.search"""
135        return re.search(regex, value) is not None
136
137    @staticmethod
138    def expr_regex_replace(value: Any, regex: str, repl: str) -> str:
139        """Expression Filter to run re.sub"""
140        return re.sub(regex, repl, value)
141
142    @staticmethod
143    def expr_is_group_member(user: User, **group_filters) -> bool:
144        """Check if `user` is member of group with name `group_name`"""
145        return user.all_groups().filter(**group_filters).exists()
146
147    @staticmethod
148    def expr_user_by(**filters) -> User | None:
149        """Get user by filters"""
150        try:
151            users = User.objects.filter(**filters)
152            if users:
153                return users.first()
154            return None
155        except FieldError:
156            return None
157
158    @staticmethod
159    def expr_func_user_has_authenticator(user: User, device_type: str | None = None) -> bool:
160        """Check if a user has any authenticator devices, optionally matching *device_type*"""
161        user_devices = devices_for_user(user)
162        if device_type:
163            for device in user_devices:
164                device_class = device.__class__.__name__.lower().replace("device", "")
165                if device_class == device_type:
166                    return True
167            return False
168        return len(list(user_devices)) > 0
169
170    @staticmethod
171    def expr_obj_attr(obj: Model, attr_key: str, fallback: str | None = None) -> Any:
172        """Get an attribute of the given object if set by its dotted path, otherwise
173        return fallback value."""
174        attrs = getattr(obj, "attributes", {})
175        value = get_path_from_dict(attrs, attr_key)
176        if value is None and fallback is not None:
177            return getattr(obj, fallback, fallback)
178        return value
179
180    def expr_event_create(self, action: str, **kwargs):
181        """Create event with supplied data and try to extract as much relevant data
182        from the context"""
183        context = self._context.copy()
184        # If the result was a complex variable, we don't want to reuse it
185        context.pop("result", None)
186        context.pop("handler", None)
187        event_kwargs = context
188        event_kwargs.update(kwargs)
189        event = Event.new(
190            action,
191            app=self._filename,
192            **event_kwargs,
193        )
194        if "request" in context and isinstance(context["request"], PolicyRequest):
195            policy_request: PolicyRequest = context["request"]
196            if policy_request.http_request:
197                event.from_http(policy_request.http_request)
198                return
199        event.save()
200
201    def expr_func_call_policy(self, name: str, **kwargs) -> PolicyResult:
202        """Call policy by name, with current request"""
203        policy = Policy.objects.filter(name=name).select_subclasses().first()
204        if not policy:
205            raise ValueError(f"Policy '{name}' not found.")
206        user = self._context.get("user", get_anonymous_user())
207        req = PolicyRequest(user)
208        if "request" in self._context:
209            current_req: PolicyRequest = self._context["request"]
210            req = current_req.deepcopy()
211        req.context.update(kwargs)
212        # The binding is unsaved and gets a new primary key on every call, so a cached
213        # result could never be read back
214        proc = PolicyProcess(
215            PolicyBinding(policy=policy), request=req, connection=None, use_cache=False
216        )
217        return proc.profiling_wrapper()
218
219    def expr_create_jwt(
220        self,
221        user: User,
222        provider: OAuth2Provider | str,
223        scopes: list[str],
224        validity: str = "seconds=60",
225    ) -> str | None:
226        """Issue a JWT for a given provider"""
227        request: HttpRequest | None = self._context.get("http_request")
228        if not request:
229            return None
230        if not isinstance(provider, OAuth2Provider):
231            provider = OAuth2Provider.objects.get(name=provider)
232        session = None
233        if hasattr(request, "session") and request.session.session_key:
234            session = request.session["authenticatedsession"]
235        access_token = AccessToken(
236            provider=provider,
237            user=user,
238            expires=now() + timedelta_from_string(validity),
239            scope=scopes,
240            auth_time=now(),
241            session=session,
242        )
243        access_token.id_token = IDToken.new(provider, access_token, request)
244        access_token.save()
245        return access_token.token
246
247    def expr_create_jwt_raw(
248        self, provider: OAuth2Provider | str, validity: str = "seconds=60", **kwargs
249    ) -> str:
250        """Issue a JWT for a given provider with completely customized data"""
251        if not isinstance(provider, OAuth2Provider):
252            provider = OAuth2Provider.objects.get(name=provider)
253        kwargs["exp"] = int((now() + timedelta_from_string(validity)).timestamp())
254        kwargs["aud"] = provider.client_id
255        return provider.encode(kwargs)
256
257    def expr_send_email(  # noqa: PLR0913, PLR0917
258        self,
259        address: Address,
260        subject: str,
261        body: str | None = None,
262        stage: EmailStage | None = None,
263        template: str | None = None,
264        context: dict | None = None,
265        cc: Address = None,
266        bcc: Address = None,
267    ) -> bool:
268        """Send an email using authentik's email system
269
270        Args:
271            address: Email address(es) to send to. Can be:
272                - Single email: "user@example.com"
273                - Formatted address: "John Doe <user@example.com>"
274                - (name, email) tuple: ("John Doe", "user@example.com")
275                - List of any of the above
276            subject: Email subject
277            body: Email body (plain text/HTML). Mutually exclusive with template.
278            stage: EmailStage instance to use for settings. If None, uses global settings.
279            template: Template name to render. Mutually exclusive with body.
280            context: Additional context variables for template rendering.
281            cc: Email address(es) to CC. Same format as address.
282            bcc: Email address(es) to BCC. Same format as address.
283
284        Returns:
285            bool: True if email was queued successfully, False otherwise
286        """
287        # Deferred imports to avoid circular import issues
288        from authentik.stages.email.tasks import send_mails
289
290        if body and template:
291            raise ValueError("body and template parameters are mutually exclusive")
292
293        if not body and not template:
294            raise ValueError("Either body or template parameter must be provided")
295
296        to_addresses = normalize_addresses(address)
297        cc_addresses = normalize_addresses(cc)
298        bcc_addresses = normalize_addresses(bcc)
299
300        try:
301            if template is not None:
302                # Use all available context from the evaluator for template rendering
303                template_context = self._context.copy()
304                # Add any custom context passed to the function
305                if context:
306                    template_context.update(context)
307
308                # Use template rendering
309                message = TemplateEmailMessage(
310                    subject=subject,
311                    to=to_addresses,
312                    cc=cc_addresses,
313                    bcc=bcc_addresses,
314                    template_name=template,
315                    template_context=template_context,
316                )
317            else:
318                # Use plain body
319                message = TemplateEmailMessage(
320                    subject=subject,
321                    to=to_addresses,
322                    cc=cc_addresses,
323                    bcc=bcc_addresses,
324                    body=body,
325                )
326
327            send_mails(stage, message)
328            return True
329
330        except (SMTPException, ConnectionError, ValidationError, ValueError) as exc:
331            LOGGER.warning("Failed to send email", exc=exc, addresses=to_addresses, subject=subject)
332            return False
333
334    def wrap_expression(self, expression: str) -> str:
335        """Wrap expression in a function, call it, and save the result as `result`"""
336        handler_signature = ",".join(
337            [x for x in [sanitize_arg(x) for x in self._context.keys()] if x]
338        )
339        full_expression = ""
340        full_expression += f"def handler({handler_signature}):\n"
341        full_expression += indent(expression, "    ")
342        full_expression += f"\nresult = handler({handler_signature})"
343        return full_expression
344
345    def compile(self, expression: str) -> CodeType:
346        """Parse expression. Raises SyntaxError or ValueError if the syntax is incorrect."""
347        expression = self.wrap_expression(expression)
348        return compile(expression, self._filename, "exec")
349
350    def evaluate(self, expression_source: str) -> Any:
351        """Parse and evaluate expression. If the syntax is incorrect, a SyntaxError is raised.
352        If any exception is raised during execution, it is raised.
353        The result is returned without any type-checking."""
354        with active_tracer().start_span(op="authentik.lib.evaluator.evaluate") as span:
355            span: Span
356            span.description = self._filename
357            span.set_data("expression", expression_source)
358            try:
359                ast_obj = self.compile(expression_source)
360            except (SyntaxError, ValueError) as exc:
361                self.handle_error(exc, expression_source)
362                raise exc
363            try:
364                _locals = {sanitize_arg(x): y for x, y in self._context.items()}
365                # Yes this is an exec, yes it is potentially bad. Since we limit what variables are
366                # available here, and these policies can only be edited by admins, this is a risk
367                # we're willing to take.
368
369                exec(ast_obj, self._globals, _locals)  # nosec # noqa
370                result = _locals["result"]
371            except Exception as exc:
372                # So, this is a bit questionable. Essentially, we are edit the stacktrace
373                # so the user only sees information relevant to them
374                # and none of our surrounding error handling
375                if exc.__traceback__ is not None:
376                    exc.__traceback__ = exc.__traceback__.tb_next
377                if not isinstance(exc, ControlFlowException):
378                    self.handle_error(exc, expression_source)
379                raise exc
380            return result
381
382    def handle_error(self, exc: Exception, expression_source: str):  # pragma: no cover
383        """Exception Handler"""
384        LOGGER.warning("Expression error", exc=exc)
385
386    def validate(self, expression: str) -> bool:
387        """Validate expression's syntax, raise ValidationError if Syntax is invalid"""
388        try:
389            self.compile(expression)
390            return True
391        except (ValueError, SyntaxError) as exc:
392            raise ValidationError(f"Expression Syntax Error: {str(exc)}") from exc
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
ARG_SANITIZE = re.compile('[:.-]')
def sanitize_arg(arg_name: str) -> str:
48def sanitize_arg(arg_name: str) -> str:
49    return re.sub(ARG_SANITIZE, "_", slugify(arg_name))
class BaseEvaluator:
 52class BaseEvaluator:
 53    """Validate and evaluate python-based expressions"""
 54
 55    # Globals that can be used by function
 56    _globals: dict[str, Any]
 57    # Context passed as locals to exec()
 58    _context: dict[str, Any]
 59
 60    # Filename used for exec
 61    _filename: str
 62
 63    def __init__(self, filename: str | None = None):
 64        self._filename = filename if filename else "BaseEvaluator"
 65        # update website/docs/expressions/reference/_objects.mdx
 66        # update website/docs/expressions/reference/_functions.mdx
 67        self._globals = {
 68            "ak_call_policy": self.expr_func_call_policy,
 69            "ak_create_event": self.expr_event_create,
 70            "ak_create_jwt": self.expr_create_jwt,
 71            "ak_create_jwt_raw": self.expr_create_jwt_raw,
 72            "ak_is_group_member": BaseEvaluator.expr_is_group_member,
 73            "ak_logger": get_logger(self._filename).bind(),
 74            "ak_send_email": self.expr_send_email,
 75            "ak_user_by": BaseEvaluator.expr_user_by,
 76            "ak_user_has_authenticator": BaseEvaluator.expr_func_user_has_authenticator,
 77            "ak_obj_attr": BaseEvaluator.expr_obj_attr,
 78            "ip_address": ip_address,
 79            "ip_network": ip_network,
 80            "list_flatten": BaseEvaluator.expr_flatten,
 81            "regex_match": BaseEvaluator.expr_regex_match,
 82            "regex_replace": BaseEvaluator.expr_regex_replace,
 83            "requests": SimpleLazyObject(get_http_session),
 84            "resolve_dns": BaseEvaluator.expr_resolve_dns,
 85            "reverse_dns": BaseEvaluator.expr_reverse_dns,
 86            "slugify": slugify,
 87            "delete_none_values": delete_none_values,
 88        }
 89        self._context = {}
 90
 91    @cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
 92    @staticmethod
 93    def expr_resolve_dns(host: str, ip_version: int | None = None) -> list[str]:
 94        """Resolve host to a list of IPv4 and/or IPv6 addresses."""
 95        # Although it seems to be fine (raising OSError), docs warn
 96        # against passing `None` for both the host and the port
 97        # https://docs.python.org/3/library/socket.html#socket.getaddrinfo
 98        host = host or ""
 99
100        ip_list = []
101
102        family = 0
103        if ip_version == 4:  # noqa: PLR2004
104            family = socket.AF_INET
105        if ip_version == 6:  # noqa: PLR2004
106            family = socket.AF_INET6
107
108        try:
109            for ip_addr in socket.getaddrinfo(host, None, family=family):
110                ip_list.append(str(ip_addr[4][0]))
111        except OSError:
112            pass
113        return list(set(ip_list))
114
115    @cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
116    @staticmethod
117    def expr_reverse_dns(ip_addr: str) -> str:
118        """Perform a reverse DNS lookup."""
119        try:
120            return socket.getfqdn(ip_addr)
121        except OSError:
122            return ip_addr
123
124    @staticmethod
125    def expr_flatten(value: list[Any] | Any) -> Any | None:
126        """Flatten `value` if its a list"""
127        if isinstance(value, list):
128            if len(value) < 1:
129                return None
130            return value[0]
131        return value
132
133    @staticmethod
134    def expr_regex_match(value: Any, regex: str) -> bool:
135        """Expression Filter to run re.search"""
136        return re.search(regex, value) is not None
137
138    @staticmethod
139    def expr_regex_replace(value: Any, regex: str, repl: str) -> str:
140        """Expression Filter to run re.sub"""
141        return re.sub(regex, repl, value)
142
143    @staticmethod
144    def expr_is_group_member(user: User, **group_filters) -> bool:
145        """Check if `user` is member of group with name `group_name`"""
146        return user.all_groups().filter(**group_filters).exists()
147
148    @staticmethod
149    def expr_user_by(**filters) -> User | None:
150        """Get user by filters"""
151        try:
152            users = User.objects.filter(**filters)
153            if users:
154                return users.first()
155            return None
156        except FieldError:
157            return None
158
159    @staticmethod
160    def expr_func_user_has_authenticator(user: User, device_type: str | None = None) -> bool:
161        """Check if a user has any authenticator devices, optionally matching *device_type*"""
162        user_devices = devices_for_user(user)
163        if device_type:
164            for device in user_devices:
165                device_class = device.__class__.__name__.lower().replace("device", "")
166                if device_class == device_type:
167                    return True
168            return False
169        return len(list(user_devices)) > 0
170
171    @staticmethod
172    def expr_obj_attr(obj: Model, attr_key: str, fallback: str | None = None) -> Any:
173        """Get an attribute of the given object if set by its dotted path, otherwise
174        return fallback value."""
175        attrs = getattr(obj, "attributes", {})
176        value = get_path_from_dict(attrs, attr_key)
177        if value is None and fallback is not None:
178            return getattr(obj, fallback, fallback)
179        return value
180
181    def expr_event_create(self, action: str, **kwargs):
182        """Create event with supplied data and try to extract as much relevant data
183        from the context"""
184        context = self._context.copy()
185        # If the result was a complex variable, we don't want to reuse it
186        context.pop("result", None)
187        context.pop("handler", None)
188        event_kwargs = context
189        event_kwargs.update(kwargs)
190        event = Event.new(
191            action,
192            app=self._filename,
193            **event_kwargs,
194        )
195        if "request" in context and isinstance(context["request"], PolicyRequest):
196            policy_request: PolicyRequest = context["request"]
197            if policy_request.http_request:
198                event.from_http(policy_request.http_request)
199                return
200        event.save()
201
202    def expr_func_call_policy(self, name: str, **kwargs) -> PolicyResult:
203        """Call policy by name, with current request"""
204        policy = Policy.objects.filter(name=name).select_subclasses().first()
205        if not policy:
206            raise ValueError(f"Policy '{name}' not found.")
207        user = self._context.get("user", get_anonymous_user())
208        req = PolicyRequest(user)
209        if "request" in self._context:
210            current_req: PolicyRequest = self._context["request"]
211            req = current_req.deepcopy()
212        req.context.update(kwargs)
213        # The binding is unsaved and gets a new primary key on every call, so a cached
214        # result could never be read back
215        proc = PolicyProcess(
216            PolicyBinding(policy=policy), request=req, connection=None, use_cache=False
217        )
218        return proc.profiling_wrapper()
219
220    def expr_create_jwt(
221        self,
222        user: User,
223        provider: OAuth2Provider | str,
224        scopes: list[str],
225        validity: str = "seconds=60",
226    ) -> str | None:
227        """Issue a JWT for a given provider"""
228        request: HttpRequest | None = self._context.get("http_request")
229        if not request:
230            return None
231        if not isinstance(provider, OAuth2Provider):
232            provider = OAuth2Provider.objects.get(name=provider)
233        session = None
234        if hasattr(request, "session") and request.session.session_key:
235            session = request.session["authenticatedsession"]
236        access_token = AccessToken(
237            provider=provider,
238            user=user,
239            expires=now() + timedelta_from_string(validity),
240            scope=scopes,
241            auth_time=now(),
242            session=session,
243        )
244        access_token.id_token = IDToken.new(provider, access_token, request)
245        access_token.save()
246        return access_token.token
247
248    def expr_create_jwt_raw(
249        self, provider: OAuth2Provider | str, validity: str = "seconds=60", **kwargs
250    ) -> str:
251        """Issue a JWT for a given provider with completely customized data"""
252        if not isinstance(provider, OAuth2Provider):
253            provider = OAuth2Provider.objects.get(name=provider)
254        kwargs["exp"] = int((now() + timedelta_from_string(validity)).timestamp())
255        kwargs["aud"] = provider.client_id
256        return provider.encode(kwargs)
257
258    def expr_send_email(  # noqa: PLR0913, PLR0917
259        self,
260        address: Address,
261        subject: str,
262        body: str | None = None,
263        stage: EmailStage | None = None,
264        template: str | None = None,
265        context: dict | None = None,
266        cc: Address = None,
267        bcc: Address = None,
268    ) -> bool:
269        """Send an email using authentik's email system
270
271        Args:
272            address: Email address(es) to send to. Can be:
273                - Single email: "user@example.com"
274                - Formatted address: "John Doe <user@example.com>"
275                - (name, email) tuple: ("John Doe", "user@example.com")
276                - List of any of the above
277            subject: Email subject
278            body: Email body (plain text/HTML). Mutually exclusive with template.
279            stage: EmailStage instance to use for settings. If None, uses global settings.
280            template: Template name to render. Mutually exclusive with body.
281            context: Additional context variables for template rendering.
282            cc: Email address(es) to CC. Same format as address.
283            bcc: Email address(es) to BCC. Same format as address.
284
285        Returns:
286            bool: True if email was queued successfully, False otherwise
287        """
288        # Deferred imports to avoid circular import issues
289        from authentik.stages.email.tasks import send_mails
290
291        if body and template:
292            raise ValueError("body and template parameters are mutually exclusive")
293
294        if not body and not template:
295            raise ValueError("Either body or template parameter must be provided")
296
297        to_addresses = normalize_addresses(address)
298        cc_addresses = normalize_addresses(cc)
299        bcc_addresses = normalize_addresses(bcc)
300
301        try:
302            if template is not None:
303                # Use all available context from the evaluator for template rendering
304                template_context = self._context.copy()
305                # Add any custom context passed to the function
306                if context:
307                    template_context.update(context)
308
309                # Use template rendering
310                message = TemplateEmailMessage(
311                    subject=subject,
312                    to=to_addresses,
313                    cc=cc_addresses,
314                    bcc=bcc_addresses,
315                    template_name=template,
316                    template_context=template_context,
317                )
318            else:
319                # Use plain body
320                message = TemplateEmailMessage(
321                    subject=subject,
322                    to=to_addresses,
323                    cc=cc_addresses,
324                    bcc=bcc_addresses,
325                    body=body,
326                )
327
328            send_mails(stage, message)
329            return True
330
331        except (SMTPException, ConnectionError, ValidationError, ValueError) as exc:
332            LOGGER.warning("Failed to send email", exc=exc, addresses=to_addresses, subject=subject)
333            return False
334
335    def wrap_expression(self, expression: str) -> str:
336        """Wrap expression in a function, call it, and save the result as `result`"""
337        handler_signature = ",".join(
338            [x for x in [sanitize_arg(x) for x in self._context.keys()] if x]
339        )
340        full_expression = ""
341        full_expression += f"def handler({handler_signature}):\n"
342        full_expression += indent(expression, "    ")
343        full_expression += f"\nresult = handler({handler_signature})"
344        return full_expression
345
346    def compile(self, expression: str) -> CodeType:
347        """Parse expression. Raises SyntaxError or ValueError if the syntax is incorrect."""
348        expression = self.wrap_expression(expression)
349        return compile(expression, self._filename, "exec")
350
351    def evaluate(self, expression_source: str) -> Any:
352        """Parse and evaluate expression. If the syntax is incorrect, a SyntaxError is raised.
353        If any exception is raised during execution, it is raised.
354        The result is returned without any type-checking."""
355        with active_tracer().start_span(op="authentik.lib.evaluator.evaluate") as span:
356            span: Span
357            span.description = self._filename
358            span.set_data("expression", expression_source)
359            try:
360                ast_obj = self.compile(expression_source)
361            except (SyntaxError, ValueError) as exc:
362                self.handle_error(exc, expression_source)
363                raise exc
364            try:
365                _locals = {sanitize_arg(x): y for x, y in self._context.items()}
366                # Yes this is an exec, yes it is potentially bad. Since we limit what variables are
367                # available here, and these policies can only be edited by admins, this is a risk
368                # we're willing to take.
369
370                exec(ast_obj, self._globals, _locals)  # nosec # noqa
371                result = _locals["result"]
372            except Exception as exc:
373                # So, this is a bit questionable. Essentially, we are edit the stacktrace
374                # so the user only sees information relevant to them
375                # and none of our surrounding error handling
376                if exc.__traceback__ is not None:
377                    exc.__traceback__ = exc.__traceback__.tb_next
378                if not isinstance(exc, ControlFlowException):
379                    self.handle_error(exc, expression_source)
380                raise exc
381            return result
382
383    def handle_error(self, exc: Exception, expression_source: str):  # pragma: no cover
384        """Exception Handler"""
385        LOGGER.warning("Expression error", exc=exc)
386
387    def validate(self, expression: str) -> bool:
388        """Validate expression's syntax, raise ValidationError if Syntax is invalid"""
389        try:
390            self.compile(expression)
391            return True
392        except (ValueError, SyntaxError) as exc:
393            raise ValidationError(f"Expression Syntax Error: {str(exc)}") from exc

Validate and evaluate python-based expressions

BaseEvaluator(filename: str | None = None)
63    def __init__(self, filename: str | None = None):
64        self._filename = filename if filename else "BaseEvaluator"
65        # update website/docs/expressions/reference/_objects.mdx
66        # update website/docs/expressions/reference/_functions.mdx
67        self._globals = {
68            "ak_call_policy": self.expr_func_call_policy,
69            "ak_create_event": self.expr_event_create,
70            "ak_create_jwt": self.expr_create_jwt,
71            "ak_create_jwt_raw": self.expr_create_jwt_raw,
72            "ak_is_group_member": BaseEvaluator.expr_is_group_member,
73            "ak_logger": get_logger(self._filename).bind(),
74            "ak_send_email": self.expr_send_email,
75            "ak_user_by": BaseEvaluator.expr_user_by,
76            "ak_user_has_authenticator": BaseEvaluator.expr_func_user_has_authenticator,
77            "ak_obj_attr": BaseEvaluator.expr_obj_attr,
78            "ip_address": ip_address,
79            "ip_network": ip_network,
80            "list_flatten": BaseEvaluator.expr_flatten,
81            "regex_match": BaseEvaluator.expr_regex_match,
82            "regex_replace": BaseEvaluator.expr_regex_replace,
83            "requests": SimpleLazyObject(get_http_session),
84            "resolve_dns": BaseEvaluator.expr_resolve_dns,
85            "reverse_dns": BaseEvaluator.expr_reverse_dns,
86            "slugify": slugify,
87            "delete_none_values": delete_none_values,
88        }
89        self._context = {}
@cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
@staticmethod
def expr_resolve_dns(host: str, ip_version: int | None = None) -> list[str]:
 91    @cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
 92    @staticmethod
 93    def expr_resolve_dns(host: str, ip_version: int | None = None) -> list[str]:
 94        """Resolve host to a list of IPv4 and/or IPv6 addresses."""
 95        # Although it seems to be fine (raising OSError), docs warn
 96        # against passing `None` for both the host and the port
 97        # https://docs.python.org/3/library/socket.html#socket.getaddrinfo
 98        host = host or ""
 99
100        ip_list = []
101
102        family = 0
103        if ip_version == 4:  # noqa: PLR2004
104            family = socket.AF_INET
105        if ip_version == 6:  # noqa: PLR2004
106            family = socket.AF_INET6
107
108        try:
109            for ip_addr in socket.getaddrinfo(host, None, family=family):
110                ip_list.append(str(ip_addr[4][0]))
111        except OSError:
112            pass
113        return list(set(ip_list))

Resolve host to a list of IPv4 and/or IPv6 addresses.

@cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
@staticmethod
def expr_reverse_dns(ip_addr: str) -> str:
115    @cached(cache=TLRUCache(maxsize=32, ttu=lambda key, value, now: now + 180))
116    @staticmethod
117    def expr_reverse_dns(ip_addr: str) -> str:
118        """Perform a reverse DNS lookup."""
119        try:
120            return socket.getfqdn(ip_addr)
121        except OSError:
122            return ip_addr

Perform a reverse DNS lookup.

@staticmethod
def expr_flatten(value: list[Any] | Any) -> Any | None:
124    @staticmethod
125    def expr_flatten(value: list[Any] | Any) -> Any | None:
126        """Flatten `value` if its a list"""
127        if isinstance(value, list):
128            if len(value) < 1:
129                return None
130            return value[0]
131        return value

Flatten value if its a list

@staticmethod
def expr_regex_match(value: Any, regex: str) -> bool:
133    @staticmethod
134    def expr_regex_match(value: Any, regex: str) -> bool:
135        """Expression Filter to run re.search"""
136        return re.search(regex, value) is not None

Expression Filter to run re.search

@staticmethod
def expr_regex_replace(value: Any, regex: str, repl: str) -> str:
138    @staticmethod
139    def expr_regex_replace(value: Any, regex: str, repl: str) -> str:
140        """Expression Filter to run re.sub"""
141        return re.sub(regex, repl, value)

Expression Filter to run re.sub

@staticmethod
def expr_is_group_member(user: authentik.core.models.User, **group_filters) -> bool:
143    @staticmethod
144    def expr_is_group_member(user: User, **group_filters) -> bool:
145        """Check if `user` is member of group with name `group_name`"""
146        return user.all_groups().filter(**group_filters).exists()

Check if user is member of group with name group_name

@staticmethod
def expr_user_by(**filters) -> authentik.core.models.User | None:
148    @staticmethod
149    def expr_user_by(**filters) -> User | None:
150        """Get user by filters"""
151        try:
152            users = User.objects.filter(**filters)
153            if users:
154                return users.first()
155            return None
156        except FieldError:
157            return None

Get user by filters

@staticmethod
def expr_func_user_has_authenticator(user: authentik.core.models.User, device_type: str | None = None) -> bool:
159    @staticmethod
160    def expr_func_user_has_authenticator(user: User, device_type: str | None = None) -> bool:
161        """Check if a user has any authenticator devices, optionally matching *device_type*"""
162        user_devices = devices_for_user(user)
163        if device_type:
164            for device in user_devices:
165                device_class = device.__class__.__name__.lower().replace("device", "")
166                if device_class == device_type:
167                    return True
168            return False
169        return len(list(user_devices)) > 0

Check if a user has any authenticator devices, optionally matching device_type

@staticmethod
def expr_obj_attr( obj: django.db.models.base.Model, attr_key: str, fallback: str | None = None) -> Any:
171    @staticmethod
172    def expr_obj_attr(obj: Model, attr_key: str, fallback: str | None = None) -> Any:
173        """Get an attribute of the given object if set by its dotted path, otherwise
174        return fallback value."""
175        attrs = getattr(obj, "attributes", {})
176        value = get_path_from_dict(attrs, attr_key)
177        if value is None and fallback is not None:
178            return getattr(obj, fallback, fallback)
179        return value

Get an attribute of the given object if set by its dotted path, otherwise return fallback value.

def expr_event_create(self, action: str, **kwargs):
181    def expr_event_create(self, action: str, **kwargs):
182        """Create event with supplied data and try to extract as much relevant data
183        from the context"""
184        context = self._context.copy()
185        # If the result was a complex variable, we don't want to reuse it
186        context.pop("result", None)
187        context.pop("handler", None)
188        event_kwargs = context
189        event_kwargs.update(kwargs)
190        event = Event.new(
191            action,
192            app=self._filename,
193            **event_kwargs,
194        )
195        if "request" in context and isinstance(context["request"], PolicyRequest):
196            policy_request: PolicyRequest = context["request"]
197            if policy_request.http_request:
198                event.from_http(policy_request.http_request)
199                return
200        event.save()

Create event with supplied data and try to extract as much relevant data from the context

def expr_func_call_policy(self, name: str, **kwargs) -> authentik.policies.types.PolicyResult:
202    def expr_func_call_policy(self, name: str, **kwargs) -> PolicyResult:
203        """Call policy by name, with current request"""
204        policy = Policy.objects.filter(name=name).select_subclasses().first()
205        if not policy:
206            raise ValueError(f"Policy '{name}' not found.")
207        user = self._context.get("user", get_anonymous_user())
208        req = PolicyRequest(user)
209        if "request" in self._context:
210            current_req: PolicyRequest = self._context["request"]
211            req = current_req.deepcopy()
212        req.context.update(kwargs)
213        # The binding is unsaved and gets a new primary key on every call, so a cached
214        # result could never be read back
215        proc = PolicyProcess(
216            PolicyBinding(policy=policy), request=req, connection=None, use_cache=False
217        )
218        return proc.profiling_wrapper()

Call policy by name, with current request

def expr_create_jwt( self, user: authentik.core.models.User, provider: authentik.providers.oauth2.models.OAuth2Provider | str, scopes: list[str], validity: str = 'seconds=60') -> str | None:
220    def expr_create_jwt(
221        self,
222        user: User,
223        provider: OAuth2Provider | str,
224        scopes: list[str],
225        validity: str = "seconds=60",
226    ) -> str | None:
227        """Issue a JWT for a given provider"""
228        request: HttpRequest | None = self._context.get("http_request")
229        if not request:
230            return None
231        if not isinstance(provider, OAuth2Provider):
232            provider = OAuth2Provider.objects.get(name=provider)
233        session = None
234        if hasattr(request, "session") and request.session.session_key:
235            session = request.session["authenticatedsession"]
236        access_token = AccessToken(
237            provider=provider,
238            user=user,
239            expires=now() + timedelta_from_string(validity),
240            scope=scopes,
241            auth_time=now(),
242            session=session,
243        )
244        access_token.id_token = IDToken.new(provider, access_token, request)
245        access_token.save()
246        return access_token.token

Issue a JWT for a given provider

def expr_create_jwt_raw( self, provider: authentik.providers.oauth2.models.OAuth2Provider | str, validity: str = 'seconds=60', **kwargs) -> str:
248    def expr_create_jwt_raw(
249        self, provider: OAuth2Provider | str, validity: str = "seconds=60", **kwargs
250    ) -> str:
251        """Issue a JWT for a given provider with completely customized data"""
252        if not isinstance(provider, OAuth2Provider):
253            provider = OAuth2Provider.objects.get(name=provider)
254        kwargs["exp"] = int((now() + timedelta_from_string(validity)).timestamp())
255        kwargs["aud"] = provider.client_id
256        return provider.encode(kwargs)

Issue a JWT for a given provider with completely customized data

def expr_send_email(unknown):
258    def expr_send_email(  # noqa: PLR0913, PLR0917
259        self,
260        address: Address,
261        subject: str,
262        body: str | None = None,
263        stage: EmailStage | None = None,
264        template: str | None = None,
265        context: dict | None = None,
266        cc: Address = None,
267        bcc: Address = None,
268    ) -> bool:
269        """Send an email using authentik's email system
270
271        Args:
272            address: Email address(es) to send to. Can be:
273                - Single email: "user@example.com"
274                - Formatted address: "John Doe <user@example.com>"
275                - (name, email) tuple: ("John Doe", "user@example.com")
276                - List of any of the above
277            subject: Email subject
278            body: Email body (plain text/HTML). Mutually exclusive with template.
279            stage: EmailStage instance to use for settings. If None, uses global settings.
280            template: Template name to render. Mutually exclusive with body.
281            context: Additional context variables for template rendering.
282            cc: Email address(es) to CC. Same format as address.
283            bcc: Email address(es) to BCC. Same format as address.
284
285        Returns:
286            bool: True if email was queued successfully, False otherwise
287        """
288        # Deferred imports to avoid circular import issues
289        from authentik.stages.email.tasks import send_mails
290
291        if body and template:
292            raise ValueError("body and template parameters are mutually exclusive")
293
294        if not body and not template:
295            raise ValueError("Either body or template parameter must be provided")
296
297        to_addresses = normalize_addresses(address)
298        cc_addresses = normalize_addresses(cc)
299        bcc_addresses = normalize_addresses(bcc)
300
301        try:
302            if template is not None:
303                # Use all available context from the evaluator for template rendering
304                template_context = self._context.copy()
305                # Add any custom context passed to the function
306                if context:
307                    template_context.update(context)
308
309                # Use template rendering
310                message = TemplateEmailMessage(
311                    subject=subject,
312                    to=to_addresses,
313                    cc=cc_addresses,
314                    bcc=bcc_addresses,
315                    template_name=template,
316                    template_context=template_context,
317                )
318            else:
319                # Use plain body
320                message = TemplateEmailMessage(
321                    subject=subject,
322                    to=to_addresses,
323                    cc=cc_addresses,
324                    bcc=bcc_addresses,
325                    body=body,
326                )
327
328            send_mails(stage, message)
329            return True
330
331        except (SMTPException, ConnectionError, ValidationError, ValueError) as exc:
332            LOGGER.warning("Failed to send email", exc=exc, addresses=to_addresses, subject=subject)
333            return False

Send an email using authentik's email system

Args: address: Email address(es) to send to. Can be: - Single email: "user@example.com" - Formatted address: "John Doe user@example.com" - (name, email) tuple: ("John Doe", "user@example.com") - List of any of the above subject: Email subject body: Email body (plain text/HTML). Mutually exclusive with template. stage: EmailStage instance to use for settings. If None, uses global settings. template: Template name to render. Mutually exclusive with body. context: Additional context variables for template rendering. cc: Email address(es) to CC. Same format as address. bcc: Email address(es) to BCC. Same format as address.

Returns: bool: True if email was queued successfully, False otherwise

def wrap_expression(self, expression: str) -> str:
335    def wrap_expression(self, expression: str) -> str:
336        """Wrap expression in a function, call it, and save the result as `result`"""
337        handler_signature = ",".join(
338            [x for x in [sanitize_arg(x) for x in self._context.keys()] if x]
339        )
340        full_expression = ""
341        full_expression += f"def handler({handler_signature}):\n"
342        full_expression += indent(expression, "    ")
343        full_expression += f"\nresult = handler({handler_signature})"
344        return full_expression

Wrap expression in a function, call it, and save the result as result

def compile(self, expression: str) -> code:
346    def compile(self, expression: str) -> CodeType:
347        """Parse expression. Raises SyntaxError or ValueError if the syntax is incorrect."""
348        expression = self.wrap_expression(expression)
349        return compile(expression, self._filename, "exec")

Parse expression. Raises SyntaxError or ValueError if the syntax is incorrect.

def evaluate(self, expression_source: str) -> Any:
351    def evaluate(self, expression_source: str) -> Any:
352        """Parse and evaluate expression. If the syntax is incorrect, a SyntaxError is raised.
353        If any exception is raised during execution, it is raised.
354        The result is returned without any type-checking."""
355        with active_tracer().start_span(op="authentik.lib.evaluator.evaluate") as span:
356            span: Span
357            span.description = self._filename
358            span.set_data("expression", expression_source)
359            try:
360                ast_obj = self.compile(expression_source)
361            except (SyntaxError, ValueError) as exc:
362                self.handle_error(exc, expression_source)
363                raise exc
364            try:
365                _locals = {sanitize_arg(x): y for x, y in self._context.items()}
366                # Yes this is an exec, yes it is potentially bad. Since we limit what variables are
367                # available here, and these policies can only be edited by admins, this is a risk
368                # we're willing to take.
369
370                exec(ast_obj, self._globals, _locals)  # nosec # noqa
371                result = _locals["result"]
372            except Exception as exc:
373                # So, this is a bit questionable. Essentially, we are edit the stacktrace
374                # so the user only sees information relevant to them
375                # and none of our surrounding error handling
376                if exc.__traceback__ is not None:
377                    exc.__traceback__ = exc.__traceback__.tb_next
378                if not isinstance(exc, ControlFlowException):
379                    self.handle_error(exc, expression_source)
380                raise exc
381            return result

Parse and evaluate expression. If the syntax is incorrect, a SyntaxError is raised. If any exception is raised during execution, it is raised. The result is returned without any type-checking.

def handle_error(self, exc: Exception, expression_source: str):
383    def handle_error(self, exc: Exception, expression_source: str):  # pragma: no cover
384        """Exception Handler"""
385        LOGGER.warning("Expression error", exc=exc)

Exception Handler

def validate(self, expression: str) -> bool:
387    def validate(self, expression: str) -> bool:
388        """Validate expression's syntax, raise ValidationError if Syntax is invalid"""
389        try:
390            self.compile(expression)
391            return True
392        except (ValueError, SyntaxError) as exc:
393            raise ValidationError(f"Expression Syntax Error: {str(exc)}") from exc

Validate expression's syntax, raise ValidationError if Syntax is invalid