From 55c63aa5f6687f29c29f3d5baa466781a9f5d093 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20M=C3=A9ndez?= Date: Wed, 2 Dec 2026 15:04:36 -0600 Subject: [PATCH] feat: validate permission dependencies when creating or editing a custom role POST /api/authz/v1/roles/ and PATCH /api/authz/v1/roles// now reject a permission set that leaves out a direct or indirect dependency of another permission in the set, with 400 and missing_dependencies (ADR 0036 section 7). Hidden permissions an edit keeps count as granted, and their own dependencies are not checked. Closes #674 --- CHANGELOG.rst | 8 +- src/openedx_authz/api/custom_roles.py | 43 ++++++- src/openedx_authz/api/exceptions.py | 16 +++ src/openedx_authz/rest_api/v1/views.py | 43 ++++++- .../tests/api/test_custom_roles.py | 117 +++++++++++++++++- .../tests/rest_api/test_views.py | 37 +++++- 6 files changed, 246 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 92351ab5..4e32eb78 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -43,13 +43,17 @@ Added * Added ``POST /api/authz/v1/roles/`` to create a custom role for one resource type (ADR 0036). 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. + Permissions that leave out a direct or indirect dependency of another permission in the request + return 400 with ``missing_dependencies``, which maps each permission to the dependencies it is + missing; the server does not add them (ADR 0036 §7). ``create_custom_role`` and + ``update_custom_role`` raise ``MissingPermissionDependenciesError`` in that case. * 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. + Permission dependencies are checked as for create, including an edit that removes a dependency + another permission still needs. Hidden permissions the role keeps count as granted. * 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``); diff --git a/src/openedx_authz/api/custom_roles.py b/src/openedx_authz/api/custom_roles.py index 5d248cbf..79dd4171 100644 --- a/src/openedx_authz/api/custom_roles.py +++ b/src/openedx_authz/api/custom_roles.py @@ -23,13 +23,20 @@ CustomRoleNameTakenError, CustomRoleNotFoundError, InvalidCustomRoleError, + MissingPermissionDependenciesError, StaticRoleError, ) from openedx_authz.api.roles import get_role_assignments, unassign_role_from_subject_in_scope from openedx_authz.constants import CUSTOM_ROLE_ID_MAX_LENGTH, CUSTOM_ROLE_ID_PREFIX, DefinitionKind from openedx_authz.engine.enforcer import AuthzEnforcer from openedx_authz.engine.policy import PolicyRow, PolicyStore, serialized_policy_update -from openedx_authz.models.schema import AuthzPermissionDefinition, AuthzRoleDefinition, AuthzRolePermission +from openedx_authz.engine.schema.dependencies import missing_dependencies +from openedx_authz.models.schema import ( + AuthzPermissionDefinition, + AuthzPermissionDependency, + AuthzRoleDefinition, + AuthzRolePermission, +) __all__ = [ "create_custom_role", @@ -112,6 +119,8 @@ def create_custom_role( Raises: InvalidCustomRoleError: If an argument has the wrong type, the name is blank or too long, or the permissions are empty, unknown, hidden or do not support the scope type. + MissingPermissionDependenciesError: If the permissions leave out a direct or indirect + dependency of another permission in the list. CustomRoleNameTakenError: If another role that has not been removed uses the name. """ _validate_text("description", description) @@ -120,6 +129,7 @@ def create_custom_role( with _writing_custom_roles() as policy_store: _check_display_name_is_free(display_name) resolved = _resolve_permissions(permissions, [scope_type]) + _check_dependencies(resolved) role = AuthzRoleDefinition.objects.create( role_id=build_custom_role_id(display_name, _taken_role_ids()), display_name=display_name, @@ -180,6 +190,9 @@ def update_custom_role( StaticRoleError: If the role is a static role. InvalidCustomRoleError: If nothing is given to change, an argument has the wrong type, or the permissions are empty, unknown, hidden or unsupported by the role. + MissingPermissionDependenciesError: If the permissions leave out a direct or indirect + dependency of another permission in the list. Hidden permissions the role keeps count + as granted. """ if description is None and permissions is None: raise InvalidCustomRoleError("Give a description or permissions to change.") @@ -188,7 +201,9 @@ def update_custom_role( with _writing_custom_roles() as policy_store: role = _get_active_custom_role(role_id) if permissions is not None: - _replace_grants(policy_store, role, _resolve_permissions(permissions, role.scopes)) + resolved = _resolve_permissions(permissions, role.scopes) + _check_dependencies(resolved, kept_hidden=_hidden_grants(role)) + _replace_grants(policy_store, role, resolved) if description is not None: role.description = description role.save(update_fields=["description", "updated_at"]) @@ -350,6 +365,30 @@ def _resolve_permissions(permission_ids: Sequence[str], scope_types: Sequence[st return [found[pid] for pid in requested] +def _hidden_grants(role: AuthzRoleDefinition) -> set[str]: + """Return the IDs of the hidden permissions the role grants, which an edit keeps (ADR 0038).""" + return { + grant.permission.identifier + for grant in role.role_permissions.exclude( + permission__in=AuthzPermissionDefinition.objects.visible() + ).select_related("permission") + } + + +def _check_dependencies(permissions: Sequence[AuthzPermissionDefinition], kept_hidden: Collection[str] = ()) -> None: + """Reject permissions that leave out a direct or indirect dependency of one of them (ADR 0036 §7). + + The server does not add the missing dependencies. Hidden permissions the role keeps count as + granted, but their own dependencies are not checked: clients cannot see them, so they could + not fix the request, and the ``g2`` rows still grant those dependencies. + """ + requested = {permission.identifier for permission in permissions} + missing = missing_dependencies(requested | set(kept_hidden), AuthzPermissionDependency.objects.dependency_map()) + missing = {permission_id: absent for permission_id, absent in missing.items() if permission_id in requested} + if missing: + raise MissingPermissionDependenciesError(missing) + + def _replace_grants( policy_store: PolicyStore, role: AuthzRoleDefinition, permissions: Sequence[AuthzPermissionDefinition] ) -> None: diff --git a/src/openedx_authz/api/exceptions.py b/src/openedx_authz/api/exceptions.py index 601482fb..44f67239 100644 --- a/src/openedx_authz/api/exceptions.py +++ b/src/openedx_authz/api/exceptions.py @@ -10,6 +10,7 @@ "CustomRoleNameTakenError", "CustomRoleNotFoundError", "InvalidCustomRoleError", + "MissingPermissionDependenciesError", "RoleNotFoundError", "StaticRoleError", ] @@ -35,6 +36,21 @@ class InvalidCustomRoleError(CustomRoleError): """The requested name or permissions cannot make a valid custom role.""" +class MissingPermissionDependenciesError(InvalidCustomRoleError): + """The permissions leave out a direct or indirect dependency of another permission in the set (ADR 0036 §7).""" + + def __init__(self, missing: dict[str, tuple[str, ...]]) -> None: + """Keep the missing dependencies so callers can report which permissions need which. + + Args: + missing (dict[str, tuple[str, ...]]): Each permission with missing dependencies, + mapped to the IDs of the dependencies it is missing. + """ + details = "; ".join(f"{permission_id} needs {', '.join(absent)}" for permission_id, absent in missing.items()) + super().__init__(f"Permissions are missing their dependencies: {details}.") + self.missing = missing + + class CustomRoleNameTakenError(CustomRoleError): """Another role that has not been removed already uses the display name, ignoring case.""" diff --git a/src/openedx_authz/rest_api/v1/views.py b/src/openedx_authz/rest_api/v1/views.py index 46af102f..96577bdd 100644 --- a/src/openedx_authz/rest_api/v1/views.py +++ b/src/openedx_authz/rest_api/v1/views.py @@ -102,6 +102,27 @@ def add_user_count(role_entry: dict, username: str) -> dict: return {**role_entry, "user_count": user_counts.get(role_entry["role"], 0)} +def missing_dependencies_response(exc: api.MissingPermissionDependenciesError) -> Response: + """Return the 400 for a permission set that leaves out dependencies (ADR 0036 §7). + + Next to the message, ``missing_dependencies`` maps each permission to the dependencies it is + missing, so a client can point at the permissions to add without parsing the message. + + Args: + exc (MissingPermissionDependenciesError): The error raised by the custom role API. + + Returns: + Response: The 400 response. + """ + return Response( + data={ + "message": str(exc), + "missing_dependencies": {permission_id: list(absent) for permission_id, absent in exc.missing.items()}, + }, + status=status.HTTP_400_BAD_REQUEST, + ) + + @view_auth_classes() class PermissionValidationMeView(APIView): """ @@ -491,10 +512,13 @@ class RoleListView(APIView): - display_name (Required): Unique among the roles that have not been removed, ignoring case - description (Optional): Free text, which may be empty - scope_types (Required): The role's resource type, as a one-item list: ``["course-v1"]`` or ``["lib"]`` - - permissions (Required): Ids of at least one permission that supports the resource type + - permissions (Required): Ids of at least one permission that supports the resource type, + including every direct and indirect dependency of each one (``all_depends_on``) POST returns 201 with the new role, in the format of an item of ``results``. A taken display - name returns 409; any other invalid request returns 400. + name returns 409; any other invalid request returns 400. When permissions leave out + dependencies, the 400 adds ``missing_dependencies``, which maps each permission to the sorted + ids of the dependencies it is missing. The server does not add them. **Authentication and Permissions** @@ -582,7 +606,7 @@ def get(self, request: HttpRequest) -> Response: body=CreateCustomRoleSerializer, responses={ status.HTTP_201_CREATED: RoleCatalogRoleSerializer, - status.HTTP_400_BAD_REQUEST: "The request data is invalid", + status.HTTP_400_BAD_REQUEST: "The request data is invalid, or the permissions leave out dependencies", status.HTTP_401_UNAUTHORIZED: "The user is not authenticated", status.HTTP_403_FORBIDDEN: "The user is neither staff nor a superuser", status.HTTP_409_CONFLICT: "Another role already uses the display name", @@ -599,6 +623,8 @@ def post(self, request: HttpRequest) -> Response: scope_type=serializer.validated_data["scope_types"][0], permissions=serializer.validated_data["permissions"], ) + except api.MissingPermissionDependenciesError as exc: + return missing_dependencies_response(exc) except api.InvalidCustomRoleError as exc: return Response(data={"message": str(exc)}, status=status.HTTP_400_BAD_REQUEST) except api.CustomRoleNameTakenError as exc: @@ -625,10 +651,12 @@ class RoleDetailView(APIView): - 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. + Replaces the visible permissions. Hidden permissions the role already grants are kept, and + count as granted when dependencies are checked. At least one of the fields is required. ``display_name`` and ``scope_types`` cannot change, and - a request that sends either one returns 400. + a request that sends either one returns 400. Permissions that leave out a direct or indirect + dependency return 400 with ``missing_dependencies``, as for ``POST /api/authz/v1/roles/``. **Query Parameters (DELETE)** @@ -681,7 +709,8 @@ def get(self, request: HttpRequest, role_id: str) -> Response: 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_400_BAD_REQUEST: "The request data is invalid, the permissions leave out dependencies, " + "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", @@ -695,6 +724,8 @@ def patch(self, request: HttpRequest, role_id: str) -> Response: 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.MissingPermissionDependenciesError as exc: + return missing_dependencies_response(exc) 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) diff --git a/src/openedx_authz/tests/api/test_custom_roles.py b/src/openedx_authz/tests/api/test_custom_roles.py index 5046aae6..64286ebd 100644 --- a/src/openedx_authz/tests/api/test_custom_roles.py +++ b/src/openedx_authz/tests/api/test_custom_roles.py @@ -29,6 +29,7 @@ CustomRoleNameTakenError, CustomRoleNotFoundError, InvalidCustomRoleError, + MissingPermissionDependenciesError, StaticRoleError, ) from openedx_authz.api.roles import assign_role_to_subject_in_scope @@ -55,6 +56,7 @@ VIEW_LIBRARY = "content_libraries.view_library" EDIT_LIBRARY_CONTENT = "content_libraries.edit_library_content" +DELETE_LIBRARY = "content_libraries.delete_library" VIEW_LIBRARY_TEAM = "content_libraries.view_library_team" VIEW_COURSE = "courses.view_course" HIDDEN_CATEGORY_PERMISSION = "courses.legacy_beta_tester_permissions" @@ -317,6 +319,42 @@ def test_hidden_permission_is_rejected(self): self.assertFalse(AuthzRoleDefinition.objects.user_defined().exists()) + def test_permissions_with_all_their_dependencies_are_granted(self): + """A set that includes every direct and indirect dependency creates the role with each grant.""" + role = self.create_role(permissions=[DELETE_LIBRARY, EDIT_LIBRARY_CONTENT, VIEW_LIBRARY]) + + self.assertCountEqual( + AuthzRolePermission.objects.filter(role=role).values_list("permission__name", flat=True), + ["delete_library", "edit_library_content", "view_library"], + ) + + @data( + ([EDIT_LIBRARY_CONTENT], {EDIT_LIBRARY_CONTENT: (VIEW_LIBRARY,)}), + ([DELETE_LIBRARY, VIEW_LIBRARY], {DELETE_LIBRARY: (EDIT_LIBRARY_CONTENT,)}), + ( + [DELETE_LIBRARY, EDIT_LIBRARY_CONTENT], + {DELETE_LIBRARY: (VIEW_LIBRARY,), EDIT_LIBRARY_CONTENT: (VIEW_LIBRARY,)}, + ), + ([DELETE_LIBRARY], {DELETE_LIBRARY: (EDIT_LIBRARY_CONTENT, VIEW_LIBRARY)}), + ) + @unpack + def test_missing_dependencies_are_rejected(self, permissions, expected_missing): + """A set without a direct or indirect dependency names what each permission misses and creates nothing. + + ``delete_library`` depends on ``edit_library_content``, which depends on ``view_library``, + so ``view_library`` is an indirect dependency of ``delete_library``. + """ + policy_before = self.enforcer.get_policy() + + with self.assertRaises(MissingPermissionDependenciesError) as raised: + self.create_role(permissions=permissions) + + self.assertEqual(raised.exception.missing, expected_missing) + self.assertFalse(AuthzRoleDefinition.objects.user_defined().exists()) + self.assertFalse(AuthzRolePermission.objects.user_defined().exists()) + self.assertFalse(self.stored_policy_rows("custom_designer").exists()) + self.assertEqual(self.enforcer.get_policy(), policy_before) + def test_failure_while_writing_policy_rolls_everything_back(self): """A failure after the first policy row leaves no definition, grant or policy row behind.""" real_add = PolicyStore.add_policy_row @@ -456,7 +494,7 @@ def test_description_only_leaves_permissions_alone(self): self.assertEqual(updated.description, "New description") self.assertEqual(self.enforcer.get_policy(), policy_before) - @data({"description": "New description"}, {"permissions": [EDIT_LIBRARY_CONTENT]}) + @data({"description": "New description"}, {"permissions": [VIEW_LIBRARY_TEAM]}) def test_any_edit_sets_updated_at(self, changes): """Editing only the description or only the permissions both record when the role changed.""" role = self.create_role(permissions=[VIEW_LIBRARY]) @@ -471,7 +509,7 @@ def test_role_id_name_and_scope_type_do_not_change(self): """Editing keeps the identity of the role, so its assignments stay valid.""" role = self.create_role("Designer") - update_custom_role(role.role_id, description="x", permissions=[EDIT_LIBRARY_CONTENT]) + update_custom_role(role.role_id, description="x", permissions=[VIEW_LIBRARY_TEAM]) stored = AuthzRoleDefinition.objects.get(pk=role.pk) self.assertEqual((stored.role_id, stored.display_name, stored.scopes), ("custom_designer", "Designer", ["lib"])) @@ -505,10 +543,10 @@ 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. + leaves them visible. None of the permissions left after the edit depend on another, so each + check reflects only its own grant. """ - role = self.create_role(permissions=[VIEW_LIBRARY_TEAM, EDIT_LIBRARY_CONTENT]) + role = self.create_role(permissions=[VIEW_LIBRARY_TEAM, VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) self.assign(role) self.hide_permission(VIEW_LIBRARY_TEAM, whole_category=whole_category) @@ -526,6 +564,75 @@ def test_permission_hidden_after_granting_is_kept(self, whole_category): [make_action_key(VIEW_LIBRARY_TEAM), make_action_key(VIEW_LIBRARY)], ) + @data( + ([EDIT_LIBRARY_CONTENT], {EDIT_LIBRARY_CONTENT: (VIEW_LIBRARY,)}), + ([DELETE_LIBRARY, VIEW_LIBRARY], {DELETE_LIBRARY: (EDIT_LIBRARY_CONTENT,)}), + ) + @unpack + def test_edit_that_leaves_out_a_dependency_is_rejected(self, permissions, expected_missing): + """Dropping a dependency that another permission still needs names it and leaves the role unchanged. + + The first case drops a direct dependency of ``edit_library_content``; the second drops + ``edit_library_content``, which ``delete_library`` needs directly. + """ + role = self.create_role(permissions=[DELETE_LIBRARY, EDIT_LIBRARY_CONTENT, VIEW_LIBRARY]) + policy_before = self.enforcer.get_policy() + + with self.assertRaises(MissingPermissionDependenciesError) as raised: + update_custom_role(role.role_id, description="New description", permissions=permissions) + + self.assertEqual(raised.exception.missing, expected_missing) + self.assertEqual(self.enforcer.get_policy(), policy_before) + self.assertEqual(AuthzRoleDefinition.objects.get(pk=role.pk).description, "") + self.assertEqual(AuthzRolePermission.objects.filter(role=role).count(), 3) + + def test_edit_that_adds_a_permission_without_its_dependencies_is_rejected(self): + """Adding a permission whose dependency the role does not grant names it and leaves the role unchanged.""" + role = self.create_role(permissions=[VIEW_LIBRARY]) + + with self.assertRaises(MissingPermissionDependenciesError) as raised: + update_custom_role(role.role_id, permissions=[VIEW_LIBRARY, DELETE_LIBRARY]) + + self.assertEqual(raised.exception.missing, {DELETE_LIBRARY: (EDIT_LIBRARY_CONTENT,)}) + self.assertEqual( + list(AuthzRolePermission.objects.filter(role=role).values_list("permission__name", flat=True)), + ["view_library"], + ) + + def test_kept_hidden_permission_counts_as_a_granted_dependency(self): + """A hidden permission the role keeps satisfies the dependency of a permission the client sends. + + The client cannot send the hidden permission, so without counting it the role could never + keep the permissions that depend on it. + """ + role = self.create_role(permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + self.hide_permission(VIEW_LIBRARY, whole_category=False) + + update_custom_role(role.role_id, permissions=[EDIT_LIBRARY_CONTENT, DELETE_LIBRARY]) + + self.assertCountEqual( + AuthzRolePermission.objects.filter(role=role).values_list("permission__name", flat=True), + ["view_library", "edit_library_content", "delete_library"], + ) + + def test_dependencies_of_a_kept_hidden_permission_are_not_checked(self): + """An edit may drop a visible permission that only a kept hidden permission depends on. + + The client cannot see the hidden permission, so it could not fix an error about it. The + hidden permission's ``g2`` row still grants the dropped dependency to the role's holders. + """ + role = self.create_role(permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + self.assign(role) + self.hide_permission(EDIT_LIBRARY_CONTENT, whole_category=False) + + update_custom_role(role.role_id, permissions=[VIEW_LIBRARY_TEAM]) + + self.assertCountEqual( + AuthzRolePermission.objects.filter(role=role).values_list("permission__name", flat=True), + ["edit_library_content", "view_library_team"], + ) + self.assertTrue(self.is_allowed(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]) diff --git a/src/openedx_authz/tests/rest_api/test_views.py b/src/openedx_authz/tests/rest_api/test_views.py index 26b4fb95..d6930f4d 100644 --- a/src/openedx_authz/tests/rest_api/test_views.py +++ b/src/openedx_authz/tests/rest_api/test_views.py @@ -37,6 +37,7 @@ COURSES_LEGACY_BETA_TESTER_PERMISSIONS, COURSES_MANAGE_COURSE_TEAM, COURSES_VIEW_COURSE, + DELETE_LIBRARY, EDIT_LIBRARY_CONTENT, LIBRARY_ADMIN, LIBRARY_AUTHOR, @@ -2087,6 +2088,23 @@ def test_invalid_role_is_rejected(self, overrides, expected_in_message): self.assertIn(expected_in_message, response.data["message"]) self.assert_no_custom_role_created() + def test_missing_dependencies_are_listed(self): + """Test creating a role whose permissions leave out a direct and an indirect dependency (ADR 0036 §7). + + Expected result: + - Returns 400 BAD REQUEST with ``missing_dependencies`` mapping each permission to what it misses + - No role is created + """ + response = self.post_role(permissions=[DELETE_LIBRARY.identifier]) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertEqual( + response.data["missing_dependencies"], + {DELETE_LIBRARY.identifier: [EDIT_LIBRARY_CONTENT.identifier, VIEW_LIBRARY.identifier]}, + ) + self.assertIn(DELETE_LIBRARY.identifier, response.data["message"]) + self.assert_no_custom_role_created() + def test_name_of_a_static_role_is_taken(self): """Test reusing the stored name of a static role with a different case. @@ -2381,17 +2399,30 @@ def test_description_and_permissions_change_together(self): - 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]}) + response = self.patch_role({"description": "Edits libraries", "permissions": [VIEW_LIBRARY_TEAM.identifier]}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( (response.data["description"], response.data["permissions"]), - ("Edits libraries", [EDIT_LIBRARY_CONTENT.identifier]), + ("Edits libraries", [VIEW_LIBRARY_TEAM.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"], [VIEW_LIBRARY_TEAM.identifier]) + + def test_missing_dependencies_are_listed(self): + """Test an edit that drops a dependency another sent permission still needs (ADR 0036 §7). + + Expected result: + - Returns 400 BAD REQUEST with ``missing_dependencies`` mapping the permission to what it misses + - The role is unchanged, including the description sent with the permissions + """ + response = self.patch_role({"description": "Edits libraries", "permissions": [EDIT_LIBRARY_CONTENT.identifier]}) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( - api.get_role_catalog_entry(self.role.role_id)["permissions"], [EDIT_LIBRARY_CONTENT.identifier] + response.data["missing_dependencies"], {EDIT_LIBRARY_CONTENT.identifier: [VIEW_LIBRARY.identifier]} ) + self.assert_role_unchanged() def test_user_count_counts_holders(self): """Test that the returned role counts its users, not its assignments.