From 960429355f4ced4d42f07c4e606422364e4a48e0 Mon Sep 17 00:00:00 2001 From: "gcp-cherry-pick-bot[bot]" <98988430+gcp-cherry-pick-bot[bot]@users.noreply.github.com> Date: Thu, 10 Oct 2024 17:27:21 +0200 Subject: [PATCH] core: fix permission check for scoped impersonation (cherry-pick #11603) (#11650) core: fix permission check for scoped impersonation (#11603) * fix: permission check for scoped impersonation set global permission to have higher priority than the permission on a specific object * add tests --------- Signed-off-by: Jens Langhammer Co-authored-by: walhallyus Co-authored-by: Jens Langhammer --- authentik/core/api/users.py | 5 ++++- authentik/core/tests/test_impersonation.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/authentik/core/api/users.py b/authentik/core/api/users.py index e6ccb273c3..37656933d5 100644 --- a/authentik/core/api/users.py +++ b/authentik/core/api/users.py @@ -679,7 +679,10 @@ class UserViewSet(UsedByMixin, ModelViewSet): LOGGER.debug("User attempted to impersonate", user=request.user) return Response(status=401) user_to_be = self.get_object() - if not request.user.has_perm("impersonate", user_to_be): + # Check both object-level perms and global perms + if not request.user.has_perm( + "authentik_core.impersonate", user_to_be + ) and not request.user.has_perm("authentik_core.impersonate"): LOGGER.debug("User attempted to impersonate without permissions", user=request.user) return Response(status=401) if user_to_be.pk == self.request.user.pk: diff --git a/authentik/core/tests/test_impersonation.py b/authentik/core/tests/test_impersonation.py index 6026c39097..d877e55c9e 100644 --- a/authentik/core/tests/test_impersonation.py +++ b/authentik/core/tests/test_impersonation.py @@ -44,6 +44,26 @@ class TestImpersonation(APITestCase): self.assertEqual(response_body["user"]["username"], self.user.username) self.assertNotIn("original", response_body) + def test_impersonate_global(self): + """Test impersonation with global permissions""" + new_user = create_test_user() + assign_perm("authentik_core.impersonate", new_user) + assign_perm("authentik_core.view_user", new_user) + self.client.force_login(new_user) + + response = self.client.post( + reverse( + "authentik_api:user-impersonate", + kwargs={"pk": self.other_user.pk}, + ) + ) + self.assertEqual(response.status_code, 201) + + response = self.client.get(reverse("authentik_api:user-me")) + response_body = loads(response.content.decode()) + self.assertEqual(response_body["user"]["username"], self.other_user.username) + self.assertEqual(response_body["original"]["username"], new_user.username) + def test_impersonate_scoped(self): """Test impersonation with scoped permissions""" new_user = create_test_user()