From d44d5a44a18b18a50029e1fdb8528589a70fc96c Mon Sep 17 00:00:00 2001 From: Jens L Date: Fri, 24 May 2024 13:29:54 +0200 Subject: [PATCH] policies: fix ak_call_policy failing when used in testing (#9853) Signed-off-by: Jens Langhammer --- authentik/policies/expression/tests.py | 46 ++++++++++++++++++++------ authentik/policies/process.py | 4 +-- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/authentik/policies/expression/tests.py b/authentik/policies/expression/tests.py index b1537758cb..ed8fac2c65 100644 --- a/authentik/policies/expression/tests.py +++ b/authentik/policies/expression/tests.py @@ -96,16 +96,42 @@ class TestEvaluator(TestCase): execution_logging=True, expression="ak_message(request.http_request.path)\nreturn True", ) - tmpl = f""" - ak_message(request.http_request.path) - res = ak_call_policy('{expr.name}') - ak_message(request.http_request.path) - for msg in res.messages: - ak_message(msg) - """ - evaluator = PolicyEvaluator("test") - evaluator.set_policy_request(self.request) - res = evaluator.evaluate(tmpl) + expr2 = ExpressionPolicy.objects.create( + name=generate_id(), + execution_logging=True, + expression=f""" + ak_message(request.http_request.path) + res = ak_call_policy('{expr.name}') + ak_message(request.http_request.path) + for msg in res.messages: + ak_message(msg) + """, + ) + proc = PolicyProcess(PolicyBinding(policy=expr2), request=self.request, connection=None) + res = proc.profiling_wrapper() + self.assertEqual(res.messages, ("/", "/", "/")) + + def test_call_policy_test_like(self): + """test ak_call_policy without `obj` set, as if it was when testing policies""" + expr = ExpressionPolicy.objects.create( + name=generate_id(), + execution_logging=True, + expression="ak_message(request.http_request.path)\nreturn True", + ) + expr2 = ExpressionPolicy.objects.create( + name=generate_id(), + execution_logging=True, + expression=f""" + ak_message(request.http_request.path) + res = ak_call_policy('{expr.name}') + ak_message(request.http_request.path) + for msg in res.messages: + ak_message(msg) + """, + ) + self.request.obj = None + proc = PolicyProcess(PolicyBinding(policy=expr2), request=self.request, connection=None) + res = proc.profiling_wrapper() self.assertEqual(res.messages, ("/", "/", "/")) diff --git a/authentik/policies/process.py b/authentik/policies/process.py index e2d9139b0c..cc208da103 100644 --- a/authentik/policies/process.py +++ b/authentik/policies/process.py @@ -128,8 +128,8 @@ class PolicyProcess(PROCESS_CLASS): binding_order=self.binding.order, binding_target_type=self.binding.target_type, binding_target_name=self.binding.target_name, - object_pk=str(self.request.obj.pk), - object_type=class_to_path(self.request.obj.__class__), + object_pk=str(self.request.obj.pk) if self.request.obj else "", + object_type=class_to_path(self.request.obj.__class__) if self.request.obj else "", mode="execute_process", ).time(), ):