Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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/<role_id>/`` 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.
Expand Down
7 changes: 5 additions & 2 deletions docs/decisions/0036-api-contract-for-custom-roles.rst
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,10 @@ Returns 200 with the role object.
PATCH /api/authz/v1/roles/<role_id>/
====================================

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/<role_id>/
=====================================
Expand Down Expand Up @@ -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
19 changes: 14 additions & 5 deletions src/openedx_authz/api/custom_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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])
Expand Down
25 changes: 25 additions & 0 deletions src/openedx_authz/rest_api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
1 change: 1 addition & 0 deletions src/openedx_authz/rest_api/v1/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/<str:role_id>/", views.RoleDetailView.as_view(), name="role-detail"),
path("users/validate/", views.UserValidationAPIView.as_view(), name="user-validation"),
]

Expand Down
80 changes: 78 additions & 2 deletions src/openedx_authz/rest_api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
RoleCatalogMetaSerializer,
RoleCatalogResponseSerializer,
RoleCatalogRoleSerializer,
UpdateCustomRoleSerializer,
UserRoleAssignmentSerializer,
UserValidationAPIViewResponseSerializer,
UserValidationAPIViewSerializer,
Expand All @@ -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):
"""
Expand Down Expand Up @@ -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)
Comment thread
BryanttV marked this conversation as resolved.
Resolved
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.
Expand Down
54 changes: 53 additions & 1 deletion src/openedx_authz/tests/api/test_custom_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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])
Expand Down
23 changes: 23 additions & 0 deletions src/openedx_authz/tests/rest_api/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Loading