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
9 changes: 9 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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/<role_id>/`` 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/<role_id>/`` 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.
Expand Down
4 changes: 3 additions & 1 deletion src/openedx_authz/api/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
8 changes: 6 additions & 2 deletions src/openedx_authz/api/custom_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
9 changes: 7 additions & 2 deletions src/openedx_authz/api/roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}.")


Expand Down
6 changes: 6 additions & 0 deletions src/openedx_authz/rest_api/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
54 changes: 50 additions & 4 deletions src/openedx_authz/rest_api/v1/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
23 changes: 22 additions & 1 deletion src/openedx_authz/rest_api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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."""

Expand Down
98 changes: 89 additions & 9 deletions src/openedx_authz/rest_api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -37,6 +37,7 @@
AnyScopePermission,
DynamicScopePermission,
PrivilegedWritePermission,
RoleScopeTypePermission,
ScopeTypePermission,
)
from openedx_authz.rest_api.v1.serializers import (
Expand All @@ -46,6 +47,7 @@
ListUsersInRoleWithScopeSerializer,
PermissionValidationResponseSerializer,
PermissionValidationSerializer,
RemoveCustomRoleQuerySerializer,
RemoveUsersFromRoleWithScopeSerializer,
RoleCatalogMetaSerializer,
RoleCatalogResponseSerializer,
Expand All @@ -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.
Expand All @@ -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()
Expand Down Expand Up @@ -586,11 +600,13 @@ def post(self, request: HttpRequest) -> Response:

@view_auth_classes()
class RoleDetailView(APIView):
Comment thread
BryanttV marked this conversation as resolved.
Resolved
"""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**

Expand All @@ -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,
Expand All @@ -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):
Expand Down
6 changes: 6 additions & 0 deletions src/openedx_authz/tests/api/test_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
AuthzRoleDefinition,
AuthzRolePermission,
)
from openedx_authz.tests.test_utils import role_ids_matched_ignoring_case


class CatalogTestCase(TestCase):
Expand Down Expand Up @@ -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``.

Expand Down
Loading