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
11 changes: 11 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,17 @@ Added
``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 ``POST /api/authz/v1/roles/validate-name/`` to check whether a new custom role can use a
display name before it is created (ADR 0036). Only staff and superusers can call it. It returns
200 with ``available`` and, when the name cannot be used, a ``reason`` (``taken`` or
``invalid``) and a ``message``. The check is not a reservation; create checks the name again.
Added ``validate_custom_role_name`` to the public API, which applies the same name rules as
``create_custom_role`` without writing anything.
Both this endpoint and ``POST /api/authz/v1/roles/`` return 400 for a ``display_name`` that is
not a string, such as a number, instead of converting it.
Custom role names are now stored in Unicode NFC form. A name made only of invisible characters
is blank, and a name with a zero-width space (U+200B), word joiner (U+2060) or U+FEFF is
rejected, on both create and this endpoint.
* 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
45 changes: 45 additions & 0 deletions docs/decisions/0036-api-contract-for-custom-roles.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ role.
* The display name is unique among the roles that have not been removed, static and custom,
ignoring case. For static roles, the stored name is compared, not its translation. A taken name
returns 409. The name cannot be changed after creation.
* The name is stored in Unicode NFC form without surrounding whitespace, so a name typed with
composed or decomposed accents is the same name. A name made only of invisible characters, such
as a zero-width space, is blank. A zero-width space (U+200B), word joiner (U+2060) or U+FEFF
anywhere in the name is rejected, because it would let two names that look the same both be
stored. The joiners U+200C and U+200D are allowed, since emoji and some languages, such as
Persian, need them to write a word correctly.
* This name check is separate from role IDs, which cannot collide because of the ``custom_``
prefix (`ADR 0035`_). The name of a removed role can be used again, and the new role gets a new
ID.
Expand Down Expand Up @@ -248,6 +254,45 @@ Response codes
* 404: the role does not exist or was removed.
* 409: the display name is taken, or the role has assignments and ``assignments`` was not given.

Addendum: Check a name before creating the role
================================================

**2026-11-27**

The create wizard asks for the name on its first step and sends ``POST /api/authz/v1/roles/`` on
its last one, so a taken name was only reported after the administrator had picked the
permissions. A separate endpoint lets the wizard check the name when it leaves the first step.

.. code:: ts

// POST /api/authz/v1/roles/validate-name/
// Request
{
display_name: string
}

// Response, always 200
{
display_name: string // as sent
available: boolean
reason: "taken" | "invalid" | null
message: string | null
}

* The name is checked as create checks it (section 5): blank names, names with a zero-width space
and names over 255 characters are ``invalid``, and a name used by a role that has not been
removed is ``taken``.
* Only staff and superusers can call it, as for create.
* An unavailable name is an answer, not an error, so the response is 200. A request without
``display_name``, or with null or a value that is not a string, such as a number or a list,
returns 400. Create rejects the same values, so a number is never turned into a name.
* The answer is not a reservation. Another role can take the name before the create request,
which still returns 409, so clients must keep handling it.

The list endpoint's ``search`` was not used for this check. It matches part of the translated name
in the requested scope types and needs only the permission to list roles, while the name rule
compares the whole stored name across every resource type.

Consequences
************

Expand Down
52 changes: 47 additions & 5 deletions src/openedx_authz/api/custom_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,18 @@
"create_custom_role",
"remove_custom_role",
"update_custom_role",
"validate_custom_role_name",
]

FALLBACK_ROLE_SLUG = "role"
DISPLAY_NAME_MAX_LENGTH = AuthzRoleDefinition._meta.get_field("display_name").max_length
# Control, format and separator characters draw nothing on their own, so a name made only of them
# looks blank even though ``str.strip`` keeps some of them, such as U+200B.
INVISIBLE_CHARACTER_CATEGORIES = frozenset({"Cc", "Cf", "Zs", "Zl", "Zp"})
# Zero-width characters that no language needs to write a name. They would let two names that
# look the same both be stored. ZWJ and ZWNJ are not listed because emoji and some languages,
# such as Persian, need them to write a word correctly.
ZERO_WIDTH_CHARACTERS = frozenset({"\u200b", "\u2060", "\ufeff"})


def slugify_role_name(display_name: str) -> str:
Expand Down Expand Up @@ -106,11 +114,9 @@ def create_custom_role(
or the permissions are empty, unknown, hidden or do not support the scope type.
CustomRoleNameTakenError: If another role that has not been removed uses the name.
"""
_validate_text("display name", display_name)
_validate_text("description", description)
_validate_text("scope type", scope_type)
display_name = display_name.strip()
_validate_display_name(display_name)
display_name = _clean_display_name(display_name)
with _writing_custom_roles() as policy_store:
_check_display_name_is_free(display_name)
resolved = _resolve_permissions(permissions, [scope_type])
Expand All @@ -125,6 +131,28 @@ def create_custom_role(
return role


def validate_custom_role_name(display_name: str) -> str:
"""Check that a new custom role could use a display name, without creating anything.

Lets a client report a bad name before it collects the rest of the role. The check runs
outside the custom role lock, so another role can still take the name before the role is
created; ``create_custom_role`` checks it again.

Args:
display_name (str): The name as the administrator entered it.

Returns:
str: The name as it would be stored, without surrounding whitespace.

Raises:
InvalidCustomRoleError: If the name is not a string, is blank or is too long.
CustomRoleNameTakenError: If another role that has not been removed uses the name.
"""
display_name = _clean_display_name(display_name)
_check_display_name_is_free(display_name)
return display_name


def update_custom_role(
role_id: str,
*,
Expand Down Expand Up @@ -236,10 +264,24 @@ def _validate_permission_ids(permission_ids: object) -> None:
raise InvalidCustomRoleError("The permissions must be a list of permission ID strings.")


def _clean_display_name(display_name: object) -> str:
"""Return the display name in NFC form without surrounding whitespace, if it is a valid name.

NFC makes a name typed with composed or decomposed accents the same stored name, so the
uniqueness check compares what the administrator sees.
"""
_validate_text("display name", display_name)
display_name = unicodedata.normalize("NFC", display_name).strip()
_validate_display_name(display_name)
return display_name


def _validate_display_name(display_name: str) -> None:
"""Reject a display name that is blank or longer than its column."""
if not display_name:
"""Reject a display name that is blank, has zero-width characters or is longer than its column."""
if all(unicodedata.category(character) in INVISIBLE_CHARACTER_CATEGORIES for character in display_name):
raise InvalidCustomRoleError("The display name cannot be blank.")
if ZERO_WIDTH_CHARACTERS.intersection(display_name):
raise InvalidCustomRoleError("The display name cannot contain zero-width spaces.")
if len(display_name) > DISPLAY_NAME_MAX_LENGTH:
raise InvalidCustomRoleError(f"The display name cannot be longer than {DISPLAY_NAME_MAX_LENGTH} characters.")

Expand Down
7 changes: 7 additions & 0 deletions src/openedx_authz/rest_api/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ class RoleRemovalAssignmentsAction(BaseEnum):
REVOKE = "revoke"


class RoleNameUnavailableReason(BaseEnum):
"""Enum for why a new custom role cannot use a display name (ADR 0036)."""

TAKEN = "taken"
INVALID = "invalid"


class SearchField(BaseEnum):
"""Enum for the fields allowed for text search filtering."""

Expand Down
14 changes: 14 additions & 0 deletions src/openedx_authz/rest_api/v1/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ def to_representation(self, value):
return ",".join(value)


class StrictCharField(serializers.CharField):
"""Serializer for a string that rejects other JSON types instead of converting them.

DRF's ``CharField`` turns numbers into strings, so ``123`` would be accepted as ``"123"``.
Fields whose value is returned or stored as sent need the client's own string.
"""

def to_internal_value(self, data):
"""Reject a value that is not a string, then apply the usual ``CharField`` rules."""
if not isinstance(data, str):
self.fail("invalid")
return super().to_internal_value(data)


class LowercaseCharField(serializers.CharField):
"""Serializer for a lowercase string."""

Expand Down
28 changes: 26 additions & 2 deletions src/openedx_authz/rest_api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
from openedx_authz import api
from openedx_authz.api.data import GLOBAL_SCOPE_WILDCARD, DefinitionKind
from openedx_authz.rest_api.data import (
RoleNameUnavailableReason,
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
from openedx_authz.rest_api.v1.fields import CommaSeparatedListField, LowercaseCharField, StrictCharField

User = get_user_model()

Expand Down Expand Up @@ -246,7 +247,7 @@ class CreateCustomRoleSerializer(serializers.Serializer): # pylint: disable=abs
``api.create_custom_role``, so the rules live in one place.
"""

display_name = serializers.CharField()
display_name = StrictCharField()
description = serializers.CharField(required=False, default="", allow_blank=True)
scope_types = serializers.ListField(
child=serializers.ChoiceField(choices=ScopesTypeField.values()),
Expand Down Expand Up @@ -281,6 +282,29 @@ def validate(self, attrs: dict) -> dict:
return attrs


class RoleNameValidationSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for the request body that checks a custom role name (ADR 0036).

Blank values and surrounding whitespace are kept, so ``api.validate_custom_role_name`` decides
whether the name is usable and the answer matches what create would do.
"""

display_name = StrictCharField(allow_blank=True, trim_whitespace=False)


class RoleNameValidationResponseSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for whether a new custom role can use a display name, and why not."""

display_name = serializers.CharField(help_text="The name as it was sent")
available = serializers.BooleanField(help_text="Whether a new custom role can use the name")
reason = serializers.ChoiceField(
choices=RoleNameUnavailableReason.values(),
allow_null=True,
help_text="Why the name cannot be used, or null when it can",
)
message = serializers.CharField(allow_null=True, help_text="A description of the problem, or null")


class RemoveCustomRoleQuerySerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for the query parameters of the request that removes a custom role (ADR 0036).

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/validate-name/", views.RoleNameValidationView.as_view(), name="role-name-validation"),
path("roles/<str:role_id>/", views.RoleDetailView.as_view(), name="role-detail"),
path("users/validate/", views.UserValidationAPIView.as_view(), name="user-validation"),
]
Expand Down
83 changes: 82 additions & 1 deletion src/openedx_authz/rest_api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,12 @@
VIEW_LIBRARY,
)
from openedx_authz.filters import PermissionValidationRequested, RoleAssignmentRequested, RoleRemovalRequested
from openedx_authz.rest_api.data import RoleOperationError, RoleOperationStatus, RoleRemovalAssignmentsAction
from openedx_authz.rest_api.data import (
RoleNameUnavailableReason,
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 @@ -52,6 +57,8 @@
RoleCatalogMetaSerializer,
RoleCatalogResponseSerializer,
RoleCatalogRoleSerializer,
RoleNameValidationResponseSerializer,
RoleNameValidationSerializer,
UpdateCustomRoleSerializer,
UserRoleAssignmentSerializer,
UserValidationAPIViewResponseSerializer,
Expand Down Expand Up @@ -727,6 +734,80 @@ def delete(self, request: HttpRequest, role_id: str) -> Response:
return Response(status=status.HTTP_204_NO_CONTENT)


@view_auth_classes()
class RoleNameValidationView(APIView):
"""API view for checking whether a new custom role can use a display name (ADR 0036).

Lets the create wizard report a taken or invalid name on its first step, before the
administrator picks permissions. The answer is not a reservation: another role can take the
name before the create request, which then returns 409.

**Endpoints**

- POST: Check one display name

**Request Body (POST)**

- display_name (Required): The name to check. It is compared like
``POST /api/authz/v1/roles/`` compares it: without surrounding whitespace and ignoring case,
against every role that has not been removed, static or custom.

**Response Format (POST)**

Returns HTTP 200 OK with::

{
"display_name": "Library Designer",
"available": false,
"reason": "taken",
"message": "A role named 'Library Designer' already exists."
}

``reason`` is ``taken`` when another role uses the name, ``invalid`` when the name is blank or
too long, and ``null`` when the name is available.

**Authentication and Permissions**

- Requires authenticated user.
- Requires a staff user or a superuser, as for creating a custom role.

**Example Request**

POST /api/authz/v1/roles/validate-name/ {"display_name": "Library Designer"}
"""

permission_classes = [PrivilegedWritePermission]

@apidocs.schema(
body=RoleNameValidationSerializer,
responses={
status.HTTP_200_OK: RoleNameValidationResponseSerializer,
status.HTTP_400_BAD_REQUEST: "The request data is invalid",
status.HTTP_401_UNAUTHORIZED: "The user is not authenticated",
status.HTTP_403_FORBIDDEN: "The user is neither staff nor a superuser",
},
)
def post(self, request: HttpRequest) -> Response:
"""Report whether a new custom role can use the display name, and why not."""
serializer = RoleNameValidationSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
display_name = serializer.validated_data["display_name"]
reason, message = None, None
try:
api.validate_custom_role_name(display_name)
except api.CustomRoleNameTakenError as exc:
reason, message = RoleNameUnavailableReason.TAKEN, str(exc)
except api.InvalidCustomRoleError as exc:
reason, message = RoleNameUnavailableReason.INVALID, str(exc)
response_data = {
"display_name": display_name,
"available": reason is None,
"reason": reason,
"message": message,
}
return Response(RoleNameValidationResponseSerializer(response_data).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
Loading