diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 61361e7a2..05114f318 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -55,6 +55,17 @@ Added be loaded together. Validation rejects unknown dependencies, dependency cycles, dependencies that do not support the dependent permission's scopes, visible permissions that depend on hidden ones, and roles that grant a permission without all of its dependencies. +* Permission dependencies are stored in a new definition table, in migration + ``0015_authzpermissiondependency``, and rendered as one Casbin ``g2`` row each (ADR 0034). + ``load_authz_schema`` adds and removes these rows with the ``p`` rows, keeps existing rows that + match, leaves ``g2`` rows that no schema declares in place, and lists the ``g2`` changes in its + report. +* The content library permissions now use schema version ``1.1`` and declare the dependencies that + ``authz.policy`` held before the static schema, so new installations get the library ``g2`` rows + again. Installations that loaded ``authz.policy`` keep their rows unchanged. A schema file outside + this package that redefines a content library permission must remove that definition, or declare + the same ``depends_on`` in a ``1.1`` file; otherwise ``load_authz_schema`` reports a conflicting + permission definition. * Added an optional ``hidden`` flag to permission categories and permissions in the authorization schema. Hidden permissions, and the permissions of hidden categories, are left out of the role and permission catalog, including each role's permission list, but keep their role grants diff --git a/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst b/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst index e07781043..76771a618 100644 --- a/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst +++ b/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst @@ -4,7 +4,7 @@ Status ****** -**Draft** +**Accepted** Context ******* diff --git a/docs/references/authorization-schema.rst b/docs/references/authorization-schema.rst index 73c87d9e4..e075dee33 100644 --- a/docs/references/authorization-schema.rst +++ b/docs/references/authorization-schema.rst @@ -225,6 +225,10 @@ Validation rejects a schema when: The last rule applies to roles and role extensions in every file, whatever ``schema_version`` the file declares. If a ``1.1`` file adds ``depends_on`` to a permission, every role that grants that permission must also list its dependencies. +Only the file that defines a permission declares its dependencies. Another file that defines the same permission must declare the same ``depends_on``, which requires schema version ``1.1``. A ``1.0`` copy of a permission that declares dependencies is a conflicting definition. + +Each direct dependency is stored as a Casbin ``g2`` row, such as ``g2, act^content_libraries.edit_library_content, act^content_libraries.view_library``. Loading the schema adds, keeps and removes these rows the same way as the ``p`` rows of role grants: an existing ``g2`` row that matches a dependency is kept as is, and a ``g2`` row that no schema declares is left in place. A permission check that a role passes for a permission also passes for the permissions it depends on, so a role stored only in the database still works when it lacks a dependency. + Roles ***** diff --git a/docs/references/compiled-schema.yaml b/docs/references/compiled-schema.yaml index 0558b504e..ec37a9061 100644 --- a/docs/references/compiled-schema.yaml +++ b/docs/references/compiled-schema.yaml @@ -272,7 +272,8 @@ permissions: - lib icon: Plus hidden: false - depends_on: [] + depends_on: + - content_libraries.edit_library_collection content_libraries.delete_library: applet: content_libraries namespace: content_libraries @@ -284,7 +285,8 @@ permissions: - lib icon: Delete hidden: false - depends_on: [] + depends_on: + - content_libraries.edit_library_content content_libraries.delete_library_collection: applet: content_libraries namespace: content_libraries @@ -296,7 +298,8 @@ permissions: - lib icon: Delete hidden: false - depends_on: [] + depends_on: + - content_libraries.edit_library_collection content_libraries.edit_library_collection: applet: content_libraries namespace: content_libraries @@ -308,7 +311,8 @@ permissions: - lib icon: EditOutline hidden: false - depends_on: [] + depends_on: + - content_libraries.view_library content_libraries.edit_library_content: applet: content_libraries namespace: content_libraries @@ -320,7 +324,8 @@ permissions: - lib icon: EditOutline hidden: false - depends_on: [] + depends_on: + - content_libraries.view_library content_libraries.manage_library_tags: applet: content_libraries namespace: content_libraries @@ -332,7 +337,8 @@ permissions: - lib icon: Settings hidden: false - depends_on: [] + depends_on: + - content_libraries.edit_library_content content_libraries.manage_library_team: applet: content_libraries namespace: content_libraries @@ -344,7 +350,8 @@ permissions: - lib icon: Settings hidden: false - depends_on: [] + depends_on: + - content_libraries.view_library_team content_libraries.publish_library_content: applet: content_libraries namespace: content_libraries @@ -356,7 +363,9 @@ permissions: - lib icon: DownloadDone hidden: false - depends_on: [] + depends_on: + - content_libraries.edit_library_content + - content_libraries.view_library content_libraries.reuse_library_content: applet: content_libraries namespace: content_libraries @@ -368,7 +377,8 @@ permissions: - lib icon: SpinnerIcon hidden: false - depends_on: [] + depends_on: + - content_libraries.view_library content_libraries.view_library: applet: content_libraries namespace: content_libraries diff --git a/src/openedx_authz/applets/content_libraries/schema/permissions.yaml b/src/openedx_authz/applets/content_libraries/schema/permissions.yaml index a1c809718..03cf5d2a5 100644 --- a/src/openedx_authz/applets/content_libraries/schema/permissions.yaml +++ b/src/openedx_authz/applets/content_libraries/schema/permissions.yaml @@ -1,4 +1,4 @@ -schema_version: "1.0" +schema_version: "1.1" priority: 100 # Content library permission and category definitions for the @@ -41,6 +41,8 @@ permissions: scopes: - lib icon: Settings + depends_on: + - content_libraries.edit_library_content - namespace: content_libraries name: delete_library display_name: Delete @@ -49,6 +51,8 @@ permissions: scopes: - lib icon: Delete + depends_on: + - content_libraries.edit_library_content - namespace: content_libraries name: edit_library_content display_name: Edit @@ -57,6 +61,8 @@ permissions: scopes: - lib icon: EditOutline + depends_on: + - content_libraries.view_library - namespace: content_libraries name: publish_library_content display_name: Publish @@ -65,6 +71,9 @@ permissions: scopes: - lib icon: DownloadDone + depends_on: + - content_libraries.edit_library_content + - content_libraries.view_library - namespace: content_libraries name: reuse_library_content display_name: Reuse @@ -73,6 +82,8 @@ permissions: scopes: - lib icon: SpinnerIcon + depends_on: + - content_libraries.view_library - namespace: content_libraries name: view_library_team display_name: View @@ -89,6 +100,8 @@ permissions: scopes: - lib icon: Settings + depends_on: + - content_libraries.view_library_team - namespace: content_libraries name: create_library_collection display_name: Create @@ -97,6 +110,8 @@ permissions: scopes: - lib icon: Plus + depends_on: + - content_libraries.edit_library_collection - namespace: content_libraries name: edit_library_collection display_name: Edit @@ -105,6 +120,8 @@ permissions: scopes: - lib icon: EditOutline + depends_on: + - content_libraries.view_library - namespace: content_libraries name: delete_library_collection display_name: Delete @@ -113,3 +130,5 @@ permissions: scopes: - lib icon: Delete + depends_on: + - content_libraries.edit_library_collection diff --git a/src/openedx_authz/engine/policy.py b/src/openedx_authz/engine/policy.py index 78360d385..3f0f08fa2 100644 --- a/src/openedx_authz/engine/policy.py +++ b/src/openedx_authz/engine/policy.py @@ -49,7 +49,14 @@ from openedx_authz.engine.enforcer import AuthzEnforcer from openedx_authz.models.engine import PolicyCacheControl -__all__ = ["PolicyRow", "GroupingRow", "PolicyStore", "policy_write_lock", "serialized_policy_update"] +__all__ = [ + "PolicyRow", + "GroupingRow", + "ActionGroupingRow", + "PolicyStore", + "policy_write_lock", + "serialized_policy_update", +] @dataclass(frozen=True) @@ -142,6 +149,38 @@ def from_policy(cls, values: list[str]) -> "GroupingRow": return cls(subject, role, scope) +@dataclass(frozen=True) +class ActionGroupingRow: + """A single Casbin ``g2`` row: an action that implies another (ADR 0034 §4). + + Fields follow the ``g2`` shape: ``[action, implied_action]``, both in the internal ``act^`` + form. A permission dependency renders as one row whose ``action`` is the dependent + permission and whose ``implied_action`` is the permission it depends on. + """ + + PTYPE: ClassVar[str] = "g2" + + action: str + implied_action: str + + def as_policy(self) -> list[str]: + """Return the enforcer arg form: ``[action, implied_action]``.""" + return [self.action, self.implied_action] + + @classmethod + def from_policy(cls, values: list[str]) -> "ActionGroupingRow": + """Build from a stored ``g2`` row (``[action, implied_action]``).""" + return cls(values[0], values[1]) + + @classmethod + def from_dependency(cls, permission_id: str, depends_on_id: str) -> "ActionGroupingRow": + """Build the ``g2`` row for one direct dependency, applying the same ``act^`` form as ``p`` rows.""" + return cls( + action=f"{ACTION_NAMESPACE}{SEP}{permission_id}", + implied_action=f"{ACTION_NAMESPACE}{SEP}{depends_on_id}", + ) + + class PolicyStore: """Casbin-facing facade exposing only the operations the schema pipeline needs. @@ -205,6 +244,19 @@ def remove_grouping_row(self, row: GroupingRow) -> bool: """ return self._resolved_enforcer.remove_grouping_policy(*row.as_policy()) + def get_action_grouping_rows(self) -> list[ActionGroupingRow]: + """Return every stored ``g2`` row as an :class:`ActionGroupingRow`.""" + rows = self._resolved_enforcer.get_named_grouping_policy(ActionGroupingRow.PTYPE) + return [ActionGroupingRow.from_policy(row) for row in rows] + + def add_action_grouping_row(self, row: ActionGroupingRow) -> bool: + """Add one ``g2`` row. Returns the enforcer's add result (True if added).""" + return self._resolved_enforcer.add_named_grouping_policy(ActionGroupingRow.PTYPE, *row.as_policy()) + + def remove_action_grouping_row(self, row: ActionGroupingRow) -> bool: + """Remove one ``g2`` row. Returns the enforcer's remove result (True if removed).""" + return self._resolved_enforcer.remove_named_grouping_policy(ActionGroupingRow.PTYPE, *row.as_policy()) + def reload(self) -> None: """Reload the enforcer's in-memory model from the database (ADR 0018 §8). diff --git a/src/openedx_authz/engine/renderer.py b/src/openedx_authz/engine/renderer.py index 6c07982a2..d8da7f26c 100644 --- a/src/openedx_authz/engine/renderer.py +++ b/src/openedx_authz/engine/renderer.py @@ -3,11 +3,12 @@ This is the only Casbin/Django-aware part of the schema pipeline. It implements the ``render`` and ``apply`` lifecycle steps: -* ``render`` builds the Casbin ``p`` rows for a :class:`CompiledSchema` in - memory, without touching the database. +* ``render`` builds the Casbin ``p`` rows and the ``g2`` permission-dependency + rows (ADR 0034 §4) for a :class:`CompiledSchema` in memory, without touching + the database. * ``apply`` persists the rows in a single transaction, while preserving data owned by other services (ADR 0018 §3): dynamic roles, user assignments, and - legacy ``g2`` action-inheritance rows. + ``g2`` rows that no schema declares. Key semantics: * Idempotent (ADR 0018 §2): re-applying identical definitions changes @@ -31,9 +32,10 @@ The definition/source model (ADR 0018 §3, ADR 0025) is the ownership record that makes precise pruning safe, and it is consulted rather than assumed: -removal candidates are intersected with the stored role-permission grants (see -:meth:`SchemaApplier._managed_rows`), so unmanaged ``p`` rows, dynamic roles, -user assignments, and legacy ``g2`` action inheritance are all preserved. +removal candidates are intersected with the stored role-permission grants and +permission dependencies (see :meth:`SchemaApplier._managed_rows` and +:meth:`SchemaApplier._managed_action_rows`), so unmanaged ``p`` and ``g2`` rows, +dynamic roles, and user assignments are all preserved. ``render`` is pure in behavior — it touches no database and holds no Casbin state. ``plan``/``apply`` resolve the enforcer only when called (not at import), @@ -52,7 +54,7 @@ from openedx_events.authz.signals import ROLE_ASSIGNMENT_DELETED from openedx_authz.engine.enforcer import AuthzEnforcer -from openedx_authz.engine.policy import PolicyRow, PolicyStore, serialized_policy_update +from openedx_authz.engine.policy import ActionGroupingRow, PolicyRow, PolicyStore, serialized_policy_update from openedx_authz.engine.schema.exceptions import SchemaApplyError from openedx_authz.engine.schema.types import CompiledSchema, RoleDefinition from openedx_authz.models import schema as schema_models @@ -63,9 +65,11 @@ @dataclass class RenderedPolicy: - """The full set of ``p`` rows for a compiled schema (no DB access).""" + """The full set of ``p`` and ``g2`` rows for a compiled schema (no DB access).""" rows: list[PolicyRow] = field(default_factory=list) + # One ``g2`` row per direct permission dependency (ADR 0034 §4). + action_rows: list[ActionGroupingRow] = field(default_factory=list) @dataclass @@ -100,6 +104,8 @@ class ChangePlan: added_rows: list[PolicyRow] = field(default_factory=list) removed_rows: list[PolicyRow] = field(default_factory=list) + added_action_rows: list[ActionGroupingRow] = field(default_factory=list) + removed_action_rows: list[ActionGroupingRow] = field(default_factory=list) unchanged: bool = False # (role_subject, assignment_subject) pairs: roles being removed that still # have user assignments; block removal unless force is set. @@ -109,6 +115,7 @@ class ChangePlan: permissions: DefinitionDiff = field(default_factory=DefinitionDiff) roles: DefinitionDiff = field(default_factory=DefinitionDiff) grants: DefinitionDiff = field(default_factory=DefinitionDiff) + dependencies: DefinitionDiff = field(default_factory=DefinitionDiff) # (role_id, permission_id, scope) grants of custom roles whose permission the schema no longer # declares (ADR 0035 §5); apply stops unless the operator opts in to dropping them. unlinked_custom_grants: list[tuple[str, str, str]] = field(default_factory=list) @@ -130,6 +137,7 @@ def definition_diffs(self) -> list[tuple[str, DefinitionDiff]]: ("permission", self.permissions), ("role", self.roles), ("role-permission", self.grants), + ("permission dependency", self.dependencies), ] @property @@ -144,6 +152,8 @@ class ApplyResult: added: int = 0 removed: int = 0 + added_action_rows: int = 0 + removed_action_rows: int = 0 unchanged: bool = False # The change plan that was applied, so callers can report the same detailed # policy-row and definition breakdown they would print for a dry run. @@ -151,13 +161,12 @@ class ApplyResult: class PolicyRenderer: - """Turns a :class:`CompiledSchema` into Casbin ``p`` rows in memory.""" + """Turns a :class:`CompiledSchema` into Casbin ``p`` and ``g2`` rows in memory.""" def render(self, schema: CompiledSchema) -> RenderedPolicy: - """Produce one ``p`` row per (role, permission, supported scope). + """Produce one ``p`` row per (role, permission, supported scope) and one ``g2`` row per direct dependency. - Emits definition (``p``) rows only — never ``g`` (assignments) or ``g2`` - (action inheritance). Applies the internal Casbin namespacing here. + Never emits ``g`` (assignment) rows. Applies the internal Casbin namespacing here. Performs no database access. Output order is deterministic. """ rows: list[PolicyRow] = [] @@ -166,7 +175,20 @@ def render(self, schema: CompiledSchema) -> RenderedPolicy: for scope in sorted(role.scopes): for permission in sorted(role.permissions): rows.append(PolicyRow.from_grant(role.id, permission, scope)) - return RenderedPolicy(rows=rows) + action_rows = [ + ActionGroupingRow.from_dependency(permission_id, depends_on_id) + for permission_id, depends_on_id in self.dependency_pairs(schema) + ] + return RenderedPolicy(rows=rows, action_rows=action_rows) + + @staticmethod + def dependency_pairs(schema: CompiledSchema) -> list[tuple[str, str]]: + """Return every ``(permission_id, depends_on_id)`` direct dependency, sorted.""" + return sorted( + (permission_id, depends_on_id) + for permission_id, compiled in schema.permissions.items() + for depends_on_id in compiled.definition.depends_on + ) class SchemaApplier: @@ -207,6 +229,15 @@ def plan(self, rendered: RenderedPolicy, schema: CompiledSchema | None = None) - # ownership boundary of ADR 0018 §3 real rather than aspirational. removed = sorted((stored_set & managed_set) - rendered_set, key=self._row_sort_key) + # ``g2`` rows follow the same ownership rule (ADR 0034 §5): a stored row that matches a + # rendered one is adopted, and only rows backed by a stored dependency are removed. + rendered_action_set = set(rendered.action_rows) + stored_action_set = set(policy_store.get_action_grouping_rows()) + added_action_rows = sorted(rendered_action_set - stored_action_set, key=self._action_row_sort_key) + removed_action_rows = sorted( + (stored_action_set & self._managed_action_rows()) - rendered_action_set, key=self._action_row_sort_key + ) + rendered_subjects = {row.subject for row in rendered_set} removed_subjects = {row.subject for row in removed} - rendered_subjects @@ -223,12 +254,21 @@ def plan(self, rendered: RenderedPolicy, schema: CompiledSchema | None = None) - plan = ChangePlan( added_rows=added, removed_rows=removed, + added_action_rows=added_action_rows, + removed_action_rows=removed_action_rows, blocking_assignments=blocking, unlinked_custom_grants=unlinked_custom_grants, emptied_custom_roles=emptied_custom_roles, **definitions, ) - plan.unchanged = not added and not removed and plan.definitions_unchanged and not unlinked_custom_grants + plan.unchanged = ( + not added + and not removed + and not added_action_rows + and not removed_action_rows + and plan.definitions_unchanged + and not unlinked_custom_grants + ) return plan def apply( @@ -244,7 +284,8 @@ def apply( Adds rendered rows not already present, removes stale schema-owned rows no longer rendered, prunes definition/source records the compiled schema no longer contains, and invalidates the policy cache so the enforcer - reloads. Preserves dynamic roles, user assignments, and ``g2`` rows. + reloads. Adds and removes the ``g2`` rows of permission dependencies the same way. + Preserves dynamic roles, user assignments, and ``g2`` rows that no schema declares. Custom roles and their grants are never created, updated or removed, except for the grants of a permission the schema no longer declares (ADR 0035 §5). @@ -307,6 +348,10 @@ def apply( policy_store.add_policy_row(row) for row in plan.removed_rows: policy_store.remove_policy_row(row) + for action_row in plan.added_action_rows: + policy_store.add_action_grouping_row(action_row) + for action_row in plan.removed_action_rows: + policy_store.remove_action_grouping_row(action_row) if plan.unlinked_custom_grants: self._drop_unlinked_custom_grants(policy_store, schema) removed_assignments: list[tuple[str, str, str]] = [] @@ -314,7 +359,13 @@ def apply( removed_assignments = self._remove_assignments(policy_store, plan.blocking_assignments) self._store_sources(schema) - changed = bool(plan.added_rows or plan.removed_rows or plan.unlinked_custom_grants) + changed = bool( + plan.added_rows + or plan.removed_rows + or plan.added_action_rows + or plan.removed_action_rows + or plan.unlinked_custom_grants + ) if changed: # Bump the cache version *inside* the transaction so it commits # atomically with the p-row writes. If it ran after the block @@ -346,11 +397,13 @@ def apply( raise removed_count = len(plan.removed_rows) + len(plan.unlinked_custom_rows) - if plan.added_rows or removed_count: + if plan.added_rows or removed_count or plan.added_action_rows or plan.removed_action_rows: logger.info( - "Authz schema apply: added %d p row(s), removed %d p row(s).", + "Authz schema apply: added %d p row(s), removed %d p row(s), added %d g2 row(s), removed %d g2 row(s).", len(plan.added_rows), removed_count, + len(plan.added_action_rows), + len(plan.removed_action_rows), ) else: logger.info("Authz schema apply: policy rows unchanged; definitions synced.") @@ -358,6 +411,8 @@ def apply( return ApplyResult( added=len(plan.added_rows), removed=removed_count, + added_action_rows=len(plan.added_action_rows), + removed_action_rows=len(plan.removed_action_rows), unchanged=plan.unchanged, plan=plan, ) @@ -483,6 +538,10 @@ def _drop_unlinked_custom_grants(self, policy_store: PolicyStore, schema: Compil def _row_sort_key(row: PolicyRow) -> tuple[str, str, str, str]: return (row.subject, row.action, row.scope, row.effect) + @staticmethod + def _action_row_sort_key(row: ActionGroupingRow) -> tuple[str, str]: + return (row.action, row.implied_action) + def _diff_definitions(self, schema: CompiledSchema) -> dict[str, DefinitionDiff]: """Diff the compiled definitions against the stored ones (ADR 0018 §6). @@ -537,8 +596,25 @@ def _diff_definitions(self, schema: CompiledSchema) -> dict[str, DefinitionDiff] }, lambda _compiled, _stored: True, ), + "dependencies": self._diff_kind( + { + self._dependency_key(permission_id, depends_on_id): None + for permission_id, depends_on_id in PolicyRenderer.dependency_pairs(schema) + }, + { + self._dependency_key(dependency.permission.identifier, dependency.depends_on.identifier): None + for dependency in schema_models.AuthzPermissionDependency.objects.select_related( + "permission", "depends_on" + ) + }, + lambda _compiled, _stored: True, + ), } + @staticmethod + def _dependency_key(permission_id: str, depends_on_id: str) -> str: + return f"{permission_id} -> {depends_on_id}" + @staticmethod def _compiled_grants(schema: CompiledSchema): """Yield every ``(role_id, permission_id, scope)`` the schema grants.""" @@ -586,6 +662,20 @@ def _managed_rows() -> set[PolicyRow]: for grant in schema_models.AuthzRolePermission.objects.static().select_related("role", "permission") } + @staticmethod + def _managed_action_rows() -> set[ActionGroupingRow]: + """Return the ``g2`` rows the loader previously recorded as schema-owned (ADR 0034 §5). + + Each stored permission dependency corresponds to one rendered ``g2`` row. A ``g2`` row + outside this set, such as one loaded from ``authz.policy`` before any dependency was + stored, is not removed. Empty on the first deployment that stores dependencies, so + existing rows are adopted before anything can be pruned. + """ + return { + ActionGroupingRow.from_dependency(dependency.permission.identifier, dependency.depends_on.identifier) + for dependency in schema_models.AuthzPermissionDependency.objects.select_related("permission", "depends_on") + } + def _store_sources(self, schema: CompiledSchema) -> None: """Persist compiled definitions and their sources (ADR 0025). @@ -660,6 +750,18 @@ def source_obj(record): permission=obj, source=source_obj(record), defaults={"origin_kind": schema_models.OriginKind.BASE} ) + # Permission dependencies (one per rendered ``g2`` row). Track the ones the schema still + # declares so stale dependencies can be pruned below. + live_dependency_ids: set[int] = set() + for permission_id, depends_on_id in PolicyRenderer.dependency_pairs(schema): + permission_obj, depends_on_obj = permission_objs.get(permission_id), permission_objs.get(depends_on_id) + if permission_obj is None or depends_on_obj is None: + continue # validated away in practice; skip defensively + dependency, _ = schema_models.AuthzPermissionDependency.objects.get_or_create( + permission=permission_obj, depends_on=depends_on_obj + ) + live_dependency_ids.add(dependency.pk) + # Roles. role_objs: dict[str, object] = {} for rid, compiled in schema.roles.items(): @@ -703,7 +805,7 @@ def source_obj(record): defaults={"origin_kind": rel.origin_kind, "priority": rel.priority}, ) - self._prune_definitions(schema, live_grant_ids) + self._prune_definitions(schema, live_grant_ids, live_dependency_ids) logger.info( "Authz schema apply: persisted %d role(s), %d permission(s), %d category(ies).", @@ -713,20 +815,21 @@ def source_obj(record): ) @staticmethod - def _prune_definitions(schema: CompiledSchema, live_grant_ids: set[int]) -> None: + def _prune_definitions(schema: CompiledSchema, live_grant_ids: set[int], live_dependency_ids: set[int]) -> None: """Delete definition/source rows the compiled schema no longer contains. - Removes stale role-permission grants, roles, permissions, and categories - so the definition tables match the compiled schema (ADR 0018 §2). Source + Removes stale role-permission grants, permission dependencies, roles, permissions, and + categories so the definition tables match the compiled schema (ADR 0018 §2). Source link rows and per-source records cascade via their foreign keys; the shared :class:`AuthzSchemaSource` rows are left in place because they may still back other definitions and carry no access on their own. - Ordering matters: grants first (they reference roles and permissions), + Ordering matters: grants and dependencies first (they reference roles and permissions), then roles and permissions, then categories. """ # Stale role-permission grants: any grant not re-created this run. schema_models.AuthzRolePermission.objects.static().exclude(pk__in=live_grant_ids).delete() + schema_models.AuthzPermissionDependency.objects.exclude(pk__in=live_dependency_ids).delete() live_role_ids = {compiled.definition.id for compiled in schema.roles.values()} schema_models.AuthzRoleDefinition.objects.static().exclude(role_id__in=live_role_ids).delete() diff --git a/src/openedx_authz/management/commands/load_authz_schema.py b/src/openedx_authz/management/commands/load_authz_schema.py index 1394026d4..722f999df 100644 --- a/src/openedx_authz/management/commands/load_authz_schema.py +++ b/src/openedx_authz/management/commands/load_authz_schema.py @@ -114,7 +114,9 @@ def _apply_summary(self, result) -> str: change on its own — a metadata-only edit writes 0 policy rows but is still a real change the operator should see reflected here. """ - summary = f"Authz schema applied: {result.added} Casbin policy row(s) added, {result.removed} removed" + added = result.added + result.added_action_rows + removed = result.removed + result.removed_action_rows + summary = f"Authz schema applied: {added} Casbin policy row(s) added, {removed} removed" plan = result.plan if plan is not None and not plan.definitions_unchanged: @@ -195,10 +197,12 @@ def _report_plan(self, plan, *, applied: bool = False) -> None: self.stdout.write("\nChanges applied:" if applied else "\nChanges to apply:") removed_rows = plan.removed_rows + plan.unlinked_custom_rows if applied else plan.removed_rows - total_rows = len(plan.added_rows) + len(removed_rows) + added_rows = [*plan.added_rows, *plan.added_action_rows] + removed_rows = [*removed_rows, *plan.removed_action_rows] + total_rows = len(added_rows) + len(removed_rows) if total_rows: self._write_section_header(f"Casbin policies ({total_rows})") - for row in plan.added_rows: + for row in added_rows: self._write_marked_line("+", self._format_policy_row(row), self.style.SUCCESS) for row in removed_rows: self._write_marked_line("-", self._format_policy_row(row), self.style.ERROR) diff --git a/src/openedx_authz/migrations/0015_authzpermissiondependency.py b/src/openedx_authz/migrations/0015_authzpermissiondependency.py new file mode 100644 index 000000000..2813e5221 --- /dev/null +++ b/src/openedx_authz/migrations/0015_authzpermissiondependency.py @@ -0,0 +1,46 @@ +# Generated by Django 5.2.19 on 2026-11-25 21:10 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("openedx_authz", "0014_add_custom_role_fields"), + ] + + operations = [ + migrations.CreateModel( + name="AuthzPermissionDependency", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("created_at", models.DateTimeField(auto_now_add=True)), + ("updated_at", models.DateTimeField(auto_now=True)), + ( + "depends_on", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="dependents", + to="openedx_authz.authzpermissiondefinition", + ), + ), + ( + "permission", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="dependencies", + to="openedx_authz.authzpermissiondefinition", + ), + ), + ], + options={ + "verbose_name": "Authz Permission Dependency", + "verbose_name_plural": "Authz Permission Dependencies", + "constraints": [ + models.UniqueConstraint( + fields=("permission", "depends_on"), name="authz_permission_dependency_uniq" + ) + ], + }, + ), + ] diff --git a/src/openedx_authz/models/schema.py b/src/openedx_authz/models/schema.py index 7cd1c3a77..347b0e6e0 100644 --- a/src/openedx_authz/models/schema.py +++ b/src/openedx_authz/models/schema.py @@ -37,6 +37,7 @@ "AuthzPermissionDefinition", "AuthzRoleDefinition", "AuthzRolePermission", + "AuthzPermissionDependency", "AuthzCategorySource", "AuthzPermissionSource", "AuthzRoleSource", @@ -398,6 +399,30 @@ def __str__(self): return f"{self.role.role_id} -> {self.permission.identifier} @ {self.scope}" +class AuthzPermissionDependency(TimeStampedModel): + """A direct dependency of one permission on another (ADR 0034 §5). + + .. no_pii: + + Each row corresponds to one rendered Casbin ``g2`` row and marks that row as schema-owned. + It has no scope, because ``g2`` rows have none, and no source records, because only the file + that defines a permission declares its dependencies. + """ + + permission = models.ForeignKey(AuthzPermissionDefinition, on_delete=models.CASCADE, related_name="dependencies") + depends_on = models.ForeignKey(AuthzPermissionDefinition, on_delete=models.CASCADE, related_name="dependents") + + class Meta: + verbose_name = "Authz Permission Dependency" + verbose_name_plural = "Authz Permission Dependencies" + constraints = [ + models.UniqueConstraint(fields=["permission", "depends_on"], name="authz_permission_dependency_uniq"), + ] + + def __str__(self): + return f"{self.permission.identifier} -> {self.depends_on.identifier}" + + # --------------------------------------------------------------------------- # Source link (through) models. Each carries origin and priority so the winning # metadata source is derivable and shared ownership is representable. diff --git a/src/openedx_authz/tests/api/test_custom_roles.py b/src/openedx_authz/tests/api/test_custom_roles.py index 9de571a94..bbbf8254e 100644 --- a/src/openedx_authz/tests/api/test_custom_roles.py +++ b/src/openedx_authz/tests/api/test_custom_roles.py @@ -48,6 +48,7 @@ VIEW_LIBRARY = "content_libraries.view_library" EDIT_LIBRARY_CONTENT = "content_libraries.edit_library_content" +VIEW_LIBRARY_TEAM = "content_libraries.view_library_team" VIEW_COURSE = "courses.view_course" HIDDEN_CATEGORY_PERMISSION = "courses.legacy_beta_tester_permissions" LIBRARY_SCOPE_TYPE = "lib" @@ -332,17 +333,17 @@ def test_added_and_dropped_permissions_reach_holders_immediately(self): role = self.create_role(permissions=[VIEW_LIBRARY]) self.assign(role) - update_custom_role(role.role_id, permissions=[EDIT_LIBRARY_CONTENT]) + update_custom_role(role.role_id, permissions=[VIEW_LIBRARY_TEAM]) - self.assertTrue(self.is_allowed(EDIT_LIBRARY_CONTENT)) + self.assertTrue(self.is_allowed(VIEW_LIBRARY_TEAM)) self.assertFalse(self.is_allowed(VIEW_LIBRARY)) self.assertEqual( list(AuthzRolePermission.objects.filter(role=role).values_list("permission__name", flat=True)), - ["edit_library_content"], + ["view_library_team"], ) self.assertEqual( list(self.stored_policy_rows(role.role_id).values_list("v1", flat=True)), - [make_action_key(EDIT_LIBRARY_CONTENT)], + [make_action_key(VIEW_LIBRARY_TEAM)], ) def test_kept_permissions_keep_their_grants(self): diff --git a/src/openedx_authz/tests/schema/test_apply.py b/src/openedx_authz/tests/schema/test_apply.py index 7be500afe..b34654c47 100644 --- a/src/openedx_authz/tests/schema/test_apply.py +++ b/src/openedx_authz/tests/schema/test_apply.py @@ -32,6 +32,7 @@ from openedx_authz.models.schema import ( AuthzPermissionCategory, AuthzPermissionDefinition, + AuthzPermissionDependency, AuthzRoleDefinition, AuthzRolePermission, ) @@ -63,9 +64,33 @@ class FakeEnforcer: is the shape the real enforcer returns. """ - def __init__(self, policies=None, grouping=None): + def __init__(self, policies=None, grouping=None, action_grouping=None): self._policies = [list(row) for row in (policies or [])] self._grouping = [list(row) for row in (grouping or [])] + self._action_grouping = [list(row) for row in (action_grouping or [])] + + def get_named_grouping_policy(self, ptype): + """Return a copy of the stored ``g2`` rows.""" + assert ptype == "g2" + return [list(row) for row in self._action_grouping] + + def add_named_grouping_policy(self, ptype, *args): + """Add a ``g2`` row, ignoring exact duplicates. Returns True if added.""" + assert ptype == "g2" + row = list(args) + if row not in self._action_grouping: + self._action_grouping.append(row) + return True + return False + + def remove_named_grouping_policy(self, ptype, *args): + """Remove a ``g2`` row if present. Returns True if removed.""" + assert ptype == "g2" + row = list(args) + if row in self._action_grouping: + self._action_grouping.remove(row) + return True + return False def load_policy(self): """No-op reload hook: the fake is already its own in-memory source of truth.""" @@ -171,6 +196,172 @@ def _apply( ) +DEPENDENT_PERMS = [ + permission(name="view_course", cat="cat"), + permission(name="manage_tags", cat="cat", depends_on=("courses.view_course",)), + permission(name="export_course", cat="cat", depends_on=("courses.view_course",)), +] +TAGS_ROW = ["act^courses.manage_tags", "act^courses.view_course"] +EXPORT_ROW = ["act^courses.export_course", "act^courses.view_course"] + + +def _dependent_doc(permissions=None): + """A schema whose ``manage_tags`` and ``export_course`` permissions depend on ``view_course``.""" + return _doc( + permissions=permissions if permissions is not None else DEPENDENT_PERMS, + roles=[ + role( + rid="course_editor", + scopes=("course-v1",), + permissions=("courses.view_course", "courses.manage_tags", "courses.export_course"), + ) + ], + ) + + +def _stored_dependencies() -> set[tuple[str, str]]: + """The stored ``(permission, depends_on)`` pairs.""" + return { + (dependency.permission.identifier, dependency.depends_on.identifier) + for dependency in AuthzPermissionDependency.objects.select_related("permission", "depends_on") + } + + +class TestRenderDependencies: + """Each direct dependency renders as one ``g2`` row (ADR 0034 §4).""" + + def test_renders_one_sorted_g2_row_per_direct_dependency(self): + """Two dependencies render as two ``g2`` rows, in sorted order.""" + rendered = _render(_dependent_doc()) + + assert [row.as_policy() for row in rendered.action_rows] == [EXPORT_ROW, TAGS_ROW] + + def test_permissions_without_dependencies_render_no_g2_rows(self): + """A schema with no ``depends_on`` renders no ``g2`` rows.""" + assert not _render(_editor(("courses.view_course",))).action_rows + + +@pytest.mark.django_db +@pytest.mark.usefixtures("cache_invalidation") +class TestApplyDependencies: + """``g2`` rows are added, adopted and removed like ``p`` rows (ADR 0034 §4, §5).""" + + def test_first_apply_adds_g2_rows_and_stores_dependencies(self): + """A first apply writes one ``g2`` row and one stored dependency per direct dependency.""" + enforcer = FakeEnforcer() + + result = _apply(enforcer, _dependent_doc()) + + assert result.added_action_rows == 2 + assert enforcer.get_named_grouping_policy("g2") == [EXPORT_ROW, TAGS_ROW] + assert _stored_dependencies() == { + ("courses.manage_tags", "courses.view_course"), + ("courses.export_course", "courses.view_course"), + } + + def test_reapply_is_idempotent(self): + """Re-applying the same schema adds and removes no ``g2`` row.""" + enforcer = FakeEnforcer() + _apply(enforcer, _dependent_doc()) + + result = _apply(enforcer, _dependent_doc()) + + assert result.added_action_rows == 0 + assert result.removed_action_rows == 0 + assert result.unchanged is True + + def test_existing_g2_rows_are_adopted_without_writes(self): + """Rows loaded from ``authz.policy`` before dependencies were stored are adopted, not rewritten.""" + enforcer = FakeEnforcer(action_grouping=[TAGS_ROW, EXPORT_ROW]) + + result = _apply(enforcer, _dependent_doc()) + + assert result.added_action_rows == 0 + assert len(_stored_dependencies()) == 2 + + def test_unmanaged_g2_row_survives_an_empty_schema(self): + """A ``g2`` row that no schema declares is not removed, even with nothing to render.""" + unmanaged = ["act^other.edit", "act^other.view"] + enforcer = FakeEnforcer(action_grouping=[unmanaged]) + + result = _apply(enforcer) + + assert result.removed_action_rows == 0 + assert enforcer.get_named_grouping_policy("g2") == [unmanaged] + + def test_removed_dependency_removes_its_g2_row_and_stored_dependency(self): + """Dropping one dependency removes only its ``g2`` row and its stored dependency.""" + enforcer = FakeEnforcer() + _apply(enforcer, _dependent_doc()) + without_export_dependency = [*DEPENDENT_PERMS[:2], permission(name="export_course", cat="cat")] + + result = _apply(enforcer, _dependent_doc(without_export_dependency)) + + assert result.removed_action_rows == 1 + assert enforcer.get_named_grouping_policy("g2") == [TAGS_ROW] + assert _stored_dependencies() == {("courses.manage_tags", "courses.view_course")} + + def test_added_dependency_alone_invalidates_the_policy_cache(self, cache_invalidation): + """Adding a dependency changes only ``g2`` rows, and the policy cache is still invalidated.""" + enforcer = FakeEnforcer() + without_export_dependency = [*DEPENDENT_PERMS[:2], permission(name="export_course", cat="cat")] + _apply(enforcer, _dependent_doc(without_export_dependency)) + cache_invalidation.reset_mock() + + result = _apply(enforcer, _dependent_doc()) + + assert (result.added, result.removed, result.added_action_rows) == (0, 0, 1) + cache_invalidation.assert_called_once() + + def test_removed_dependency_alone_invalidates_the_policy_cache(self, cache_invalidation): + """Removing a dependency changes only ``g2`` rows, and the policy cache is still invalidated.""" + enforcer = FakeEnforcer() + _apply(enforcer, _dependent_doc()) + cache_invalidation.reset_mock() + without_export_dependency = [*DEPENDENT_PERMS[:2], permission(name="export_course", cat="cat")] + + result = _apply(enforcer, _dependent_doc(without_export_dependency)) + + assert (result.added, result.removed, result.removed_action_rows) == (0, 0, 1) + cache_invalidation.assert_called_once() + + def test_removed_permission_removes_its_g2_row(self): + """Removing a permission removes the ``g2`` row of its dependency.""" + enforcer = FakeEnforcer() + _apply(enforcer, _dependent_doc()) + schema = _doc( + permissions=DEPENDENT_PERMS[:2], + roles=[ + role( + rid="course_editor", + scopes=("course-v1",), + permissions=("courses.view_course", "courses.manage_tags"), + ) + ], + ) + + result = _apply(enforcer, schema) + + assert result.removed_action_rows == 1 + assert enforcer.get_named_grouping_policy("g2") == [TAGS_ROW] + assert _stored_dependencies() == {("courses.manage_tags", "courses.view_course")} + + def test_plan_reports_g2_rows_and_dependencies_without_writing(self): + """The plan lists the ``g2`` rows and dependencies to add, and writes nothing.""" + enforcer = FakeEnforcer() + schema = _compile(_dependent_doc()) + + plan = SchemaApplier(policy_store=PolicyStore(enforcer)).plan(PolicyRenderer().render(schema), schema) + + assert [row.as_policy() for row in plan.added_action_rows] == [EXPORT_ROW, TAGS_ROW] + assert plan.dependencies.added == [ + "courses.export_course -> courses.view_course", + "courses.manage_tags -> courses.view_course", + ] + assert not enforcer.get_named_grouping_policy("g2") + assert not AuthzPermissionDependency.objects.exists() + + @pytest.mark.django_db @pytest.mark.usefixtures("cache_invalidation") class TestApplyReconciliation: diff --git a/src/openedx_authz/tests/schema/test_dependency_enforcement.py b/src/openedx_authz/tests/schema/test_dependency_enforcement.py new file mode 100644 index 000000000..fce2d828d --- /dev/null +++ b/src/openedx_authz/tests/schema/test_dependency_enforcement.py @@ -0,0 +1,132 @@ +"""Permission dependencies through the real enforcer and the built-in schema (ADR 0034 §4, §5).""" + +from casbin_adapter.models import CasbinRule +from django.test import TestCase + +from openedx_authz.engine.enforcer import AuthzEnforcer +from openedx_authz.engine.schema.pipeline import SchemaPipeline +from openedx_authz.models.schema import AuthzPermissionDependency +from openedx_authz.tests.test_utils import ( + AuthzEnforcerTestMixin, + make_action_key, + make_role_key, + make_scope_key, + make_user_key, +) + +# The action-inheritance rows ``authz.policy`` declared before the static schema replaced it. +LEGACY_LIBRARY_G2_ROWS = { + ("content_libraries.manage_library_tags", "content_libraries.edit_library_content"), + ("content_libraries.delete_library", "content_libraries.edit_library_content"), + ("content_libraries.publish_library_content", "content_libraries.edit_library_content"), + ("content_libraries.edit_library_content", "content_libraries.view_library"), + ("content_libraries.reuse_library_content", "content_libraries.view_library"), + ("content_libraries.publish_library_content", "content_libraries.view_library"), + ("content_libraries.manage_library_team", "content_libraries.view_library_team"), + ("content_libraries.delete_library_collection", "content_libraries.edit_library_collection"), + ("content_libraries.create_library_collection", "content_libraries.edit_library_collection"), + ("content_libraries.edit_library_collection", "content_libraries.view_library"), +} + +# One concrete scope per scope type, for assigning roles in the enforcement check. +SCOPES = { + "lib": make_scope_key("lib", "lib:DependencyOrg:dependency_library"), + "course-v1": make_scope_key("course-v1", "course-v1:DependencyOrg+Course+Run"), +} + + +def stored_g2_rows() -> set[tuple[str, str]]: + """The stored ``g2`` rows, without the ``act^`` prefix.""" + prefix = make_action_key("") + return { + (rule.v0.removeprefix(prefix), rule.v1.removeprefix(prefix)) for rule in CasbinRule.objects.filter(ptype="g2") + } + + +def seed_legacy_g2_rows() -> None: + """Store the ``g2`` rows exactly as loading ``authz.policy`` did.""" + for permission_id, depends_on_id in LEGACY_LIBRARY_G2_ROWS: + CasbinRule.objects.create(ptype="g2", v0=make_action_key(permission_id), v1=make_action_key(depends_on_id)) + + +class TestBuiltInDependencyRows(AuthzEnforcerTestMixin, TestCase): + """Applying the built-in schema stores the library dependencies as ``g2`` rows.""" + + def test_fresh_install_gets_the_legacy_library_g2_rows(self): + """A database that never loaded ``authz.policy`` gets the same rows it used to declare.""" + SchemaPipeline().apply() + + assert stored_g2_rows() == LEGACY_LIBRARY_G2_ROWS + assert AuthzPermissionDependency.objects.count() == len(LEGACY_LIBRARY_G2_ROWS) + + def test_rows_from_authz_policy_are_adopted_without_writes(self): + """An existing installation keeps its ``g2`` rows, and the loader records that it owns them.""" + seed_legacy_g2_rows() + + result = SchemaPipeline().apply() + + assert result.added_action_rows == 0 + assert result.removed_action_rows == 0 + assert CasbinRule.objects.filter(ptype="g2").count() == len(LEGACY_LIBRARY_G2_ROWS) + assert AuthzPermissionDependency.objects.count() == len(LEGACY_LIBRARY_G2_ROWS) + + def test_reapplying_changes_nothing(self): + """A second apply of the same schema writes no ``g2`` rows and reports no change.""" + SchemaPipeline().apply() + + result = SchemaPipeline().apply() + + assert result.unchanged is True + assert stored_g2_rows() == LEGACY_LIBRARY_G2_ROWS + + def test_unmanaged_g2_row_is_kept(self): + """A ``g2`` row that no schema declares is left in place.""" + CasbinRule.objects.create(ptype="g2", v0=make_action_key("other.edit"), v1=make_action_key("other.view")) + + SchemaPipeline().apply() + + assert ("other.edit", "other.view") in stored_g2_rows() + + +class TestEnforcementMatchesRolePermissions(AuthzEnforcerTestMixin, TestCase): + """With ``g2`` rows in place, each built-in role allows exactly the permissions it lists (ADR 0034). + + Every built-in role lists all of its dependencies, so the ``g2`` rows must not grant anything + a role does not already list. + """ + + @classmethod + def setUpTestData(cls): + """Apply the built-in schema once for the class.""" + super().setUpTestData() + cls.schema = SchemaPipeline().compile() + SchemaPipeline().apply() + + def test_each_role_allows_exactly_its_listed_permissions(self): + """Assign each static role in each of its scope types and check every permission for that scope type.""" + enforcer = AuthzEnforcer.get_enforcer() + mismatches = [] + for role_id, compiled_role in sorted(self.schema.roles.items()): + role = compiled_role.definition + for scope_type in role.scopes: + user = make_user_key(f"user_{role_id}_{scope_type}") + enforcer.add_grouping_policy(user, make_role_key(role_id), SCOPES[scope_type]) + for permission_id, compiled_permission in sorted(self.schema.permissions.items()): + if scope_type not in compiled_permission.definition.scopes: + continue + allowed = enforcer.enforce(user, make_action_key(permission_id), SCOPES[scope_type]) + if allowed != (permission_id in role.permissions): + mismatches.append((role_id, scope_type, permission_id, allowed)) + + assert not mismatches + + def test_g2_rows_grant_the_dependency_to_a_role_that_does_not_list_it(self): + """A role outside schema validation still gets the permissions its permissions depend on.""" + enforcer = AuthzEnforcer.get_enforcer() + user, role, scope = make_user_key("db_only_user"), make_role_key("db_only_role"), SCOPES["lib"] + enforcer.add_policy(role, make_action_key("content_libraries.delete_library"), "lib^*", "allow") + enforcer.add_grouping_policy(user, role, scope) + + assert enforcer.enforce(user, make_action_key("content_libraries.edit_library_content"), scope) + assert enforcer.enforce(user, make_action_key("content_libraries.view_library"), scope) + assert not enforcer.enforce(user, make_action_key("content_libraries.view_library_team"), scope) 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 8e8837a80..2f028bcf0 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 @@ -13,6 +13,7 @@ from django.core.management import call_command from django.core.management.base import CommandError +from openedx_authz.engine.policy import ActionGroupingRow from openedx_authz.engine.renderer import ( ApplyResult, ChangePlan, @@ -328,6 +329,36 @@ def test_casbin_rows_render_as_comma_joined_policy_lines(self): # The old Python-list repr form must not leak into the report. assert "['role^course_editor'" not in output + def test_g2_rows_and_dependencies_are_reported(self): + """Dependency ``g2`` rows print in the Casbin section, and dependency changes in the definitions.""" + plan = ChangePlan( + added_action_rows=[ActionGroupingRow("act^courses.manage_tags", "act^courses.view_course")], + removed_action_rows=[ActionGroupingRow("act^courses.export_course", "act^courses.view_course")], + unchanged=False, + dependencies=DefinitionDiff( + added=["courses.manage_tags -> courses.view_course"], + removed=["courses.export_course -> courses.view_course"], + ), + ) + with mock.patch(PIPELINE_PATH) as pipeline_cls: + pipeline_cls.return_value.plan.return_value = plan + output = _run("--dry-run") + + assert "Casbin policies (2)" in output + assert "+ g2, act^courses.manage_tags, act^courses.view_course" in output + assert "- g2, act^courses.export_course, act^courses.view_course" in output + assert "+ permission dependency: courses.manage_tags -> courses.view_course" in output + + def test_apply_summary_counts_g2_rows(self): + """The applied summary counts ``g2`` rows together with ``p`` rows.""" + with mock.patch(PIPELINE_PATH) as pipeline_cls: + pipeline_cls.return_value.apply.return_value = ApplyResult( + added=1, removed=0, added_action_rows=10, removed_action_rows=2, unchanged=False + ) + output = _run() + + assert "11 Casbin policy row(s) added, 2 removed" in output + def test_dry_run_reports_compact_definitions_section_without_casbin(self): """A definitions-only change prints 'Definitions (N)' with the Casbin section omitted.""" plan = ChangePlan( diff --git a/src/openedx_authz/tests/test_policy.py b/src/openedx_authz/tests/test_policy.py index 28aa4d1f8..c3b53bbc7 100644 --- a/src/openedx_authz/tests/test_policy.py +++ b/src/openedx_authz/tests/test_policy.py @@ -16,7 +16,7 @@ import pytest from openedx_authz.data import GroupingPolicyIndex -from openedx_authz.engine.policy import GroupingRow, PolicyRow, PolicyStore +from openedx_authz.engine.policy import ActionGroupingRow, GroupingRow, PolicyRow, PolicyStore class FakeEnforcer: @@ -27,9 +27,30 @@ class FakeEnforcer: without Django or Casbin. """ - def __init__(self, policies=None, grouping=None): + def __init__(self, policies=None, grouping=None, named_grouping=None): self._policies = [list(row) for row in (policies or [])] self._grouping = [list(row) for row in (grouping or [])] + self._named_grouping = {ptype: [list(row) for row in rows] for ptype, rows in (named_grouping or {}).items()} + + def get_named_grouping_policy(self, ptype: str) -> list[list[str]]: + """Return a copy of the stored rows of one named grouping type, such as ``g2``.""" + return [list(row) for row in self._named_grouping.get(ptype, [])] + + def add_named_grouping_policy(self, ptype: str, *args) -> bool: + """Add a named grouping row, ignoring exact duplicates. Returns True if added.""" + rows = self._named_grouping.setdefault(ptype, []) + if list(args) in rows: + return False + rows.append(list(args)) + return True + + def remove_named_grouping_policy(self, ptype: str, *args) -> bool: + """Remove a named grouping row if present. Returns True if removed.""" + rows = self._named_grouping.get(ptype, []) + if list(args) not in rows: + return False + rows.remove(list(args)) + return True def get_policy(self) -> list[list[str]]: """Return a copy of the stored ``p`` rows.""" @@ -202,6 +223,50 @@ def test_remove_grouping_row_deletes_the_exact_stored_row(self): assert enforcer.get_grouping_policy() == [] +class TestActionGroupingRow: + """Constructing and round-tripping a single Casbin ``g2`` row.""" + + def test_from_dependency_applies_the_action_namespace(self): + """A dependency renders with the same ``act^`` form as ``p`` rows.""" + row = ActionGroupingRow.from_dependency("courses.manage_tags", "courses.view_course") + + assert row.as_policy() == ["act^courses.manage_tags", "act^courses.view_course"] + assert row.action == PolicyRow.from_grant("r", "courses.manage_tags", "course-v1").action + + def test_from_policy_round_trips_as_policy(self): + """A row rebuilt from ``as_policy`` output equals the original.""" + row = ActionGroupingRow("act^courses.manage_tags", "act^courses.view_course") + + assert ActionGroupingRow.from_policy(row.as_policy()) == row + + def test_ptype_is_g2(self): + """``g2`` is the Casbin grouping type the matcher checks for action implication.""" + assert ActionGroupingRow.PTYPE == "g2" + + +class TestPolicyStoreActionGroupingRows: + """Reading and writing ``g2`` rows through the store.""" + + ROW = ["act^courses.manage_tags", "act^courses.view_course"] + + def test_get_action_grouping_rows_returns_typed_rows(self): + """Stored ``g2`` rows come back as :class:`ActionGroupingRow` values.""" + store = PolicyStore(FakeEnforcer(named_grouping={"g2": [self.ROW]})) + + assert store.get_action_grouping_rows() == [ActionGroupingRow(*self.ROW)] + + def test_add_and_remove_write_the_g2_type(self): + """Adding and removing go to the ``g2`` grouping type, in the raw two-field shape.""" + enforcer = FakeEnforcer() + store = PolicyStore(enforcer) + row = ActionGroupingRow(*self.ROW) + + assert store.add_action_grouping_row(row) is True + assert enforcer.get_named_grouping_policy("g2") == [self.ROW] + assert store.remove_action_grouping_row(row) is True + assert enforcer.get_named_grouping_policy("g2") == [] + + class TestPolicyStoreEnforcerResolution: """``PolicyStore`` owns enforcer resolution so callers hold no handle."""