def test_empty(self): """Test binding to user""" binding = PolicyBinding() request = PolicyRequest(self.user) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, False)
def test_user_passing(self): """Test binding to user""" binding = PolicyBinding(user=self.user) request = PolicyRequest(self.user) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, True)
def test_user_negative(self): """Test binding to user""" binding = PolicyBinding(user=get_anonymous_user()) request = PolicyRequest(self.user) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, False)
def test_execution_logging_anonymous(self): """Test policy execution creates event with anonymous user""" policy = DummyPolicy.objects.create( name="test-execution-logging-anon", result=False, wait_min=0, wait_max=1, execution_logging=True, ) binding = PolicyBinding(policy=policy, target=Application.objects.create(name="test")) user = AnonymousUser() http_request = self.factory.get("/") http_request.user = user request = PolicyRequest(user) request.set_http_request(http_request) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, False) self.assertEqual(response.messages, ("dummy",)) events = Event.objects.filter( action=EventAction.POLICY_EXECUTION, context__policy_uuid=policy.policy_uuid.hex, ) self.assertTrue(events.exists()) self.assertEqual(len(events), 1) event = events.first() self.assertEqual(event.user["username"], "AnonymousUser") self.assertEqual(event.context["result"]["passing"], False) self.assertEqual(event.context["result"]["messages"], ["dummy"]) self.assertEqual(event.client_ip, "127.0.0.1")
def test_exception(self): """Test policy execution""" policy = Policy.objects.create(name="test-execution") binding = PolicyBinding(policy=policy, target=Application.objects.create(name="test")) request = PolicyRequest(self.user) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, False)
def test_invalid(self): """Test Process with invalid arguments""" policy = DummyPolicy.objects.create(result=True, wait_min=0, wait_max=1) binding = PolicyBinding(policy=policy) with self.assertRaises(ValueError): PolicyProcess(binding, None, None) # type: ignore
def test_false(self): """Test policy execution""" policy = DummyPolicy.objects.create(result=False, wait_min=0, wait_max=1) binding = PolicyBinding(policy=policy) request = PolicyRequest(self.user) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, False) self.assertEqual(response.messages, ("dummy",))
def test_group_negative(self): """Test binding to group""" group = Group.objects.create(name="test-group") group.save() binding = PolicyBinding(group=group) request = PolicyRequest(self.user) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, False)
def build(self) -> "PolicyEngine": """Build wrapper which monitors performance""" with Hub.current.start_span( op="authentik.policy.engine.build", description=self.__pbm, ) as span, HIST_POLICIES_BUILD_TIME.labels( object_name=self.__pbm, object_type= f"{self.__pbm._meta.app_label}.{self.__pbm._meta.model_name}", user=self.request.user, ).time(): span: Span span.set_data("pbm", self.__pbm) span.set_data("request", self.request) for binding in self._iter_bindings(): self.__expected_result_count += 1 self._check_policy_type(binding) key = cache_key(binding, self.request) cached_policy = cache.get(key, None) if cached_policy and self.use_cache: self.logger.debug( "P_ENG: Taking result from cache", binding=binding, cache_key=key, request=self.request, ) self.__cached_policies.append(cached_policy) continue self.logger.debug("P_ENG: Evaluating policy", binding=binding, request=self.request) our_end, task_end = Pipe(False) task = PolicyProcess(binding, self.request, task_end) task.daemon = False self.logger.debug("P_ENG: Starting Process", binding=binding, request=self.request) if not CURRENT_PROCESS._config.get("daemon"): task.run() else: task.start() self.__processes.append( PolicyProcessInfo(process=task, connection=our_end, binding=binding)) # If all policies are cached, we have an empty list here. for proc_info in self.__processes: if proc_info.process.is_alive(): proc_info.process.join(proc_info.binding.timeout) # Only call .recv() if no result is saved, otherwise we just deadlock here if not proc_info.result: proc_info.result = proc_info.connection.recv() return self
def test(self, request: Request, pk: str) -> Response: """Test policy""" policy = self.get_object() test_params = PolicyTestSerializer(data=request.data) if not test_params.is_valid(): return Response(test_params.errors, status=400) # User permission check, only allow policy testing for users that are readable users = get_objects_for_user( request.user, "authentik_core.view_user").filter( pk=test_params.validated_data["user"].pk) if not users.exists(): raise PermissionDenied() p_request = PolicyRequest(users.first()) p_request.debug = True p_request.set_http_request(self.request) p_request.context = test_params.validated_data.get("context", {}) proc = PolicyProcess(PolicyBinding(policy=policy), p_request, None) result = proc.execute() response = PolicyTestResultSerializer(result) return Response(response.data)
def test_raises(self): """Test policy that raises error""" policy_raises = ExpressionPolicy.objects.create(name="raises", expression="{{ 0/0 }}") binding = PolicyBinding( policy=policy_raises, target=Application.objects.create(name="test") ) request = PolicyRequest(self.user) response = PolicyProcess(binding, request, None).execute() self.assertEqual(response.passing, False) self.assertEqual(response.messages, ("division by zero",)) events = Event.objects.filter( action=EventAction.POLICY_EXCEPTION, context__policy_uuid=policy_raises.policy_uuid.hex, ) self.assertTrue(events.exists()) self.assertEqual(len(events), 1) event = events.first() self.assertEqual(event.user["username"], self.user.username) self.assertIn("division by zero", event.context["message"])