From ecb1ce8135f45e5f55a50fea156c77924872cd9e Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Fri, 27 Jan 2023 23:57:35 +0100 Subject: [PATCH] core: fix token's set_key accessing data incorrectly also add tests closes #4551 Signed-off-by: Jens Langhammer --- authentik/core/api/tokens.py | 5 +++-- authentik/core/tests/test_token_api.py | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/authentik/core/api/tokens.py b/authentik/core/api/tokens.py index ed4bb1b5f..96111e7fa 100644 --- a/authentik/core/api/tokens.py +++ b/authentik/core/api/tokens.py @@ -134,9 +134,10 @@ class TokenViewSet(UsedByMixin, ModelViewSet): ) @action(detail=True, pagination_class=None, filter_backends=[], methods=["POST"]) def set_key(self, request: Request, identifier: str) -> Response: - """Return token key and log access""" + """Set token key. Action is logged as event. `authentik_core.set_token_key` permission + is required.""" token: Token = self.get_object() - key = request.POST.get("key") + key = request.data.get("key") if not key: return Response(status=400) token.key = key diff --git a/authentik/core/tests/test_token_api.py b/authentik/core/tests/test_token_api.py index eea1c88e1..f1a718688 100644 --- a/authentik/core/tests/test_token_api.py +++ b/authentik/core/tests/test_token_api.py @@ -7,6 +7,7 @@ from rest_framework.test import APITestCase from authentik.core.models import USER_ATTRIBUTE_TOKEN_EXPIRING, Token, TokenIntents, User from authentik.core.tests.utils import create_test_admin_user +from authentik.lib.generators import generate_id class TestTokenAPI(APITestCase): @@ -30,6 +31,28 @@ class TestTokenAPI(APITestCase): self.assertEqual(token.expiring, True) self.assertTrue(self.user.has_perm("authentik_core.view_token_key", token)) + def test_token_set_key(self): + """Test token creation endpoint""" + response = self.client.post( + reverse("authentik_api:token-list"), {"identifier": "test-token"} + ) + self.assertEqual(response.status_code, 201) + token = Token.objects.get(identifier="test-token") + self.assertEqual(token.user, self.user) + self.assertEqual(token.intent, TokenIntents.INTENT_API) + self.assertEqual(token.expiring, True) + self.assertTrue(self.user.has_perm("authentik_core.view_token_key", token)) + + self.client.force_login(self.admin) + new_key = generate_id() + response = self.client.post( + reverse("authentik_api:token-set-key", kwargs={"identifier": token.identifier}), + {"key": new_key}, + ) + self.assertEqual(response.status_code, 204) + token.refresh_from_db() + self.assertEqual(token.key, new_key) + def test_token_create_invalid(self): """Test token creation endpoint (invalid data)""" response = self.client.post(