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: 7 additions & 1 deletion src/openedx_authz/engine/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]:
Expand Down
4 changes: 2 additions & 2 deletions src/openedx_authz/rest_api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
wgu-taylor-payne marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also enforce this limit at the python API level at create_custom_role and update_custom_role in api/custom_roles.py? what do you think?

scope_types = serializers.ListField(
child=serializers.ChoiceField(choices=ScopesTypeField.values()),
min_length=1,
Expand All @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, should we make this 500 a constant to avoid repeating it several times?

permissions = serializers.ListField(child=serializers.CharField(), required=False)

def validate(self, attrs: dict) -> dict:
Expand Down
4 changes: 2 additions & 2 deletions src/openedx_authz/rest_api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

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

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

Expand Down
14 changes: 14 additions & 0 deletions src/openedx_authz/tests/schema/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down