From 3639c64174c260204d7d1d961e455133969a741e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20M=C3=A9ndez?= Date: Wed, 2 Dec 2026 16:27:11 -0600 Subject: [PATCH] feat: warn when a schema load hides a permission granted by a custom role Closes #673 --- CHANGELOG.rst | 5 + ...-permission-categories-and-permissions.rst | 1 + src/openedx_authz/engine/renderer.py | 51 ++++++++ .../management/commands/load_authz_schema.py | 22 ++++ src/openedx_authz/tests/schema/test_apply.py | 112 ++++++++++++++++++ .../schema/test_load_authz_schema_command.py | 27 +++++ 6 files changed, 218 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 92351ab5..0ada855d 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -30,6 +30,11 @@ Added the same deployment; a custom role left with no permissions keeps its assignments, and the report lists it. Releases that remove a permission must say so in their operator release notes and name this option. +* ``load_authz_schema`` now warns when it hides a permission, or its category, that custom roles + grant (ADR 0038). The change report and the log name each permission and the custom roles that + grant it, because the UI no longer shows the permission, so it can no longer be seen or edited + in those roles. The grants stay and keep working, and the load does not fail. A permission that + was already hidden is not reported again. * Added ``create_custom_role``, ``update_custom_role`` and ``remove_custom_role`` to the public API (ADR 0035). Each change updates the role definition, its grants and its policy rows in one transaction, under the same lock as schema deployments, and reaches every holder of the role diff --git a/docs/decisions/0038-hidden-permission-categories-and-permissions.rst b/docs/decisions/0038-hidden-permission-categories-and-permissions.rst index 6fb864d9..3941c59c 100644 --- a/docs/decisions/0038-hidden-permission-categories-and-permissions.rst +++ b/docs/decisions/0038-hidden-permission-categories-and-permissions.rst @@ -82,6 +82,7 @@ Consequences * The permissions of a hidden category can be hidden with one flag. * Permissions that must keep working but should not be offered, such as compatibility, internal or deprecated ones, can be kept for existing roles without appearing in the UI. * An administrator cannot see, and therefore cannot select, hidden permissions in a custom role, but roles that already grant them continue to work. +* A schema load that hides a permission, or its category, that custom roles grant logs a warning that names the permission and those roles. The load does not fail. * API clients that need hidden permissions cannot discover them through the role catalog. * The schema models need a migration to store the flag. diff --git a/src/openedx_authz/engine/renderer.py b/src/openedx_authz/engine/renderer.py index d8da7f26..be79e05d 100644 --- a/src/openedx_authz/engine/renderer.py +++ b/src/openedx_authz/engine/renderer.py @@ -121,6 +121,9 @@ class ChangePlan: unlinked_custom_grants: list[tuple[str, str, str]] = field(default_factory=list) # IDs of the custom roles that dropping the unlinked grants leaves with no permissions. emptied_custom_roles: list[str] = field(default_factory=list) + # (permission_id, custom role IDs) for each visible permission that this load hides while + # custom roles grant it. The grants stay (ADR 0038 §2), so the operator is only warned. + hidden_custom_grants: list[tuple[str, list[str]]] = field(default_factory=list) @property def unlinked_custom_rows(self) -> list[PolicyRow]: @@ -246,10 +249,12 @@ def plan(self, rendered: RenderedPolicy, schema: CompiledSchema | None = None) - definitions = self._diff_definitions(schema) if schema is not None else {} unlinked_custom_grants: list[tuple[str, str, str]] = [] emptied_custom_roles: list[str] = [] + hidden_custom_grants: list[tuple[str, list[str]]] = [] if schema is not None: unlinked = self._unlinked_custom_grants(schema) unlinked_custom_grants = self._sorted_grant_triples(unlinked) emptied_custom_roles = self._emptied_custom_roles(unlinked) + hidden_custom_grants = self._newly_hidden_custom_grants(schema) plan = ChangePlan( added_rows=added, @@ -259,6 +264,7 @@ def plan(self, rendered: RenderedPolicy, schema: CompiledSchema | None = None) - blocking_assignments=blocking, unlinked_custom_grants=unlinked_custom_grants, emptied_custom_roles=emptied_custom_roles, + hidden_custom_grants=hidden_custom_grants, **definitions, ) plan.unchanged = ( @@ -407,6 +413,7 @@ def apply( ) else: logger.info("Authz schema apply: policy rows unchanged; definitions synced.") + self._warn_hidden_custom_grants(plan.hidden_custom_grants) return ApplyResult( added=len(plan.added_rows), @@ -512,6 +519,50 @@ def _emptied_custom_roles(unlinked_grants: QuerySet) -> list[str]: .distinct() ) + @staticmethod + def _newly_hidden_custom_grants(schema: CompiledSchema) -> list[tuple[str, list[str]]]: + """Return the visible permissions that ``schema`` hides, with the custom roles that grant them. + + Runs before the definitions are synced, so the stored rows still hold the previous ``hidden`` + values. A permission already hidden before this load is not reported again. + """ + hidden_categories = { + category_id for category_id, compiled in schema.categories.items() if compiled.definition.hidden + } + hidden_ids = [ + permission_id + for permission_id, compiled in schema.permissions.items() + if compiled.definition.hidden or compiled.definition.category_id in hidden_categories + ] + if not hidden_ids: + return [] + newly_hidden = schema_models.AuthzPermissionDefinition.objects.visible().with_identifiers(hidden_ids) + grants = ( + schema_models.AuthzRolePermission.objects.user_defined() + .filter(permission__in=newly_hidden) + .select_related("role", "permission") + ) + roles_by_permission: dict[str, set[str]] = {} + for grant in grants: + roles_by_permission.setdefault(grant.permission.identifier, set()).add(grant.role.role_id) + return [(permission_id, sorted(roles)) for permission_id, roles in sorted(roles_by_permission.items())] + + @staticmethod + def _warn_hidden_custom_grants(hidden_custom_grants: list[tuple[str, list[str]]]) -> None: + """Log one warning per permission this load hid while custom roles still grant it. + + The catalog no longer lists such a permission, so nobody can see that these roles still + grant it. The load does not fail, so deployments are not blocked. + """ + for permission_id, role_ids in hidden_custom_grants: + logger.warning( + "Authz schema apply: permission %s is now hidden but is still granted by custom role(s): %s. " + "The grants keep working, but the UI no longer shows this permission, so it can no longer be " + "seen or edited in these roles.", + permission_id, + ", ".join(role_ids), + ) + @staticmethod def _unlinked_custom_grants_message(grants: list[tuple[str, str, str]]) -> str: """Explain why an apply stopped because custom roles still grant removed permissions.""" diff --git a/src/openedx_authz/management/commands/load_authz_schema.py b/src/openedx_authz/management/commands/load_authz_schema.py index 722f999d..cfc86b9a 100644 --- a/src/openedx_authz/management/commands/load_authz_schema.py +++ b/src/openedx_authz/management/commands/load_authz_schema.py @@ -210,6 +210,7 @@ def _report_plan(self, plan, *, applied: bool = False) -> None: self._report_definitions(plan) self._report_unlinked_custom_grants(plan, applied=applied) self._report_emptied_custom_roles(plan, applied=applied) + self._report_hidden_custom_grants(plan) self._report_blocking_assignments(plan, applied=applied) def _report_blocking_assignments(self, plan, *, applied: bool) -> None: @@ -268,6 +269,27 @@ def _report_emptied_custom_roles(self, plan, *, applied: bool) -> None: for role in plan.emptied_custom_roles: self._write_marked_line("!", f"{role} {verb} no permissions; its assignments stay", self.style.WARNING) + def _report_hidden_custom_grants(self, plan) -> None: + """Print the permissions this load hides that custom roles still grant (ADR 0038). + + The grants stay and keep working, but the role catalog no longer lists the permission, so + this report is the only place an operator sees that these custom roles still grant it. + """ + if not plan.hidden_custom_grants: + return + + self._write_section_header(f"Custom role grants of hidden permissions ({len(plan.hidden_custom_grants)})") + for permission_id, role_ids in plan.hidden_custom_grants: + self._write_marked_line( + "!", f"{permission_id} is still granted by {', '.join(role_ids)}", self.style.WARNING + ) + self.stdout.write( + self.style.WARNING( + "These grants keep working, but the UI no longer shows these permissions, so they can no " + "longer be seen or edited in these roles." + ) + ) + def _report_definitions(self, plan) -> None: """Print the definition-metadata changes as one compact, interleaved diff. diff --git a/src/openedx_authz/tests/schema/test_apply.py b/src/openedx_authz/tests/schema/test_apply.py index b34654c4..399f96f6 100644 --- a/src/openedx_authz/tests/schema/test_apply.py +++ b/src/openedx_authz/tests/schema/test_apply.py @@ -15,6 +15,7 @@ from __future__ import annotations +import logging from unittest import mock import pytest @@ -570,6 +571,117 @@ def _without_permission(permission_name: str) -> SchemaDocument: ) +def _hiding( + *, + hidden_permission: str | None = None, + hide_category: bool = False, + moved_permission: str | None = None, +) -> SchemaDocument: + """A schema whose ``course_editor`` role grants ``view_course`` and that hides some permissions. + + ``hidden_permission`` sets ``hidden`` on that permission, ``hide_category`` hides the shared + ``cat`` category, and ``moved_permission`` moves that permission into a new hidden category. + """ + permissions = [ + permission( + name=perm.name, + cat="internal" if perm.name == moved_permission else "cat", + hidden=perm.name == hidden_permission, + ) + for perm in PERMS + ] + return _doc( + roles=[role(rid="course_editor", scopes=("course-v1",), permissions=("courses.view_course",))], + permissions=permissions, + categories=[category("cat", hidden=hide_category), category("internal", hidden=True)], + ) + + +@pytest.mark.django_db +@pytest.mark.usefixtures("cache_invalidation") +class TestHiddenCustomRoleGrants: + """A load that hides a permission custom roles grant warns and keeps the grants (ADR 0038 §2).""" + + @staticmethod + def _seeded_enforcer() -> FakeEnforcer: + """An enforcer with two custom roles that grant ``manage_tags`` and one that does not.""" + enforcer = FakeEnforcer() + _apply(enforcer, _editor(("courses.view_course",))) + _add_custom_role(enforcer, role_id="custom_tagger", permissions=("courses.manage_tags",)) + _add_custom_role(enforcer, role_id="custom_designer", permissions=("courses.manage_tags",)) + _add_custom_role(enforcer, role_id="custom_viewer", permissions=("courses.view_course",)) + return enforcer + + @staticmethod + def _plan(enforcer: FakeEnforcer, document: SchemaDocument): + """Plan ``document`` against the stored state without writing.""" + schema = _compile(document) + return SchemaApplier(policy_store=PolicyStore(enforcer)).plan(PolicyRenderer().render(schema), schema) + + @pytest.mark.parametrize( + "document", + [ + pytest.param(_hiding(hidden_permission="manage_tags"), id="permission-hidden"), + pytest.param(_hiding(moved_permission="manage_tags"), id="moved-into-hidden-category"), + ], + ) + def test_plan_reports_the_custom_roles_that_grant_a_newly_hidden_permission(self, document): + """Only the custom roles that grant the hidden permission are reported, sorted.""" + enforcer = self._seeded_enforcer() + + plan = self._plan(enforcer, document) + + assert plan.hidden_custom_grants == [("courses.manage_tags", ["custom_designer", "custom_tagger"])] + + def test_hiding_the_category_reports_every_granted_permission_in_it(self): + """A hidden category hides each of its permissions, so each granted one is reported.""" + enforcer = self._seeded_enforcer() + + plan = self._plan(enforcer, _hiding(hide_category=True)) + + assert plan.hidden_custom_grants == [ + ("courses.manage_tags", ["custom_designer", "custom_tagger"]), + ("courses.view_course", ["custom_viewer"]), + ] + + def test_hiding_a_permission_no_custom_role_grants_reports_nothing(self): + """Only custom role grants are reported, since static role grants are declared in the schema itself.""" + enforcer = self._seeded_enforcer() + _apply(enforcer, _editor(("courses.view_course", "courses.export_course"))) + + plan = self._plan(enforcer, _hiding(hidden_permission="export_course")) + + assert AuthzRolePermission.objects.filter(permission__name="export_course").exists() + assert not plan.hidden_custom_grants + + def test_a_permission_hidden_by_an_earlier_load_is_not_reported_again(self): + """Only the load that hides the permission warns, so later deployments stay quiet.""" + enforcer = self._seeded_enforcer() + _apply(enforcer, _hiding(hidden_permission="manage_tags")) + + plan = self._plan(enforcer, _hiding(hidden_permission="manage_tags")) + + assert not plan.hidden_custom_grants + + def test_apply_warns_and_keeps_the_grants(self, caplog): + """The apply succeeds, logs the permission and its roles, and leaves the grants and ``p`` rows.""" + enforcer = self._seeded_enforcer() + policy_before = enforcer.get_policy() + + with caplog.at_level(logging.WARNING, logger="openedx_authz.engine.renderer"): + result = _apply(enforcer, _hiding(hidden_permission="manage_tags")) + + assert result.plan.hidden_custom_grants == [("courses.manage_tags", ["custom_designer", "custom_tagger"])] + assert ( + "permission courses.manage_tags is now hidden but is still granted by custom role(s): " + "custom_designer, custom_tagger. The grants keep working, but the UI no longer shows this " + "permission, so it can no longer be seen or edited in these roles." in caplog.text + ) + assert sorted(enforcer.get_policy()) == sorted(policy_before) + assert AuthzRolePermission.objects.user_defined().filter(permission__name="manage_tags").count() == 2 + assert AuthzPermissionDefinition.objects.get(name="manage_tags").hidden is True + + @pytest.mark.django_db @pytest.mark.usefixtures("cache_invalidation") class TestCustomRoles: diff --git a/src/openedx_authz/tests/schema/test_load_authz_schema_command.py b/src/openedx_authz/tests/schema/test_load_authz_schema_command.py index 2f028bcf..604d721f 100644 --- a/src/openedx_authz/tests/schema/test_load_authz_schema_command.py +++ b/src/openedx_authz/tests/schema/test_load_authz_schema_command.py @@ -195,6 +195,33 @@ def test_dry_run_reports_custom_roles_that_would_be_left_with_no_permissions(sel assert "Custom roles left with no permissions (1)" in output assert "! custom_designer would have no permissions; its assignments stay" in output + @pytest.mark.parametrize("args", [pytest.param(("--dry-run",), id="dry-run"), pytest.param((), id="apply")]) + def test_report_lists_custom_role_grants_of_hidden_permissions(self, args): + """Both modes name each newly hidden permission and the custom roles that still grant it.""" + plan = ChangePlan( + permissions=DefinitionDiff(updated=["courses.manage_tags"]), + hidden_custom_grants=[("courses.manage_tags", ["custom_designer", "custom_tagger"])], + ) + with mock.patch(PIPELINE_PATH) as pipeline_cls: + pipeline_cls.return_value.plan.return_value = plan + pipeline_cls.return_value.apply.return_value = ApplyResult(plan=plan) + output = _run(*args) + + assert "Custom role grants of hidden permissions (1)" in output + assert "! courses.manage_tags is still granted by custom_designer, custom_tagger" in output + assert "the UI no longer shows these permissions, so they can no longer be seen or edited" in output + + def test_report_omits_the_hidden_permissions_section_when_none_are_granted(self): + """A plan with no hidden custom role grants prints no such section.""" + plan = ChangePlan(permissions=DefinitionDiff(updated=["courses.manage_tags"])) + with mock.patch(PIPELINE_PATH) as pipeline_cls: + pipeline_cls.return_value.plan.return_value = plan + output = _run("--dry-run") + + assert "permission: courses.manage_tags" in output + assert "hidden permissions" not in output + assert "the UI no longer shows" not in output + def test_applied_report_lists_force_removed_assignments(self): """After a forced apply, the report says the assignments were removed rather than that they require force.""" plan = ChangePlan(blocking_assignments=[("role^course_editor", "user^alice")])