From fbff17ac09d8ce25e826bf9ccdd043c60be0654e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20M=C3=A9ndez?= Date: Wed, 25 Nov 2026 12:23:35 -0600 Subject: [PATCH 1/2] feat: add the endpoints to read and remove custom roles GET /api/authz/v1/roles// returns one role, static or custom, in the format of the role list (ADR 0036). The caller needs the permission to list roles of one of the role's resource types; staff and superusers always pass. DELETE /api/authz/v1/roles// removes a custom role and is limited to staff and superusers. A role with assignments needs assignments=revoke, otherwise it returns 409 and removes nothing. Static roles return 400, and unknown or removed roles return 404 on both endpoints. Closes #581 Co-authored-by: Kiro --- CHANGELOG.rst | 9 + src/openedx_authz/api/catalog.py | 4 +- src/openedx_authz/api/custom_roles.py | 8 +- src/openedx_authz/api/roles.py | 9 +- src/openedx_authz/rest_api/data.py | 6 + src/openedx_authz/rest_api/v1/permissions.py | 54 ++- src/openedx_authz/rest_api/v1/serializers.py | 23 +- src/openedx_authz/rest_api/v1/views.py | 98 ++++- src/openedx_authz/tests/api/test_catalog.py | 6 + .../tests/api/test_custom_roles.py | 37 ++ .../tests/rest_api/test_views.py | 406 +++++++++++++++++- src/openedx_authz/tests/test_utils.py | 20 + 12 files changed, 660 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 62d726518..fd47d2082 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -50,6 +50,15 @@ Added ``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 /api/authz/v1/roles//`` to read one role, static or custom, in the format + of the role list (ADR 0036). The caller needs the permission to list the roles of one of the + role's resource types (``courses.view_course_team`` or ``content_libraries.view_library_team``); + staff and superusers always pass. A role that does not exist or was removed returns 404. +* Added ``DELETE /api/authz/v1/roles//`` to remove a custom role (ADR 0036). Only staff + and superusers can call it. A role that has assignments is removed only with + ``assignments=revoke``, which deletes them too; without it the response is 409 and nothing is + removed. Any other ``assignments`` value, or removing a static role, returns 400, and a role that + does not exist or was removed returns 404. It returns 204. * 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/src/openedx_authz/api/catalog.py b/src/openedx_authz/api/catalog.py index 4b8d3d24f..0ebddad0a 100644 --- a/src/openedx_authz/api/catalog.py +++ b/src/openedx_authz/api/catalog.py @@ -104,7 +104,9 @@ def get_role_catalog_entry(role_id: str) -> dict: roles = AuthzRoleDefinition.objects.visible().filter(role_id=role_id) scope_types = roles.values_list("scopes", flat=True).first() role = None if scope_types is None else _roles_in_scope_types(roles, scope_types).first() - if role is None: + # The database may match the ID ignoring case or accents (MySQL collation), while Casbin + # matches it exactly, so a role found under a different spelling of its ID is not returned. + if role is None or role.role_id != role_id: raise RoleNotFoundError(f"There is no role {role_id!r}.") return _build_role_entry(role, scope_types) diff --git a/src/openedx_authz/api/custom_roles.py b/src/openedx_authz/api/custom_roles.py index 91d51b5cb..7764649dc 100644 --- a/src/openedx_authz/api/custom_roles.py +++ b/src/openedx_authz/api/custom_roles.py @@ -260,9 +260,13 @@ def _taken_role_ids() -> set[str]: def _get_active_custom_role(role_id: str) -> AuthzRoleDefinition: - """Return a custom role that has not been removed, or explain why there is none.""" + """Return a custom role that has not been removed, or explain why there is none. + + The database may match the ID ignoring case or accents (MySQL collation), while Casbin matches + it exactly, so a role found under a different spelling of its ID is treated as not found. + """ role = AuthzRoleDefinition.objects.filter(role_id=role_id).first() - if role is None or role.removed_at is not None: + if role is None or role.role_id != role_id or role.removed_at is not None: raise CustomRoleNotFoundError(f"There is no custom role {role_id!r}.") if role.definition_kind != DefinitionKind.USER_DEFINED.value: raise StaticRoleError(f"Role {role_id!r} is a static role and is read-only.") diff --git a/src/openedx_authz/api/roles.py b/src/openedx_authz/api/roles.py index c191b2a87..8c5d001a1 100644 --- a/src/openedx_authz/api/roles.py +++ b/src/openedx_authz/api/roles.py @@ -237,8 +237,13 @@ def assign_role_to_subject_in_scope(subject: SubjectData, role: RoleData, scope: def _ensure_active_custom_role(role: RoleData) -> None: - """Reject a custom role that has no definition or has been removed.""" - if not AuthzRoleDefinition.objects.user_defined().active().filter(role_id=role.external_key).exists(): + """Reject a custom role that has no definition or has been removed. + + The database may match the ID ignoring case or accents (MySQL collation), while Casbin matches + it exactly, so the stored ID is compared again to reject a different spelling of it. + """ + stored_ids = AuthzRoleDefinition.objects.user_defined().active().filter(role_id=role.external_key) + if role.external_key not in stored_ids.values_list("role_id", flat=True): raise CustomRoleNotFoundError(f"There is no custom role {role.external_key!r}.") diff --git a/src/openedx_authz/rest_api/data.py b/src/openedx_authz/rest_api/data.py index 6c4a9a17a..0c3c2ed28 100644 --- a/src/openedx_authz/rest_api/data.py +++ b/src/openedx_authz/rest_api/data.py @@ -58,6 +58,12 @@ class SortOrder(BaseEnum): DESC = "desc" +class RoleRemovalAssignmentsAction(BaseEnum): + """Enum for what removing a custom role does with its assignments (ADR 0036).""" + + REVOKE = "revoke" + + class SearchField(BaseEnum): """Enum for the fields allowed for text search filtering.""" diff --git a/src/openedx_authz/rest_api/v1/permissions.py b/src/openedx_authz/rest_api/v1/permissions.py index 83cb3b691..bb1d7d227 100644 --- a/src/openedx_authz/rest_api/v1/permissions.py +++ b/src/openedx_authz/rest_api/v1/permissions.py @@ -407,10 +407,56 @@ def has_scoped_permission(self, request, view) -> bool: scope_types = parse_scope_types(request.query_params.get("scope_types")) if scope_types is None: return False - return all( - self.has_permission_in_any_scope(request.user, self.SCOPE_TYPE_PERMISSIONS[scope_type]) - for scope_type in scope_types - ) + return all(self.has_scope_type_permission(request.user, scope_type) for scope_type in scope_types) + + def has_scope_type_permission(self, user, scope_type: str) -> bool: + """Return True if the user holds the permission of ``scope_type`` in at least one scope. + + A scope type with no mapped permission is denied, so a role of a new scope type stays + readable only by privileged users until its permission is mapped. + """ + permission = self.SCOPE_TYPE_PERMISSIONS.get(scope_type) + return permission is not None and self.has_permission_in_any_scope(user, permission) + + +class RoleScopeTypePermission(ScopeTypePermission): + """Permission handler for endpoints about one role, checked against the role the view loads. + + The user needs the permission of ``ScopeTypePermission`` for one of the scope types the role + supports, because the role is listed in the catalog of each of them (ADR 0036). Superusers and + staff are always granted access. + + The check runs in ``has_object_permission`` against the catalog entry the view already loads, + so a read loads the role once instead of once here and once in the view. DRF does not call it + on its own for an ``APIView``: every handler that uses this class must load the entry and call + ``self.check_object_permissions(request, role_entry)`` before responding. A handler that skips + the call allows every authenticated user. + + Use it with ``PrivilegedWritePermission``, which limits writes to staff and superusers. + """ + + def has_scoped_permission(self, request, view) -> bool: + """Leave the check to ``has_object_permission``, which needs the role the view loads. + + This allows every request on its own. The handler must call ``check_object_permissions``. + + Returns: + bool: Always True. + """ + return True + + def has_object_permission(self, request, view, obj) -> bool: + """Check if the user may read the roles of one of the scope types of the role. + + Args: + obj (dict): The catalog entry of the role. + + Returns: + bool: True if the user is privileged or may read one of the role's scope types. + """ + if self.is_privileged(request.user): + return True + return any(self.has_scope_type_permission(request.user, scope_type) for scope_type in obj["scope_types"]) class PrivilegedWritePermission(UserScopesPermission): diff --git a/src/openedx_authz/rest_api/v1/serializers.py b/src/openedx_authz/rest_api/v1/serializers.py index e146ea08f..1bd736a48 100644 --- a/src/openedx_authz/rest_api/v1/serializers.py +++ b/src/openedx_authz/rest_api/v1/serializers.py @@ -5,7 +5,13 @@ from openedx_authz import api from openedx_authz.api.data import GLOBAL_SCOPE_WILDCARD, DefinitionKind -from openedx_authz.rest_api.data import RoleSortField, ScopesTypeField, SortField, SortOrder +from openedx_authz.rest_api.data import ( + RoleRemovalAssignmentsAction, + RoleSortField, + ScopesTypeField, + SortField, + SortOrder, +) from openedx_authz.rest_api.utils import get_generic_scope, parse_scope_types from openedx_authz.rest_api.v1.fields import CommaSeparatedListField, LowercaseCharField @@ -275,6 +281,21 @@ def validate(self, attrs: dict) -> dict: return attrs +class RemoveCustomRoleQuerySerializer(serializers.Serializer): # pylint: disable=abstract-method + """Serializer for the query parameters of the request that removes a custom role (ADR 0036). + + ``assignments=revoke`` confirms that the assignments of the role are deleted with it. Whether + the role has assignments, and so whether the confirmation is required, is decided by + ``api.remove_custom_role``. + """ + + assignments = serializers.ChoiceField( + required=False, + choices=[(e.value, e.name) for e in RoleRemovalAssignmentsAction], + default=None, + ) + + class RoleCatalogCategorySerializer(serializers.Serializer): # pylint: disable=abstract-method """A permission category of the role catalog.""" diff --git a/src/openedx_authz/rest_api/v1/views.py b/src/openedx_authz/rest_api/v1/views.py index 41b7fb55b..4c3b1c889 100644 --- a/src/openedx_authz/rest_api/v1/views.py +++ b/src/openedx_authz/rest_api/v1/views.py @@ -28,7 +28,7 @@ VIEW_LIBRARY, ) from openedx_authz.filters import PermissionValidationRequested, RoleAssignmentRequested, RoleRemovalRequested -from openedx_authz.rest_api.data import RoleOperationError, RoleOperationStatus +from openedx_authz.rest_api.data import RoleOperationError, RoleOperationStatus, RoleRemovalAssignmentsAction from openedx_authz.rest_api.decorators import authz_permissions, view_auth_classes from openedx_authz.rest_api.utils import filter_users, sort_users from openedx_authz.rest_api.v1.admin_console.filters import RoleOrderingFilter, RoleSearchFilter @@ -37,6 +37,7 @@ AnyScopePermission, DynamicScopePermission, PrivilegedWritePermission, + RoleScopeTypePermission, ScopeTypePermission, ) from openedx_authz.rest_api.v1.serializers import ( @@ -46,6 +47,7 @@ ListUsersInRoleWithScopeSerializer, PermissionValidationResponseSerializer, PermissionValidationSerializer, + RemoveCustomRoleQuerySerializer, RemoveUsersFromRoleWithScopeSerializer, RoleCatalogMetaSerializer, RoleCatalogResponseSerializer, @@ -67,7 +69,7 @@ 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. + """Return one role in the format of a role list item, as the role endpoints respond with it. Args: role_id (str): The role identifier. @@ -76,9 +78,21 @@ def get_role_entry(role_id: str, username: str) -> dict: Returns: dict: The catalog entry of the role with its ``user_count``. """ - role_entry = api.get_role_catalog_entry(role_id) + return add_user_count(api.get_role_catalog_entry(role_id), username) + + +def add_user_count(role_entry: dict, username: str) -> dict: + """Return the catalog entry of a role with the ``user_count`` the caller can view. + + Args: + role_entry (dict): The catalog entry of the role. + username (str): The caller, whose visible assignments make up ``user_count``. + + Returns: + dict: A copy of the entry with its ``user_count``. + """ user_counts = api.get_visible_role_user_counts(role_entry["scope_types"], username) - return {**role_entry, "user_count": user_counts.get(role_id, 0)} + return {**role_entry, "user_count": user_counts.get(role_entry["role"], 0)} @view_auth_classes() @@ -586,11 +600,13 @@ def post(self, request: HttpRequest) -> Response: @view_auth_classes() class RoleDetailView(APIView): - """API view for editing one custom role (ADR 0036). + """API view for reading one role, and editing or removing one custom role (ADR 0036). **Endpoints** + - GET: Retrieve one role, static or custom - PATCH: Change the description or the permissions of a custom role + - DELETE: Remove a custom role **Path Parameters** @@ -605,21 +621,52 @@ class RoleDetailView(APIView): At least one of the fields is required. ``display_name`` and ``scope_types`` cannot change, and a request that sends either one returns 400. + **Query Parameters (DELETE)** + + - assignments (Optional): ``revoke`` to delete the assignments of the role with it. Required + when the role has assignments; without it, such a role is not removed and the response is 409. + **Response Format** - The role, in the format of an item of the ``results`` of ``GET /api/authz/v1/roles/``. + GET and PATCH return the role, in the format of an item of the ``results`` of + ``GET /api/authz/v1/roles/``. DELETE returns no content. **Authentication and Permissions** - Requires authenticated user. - - PATCH requires a staff user or a superuser. + - GET requires the permission to list the roles of one of the role's resource types + (``courses.view_course_team`` or ``content_libraries.view_library_team``), as for + ``GET /api/authz/v1/roles/``. + - PATCH and DELETE require a staff user or a superuser. - **Example Request** + **Example Requests** + + GET /api/authz/v1/roles/custom_library_designer/ PATCH /api/authz/v1/roles/custom_library_designer/ {"permissions": ["content_libraries.view_library"]} + + DELETE /api/authz/v1/roles/custom_library_designer/?assignments=revoke """ - permission_classes = [PrivilegedWritePermission] + permission_classes = [PrivilegedWritePermission, RoleScopeTypePermission] + + @apidocs.schema( + responses={ + status.HTTP_200_OK: RoleCatalogRoleSerializer, + status.HTTP_401_UNAUTHORIZED: "The user is not authenticated", + status.HTTP_403_FORBIDDEN: "The user cannot list the roles of the role's resource type", + status.HTTP_404_NOT_FOUND: "There is no such role, or it was removed", + }, + ) + def get(self, request: HttpRequest, role_id: str) -> Response: + """Retrieve one role, static or custom.""" + try: + role_entry = api.get_role_catalog_entry(role_id) + except api.RoleNotFoundError as exc: + return Response(data={"message": str(exc)}, status=status.HTTP_404_NOT_FOUND) + self.check_object_permissions(request, role_entry) + role_entry = add_user_count(role_entry, request.user.username) + return Response(RoleCatalogRoleSerializer(role_entry).data, status=status.HTTP_200_OK) @apidocs.schema( body=UpdateCustomRoleSerializer, @@ -644,6 +691,39 @@ def patch(self, request: HttpRequest, role_id: str) -> Response: role_entry = get_role_entry(role_id, request.user.username) return Response(RoleCatalogRoleSerializer(role_entry).data, status=status.HTTP_200_OK) + @apidocs.schema( + parameters=[ + apidocs.query_parameter( + "assignments", + str, + description="`revoke` to delete the assignments of the role with it. Required when the role " + "has assignments", + ), + ], + responses={ + status.HTTP_204_NO_CONTENT: "The role was removed", + status.HTTP_400_BAD_REQUEST: "The query parameters are 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", + status.HTTP_409_CONFLICT: "The role has assignments and `assignments=revoke` was not given", + }, + ) + def delete(self, request: HttpRequest, role_id: str) -> Response: + """Remove a custom role, and its assignments if the request confirms it.""" + query_serializer = RemoveCustomRoleQuerySerializer(data=request.query_params) + query_serializer.is_valid(raise_exception=True) + delete_assignments = query_serializer.validated_data["assignments"] == RoleRemovalAssignmentsAction.REVOKE + try: + api.remove_custom_role(role_id, delete_assignments=delete_assignments) + except api.CustomRoleNotFoundError as exc: + return Response(data={"message": str(exc)}, status=status.HTTP_404_NOT_FOUND) + except api.StaticRoleError as exc: + return Response(data={"message": str(exc)}, status=status.HTTP_400_BAD_REQUEST) + except api.CustomRoleHasAssignmentsError as exc: + return Response(data={"message": str(exc)}, status=status.HTTP_409_CONFLICT) + return Response(status=status.HTTP_204_NO_CONTENT) + @view_auth_classes() class UserValidationAPIView(APIView): diff --git a/src/openedx_authz/tests/api/test_catalog.py b/src/openedx_authz/tests/api/test_catalog.py index 77f23a280..8f9c76116 100644 --- a/src/openedx_authz/tests/api/test_catalog.py +++ b/src/openedx_authz/tests/api/test_catalog.py @@ -17,6 +17,7 @@ AuthzRoleDefinition, AuthzRolePermission, ) +from openedx_authz.tests.test_utils import role_ids_matched_ignoring_case class CatalogTestCase(TestCase): @@ -324,6 +325,11 @@ def test_custom_role_without_grants_is_found_by_its_resource_type(self): self.assertEqual(entry["permissions"], []) self.assertEqual(entry["scope_types"], ["course-v1"]) + def test_other_spelling_of_the_id_is_not_found(self): + """An ID that the database matches ignoring case is not the role's ID.""" + with role_ids_matched_ignoring_case(), self.assertRaises(RoleNotFoundError): + get_role_catalog_entry("EDITOR") + def test_roles_left_out_of_the_catalog_are_not_found(self): """Roles the catalog leaves out raise ``RoleNotFoundError``. diff --git a/src/openedx_authz/tests/api/test_custom_roles.py b/src/openedx_authz/tests/api/test_custom_roles.py index bdf9a5159..4b558954e 100644 --- a/src/openedx_authz/tests/api/test_custom_roles.py +++ b/src/openedx_authz/tests/api/test_custom_roles.py @@ -49,6 +49,7 @@ make_library_key, make_role_key, make_user_key, + role_ids_matched_ignoring_case, ) VIEW_LIBRARY = "content_libraries.view_library" @@ -59,6 +60,7 @@ LIBRARY_SCOPE_TYPE = "lib" COURSE_SCOPE_TYPE = "course-v1" LIBRARY = make_library_key("lib:UnitTest:designer") +CUSTOM_DESIGNER_VARIANT = "custom_DESIGNER" ALICE = make_user_key("alice") User = get_user_model() @@ -497,7 +499,17 @@ def test_removed_role_is_not_found(self): with self.assertRaises(CustomRoleNotFoundError): update_custom_role(role.role_id, description="x") + def test_other_spelling_of_the_id_is_not_found(self): + """An ID that the database matches ignoring case is not the role's ID, so nothing changes.""" + role = self.create_role() + + with role_ids_matched_ignoring_case(), self.assertRaises(CustomRoleNotFoundError): + update_custom_role(CUSTOM_DESIGNER_VARIANT, description="x") + + self.assertEqual(AuthzRoleDefinition.objects.get(pk=role.pk).description, "") + +@ddt class TestRemoveCustomRole(CustomRoleTestCase): """Removing a role keeps its ID reserved and removes everything that grants access.""" @@ -589,6 +601,18 @@ def test_removed_role_is_not_found(self): with self.assertRaises(CustomRoleNotFoundError): remove_custom_role(role.role_id) + @data(False, True) + def test_other_spelling_of_the_id_is_not_found(self, delete_assignments): + """An ID that the database matches ignoring case leaves the role and its assignment in place.""" + role = self.create_role() + self.assign(role) + + with role_ids_matched_ignoring_case(), self.assertRaises(CustomRoleNotFoundError): + remove_custom_role(CUSTOM_DESIGNER_VARIANT, delete_assignments=delete_assignments) + + self.assertIsNone(AuthzRoleDefinition.objects.get(pk=role.pk).removed_at) + self.assertTrue(self.is_allowed(VIEW_LIBRARY)) + def test_failure_during_removal_rolls_everything_back(self): """A failure after the assignment and one grant are deleted restores every row and sends no event.""" role = self.create_role(permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) @@ -655,6 +679,19 @@ def test_unknown_custom_role_cannot_be_assigned(self): self.assertFalse(CasbinRule.objects.filter(ptype="g", v1=make_role_key("custom_missing")).exists()) + def test_other_spelling_of_the_id_cannot_be_assigned(self): + """An ID that the database matches ignoring case is rejected, so no assignment is left without a role.""" + self.create_role() + + with role_ids_matched_ignoring_case(), self.assertRaises(CustomRoleNotFoundError): + assign_role_to_subject_in_scope( + SubjectData(namespaced_key=ALICE), + RoleData(external_key=CUSTOM_DESIGNER_VARIANT), + ScopeData(namespaced_key=LIBRARY), + ) + + self.assertFalse(CasbinRule.objects.filter(ptype="g", v1=make_role_key(CUSTOM_DESIGNER_VARIANT)).exists()) + def test_custom_role_assignment_takes_the_policy_write_lock(self): """Assigning a custom role holds the same lock as removing it.""" role = self.create_role() diff --git a/src/openedx_authz/tests/rest_api/test_views.py b/src/openedx_authz/tests/rest_api/test_views.py index ec9915234..036c4ab62 100644 --- a/src/openedx_authz/tests/rest_api/test_views.py +++ b/src/openedx_authz/tests/rest_api/test_views.py @@ -26,6 +26,7 @@ OrgCourseOverviewGlobData, PlatformContentLibraryGlobData, PlatformCourseOverviewGlobData, + RoleData, ) from openedx_authz.api.users import assign_role_to_user_in_scope from openedx_authz.authz import ( @@ -57,7 +58,12 @@ from openedx_authz.rest_api.v1.views import UserValidationAPIView 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 +from openedx_authz.tests.test_utils import ( + make_action_key, + make_role_key, + make_wildcard_key, + role_ids_matched_ignoring_case, +) User = get_user_model() @@ -2346,6 +2352,404 @@ def test_unauthenticated_user_cannot_edit(self): self.assert_role_unchanged() +@ddt +class TestRoleDetailViewRead(CustomRoleViewTestMixin): + """Test suite for reading one role through RoleDetailView (ADR 0036).""" + + @classmethod + def setUpTestData(cls): + """Make ``regular_9`` a course staff member, who can read course roles but not library roles.""" + super().setUpTestData() + cls._assign_roles_to_users( + assignments=[ + {"subject_name": "regular_9", "role_name": COURSE_STAFF.external_key, "scope_name": COURSE_SCOPE_ORG1} + ] + ) + + def setUp(self): + """Create a custom role of each resource type.""" + super().setUp() + self.library_role = api.create_custom_role( + "Library Designer", "Designs libraries", "lib", [VIEW_LIBRARY.identifier] + ) + self.course_role = api.create_custom_role("Course Designer", "", "course-v1", [COURSES_VIEW_COURSE.identifier]) + + def get_role(self, role_id: str) -> Response: + """Send a read request for ``role_id``.""" + return self.client.get(reverse("openedx_authz:role-detail", args=[role_id])) + + def test_custom_role_is_returned(self): + """Test reading a custom role that is assigned. + + Expected result: + - Returns 200 OK with the role in the format of a role list item, with its user count + """ + assign_role_to_user_in_scope("regular_10", self.library_role.role_id, LIB_SCOPE_ORG1) + + response = self.get_role(self.library_role.role_id) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + stored = AuthzRoleDefinition.objects.get(pk=self.library_role.pk) + self.assertEqual( + response.data, + { + "role": "custom_library_designer", + "display_name": "Library Designer", + "description": "Designs libraries", + "icon": None, + "definition_kind": DefinitionKind.USER_DEFINED.value, + "permissions": [VIEW_LIBRARY.identifier], + "scope_types": ["lib"], + "user_count": 1, + "updated_at": DateTimeField().to_representation(stored.updated_at), + }, + ) + + def test_static_role_is_returned(self): + """Test reading a static role. + + Expected result: + - Returns 200 OK with the static role and no ``updated_at`` + """ + response = self.get_role(LIBRARY_AUTHOR.external_key) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual( + (response.data["role"], response.data["definition_kind"], response.data["updated_at"]), + (LIBRARY_AUTHOR.external_key, DefinitionKind.STATIC.value, None), + ) + + def test_user_count_counts_only_visible_holders(self): + """Test that the user count leaves out the holders in scopes the caller cannot view. + + Expected result: + - An admin of one library counts only the holder in that library + - A superuser counts the holders in every library + """ + assign_role_to_user_in_scope("regular_9", self.library_role.role_id, LIB_SCOPE_ORG1) + assign_role_to_user_in_scope("regular_10", self.library_role.role_id, "lib:Org3:LIB3") + + self.client.force_authenticate(user=User.objects.get(username="regular_5")) + library_admin_count = self.get_role(self.library_role.role_id).data["user_count"] + self.client.force_authenticate(user=self.admin_user) + superuser_count = self.get_role(self.library_role.role_id).data["user_count"] + + self.assertEqual((library_admin_count, superuser_count), (1, 2)) + + @data( + ("regular_5", "custom_library_designer", status.HTTP_200_OK), + ("regular_8", "custom_library_designer", status.HTTP_200_OK), + ("regular_5", "custom_course_designer", status.HTTP_403_FORBIDDEN), + ("regular_9", "custom_course_designer", status.HTTP_200_OK), + ("regular_9", "custom_library_designer", status.HTTP_403_FORBIDDEN), + ("regular_9", LIBRARY_AUTHOR.external_key, status.HTTP_403_FORBIDDEN), + ("regular_10", "custom_course_designer", status.HTTP_403_FORBIDDEN), + ("staff_only", "custom_library_designer", status.HTTP_200_OK), + ("superuser_only", "custom_course_designer", status.HTTP_200_OK), + (None, "custom_library_designer", status.HTTP_401_UNAUTHORIZED), + ) + @unpack + def test_read_permission_follows_the_resource_type(self, username, role_id, status_code): + """Test that reading a role needs the permission to list roles of its resource type. + + Expected result: + - Users who can view a library team can read library roles, but not course roles + - Users who can view a course team can read course roles, but not library roles + - Users with neither permission get 403 FORBIDDEN + - Staff and superusers can read any role, and anonymous requests get 401 UNAUTHORIZED + """ + self.client.force_authenticate(user=User.objects.filter(username=username).first()) + + response = self.get_role(role_id) + + self.assertEqual(response.status_code, status_code) + + def test_role_is_loaded_once_for_a_regular_user(self): + """Test that the permission check reuses the role the view loads. + + Expected result: + - A library admin's read loads the catalog entry of the role once + """ + self.client.force_authenticate(user=User.objects.get(username="regular_5")) + + with patch.object(api, "get_role_catalog_entry", wraps=api.get_role_catalog_entry) as get_role_catalog_entry: + response = self.get_role(self.library_role.role_id) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + get_role_catalog_entry.assert_called_once_with(self.library_role.role_id) + + def test_role_of_two_resource_types_needs_either_permission(self): + """Test reading a static role that supports both resource types. + + Expected result: + - A course staff member, who cannot view library teams, can read the role + """ + AuthzRoleDefinition.objects.filter(role_id=COURSE_STAFF.external_key).update(scopes=["course-v1", "lib"]) + self.client.force_authenticate(user=User.objects.get(username="regular_9")) + + response = self.get_role(COURSE_STAFF.external_key) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_role_of_an_unmapped_scope_type_is_denied(self): + """Test reading a role whose resource type has no read permission mapped. + + Expected result: + - A library admin gets 403 FORBIDDEN instead of a server error + - A superuser can still read the role + """ + AuthzRoleDefinition.objects.filter(pk=self.library_role.pk).update(scopes=["unmapped"]) + + self.client.force_authenticate(user=User.objects.get(username="regular_5")) + library_admin_status = self.get_role(self.library_role.role_id).status_code + self.client.force_authenticate(user=self.admin_user) + superuser_status = self.get_role(self.library_role.role_id).status_code + + self.assertEqual((library_admin_status, superuser_status), (status.HTTP_403_FORBIDDEN, status.HTTP_200_OK)) + + @data("admin_1", "regular_9") + def test_unknown_role_is_not_found(self, username): + """Test reading a role ID that does not exist, as a privileged and as a regular user. + + Expected result: + - Returns 404 NOT FOUND + """ + self.client.force_authenticate(user=User.objects.get(username=username)) + + response = self.get_role("custom_missing") + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + def test_removed_role_is_not_found(self): + """Test reading a role after it was removed. + + Expected result: + - Returns 404 NOT FOUND + """ + api.remove_custom_role(self.library_role.role_id) + + response = self.get_role(self.library_role.role_id) + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + def test_other_spelling_of_the_id_is_not_found(self): + """Test reading a role by an ID that the database matches ignoring case, as MySQL does. + + Expected result: + - Returns 404 NOT FOUND + """ + with role_ids_matched_ignoring_case(): + response = self.get_role(self.library_role.role_id.upper()) + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + +@ddt +class TestRoleDetailViewRemove(CustomRoleViewTestMixin): + """Test suite for removing custom roles through RoleDetailView (ADR 0036).""" + + def setUp(self): + """Create the custom role to remove 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 delete_role(self, query_params: dict | None = None, role_id: str | None = None) -> Response: + """Send a removal request for the role, or for ``role_id`` if given, with ``query_params``.""" + url = reverse("openedx_authz:role-detail", args=[role_id]) if role_id else self.url + if query_params: + url = f"{url}?{urlencode(query_params)}" + return self.client.delete(url) + + def get_listed_custom_role_ids(self) -> list[str]: + """Return the IDs of the custom roles that the library role list returns.""" + response = self.client.get( + reverse("openedx_authz:role-list"), + {"scope_types": "lib", "definition_kind": DefinitionKind.USER_DEFINED.value}, + ) + return [role["role"] for role in response.data["results"]] + + def assert_role_kept(self): + """Fail if a rejected request removed the role.""" + self.assertEqual(api.get_role_catalog_entry(self.role.role_id)["role"], self.role.role_id) + + def test_role_without_assignments_is_removed(self): + """Test removing a role that has no assignments, without the ``assignments`` parameter. + + Expected result: + - Returns 204 NO CONTENT with no body + - The role can no longer be read and is left out of the role list + """ + response = self.delete_role() + + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + self.assertIsNone(response.data) + self.assertEqual(self.client.get(self.url).status_code, status.HTTP_404_NOT_FOUND) + self.assertNotIn(self.role.role_id, self.get_listed_custom_role_ids()) + + def test_role_with_assignments_needs_confirmation(self): + """Test removing a role that has assignments without ``assignments=revoke``. + + Expected result: + - Returns 409 CONFLICT explaining that the assignments must be deleted + - The role is kept and its holder keeps the access it grants + """ + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + + response = self.delete_role() + + self.assertEqual(response.status_code, status.HTTP_409_CONFLICT) + self.assertIn("assignment", response.data["message"]) + self.assert_role_kept() + self.assertTrue(api.is_user_allowed("regular_10", VIEW_LIBRARY.identifier, LIB_SCOPE_ORG1)) + + def test_revoke_removes_the_role_and_its_assignments(self): + """Test removing a role that has assignments with ``assignments=revoke``. + + Expected result: + - Returns 204 NO CONTENT + - The role has no assignments left and the holder loses the access it granted + - The role is left out of the role list + """ + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + + response = self.delete_role({"assignments": "revoke"}) + + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + self.assertEqual(api.get_role_assignments(role=RoleData(external_key=self.role.role_id)), []) + self.assertFalse(api.is_user_allowed("regular_10", VIEW_LIBRARY.identifier, LIB_SCOPE_ORG1)) + self.assertNotIn(self.role.role_id, self.get_listed_custom_role_ids()) + + def test_revoke_removes_a_role_without_assignments(self): + """Test that ``assignments=revoke`` is accepted for a role that has no assignments. + + Expected result: + - Returns 204 NO CONTENT and the role is left out of the role list + """ + response = self.delete_role({"assignments": "revoke"}) + + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + self.assertNotIn(self.role.role_id, self.get_listed_custom_role_ids()) + + @data("keep", "REVOKE") + def test_invalid_assignments_value_is_rejected(self, value): + """Test removal requests with an ``assignments`` value other than ``revoke``. + + Expected result: + - Returns 400 BAD REQUEST naming the parameter, and the role and its assignment are kept + """ + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + + response = self.delete_role({"assignments": value}) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn("assignments", response.data) + self.assert_role_kept() + self.assertTrue(api.is_user_allowed("regular_10", VIEW_LIBRARY.identifier, LIB_SCOPE_ORG1)) + + def test_empty_assignments_value_does_not_confirm(self): + """Test that an empty ``assignments`` value is treated as not sent, like other query parameters. + + Expected result: + - A role with assignments returns 409 CONFLICT and is kept + """ + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + + response = self.delete_role({"assignments": ""}) + + self.assertEqual(response.status_code, status.HTTP_409_CONFLICT) + self.assert_role_kept() + + def test_static_role_is_read_only(self): + """Test removing a static role. + + Expected result: + - Returns 400 BAD REQUEST and the static role is still listed + """ + response = self.delete_role(role_id=LIBRARY_AUTHOR.external_key) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual(api.get_role_catalog_entry(LIBRARY_AUTHOR.external_key)["role"], LIBRARY_AUTHOR.external_key) + + def test_unknown_role_is_not_found(self): + """Test removing a role ID that does not exist. + + Expected result: + - Returns 404 NOT FOUND + """ + response = self.delete_role(role_id="custom_missing") + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + def test_removed_role_is_not_found(self): + """Test removing a role a second time. + + Expected result: + - Returns 404 NOT FOUND + """ + self.delete_role() + + response = self.delete_role() + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + @data({}, {"assignments": "revoke"}) + def test_other_spelling_of_the_id_is_not_found(self, query_params): + """Test removing an assigned role by an ID that the database matches ignoring case, as MySQL does. + + Expected result: + - Returns 404 NOT FOUND + - The role is kept and its holder keeps the access it grants + """ + assign_role_to_user_in_scope("regular_10", self.role.role_id, LIB_SCOPE_ORG1) + + with role_ids_matched_ignoring_case(): + response = self.delete_role(query_params, role_id=self.role.role_id.upper()) + + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + self.assert_role_kept() + self.assertTrue(api.is_user_allowed("regular_10", VIEW_LIBRARY.identifier, LIB_SCOPE_ORG1)) + + @data("staff_only", "superuser_only") + def test_staff_and_superusers_can_remove(self, username): + """Test that each privileged kind of user can remove a role. + + Expected result: + - Returns 204 NO CONTENT for a staff user and for a superuser + """ + self.client.force_authenticate(user=User.objects.get(username=username)) + + response = self.delete_role() + + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + def test_team_admin_cannot_remove(self): + """Test that a user who manages library teams cannot remove roles. + + Expected result: + - A library admin gets 403 FORBIDDEN and the role is kept + """ + self.client.force_authenticate(user=User.objects.get(username="regular_5")) + + response = self.delete_role({"assignments": "revoke"}) + + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + self.assert_role_kept() + + def test_unauthenticated_user_cannot_remove(self): + """Test that an anonymous request is rejected. + + Expected result: + - Returns 401 UNAUTHORIZED and the role is kept + """ + self.client.force_authenticate(user=None) + + response = self.delete_role() + + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + self.assert_role_kept() + + class TestArbitraryRoleSupport(ViewTestMixin): """Regression tests for openedx-authz#414. diff --git a/src/openedx_authz/tests/test_utils.py b/src/openedx_authz/tests/test_utils.py index da880f662..1a019d8d7 100644 --- a/src/openedx_authz/tests/test_utils.py +++ b/src/openedx_authz/tests/test_utils.py @@ -6,6 +6,7 @@ from ddt import data, ddt, unpack from django.conf import settings +from django.db.models import QuerySet from django.test import TestCase from openedx_authz.api.data import ( @@ -20,6 +21,7 @@ from openedx_authz.engine.enforcer import AuthzEnforcer from openedx_authz.engine.renderer import PolicyRenderer from openedx_authz.engine.schema.pipeline import SchemaPipeline +from openedx_authz.models.schema import AuthzRoleDefinitionQuerySet from openedx_authz.utils import get_waffle_flag_states FLAG_NAME = "authz.enable_course_authoring" @@ -61,6 +63,24 @@ def pause_authz_auto_load(self, enforcer): enforcer.start_auto_load_policy(interval) +@contextmanager +def role_ids_matched_ignoring_case(): + """Make role definition lookups by ``role_id`` ignore case, as MySQL's default collation does. + + The tests run on SQLite, which compares the ID exactly, so code that relies on an exact match + would pass here and fail in production without this. + """ + + def filter_ignoring_case(queryset, *args, **kwargs): + """Filter like ``QuerySet.filter``, matching ``role_id`` without case.""" + if "role_id" in kwargs: + kwargs["role_id__iexact"] = kwargs.pop("role_id") + return QuerySet.filter(queryset, *args, **kwargs) + + with patch.object(AuthzRoleDefinitionQuerySet, "filter", filter_ignoring_case): + yield + + def seed_static_authorization_policies(target_enforcer) -> list[list[str]]: """Seed schema-defined role-permission policies.""" schema = SchemaPipeline().compile() From 8e314f59ee7b7790de060b8b030e4df844582992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20M=C3=A9ndez?= Date: Wed, 2 Dec 2026 12:10:16 -0600 Subject: [PATCH 2/2] squash!: retrigger CI