コード例 #1
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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)
コード例 #2
0
 def test_full(self):
     """Test full with Policy instance"""
     policy = ExpressionPolicy(name="test", expression="return 'test'")
     policy.save()
     request = PolicyRequest(get_anonymous_user())
     result = policy.passes(request)
     self.assertTrue(result.passing)
コード例 #3
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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)
コード例 #4
0
 def test_failed_length(self):
     """Password too short"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages, ("test message", ))
コード例 #5
0
 def test_failed_digits(self):
     """not enough digits"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages, ("test message", ))
コード例 #6
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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")
コード例 #7
0
 def test_failed_uppercase(self):
     """not enough uppercase"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages, ("test message", ))
コード例 #8
0
 def test_true(self):
     """Positive password case"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = generate_key() + "1ee!!!"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertTrue(result.passing)
     self.assertEqual(result.messages, tuple())
コード例 #9
0
 def test_invalid(self):
     """Test passing event"""
     request = PolicyRequest(get_anonymous_user())
     policy: EventMatcherPolicy = EventMatcherPolicy.objects.create(
         client_ip="1.2.3.4")
     response = policy.passes(request)
     self.assertFalse(response.passing)
コード例 #10
0
ファイル: tests.py プロジェクト: goauthentik/authentik
 def test_invalid(self):
     """Test without password"""
     policy = HaveIBeenPwendPolicy.objects.create(name="test_invalid", )
     request = PolicyRequest(get_anonymous_user())
     result: PolicyResult = policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages[0], "Password not set in context")
コード例 #11
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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)
コード例 #12
0
ファイル: tests.py プロジェクト: goauthentik/authentik
 def test_false(self):
     """Failing password case"""
     policy = HaveIBeenPwendPolicy.objects.create(name="test_false", )
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"  # nosec
     result: PolicyResult = policy.passes(request)
     self.assertFalse(result.passing)
     self.assertTrue(result.messages[0].startswith("Password exists on "))
コード例 #13
0
ファイル: tests.py プロジェクト: goauthentik/authentik
 def test_true(self):
     """Positive password case"""
     policy = HaveIBeenPwendPolicy.objects.create(name="test_true", )
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = generate_key()
     result: PolicyResult = policy.passes(request)
     self.assertTrue(result.passing)
     self.assertEqual(result.messages, tuple())
コード例 #14
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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)
コード例 #15
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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",))
コード例 #16
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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)
コード例 #17
0
 def test_drop(self):
     """Test drop event"""
     event = Event.new(EventAction.LOGIN)
     event.client_ip = "1.2.3.4"
     request = PolicyRequest(get_anonymous_user())
     request.context["event"] = event
     policy: EventMatcherPolicy = EventMatcherPolicy.objects.create(
         client_ip="1.2.3.5")
     response = policy.passes(request)
     self.assertFalse(response.passing)
コード例 #18
0
 def test_match_action(self):
     """Test match action"""
     event = Event.new(EventAction.LOGIN)
     request = PolicyRequest(get_anonymous_user())
     request.context["event"] = event
     policy: EventMatcherPolicy = EventMatcherPolicy.objects.create(
         action=EventAction.LOGIN)
     response = policy.passes(request)
     self.assertTrue(response.passing)
     self.assertTupleEqual(response.messages, ("Action matched.", ))
コード例 #19
0
 def test_match_client_ip(self):
     """Test match client_ip"""
     event = Event.new(EventAction.LOGIN)
     event.client_ip = "1.2.3.4"
     request = PolicyRequest(get_anonymous_user())
     request.context["event"] = event
     policy: EventMatcherPolicy = EventMatcherPolicy.objects.create(
         client_ip="1.2.3.4")
     response = policy.passes(request)
     self.assertTrue(response.passing)
     self.assertTupleEqual(response.messages, ("Client IP matched.", ))
コード例 #20
0
ファイル: tests.py プロジェクト: whit-colm/authentik
 def test_invalid(self):
     """Test without password"""
     policy = PasswordPolicy.objects.create(
         name="test_invalid",
         amount_uppercase=1,
         amount_lowercase=2,
         amount_symbols=3,
         length_min=24,
         error_message="test message",
     )
     request = PolicyRequest(get_anonymous_user())
     result: PolicyResult = policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages[0], "Password not set in context")
コード例 #21
0
ファイル: tests.py プロジェクト: whit-colm/authentik
 def test_false(self):
     """Failing password case"""
     policy = PasswordPolicy.objects.create(
         name="test_false",
         amount_uppercase=1,
         amount_lowercase=2,
         amount_symbols=3,
         length_min=24,
         error_message="test message",
     )
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"
     result: PolicyResult = policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages, ("test message", ))
コード例 #22
0
ファイル: tests.py プロジェクト: whit-colm/authentik
 def test_true(self):
     """Positive password case"""
     policy = PasswordPolicy.objects.create(
         name="test_true",
         amount_uppercase=1,
         amount_lowercase=2,
         amount_symbols=3,
         length_min=3,
         error_message="test message",
     )
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"
     result: PolicyResult = policy.passes(request)
     self.assertTrue(result.passing)
     self.assertEqual(result.messages, tuple())
コード例 #23
0
ファイル: expression.py プロジェクト: goauthentik/authentik
 def set_context(
     self,
     user: Optional[User],
     request: Optional[HttpRequest],
     mapping: PropertyMapping,
     **kwargs,
 ):
     """Update context with context from PropertyMapping's evaluate"""
     req = PolicyRequest(user=get_anonymous_user())
     req.obj = mapping
     if user:
         req.user = user
         self._context["user"] = user
     if request:
         req.http_request = request
     self._context["request"] = req
     self._context.update(**kwargs)
コード例 #24
0
ファイル: engine.py プロジェクト: goauthentik/authentik
 def __init__(self,
              pbm: PolicyBindingModel,
              user: User,
              request: HttpRequest = None):
     self.logger = get_logger().bind()
     self.mode = pbm.policy_engine_mode
     # For backwards compatibility, set empty_result to true
     # objects with no policies attached will pass.
     self.empty_result = True
     if not isinstance(pbm, PolicyBindingModel):  # pragma: no cover
         raise ValueError(f"{pbm} is not instance of PolicyBindingModel")
     self.__pbm = pbm
     self.request = PolicyRequest(user)
     self.request.obj = pbm
     if request:
         self.request.set_http_request(request)
     self.__cached_policies: list[PolicyResult] = []
     self.__processes: list[PolicyProcessInfo] = []
     self.use_cache = True
     self.__expected_result_count = 0
コード例 #25
0
ファイル: test_process.py プロジェクト: goauthentik/authentik
    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"])
コード例 #26
0
    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)
コード例 #27
0
 def setUp(self):
     self.request = PolicyRequest(user=get_anonymous_user())
コード例 #28
0
 def test_invalid(self):
     """Test without password"""
     request = PolicyRequest(get_anonymous_user())
     result: PolicyResult = self.policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages[0], "Password not set in context")
コード例 #29
0
 def test_policy(self):
     """Test Policy"""
     request = PolicyRequest(user=self.user)
     policy: ReputationPolicy = ReputationPolicy.objects.create(
         name="reputation-test", threshold=0)
     self.assertTrue(policy.passes(request).passing)