Skip to content
Draft
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
80 changes: 76 additions & 4 deletions src/openedx_authz/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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('<a href="{}?role_change_id={}">View assignment changes</a>', 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
94 changes: 86 additions & 8 deletions src/openedx_authz/api/custom_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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])
Expand All @@ -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


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


Expand All @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand Down
11 changes: 10 additions & 1 deletion src/openedx_authz/api/roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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,
)
)
)
Expand Down
40 changes: 39 additions & 1 deletion src/openedx_authz/engine/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]:
Expand Down
Loading
Loading