diff --git a/src/openedx_authz/admin.py b/src/openedx_authz/admin.py index ee23e1af5..30aa967e7 100644 --- a/src/openedx_authz/admin.py +++ b/src/openedx_authz/admin.py @@ -5,11 +5,15 @@ from casbin_adapter.models import CasbinRule from django import forms from django.contrib import admin +from django.db.models import OuterRef, Subquery +from django.db.models.functions import Substr +from django.urls import reverse from django.utils.html import format_html from openedx_authz.api.data import ContentLibraryData, CourseOverviewData -from openedx_authz.models import AuthzCourseAuthoringMigrationRun, ExtendedCasbinRule -from openedx_authz.models.core import RoleAssignmentAudit +from openedx_authz.data import AUTHZ_POLICY_ATTRIBUTES_SEPARATOR, ROLE_NAMESPACE +from openedx_authz.models import AuthzCourseAuthoringMigrationRun, AuthzRoleDefinition, ExtendedCasbinRule +from openedx_authz.models.core import RoleAssignmentAudit, RoleDefinitionAudit def pretty_json(value) -> str: @@ -124,9 +128,9 @@ class RoleAssignmentAuditAdmin(admin.ModelAdmin): list_display = ("operation", "display_subject", "display_role", "display_scope", "actor_id", "timestamp") list_filter = ("operation", ScopeTypeFilter) - search_fields = ("subject", "role", "scope") + search_fields = ("subject", "role", "scope", "role_change_id") date_hierarchy = "timestamp" - readonly_fields = ("operation", "subject", "role", "scope", "actor_id", "timestamp") + readonly_fields = ("operation", "subject", "role", "scope", "actor_id", "role_change_id", "timestamp") @admin.display(description="subject") def display_subject(self, obj): @@ -154,3 +158,71 @@ def has_change_permission(self, request, obj=None): def has_delete_permission(self, request, obj=None): """Audit records must not be deleted through the admin.""" return False + + +@admin.register(RoleDefinitionAudit) +class RoleDefinitionAuditAdmin(admin.ModelAdmin): + """Read-only admin for the custom role change log (ADR 0037).""" + + list_display = ("operation", "display_role", "role_display_name", "actor_id", "timestamp") + list_filter = ("operation", "role", "actor_id") + search_fields = ("role", "change_id") + date_hierarchy = "timestamp" + readonly_fields = ( + "operation", + "change_id", + "role", + "role_display_name", + "pretty_changes", + "actor_id", + "timestamp", + "assignment_changes", + ) + fields = readonly_fields + + def get_queryset(self, request): + """ + Add the display name of each record's role with one subquery. + + The subquery matches the role ID without its namespace. The audit has no foreign key to the + role, and a removed custom role keeps its row, so the name is still found after the role is + removed. + """ + role_id_start = len(f"{ROLE_NAMESPACE}{AUTHZ_POLICY_ATTRIBUTES_SEPARATOR}") + 1 + display_names = AuthzRoleDefinition.objects.filter(role_id=Substr(OuterRef("role"), role_id_start)).values( + "display_name" + )[:1] + return super().get_queryset(request).annotate(role_name=Subquery(display_names)) + + @admin.display(description="role") + def display_role(self, obj): + """Role ID without the namespace prefix.""" + return obj.role_display + + @admin.display(description="display name") + def role_display_name(self, obj): + """Return the display name of the role, which a removed custom role keeps.""" + return obj.role_name or "-" + + @admin.display(description="changes") + def pretty_changes(self, obj): + """Return formatted JSON for the changes field.""" + return pretty_json(obj.changes) + + @admin.display(description="assignment changes") + def assignment_changes(self, obj): + """Link to the assignment audit records this change caused, such as the removal of a custom role.""" + url = reverse("admin:openedx_authz_roleassignmentaudit_changelist") + return format_html('View assignment changes', url, obj.change_id) + + def has_add_permission(self, request): + """Audit records are created by the system only.""" + return False + + def has_change_permission(self, request, obj=None): + """Audit records must not be modified after creation.""" + return False + + def has_delete_permission(self, request, obj=None): + """Audit records must not be deleted through the admin.""" + return False diff --git a/src/openedx_authz/api/custom_roles.py b/src/openedx_authz/api/custom_roles.py index 5d248cbf1..c702adc35 100644 --- a/src/openedx_authz/api/custom_roles.py +++ b/src/openedx_authz/api/custom_roles.py @@ -5,16 +5,23 @@ transaction, under the same lock as schema deployments, and takes effect for every holder of the role as soon as the policy cache is invalidated. -This module only changes definitions. Who may call it, the REST contract and the audit trail of -role changes are decided elsewhere. +Every change also sends a ``ROLE_DEFINITION_*`` event once the transaction commits, which the audit +handler records (ADR 0037). Who may call this module and the REST contract are decided elsewhere. """ +import json import re import unicodedata -from collections.abc import Collection, Iterator, Sequence +import uuid +from collections.abc import Collection, Iterable, Iterator, Sequence from contextlib import contextmanager +from crum import get_current_user +from django.db import transaction from django.utils import timezone +from openedx_events.authz.data import RoleDefinitionData as RoleDefinitionEventData +from openedx_events.authz.signals import ROLE_DEFINITION_CREATED, ROLE_DEFINITION_DELETED, ROLE_DEFINITION_UPDATED +from openedx_events.tooling import OpenEdxPublicSignal from openedx_authz.api.data import RoleData from openedx_authz.api.exceptions import ( @@ -117,6 +124,7 @@ def create_custom_role( _validate_text("description", description) _validate_text("scope type", scope_type) display_name = _clean_display_name(display_name) + change = _RoleChange() with _writing_custom_roles() as policy_store: _check_display_name_is_free(display_name) resolved = _resolve_permissions(permissions, [scope_type]) @@ -128,6 +136,9 @@ def create_custom_role( definition_kind=DefinitionKind.USER_DEFINED.value, ) _add_grants(policy_store, role, resolved) + # .. event_implemented_name: ROLE_DEFINITION_CREATED + # .. event_type: org.openedx.authz.role_definition.created + change.send_on_commit(ROLE_DEFINITION_CREATED, role, _role_snapshot(role)) return role @@ -185,13 +196,25 @@ def update_custom_role( raise InvalidCustomRoleError("Give a description or permissions to change.") if description is not None: _validate_text("description", description) + change = _RoleChange() with _writing_custom_roles() as policy_store: role = _get_active_custom_role(role_id) + changes = {} + if description is not None and description != role.description: + changes["description"] = {"old": role.description, "new": description} if permissions is not None: - _replace_grants(policy_store, role, _resolve_permissions(permissions, role.scopes)) + added, removed = _replace_grants(policy_store, role, _resolve_permissions(permissions, role.scopes)) + if added: + changes["permissions_added"] = added + if removed: + changes["permissions_removed"] = removed if description is not None: role.description = description role.save(update_fields=["description", "updated_at"]) + # An edit that changes nothing is still recorded, with empty changes. + # .. event_implemented_name: ROLE_DEFINITION_UPDATED + # .. event_type: org.openedx.authz.role_definition.updated + change.send_on_commit(ROLE_DEFINITION_UPDATED, role, changes) return role @@ -210,16 +233,23 @@ def remove_custom_role(role_id: str, *, delete_assignments: bool = False) -> Non StaticRoleError: If the role is a static role. CustomRoleHasAssignmentsError: If the role has assignments and ``delete_assignments`` is false. """ + change = _RoleChange() with _writing_custom_roles() as policy_store: role = _get_active_custom_role(role_id) assignments = get_role_assignments(role=RoleData(external_key=role_id)) if assignments and not delete_assignments: raise CustomRoleHasAssignmentsError(role_id, len(assignments)) + snapshot = _role_snapshot(role) for assignment in assignments: - unassign_role_from_subject_in_scope(assignment.subject, assignment.roles[0], assignment.scope) + unassign_role_from_subject_in_scope( + assignment.subject, assignment.roles[0], assignment.scope, role_change_id=change.change_id + ) _remove_grants(policy_store, role, list(role.role_permissions.select_related("permission"))) role.removed_at = timezone.now() role.save(update_fields=["removed_at", "updated_at"]) + # .. event_implemented_name: ROLE_DEFINITION_DELETED + # .. event_type: org.openedx.authz.role_definition.deleted + change.send_on_commit(ROLE_DEFINITION_DELETED, role, snapshot) @contextmanager @@ -245,6 +275,48 @@ def _writing_custom_roles() -> Iterator[PolicyStore]: raise +class _RoleChange: + """One change to a custom role, identified before any write (ADR 0037). + + The change ID and the actor are taken when the change starts, so the role event and every + assignment event the change causes carry the same ``change_id``, whatever order the handlers + run in. + """ + + def __init__(self) -> None: + self.change_id = str(uuid.uuid4()) + self.actor_id = getattr(get_current_user(), "id", None) + + def send_on_commit(self, signal: OpenEdxPublicSignal, role: AuthzRoleDefinition, changes: dict) -> None: + """Send the role event once the transaction commits, so a rolled-back change sends nothing.""" + event = RoleDefinitionEventData( + change_id=self.change_id, + role=RoleData(external_key=role.role_id).namespaced_key, + changes=json.dumps(changes), + actor_id=self.actor_id, + ) + transaction.on_commit(lambda: signal.send_event(role_definition=event)) + + +def _role_snapshot(role: AuthzRoleDefinition) -> dict: + """Return the full role as recorded when it is created or deleted. + + The permissions include every grant the role holds, including hidden permissions it kept + (ADR 0038), so the record shows what the role actually granted. + """ + return { + "display_name": role.display_name, + "description": role.description, + "scope_types": list(role.scopes), + "permissions": _permission_ids(role.role_permissions.select_related("permission")), + } + + +def _permission_ids(grants: Iterable[AuthzRolePermission]) -> list[str]: + """Return the sorted, distinct permission IDs of the grants.""" + return sorted({grant.permission.identifier for grant in grants}) + + def _validate_text(field: str, value: object) -> None: """Reject a value that is not a string, so a missing field is reported instead of failing in the database.""" if not isinstance(value, str): @@ -352,11 +424,14 @@ def _resolve_permissions(permission_ids: Sequence[str], scope_types: Sequence[st def _replace_grants( policy_store: PolicyStore, role: AuthzRoleDefinition, permissions: Sequence[AuthzPermissionDefinition] -) -> None: +) -> tuple[list[str], list[str]]: """Make the role's visible grants match the given permissions, changing only what differs. Grants of hidden permissions are kept. Clients cannot see or send hidden permissions, so the new list never names them, and hiding must not change permission checks (ADR 0038). + + Returns: + tuple[list[str], list[str]]: The sorted IDs of the permissions added and removed. """ current = list( role.role_permissions.filter(permission__in=AuthzPermissionDefinition.objects.visible()).select_related( @@ -365,8 +440,11 @@ def _replace_grants( ) wanted = {permission.pk for permission in permissions} granted = {grant.permission_id for grant in current} - _remove_grants(policy_store, role, [grant for grant in current if grant.permission_id not in wanted]) - _add_grants(policy_store, role, [permission for permission in permissions if permission.pk not in granted]) + dropped = [grant for grant in current if grant.permission_id not in wanted] + new = [permission for permission in permissions if permission.pk not in granted] + _remove_grants(policy_store, role, dropped) + _add_grants(policy_store, role, new) + return sorted({permission.identifier for permission in new}), _permission_ids(dropped) def _add_grants( diff --git a/src/openedx_authz/api/roles.py b/src/openedx_authz/api/roles.py index 8c5d001a1..36bce3b3a 100644 --- a/src/openedx_authz/api/roles.py +++ b/src/openedx_authz/api/roles.py @@ -299,7 +299,13 @@ def batch_assign_role_to_subjects_in_scope(subjects: list[SubjectData], role: Ro assign_role_to_subject_in_scope(subject, role, scope) -def unassign_role_from_subject_in_scope(subject: SubjectData, role: RoleData, scope: ScopeData) -> bool: +def unassign_role_from_subject_in_scope( + subject: SubjectData, + role: RoleData, + scope: ScopeData, + *, + role_change_id: str | None = None, +) -> bool: """Unassign a role from a subject within a specific scope. This function removes a role assignment by deleting the corresponding grouping policy from the enforcer and @@ -310,6 +316,8 @@ def unassign_role_from_subject_in_scope(subject: SubjectData, role: RoleData, sc subject: The ID of the subject. role: The role to unassign. scope: The scope from which to unassign the role. + role_change_id: The ``change_id`` of the role definition change that removes this assignment, such as + the removal of a custom role (ADR 0037). Left empty for direct removals. Returns: bool: True if the role was unassigned successfully, False otherwise. @@ -330,6 +338,7 @@ def unassign_role_from_subject_in_scope(subject: SubjectData, role: RoleData, sc role=role.namespaced_key, scope=scope.namespaced_key, actor_id=getattr(get_current_user(), "id", None), + role_change_id=role_change_id, ) ) ) diff --git a/src/openedx_authz/engine/renderer.py b/src/openedx_authz/engine/renderer.py index d8da7f26c..864080eaf 100644 --- a/src/openedx_authz/engine/renderer.py +++ b/src/openedx_authz/engine/renderer.py @@ -44,15 +44,21 @@ from __future__ import annotations +import json import logging +import uuid +from collections import defaultdict from dataclasses import dataclass, field from crum import get_current_user from django.db import transaction from django.db.models import QuerySet from openedx_events.authz.data import RoleAssignmentData as RoleAssignmentEventData -from openedx_events.authz.signals import ROLE_ASSIGNMENT_DELETED +from openedx_events.authz.data import RoleDefinitionData as RoleDefinitionEventData +from openedx_events.authz.signals import ROLE_ASSIGNMENT_DELETED, ROLE_DEFINITION_UPDATED +from openedx_authz.data import AUTHZ_POLICY_ATTRIBUTES_SEPARATOR as SEP +from openedx_authz.data import ROLE_NAMESPACE from openedx_authz.engine.enforcer import AuthzEnforcer from openedx_authz.engine.policy import ActionGroupingRow, PolicyRow, PolicyStore, serialized_policy_update from openedx_authz.engine.schema.exceptions import SchemaApplyError @@ -533,6 +539,38 @@ def _drop_unlinked_custom_grants(self, policy_store: PolicyStore, schema: Compil 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() + events = self._dropped_grant_events(grants) + # Sent only if the apply commits, like the assignment removals above. + transaction.on_commit(lambda: self._emit_role_definition_updated(events)) + + @staticmethod + def _dropped_grant_events(grants: list) -> list[RoleDefinitionEventData]: + """Build one ``ROLE_DEFINITION_UPDATED`` payload per custom role that lost grants (ADR 0037). + + Each role gets its own ``change_id``, and its changes list the permissions it no longer + grants. A deployment has no user, so the actor is normally ``None``. + """ + dropped: dict[str, set[str]] = defaultdict(set) + for grant in grants: + dropped[grant.role.role_id].add(grant.permission.identifier) + actor_id = getattr(get_current_user(), "id", None) + return [ + RoleDefinitionEventData( + change_id=str(uuid.uuid4()), + role=f"{ROLE_NAMESPACE}{SEP}{role_id}", + changes=json.dumps({"permissions_removed": sorted(permissions)}), + actor_id=actor_id, + ) + for role_id, permissions in sorted(dropped.items()) + ] + + @staticmethod + def _emit_role_definition_updated(events: list[RoleDefinitionEventData]) -> None: + """Emit ``ROLE_DEFINITION_UPDATED`` for each custom role whose grants were dropped.""" + # .. event_implemented_name: ROLE_DEFINITION_UPDATED + # .. event_type: org.openedx.authz.role_definition.updated + for event in events: + ROLE_DEFINITION_UPDATED.send_event(role_definition=event) @staticmethod def _row_sort_key(row: PolicyRow) -> tuple[str, str, str, str]: diff --git a/src/openedx_authz/handlers.py b/src/openedx_authz/handlers.py index bab1c6ec0..c8962ac74 100644 --- a/src/openedx_authz/handlers.py +++ b/src/openedx_authz/handlers.py @@ -6,6 +6,7 @@ from __future__ import annotations +import json import logging from typing import Union @@ -14,13 +15,19 @@ from django.db import transaction from django.db.models.signals import post_delete, post_save from django.dispatch import receiver -from openedx_events.authz.signals import ROLE_ASSIGNMENT_CREATED, ROLE_ASSIGNMENT_DELETED +from openedx_events.authz.signals import ( + ROLE_ASSIGNMENT_CREATED, + ROLE_ASSIGNMENT_DELETED, + ROLE_DEFINITION_CREATED, + ROLE_DEFINITION_DELETED, + ROLE_DEFINITION_UPDATED, +) from waffle.models import Flag from openedx_authz.api.users import unassign_all_roles_from_user from openedx_authz.engine.utils import run_course_authoring_migration from openedx_authz.models.authz_migration import MigrationType, ScopeType -from openedx_authz.models.core import ExtendedCasbinRule, RoleAssignmentAudit +from openedx_authz.models.core import ExtendedCasbinRule, RoleAssignmentAudit, RoleDefinitionAudit from openedx_authz.models.scopes import ContentLibrary, ContentLibraryScope, CourseOverview, CourseScope from openedx_authz.models.subjects import UserSubject @@ -374,6 +381,8 @@ def create_audit_record_on_role_assignment_change(sender, role_assignment, **kwa role_assignment: RoleAssignmentEventData carrying the operation, subject, role, scope, and actor. **kwargs: Additional keyword arguments from the signal. """ + if not audit_records_enabled(): + return try: RoleAssignmentAudit.objects.create( operation=role_assignment.operation, @@ -381,6 +390,7 @@ def create_audit_record_on_role_assignment_change(sender, role_assignment, **kwa role=role_assignment.role, scope=role_assignment.scope, actor_id=role_assignment.actor_id, + role_change_id=role_assignment.role_change_id, timestamp=kwargs["metadata"].time, ) except Exception as exc: # pylint: disable=broad-exception-caught @@ -388,3 +398,52 @@ def create_audit_record_on_role_assignment_change(sender, role_assignment, **kwa "Error creating audit record for role assignment change: %s", exc, ) + + +def audit_records_enabled() -> bool: + """ + Return whether the audit handlers write records (``AUTHZ_AUDIT_RECORDS_ENABLED``, on by default). + + Operators who send the events to an event bus, Aspects or a SIEM can turn the database write + off. The events are still sent either way. + """ + return getattr(settings, "AUTHZ_AUDIT_RECORDS_ENABLED", True) + + +ROLE_DEFINITION_OPERATIONS = { + ROLE_DEFINITION_CREATED.event_type: RoleDefinitionAudit.OPERATIONS.created, + ROLE_DEFINITION_UPDATED.event_type: RoleDefinitionAudit.OPERATIONS.updated, + ROLE_DEFINITION_DELETED.event_type: RoleDefinitionAudit.OPERATIONS.deleted, +} + + +@receiver(ROLE_DEFINITION_CREATED) +@receiver(ROLE_DEFINITION_UPDATED) +@receiver(ROLE_DEFINITION_DELETED) +def create_audit_record_on_role_definition_change(sender, role_definition, **kwargs): # pylint: disable=unused-argument + """ + Create an audit record when a custom role is created, updated or deleted (ADR 0037). + + The event type gives the operation, so the payload does not carry it. + + Args: + sender: The sender of the signal. + role_definition: RoleDefinitionEventData carrying the change ID, role, changes and actor. + **kwargs: Additional keyword arguments from the signal, including ``signal`` and ``metadata``. + """ + if not audit_records_enabled(): + return + try: + RoleDefinitionAudit.objects.create( + operation=ROLE_DEFINITION_OPERATIONS[kwargs["signal"].event_type], + change_id=role_definition.change_id, + role=role_definition.role, + changes=json.loads(role_definition.changes), + actor_id=role_definition.actor_id, + timestamp=kwargs["metadata"].time, + ) + except Exception as exc: # pylint: disable=broad-exception-caught + logger.exception( + "Error creating audit record for role definition change: %s", + exc, + ) diff --git a/src/openedx_authz/migrations/0016_role_definition_audit.py b/src/openedx_authz/migrations/0016_role_definition_audit.py new file mode 100644 index 000000000..614940518 --- /dev/null +++ b/src/openedx_authz/migrations/0016_role_definition_audit.py @@ -0,0 +1,79 @@ +# Generated by Django 5.2.19 on 2026-12-03 21:31 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("openedx_authz", "0015_authzpermissiondependency"), + ] + + operations = [ + migrations.AddField( + model_name="roleassignmentaudit", + name="role_change_id", + field=models.UUIDField( + blank=True, + db_index=True, + help_text=( + "change_id of the role definition change that caused this assignment change, such as the " + "removal of a custom role. Null for direct assignments and removals." + ), + null=True, + ), + ), + migrations.CreateModel( + name="RoleDefinitionAudit", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ( + "operation", + models.CharField( + choices=[("created", "created"), ("updated", "updated"), ("deleted", "deleted")], max_length=20 + ), + ), + ( + "change_id", + models.UUIDField( + help_text=( + "Identifies this change. Assignment changes it caused carry the same value as " + "role_change_id." + ), + unique=True, + ), + ), + ( + "role", + models.CharField( + help_text="Namespaced key of the role (e.g. 'role^custom_course_designer').", max_length=255 + ), + ), + ( + "changes", + models.JSONField( + default=dict, + help_text=( + "The full role for created and deleted records, only the changed fields for updated ones." + ), + ), + ), + ( + "actor_id", + models.IntegerField( + blank=True, + help_text=( + "Database ID of the user who performed the operation. Null for system-initiated actions." + ), + null=True, + ), + ), + ("timestamp", models.DateTimeField()), + ], + options={ + "verbose_name": "Role Definition Audit", + "verbose_name_plural": "Role Definition Audits", + "ordering": ["-timestamp"], + "indexes": [models.Index(fields=["role"], name="role_def_audit_role_idx")], + }, + ), + ] diff --git a/src/openedx_authz/models/core.py b/src/openedx_authz/models/core.py index 9b4491da1..6e938db1f 100644 --- a/src/openedx_authz/models/core.py +++ b/src/openedx_authz/models/core.py @@ -370,6 +370,15 @@ class Operations(NamedTuple): blank=True, help_text="Database ID of the user who performed the operation. Null for system-initiated actions.", ) + role_change_id = models.UUIDField( + null=True, + blank=True, + db_index=True, + help_text=( + "change_id of the role definition change that caused this assignment change, such as the " + "removal of a custom role. Null for direct assignments and removals." + ), + ) timestamp = models.DateTimeField() class Meta: @@ -395,3 +404,58 @@ def role_display(self) -> str: def scope_display(self) -> str: """Scope key without the namespace prefix (e.g. ``lib:Org1:lib1`` for ``lib^lib:Org1:lib1``).""" return self.scope.split(AUTHZ_POLICY_ATTRIBUTES_SEPARATOR, 1)[-1] + + +class RoleDefinitionAudit(models.Model): + """Model to audit changes to custom role definitions (ADR 0037). + + .. no_pii: + + Each record describes one change to one role: its creation, an edit of its description or + permissions, its removal, or a deployment that dropped some of its grants. Like + ``RoleAssignmentAudit``, values are plain strings with no foreign keys, so records survive the + removal of the role. + """ + + class Operations(NamedTuple): + created: str = "created" + updated: str = "updated" + deleted: str = "deleted" + + OPERATIONS = Operations() + + operation = models.CharField( + max_length=20, + choices=[(op, op) for op in OPERATIONS], + ) + change_id = models.UUIDField( + unique=True, + help_text="Identifies this change. Assignment changes it caused carry the same value as role_change_id.", + ) + role = models.CharField( + max_length=255, + help_text="Namespaced key of the role (e.g. 'role^custom_course_designer').", + ) + changes = models.JSONField( + default=dict, + help_text="The full role for created and deleted records, only the changed fields for updated ones.", + ) + actor_id = models.IntegerField( + null=True, + blank=True, + help_text="Database ID of the user who performed the operation. Null for system-initiated actions.", + ) + timestamp = models.DateTimeField() + + class Meta: + verbose_name = "Role Definition Audit" + verbose_name_plural = "Role Definition Audits" + ordering = ["-timestamp"] + indexes = [ + models.Index(fields=["role"], name="role_def_audit_role_idx"), + ] + + @property + def role_display(self) -> str: + """Role ID without the namespace prefix (e.g. ``custom_designer`` for ``role^custom_designer``).""" + return self.role.split(AUTHZ_POLICY_ATTRIBUTES_SEPARATOR, 1)[-1] diff --git a/src/openedx_authz/settings/common.py b/src/openedx_authz/settings/common.py index c6cabc247..5fab7a334 100644 --- a/src/openedx_authz/settings/common.py +++ b/src/openedx_authz/settings/common.py @@ -59,3 +59,9 @@ def plugin_settings(settings): # This setting defines whether to enable automatic course migration. See ADR-0013 for more details. if not hasattr(settings, "ENABLE_AUTOMATIC_AUTHZ_COURSE_AUTHORING_MIGRATION"): settings.ENABLE_AUTOMATIC_AUTHZ_COURSE_AUTHORING_MIGRATION = False + + # Set default AUTHZ_AUDIT_RECORDS_ENABLED if not already set. + # This setting defines whether role assignment and role definition changes are written to the + # audit tables. The events are sent either way. See ADR-0012 and ADR-0037 for more details. + if not hasattr(settings, "AUTHZ_AUDIT_RECORDS_ENABLED"): + settings.AUTHZ_AUDIT_RECORDS_ENABLED = True diff --git a/src/openedx_authz/tests/api/test_custom_roles.py b/src/openedx_authz/tests/api/test_custom_roles.py index 5046aae6a..7190dc9ca 100644 --- a/src/openedx_authz/tests/api/test_custom_roles.py +++ b/src/openedx_authz/tests/api/test_custom_roles.py @@ -9,6 +9,7 @@ from unittest.mock import patch from casbin_adapter.models import CasbinRule +from crum import impersonate from ddt import data, ddt, unpack from django.contrib.auth import get_user_model from django.db.models import QuerySet @@ -31,12 +32,12 @@ InvalidCustomRoleError, StaticRoleError, ) -from openedx_authz.api.roles import assign_role_to_subject_in_scope +from openedx_authz.api.roles import assign_role_to_subject_in_scope, unassign_role_from_subject_in_scope from openedx_authz.constants import CUSTOM_ROLE_ID_MAX_LENGTH, DefinitionKind from openedx_authz.engine.enforcer import AuthzEnforcer from openedx_authz.engine.policy import PolicyRow, PolicyStore from openedx_authz.engine.schema.pipeline import SchemaPipeline -from openedx_authz.models.core import ExtendedCasbinRule +from openedx_authz.models.core import ExtendedCasbinRule, RoleAssignmentAudit, RoleDefinitionAudit from openedx_authz.models.engine import PolicyCacheControl from openedx_authz.models.schema import ( AuthzPermissionCategory, @@ -823,3 +824,189 @@ def test_deployment_keeps_the_role_its_grants_and_access(self): self.assertEqual(self.stored_policy_rows(role.role_id).count(), 2) self.assertTrue(self.is_allowed(VIEW_LIBRARY)) self.assertTrue(self.is_allowed(EDIT_LIBRARY_CONTENT)) + + +class TestCustomRoleAuditTrail(CustomRoleTestCase): + """Every custom role change leaves one RoleDefinitionAudit record once it commits (ADR 0037).""" + + def run_committed(self, operation, *args, **kwargs): + """Run a custom role operation and the callbacks its transaction registers on commit.""" + with self.captureOnCommitCallbacks(execute=True): + return operation(*args, **kwargs) + + def create_audited_role(self, permissions: Sequence[str] = (VIEW_LIBRARY,)) -> AuthzRoleDefinition: + """Create a library role with a description and committed records.""" + return self.run_committed(create_custom_role, "Designer", "Designs", LIBRARY_SCOPE_TYPE, permissions) + + @staticmethod + def record(operation: str) -> RoleDefinitionAudit: + """The only record with the given operation.""" + return RoleDefinitionAudit.objects.get(operation=operation) + + def test_create_records_the_full_role(self): + """A new role is recorded as created, with every field it was created with.""" + role = self.create_audited_role(permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + + record = RoleDefinitionAudit.objects.get() + self.assertEqual(record.operation, RoleDefinitionAudit.OPERATIONS.created) + self.assertEqual(record.role, make_role_key(role.role_id)) + self.assertEqual( + record.changes, + { + "display_name": "Designer", + "description": "Designs", + "scope_types": [LIBRARY_SCOPE_TYPE], + "permissions": sorted([VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]), + }, + ) + self.assertIsNone(record.actor_id) + + def test_actor_is_the_current_user(self): + """The record names the user who made the change.""" + actor = User.objects.get(username="alice") + + with impersonate(actor): + self.create_audited_role() + + self.assertEqual(RoleDefinitionAudit.objects.get().actor_id, actor.id) + + def test_description_edit_records_old_and_new_values(self): + """Only the description is recorded when only the description changes.""" + role = self.create_audited_role() + + self.run_committed(update_custom_role, role.role_id, description="Designs libraries") + + self.assertEqual( + self.record(RoleDefinitionAudit.OPERATIONS.updated).changes, + {"description": {"old": "Designs", "new": "Designs libraries"}}, + ) + + def test_permission_edit_records_what_was_added_and_removed(self): + """A permission edit lists the permissions added and removed, not the ones kept.""" + role = self.create_audited_role(permissions=[VIEW_LIBRARY, VIEW_LIBRARY_TEAM]) + + self.run_committed(update_custom_role, role.role_id, permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + + self.assertEqual( + self.record(RoleDefinitionAudit.OPERATIONS.updated).changes, + {"permissions_added": [EDIT_LIBRARY_CONTENT], "permissions_removed": [VIEW_LIBRARY_TEAM]}, + ) + + def test_empty_permission_lists_are_left_out(self): + """Adding a permission records no ``permissions_removed`` key.""" + role = self.create_audited_role() + + self.run_committed(update_custom_role, role.role_id, permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + + self.assertEqual( + self.record(RoleDefinitionAudit.OPERATIONS.updated).changes, {"permissions_added": [EDIT_LIBRARY_CONTENT]} + ) + + def test_edit_of_both_fields_is_one_record(self): + """One request is one record, even when it changes the description and the permissions.""" + role = self.create_audited_role() + + self.run_committed(update_custom_role, role.role_id, description="Edits", permissions=[EDIT_LIBRARY_CONTENT]) + + self.assertEqual( + self.record(RoleDefinitionAudit.OPERATIONS.updated).changes, + { + "description": {"old": "Designs", "new": "Edits"}, + "permissions_added": [EDIT_LIBRARY_CONTENT], + "permissions_removed": [VIEW_LIBRARY], + }, + ) + + def test_edit_that_changes_nothing_is_recorded_with_no_changes(self): + """An edit that sends the current values still leaves a record, with empty changes.""" + role = self.create_audited_role() + + self.run_committed(update_custom_role, role.role_id, description="Designs", permissions=[VIEW_LIBRARY]) + + self.assertEqual(self.record(RoleDefinitionAudit.OPERATIONS.updated).changes, {}) + + def test_remove_records_the_full_role(self): + """A removed role is recorded as deleted, with what it granted before the removal.""" + role = self.create_audited_role(permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + + self.run_committed(remove_custom_role, role.role_id) + + self.assertEqual( + self.record(RoleDefinitionAudit.OPERATIONS.deleted).changes, + { + "display_name": "Designer", + "description": "Designs", + "scope_types": [LIBRARY_SCOPE_TYPE], + "permissions": sorted([VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]), + }, + ) + + def test_removed_role_record_includes_kept_hidden_permissions(self): + """The deleted record lists a hidden permission the role still granted.""" + role = self.create_audited_role(permissions=[VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]) + self.hide_permission(EDIT_LIBRARY_CONTENT, whole_category=False) + + self.run_committed(remove_custom_role, role.role_id) + + self.assertEqual( + self.record(RoleDefinitionAudit.OPERATIONS.deleted).changes["permissions"], + sorted([VIEW_LIBRARY, EDIT_LIBRARY_CONTENT]), + ) + + def test_assignments_deleted_with_the_role_carry_its_change_id(self): + """Each assignment removed with the role links to the role's deleted record.""" + role = self.create_audited_role() + self.run_committed(self.assign, role) + + self.run_committed(remove_custom_role, role.role_id, delete_assignments=True) + + deleted = self.record(RoleDefinitionAudit.OPERATIONS.deleted) + assignment = RoleAssignmentAudit.objects.get(operation=RoleAssignmentAudit.OPERATIONS.deleted) + self.assertEqual(assignment.role_change_id, deleted.change_id) + self.assertEqual((assignment.subject, assignment.role), (ALICE, make_role_key(role.role_id))) + + def test_direct_assignment_changes_have_no_change_id(self): + """Assigning and unassigning a custom role directly is not linked to any role change.""" + role = self.create_audited_role() + self.run_committed(self.assign, role) + + self.run_committed( + unassign_role_from_subject_in_scope, + SubjectData(namespaced_key=ALICE), + RoleData(external_key=role.role_id), + ScopeData(namespaced_key=LIBRARY), + ) + + self.assertEqual(RoleAssignmentAudit.objects.count(), 2) + self.assertFalse(RoleAssignmentAudit.objects.filter(role_change_id__isnull=False).exists()) + + def test_each_change_has_its_own_change_id(self): + """Records of different changes to the same role never share a change ID.""" + role = self.create_audited_role() + self.run_committed(update_custom_role, role.role_id, description="Edits") + self.run_committed(remove_custom_role, role.role_id) + + change_ids = set(RoleDefinitionAudit.objects.values_list("change_id", flat=True)) + + self.assertEqual(len(change_ids), 3) + + def test_rejected_request_records_nothing(self): + """A request that fails validation leaves no record.""" + role = self.create_audited_role() + + with self.assertRaises(InvalidCustomRoleError): + self.run_committed(update_custom_role, role.role_id, permissions=[]) + with self.assertRaises(CustomRoleNameTakenError): + self.run_committed(create_custom_role, "Designer", "", LIBRARY_SCOPE_TYPE, [VIEW_LIBRARY]) + + self.assertEqual(RoleDefinitionAudit.objects.count(), 1) + + def test_rolled_back_change_records_nothing(self): + """A change whose transaction rolls back sends no event, so it leaves no record.""" + with ( + patch("openedx_authz.api.custom_roles._add_grants", side_effect=RuntimeError("simulated failure")), + self.assertRaises(RuntimeError), + ): + self.create_audited_role() + + self.assertFalse(RoleDefinitionAudit.objects.exists()) diff --git a/src/openedx_authz/tests/schema/test_apply.py b/src/openedx_authz/tests/schema/test_apply.py index b34654c47..6ffbf2ca1 100644 --- a/src/openedx_authz/tests/schema/test_apply.py +++ b/src/openedx_authz/tests/schema/test_apply.py @@ -28,6 +28,7 @@ from openedx_authz.engine.schema.compilation import SchemaCompiler from openedx_authz.engine.schema.exceptions import SchemaApplyError from openedx_authz.engine.schema.types import SchemaDocument +from openedx_authz.models.core import RoleDefinitionAudit from openedx_authz.models.engine import PolicyCacheControl from openedx_authz.models.schema import ( AuthzPermissionCategory, @@ -706,6 +707,40 @@ 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_opt_in_records_one_update_per_role_that_lost_grants(self, django_capture_on_commit_callbacks): + """Each custom role that loses grants gets its own system ``updated`` record (ADR 0037).""" + enforcer = self._seeded_enforcer(custom_permissions=("courses.view_course", "courses.manage_tags")) + _add_custom_role(enforcer, role_id="custom_tagger", permissions=("courses.manage_tags",)) + + with django_capture_on_commit_callbacks(execute=True): + _apply(enforcer, _without_permission("manage_tags"), drop_custom_role_permissions=True) + + records = list(RoleDefinitionAudit.objects.order_by("role")) + assert [record.role for record in records] == ["role^custom_designer", "role^custom_tagger"] + for record in records: + assert record.operation == RoleDefinitionAudit.OPERATIONS.updated + assert record.changes == {"permissions_removed": ["courses.manage_tags"]} + assert record.actor_id is None + assert records[0].change_id != records[1].change_id + + def test_stopped_apply_records_nothing(self, django_capture_on_commit_callbacks): + """Without the opt-in the apply stops before any write, so no role change is recorded.""" + enforcer = self._seeded_enforcer(custom_permissions=("courses.view_course", "courses.manage_tags")) + + with django_capture_on_commit_callbacks(execute=True), pytest.raises(SchemaApplyError): + _apply(enforcer, _without_permission("manage_tags")) + + assert not RoleDefinitionAudit.objects.exists() + + def test_apply_that_keeps_custom_grants_records_nothing(self, django_capture_on_commit_callbacks): + """A deployment that drops no custom role grant leaves no role change record.""" + enforcer = self._seeded_enforcer() + + with django_capture_on_commit_callbacks(execute=True): + _apply(enforcer, _without_permission("export_course")) + + assert not RoleDefinitionAudit.objects.exists() + @pytest.mark.django_db class TestApplyFailure: diff --git a/src/openedx_authz/tests/test_admin.py b/src/openedx_authz/tests/test_admin.py new file mode 100644 index 000000000..a177883a7 --- /dev/null +++ b/src/openedx_authz/tests/test_admin.py @@ -0,0 +1,83 @@ +"""Tests for the read-only admin of the custom role audit trail (ADR 0037).""" + +import uuid +from unittest.mock import patch + +from django.contrib.admin.sites import AdminSite +from django.test import RequestFactory, TestCase +from django.utils import timezone + +from openedx_authz.admin import RoleDefinitionAuditAdmin +from openedx_authz.constants import DefinitionKind +from openedx_authz.models.core import RoleDefinitionAudit +from openedx_authz.models.schema import AuthzRoleDefinition + + +class TestRoleDefinitionAuditAdmin(TestCase): + """The admin shows each record with the role's display name and links to the assignments it changed.""" + + def setUp(self): + super().setUp() + self.model_admin = RoleDefinitionAuditAdmin(RoleDefinitionAudit, AdminSite()) + self.request = RequestFactory().get("/") + + @staticmethod + def create_record(role: str, operation: str = RoleDefinitionAudit.OPERATIONS.deleted) -> RoleDefinitionAudit: + """Store one audit record for the role key.""" + return RoleDefinitionAudit.objects.create( + operation=operation, + change_id=uuid.uuid4(), + role=role, + changes={"permissions_removed": ["courses.view_course"]}, + timestamp=timezone.now(), + ) + + def listed(self, record: RoleDefinitionAudit) -> RoleDefinitionAudit: + """The record as the admin changelist loads it.""" + return self.model_admin.get_queryset(self.request).get(pk=record.pk) + + def test_shows_the_display_name_of_a_removed_role(self): + """A removed custom role keeps its row, so its record still shows its name.""" + AuthzRoleDefinition.objects.create( + role_id="custom_designer", + display_name="Designer", + scopes=["lib"], + definition_kind=DefinitionKind.USER_DEFINED.value, + removed_at=timezone.now(), + ) + record = self.create_record("role^custom_designer") + + self.assertEqual(self.model_admin.role_display_name(self.listed(record)), "Designer") + self.assertEqual(self.model_admin.display_role(record), "custom_designer") + + def test_role_without_a_definition_shows_a_dash(self): + """A record whose role has no definition row still renders.""" + record = self.create_record("role^custom_unknown") + + self.assertEqual(self.model_admin.role_display_name(self.listed(record)), "-") + + def test_changes_are_shown_as_formatted_json(self): + """The changes are shown indented, inside a ``pre`` block.""" + record = self.create_record("role^custom_designer") + + rendered = self.model_admin.pretty_changes(record) + + self.assertIn("
", rendered)
+ self.assertIn("permissions_removed", rendered)
+
+ def test_links_to_the_assignment_changes_of_the_same_change(self):
+ """The link filters the assignment audit by this record's change ID."""
+ record = self.create_record("role^custom_designer")
+
+ with patch("openedx_authz.admin.reverse", return_value="/admin/assignments/"):
+ link = self.model_admin.assignment_changes(record)
+
+ self.assertIn(f'href="/admin/assignments/?role_change_id={record.change_id}"', link)
+
+ def test_records_are_read_only(self):
+ """Nobody can add, change or delete records through the admin."""
+ record = self.create_record("role^custom_designer")
+
+ self.assertFalse(self.model_admin.has_add_permission(self.request))
+ self.assertFalse(self.model_admin.has_change_permission(self.request, record))
+ self.assertFalse(self.model_admin.has_delete_permission(self.request, record))
diff --git a/src/openedx_authz/tests/test_handlers.py b/src/openedx_authz/tests/test_handlers.py
index 0e448a9c4..757e7bfbb 100644
--- a/src/openedx_authz/tests/test_handlers.py
+++ b/src/openedx_authz/tests/test_handlers.py
@@ -7,6 +7,7 @@
waffle models are not imported in the test environment).
"""
+import json
from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -16,17 +17,19 @@
from django.test import TestCase, override_settings
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import LibraryLocatorV2
-from openedx_events.authz.data import RoleAssignmentData
+from openedx_events.authz.data import RoleAssignmentData, RoleDefinitionData
+from openedx_events.authz.signals import ROLE_DEFINITION_CREATED, ROLE_DEFINITION_DELETED, ROLE_DEFINITION_UPDATED
from openedx_authz.handlers import (
WAFFLE_OVERRIDE_FORCE_OFF,
WAFFLE_OVERRIDE_FORCE_ON,
create_audit_record_on_role_assignment_change,
+ create_audit_record_on_role_definition_change,
get_migration_type,
trigger_course_authoring_migration,
)
from openedx_authz.models.authz_migration import MigrationType, ScopeType
-from openedx_authz.models.core import ExtendedCasbinRule, RoleAssignmentAudit, Scope, Subject
+from openedx_authz.models.core import ExtendedCasbinRule, RoleAssignmentAudit, RoleDefinitionAudit, Scope, Subject
from openedx_authz.models.subjects import UserSubject
from openedx_authz.tests.stubs.models import (
ContentLibrary,
@@ -745,6 +748,9 @@ def test_unknown_override_choice_follows_global(self):
self.assertIsNone(get_migration_type(curr, prev, global_flag_enabled=True))
+ROLE_CHANGE_ID = "0b6c3d1e-6f1a-4d55-9a5e-2f0f3c9d7a10"
+
+
class TestCreateAuditRecordHandler(TestCase):
"""Confirm the audit record handler creates RoleAssignmentAudit entries correctly."""
@@ -826,3 +832,146 @@ def test_logs_exception_and_does_not_raise_when_creation_fails(self):
mock_logger.exception.assert_called_once()
self.assertIn("Error creating audit record", mock_logger.exception.call_args[0][0])
self.assertEqual(RoleAssignmentAudit.objects.count(), 0)
+
+ def test_stores_the_role_change_id(self):
+ """An assignment removed by a role change keeps that change's ID.
+
+ Expected result:
+ - The RoleAssignmentAudit record has the role_change_id of the event.
+ """
+ role_assignment = RoleAssignmentData(
+ operation=RoleAssignmentAudit.OPERATIONS.deleted,
+ subject="user^john_doe",
+ role="role^custom_designer",
+ scope="lib^org1:lib1",
+ role_change_id=ROLE_CHANGE_ID,
+ )
+
+ self._call_handler(role_assignment)
+
+ self.assertEqual(str(RoleAssignmentAudit.objects.get().role_change_id), ROLE_CHANGE_ID)
+
+ def test_direct_changes_have_no_role_change_id(self):
+ """An assignment change that no role change caused leaves role_change_id empty.
+
+ Expected result:
+ - The RoleAssignmentAudit record has no role_change_id.
+ """
+ role_assignment = RoleAssignmentData(
+ operation=RoleAssignmentAudit.OPERATIONS.deleted,
+ subject="user^john_doe",
+ role="role^library_admin",
+ scope="lib^org1:lib1",
+ )
+
+ self._call_handler(role_assignment)
+
+ self.assertIsNone(RoleAssignmentAudit.objects.get().role_change_id)
+
+ @override_settings(AUTHZ_AUDIT_RECORDS_ENABLED=False)
+ def test_setting_turns_the_handler_off(self):
+ """With AUTHZ_AUDIT_RECORDS_ENABLED off, no record is written.
+
+ Expected result:
+ - No RoleAssignmentAudit record exists.
+ """
+ role_assignment = RoleAssignmentData(
+ operation=RoleAssignmentAudit.OPERATIONS.created,
+ subject="user^john_doe",
+ role="role^library_admin",
+ scope="lib^org1:lib1",
+ )
+
+ self._call_handler(role_assignment)
+
+ self.assertFalse(RoleAssignmentAudit.objects.exists())
+
+
+@ddt
+class TestCreateRoleDefinitionAuditHandler(TestCase):
+ """Confirm the role definition audit handler creates RoleDefinitionAudit entries correctly (ADR 0037)."""
+
+ TIMESTAMP = datetime(2026, 12, 1, 12, 0, 0, tzinfo=timezone.utc)
+ CHANGES = {"description": {"old": "", "new": "Designs courses"}}
+
+ def _call_handler(self, signal, role_definition):
+ """Invoke the handler directly, as the signal would, with a mock metadata object."""
+ metadata = MagicMock()
+ metadata.time = self.TIMESTAMP
+ create_audit_record_on_role_definition_change(
+ sender=None,
+ role_definition=role_definition,
+ signal=signal,
+ metadata=metadata,
+ )
+
+ def _event_data(self, actor_id=None):
+ """Event data for a change to the custom designer role."""
+ return RoleDefinitionData(
+ change_id=ROLE_CHANGE_ID,
+ role="role^custom_designer",
+ changes=json.dumps(self.CHANGES),
+ actor_id=actor_id,
+ )
+
+ @data(
+ (ROLE_DEFINITION_CREATED, RoleDefinitionAudit.OPERATIONS.created),
+ (ROLE_DEFINITION_UPDATED, RoleDefinitionAudit.OPERATIONS.updated),
+ (ROLE_DEFINITION_DELETED, RoleDefinitionAudit.OPERATIONS.deleted),
+ )
+ @unpack
+ def test_event_type_gives_the_operation(self, signal, operation):
+ """Each event is recorded with its operation and every field of the payload.
+
+ Expected result:
+ - One RoleDefinitionAudit record with the operation of the event, the change ID, role,
+ parsed changes, actor and the event timestamp.
+ """
+ self._call_handler(signal, self._event_data(actor_id=7))
+
+ audit = RoleDefinitionAudit.objects.get()
+ self.assertEqual(audit.operation, operation)
+ self.assertEqual(str(audit.change_id), ROLE_CHANGE_ID)
+ self.assertEqual(audit.role, "role^custom_designer")
+ self.assertEqual(audit.changes, self.CHANGES)
+ self.assertEqual(audit.actor_id, 7)
+ self.assertEqual(audit.timestamp, self.TIMESTAMP)
+
+ def test_sending_the_event_writes_the_record(self):
+ """The handler is connected to the signal.
+
+ Expected result:
+ - Sending ROLE_DEFINITION_UPDATED writes one 'updated' record.
+ """
+ ROLE_DEFINITION_UPDATED.send_event(role_definition=self._event_data())
+
+ self.assertEqual(RoleDefinitionAudit.objects.get().operation, RoleDefinitionAudit.OPERATIONS.updated)
+
+ def test_logs_exception_and_does_not_raise_when_creation_fails(self):
+ """Handler logs the error without re-raising when RoleDefinitionAudit.create fails.
+
+ Expected result:
+ - logger.exception is called once with a message containing 'Error creating audit record'.
+ - No RoleDefinitionAudit record is created.
+ """
+ with (
+ patch("openedx_authz.handlers.RoleDefinitionAudit.objects.create") as mock_create,
+ patch("openedx_authz.handlers.logger") as mock_logger,
+ ):
+ mock_create.side_effect = Exception("DB error")
+ self._call_handler(ROLE_DEFINITION_CREATED, self._event_data())
+
+ mock_logger.exception.assert_called_once()
+ self.assertIn("Error creating audit record", mock_logger.exception.call_args[0][0])
+ self.assertEqual(RoleDefinitionAudit.objects.count(), 0)
+
+ @override_settings(AUTHZ_AUDIT_RECORDS_ENABLED=False)
+ def test_setting_turns_the_handler_off(self):
+ """With AUTHZ_AUDIT_RECORDS_ENABLED off, the event is still sent but no record is written.
+
+ Expected result:
+ - No RoleDefinitionAudit record exists.
+ """
+ ROLE_DEFINITION_CREATED.send_event(role_definition=self._event_data())
+
+ self.assertFalse(RoleDefinitionAudit.objects.exists())