From 21e709b0b7be65dcd7b40b97dcf940c8c51d514f Mon Sep 17 00:00:00 2001 From: Taylor Payne Date: Thu, 3 Dec 2026 14:14:27 -0700 Subject: [PATCH] feat: cap role description length and update timestamp on permission drops Addresses issue #667 (follow-up from PR #647 review): 1. Cap role description length at 500 characters in both CreateCustomRoleSerializer and UpdateCustomRoleSerializer. The field previously had no max length; a 10k+ character value was accepted during review. The longest existing role description is 201 characters, so 500 is a reasonable limit. 2. Update custom role updated_at timestamp when load_authz_schema --drop-custom-role-permissions removes grants. Previously the command deleted permission grants without touching the role row, so updated_at stayed old and GET /roles/ sorted by a stale timestamp. Per ADR 0036, permission changes should update the role's timestamp. Closes #667 --- src/openedx_authz/engine/renderer.py | 8 +++- src/openedx_authz/rest_api/v1/serializers.py | 4 +- src/openedx_authz/rest_api/v1/views.py | 4 +- .../tests/rest_api/test_views.py | 46 +++++++++++++++++++ src/openedx_authz/tests/schema/test_apply.py | 14 ++++++ 5 files changed, 71 insertions(+), 5 deletions(-) diff --git a/src/openedx_authz/engine/renderer.py b/src/openedx_authz/engine/renderer.py index d8da7f26..22c34e65 100644 --- a/src/openedx_authz/engine/renderer.py +++ b/src/openedx_authz/engine/renderer.py @@ -50,6 +50,7 @@ from crum import get_current_user from django.db import transaction from django.db.models import QuerySet +from django.db.models.functions import Now from openedx_events.authz.data import RoleAssignmentData as RoleAssignmentEventData from openedx_events.authz.signals import ROLE_ASSIGNMENT_DELETED @@ -525,14 +526,19 @@ def _drop_unlinked_custom_grants(self, policy_store: PolicyStore, schema: Compil """Remove the unlinked custom role grants and their ``p`` rows (ADR 0035 ยง5). Must run before the definitions are pruned, because deleting a permission definition - cascades to every grant of it. + cascades to every grant of it. Each role that loses a grant has its ``updated_at`` set + to the database time, since a permission change is a change to the role (ADR 0036). """ grants = list(self._unlinked_custom_grants(schema)) + affected_role_pks = set() for grant in grants: + affected_role_pks.add(grant.role_id) policy_store.remove_policy_row( PolicyRow.from_grant(grant.role.role_id, grant.permission.identifier, grant.scope) ) schema_models.AuthzRolePermission.objects.filter(pk__in=[grant.pk for grant in grants]).delete() + if affected_role_pks: + schema_models.AuthzRoleDefinition.objects.filter(pk__in=affected_role_pks).update(updated_at=Now()) @staticmethod def _row_sort_key(row: PolicyRow) -> tuple[str, str, str, str]: diff --git a/src/openedx_authz/rest_api/v1/serializers.py b/src/openedx_authz/rest_api/v1/serializers.py index 38acf131..135affc8 100644 --- a/src/openedx_authz/rest_api/v1/serializers.py +++ b/src/openedx_authz/rest_api/v1/serializers.py @@ -249,7 +249,7 @@ class CreateCustomRoleSerializer(serializers.Serializer): # pylint: disable=abs """ display_name = StrictCharField() - description = serializers.CharField(required=False, default="", allow_blank=True) + description = serializers.CharField(required=False, default="", allow_blank=True, max_length=500) scope_types = serializers.ListField( child=serializers.ChoiceField(choices=ScopesTypeField.values()), min_length=1, @@ -268,7 +268,7 @@ class UpdateCustomRoleSerializer(serializers.Serializer): # pylint: disable=abs FIXED_FIELDS = ("display_name", "scope_types") - description = serializers.CharField(required=False, allow_blank=True) + description = serializers.CharField(required=False, allow_blank=True, max_length=500) permissions = serializers.ListField(child=serializers.CharField(), required=False) def validate(self, attrs: dict) -> dict: diff --git a/src/openedx_authz/rest_api/v1/views.py b/src/openedx_authz/rest_api/v1/views.py index 46af102f..a22974d4 100644 --- a/src/openedx_authz/rest_api/v1/views.py +++ b/src/openedx_authz/rest_api/v1/views.py @@ -489,7 +489,7 @@ class RoleListView(APIView): **Request Body (POST)** - display_name (Required): Unique among the roles that have not been removed, ignoring case - - description (Optional): Free text, which may be empty + - description (Optional): Free text of at most 500 characters, 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 @@ -623,7 +623,7 @@ class RoleDetailView(APIView): **Request Body (PATCH)** - - description (Optional): Free text, which may be empty + - description (Optional): Free text of at most 500 characters, 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. diff --git a/src/openedx_authz/tests/rest_api/test_views.py b/src/openedx_authz/tests/rest_api/test_views.py index 48d553e6..499c8ccc 100644 --- a/src/openedx_authz/tests/rest_api/test_views.py +++ b/src/openedx_authz/tests/rest_api/test_views.py @@ -2049,6 +2049,29 @@ def test_malformed_request_is_rejected(self, overrides, field): self.assertIn(field, response.data) self.assert_no_custom_role_created() + def test_description_of_500_characters_is_stored(self): + """Test a description at the length limit. + + Expected result: + - Returns 201 CREATED and the full description is stored + """ + response = self.post_role(description="x" * 500) + + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + self.assertEqual(AuthzRoleDefinition.objects.get(role_id="custom_library_designer").description, "x" * 500) + + def test_description_over_500_characters_is_rejected(self): + """Test a description just over the length limit. + + Expected result: + - Returns 400 BAD REQUEST naming the field, and no role is created + """ + response = self.post_role(description="x" * 501) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn("description", response.data) + self.assert_no_custom_role_created() + @data("display_name", "scope_types", "permissions") def test_missing_required_field_is_rejected(self, field): """Test requests that leave out a required field. @@ -2341,6 +2364,29 @@ def test_description_can_be_emptied(self): self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(AuthzRoleDefinition.objects.get(pk=self.role.pk).description, "") + def test_description_of_500_characters_is_stored(self): + """Test a description at the length limit. + + Expected result: + - Returns 200 OK and the full description is stored + """ + response = self.patch_role({"description": "x" * 500}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(AuthzRoleDefinition.objects.get(pk=self.role.pk).description, "x" * 500) + + def test_description_over_500_characters_is_rejected(self): + """Test a description just over the length limit. + + Expected result: + - Returns 400 BAD REQUEST naming the field, and the role is unchanged + """ + response = self.patch_role({"description": "x" * 501}) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn("description", response.data) + self.assert_role_unchanged() + def test_permissions_are_replaced_for_holders(self): """Test replacing the permissions of a role that is assigned. diff --git a/src/openedx_authz/tests/schema/test_apply.py b/src/openedx_authz/tests/schema/test_apply.py index b34654c4..6a7c64e3 100644 --- a/src/openedx_authz/tests/schema/test_apply.py +++ b/src/openedx_authz/tests/schema/test_apply.py @@ -15,11 +15,13 @@ from __future__ import annotations +from datetime import timedelta from unittest import mock import pytest from django.db import IntegrityError, transaction from django.test import TestCase +from django.utils import timezone from openedx_authz.api.catalog import get_role_catalog from openedx_authz.constants import DefinitionKind @@ -706,6 +708,18 @@ def test_role_left_without_permissions_stays_in_the_catalog(self): roles = {item["role"]: item for item in get_role_catalog(["course-v1"])} assert roles["custom_designer"]["permissions"] == [] + def test_drop_updates_only_the_affected_roles_timestamp(self): + """A role that loses a grant records the change; a role whose grants all stay keeps its timestamp.""" + enforcer = self._seeded_enforcer(custom_permissions=("courses.view_course", "courses.manage_tags")) + _add_custom_role(enforcer, role_id="custom_reviewer", permissions=("courses.view_course",)) + earlier = timezone.now() - timedelta(days=1) + AuthzRoleDefinition.objects.user_defined().update(updated_at=earlier) + + _apply(enforcer, _without_permission("manage_tags"), drop_custom_role_permissions=True) + + assert AuthzRoleDefinition.objects.get(role_id="custom_designer").updated_at > earlier + assert AuthzRoleDefinition.objects.get(role_id="custom_reviewer").updated_at == earlier + @pytest.mark.django_db class TestApplyFailure: