Skip to content
Open
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
8 changes: 6 additions & 2 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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.
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/<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``);
Expand Down
43 changes: 41 additions & 2 deletions src/openedx_authz/api/custom_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -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.")
Expand All @@ -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"])
Expand Down Expand Up @@ -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:
Expand Down
16 changes: 16 additions & 0 deletions src/openedx_authz/api/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"CustomRoleNameTakenError",
"CustomRoleNotFoundError",
"InvalidCustomRoleError",
"MissingPermissionDependenciesError",
"RoleNotFoundError",
"StaticRoleError",
]
Expand All @@ -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."""

Expand Down
43 changes: 37 additions & 6 deletions src/openedx_authz/rest_api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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**

Expand Down Expand Up @@ -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",
Expand All @@ -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:
Expand All @@ -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)**

Expand Down Expand Up @@ -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",
Expand All @@ -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)
Expand Down
Loading
Loading