From 9ea517d606eb9bd2bed23e4bc0e9089a122ea9f1 Mon Sep 17 00:00:00 2001 From: "gcp-cherry-pick-bot[bot]" <98988430+gcp-cherry-pick-bot[bot]@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:45:06 +0900 Subject: [PATCH] core: fix error when raising SkipObject in mapping (cherry-pick #10153) (#10173) core: fix error when raising SkipObject in mapping (#10153) * core: fix error when raising SkipObject in mapping * fix events not being saved thanks tests --------- Signed-off-by: Jens Langhammer Co-authored-by: Jens L --- authentik/core/expression/evaluator.py | 7 +++++-- authentik/core/expression/exceptions.py | 4 ++++ authentik/lib/sync/mapper.py | 9 ++++++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/authentik/core/expression/evaluator.py b/authentik/core/expression/evaluator.py index 23ebeffb77..187e4b35dd 100644 --- a/authentik/core/expression/evaluator.py +++ b/authentik/core/expression/evaluator.py @@ -76,8 +76,11 @@ class PropertyMappingEvaluator(BaseEvaluator): ) if "request" in self._context: req: PolicyRequest = self._context["request"] - event.from_http(req.http_request, req.user) - return + if req.http_request: + event.from_http(req.http_request, req.user) + return + elif req.user: + event.set_user(req.user) event.save() def evaluate(self, *args, **kwargs) -> Any: diff --git a/authentik/core/expression/exceptions.py b/authentik/core/expression/exceptions.py index 05571e59f4..bf0de9bd42 100644 --- a/authentik/core/expression/exceptions.py +++ b/authentik/core/expression/exceptions.py @@ -16,3 +16,7 @@ class SkipObjectException(PropertyMappingExpressionException): """Exception which can be raised in a property mapping to skip syncing an object. Only applies to Property mappings which sync objects, and not on mappings which transitively apply to a single user""" + + def __init__(self) -> None: + # For this class only, both of these are set by the function evaluating the property mapping + super().__init__(exc=None, mapping=None) diff --git a/authentik/lib/sync/mapper.py b/authentik/lib/sync/mapper.py index 806dd8cd63..21374807ba 100644 --- a/authentik/lib/sync/mapper.py +++ b/authentik/lib/sync/mapper.py @@ -4,7 +4,10 @@ from django.db.models import QuerySet from django.http import HttpRequest from authentik.core.expression.evaluator import PropertyMappingEvaluator -from authentik.core.expression.exceptions import PropertyMappingExpressionException +from authentik.core.expression.exceptions import ( + PropertyMappingExpressionException, + SkipObjectException, +) from authentik.core.models import PropertyMapping, User @@ -57,6 +60,10 @@ class PropertyMappingManager: mapping.set_context(user, request, **kwargs) try: value = mapping.evaluate(mapping.model.expression) + except SkipObjectException as exc: + exc.exc = exc + exc.mapping = mapping + raise exc from exc except PropertyMappingExpressionException as exc: raise exc from exc except Exception as exc: