From f0f7d61097a5a7c9f6f65731f278192c9c9b4431 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20M=C3=A9ndez?= Date: Fri, 27 Nov 2026 15:28:37 -0600 Subject: [PATCH] feat: add the endpoint to check a custom role name --- CHANGELOG.rst | 11 ++ .../0036-api-contract-for-custom-roles.rst | 45 +++++ src/openedx_authz/api/custom_roles.py | 52 +++++- src/openedx_authz/rest_api/data.py | 7 + src/openedx_authz/rest_api/v1/fields.py | 14 ++ src/openedx_authz/rest_api/v1/serializers.py | 28 +++- src/openedx_authz/rest_api/v1/urls.py | 1 + src/openedx_authz/rest_api/v1/views.py | 83 +++++++++- .../tests/api/test_custom_roles.py | 73 +++++++++ .../tests/rest_api/test_views.py | 155 ++++++++++++++++++ 10 files changed, 461 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 06b67f95f..92351ab58 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -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. diff --git a/docs/decisions/0036-api-contract-for-custom-roles.rst b/docs/decisions/0036-api-contract-for-custom-roles.rst index 6ff40d54d..96facb39f 100644 --- a/docs/decisions/0036-api-contract-for-custom-roles.rst +++ b/docs/decisions/0036-api-contract-for-custom-roles.rst @@ -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. @@ -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 ************ diff --git a/src/openedx_authz/api/custom_roles.py b/src/openedx_authz/api/custom_roles.py index 7764649dc..5d248cbf1 100644 --- a/src/openedx_authz/api/custom_roles.py +++ b/src/openedx_authz/api/custom_roles.py @@ -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: @@ -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]) @@ -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, *, @@ -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.") diff --git a/src/openedx_authz/rest_api/data.py b/src/openedx_authz/rest_api/data.py index 0c3c2ed28..12067ec67 100644 --- a/src/openedx_authz/rest_api/data.py +++ b/src/openedx_authz/rest_api/data.py @@ -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.""" diff --git a/src/openedx_authz/rest_api/v1/fields.py b/src/openedx_authz/rest_api/v1/fields.py index 2413a975e..2af1a06c5 100644 --- a/src/openedx_authz/rest_api/v1/fields.py +++ b/src/openedx_authz/rest_api/v1/fields.py @@ -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.""" diff --git a/src/openedx_authz/rest_api/v1/serializers.py b/src/openedx_authz/rest_api/v1/serializers.py index 909880405..9093e8ef3 100644 --- a/src/openedx_authz/rest_api/v1/serializers.py +++ b/src/openedx_authz/rest_api/v1/serializers.py @@ -6,6 +6,7 @@ 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, @@ -13,7 +14,7 @@ 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() @@ -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()), @@ -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). diff --git a/src/openedx_authz/rest_api/v1/urls.py b/src/openedx_authz/rest_api/v1/urls.py index dbc04990f..13c7ff7b0 100644 --- a/src/openedx_authz/rest_api/v1/urls.py +++ b/src/openedx_authz/rest_api/v1/urls.py @@ -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//", views.RoleDetailView.as_view(), name="role-detail"), path("users/validate/", views.UserValidationAPIView.as_view(), name="user-validation"), ] diff --git a/src/openedx_authz/rest_api/v1/views.py b/src/openedx_authz/rest_api/v1/views.py index 5b468c5a2..46af102fd 100644 --- a/src/openedx_authz/rest_api/v1/views.py +++ b/src/openedx_authz/rest_api/v1/views.py @@ -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 @@ -52,6 +57,8 @@ RoleCatalogMetaSerializer, RoleCatalogResponseSerializer, RoleCatalogRoleSerializer, + RoleNameValidationResponseSerializer, + RoleNameValidationSerializer, UpdateCustomRoleSerializer, UserRoleAssignmentSerializer, UserValidationAPIViewResponseSerializer, @@ -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. diff --git a/src/openedx_authz/tests/api/test_custom_roles.py b/src/openedx_authz/tests/api/test_custom_roles.py index 4b558954e..5046aae6a 100644 --- a/src/openedx_authz/tests/api/test_custom_roles.py +++ b/src/openedx_authz/tests/api/test_custom_roles.py @@ -21,6 +21,7 @@ remove_custom_role, slugify_role_name, update_custom_role, + validate_custom_role_name, ) from openedx_authz.api.data import RoleData, ScopeData, SubjectData from openedx_authz.api.exceptions import ( @@ -229,6 +230,13 @@ def test_surrounding_whitespace_is_dropped_from_the_name(self): self.assertEqual(role.display_name, "Designer") self.assertEqual(role.role_id, "custom_designer") + def test_name_is_stored_in_nfc_form(self): + """A name typed with a decomposed accent is stored with the composed character.""" + role = self.create_role("Cafe\u0301 Designer") + + role.refresh_from_db() + self.assertEqual(role.display_name, "Caf\u00e9 Designer") + def test_name_that_converts_to_a_taken_id_gets_a_new_id(self): """Two different names that convert to the same ID get the next free ID.""" first = self.create_role("Course Designer") @@ -340,6 +348,71 @@ def test_takes_the_policy_write_lock(self): lock.assert_called_once_with() +@ddt +class TestValidateCustomRoleName(CustomRoleTestCase): + """Checking a name applies the rules of create and writes nothing.""" + + def test_free_name_is_returned_as_it_would_be_stored(self): + """A free name comes back without surrounding whitespace and no role is created.""" + policy_before = self.enforcer.get_policy() + + self.assertEqual(validate_custom_role_name(" Designer "), "Designer") + + self.assertFalse(AuthzRoleDefinition.objects.user_defined().exists()) + self.assertEqual(self.enforcer.get_policy(), policy_before) + + @data("Designer", "DESIGNER", " designer ", "Library Admin", "library admin") + def test_name_taken_by_an_active_role_is_rejected(self, display_name): + """A name used by another role, custom or static by its stored name, is taken ignoring case and whitespace.""" + self.create_role("Designer") + + with self.assertRaises(CustomRoleNameTakenError): + validate_custom_role_name(display_name) + + def test_name_of_a_removed_role_is_free(self): + """A removed role gives its name back, as it does for create.""" + role = self.create_role("Designer") + remove_custom_role(role.role_id) + + self.assertEqual(validate_custom_role_name("Designer"), "Designer") + + @data("", " ", "x" * 256, None) + def test_invalid_name_is_rejected(self, display_name): + """A blank, too long or non-string name is invalid, the same as on create.""" + with self.assertRaises(InvalidCustomRoleError): + validate_custom_role_name(display_name) + + @data("\u200b", " \u200b ", "\u200d", "\u2060", "\ufeff", "\u200c\u200d\u00a0") + def test_name_without_visible_characters_is_blank(self, display_name): + """A name made only of invisible characters, which ``str.strip`` keeps, is blank.""" + with self.assertRaisesRegex(InvalidCustomRoleError, "blank"): + validate_custom_role_name(display_name) + + @data("Desi\u200bgner", "Designer\u200b", "\u2060Designer", "Desi\ufeffgner") + def test_name_with_a_zero_width_space_is_rejected(self, display_name): + """A zero-width space would let a name that looks like a taken one be stored.""" + self.create_role("Designer") + + with self.assertRaisesRegex(InvalidCustomRoleError, "zero-width"): + validate_custom_role_name(display_name) + + @data("\U0001f469\u200d\U0001f4bb Developers", "\u0645\u06cc\u200c\u062e\u0648\u0627\u0647\u0645") + def test_name_with_joiners_is_free(self, display_name): + """ZWJ in emoji sequences and ZWNJ in languages such as Persian are part of the name.""" + self.assertEqual(validate_custom_role_name(display_name), display_name) + + def test_name_taken_in_another_normal_form_is_rejected(self): + """A decomposed accent matches the same name stored with the composed character.""" + self.create_role("Caf\u00e9 Designer") + + with self.assertRaises(CustomRoleNameTakenError): + validate_custom_role_name("Cafe\u0301 Designer") + + def test_name_at_the_maximum_length_is_free(self): + """The length limit is inclusive, so a name that fills the column can be used.""" + self.assertEqual(validate_custom_role_name("x" * 255), "x" * 255) + + @ddt class TestUpdateCustomRole(CustomRoleTestCase): """Editing a role changes only what differs and reaches its holders at once.""" diff --git a/src/openedx_authz/tests/rest_api/test_views.py b/src/openedx_authz/tests/rest_api/test_views.py index 6e5aed4b0..26b4fb959 100644 --- a/src/openedx_authz/tests/rest_api/test_views.py +++ b/src/openedx_authz/tests/rest_api/test_views.py @@ -2027,6 +2027,8 @@ def test_unauthenticated_user_cannot_create(self): @data( ({"display_name": None}, "display_name"), ({"display_name": " "}, "display_name"), + ({"display_name": 123}, "display_name"), + ({"display_name": 1.5}, "display_name"), ({"scope_types": []}, "scope_types"), ({"scope_types": ["lib", "course-v1"]}, "scope_types"), ({"scope_types": ["org"]}, "scope_types"), @@ -2129,6 +2131,159 @@ def test_name_of_a_removed_role_can_be_reused(self): self.assertEqual(response.data["role"], "custom_library_designer_2") +@ddt +class TestRoleNameValidationView(CustomRoleViewTestMixin): + """Test suite for checking custom role names through RoleNameValidationView (ADR 0036).""" + + def setUp(self): + """Point the client at the name check.""" + super().setUp() + self.url = reverse("openedx_authz:role-name-validation") + + def post_name(self, display_name) -> Response: + """Send a name check request for ``display_name``.""" + return self.client.post(self.url, {"display_name": display_name}, format="json") + + def create_role(self, display_name: str) -> None: + """Create a library custom role with the given name through the API.""" + api.create_custom_role(display_name, "", "lib", [VIEW_LIBRARY.identifier]) + + def test_free_name_is_available(self): + """Test checking a name no role uses. + + Expected result: + - Returns 200 OK with the name as sent, available, and no reason or message + - No role is created + """ + response = self.post_name(" Library Designer ") + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual( + response.data, + {"display_name": " Library Designer ", "available": True, "reason": None, "message": None}, + ) + self.assertFalse(AuthzRoleDefinition.objects.user_defined().exists()) + + def test_name_of_a_static_role_is_taken(self): + """Test checking the stored name of a static role with a different case. + + Expected result: + - Returns 200 OK, not available, with the ``taken`` reason and a message naming the name + """ + static_name = AuthzRoleDefinition.objects.get(role_id=LIBRARY_AUTHOR.external_key).display_name + + response = self.post_name(static_name.upper()) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertFalse(response.data["available"]) + self.assertEqual(response.data["reason"], "taken") + self.assertIn(static_name.upper(), response.data["message"]) + + def test_name_of_a_custom_role_is_taken(self): + """Test checking the name of a custom role with a different case and surrounding spaces. + + Expected result: + - Returns 200 OK, not available, with the ``taken`` reason + """ + self.create_role("Library Designer") + + response = self.post_name(" library designer ") + + self.assertFalse(response.data["available"]) + self.assertEqual(response.data["reason"], "taken") + + def test_name_of_a_removed_role_is_available(self): + """Test checking the name of a removed custom role. + + Expected result: + - The name is available again + """ + self.create_role("Library Designer") + api.remove_custom_role("custom_library_designer") + + response = self.post_name("Library Designer") + + self.assertTrue(response.data["available"]) + self.assertIsNone(response.data["reason"]) + + @data( + ("", "blank"), + (" ", "blank"), + ("\u200b", "blank"), + ("Desi\u200bgner", "zero-width"), + ("x" * 256, "longer than"), + ) + @unpack + def test_invalid_name_is_not_available(self, display_name, expected_in_message): + """Test checking names that create would reject. + + Expected result: + - Returns 200 OK, not available, with the ``invalid`` reason explaining the problem + """ + response = self.post_name(display_name) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertFalse(response.data["available"]) + self.assertEqual(response.data["reason"], "invalid") + self.assertIn(expected_in_message, response.data["message"]) + + @data( + {}, + {"display_name": None}, + {"display_name": ["Designer"]}, + {"display_name": 123}, + {"display_name": 1.5}, + ) + def test_malformed_request_is_rejected(self, body): + """Test requests without a usable ``display_name`` field. + + Expected result: + - Returns 400 BAD REQUEST naming the field + """ + response = self.client.post(self.url, body, format="json") + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn("display_name", response.data) + + @data("staff_only", "superuser_only") + def test_staff_and_superusers_can_check(self, username): + """Test that each privileged kind of user can check a name. + + Expected result: + - Returns 200 OK with the answer for a staff user and for a superuser + """ + self.client.force_authenticate(user=User.objects.get(username=username)) + + response = self.post_name("Library Designer") + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertTrue(response.data["available"]) + + def test_team_admin_cannot_check(self): + """Test that a user who can list roles but not create them cannot check names. + + Expected result: + - A library admin gets 403 FORBIDDEN + """ + self.client.force_authenticate(user=User.objects.get(username="regular_5")) + + response = self.post_name("Library Designer") + + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + + def test_unauthenticated_user_cannot_check(self): + """Test that an anonymous request is rejected. + + Expected result: + - Returns 401 UNAUTHORIZED + """ + self.client.force_authenticate(user=None) + + response = self.post_name("Library Designer") + + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + + @ddt class TestRoleDetailViewUpdate(CustomRoleViewTestMixin): """Test suite for editing custom roles through RoleDetailView (ADR 0036)."""