diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 096ef497d..61361e7a2 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -50,6 +50,11 @@ Added * ``assign_role_to_subject_in_scope`` now raises ``CustomRoleNotFoundError`` for a custom role that does not exist or was removed. It assigns custom roles under the same lock as removing them, so an assignment cannot outlive a concurrent removal. Static role assignments are unchanged. +* Added authorization schema version ``1.1``, with its own ``authz-schema-v1.1.json``. It adds an + optional ``depends_on`` list to permissions (ADR 0034). Files of versions ``1.0`` and ``1.1`` can + 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. * 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 @@ -117,6 +122,9 @@ Changed return a 400 validation error, the same as ``/roles/``. * The role catalog now lists roles by display name by default, instead of by role identifier. Pass ``sort_by`` and ``order`` to choose another order. +* Replaced the ``OPENEDX_AUTHZ_JSON_SCHEMA`` setting with ``OPENEDX_AUTHZ_JSON_SCHEMAS``, which maps + ``schema_version`` values to JSON Schema resources. It overrides only the versions it lists, and + the built-in schemas cover the rest. Setting the old name raises ``ImproperlyConfigured``. Removed ======= diff --git a/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst b/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst index d6ccaa803..e07781043 100644 --- a/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst +++ b/docs/decisions/0034-permission-dependencies-in-authorization-schema.rst @@ -123,6 +123,15 @@ Addendum: Indirect Dependencies in the Catalog (2026-11-17) `ADR 0036`_ adds ``all_depends_on`` to each permission in the role catalog, next to ``depends_on``. It lists every direct and indirect dependency, so clients no longer compute indirect dependencies themselves. This replaces the last part of section 6. +Addendum: Visible Permissions Cannot Depend on Hidden Ones (2026-11-26) +======================================================================= + +Validation also rejects a visible permission that depends on a hidden one. A permission is hidden when it, or its category, is hidden (`ADR 0038`_). This adds a rule to section 3. + +The rule exists because hidden permissions are left out of the role catalog and a custom role cannot grant them. A custom role that grants the visible permission could never include its dependency, and the catalog would ask clients to select a permission it never lists. + +Only direct dependencies are checked. This also covers indirect ones, because any chain from a visible permission to a hidden one contains a visible permission that directly depends on a hidden one. + Rejected Alternatives ********************* @@ -151,6 +160,7 @@ References * `ADR 0028`_ * `ADR 0031`_ * `ADR 0036`_ +* `ADR 0038`_ * `Issue #91`_ * `Issue #523`_ * `PR #538`_ @@ -163,6 +173,7 @@ References .. _ADR 0028: 0028-api-contract-for-role-catalog.rst .. _ADR 0031: 0031-priority-applies-to-role-extensions-only.rst .. _ADR 0036: 0036-api-contract-for-custom-roles.rst +.. _ADR 0038: 0038-hidden-permission-categories-and-permissions.rst .. _Issue #91: https://github.com/openedx/openedx-authz/issues/91 .. _Issue #523: https://github.com/openedx/openedx-authz/issues/523 .. _PR #538: https://github.com/openedx/openedx-authz/pull/538 diff --git a/docs/references/authorization-schema-json.rst b/docs/references/authorization-schema-json.rst index 80f835e97..050ad4cd5 100644 --- a/docs/references/authorization-schema-json.rst +++ b/docs/references/authorization-schema-json.rst @@ -3,122 +3,125 @@ Generated Authorization Schema ############################## -This page renders the exact validation rules from the :download:`authz JSON Schema <../../src/openedx_authz/engine/schema/authz-schema-v1.json>`. See the :doc:`Authorization Schema Reference ` for guidance, examples, and validation performed by the compiler across schema contributions. +This page renders the exact validation rules from the :download:`authz JSON Schema <../../src/openedx_authz/engine/schema/authz-schema-v1.1.json>` for schema version ``1.1``, the current version. The :download:`version 1.0 JSON Schema <../../src/openedx_authz/engine/schema/authz-schema-v1.json>` accepts the same fields except the permission ``depends_on`` field. See the :doc:`Authorization Schema Reference ` for guidance, examples, and validation performed by the compiler across schema contributions. Top-level fields **************** -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/properties/schema_version +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/properties/schema_version :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/properties/priority +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/properties/priority :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/properties/permission_categories +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/properties/permission_categories :lift_description: :hide_key: /items -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/properties/permissions +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/properties/permissions :lift_description: :hide_key: /items -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/properties/roles +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/properties/roles :lift_description: :hide_key: /items -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/properties/role_extensions +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/properties/role_extensions :lift_description: :hide_key: /items Permission category fields ************************** -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission_category/properties/id +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission_category/properties/id :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission_category/properties/display_name +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission_category/properties/display_name :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission_category/properties/description +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission_category/properties/description :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission_category/properties/icon +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission_category/properties/icon :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission_category/properties/hidden +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission_category/properties/hidden :lift_description: Permission fields ***************** -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/namespace +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/namespace :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/name +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/name :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/display_name +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/display_name :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/description +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/description :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/category_id +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/category_id :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/scopes +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/scopes :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/icon +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/icon :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/permission/properties/hidden +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/hidden + :lift_description: + +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/permission/properties/depends_on :lift_description: Role fields *********** -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role/properties/id +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role/properties/id :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role/properties/display_name +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role/properties/display_name :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role/properties/description +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role/properties/description :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role/properties/scopes +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role/properties/scopes :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role/properties/permissions +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role/properties/permissions :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role/properties/icon +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role/properties/icon :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role/properties/hidden +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role/properties/hidden :lift_description: Role extension fields ********************* -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role_extension/properties/role_id +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role_extension/properties/role_id :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role_extension/properties/add_permissions +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role_extension/properties/add_permissions :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role_extension/properties/remove_permissions +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role_extension/properties/remove_permissions :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role_extension/properties/display_name +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role_extension/properties/display_name :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role_extension/properties/description +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role_extension/properties/description :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role_extension/properties/icon +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role_extension/properties/icon :lift_description: -.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.json#/$defs/role_extension/properties/hidden +.. jsonschema:: ../../src/openedx_authz/engine/schema/authz-schema-v1.1.json#/$defs/role_extension/properties/hidden :lift_description: diff --git a/docs/references/authorization-schema.rst b/docs/references/authorization-schema.rst index 71d51a13a..73c87d9e4 100644 --- a/docs/references/authorization-schema.rst +++ b/docs/references/authorization-schema.rst @@ -19,7 +19,12 @@ Use this reference when creating or reviewing an authz schema file. The examples Machine-readable schema *********************** -The :download:`downloadable authz JSON Schema <../../src/openedx_authz/engine/schema/authz-schema-v1.json>` describes the fields, types, required values, and identifier formats for schema version ``1.0``. You can also :doc:`browse the generated schema ` or `view the schema source `_. Editors and validation tools can use it to check YAML files because JSON Schema applies to the data represented by both JSON and YAML. +Each schema version has a downloadable authz JSON Schema that describes its fields, types, required values, and identifier formats: + +* :download:`authz-schema-v1.json <../../src/openedx_authz/engine/schema/authz-schema-v1.json>` for schema version ``1.0`` (`view source `__). +* :download:`authz-schema-v1.1.json <../../src/openedx_authz/engine/schema/authz-schema-v1.1.json>` for schema version ``1.1`` (`view source `__). It accepts everything ``1.0`` accepts and adds the optional ``depends_on`` field to permissions. + +You can also :doc:`browse the generated schema `. Editors and validation tools can use these files to check YAML files because JSON Schema applies to the data represented by both JSON and YAML. The JSON Schema checks the structure of one file. The compiler also checks references across the combined schema, registered scope namespaces, available Paragon icons, and conflicts between contributions. @@ -81,6 +86,8 @@ Top-level fields The version of the YAML format used by the file. Write it as a quoted ``major.minor`` value, such as ``"1.0"``. A deployment stops before changing the database when it encounters a version it cannot read. +The supported versions are ``"1.0"`` and ``"1.1"``. Each file is validated against the JSON Schema of the version it declares, so a deployment can load files of both versions together, and a file can move to ``1.1`` without the other files moving with it. A file needs ``"1.1"`` only to declare ``depends_on``, and a ``1.1`` file without it means the same as it would in ``1.0``. A ``1.0`` file that declares it fails validation with an unknown-field error. + ``priority`` ============ @@ -167,6 +174,9 @@ A permission contains these fields: ``hidden`` An optional boolean that defaults to ``false``. A hidden permission does not appear in normal discovery and selection interfaces or in role details. Hiding does not delete the permission, remove it from roles, or change permission checks. Role extensions cannot change this field. +``depends_on`` + An optional list of the complete IDs of the permissions this permission directly requires. Only the file that defines a permission declares its dependencies, and role extensions cannot add or remove them. Requires schema version ``1.1``. See :doc:`ADR 0034 <../decisions/0034-permission-dependencies-in-authorization-schema>`. + The complete permission ID joins ``namespace`` and ``name`` with a period. For example: .. code-block:: yaml @@ -184,6 +194,37 @@ The complete ID is ``content_libraries.manage_library_tags``. Role definitions, The Casbin form ``act^content_libraries.manage_library_tags`` is an internal value and is not valid in a schema file. +Permission dependencies +======================= + +A permission declares the permissions it directly requires in ``depends_on``. For example, editing library content requires viewing the library: + +.. code-block:: yaml + + schema_version: "1.1" + priority: 100 + + permissions: + - namespace: content_libraries + name: edit_library_content + display_name: Edit library content + description: Create, edit, and delete content in a content library. + category_id: library_content + scopes: + - lib + depends_on: + - content_libraries.view_library + +Validation rejects a schema when: + +* a dependency is not a permission defined in the combined schema; +* a permission depends on itself, or permissions depend on each other in a cycle; +* a dependency does not support every scope of the permission that depends on it; +* a visible permission depends on a hidden permission, or on a permission in a hidden category; or +* a role, after role extensions are applied, grants a permission without all of its direct and indirect dependencies. + +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. + Roles ***** @@ -202,7 +243,7 @@ A role contains these fields: The scope namespaces where the role can be assigned. Every permission listed by the role must support those scopes. ``permissions`` - A list of complete permission IDs. The compiler does not infer one permission from another, so the role lists every permission it needs. + A list of complete permission IDs. The role lists every permission it needs, including every direct and indirect dependency of those permissions (see `Permission dependencies`_). ``icon`` An optional, case-sensitive icon name exported by ``@openedx/paragon/icons``. @@ -266,7 +307,7 @@ For example, a deployment can allow course editors to export courses, remove the - role_id: course_auditor hidden: true -An extension fails validation when its target role or a referenced permission does not exist. Adding a permission already assigned to the role or removing one the role does not have produces a warning and leaves the result unchanged. +An extension fails validation when its target role or a referenced permission does not exist. It also fails when the resulting role grants a permission without its dependencies: an extension that adds a permission must also add the dependencies the role lacks, and ``remove_permissions`` cannot remove a dependency that another permission on the role still needs. Adding a permission already assigned to the role or removing one the role does not have produces a warning and leaves the result unchanged. Identifier rules **************** diff --git a/docs/references/compiled-schema.yaml b/docs/references/compiled-schema.yaml index 9b811e766..0558b504e 100644 --- a/docs/references/compiled-schema.yaml +++ b/docs/references/compiled-schema.yaml @@ -272,6 +272,7 @@ permissions: - lib icon: Plus hidden: false + depends_on: [] content_libraries.delete_library: applet: content_libraries namespace: content_libraries @@ -283,6 +284,7 @@ permissions: - lib icon: Delete hidden: false + depends_on: [] content_libraries.delete_library_collection: applet: content_libraries namespace: content_libraries @@ -294,6 +296,7 @@ permissions: - lib icon: Delete hidden: false + depends_on: [] content_libraries.edit_library_collection: applet: content_libraries namespace: content_libraries @@ -305,6 +308,7 @@ permissions: - lib icon: EditOutline hidden: false + depends_on: [] content_libraries.edit_library_content: applet: content_libraries namespace: content_libraries @@ -316,6 +320,7 @@ permissions: - lib icon: EditOutline hidden: false + depends_on: [] content_libraries.manage_library_tags: applet: content_libraries namespace: content_libraries @@ -327,6 +332,7 @@ permissions: - lib icon: Settings hidden: false + depends_on: [] content_libraries.manage_library_team: applet: content_libraries namespace: content_libraries @@ -338,6 +344,7 @@ permissions: - lib icon: Settings hidden: false + depends_on: [] content_libraries.publish_library_content: applet: content_libraries namespace: content_libraries @@ -349,6 +356,7 @@ permissions: - lib icon: DownloadDone hidden: false + depends_on: [] content_libraries.reuse_library_content: applet: content_libraries namespace: content_libraries @@ -360,6 +368,7 @@ permissions: - lib icon: SpinnerIcon hidden: false + depends_on: [] content_libraries.view_library: applet: content_libraries namespace: content_libraries @@ -371,6 +380,7 @@ permissions: - lib icon: RemoveRedEye hidden: false + depends_on: [] content_libraries.view_library_team: applet: content_libraries namespace: content_libraries @@ -382,6 +392,7 @@ permissions: - lib icon: RemoveRedEye hidden: false + depends_on: [] courses.create_files: applet: course_authoring namespace: courses @@ -393,6 +404,7 @@ permissions: - course-v1 icon: Plus hidden: false + depends_on: [] courses.delete_files: applet: course_authoring namespace: courses @@ -404,6 +416,7 @@ permissions: - course-v1 icon: Delete hidden: false + depends_on: [] courses.edit_course_content: applet: course_authoring namespace: courses @@ -415,6 +428,7 @@ permissions: - course-v1 icon: EditOutline hidden: false + depends_on: [] courses.edit_details: applet: course_authoring namespace: courses @@ -426,6 +440,7 @@ permissions: - course-v1 icon: EditOutline hidden: false + depends_on: [] courses.edit_files: applet: course_authoring namespace: courses @@ -437,6 +452,7 @@ permissions: - course-v1 icon: EditOutline hidden: false + depends_on: [] courses.edit_grading_settings: applet: course_authoring namespace: courses @@ -448,6 +464,7 @@ permissions: - course-v1 icon: EditOutline hidden: false + depends_on: [] courses.edit_schedule: applet: course_authoring namespace: courses @@ -459,6 +476,7 @@ permissions: - course-v1 icon: EditOutline hidden: false + depends_on: [] courses.enroll_learners: applet: enrollments namespace: courses @@ -470,6 +488,7 @@ permissions: - course-v1 icon: PersonAdd hidden: false + depends_on: [] courses.export_course: applet: course_authoring namespace: courses @@ -481,6 +500,7 @@ permissions: - course-v1 icon: Upload hidden: false + depends_on: [] courses.export_tags: applet: course_authoring namespace: courses @@ -492,6 +512,7 @@ permissions: - course-v1 icon: Upload hidden: false + depends_on: [] courses.import_course: applet: course_authoring namespace: courses @@ -503,6 +524,7 @@ permissions: - course-v1 icon: Download hidden: false + depends_on: [] courses.legacy_beta_tester_permissions: applet: course_team_roles namespace: courses @@ -514,6 +536,7 @@ permissions: - course-v1 icon: DrawShapes hidden: false + depends_on: [] courses.legacy_data_researcher_permissions: applet: course_team_roles namespace: courses @@ -525,6 +548,7 @@ permissions: - course-v1 icon: DrawShapes hidden: false + depends_on: [] courses.legacy_instructor_role_permissions: applet: course_team_roles namespace: courses @@ -536,6 +560,7 @@ permissions: - course-v1 icon: DrawShapes hidden: false + depends_on: [] courses.legacy_limited_staff_role_permissions: applet: course_team_roles namespace: courses @@ -547,6 +572,7 @@ permissions: - course-v1 icon: DrawShapes hidden: false + depends_on: [] courses.legacy_staff_role_permissions: applet: course_team_roles namespace: courses @@ -558,6 +584,7 @@ permissions: - course-v1 icon: DrawShapes hidden: false + depends_on: [] courses.manage_advanced_settings: applet: course_authoring namespace: courses @@ -569,6 +596,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_certificates: applet: course_authoring namespace: courses @@ -580,6 +608,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_cohorts: applet: learner_administration namespace: courses @@ -591,6 +620,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_course_team: applet: course_authoring namespace: courses @@ -602,6 +632,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_course_updates: applet: course_authoring namespace: courses @@ -613,6 +644,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_group_configurations: applet: course_authoring namespace: courses @@ -624,6 +656,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_learner_extensions: applet: learner_administration namespace: courses @@ -635,6 +668,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_learner_grading: applet: learner_grading namespace: courses @@ -646,6 +680,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_library_updates: applet: course_authoring namespace: courses @@ -657,6 +692,7 @@ permissions: - course-v1 icon: Checklist hidden: false + depends_on: [] courses.manage_pages_and_resources: applet: course_authoring namespace: courses @@ -668,6 +704,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_tags: applet: course_authoring namespace: courses @@ -679,6 +716,7 @@ permissions: - course-v1 icon: Settings hidden: false + depends_on: [] courses.manage_taxonomies: applet: course_authoring namespace: courses @@ -690,6 +728,7 @@ permissions: - course-v1 icon: LocalOffer hidden: true + depends_on: [] courses.publish_course_content: applet: course_authoring namespace: courses @@ -701,6 +740,7 @@ permissions: - course-v1 icon: DownloadDone hidden: false + depends_on: [] courses.unenroll_learners: applet: enrollments namespace: courses @@ -712,6 +752,7 @@ permissions: - course-v1 icon: PersonRemove hidden: false + depends_on: [] courses.view_advanced_settings: applet: course_authoring namespace: courses @@ -723,6 +764,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_certificates: applet: course_authoring namespace: courses @@ -734,6 +776,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_checklists: applet: course_authoring namespace: courses @@ -745,6 +788,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_cohorts: applet: learner_administration namespace: courses @@ -756,6 +800,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_course: applet: course_authoring namespace: courses @@ -767,6 +812,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_course_info: applet: learner_administration namespace: courses @@ -778,6 +824,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_course_team: applet: course_authoring namespace: courses @@ -789,6 +836,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_course_updates: applet: course_authoring namespace: courses @@ -800,6 +848,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_enrollments: applet: enrollments namespace: courses @@ -811,6 +860,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_files: applet: course_authoring namespace: courses @@ -822,6 +872,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_gradebook: applet: learner_grading namespace: courses @@ -833,6 +884,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_grading_settings: applet: course_authoring namespace: courses @@ -844,6 +896,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_group_configurations: applet: course_authoring namespace: courses @@ -855,6 +908,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_learner_extensions: applet: learner_administration namespace: courses @@ -866,6 +920,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_library_updates: applet: course_authoring namespace: courses @@ -877,6 +932,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_pages_and_resources: applet: course_authoring namespace: courses @@ -888,6 +944,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] courses.view_schedule_and_details: applet: course_authoring namespace: courses @@ -899,6 +956,7 @@ permissions: - course-v1 icon: RemoveRedEye hidden: false + depends_on: [] categories: course_access_content: applet: course_authoring diff --git a/src/openedx_authz/constants/schema.py b/src/openedx_authz/constants/schema.py index 72b95eab9..a07aa54c8 100644 --- a/src/openedx_authz/constants/schema.py +++ b/src/openedx_authz/constants/schema.py @@ -11,9 +11,24 @@ from __future__ import annotations from enum import Enum - -AUTHZ_JSON_SCHEMA_SETTING = "OPENEDX_AUTHZ_JSON_SCHEMA" -DEFAULT_AUTHZ_JSON_SCHEMA = "openedx_authz.engine.schema/authz-schema-v1.json" +from types import MappingProxyType + +AUTHZ_JSON_SCHEMAS_SETTING = "OPENEDX_AUTHZ_JSON_SCHEMAS" +# The single-resource setting used before schema version 1.1. It is rejected with a rename error. +REMOVED_AUTHZ_JSON_SCHEMA_SETTING = "OPENEDX_AUTHZ_JSON_SCHEMA" + +AUTHZ_JSON_SCHEMA_V1_0 = "openedx_authz.engine.schema/authz-schema-v1.json" +AUTHZ_JSON_SCHEMA_V1_1 = "openedx_authz.engine.schema/authz-schema-v1.1.json" + +# The built-in JSON Schema for each supported ``schema_version`` (ADR 0034 §2). Each file is +# validated against the JSON Schema of the version it declares, so files of different versions +# can be loaded together. ``OPENEDX_AUTHZ_JSON_SCHEMAS`` overrides individual entries. +DEFAULT_AUTHZ_JSON_SCHEMAS = MappingProxyType( + { + "1.0": AUTHZ_JSON_SCHEMA_V1_0, + "1.1": AUTHZ_JSON_SCHEMA_V1_1, + } +) CUSTOM_ROLE_ID_PREFIX = "custom_" CUSTOM_ROLE_ID_MAX_LENGTH = 64 diff --git a/src/openedx_authz/engine/schema/authz-schema-v1.1.json b/src/openedx_authz/engine/schema/authz-schema-v1.1.json new file mode 100644 index 000000000..001be7265 --- /dev/null +++ b/src/openedx_authz/engine/schema/authz-schema-v1.1.json @@ -0,0 +1,428 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/openedx/openedx-authz/main/src/openedx_authz/engine/schema/authz-schema-v1.1.json", + "title": "Open edX Authorization schema", + "description": "A version 1.1 Open edX authorization schema contribution. Applications and deployment configuration use this format to define static permission categories, permissions, roles, and changes to existing roles. Version 1.1 accepts everything version 1.0 accepts and adds the optional depends_on field to permissions.", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "priority"], + "properties": { + "schema_version": { + "title": "schema_version", + "description": "The authorization schema format version. Quote this value in YAML so it remains a string.", + "type": "string", + "const": "1.1", + "examples": ["1.1"] + }, + "priority": { + "title": "priority", + "description": "The precedence used only when role_extensions contributions change the same role. A higher number takes precedence when extensions conflict. Priority does not resolve conflicting base definitions (permission categories, permissions, or roles); conflicting base definitions are rejected regardless of priority.", + "type": "integer", + "examples": [100] + }, + "permission_categories": { + "title": "permission_categories", + "description": "Permission categories contributed by this file. Categories group permissions for display and discovery but do not grant access.", + "type": "array", + "items": { + "$ref": "#/$defs/permission_category" + }, + "minItems": 1, + "examples": [ + [ + { + "id": "course_content", + "display_name": "Course content", + "description": "Permissions for viewing and editing course content.", + "icon": "Article" + } + ] + ] + }, + "permissions": { + "title": "permissions", + "description": "Static permissions contributed by this file.", + "type": "array", + "items": { + "$ref": "#/$defs/permission" + }, + "minItems": 1, + "examples": [ + [ + { + "namespace": "courses", + "name": "view_course", + "display_name": "View course", + "description": "View course configuration and content.", + "category_id": "course_content", + "scopes": ["course-v1"], + "icon": "Visibility" + } + ] + ] + }, + "roles": { + "title": "roles", + "description": "Static roles contributed by this file.", + "type": "array", + "items": { + "$ref": "#/$defs/role" + }, + "minItems": 1, + "examples": [ + [ + { + "id": "course_observer", + "display_name": "Course observer", + "description": "Reviews a course without changing it.", + "scopes": ["course-v1"], + "permissions": ["courses.view_course"] + } + ] + ] + }, + "role_extensions": { + "title": "role_extensions", + "description": "Changes to static roles defined in this file or another contribution.", + "type": "array", + "items": { + "$ref": "#/$defs/role_extension" + }, + "minItems": 1, + "examples": [ + [ + { + "role_id": "course_editor", + "add_permissions": ["courses.export_course"] + } + ] + ] + } + }, + "anyOf": [ + {"required": ["permission_categories"]}, + {"required": ["permissions"]}, + {"required": ["roles"]}, + {"required": ["role_extensions"]} + ], + "$defs": { + "identifier": { + "description": "A stable lowercase snake-case identifier that begins with a letter.", + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$", + "examples": ["course_content"] + }, + "permission_id": { + "description": "A complete permission identifier formed from its namespace and name, separated by a period.", + "type": "string", + "pattern": "^[a-z][a-z0-9_]*\\.[a-z][a-z0-9_]*$", + "examples": ["courses.view_course"] + }, + "scope_namespace": { + "description": "A scope namespace registered by a ScopeData type.", + "type": "string", + "pattern": "^[a-z][a-z0-9_-]*$", + "examples": ["course-v1"] + }, + "display_name": { + "description": "The source-language name shown to users.", + "type": "string", + "minLength": 1, + "examples": ["View course"] + }, + "description": { + "description": "A source-language description shown to users.", + "type": "string", + "minLength": 1, + "examples": ["View course configuration and content."] + }, + "icon": { + "description": "A case-sensitive icon name exported by @openedx/paragon/icons.", + "type": "string", + "pattern": "^[A-Z][A-Za-z0-9]*$", + "examples": ["Visibility"] + }, + "permission_list": { + "description": "A non-empty list of unique, complete permission identifiers.", + "type": "array", + "items": { + "$ref": "#/$defs/permission_id" + }, + "minItems": 1, + "uniqueItems": true + }, + "role_permission_list": { + "description": "A list of unique, complete permission identifiers. The list may be empty when role extensions contribute every permission.", + "type": "array", + "items": { + "$ref": "#/$defs/permission_id" + }, + "uniqueItems": true + }, + "scope_list": { + "description": "A non-empty list of unique scope namespaces.", + "type": "array", + "items": { + "$ref": "#/$defs/scope_namespace" + }, + "minItems": 1, + "uniqueItems": true + }, + "permission_category": { + "title": "Permission category", + "description": "A category used to group permissions for display and discovery.", + "type": "object", + "additionalProperties": false, + "required": ["id", "display_name", "description"], + "properties": { + "id": { + "title": "Category id", + "description": "The global category identifier.", + "examples": ["course_content"], + "$ref": "#/$defs/identifier" + }, + "display_name": { + "title": "Category display_name", + "examples": ["Course content"], + "$ref": "#/$defs/display_name" + }, + "description": { + "title": "Category description", + "examples": ["Permissions for viewing and editing course content."], + "$ref": "#/$defs/description" + }, + "icon": { + "title": "Category icon", + "examples": ["Article"], + "$ref": "#/$defs/icon" + }, + "hidden": { + "title": "Category hidden", + "description": "Whether normal discovery and selection interfaces omit this category and all of its permissions.", + "type": "boolean", + "default": false, + "examples": [false] + } + } + }, + "permission": { + "title": "Permission", + "description": "A static permission. Its complete identifier is namespace.name.", + "type": "object", + "additionalProperties": false, + "required": ["namespace", "name", "display_name", "description", "category_id", "scopes"], + "properties": { + "namespace": { + "title": "Permission namespace", + "description": "The stable product domain that owns the permission.", + "examples": ["courses"], + "$ref": "#/$defs/identifier" + }, + "name": { + "title": "Permission name", + "description": "The operation within the product domain, normally beginning with a verb.", + "examples": ["view_course"], + "$ref": "#/$defs/identifier" + }, + "display_name": { + "title": "Permission display_name", + "examples": ["View course"], + "$ref": "#/$defs/display_name" + }, + "description": { + "title": "Permission description", + "examples": ["View course configuration and content."], + "$ref": "#/$defs/description" + }, + "category_id": { + "title": "Permission category_id", + "description": "The ID of a permission category in the combined schema.", + "examples": ["course_content"], + "$ref": "#/$defs/identifier" + }, + "scopes": { + "title": "Permission scopes", + "description": "The scope namespaces where this permission can apply.", + "examples": [["course-v1"]], + "$ref": "#/$defs/scope_list" + }, + "icon": { + "title": "Permission icon", + "examples": ["Visibility"], + "$ref": "#/$defs/icon" + }, + "hidden": { + "title": "Permission hidden", + "description": "Whether normal discovery and selection interfaces, and role details, omit this permission.", + "type": "boolean", + "default": false, + "examples": [false] + }, + "depends_on": { + "title": "Permission depends_on", + "description": "Complete IDs of the permissions this permission directly requires. Only the file that defines the permission declares its dependencies; role extensions cannot change them. Omit the field when the permission has none.", + "examples": [["courses.view_course"]], + "$ref": "#/$defs/permission_list" + } + } + }, + "role": { + "title": "Role", + "description": "A static role definition. Permissions may be assigned by this definition or contributed by role extensions.", + "type": "object", + "additionalProperties": false, + "required": ["id", "display_name", "description", "scopes", "permissions"], + "properties": { + "id": { + "title": "Role id", + "description": "The stable role identifier.", + "examples": ["course_observer"], + "$ref": "#/$defs/identifier" + }, + "display_name": { + "title": "Role display_name", + "examples": ["Course observer"], + "$ref": "#/$defs/display_name" + }, + "description": { + "title": "Role description", + "examples": ["Reviews a course without changing it."], + "$ref": "#/$defs/description" + }, + "scopes": { + "title": "Role scopes", + "description": "The scope namespaces where this role can be assigned.", + "examples": [["course-v1"]], + "$ref": "#/$defs/scope_list" + }, + "permissions": { + "title": "Role permissions", + "description": "Permissions assigned by this base definition. Role extensions may contribute the complete permission set.", + "examples": [["courses.view_course"]], + "$ref": "#/$defs/role_permission_list" + }, + "icon": { + "title": "Role icon", + "examples": ["Visibility"], + "$ref": "#/$defs/icon" + }, + "hidden": { + "title": "Role hidden", + "description": "Whether normal role discovery and selection interfaces omit this role.", + "type": "boolean", + "default": false, + "examples": [false] + } + } + }, + "role_extension": { + "title": "Role extension", + "description": "A partial change to an existing static role. Include at least one field in addition to role_id.", + "type": "object", + "additionalProperties": false, + "required": ["role_id"], + "properties": { + "role_id": { + "title": "Extension role_id", + "description": "The ID of the static role to change.", + "examples": ["course_editor"], + "$ref": "#/$defs/identifier" + }, + "add_permissions": { + "title": "Extension add_permissions", + "description": "Complete permission IDs to add to the role.", + "examples": [["courses.export_course"]], + "$ref": "#/$defs/permission_list" + }, + "remove_permissions": { + "title": "Extension remove_permissions", + "description": "Complete permission IDs to remove from the role.", + "examples": [["courses.manage_tags"]], + "$ref": "#/$defs/permission_list" + }, + "display_name": { + "title": "Extension display_name", + "description": "A replacement source-language display name.", + "examples": ["Course author"], + "$ref": "#/$defs/display_name" + }, + "description": { + "title": "Extension description", + "description": "A replacement source-language description.", + "examples": ["Creates and exports course content."], + "$ref": "#/$defs/description" + }, + "icon": { + "title": "Extension icon", + "description": "A replacement Paragon icon name.", + "examples": ["Edit"], + "$ref": "#/$defs/icon" + }, + "hidden": { + "title": "Extension hidden", + "description": "Whether normal role discovery and selection interfaces omit this role.", + "type": "boolean", + "examples": [true] + } + }, + "anyOf": [ + {"required": ["add_permissions"]}, + {"required": ["remove_permissions"]}, + {"required": ["display_name"]}, + {"required": ["description"]}, + {"required": ["icon"]}, + {"required": ["hidden"]} + ] + } + }, + "examples": [ + { + "schema_version": "1.1", + "priority": 100, + "permission_categories": [ + { + "id": "course_content", + "display_name": "Course content", + "description": "Permissions for viewing and editing course content.", + "icon": "Article" + } + ], + "permissions": [ + { + "namespace": "courses", + "name": "view_course", + "display_name": "View course", + "description": "View course configuration and content.", + "category_id": "course_content", + "scopes": ["course-v1"], + "icon": "Visibility" + }, + { + "namespace": "courses", + "name": "export_course", + "display_name": "Export course", + "description": "Export course configuration and content.", + "category_id": "course_content", + "scopes": ["course-v1"], + "icon": "Download", + "depends_on": ["courses.view_course"] + } + ], + "roles": [ + { + "id": "course_observer", + "display_name": "Course observer", + "description": "Reviews a course without changing it.", + "scopes": ["course-v1"], + "permissions": ["courses.view_course"] + } + ], + "role_extensions": [ + { + "role_id": "course_editor", + "add_permissions": ["courses.export_course"] + } + ] + } + ] +} diff --git a/src/openedx_authz/engine/schema/dependencies.py b/src/openedx_authz/engine/schema/dependencies.py new file mode 100644 index 000000000..c9bb9143c --- /dev/null +++ b/src/openedx_authz/engine/schema/dependencies.py @@ -0,0 +1,120 @@ +"""Permission dependency graph helpers (ADR 0034). + +A permission's ``depends_on`` lists the permissions it directly requires. These +helpers work on a plain mapping of permission ID to its direct dependencies, so +schema validation and the Custom Roles API can apply the same rules to any set +of permissions. The permissions passed in can be any subset, but +``dependency_map`` must include every permission that has dependencies, not +only the ones passed in: results for a partial map are incomplete, not an error. + +No Casbin or Django imports, so it stays unit-testable in isolation. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping + +DependencyMap = Mapping[str, Iterable[str]] + + +def all_dependencies(permission_ids: Iterable[str], dependency_map: DependencyMap) -> set[str]: + """Return every direct and indirect dependency of the given permissions. + + The result does not include a given permission unless another given permission depends on + it. A dependency with no entry in ``dependency_map`` is included in the result, but has no + dependencies of its own to add. Cycles do not loop forever. + + Args: + permission_ids: The permissions to resolve, as ``namespace.name`` IDs (e.g., + ``["content_libraries.edit_library_content"]``). Any subset of permissions can be passed. + dependency_map: Each permission ID mapped to the IDs of its direct dependencies. + + Returns: + set[str]: The IDs of the permissions the given ones require, directly or indirectly. + """ + found: set[str] = set() + pending = [dependency for permission_id in permission_ids for dependency in dependency_map.get(permission_id, ())] + while pending: + dependency = pending.pop() + if dependency in found: + continue + found.add(dependency) + pending.extend(dependency_map.get(dependency, ())) + return found + + +def missing_dependencies(permission_ids: Iterable[str], dependency_map: DependencyMap) -> dict[str, tuple[str, ...]]: + """Return, for each given permission, the dependencies that are not also given. + + This is the role rule of ADR 0034 §3: a set of permissions is complete when it includes every + direct and indirect dependency of each of its permissions. + + Args: + permission_ids: The ``namespace.name`` IDs of the permissions a role grants. + dependency_map: Each permission ID mapped to the IDs of its direct dependencies. + + Returns: + dict[str, tuple[str, ...]]: Each permission with missing dependencies, mapped to the sorted + IDs it is missing. Empty when the set is complete. Ordered by permission ID. + """ + granted = set(permission_ids) + missing = {} + for permission_id in sorted(granted): + absent = all_dependencies((permission_id,), dependency_map) - granted + if absent: + missing[permission_id] = tuple(sorted(absent)) + return missing + + +def find_cycles(dependency_map: DependencyMap) -> list[tuple[str, ...]]: + """Return dependency cycles among the permissions in ``dependency_map``. + + A permission that depends on itself is a cycle of one. At least one cycle is returned for + every group of permissions that depend on each other, which is enough to reject the schema and + point the author at the problem. Dependencies missing from ``dependency_map`` are ignored. + + Args: + dependency_map: Each permission ID mapped to the IDs of its direct dependencies. + + Returns: + list[tuple[str, ...]]: Each cycle as the permissions along it, starting from the ID that + sorts first, with the return to the start left implicit. Sorted and without duplicates. + """ + graph = {permission_id: sorted(set(dependencies)) for permission_id, dependencies in dependency_map.items()} + visited: set[str] = set() + cycles: set[tuple[str, ...]] = set() + + for start in sorted(graph): + if start in visited: + continue + # Iterative depth-first search. ``path`` is the chain from ``start`` to the current + # permission, and ``position`` finds where a back edge re-enters it. + path: list[str] = [start] + position = {start: 0} + iterators = [iter(graph[start])] + visited.add(start) + while iterators: + dependency = next(iterators[-1], None) + if dependency is None: + del position[path.pop()] + iterators.pop() + continue + if dependency not in graph: + continue + if dependency in position: + cycles.add(_canonical(path[position[dependency] :])) + continue + if dependency in visited: + continue + visited.add(dependency) + position[dependency] = len(path) + path.append(dependency) + iterators.append(iter(graph[dependency])) + + return sorted(cycles) + + +def _canonical(cycle: list[str]) -> tuple[str, ...]: + """Rotate a cycle to start at the ID that sorts first, so the same cycle is reported once.""" + start = cycle.index(min(cycle)) + return tuple(cycle[start:] + cycle[:start]) diff --git a/src/openedx_authz/engine/schema/loading.py b/src/openedx_authz/engine/schema/loading.py index ed754bd96..333b4aba3 100644 --- a/src/openedx_authz/engine/schema/loading.py +++ b/src/openedx_authz/engine/schema/loading.py @@ -99,6 +99,8 @@ def _build_permission(self, item: dict, source: SourceRecord) -> PermissionDefin scopes=self._as_tuple(item.get("scopes")), icon=item.get("icon"), hidden=bool(item.get("hidden", False)), + # Sorted so the order in the file does not make two definitions differ (ADR 0034 §5). + depends_on=tuple(sorted(self._as_tuple(item.get("depends_on")))), ) def _build_role(self, item: dict, source: SourceRecord) -> RoleDefinition: diff --git a/src/openedx_authz/engine/schema/snapshot.py b/src/openedx_authz/engine/schema/snapshot.py index 9a70a5266..e5b36e578 100644 --- a/src/openedx_authz/engine/schema/snapshot.py +++ b/src/openedx_authz/engine/schema/snapshot.py @@ -46,6 +46,7 @@ def render_permission(compiled_permission: CompiledDefinition) -> dict[str, obje """Render one compiled permission with its owning applet.""" definition = asdict(compiled_permission.definition) definition["scopes"] = list(definition["scopes"]) + definition["depends_on"] = list(definition["depends_on"]) return {"applet": source_applet_name(compiled_permission.sources[0]), **definition} diff --git a/src/openedx_authz/engine/schema/syntax.py b/src/openedx_authz/engine/schema/syntax.py index 0c55e37b4..361241d80 100644 --- a/src/openedx_authz/engine/schema/syntax.py +++ b/src/openedx_authz/engine/schema/syntax.py @@ -1,42 +1,101 @@ -"""Validate parsed schema values against the configured JSON Schema. +"""Validate parsed schema values against the configured JSON Schemas. -The schema owns supported ``schema_version`` values, required fields, +The schemas own supported ``schema_version`` values, required fields, identifier and permission-reference formats, scope formats, collection shapes, value types, and Paragon icon-name format. Semantic relationship and icon membership checks remain in :mod:`.validation`. + +Each document is validated against the JSON Schema of the ``schema_version`` it +declares (ADR 0034 §2), so documents of different supported versions can be +validated together. """ from __future__ import annotations import json +from collections.abc import Mapping from importlib import resources +from types import MappingProxyType from django.conf import settings from django.core.exceptions import ImproperlyConfigured from jsonschema import Draft202012Validator -from openedx_authz.constants.schema import AUTHZ_JSON_SCHEMA_SETTING, DEFAULT_AUTHZ_JSON_SCHEMA +from openedx_authz.constants.schema import ( + AUTHZ_JSON_SCHEMA_V1_0, + AUTHZ_JSON_SCHEMAS_SETTING, + DEFAULT_AUTHZ_JSON_SCHEMAS, + REMOVED_AUTHZ_JSON_SCHEMA_SETTING, +) from openedx_authz.engine.schema.issues import IssueLevel, ValidationIssue from openedx_authz.engine.schema.types import ParsedSchemaDocument +_UNSET = object() + def document_validator(schema_resource: str) -> Draft202012Validator: """Load an authorization validator from a package resource.""" schema_package, separator, schema_filename = schema_resource.partition("/") if not separator: - raise ValueError(f"{AUTHZ_JSON_SCHEMA_SETTING} must be a package-anchored resource path.") + raise ValueError(f"{AUTHZ_JSON_SCHEMAS_SETTING} values must be package-anchored resource paths.") schema_path = resources.files(schema_package).joinpath(schema_filename) schema = json.loads(schema_path.read_text(encoding="utf-8")) Draft202012Validator.check_schema(schema) return Draft202012Validator(schema) -def configured_schema_resource() -> str: - """Return the configured JSON Schema resource, including outside Django.""" +def _read_setting(name: str) -> object: + """Return a Django setting, or ``_UNSET`` when it is absent or settings are not configured.""" try: - return getattr(settings, AUTHZ_JSON_SCHEMA_SETTING, DEFAULT_AUTHZ_JSON_SCHEMA) + return getattr(settings, name, _UNSET) except ImproperlyConfigured: - return DEFAULT_AUTHZ_JSON_SCHEMA + return _UNSET + + +def configured_schema_resources() -> Mapping[str, str]: + """Return the JSON Schema resource for each supported ``schema_version``, including outside Django. + + The built-in schemas are the base. ``OPENEDX_AUTHZ_JSON_SCHEMAS`` replaces only the versions it + lists, so a deployment that overrides one version keeps every other built-in version, including + versions added by later releases. It can replace built-in versions but not add new ones. + + Raises: + ImproperlyConfigured: If the removed ``OPENEDX_AUTHZ_JSON_SCHEMA`` setting is set, or if + ``OPENEDX_AUTHZ_JSON_SCHEMAS`` is not a mapping, names a version that is not built in, or + maps a version to anything but a package-anchored resource path. + """ + if _read_setting(REMOVED_AUTHZ_JSON_SCHEMA_SETTING) is not _UNSET: + raise ImproperlyConfigured( + f"{REMOVED_AUTHZ_JSON_SCHEMA_SETTING} was replaced by {AUTHZ_JSON_SCHEMAS_SETTING}, which maps " + f'each schema_version to a JSON Schema resource, for example {{"1.0": "{AUTHZ_JSON_SCHEMA_V1_0}"}}. ' + "List only the versions to override." + ) + configured = _read_setting(AUTHZ_JSON_SCHEMAS_SETTING) + if configured is _UNSET: + return DEFAULT_AUTHZ_JSON_SCHEMAS + if not isinstance(configured, Mapping): + raise ImproperlyConfigured( + f"{AUTHZ_JSON_SCHEMAS_SETTING} must map schema_version values to package-anchored JSON Schema " + f'resources, for example {{"1.0": "{AUTHZ_JSON_SCHEMA_V1_0}"}}. Got {configured!r}.' + ) + unknown = sorted(str(version) for version in configured if version not in DEFAULT_AUTHZ_JSON_SCHEMAS) + if unknown: + raise ImproperlyConfigured( + f"{AUTHZ_JSON_SCHEMAS_SETTING} can only override built-in schema versions " + f"({', '.join(DEFAULT_AUTHZ_JSON_SCHEMAS)}), got {', '.join(unknown)}." + ) + for version, resource in configured.items(): + if not isinstance(resource, str) or "/" not in resource: + raise ImproperlyConfigured( + f"{AUTHZ_JSON_SCHEMAS_SETTING}[{version!r}] must be a package-anchored JSON Schema resource " + f'such as "{AUTHZ_JSON_SCHEMA_V1_0}", got {resource!r}.' + ) + return MappingProxyType({**DEFAULT_AUTHZ_JSON_SCHEMAS, **configured}) + + +def _version_key(version: str) -> tuple[int, ...]: + """Order ``major.minor`` versions numerically, so ``"1.10"`` sorts after ``"1.9"``.""" + return tuple(int(part) for part in version.split(".")) class SchemaSyntaxValidator: @@ -44,15 +103,47 @@ class SchemaSyntaxValidator: def validate(self, documents: list[ParsedSchemaDocument]) -> list[ValidationIssue]: """Return every structural error from every parsed document.""" - validator = document_validator(configured_schema_resource()) + validators = { + version: document_validator(resource) + for version, resource in sorted( + configured_schema_resources().items(), key=lambda item: _version_key(item[0]) + ) + } + latest = next(reversed(validators.values())) + issues = [] for document in documents: - issues.extend( - ValidationIssue( - IssueLevel.ERROR, - f"{error.json_path}: {error.message}", - document.source.source_id, - ) - for error in validator.iter_errors(document.data) - ) + data = document.data + if not isinstance(data, dict) or "schema_version" not in data: + # Without a version to select by, the latest schema reports the missing field or + # the wrong root type, along with any other structural error. + issues.extend(self._errors(latest, document)) + continue + + version = data["schema_version"] + validator = validators.get(version) if isinstance(version, str) else None + if validator is None: + issues.append(self._unsupported_version(version, validators, document)) + continue + issues.extend(self._errors(validator, document)) return issues + + @staticmethod + def _errors(validator: Draft202012Validator, document: ParsedSchemaDocument) -> list[ValidationIssue]: + """Return the JSON Schema errors of one document as validation issues.""" + return [ + ValidationIssue(IssueLevel.ERROR, f"{error.json_path}: {error.message}", document.source.source_id) + for error in validator.iter_errors(document.data) + ] + + @staticmethod + def _unsupported_version(version: object, validators: dict, document: ParsedSchemaDocument) -> ValidationIssue: + """Report a ``schema_version`` with no configured JSON Schema. + + The rest of the document is not checked, because its fields depend on the version. + """ + supported = ", ".join(repr(supported_version) for supported_version in validators) + message = f"$.schema_version: {version!r} is not a supported schema version. Supported versions: {supported}." + if not isinstance(version, str): + message += " Quote the value in YAML so it remains a string." + return ValidationIssue(IssueLevel.ERROR, message, document.source.source_id) diff --git a/src/openedx_authz/engine/schema/types/definitions.py b/src/openedx_authz/engine/schema/types/definitions.py index f906246b0..80af0be7e 100644 --- a/src/openedx_authz/engine/schema/types/definitions.py +++ b/src/openedx_authz/engine/schema/types/definitions.py @@ -53,6 +53,10 @@ class PermissionDefinition: scopes: tuple[str, ...] icon: str | None = None hidden: bool = False + # Complete IDs of the permissions this permission directly requires (ADR 0034). The loader + # sorts them, so two files that list the same dependencies in a different order declare an + # identical definition rather than a conflicting one. + depends_on: tuple[str, ...] = () @property def identifier(self) -> str: diff --git a/src/openedx_authz/engine/schema/validation.py b/src/openedx_authz/engine/schema/validation.py index cc4efeb01..829055c1f 100644 --- a/src/openedx_authz/engine/schema/validation.py +++ b/src/openedx_authz/engine/schema/validation.py @@ -16,11 +16,19 @@ * A role's ``scopes`` are supported by each of its permissions. * ``role_extensions`` target an existing role (ADR 0023). * Conflicting duplicate base definitions fail; identical duplicates warn. + * Every ``depends_on`` entry references an existing permission whose scopes + include every scope of the dependent permission, and dependencies form + no cycle, including a permission that depends on itself (ADR 0034 §3). Post-compile checks (after extensions and priority are resolved): * A role's ``scopes`` are supported by every permission it *ends up* with, including permissions contributed by ``role_extensions``. * The resolved permissions and categories still exist. + * A role that ends up with a permission also ends up with all of its direct + and indirect dependencies, whatever ``schema_version`` its files declare + (ADR 0034 §3). + * A visible permission does not depend on a hidden permission or on a + permission in a hidden category. Validation collects issues rather than raising on the first problem, so the deployment report can list every error and warning at once. No Casbin imports. @@ -31,10 +39,12 @@ from collections.abc import Container from openedx_authz.constants import CUSTOM_ROLE_ID_PREFIX, SchemaOriginKind +from openedx_authz.engine.schema.dependencies import find_cycles, missing_dependencies from openedx_authz.engine.schema.issues import IssueLevel, ValidationIssue from openedx_authz.engine.schema.paragon_icons import PARAGON_ICON_NAMES from openedx_authz.engine.schema.types import ( CompiledSchema, + PermissionDefinition, SchemaDocument, ) @@ -92,6 +102,9 @@ def validate_compiled(self, schema: CompiledSchema) -> list[ValidationIssue]: ) ) + issues.extend(self._check_role_dependencies(schema)) + issues.extend(self._check_visible_dependencies(schema)) + return issues def validate_document(self, document: SchemaDocument) -> list[ValidationIssue]: @@ -124,6 +137,7 @@ def validate_set(self, documents: list[SchemaDocument]) -> list[ValidationIssue] role_ids: set[str] = set() issues.extend(self._collect_and_check_duplicates(documents, category_ids, permission_index, role_ids)) + issues.extend(self._check_permission_dependencies(documents)) # Reference integrity: permission categories exist. for document in documents: @@ -195,6 +209,111 @@ def _collect_and_check_duplicates( role_ids.add(role.id) return issues + @staticmethod + def _check_permission_dependencies(documents: list[SchemaDocument]) -> list[ValidationIssue]: + """Check every ``depends_on`` entry and reject dependency cycles (ADR 0034 §3). + + A conflicting duplicate permission is already an error, so the first definition of each + permission is the one checked. + """ + definitions: dict[str, tuple[PermissionDefinition, str]] = {} + for document in documents: + for permission in document.permissions: + definitions.setdefault(permission.identifier, (permission, document.source.source_id)) + + issues: list[ValidationIssue] = [] + for perm_id, (permission, sid) in sorted(definitions.items()): + for dependency_id in permission.depends_on: + if dependency_id == perm_id: + continue # Reported below as a cycle of one. + dependency = definitions.get(dependency_id) + if dependency is None: + issues.append( + ValidationIssue( + IssueLevel.ERROR, + f"Permission {perm_id} depends on unknown permission {dependency_id!r}.", + sid, + ) + ) + continue + uncovered = set(permission.scopes) - set(dependency[0].scopes) + if uncovered: + issues.append( + ValidationIssue( + IssueLevel.ERROR, + f"Permission {perm_id} supports scope(s) {sorted(uncovered)} " + f"that its dependency {dependency_id!r} does not support.", + sid, + ) + ) + + dependency_map = {perm_id: permission.depends_on for perm_id, (permission, _sid) in definitions.items()} + for cycle in find_cycles(dependency_map): + if len(cycle) == 1: + message = f"Permission {cycle[0]} depends on itself." + else: + message = f"Permissions form a dependency cycle: {' -> '.join((*cycle, cycle[0]))}." + issues.append(ValidationIssue(IssueLevel.ERROR, message, definitions[cycle[0]][1])) + return issues + + def _check_role_dependencies(self, schema: CompiledSchema) -> list[ValidationIssue]: + """A role must grant every direct and indirect dependency of its permissions (ADR 0034 §3). + + The check runs on the compiled roles, so it sees permissions added and removed by role + extensions, and it applies to every file whatever ``schema_version`` it declares. + """ + dependency_map = {perm_id: compiled.definition.depends_on for perm_id, compiled in schema.permissions.items()} + issues: list[ValidationIssue] = [] + for role_id, compiled_role in sorted(schema.roles.items()): + missing = missing_dependencies(compiled_role.definition.permissions, dependency_map) + for perm_id, absent in missing.items(): + issues.append( + ValidationIssue( + IssueLevel.ERROR, + f"Role {role_id} grants permission {perm_id!r} without its dependencies {list(absent)}. " + f"Add them to the role, or keep role_extensions from removing them.", + self._role_permission_source_id(schema, role_id, perm_id), + ) + ) + return issues + + @staticmethod + def _check_visible_dependencies(schema: CompiledSchema) -> list[ValidationIssue]: + """Reject visible permissions that depend on hidden ones, directly or indirectly. + + A permission is hidden when it, or its category, is hidden (ADR 0038). Only direct + dependencies are checked, which also covers indirect ones: any chain from a visible + permission to a hidden one has a visible permission that directly depends on a hidden one. + Unknown dependencies and categories are skipped, since other checks report them. + """ + issues: list[ValidationIssue] = [] + for perm_id, compiled in sorted(schema.permissions.items()): + if SchemaValidator._is_hidden_permission(schema, perm_id): + continue + hidden_dependencies = sorted( + dep for dep in compiled.definition.depends_on if SchemaValidator._is_hidden_permission(schema, dep) + ) + if hidden_dependencies: + sources = compiled.sources + issues.append( + ValidationIssue( + IssueLevel.ERROR, + f"Visible permission {perm_id} depends on hidden permission(s) {hidden_dependencies}. " + f"Hide the permission too, or make its dependencies visible.", + sources[0].source_id if sources else None, + ) + ) + return issues + + @staticmethod + def _is_hidden_permission(schema: CompiledSchema, perm_id: str) -> bool: + """Return whether a permission, or its category, is hidden. Unknown permissions are not hidden.""" + compiled = schema.permissions.get(perm_id) + if compiled is None: + return False + category = schema.categories.get(compiled.definition.category_id) + return compiled.definition.hidden or bool(category and category.definition.hidden) + @staticmethod def _register(index: dict, key: str, value, kind: str, sid: str) -> list[ValidationIssue]: """Record a base definition, flagging duplicates. diff --git a/src/openedx_authz/settings/common.py b/src/openedx_authz/settings/common.py index 9f03cd512..c6cabc247 100644 --- a/src/openedx_authz/settings/common.py +++ b/src/openedx_authz/settings/common.py @@ -5,7 +5,6 @@ import os from openedx_authz import ROOT_DIRECTORY -from openedx_authz.constants.schema import DEFAULT_AUTHZ_JSON_SCHEMA def plugin_settings(settings): @@ -60,6 +59,3 @@ 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 - - if not hasattr(settings, "OPENEDX_AUTHZ_JSON_SCHEMA"): - settings.OPENEDX_AUTHZ_JSON_SCHEMA = DEFAULT_AUTHZ_JSON_SCHEMA diff --git a/src/openedx_authz/tests/schema/factories.py b/src/openedx_authz/tests/schema/factories.py index ac500d874..8622c742b 100644 --- a/src/openedx_authz/tests/schema/factories.py +++ b/src/openedx_authz/tests/schema/factories.py @@ -72,6 +72,7 @@ def permission(namespace="courses", name="view_course", *, cat="cat", scopes=("c scopes=tuple(scopes), icon=kwargs.get("icon"), hidden=kwargs.get("hidden", False), + depends_on=tuple(kwargs.get("depends_on", ())), ) diff --git a/src/openedx_authz/tests/schema/test_compilation.py b/src/openedx_authz/tests/schema/test_compilation.py index b7654e77e..9347f3a2e 100644 --- a/src/openedx_authz/tests/schema/test_compilation.py +++ b/src/openedx_authz/tests/schema/test_compilation.py @@ -182,6 +182,14 @@ def test_error_mentions_priority_does_not_apply(self): with pytest.raises(SchemaCompileError, match="Priority does not resolve base definitions"): SchemaCompiler().compile([lo, hi]) + def test_permission_with_different_dependencies_raises_regardless_of_priority(self): + """Priority cannot pick which file's dependencies win; only the defining file declares them.""" + lo = make_document("lo", priority=100, permissions=[permission(depends_on=("courses.view_course_team",))]) + hi = make_document("hi", priority=200, permissions=[permission(depends_on=())]) + + with pytest.raises(SchemaCompileError, match="Conflicting permission definition for 'courses.view_course'"): + SchemaCompiler().compile([lo, hi]) + def test_identical_base_definitions_merge_regardless_of_priority(self): """Identical declarations are not a conflict; their sources merge.""" first = make_document("first", priority=100, roles=[role(rid="dup", permissions=())]) diff --git a/src/openedx_authz/tests/schema/test_dependencies.py b/src/openedx_authz/tests/schema/test_dependencies.py new file mode 100644 index 000000000..653e31982 --- /dev/null +++ b/src/openedx_authz/tests/schema/test_dependencies.py @@ -0,0 +1,110 @@ +"""Unit tests for the permission dependency graph helpers (ADR 0034).""" + +import pytest + +from openedx_authz.engine.schema.dependencies import all_dependencies, find_cycles, missing_dependencies + +# The library dependencies previously declared as g2 rows in authz.policy. +LIBRARY_DEPENDENCIES = { + "manage_library_tags": ("edit_library_content",), + "delete_library": ("edit_library_content",), + "publish_library_content": ("edit_library_content", "view_library"), + "edit_library_content": ("view_library",), + "reuse_library_content": ("view_library",), + "manage_library_team": ("view_library_team",), + "delete_library_collection": ("edit_library_collection",), + "create_library_collection": ("edit_library_collection",), + "edit_library_collection": ("view_library",), +} + + +class TestAllDependencies: + """All dependencies include direct and indirect ones.""" + + def test_includes_indirect_dependencies(self): + """``manage_library_tags`` requires ``view_library`` through ``edit_library_content``.""" + assert all_dependencies(["manage_library_tags"], LIBRARY_DEPENDENCIES) == { + "edit_library_content", + "view_library", + } + + def test_permission_without_dependencies_has_none(self): + """A permission with no ``depends_on`` requires nothing else.""" + assert all_dependencies(["view_library"], LIBRARY_DEPENDENCIES) == set() + + def test_given_permission_is_not_its_own_dependency(self): + """The result lists what a permission needs, not the permission itself.""" + assert all_dependencies(["edit_library_content"], LIBRARY_DEPENDENCIES) == {"view_library"} + + def test_given_permission_is_included_when_another_given_permission_depends_on_it(self): + """``delete_library`` depends on ``edit_library_content``, so it is in the result.""" + assert all_dependencies(["delete_library", "edit_library_content"], LIBRARY_DEPENDENCIES) == { + "edit_library_content", + "view_library", + } + + def test_unknown_dependencies_are_included_but_not_followed(self): + """A dependency missing from the map is still required, it just has no dependencies of its own.""" + assert all_dependencies(["a"], {"a": ("missing",)}) == {"missing"} + + def test_cycles_terminate(self): + """A cycle does not loop forever; validation rejects it separately.""" + assert all_dependencies(["a"], {"a": ("b",), "b": ("a",)}) == {"a", "b"} + + +class TestMissingDependencies: + """The role rule: a set of permissions must include all of their dependencies.""" + + def test_complete_set_has_nothing_missing(self): + """A set that lists every direct and indirect dependency is complete.""" + granted = ["manage_library_tags", "edit_library_content", "view_library"] + + assert not missing_dependencies(granted, LIBRARY_DEPENDENCIES) + + def test_reports_direct_and_indirect_dependencies_per_permission(self): + """Each permission maps to every dependency it lacks, sorted.""" + granted = ["manage_library_tags", "reuse_library_content"] + + assert missing_dependencies(granted, LIBRARY_DEPENDENCIES) == { + "manage_library_tags": ("edit_library_content", "view_library"), + "reuse_library_content": ("view_library",), + } + + def test_accepts_any_iterable(self): + """Callers can pass tuples, sets or generators.""" + assert missing_dependencies(iter(("edit_library_content",)), LIBRARY_DEPENDENCIES) == { + "edit_library_content": ("view_library",) + } + + +class TestFindCycles: + """Cycles are reported once each, starting from the ID that sorts first.""" + + def test_acyclic_graph_has_no_cycles(self): + """The library dependencies form no cycle.""" + assert find_cycles(LIBRARY_DEPENDENCIES) == [] + + def test_self_dependency_is_a_cycle_of_one(self): + """A permission that depends on itself is reported on its own.""" + assert find_cycles({"a": ("a",)}) == [("a",)] + + @pytest.mark.parametrize( + "graph", + [ + {"a": ("b",), "b": ("c",), "c": ("a",)}, + {"c": ("a",), "a": ("b",), "b": ("c",)}, + ], + ) + def test_cycle_starts_at_its_alphabetically_first_id(self, graph): + """The same cycle starts at the ID that sorts first, whatever the order of the map.""" + assert find_cycles(graph) == [("a", "b", "c")] + + def test_reports_separate_cycles(self): + """Two unrelated cycles are both reported.""" + graph = {"a": ("b",), "b": ("a",), "x": ("y",), "y": ("x",), "z": ("a",)} + + assert find_cycles(graph) == [("a", "b"), ("x", "y")] + + def test_unknown_dependencies_are_ignored(self): + """A dependency with no entry in the map is not followed, so it neither raises nor forms a cycle.""" + assert find_cycles({"a": ("missing",)}) == [] diff --git a/src/openedx_authz/tests/schema/test_json_schema.py b/src/openedx_authz/tests/schema/test_json_schema.py index ac488864e..72d77fed4 100644 --- a/src/openedx_authz/tests/schema/test_json_schema.py +++ b/src/openedx_authz/tests/schema/test_json_schema.py @@ -7,12 +7,51 @@ from jsonschema import Draft202012Validator, ValidationError +def load_schema(filename: str) -> dict: + """Load one packaged JSON Schema file.""" + schema_path = files("openedx_authz.engine.schema").joinpath(filename) + return json.loads(schema_path.read_text(encoding="utf-8")) + + @pytest.fixture(name="schema_validator", scope="module") def fixture_schema_validator(): """Build a validator from the packaged version 1 schema.""" - schema_path = files("openedx_authz.engine.schema").joinpath("authz-schema-v1.json") - schema = json.loads(schema_path.read_text(encoding="utf-8")) - return Draft202012Validator(schema) + return Draft202012Validator(load_schema("authz-schema-v1.json")) + + +class TestSchemaVersionFiles: + """Version 1.1 accepts everything 1.0 accepts and adds only ``depends_on`` (ADR 0034 §2).""" + + @pytest.mark.parametrize( + "filename,version", + [("authz-schema-v1.json", "1.0"), ("authz-schema-v1.1.json", "1.1")], + ) + def test_file_is_a_valid_json_schema_with_its_own_version(self, filename, version): + """Each file is a valid JSON Schema whose ``schema_version`` is a single constant.""" + schema = load_schema(filename) + Draft202012Validator.check_schema(schema) + assert schema["properties"]["schema_version"]["const"] == version + + def test_1_1_differs_from_1_0_only_in_version_metadata_and_depends_on(self): + """The fields both versions share stay identical, so the two files cannot drift apart.""" + v1_0 = load_schema("authz-schema-v1.json") + v1_1 = load_schema("authz-schema-v1.1.json") + + assert v1_1["$defs"]["permission"]["properties"].pop("depends_on")["$ref"] == "#/$defs/permission_list" + for schema in (v1_0, v1_1): + for key in ("$id", "description", "examples"): + schema.pop(key) + schema["properties"].pop("schema_version") + + assert v1_1 == v1_0 + + def test_1_1_examples_are_valid(self): + """The examples published in the 1.1 file validate against it.""" + schema = load_schema("authz-schema-v1.1.json") + validator = Draft202012Validator(schema) + + for example in schema["examples"]: + validator.validate(example) class TestPublishedAuthorizationJsonSchema: diff --git a/src/openedx_authz/tests/schema/test_loading.py b/src/openedx_authz/tests/schema/test_loading.py index 453e49693..97202b0f8 100644 --- a/src/openedx_authz/tests/schema/test_loading.py +++ b/src/openedx_authz/tests/schema/test_loading.py @@ -321,6 +321,42 @@ def test_scalar_scope_becomes_a_one_tuple(self): assert docs[0].roles[0].scopes == ("course-v1",) assert docs[0].roles[0].permissions == ("courses.view_course",) + def test_depends_on_is_loaded_sorted(self): + """``depends_on`` is loaded as a sorted tuple, whatever order the file lists it in (ADR 0034).""" + docs = _load( + b"schema_version: '1.1'\n" + b"priority: 1\n" + b"permissions:\n" + b" - namespace: courses\n" + b" name: export_course\n" + b" depends_on: [courses.view_course_team, courses.view_course]\n" + ) + + assert docs[0].permissions[0].depends_on == ("courses.view_course", "courses.view_course_team") + + def test_permission_without_depends_on_has_no_dependencies(self): + """A permission that omits ``depends_on``, including every 1.0 permission, has none.""" + docs = _load( + b"schema_version: '1.0'\npriority: 1\npermissions:\n - namespace: courses\n name: view_course\n" + ) + + assert docs[0].permissions[0].depends_on == () + + def test_dependency_order_does_not_make_definitions_differ(self): + """The same dependencies in a different order load as equal definitions, so they do not conflict.""" + template = ( + b"schema_version: '1.1'\n" + b"priority: 1\n" + b"permissions:\n" + b" - namespace: courses\n" + b" name: export_course\n" + b" depends_on: [%s]\n" + ) + first = _load(template % b"courses.view_course, courses.view_course_team") + second = _load(template % b"courses.view_course_team, courses.view_course") + + assert first[0].permissions[0] == second[0].permissions[0] + def test_null_blocks_are_treated_as_empty(self): """A YAML block whose value is null coerces to an empty list.""" docs = _load(b"schema_version: '1.0'\npriority: 1\nroles:\npermissions:\n") diff --git a/src/openedx_authz/tests/schema/test_snapshot.py b/src/openedx_authz/tests/schema/test_snapshot.py index d9945cbd4..552cf7b1c 100644 --- a/src/openedx_authz/tests/schema/test_snapshot.py +++ b/src/openedx_authz/tests/schema/test_snapshot.py @@ -99,7 +99,11 @@ def test_definition_renderers_shape_each_snapshot_section(self): "scopes": ["course"], "icon": None, "hidden": False, + "depends_on": [], } + assert render_permission( + replace(permission, definition=replace(permission.definition, depends_on=("courses.view_course",))) + )["depends_on"] == ["courses.view_course"] assert render_category(category) == { "applet": "course_authoring", "display_name": "Course content", diff --git a/src/openedx_authz/tests/schema/test_syntax.py b/src/openedx_authz/tests/schema/test_syntax.py index 5d1e0aa32..e027e46b7 100644 --- a/src/openedx_authz/tests/schema/test_syntax.py +++ b/src/openedx_authz/tests/schema/test_syntax.py @@ -4,18 +4,24 @@ from unittest.mock import patch import pytest +from django.core.exceptions import ImproperlyConfigured from django.test import override_settings +from openedx_authz.constants.schema import DEFAULT_AUTHZ_JSON_SCHEMAS from openedx_authz.engine.schema.discovery import SchemaDiscovery from openedx_authz.engine.schema.parsing import SchemaParser -from openedx_authz.engine.schema.syntax import SchemaSyntaxValidator, document_validator +from openedx_authz.engine.schema.syntax import ( + SchemaSyntaxValidator, + configured_schema_resources, + document_validator, +) from .factories import make_parsed_document -def schema_data(block: str, definitions: list[object]) -> dict: +def schema_data(block: str, definitions: list[object], *, version: str = "1.0") -> dict: """Build raw schema data containing one definition block.""" - return {"schema_version": "1.0", "priority": 100, block: definitions} + return {"schema_version": version, "priority": 100, block: definitions} def category_data(category_id: str = "cat", *, icon: object | None = None) -> dict: @@ -26,21 +32,21 @@ def category_data(category_id: str = "cat", *, icon: object | None = None) -> di return schema_data("permission_categories", [definition]) -def permission_data(*, namespace: str = "courses", category_id: str = "cat", scopes=None) -> dict: - """Build parsed data for one permission.""" - return schema_data( - "permissions", - [ - { - "namespace": namespace, - "name": "view_course", - "display_name": "View course", - "description": "View a course.", - "category_id": category_id, - "scopes": ["course-v1"] if scopes is None else scopes, - } - ], - ) +def permission_data( + *, namespace: str = "courses", category_id: str = "cat", scopes=None, version: str = "1.0", depends_on=None +) -> dict: + """Build parsed data for one permission, with ``depends_on`` only when given.""" + definition = { + "namespace": namespace, + "name": "view_course", + "display_name": "View course", + "description": "View a course.", + "category_id": category_id, + "scopes": ["course-v1"] if scopes is None else scopes, + } + if depends_on is not None: + definition["depends_on"] = depends_on + return schema_data("permissions", [definition], version=version) def role_data(*, role_id: str = "course_editor", scopes=None, permissions=None) -> dict: @@ -67,14 +73,121 @@ def validation_messages(data: object) -> list[str]: class TestSchemaSyntaxValidator: """JSON Schema owns validation of parsed document structure.""" - @override_settings(OPENEDX_AUTHZ_JSON_SCHEMA="custom/schema.json") - def test_uses_configured_schema_resource(self): - """The validator resolves its schema from the central Django setting.""" + def test_uses_built_in_schemas_without_the_setting(self): + """Without an override, every built-in version is validated by its packaged JSON Schema.""" + assert configured_schema_resources() == DEFAULT_AUTHZ_JSON_SCHEMAS + + @override_settings(OPENEDX_AUTHZ_JSON_SCHEMAS={"1.0": "custom/schema.json"}) + def test_override_replaces_only_the_versions_it_lists(self): + """Overriding 1.0 does not affect the default 1.1 schema""" with patch("openedx_authz.engine.schema.syntax.document_validator") as get_validator: get_validator.return_value.iter_errors.return_value = [] SchemaSyntaxValidator().validate([make_parsed_document({})]) - get_validator.assert_called_once_with("custom/schema.json") + assert sorted(call.args[0] for call in get_validator.call_args_list) == sorted( + ["custom/schema.json", DEFAULT_AUTHZ_JSON_SCHEMAS["1.1"]] + ) + + @override_settings(OPENEDX_AUTHZ_JSON_SCHEMAS={}) + def test_empty_override_uses_built_in_schemas(self): + """An empty mapping overrides nothing.""" + assert configured_schema_resources() == DEFAULT_AUTHZ_JSON_SCHEMAS + + @pytest.mark.parametrize("configured", [DEFAULT_AUTHZ_JSON_SCHEMAS["1.0"], None]) + def test_setting_that_is_not_a_mapping_is_improperly_configured(self, configured): + """A single resource string, or no value, fails with the expected format.""" + with override_settings(OPENEDX_AUTHZ_JSON_SCHEMAS=configured): + with pytest.raises(ImproperlyConfigured, match="must map schema_version values"): + SchemaSyntaxValidator().validate([make_parsed_document(permission_data())]) + + @override_settings(OPENEDX_AUTHZ_JSON_SCHEMA=DEFAULT_AUTHZ_JSON_SCHEMAS["1.0"]) + def test_old_setting_name_raises_a_rename_error(self): + """Setting ``OPENEDX_AUTHZ_JSON_SCHEMA`` raises ``ImproperlyConfigured`` that names the new setting.""" + with pytest.raises( + ImproperlyConfigured, match="OPENEDX_AUTHZ_JSON_SCHEMA was replaced by OPENEDX_AUTHZ_JSON_SCHEMAS" + ): + configured_schema_resources() + + @pytest.mark.parametrize("version", ["2.0", "latest"]) + def test_override_of_a_version_that_is_not_built_in_is_improperly_configured(self, version): + """The setting can replace built-in versions but cannot add new ones.""" + with override_settings(OPENEDX_AUTHZ_JSON_SCHEMAS={version: DEFAULT_AUTHZ_JSON_SCHEMAS["1.0"]}): + with pytest.raises(ImproperlyConfigured, match=f"can only override built-in schema versions .*{version}"): + configured_schema_resources() + + @pytest.mark.parametrize("resource", [None, "", "no-package-anchor.json", 1]) + def test_override_that_is_not_a_package_anchored_resource_is_improperly_configured(self, resource): + """Each override must be a ``package/file`` resource path.""" + with override_settings(OPENEDX_AUTHZ_JSON_SCHEMAS={"1.1": resource}): + with pytest.raises(ImproperlyConfigured, match=r"OPENEDX_AUTHZ_JSON_SCHEMAS\['1.1'\] must be"): + configured_schema_resources() + + def test_each_document_is_validated_against_the_schema_of_its_version(self): + """A ``1.0`` and a ``1.1`` document are validated together, each by its own JSON Schema.""" + documents = [ + make_parsed_document(permission_data(version="1.0"), "v1_0"), + make_parsed_document(permission_data(version="1.1", depends_on=["courses.view_course_team"]), "v1_1"), + ] + + assert not SchemaSyntaxValidator().validate(documents) + + def test_depends_on_is_rejected_in_a_1_0_document(self): + """``depends_on`` is a 1.1 field, so a 1.0 document that declares it is rejected (ADR 0034 §2).""" + messages = validation_messages(permission_data(version="1.0", depends_on=["courses.view_course_team"])) + + assert messages == ["$.permissions[0]: Additional properties are not allowed ('depends_on' was unexpected)"] + + def test_1_1_document_without_depends_on_is_valid(self): + """``depends_on`` stays optional in 1.1.""" + assert not validation_messages(permission_data(version="1.1")) + + @pytest.mark.parametrize( + "depends_on,expected", + [ + ([], "$.permissions[0].depends_on: [] should be non-empty"), + (["courses"], "$.permissions[0].depends_on[0]: 'courses' does not match"), + (["act^courses.view_course"], "$.permissions[0].depends_on[0]: 'act^courses.view_course' does not match"), + (["courses.view_course_team", "courses.view_course_team"], "has non-unique elements"), + ("courses.view_course_team", "$.permissions[0].depends_on: 'courses.view_course_team' is not of type"), + ], + ) + def test_depends_on_must_be_a_non_empty_list_of_unique_permission_ids(self, depends_on, expected): + """``depends_on`` reuses the permission list shape: non-empty, unique, complete permission IDs.""" + messages = validation_messages(permission_data(version="1.1", depends_on=depends_on)) + + assert len(messages) == 1 + assert messages[0].startswith("$.permissions[0].depends_on") + assert expected in messages[0] + + def test_role_extension_cannot_declare_depends_on(self): + """Only the file that defines a permission declares its dependencies (ADR 0034 §1).""" + data = { + "schema_version": "1.1", + "priority": 100, + "role_extensions": [ + { + "role_id": "course_editor", + "add_permissions": ["courses.view_course"], + "depends_on": ["courses.view_course_team"], + } + ], + } + + assert any("depends_on" in message for message in validation_messages(data)) + + @pytest.mark.parametrize("version", ["9.9", "1", 1.1]) + def test_unsupported_schema_version_names_the_supported_versions(self, version): + """A version without a configured JSON Schema is reported once, listing the supported versions.""" + messages = validation_messages({"schema_version": version, "priority": 100, "unexpected": True}) + + assert len(messages) == 1 + assert "'1.0', '1.1'" in messages[0] + + def test_non_string_schema_version_suggests_quoting(self): + """An unquoted YAML version is parsed as a number, so the error explains how to fix it.""" + messages = validation_messages({"schema_version": 1.0, "priority": 100, "roles": []}) + + assert any("Quote the value" in message for message in messages) def test_schema_resource_is_loaded_for_each_validator_request(self): """Schema loading has no process-global cache or configuration state.""" diff --git a/src/openedx_authz/tests/schema/test_validation.py b/src/openedx_authz/tests/schema/test_validation.py index 8c79df2c3..0357b8f0e 100644 --- a/src/openedx_authz/tests/schema/test_validation.py +++ b/src/openedx_authz/tests/schema/test_validation.py @@ -155,6 +155,40 @@ def test_conflicting_duplicate_role_is_error(self): assert any("Conflicting role definition" in m for m in messages) + def test_permission_defined_with_different_dependencies_is_error(self): + """Only the defining file declares dependencies, so two files that disagree conflict (ADR 0034 §5).""" + first = make_document( + "first", categories=[category("cat")], permissions=[permission(depends_on=("courses.view_course_team",))] + ) + second = make_document("second", permissions=[permission(depends_on=("courses.view_course_updates",))]) + + messages = [i.message for i in _errors(SchemaValidator().validate([first, second]))] + + assert any("Conflicting permission definition for 'courses.view_course'" in m for m in messages) + + def test_1_0_duplicate_of_a_permission_with_dependencies_is_error(self): + """A 1.0 file cannot declare ``depends_on``, so it cannot repeat a 1.1 definition that does.""" + v1_0 = make_document("v1_0", categories=[category("cat")], permissions=[permission()]) + v1_1 = make_document( + "v1_1", schema_version="1.1", permissions=[permission(depends_on=("courses.view_course_team",))] + ) + + messages = [i.message for i in _errors(SchemaValidator().validate([v1_0, v1_1]))] + + assert any("Conflicting permission definition" in m for m in messages) + + def test_identical_dependencies_are_an_identical_duplicate(self): + """Two files that define a permission with the same dependencies only warn.""" + first = make_document( + "first", categories=[category("cat")], permissions=[permission(depends_on=("courses.view_course_team",))] + ) + second = make_document("second", permissions=[permission(depends_on=("courses.view_course_team",))]) + + issues = SchemaValidator().validate([first, second]) + + assert not any("Conflicting" in i.message for i in _errors(issues)) + assert any("Duplicate identical permission" in i.message for i in _warnings(issues)) + def test_warning_names_the_second_source(self): """The duplicate warning is attributed to the later contributing source.""" first = make_document("first", categories=[category("cat")]) @@ -338,6 +372,287 @@ def test_source_id_is_omitted_when_provenance_is_missing(self): assert [i.source_id for i in issues] == [None] +def lib_permission(name, *, depends_on=(), scopes=("lib",)): + """Build a content library permission for dependency tests.""" + return permission("content_libraries", name, cat="cat", scopes=scopes, depends_on=depends_on) + + +LIB_VIEW = "content_libraries.view_library" +LIB_EDIT = "content_libraries.edit_library_content" +LIB_TAGS = "content_libraries.manage_library_tags" + +LIBRARY_PERMISSIONS = [ + lib_permission("view_library"), + lib_permission("edit_library_content", depends_on=(LIB_VIEW,)), + lib_permission("manage_library_tags", depends_on=(LIB_EDIT,)), +] + + +class TestPermissionDependencyRules: + """Whole-set checks on ``depends_on`` entries (ADR 0034 §3).""" + + @staticmethod + def _messages(*permissions): + """Return the whole-set errors for one 1.1 file that defines the given permissions.""" + document = make_document( + "perms", schema_version="1.1", categories=[category("cat")], permissions=list(permissions) + ) + return [i.message for i in _errors(SchemaValidator().validate([document]))] + + def test_valid_dependencies_pass(self): + """Dependencies on defined permissions with covering scopes and no cycle are valid.""" + assert not self._messages(*LIBRARY_PERMISSIONS) + + def test_dependency_on_an_undefined_permission_is_error(self): + """A dependency must reference a permission defined in the combined schema.""" + messages = self._messages(lib_permission("edit_library_content", depends_on=(LIB_VIEW,))) + + assert messages == [f"Permission {LIB_EDIT} depends on unknown permission '{LIB_VIEW}'."] + + def test_dependency_defined_in_another_file_is_valid(self): + """Dependencies resolve across files, like role permissions do.""" + first = make_document("first", categories=[category("cat")], permissions=[lib_permission("view_library")]) + second = make_document( + "second", schema_version="1.1", permissions=[lib_permission("edit_library_content", depends_on=(LIB_VIEW,))] + ) + + assert not _errors(SchemaValidator().validate([first, second])) + + def test_self_dependency_is_error(self): + """A permission cannot depend on itself.""" + messages = self._messages(lib_permission("view_library", depends_on=(LIB_VIEW,))) + + assert messages == [f"Permission {LIB_VIEW} depends on itself."] + + def test_dependency_cycle_is_error(self): + """Permissions that depend on each other, directly or through others, are rejected once.""" + messages = self._messages( + lib_permission("view_library", depends_on=(LIB_TAGS,)), + lib_permission("edit_library_content", depends_on=(LIB_VIEW,)), + lib_permission("manage_library_tags", depends_on=(LIB_EDIT,)), + ) + + assert messages == [ + f"Permissions form a dependency cycle: {LIB_EDIT} -> {LIB_VIEW} -> {LIB_TAGS} -> {LIB_EDIT}." + ] + + def test_dependency_must_support_every_scope_of_the_dependent_permission(self): + """A dependency granted in fewer scopes would leave the permission unusable in the others.""" + messages = self._messages( + lib_permission("view_library", scopes=("lib",)), + lib_permission("edit_library_content", depends_on=(LIB_VIEW,), scopes=("lib", "course-v1")), + ) + + assert messages == [ + f"Permission {LIB_EDIT} supports scope(s) ['course-v1'] that its dependency '{LIB_VIEW}' does not support." + ] + + def test_dependency_may_support_more_scopes(self): + """Only the dependent permission's scopes must be covered.""" + assert not self._messages( + lib_permission("view_library", scopes=("lib", "course-v1")), + lib_permission("edit_library_content", depends_on=(LIB_VIEW,), scopes=("lib",)), + ) + + def test_error_names_the_file_that_defines_the_permission(self): + """Dependency errors point at the file that declares ``depends_on``.""" + first = make_document("first", categories=[category("cat")], permissions=[lib_permission("view_library")]) + second = make_document( + "second", schema_version="1.1", permissions=[lib_permission("edit_library_content", depends_on=(LIB_TAGS,))] + ) + + issues = _errors(SchemaValidator().validate([first, second])) + + assert [i.source_id for i in issues] == [make_source("second").source_id] + + +class TestRoleDependencyRule: + """A role must list every dependency of the permissions it grants (ADR 0034 §3). + + The rule runs on the compiled schema, so it sees the effect of role extensions. + """ + + @staticmethod + def _messages(*documents): + """Compile the documents and return the messages of the errors found in the compiled schema.""" + schema = SchemaCompiler().compile(list(documents)) + return [i.message for i in _errors(SchemaValidator().validate_compiled(schema))] + + @staticmethod + def _base(role_permissions, *, schema_version="1.1"): + """Build a document with the library permissions and a ``library_author`` role granting the given ones.""" + return make_document( + "base", + schema_version=schema_version, + categories=[category("cat")], + permissions=LIBRARY_PERMISSIONS, + roles=[role(rid="library_author", scopes=("lib",), permissions=role_permissions)], + ) + + def test_role_with_every_dependency_passes(self): + """Listing direct and indirect dependencies satisfies the rule.""" + assert not self._messages(self._base((LIB_VIEW, LIB_EDIT, LIB_TAGS))) + + def test_role_missing_a_direct_dependency_is_error(self): + """A role cannot grant a permission without the permissions it depends on.""" + messages = self._messages(self._base((LIB_EDIT,))) + + assert messages == [ + f"Role library_author grants permission '{LIB_EDIT}' without its dependencies ['{LIB_VIEW}']. " + "Add them to the role, or keep role_extensions from removing them." + ] + + def test_role_missing_an_indirect_dependency_is_error(self): + """Indirect dependencies count: ``manage_library_tags`` also needs ``view_library``.""" + messages = self._messages(self._base((LIB_EDIT, LIB_TAGS))) + + assert len(messages) == 2 + assert all(f"['{LIB_VIEW}']" in message for message in messages) + + def test_extension_that_adds_a_permission_without_its_dependencies_is_error(self): + """An extension's additions are checked against the role's resolved permissions.""" + ext = make_document( + "ext", priority=200, role_extensions=[extension("library_author", add_permissions=(LIB_TAGS,))] + ) + + messages = self._messages(self._base((LIB_VIEW,)), ext) + + assert len(messages) == 1 + assert f"'{LIB_TAGS}' without its dependencies ['{LIB_EDIT}']" in messages[0] + + def test_extension_that_adds_the_dependencies_too_passes(self): + """An extension can satisfy the rule by adding the dependencies it needs.""" + ext = make_document( + "ext", priority=200, role_extensions=[extension("library_author", add_permissions=(LIB_EDIT, LIB_TAGS))] + ) + + assert not self._messages(self._base((LIB_VIEW,)), ext) + + def test_extension_cannot_remove_a_dependency_another_permission_needs(self): + """``remove_permissions`` cannot drop ``view_library`` while the role keeps ``edit_library_content``.""" + ext = make_document( + "ext", priority=200, role_extensions=[extension("library_author", remove_permissions=(LIB_VIEW,))] + ) + + messages = self._messages(self._base((LIB_VIEW, LIB_EDIT)), ext) + + assert len(messages) == 1 + assert f"'{LIB_EDIT}' without its dependencies ['{LIB_VIEW}']" in messages[0] + + def test_extension_that_removes_a_permission_and_its_dependents_passes(self): + """Removing a dependency together with every permission that needs it keeps the role complete.""" + ext = make_document( + "ext", priority=200, role_extensions=[extension("library_author", remove_permissions=(LIB_VIEW, LIB_EDIT))] + ) + + assert not self._messages(self._base((LIB_VIEW, LIB_EDIT)), ext) + + def test_1_0_role_file_is_checked_against_dependencies_from_a_1_1_file(self): + """The rule applies to roles in every file, whatever ``schema_version`` it declares.""" + permissions = make_document( + "permissions", schema_version="1.1", categories=[category("cat")], permissions=LIBRARY_PERMISSIONS + ) + roles = make_document( + "roles", + schema_version="1.0", + roles=[role(rid="library_author", scopes=("lib",), permissions=(LIB_EDIT,))], + ) + + messages = self._messages(permissions, roles) + + assert len(messages) == 1 + assert f"'{LIB_EDIT}' without its dependencies ['{LIB_VIEW}']" in messages[0] + + def test_error_names_the_file_that_grants_the_permission(self): + """The issue points at the file that grants the incomplete permission, here an extension.""" + ext = make_document( + "ext", priority=200, role_extensions=[extension("library_author", add_permissions=(LIB_TAGS,))] + ) + + issues = _errors(SchemaValidator().validate_compiled(SchemaCompiler().compile([self._base((LIB_VIEW,)), ext]))) + + assert [i.source_id for i in issues] == [make_source("ext").source_id] + + def test_hidden_role_is_checked_too(self): + """Hiding a role does not change what it grants, so the rule still applies.""" + document = make_document( + "base", + schema_version="1.1", + categories=[category("cat")], + permissions=LIBRARY_PERMISSIONS, + roles=[role(rid="library_author", scopes=("lib",), permissions=(LIB_EDIT,), hidden=True)], + ) + + assert self._messages(document) == [ + f"Role library_author grants permission '{LIB_EDIT}' without its dependencies ['{LIB_VIEW}']. " + "Add them to the role, or keep role_extensions from removing them." + ] + + +class TestVisibleDependencyRule: + """A visible permission cannot depend on a hidden one (ADR 0038).""" + + @staticmethod + def _issues(permissions, categories=(category("cat"), category("internal", hidden=True))): + """Compile one 1.1 document with the given permissions and return the errors in the compiled schema.""" + document = make_document("base", schema_version="1.1", categories=list(categories), permissions=permissions) + return _errors(SchemaValidator().validate_compiled(SchemaCompiler().compile([document]))) + + def test_visible_permission_depending_on_hidden_permission_is_error(self): + """A visible permission cannot depend on a permission that sets ``hidden: true``.""" + issues = self._issues( + [ + permission("content_libraries", "view_library", scopes=("lib",), hidden=True), + lib_permission("edit_library_content", depends_on=(LIB_VIEW,)), + ] + ) + + assert [i.message for i in issues] == [ + f"Visible permission {LIB_EDIT} depends on hidden permission(s) ['{LIB_VIEW}']. " + "Hide the permission too, or make its dependencies visible." + ] + assert issues[0].source_id == make_source("base").source_id + + def test_dependency_in_hidden_category_is_error(self): + """A visible permission cannot depend on a permission whose category is hidden.""" + issues = self._issues( + [ + permission("content_libraries", "view_library", cat="internal", scopes=("lib",)), + lib_permission("edit_library_content", depends_on=(LIB_VIEW,)), + ] + ) + + assert len(issues) == 1 + assert f"['{LIB_VIEW}']" in issues[0].message + + def test_indirect_hidden_dependency_is_reported_on_the_direct_dependent(self): + """In ``tags -> edit -> view (hidden)``, only ``edit`` directly depends on the hidden permission.""" + issues = self._issues( + [ + permission("content_libraries", "view_library", scopes=("lib",), hidden=True), + lib_permission("edit_library_content", depends_on=(LIB_VIEW,)), + lib_permission("manage_library_tags", depends_on=(LIB_EDIT,)), + ] + ) + + assert len(issues) == 1 + assert issues[0].message.startswith(f"Visible permission {LIB_EDIT} ") + + def test_hidden_permission_may_depend_on_hidden_or_visible_permissions(self): + """Only visible permissions are constrained.""" + assert not self._issues( + [ + lib_permission("view_library"), + permission( + "content_libraries", "edit_library_content", scopes=("lib",), hidden=True, depends_on=(LIB_VIEW,) + ), + permission( + "content_libraries", "manage_library_tags", cat="internal", scopes=("lib",), depends_on=(LIB_EDIT,) + ), + ] + ) + + class TestIconRules: """ADR 0017 §4: icon names must be valid @openedx/paragon/icons names."""