From 2dbae011b46f05de4d6de91dda38ff1ae67418f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20M=C3=A9ndez?= Date: Mon, 23 Nov 2026 13:29:57 -0600 Subject: [PATCH] feat: add the endpoint to edit custom roles PATCH /api/authz/v1/roles// changes the description or the permissions of a custom role (ADR 0036). Only staff and superusers can edit roles. The name and resource type cannot change, so sending them returns 400, as does editing a static role. A role that does not exist or was removed returns 404. Permission dependency checks wait for dependencies to be stored in the schema (#560). Co-authored-by: Kiro --- CHANGELOG.rst | 6 + .../0036-api-contract-for-custom-roles.rst | 7 +- src/openedx_authz/api/custom_roles.py | 19 +- src/openedx_authz/rest_api/v1/serializers.py | 25 ++ src/openedx_authz/rest_api/v1/urls.py | 1 + src/openedx_authz/rest_api/v1/views.py | 80 +++++- .../tests/api/test_custom_roles.py | 54 +++- src/openedx_authz/tests/rest_api/mixins.py | 23 ++ .../tests/rest_api/test_views.py | 270 +++++++++++++++++- 9 files changed, 464 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index eb99896fc..62d726518 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -44,6 +44,12 @@ Added Only staff and superusers can call it. A display name used by another role returns 409, and any other invalid request returns 400. It returns the new role in the format of the role list. Permission dependencies are not checked yet; that check needs dependencies stored in the schema. +* Added ``PATCH /api/authz/v1/roles//`` to change the description or the permissions of a + custom role (ADR 0036). ``permissions`` replaces the visible permissions; hidden permissions the + role already grants are kept (ADR 0038). Only staff and superusers can call it. Sending + ``display_name`` or ``scope_types``, or editing a static role, returns 400, and a role that does + not exist or was removed returns 404. It returns the role in the format of the role list. + Permission dependencies are not checked yet, as for create. * Added ``get_role_catalog_entry`` to the public API, which returns one role in the format of the role catalog and raises the new ``RoleNotFoundError`` for a role that is not in the catalog. The role catalog now returns ``updated_at`` for custom roles. diff --git a/docs/decisions/0036-api-contract-for-custom-roles.rst b/docs/decisions/0036-api-contract-for-custom-roles.rst index 3d7003f96..6ff40d54d 100644 --- a/docs/decisions/0036-api-contract-for-custom-roles.rst +++ b/docs/decisions/0036-api-contract-for-custom-roles.rst @@ -227,8 +227,10 @@ Returns 200 with the role object. PATCH /api/authz/v1/roles// ==================================== -Accepts any of ``description`` and ``permissions``. ``permissions`` replaces the full list. A -request that includes ``display_name`` returns 400. Returns 200 with the role object. +Accepts any of ``description`` and ``permissions``. ``permissions`` replaces the visible +permissions. Permissions that were hidden after the role granted them are kept, because clients +cannot see or send them and hiding must not change permission checks (`ADR 0038`_). A request that +includes ``display_name`` returns 400. Returns 200 with the role object. DELETE /api/authz/v1/roles// ===================================== @@ -309,4 +311,5 @@ References .. _ADR 0028: 0028-api-contract-for-role-catalog.rst .. _ADR 0034: 0034-permission-dependencies-in-authorization-schema.rst .. _ADR 0035: 0035-custom-role-persistence.rst +.. _ADR 0038: 0038-hidden-permission-categories-and-permissions.rst .. _Issue #469: https://github.com/openedx/openedx-authz/issues/469 diff --git a/src/openedx_authz/api/custom_roles.py b/src/openedx_authz/api/custom_roles.py index c1d71cad0..91d51b5cb 100644 --- a/src/openedx_authz/api/custom_roles.py +++ b/src/openedx_authz/api/custom_roles.py @@ -135,13 +135,14 @@ def update_custom_role( The role ID, name and scope type stay as they were. Permissions that are added or dropped reach every holder of the role right away. Any edit, including a permissions-only one, sets - the role's ``updated_at``. + the role's ``updated_at``. Permissions hidden after the role granted them stay granted, since + clients cannot see or send them (ADR 0038). Args: role_id (str): The ID of the custom role. description (str | None): The new description, or ``None`` to keep the current one. - permissions (Sequence[str] | None): The complete new list of permission IDs, or ``None`` - to keep the current ones. + permissions (Sequence[str] | None): The complete new list of visible permission IDs, or + ``None`` to keep the current ones. Returns: AuthzRoleDefinition: The updated role. @@ -306,8 +307,16 @@ def _resolve_permissions(permission_ids: Sequence[str], scope_types: Sequence[st def _replace_grants( policy_store: PolicyStore, role: AuthzRoleDefinition, permissions: Sequence[AuthzPermissionDefinition] ) -> None: - """Make the role grant exactly the given permissions, changing only what differs.""" - current = list(role.role_permissions.select_related("permission")) + """Make the role's visible grants match the given permissions, changing only what differs. + + Grants of hidden permissions are kept. Clients cannot see or send hidden permissions, so the + new list never names them, and hiding must not change permission checks (ADR 0038). + """ + current = list( + role.role_permissions.filter(permission__in=AuthzPermissionDefinition.objects.visible()).select_related( + "permission" + ) + ) wanted = {permission.pk for permission in permissions} granted = {grant.permission_id for grant in current} _remove_grants(policy_store, role, [grant for grant in current if grant.permission_id not in wanted]) diff --git a/src/openedx_authz/rest_api/v1/serializers.py b/src/openedx_authz/rest_api/v1/serializers.py index dcd0bb407..e146ea08f 100644 --- a/src/openedx_authz/rest_api/v1/serializers.py +++ b/src/openedx_authz/rest_api/v1/serializers.py @@ -250,6 +250,31 @@ class CreateCustomRoleSerializer(serializers.Serializer): # pylint: disable=abs permissions = serializers.ListField(child=serializers.CharField()) +class UpdateCustomRoleSerializer(serializers.Serializer): # pylint: disable=abstract-method + """Serializer for the request body that edits a custom role (ADR 0036). + + Only the fields that were sent end up in ``validated_data``. The name and the resource type + cannot change after creation, so a request that sends either one is rejected. Whether anything + was sent, and the permissions themselves, are validated by ``api.update_custom_role``. + """ + + FIXED_FIELDS = ("display_name", "scope_types") + + description = serializers.CharField(required=False, allow_blank=True) + permissions = serializers.ListField(child=serializers.CharField(), required=False) + + def validate(self, attrs: dict) -> dict: + """Reject the fields that cannot change after the role is created. + + Raises: + serializers.ValidationError: If the request sends ``display_name`` or ``scope_types``. + """ + sent = [field for field in self.FIXED_FIELDS if field in self.initial_data] + if sent: + raise serializers.ValidationError({field: "This field cannot be changed." for field in sent}) + return attrs + + class RoleCatalogCategorySerializer(serializers.Serializer): # pylint: disable=abstract-method """A permission category of the role catalog.""" diff --git a/src/openedx_authz/rest_api/v1/urls.py b/src/openedx_authz/rest_api/v1/urls.py index a08a2dec3..dbc04990f 100644 --- a/src/openedx_authz/rest_api/v1/urls.py +++ b/src/openedx_authz/rest_api/v1/urls.py @@ -14,6 +14,7 @@ ), path("roles/", views.RoleListView.as_view(), name="role-list"), path("roles/users/", views.RoleUserAPIView.as_view(), name="role-user-list"), + path("roles//", views.RoleDetailView.as_view(), name="role-detail"), path("users/validate/", views.UserValidationAPIView.as_view(), name="user-validation"), ] diff --git a/src/openedx_authz/rest_api/v1/views.py b/src/openedx_authz/rest_api/v1/views.py index eae471b0d..41b7fb55b 100644 --- a/src/openedx_authz/rest_api/v1/views.py +++ b/src/openedx_authz/rest_api/v1/views.py @@ -50,6 +50,7 @@ RoleCatalogMetaSerializer, RoleCatalogResponseSerializer, RoleCatalogRoleSerializer, + UpdateCustomRoleSerializer, UserRoleAssignmentSerializer, UserValidationAPIViewResponseSerializer, UserValidationAPIViewSerializer, @@ -65,6 +66,21 @@ SELF_PROTECTED_ROLES = (LIBRARY_ADMIN.external_key, COURSE_ADMIN.external_key) +def get_role_entry(role_id: str, username: str) -> dict: + """Return one role in the format of a role list item, as the write endpoints respond with it. + + Args: + role_id (str): The role identifier. + username (str): The caller, whose visible assignments make up ``user_count``. + + Returns: + dict: The catalog entry of the role with its ``user_count``. + """ + role_entry = api.get_role_catalog_entry(role_id) + user_counts = api.get_visible_role_user_counts(role_entry["scope_types"], username) + return {**role_entry, "user_count": user_counts.get(role_id, 0)} + + @view_auth_classes() class PermissionValidationMeView(APIView): """ @@ -564,11 +580,71 @@ def post(self, request: HttpRequest) -> Response: return Response(data={"message": str(exc)}, status=status.HTTP_400_BAD_REQUEST) except api.CustomRoleNameTakenError as exc: return Response(data={"message": str(exc)}, status=status.HTTP_409_CONFLICT) - # A new role has no assignments yet. - role_entry = {**api.get_role_catalog_entry(role.role_id), "user_count": 0} + role_entry = get_role_entry(role.role_id, request.user.username) return Response(RoleCatalogRoleSerializer(role_entry).data, status=status.HTTP_201_CREATED) +@view_auth_classes() +class RoleDetailView(APIView): + """API view for editing one custom role (ADR 0036). + + **Endpoints** + + - PATCH: Change the description or the permissions of a custom role + + **Path Parameters** + + - role_id (Required): The ``role`` field of the role, e.g. ``custom_library_designer`` + + **Request Body (PATCH)** + + - description (Optional): Free text, which may be empty + - permissions (Optional): Ids of at least one permission that supports the role's resource type. + Replaces the visible permissions. Hidden permissions the role already grants are kept. + + At least one of the fields is required. ``display_name`` and ``scope_types`` cannot change, and + a request that sends either one returns 400. + + **Response Format** + + The role, in the format of an item of the ``results`` of ``GET /api/authz/v1/roles/``. + + **Authentication and Permissions** + + - Requires authenticated user. + - PATCH requires a staff user or a superuser. + + **Example Request** + + PATCH /api/authz/v1/roles/custom_library_designer/ {"permissions": ["content_libraries.view_library"]} + """ + + permission_classes = [PrivilegedWritePermission] + + @apidocs.schema( + body=UpdateCustomRoleSerializer, + responses={ + status.HTTP_200_OK: RoleCatalogRoleSerializer, + status.HTTP_400_BAD_REQUEST: "The request data is invalid, or the role is a static role", + status.HTTP_401_UNAUTHORIZED: "The user is not authenticated", + status.HTTP_403_FORBIDDEN: "The user is neither staff nor a superuser", + status.HTTP_404_NOT_FOUND: "There is no such role, or it was removed", + }, + ) + def patch(self, request: HttpRequest, role_id: str) -> Response: + """Change the description or the permissions of a custom role.""" + serializer = UpdateCustomRoleSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + try: + api.update_custom_role(role_id, **serializer.validated_data) + except api.CustomRoleNotFoundError as exc: + return Response(data={"message": str(exc)}, status=status.HTTP_404_NOT_FOUND) + except (api.InvalidCustomRoleError, api.StaticRoleError) as exc: + return Response(data={"message": str(exc)}, status=status.HTTP_400_BAD_REQUEST) + role_entry = get_role_entry(role_id, request.user.username) + return Response(RoleCatalogRoleSerializer(role_entry).data, status=status.HTTP_200_OK) + + @view_auth_classes() class UserValidationAPIView(APIView): """API view for validating that provided user identifiers correspond to existing users. diff --git a/src/openedx_authz/tests/api/test_custom_roles.py b/src/openedx_authz/tests/api/test_custom_roles.py index bbbf8254e..bdf9a5159 100644 --- a/src/openedx_authz/tests/api/test_custom_roles.py +++ b/src/openedx_authz/tests/api/test_custom_roles.py @@ -37,7 +37,12 @@ from openedx_authz.engine.schema.pipeline import SchemaPipeline from openedx_authz.models.core import ExtendedCasbinRule from openedx_authz.models.engine import PolicyCacheControl -from openedx_authz.models.schema import AuthzPermissionDefinition, AuthzRoleDefinition, AuthzRolePermission +from openedx_authz.models.schema import ( + AuthzPermissionCategory, + AuthzPermissionDefinition, + AuthzRoleDefinition, + AuthzRolePermission, +) from openedx_authz.tests.test_utils import ( AuthzEnforcerTestMixin, make_action_key, @@ -154,6 +159,15 @@ def stored_policy_rows(role_id: str) -> QuerySet: """The ``p`` rows stored in the database for a role.""" return CasbinRule.objects.filter(ptype="p", v0=make_role_key(role_id)) + @staticmethod + def hide_permission(permission: str, *, whole_category: bool) -> None: + """Hide the stored permission, or the whole category it belongs to, as a schema change would.""" + definitions = AuthzPermissionDefinition.objects.with_identifiers([permission]) + if whole_category: + AuthzPermissionCategory.objects.filter(permissions__in=definitions).update(hidden=True) + else: + definitions.update(hidden=True) + @ddt class TestCreateCustomRole(CustomRoleTestCase): @@ -411,6 +425,44 @@ def test_hidden_permission_cannot_be_added(self): ["view_course"], ) + @data(False, True) + def test_permission_hidden_after_granting_is_kept(self, whole_category): + """Replacing the permissions keeps a grant hidden after the role got it and drops the visible ones left out. + + The hidden permission is in a different category from the others, so hiding its category + leaves them visible. None of the permissions depend on another, so each check reflects + only its own grant. + """ + role = self.create_role(permissions=[VIEW_LIBRARY_TEAM, EDIT_LIBRARY_CONTENT]) + self.assign(role) + self.hide_permission(VIEW_LIBRARY_TEAM, whole_category=whole_category) + + update_custom_role(role.role_id, permissions=[VIEW_LIBRARY]) + + self.assertTrue(self.is_allowed(VIEW_LIBRARY_TEAM)) + self.assertTrue(self.is_allowed(VIEW_LIBRARY)) + self.assertFalse(self.is_allowed(EDIT_LIBRARY_CONTENT)) + self.assertCountEqual( + AuthzRolePermission.objects.filter(role=role).values_list("permission__name", flat=True), + ["view_library_team", "view_library"], + ) + self.assertCountEqual( + self.stored_policy_rows(role.role_id).values_list("v1", flat=True), + [make_action_key(VIEW_LIBRARY_TEAM), make_action_key(VIEW_LIBRARY)], + ) + + def test_permission_hidden_after_granting_cannot_be_sent(self): + """Sending a hidden permission is rejected even when the role already grants it, and nothing changes.""" + role = self.create_role(permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + self.hide_permission(EDIT_LIBRARY_CONTENT, whole_category=False) + policy_before = self.enforcer.get_policy() + + with self.assertRaisesRegex(InvalidCustomRoleError, EDIT_LIBRARY_CONTENT): + update_custom_role(role.role_id, permissions=[EDIT_LIBRARY_CONTENT]) + + self.assertEqual(self.enforcer.get_policy(), policy_before) + self.assertEqual(AuthzRolePermission.objects.filter(role=role).count(), 2) + def test_description_that_is_not_a_string_is_rejected(self): """A non-string description raises instead of reaching the database, and the role keeps its description.""" role = create_custom_role("Designer", "Original", LIBRARY_SCOPE_TYPE, [VIEW_LIBRARY]) diff --git a/src/openedx_authz/tests/rest_api/mixins.py b/src/openedx_authz/tests/rest_api/mixins.py index c61637bd5..de2cc169c 100644 --- a/src/openedx_authz/tests/rest_api/mixins.py +++ b/src/openedx_authz/tests/rest_api/mixins.py @@ -9,6 +9,7 @@ LIBRARY_AUTHOR, LIBRARY_USER, ) +from openedx_authz.engine.schema.pipeline import SchemaPipeline from openedx_authz.tests.api.test_roles import BaseRolesTestCase User = get_user_model() @@ -150,3 +151,25 @@ def setUp(self): self.admin_user = User.objects.get(username="admin_1") self.regular_user = User.objects.get(username="regular_1") self.client.force_authenticate(user=self.admin_user) + + +class CustomRoleViewTestMixin(ViewTestMixin): + """Mixin for the custom role endpoint tests, which need stored definitions and privileged users. + + The built-in definitions are stored so requests use real permissions. ``staff_only`` and + ``superuser_only`` each have one of the two flags that allow writes, unlike the admin users, + which have both. + """ + + @classmethod + def create_privileged_users(cls): + """Create a user that is only staff and a user that is only a superuser.""" + User.objects.create(username="staff_only", email="staff_only@example.com", is_staff=True) + User.objects.create(username="superuser_only", email="superuser_only@example.com", is_superuser=True) + + @classmethod + def setUpTestData(cls): + """Store the built-in definitions and create the privileged users.""" + super().setUpTestData() + SchemaPipeline().apply() + cls.create_privileged_users() diff --git a/src/openedx_authz/tests/rest_api/test_views.py b/src/openedx_authz/tests/rest_api/test_views.py index 41bbed507..ec9915234 100644 --- a/src/openedx_authz/tests/rest_api/test_views.py +++ b/src/openedx_authz/tests/rest_api/test_views.py @@ -43,9 +43,9 @@ LIBRARY_USER, MANAGE_LIBRARY_TEAM, VIEW_LIBRARY, + VIEW_LIBRARY_TEAM, ) from openedx_authz.engine.enforcer import AuthzEnforcer -from openedx_authz.engine.schema.pipeline import SchemaPipeline from openedx_authz.models.schema import ( AuthzPermissionCategory, AuthzPermissionDefinition, @@ -55,7 +55,7 @@ from openedx_authz.rest_api.data import RoleOperationError, RoleOperationStatus from openedx_authz.rest_api.v1.permissions import AnyScopePermission, DynamicScopePermission from openedx_authz.rest_api.v1.views import UserValidationAPIView -from openedx_authz.tests.rest_api.mixins import ViewTestMixin +from openedx_authz.tests.rest_api.mixins import CustomRoleViewTestMixin, ViewTestMixin from openedx_authz.tests.role_permissions import LIBRARY_ADMIN_PERMISSIONS from openedx_authz.tests.test_utils import make_action_key, make_role_key, make_wildcard_key @@ -1843,17 +1843,9 @@ def test_get_roles_missing_scope_types_is_denied_for_regular_users(self): @ddt -class TestRoleListViewCreate(ViewTestMixin): +class TestRoleListViewCreate(CustomRoleViewTestMixin): """Test suite for creating custom roles through RoleListView (ADR 0036).""" - @classmethod - def setUpTestData(cls): - """Store the built-in definitions, so the requests use real permissions, and create staff users.""" - super().setUpTestData() - SchemaPipeline().apply() - User.objects.create(username="staff_only", email="staff_only@example.com", is_staff=True) - User.objects.create(username="superuser_only", email="superuser_only@example.com", is_superuser=True) - def setUp(self): """Point the client at the role list.""" super().setUp() @@ -2098,6 +2090,262 @@ def test_name_of_a_removed_role_can_be_reused(self): self.assertEqual(response.data["role"], "custom_library_designer_2") +@ddt +class TestRoleDetailViewUpdate(CustomRoleViewTestMixin): + """Test suite for editing custom roles through RoleDetailView (ADR 0036).""" + + def setUp(self): + """Create the custom role to edit and point the client at it.""" + super().setUp() + self.role = api.create_custom_role("Library Designer", "Designs libraries", "lib", [VIEW_LIBRARY.identifier]) + self.url = reverse("openedx_authz:role-detail", args=[self.role.role_id]) + + def patch_role(self, body: dict, url: str | None = None) -> Response: + """Send an edit request with ``body`` to the role, or to ``url`` if given.""" + return self.client.patch(url or self.url, body, format="json") + + def assert_role_unchanged(self): + """Fail if a rejected request changed the description or the permissions of the role.""" + stored = AuthzRoleDefinition.objects.get(pk=self.role.pk) + self.assertEqual(stored.description, "Designs libraries") + self.assertEqual(api.get_role_catalog_entry(self.role.role_id)["permissions"], [VIEW_LIBRARY.identifier]) + + def test_edit_returns_the_role(self): + """Test changing the description. + + Expected result: + - Returns 200 OK with the role in the format of a role list item + - The new description is stored and the permissions stay the same + """ + response = self.patch_role({"description": "Edits libraries"}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + stored = AuthzRoleDefinition.objects.get(pk=self.role.pk) + self.assertEqual( + response.data, + { + "role": "custom_library_designer", + "display_name": "Library Designer", + "description": "Edits libraries", + "icon": None, + "definition_kind": DefinitionKind.USER_DEFINED.value, + "permissions": [VIEW_LIBRARY.identifier], + "scope_types": ["lib"], + "user_count": 0, + "updated_at": DateTimeField().to_representation(stored.updated_at), + }, + ) + + def test_description_can_be_emptied(self): + """Test clearing the description. + + Expected result: + - Returns 200 OK and the stored description is empty + """ + response = self.patch_role({"description": ""}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(AuthzRoleDefinition.objects.get(pk=self.role.pk).description, "") + + def test_permissions_are_replaced_for_holders(self): + """Test replacing the permissions of a role that is assigned. + + Expected result: + - Returns 200 OK listing only the new permissions + - The holder gains the added permission and loses the dropped one + """ + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + + response = self.patch_role({"permissions": [VIEW_LIBRARY_TEAM.identifier]}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.data["permissions"], [VIEW_LIBRARY_TEAM.identifier]) + self.assertTrue(api.is_user_allowed("regular_10", VIEW_LIBRARY_TEAM.identifier, LIB_SCOPE_ORG1)) + self.assertFalse(api.is_user_allowed("regular_10", VIEW_LIBRARY.identifier, LIB_SCOPE_ORG1)) + + def test_permission_hidden_after_granting_is_kept_for_holders(self): + """Test replacing the permissions of a role whose current permission was hidden later (ADR 0038). + + Expected result: + - Returns 200 OK listing only the new permission, since hidden ones are not listed + - The holder gains the new permission and keeps the hidden one + """ + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + AuthzPermissionDefinition.objects.with_identifiers([VIEW_LIBRARY.identifier]).update(hidden=True) + + response = self.patch_role({"permissions": [VIEW_LIBRARY_TEAM.identifier]}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.data["permissions"], [VIEW_LIBRARY_TEAM.identifier]) + self.assertTrue(api.is_user_allowed("regular_10", VIEW_LIBRARY_TEAM.identifier, LIB_SCOPE_ORG1)) + self.assertTrue(api.is_user_allowed("regular_10", VIEW_LIBRARY.identifier, LIB_SCOPE_ORG1)) + + def test_description_and_permissions_change_together(self): + """Test sending both fields in one request. + + Expected result: + - Returns 200 OK with the new description and only the new permissions + - Both changes are stored + """ + response = self.patch_role({"description": "Edits libraries", "permissions": [EDIT_LIBRARY_CONTENT.identifier]}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual( + (response.data["description"], response.data["permissions"]), + ("Edits libraries", [EDIT_LIBRARY_CONTENT.identifier]), + ) + self.assertEqual(AuthzRoleDefinition.objects.get(pk=self.role.pk).description, "Edits libraries") + self.assertEqual( + api.get_role_catalog_entry(self.role.role_id)["permissions"], [EDIT_LIBRARY_CONTENT.identifier] + ) + + def test_user_count_counts_holders(self): + """Test that the returned role counts its users, not its assignments. + + Expected result: + - Two users, one of them in two libraries, give a user_count of 2 + """ + assign_role_to_user_in_scope("regular_9", self.role.role_id, LIB_SCOPE_ORG1) + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + assign_role_to_user_in_scope("regular_10", self.role.role_id, "lib:Org2:LIB2") + + response = self.patch_role({"description": "Edits libraries"}) + + self.assertEqual(response.data["user_count"], 2) + + @data( + {"display_name": "Library Editor"}, + {"display_name": "Library Designer"}, + {"scope_types": ["lib"]}, + {"scope_types": ["course-v1"]}, + ) + def test_fixed_fields_are_rejected(self, body): + """Test requests that try to change the name or the resource type, even to the current value. + + Expected result: + - Returns 400 BAD REQUEST naming the field, and the role is unchanged + """ + response = self.patch_role({"description": "Edits libraries", **body}) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn(next(iter(body)), response.data) + self.assert_role_unchanged() + + @data({"permissions": None}, {"permissions": VIEW_LIBRARY.identifier}, {"description": None}) + def test_malformed_request_is_rejected(self, body): + """Test requests whose fields have the wrong shape. + + Expected result: + - Returns 400 BAD REQUEST naming the field, and the role is unchanged + """ + response = self.patch_role(body) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn(next(iter(body)), response.data) + self.assert_role_unchanged() + + @data( + ({}, "description or permissions"), + ({"permissions": []}, "at least one permission"), + ({"permissions": ["content_libraries.does_not_exist"]}, "content_libraries.does_not_exist"), + ( + {"permissions": [COURSES_LEGACY_BETA_TESTER_PERMISSIONS.identifier]}, + COURSES_LEGACY_BETA_TESTER_PERMISSIONS.identifier, + ), + ({"permissions": [COURSES_VIEW_COURSE.identifier]}, COURSES_VIEW_COURSE.identifier), + ) + @unpack + def test_invalid_edit_is_rejected(self, body, expected_in_message): + """Test requests that change nothing or would leave the role with invalid permissions. + + Expected result: + - Returns 400 BAD REQUEST explaining the problem, and the role is unchanged + """ + response = self.patch_role(body) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn(expected_in_message, response.data["message"]) + self.assert_role_unchanged() + + def test_static_role_is_read_only(self): + """Test editing a static role. + + Expected result: + - Returns 400 BAD REQUEST and the static role keeps its description + """ + static_role = AuthzRoleDefinition.objects.get(role_id=LIBRARY_AUTHOR.external_key) + + response = self.patch_role( + {"description": "Edited"}, url=reverse("openedx_authz:role-detail", args=[static_role.role_id]) + ) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(AuthzRoleDefinition.objects.get(pk=static_role.pk).description, static_role.description) + + def test_unknown_role_is_not_found(self): + """Test editing a role ID that does not exist. + + Expected result: + - Returns 404 NOT FOUND + """ + response = self.patch_role( + {"description": "Edited"}, url=reverse("openedx_authz:role-detail", args=["custom_missing"]) + ) + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + def test_removed_role_is_not_found(self): + """Test editing a role after it was removed. + + Expected result: + - Returns 404 NOT FOUND + """ + api.remove_custom_role(self.role.role_id) + + response = self.patch_role({"description": "Edited"}) + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + @data("staff_only", "superuser_only") + def test_staff_and_superusers_can_edit(self, username): + """Test that each privileged kind of user can edit a role. + + Expected result: + - Returns 200 OK for a staff user and for a superuser + """ + self.client.force_authenticate(user=User.objects.get(username=username)) + + response = self.patch_role({"description": "Edits libraries"}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_team_admin_cannot_edit(self): + """Test that a user who manages library teams cannot edit roles. + + Expected result: + - A library admin gets 403 FORBIDDEN and the role is unchanged + """ + self.client.force_authenticate(user=User.objects.get(username="regular_5")) + + response = self.patch_role({"description": "Edits libraries"}) + + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + self.assert_role_unchanged() + + def test_unauthenticated_user_cannot_edit(self): + """Test that an anonymous request is rejected. + + Expected result: + - Returns 401 UNAUTHORIZED and the role is unchanged + """ + self.client.force_authenticate(user=None) + + response = self.patch_role({"description": "Edits libraries"}) + + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + self.assert_role_unchanged() + + class TestArbitraryRoleSupport(ViewTestMixin): """Regression tests for openedx-authz#414.