diff --git a/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py b/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py index 228fac2fb737..55a042307aef 100644 --- a/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py +++ b/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py @@ -4,21 +4,19 @@ import json from unittest.mock import patch -import casbin import ddt -import pkg_resources from django.test import override_settings from django.urls import reverse from milestones.tests.utils import MilestonesTestCaseMixin from openedx_authz.api.users import assign_role_to_user_in_scope from openedx_authz.constants.roles import COURSE_AUDITOR, COURSE_EDITOR, COURSE_STAFF from openedx_authz.engine.enforcer import AuthzEnforcer -from openedx_authz.engine.utils import migrate_policy_between_enforcers from rest_framework.test import APIClient from cms.djangoapps.contentstore.tests.utils import CourseTestCase from common.djangoapps.student.tests.factories import UserFactory from openedx.core import toggles as core_toggles +from openedx.core.djangoapps.authz.tests.fixtures import seed_policies @ddt.ddt @@ -114,7 +112,7 @@ class AdvancedSettingsAuthzTest(CourseTestCase): def setUp(self): super().setUp() - self._seed_database_with_policies() + seed_policies() self.url = reverse( "cms.djangoapps.contentstore:v0:course_advanced_settings", kwargs={"course_id": self.course.id}, @@ -142,18 +140,6 @@ def tearDown(self): super().tearDown() AuthzEnforcer.get_enforcer().clear_policy() - @classmethod - def _seed_database_with_policies(cls): - """Seed the database with policies from the policy file.""" - global_enforcer = AuthzEnforcer.get_enforcer() - global_enforcer.load_policy() - model_path = pkg_resources.resource_filename("openedx_authz.engine", "config/model.conf") - policy_path = pkg_resources.resource_filename("openedx_authz.engine", "config/authz.policy") - migrate_policy_between_enforcers( - source_enforcer=casbin.Enforcer(model_path, policy_path), - target_enforcer=global_enforcer, - ) - def test_authorized_for_specific_course(self, mock_flag): """User authorized for specific course can access.""" response = self.authorized_client.get(self.url) diff --git a/common/djangoapps/student/tests/test_roles.py b/common/djangoapps/student/tests/test_roles.py index 658192b5af41..1ec3e248177f 100644 --- a/common/djangoapps/student/tests/test_roles.py +++ b/common/djangoapps/student/tests/test_roles.py @@ -55,6 +55,7 @@ ) from common.djangoapps.student.tests.factories import AnonymousUserFactory, InstructorFactory, StaffFactory, UserFactory from lms.djangoapps.instructor import permissions as instructor_permissions +from openedx.core.djangoapps.authz.tests.fixtures import seed_policies from openedx.core.djangoapps.content.course_overviews.tests.factories import CourseOverviewFactory from openedx.core.toggles import AUTHZ_COURSE_AUTHORING_FLAG @@ -67,7 +68,8 @@ class RolesTestCase(TestCase): def setUp(self): super().setUp() - self._seed_database_with_policies() + seed_policies() + AuthzEnforcer.get_enforcer().clear_policy() # Clear to simulate fresh start for each test self.course_key = CourseKey.from_string('course-v1:course-v1:edX+toy+2012_Fall') self.course_loc = self.course_key.make_usage_key('course', '2012_Fall') self.course = CourseOverviewFactory.create(id=self.course_key) @@ -78,28 +80,6 @@ def setUp(self): self.course_instructor = InstructorFactory(course_key=self.course_key) self.orgs = ["Marvel", "DC"] - @classmethod - def _seed_database_with_policies(cls): - """Seed the database with policies from the policy file for openedx_authz tests. - - This simulates the one-time database seeding that would happen - during application deployment, separate from the runtime policy loading. - """ - import casbin - import pkg_resources - from openedx_authz.engine.utils import migrate_policy_between_enforcers - - global_enforcer = AuthzEnforcer.get_enforcer() - global_enforcer.load_policy() - model_path = pkg_resources.resource_filename("openedx_authz.engine", "config/model.conf") - policy_path = pkg_resources.resource_filename("openedx_authz.engine", "config/authz.policy") - - migrate_policy_between_enforcers( - source_enforcer=casbin.Enforcer(model_path, policy_path), - target_enforcer=global_enforcer, - ) - global_enforcer.clear_policy() # Clear to simulate fresh start for each test - @ddt.data(True, False) def test_global_staff(self, authz_enabled): with override_waffle_flag(AUTHZ_COURSE_AUTHORING_FLAG, active=authz_enabled): diff --git a/lms/djangoapps/instructor/authz/README.rst b/lms/djangoapps/instructor/authz/README.rst new file mode 100644 index 000000000000..5fb450d5ef1a --- /dev/null +++ b/lms/djangoapps/instructor/authz/README.rst @@ -0,0 +1,126 @@ +Instructor Dashboard AuthZ +########################## + +Integration of the Instructor Dashboard (``/api/instructor/v2``) with ``openedx-authz``. + +What it contains +**************** + +- ``constants.py``: groups of permission identifiers (all the dashboard permissions, and the ones of each tab). The permissions themselves come from the ``constants`` module of each ``openedx_authz.applets`` package; use their ``.identifier`` and do not repeat the strings in the code. +- ``api.py``: ``user_has_instructor_permission`` and ``user_has_any_instructor_permission``. +- ``permissions.py``: ``InstructorAuthzPermission``, the DRF permission class for the views. +- ``legacy.py``: the pre-AuthZ check equivalent to each permission. +- ``compat.py``: the legacy roles that keep their legacy access with AuthZ enabled. +- ``tests/mixins.py``: ``InstructorAuthzTestMixin`` to assign AuthZ roles in tests. + +Behavior +******** + +It is driven by the ``authz.enable_course_authoring`` waffle flag, evaluated per course, with the same semantics as Studio: + +- **Flag enabled:** only AuthZ is consulted. Legacy roles are ignored (openedx-authz already grants the global staff and superuser bypass). +- **Flag disabled:** only the legacy check runs, so the previous behavior is unchanged. + +The exception are the legacy roles that openedx-authz maps without dashboard permissions (``course_limited_staff``, ``course_data_researcher`` and ``course_beta_tester``). They only hold a compatibility permission (``courses.legacy_*_permissions``), so with the flag enabled, when AuthZ denies, they are evaluated with the legacy check, the same one used with the flag disabled. They keep exactly the access their legacy role had. To cover another legacy role, add its compatibility permission to ``LEGACY_ROLE_COMPAT_PERMISSIONS`` in ``compat.py``. ``course_admin`` and ``course_staff`` are not in it: they hold dashboard permissions, so a denial is final. + +Every decision is logged with the path that resolved it (``authz`` or ``legacy``) in ``access_path``. + +Migrating a view +**************** + +Replace ``InstructorPermission`` by ``InstructorAuthzPermission`` and declare the AuthZ permission next to the legacy one. ``course_id`` must be a URL kwarg: the permission class reads it from ``view.kwargs`` and returns a ``404`` if it is not a valid course key. Pick the case that matches the view: + +Case 1: Same permissions for every HTTP method +============================================== + +``authz_permissions`` is always a collection, like ``permission_classes``, even for a single permission. Unlike ``permission_classes``, where all the classes must pass (AND), holding **any one** of the permissions is enough (OR). Declare it with the legacy bridgekeeper permission the view already used: + +.. code-block:: python + + from openedx_authz.applets.enrollments.constants import COURSES_VIEW_ENROLLMENTS + from lms.djangoapps.instructor.authz import constants as authz_constants + from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission + + class MyView(APIView): + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = (COURSES_VIEW_ENROLLMENTS.identifier,) + # The legacy bridgekeeper permission. + permission_name = permissions.VIEW_ENROLLMENTS + +A bare string raises ``ImproperlyConfigured``. With several permissions and ``authz.enable_course_authoring`` disabled for the course, the legacy check of the view decides, evaluated once: + +.. code-block:: python + + class MyView(APIView): + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = authz_constants.INSTRUCTOR_DASHBOARD_PERMISSIONS + permission_name = permissions.VIEW_DASHBOARD + +Case 2: Different permissions per HTTP method +============================================= + +Use a mapping when reading and changing need different permissions. Each value is a collection of permissions. A method missing from the mapping is denied (``403``) with ``authz.enable_course_authoring`` enabled for the course, so a method is never left on the legacy rule by mistake. With it disabled, the legacy check decides as usual: + +.. code-block:: python + + class MyView(APIView): + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = { + "GET": (COURSES_VIEW_ENROLLMENTS.identifier,), + "POST": (COURSES_ENROLL_LEARNERS.identifier,), + } + permission_name = permissions.CAN_ENROLL + +Case 3: Legacy rule that is not a bridgekeeper permission +========================================================= + +Define ``legacy_permission_check(user, course_key)`` on the view. It replaces ``permission_name`` and receives the same arguments for every method. Reuse the checks of ``legacy.py`` when one matches: + +.. code-block:: python + + from lms.djangoapps.instructor.authz import legacy as authz_legacy + + class MyView(APIView): + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = { + "GET": (COURSES_VIEW_COHORTS.identifier,), + "POST": (COURSES_MANAGE_COHORTS.identifier,), + } + + @staticmethod + def legacy_permission_check(user, course_key): + return authz_legacy.has_cohort_manage_access(user, course_key) + +Without ``@staticmethod`` the method would receive ``self`` as the first argument. The legacy check does not receive the request, so it cannot vary by HTTP method. If the legacy rule differs per method, call ``user_has_instructor_permission`` in the handler with the legacy check of each case. + +Checking a permission in other code +=================================== + +Use ``user_has_instructor_permission`` inside a handler, a serializer or any other code. The legacy check is optional and defaults to the one registered in ``legacy.LEGACY_PERMISSION_CHECKS``: + +.. code-block:: python + + from opaque_keys.edx.keys import CourseKey + from lms.djangoapps.instructor.authz.api import user_has_instructor_permission + + def post(self, request, course_id): + course_key = CourseKey.from_string(course_id) + if user_has_instructor_permission(request.user, COURSES_MANAGE_COHORTS.identifier, course_key): + ... + + # With an explicit legacy check, used only when ``authz.enable_course_authoring`` is disabled. + user_has_instructor_permission( + request.user, + COURSES_VIEW_ENROLLMENTS.identifier, + course_key, + authz_legacy.has_instructor_access, + ) + +``CourseMetadataView`` returns ``authz_enabled``, whether AuthZ is enabled for the course. The MFE passes it as ``featureEnabled`` to the shared ``usePermissions`` hook of ``frontend-base``, so it checks the permissions through AuthZ only when it is enabled. + +Errors +====== + +- No ``authz_permissions`` on the view, or a bare string instead of a collection: ``ImproperlyConfigured``. +- Invalid ``course_id``: ``404``. +- Denied by the active path (AuthZ with ``authz.enable_course_authoring`` enabled, legacy otherwise): ``403``. diff --git a/lms/djangoapps/instructor/authz/__init__.py b/lms/djangoapps/instructor/authz/__init__.py new file mode 100644 index 000000000000..7e55aa23848e --- /dev/null +++ b/lms/djangoapps/instructor/authz/__init__.py @@ -0,0 +1,3 @@ +""" +AuthZ integration for the Instructor Dashboard. +""" diff --git a/lms/djangoapps/instructor/authz/api.py b/lms/djangoapps/instructor/authz/api.py new file mode 100644 index 000000000000..8d06a6febca5 --- /dev/null +++ b/lms/djangoapps/instructor/authz/api.py @@ -0,0 +1,146 @@ +""" +Public API to enforce AuthZ permissions in the Instructor Dashboard. + +When the ``authz.enable_course_authoring`` flag is enabled for a course, the +permission is resolved exclusively through AuthZ (same semantics as Studio, see +``openedx.core.djangoapps.authz.decorators``). When it is disabled, the legacy +check is used, so the pre-AuthZ behavior is preserved. + +The legacy roles that AuthZ maps without dashboard permissions are the exception, +see ``compat.py``: with AuthZ enabled they are evaluated with the legacy check. +""" + +import logging +from collections.abc import Callable, Iterable + +from django.contrib.auth.models import AbstractUser +from opaque_keys.edx.keys import CourseKey +from openedx_authz import api as authz_api + +from common.djangoapps.student.roles import enable_authz_course_authoring +from lms.djangoapps.instructor.authz.compat import holds_legacy_role_compat_permission +from lms.djangoapps.instructor.authz.legacy import LEGACY_PERMISSION_CHECKS + +log = logging.getLogger(__name__) + +# Signature of a legacy check: ``(user, course_key) -> bool``. +LegacyCheck = Callable[[AbstractUser, CourseKey], bool] + +ACCESS_PATH_AUTHZ = "authz" +ACCESS_PATH_LEGACY = "legacy" + + +def user_has_instructor_permission( + user: AbstractUser, + authz_permission: str, + course_key: CourseKey, + legacy_check: LegacyCheck | None = None, +) -> bool: + """ + Return whether the user holds an AuthZ permission in the course. + + When ``authz.enable_course_authoring`` is enabled for the course, only AuthZ + is consulted and legacy roles are ignored, except those of ``compat.py``, which + fall back to the legacy check when AuthZ denies. When it is disabled, only the + legacy check is evaluated. The path that resolved the check (``authz`` or + ``legacy``) is logged. + + Args: + user (AbstractUser): The user whose access is checked. + authz_permission (str): The AuthZ permission identifier, e.g. + ``courses.view_enrollments``. + course_key (CourseKey): The course where the permission is checked. + legacy_check (LegacyCheck | None): The pre-AuthZ check, used only when + AuthZ is disabled for the course. If omitted, the default one + registered for ``authz_permission`` in ``LEGACY_PERMISSION_CHECKS`` + is used, and a permission without any legacy check is denied. + + Returns: + bool: True if the user holds the permission. + """ + if enable_authz_course_authoring(course_key): + is_allowed = authz_api.is_user_allowed(user.username, authz_permission, str(course_key)) + if is_allowed or not holds_legacy_role_compat_permission(user, course_key): + _log_decision(ACCESS_PATH_AUTHZ, is_allowed, user, (authz_permission,), course_key) + return is_allowed + + legacy_check = legacy_check or LEGACY_PERMISSION_CHECKS.get(authz_permission) + is_allowed = bool(legacy_check and legacy_check(user, course_key)) + _log_decision(ACCESS_PATH_LEGACY, is_allowed, user, (authz_permission,), course_key) + return is_allowed + + +def user_has_any_instructor_permission( + user: AbstractUser, + authz_permissions: Iterable[str], + course_key: CourseKey, + legacy_check: LegacyCheck | None = None, +) -> bool: + """ + Return whether the user holds at least one of the AuthZ permissions. + + An empty collection grants no access. + + It is meant for the visibility of a tab, which is shown when the user can do + anything in it, not only a specific action. With ``authz.enable_course_authoring`` + enabled for the course, only AuthZ is consulted, except for the legacy roles of + ``compat.py``. With it disabled, ``legacy_check`` is used if given; otherwise the + default legacy check of each permission is tried. + + Args: + user (AbstractUser): The user whose access is checked. + authz_permissions (Iterable[str]): The AuthZ permission identifiers, any + of which grants access. + course_key (CourseKey): The course where the permissions are checked. + legacy_check (LegacyCheck | None): The pre-AuthZ check of the whole set, + used when AuthZ is disabled for the course, and for the legacy roles of ``compat.py``. + + Returns: + bool: True if the user holds at least one of the permissions. + """ + permissions = tuple(authz_permissions) + if not permissions: + return False + + if enable_authz_course_authoring(course_key): + course_id = str(course_key) + if any(authz_api.is_user_allowed(user.username, p, course_id) for p in permissions): + _log_decision(ACCESS_PATH_AUTHZ, True, user, permissions, course_key) + return True + if not holds_legacy_role_compat_permission(user, course_key): + _log_decision(ACCESS_PATH_AUTHZ, False, user, permissions, course_key) + return False + + if legacy_check is not None: + # The legacy check covers the whole set: run and log it once. + is_allowed = bool(legacy_check(user, course_key)) + _log_decision(ACCESS_PATH_LEGACY, is_allowed, user, permissions, course_key) + return is_allowed + + return any(user_has_instructor_permission(user, p, course_key) for p in permissions) + + +def _log_decision( + path: str, is_allowed: bool, user: AbstractUser, authz_permissions: Iterable[str], course_key: CourseKey +): + """ + Log the path that resolved a permission check, and its outcome. + + Args: + path (str): The path that resolved the check. + is_allowed (bool): Whether access was granted. + user (AbstractUser): The user checked. + authz_permissions (Iterable[str]): The AuthZ permission identifiers checked. + course_key (CourseKey): The course where it was checked. + """ + log.debug( + "Instructor dashboard permission %s via %s", + "granted" if is_allowed else "denied", + path, + extra={ + "user_id": user.id, + "authz_permissions": list(authz_permissions), + "course_key": str(course_key), + "access_path": path, + }, + ) diff --git a/lms/djangoapps/instructor/authz/compat.py b/lms/djangoapps/instructor/authz/compat.py new file mode 100644 index 000000000000..c550ee2956c4 --- /dev/null +++ b/lms/djangoapps/instructor/authz/compat.py @@ -0,0 +1,47 @@ +""" +Compatibility of the legacy course roles with the AuthZ enforcement of the Instructor Dashboard. + +openedx-authz maps some legacy course roles to AuthZ roles that hold no Instructor +Dashboard permission, only a compatibility permission (``courses.legacy_*_permissions``) +that stands for the legacy role. Before AuthZ those roles had the access their legacy +rules gave them, so enforcing only the dashboard permissions would take it away. + +A user that holds one of these compatibility permissions is evaluated with the legacy +check, as if ``authz.enable_course_authoring`` was disabled, when AuthZ denies the +dashboard permissions. The legacy rule decides, so the user keeps exactly the access +the legacy role had. +""" + +from django.contrib.auth.models import AbstractUser +from opaque_keys.edx.keys import CourseKey +from openedx_authz import api as authz_api +from openedx_authz.applets.course_team_roles.constants import ( + COURSES_LEGACY_BETA_TESTER_PERMISSIONS, + COURSES_LEGACY_DATA_RESEARCHER_PERMISSIONS, + COURSES_LEGACY_LIMITED_STAFF_ROLE_PERMISSIONS, +) + +# Compatibility permission of each legacy role that keeps its legacy access with AuthZ. +# Add the one of a legacy role here when openedx-authz maps it without dashboard permissions. +LEGACY_ROLE_COMPAT_PERMISSIONS = ( + COURSES_LEGACY_LIMITED_STAFF_ROLE_PERMISSIONS.identifier, + COURSES_LEGACY_DATA_RESEARCHER_PERMISSIONS.identifier, + COURSES_LEGACY_BETA_TESTER_PERMISSIONS.identifier, +) + + +def holds_legacy_role_compat_permission(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Return whether the user holds the compatibility permission of a legacy role. + + Args: + user (AbstractUser): The user whose access is checked. + course_key (CourseKey): The course where the permission is checked. + + Returns: + bool: True if the user holds at least one of ``LEGACY_ROLE_COMPAT_PERMISSIONS``. + """ + return any( + authz_api.is_user_allowed(user.username, permission, str(course_key)) + for permission in LEGACY_ROLE_COMPAT_PERMISSIONS + ) diff --git a/lms/djangoapps/instructor/authz/constants.py b/lms/djangoapps/instructor/authz/constants.py new file mode 100644 index 000000000000..12532455c5e5 --- /dev/null +++ b/lms/djangoapps/instructor/authz/constants.py @@ -0,0 +1,71 @@ +""" +AuthZ permission identifiers used by the Instructor Dashboard. + +The permissions are defined by openedx-authz (``openedx_authz.applets.*.constants``); +use them directly (``COURSES_VIEW_COURSE_INFO.identifier``). This module +only groups their identifiers. +""" + +from openedx_authz.applets.enrollments.constants import ( + COURSES_ENROLL_LEARNERS, + COURSES_UNENROLL_LEARNERS, + COURSES_VIEW_ENROLLMENTS, +) +from openedx_authz.applets.learner_administration.constants import ( + COURSES_MANAGE_COHORTS, + COURSES_MANAGE_LEARNER_EXTENSIONS, + COURSES_VIEW_COHORTS, + COURSES_VIEW_COURSE_INFO, + COURSES_VIEW_LEARNER_EXTENSIONS, +) +from openedx_authz.applets.learner_grading.constants import COURSES_MANAGE_LEARNER_GRADING, COURSES_VIEW_GRADEBOOK +from openedx_authz.authz import ( + COURSES_MANAGE_COURSE_TEAM, + COURSES_VIEW_COURSE_TEAM, + COURSES_VIEW_GRADING_SETTINGS, +) + +# Every permission of the Instructor Dashboard. Holding any of them grants access +# to the dashboard. +INSTRUCTOR_DASHBOARD_PERMISSIONS = ( + COURSES_VIEW_COURSE_INFO.identifier, + COURSES_VIEW_ENROLLMENTS.identifier, + COURSES_ENROLL_LEARNERS.identifier, + COURSES_UNENROLL_LEARNERS.identifier, + COURSES_VIEW_COURSE_TEAM.identifier, + COURSES_MANAGE_COURSE_TEAM.identifier, + COURSES_VIEW_GRADEBOOK.identifier, + COURSES_VIEW_GRADING_SETTINGS.identifier, + COURSES_MANAGE_LEARNER_GRADING.identifier, + COURSES_VIEW_LEARNER_EXTENSIONS.identifier, + COURSES_MANAGE_LEARNER_EXTENSIONS.identifier, + COURSES_VIEW_COHORTS.identifier, + COURSES_MANAGE_COHORTS.identifier, +) + +# Permissions that give access to each tab of the dashboard. A tab is shown when +# the user holds at least one of them, not a specific one. +TAB_PERMISSIONS = { + "course_info": (COURSES_VIEW_COURSE_INFO.identifier,), + "enrollments": ( + COURSES_VIEW_ENROLLMENTS.identifier, + COURSES_ENROLL_LEARNERS.identifier, + COURSES_UNENROLL_LEARNERS.identifier, + # Included because the tab manages the beta testers. + COURSES_MANAGE_COURSE_TEAM.identifier, + ), + "course_team": ( + COURSES_VIEW_COURSE_TEAM.identifier, + COURSES_MANAGE_COURSE_TEAM.identifier, + ), + "grading": ( + COURSES_VIEW_GRADEBOOK.identifier, + COURSES_VIEW_GRADING_SETTINGS.identifier, + COURSES_MANAGE_LEARNER_GRADING.identifier, + ), + "date_extensions": ( + COURSES_VIEW_LEARNER_EXTENSIONS.identifier, + COURSES_MANAGE_LEARNER_EXTENSIONS.identifier, + ), + "cohorts": (COURSES_VIEW_COHORTS.identifier, COURSES_MANAGE_COHORTS.identifier), +} diff --git a/lms/djangoapps/instructor/authz/legacy.py b/lms/djangoapps/instructor/authz/legacy.py new file mode 100644 index 000000000000..f0e564376854 --- /dev/null +++ b/lms/djangoapps/instructor/authz/legacy.py @@ -0,0 +1,205 @@ +""" +Legacy (pre-AuthZ) checks of the Instructor Dashboard AuthZ permissions. + +They are evaluated only when ``authz.enable_course_authoring`` is disabled for +the course, and must keep mirroring the behavior the dashboard had before AuthZ. +Each check has the ``(user, course_key) -> bool`` signature. +""" + +from django.contrib.auth.models import AbstractUser +from opaque_keys.edx.keys import CourseKey +from openedx_authz.applets.enrollments.constants import ( + COURSES_ENROLL_LEARNERS, + COURSES_UNENROLL_LEARNERS, + COURSES_VIEW_ENROLLMENTS, +) +from openedx_authz.applets.learner_administration.constants import ( + COURSES_MANAGE_COHORTS, + COURSES_MANAGE_LEARNER_EXTENSIONS, + COURSES_VIEW_COHORTS, + COURSES_VIEW_COURSE_INFO, + COURSES_VIEW_LEARNER_EXTENSIONS, +) +from openedx_authz.applets.learner_grading.constants import COURSES_MANAGE_LEARNER_GRADING, COURSES_VIEW_GRADEBOOK +from openedx_authz.authz import ( + COURSES_MANAGE_COURSE_TEAM, + COURSES_VIEW_COURSE_TEAM, + COURSES_VIEW_GRADING_SETTINGS, +) + +from common.djangoapps.student.auth import has_course_author_access, has_studio_read_access +from common.djangoapps.student.roles import GlobalStaff +from lms.djangoapps.courseware.access import administrative_accesses_to_course_for_user, has_access +from lms.djangoapps.discussion.django_comment_client.utils import get_user_role_names, has_forum_access +from lms.djangoapps.instructor import permissions +from openedx.core.djangoapps.django_comment_common.models import ( + FORUM_ROLE_ADMINISTRATOR, + FORUM_ROLE_COMMUNITY_TA, + FORUM_ROLE_MODERATOR, +) + + +def has_staff_access(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Check whether the user has course staff access. + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. + + Returns: + bool: True for course staff, course instructors and global staff. + """ + return bool(has_access(user, "staff", course_key)) + + +def has_instructor_access(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Check whether the user has course instructor access. + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. + + Returns: + bool: True for course instructors and global staff. + """ + return bool(has_access(user, "instructor", course_key)) + + +def has_course_team_access(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Check the access to the course team. + + It follows the same rule as ``CourseTeamPermission`` + (``lms.djangoapps.instructor.permissions``). + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. + + Returns: + bool: True with instructor access, or with staff access plus the forum + Administrator role. + """ + return has_instructor_access(user, course_key) or ( + has_staff_access(user, course_key) and has_forum_access(user, course_key, FORUM_ROLE_ADMINISTRATOR) + ) + + +def has_cohort_manage_access(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Check the legacy access to change cohorts. + + It applies to any non-GET request of the cohorts API and uses the same rule + as ``IsStaffOrAdmin`` (``openedx.core.djangoapps.course_groups.permissions``) + for those requests. + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. + + Returns: + bool: True for global staff, superusers, course staff and course + instructors. + """ + if GlobalStaff().has_user(user) or user.is_superuser: + return True + _, staff_access, instructor_access = administrative_accesses_to_course_for_user(user, course_key) + return bool(staff_access or instructor_access) + + +def has_cohort_view_access(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Check the legacy access to read cohorts (GET requests of the cohorts API). + + It uses the same rule as ``IsStaffOrAdmin`` + (``openedx.core.djangoapps.course_groups.permissions``) for GET requests. + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. + + Returns: + bool: True for everyone who can manage cohorts, plus the forum + Administrator, Moderator and Community TA roles. + """ + if has_cohort_manage_access(user, course_key): + return True + return bool( + get_user_role_names(user, course_key) + & {FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA} + ) + + +def has_gradebook_access(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Check the legacy access to the gradebook. + + It follows the same rule as the gradebook API (``course_author_access_required``). + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. + + Returns: + bool: True with course author (Studio write) access. + """ + return bool(has_course_author_access(user, course_key)) + + +def has_grading_settings_access(user: AbstractUser, course_key: CourseKey) -> bool: + """ + Check the legacy access to the grading settings. + + It follows the same rule as the Studio grading settings (``grading_handler``). + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. + + Returns: + bool: True with Studio read access. + """ + return bool(has_studio_read_access(user, course_key)) + + +def bridgekeeper_check(permission_name: str): + """ + Build a legacy check from a ``bridgekeeper`` permission. + + The permissions are those of ``lms.djangoapps.instructor.permissions``. + + Args: + permission_name (str): The bridgekeeper permission, e.g. + ``instructor.view_enrollments``. + + Returns: + Callable[[AbstractUser, CourseKey], bool]: A check that evaluates the + permission against the course. + """ + + def _check(user: AbstractUser, course_key: CourseKey) -> bool: + return user.has_perm(permission_name, course_key) + + return _check + + +# Default legacy check of every permission, as used for the tab visibility and +# ``authz_permissions``. Endpoints whose legacy rule differs (e.g. beta testers, +# which need instructor access) pass their own check. +LEGACY_PERMISSION_CHECKS = { + COURSES_VIEW_COURSE_INFO.identifier: bridgekeeper_check(permissions.VIEW_DASHBOARD), + COURSES_VIEW_ENROLLMENTS.identifier: bridgekeeper_check(permissions.VIEW_ENROLLMENTS), + COURSES_ENROLL_LEARNERS.identifier: bridgekeeper_check(permissions.CAN_ENROLL), + COURSES_UNENROLL_LEARNERS.identifier: bridgekeeper_check(permissions.CAN_ENROLL), + COURSES_VIEW_COURSE_TEAM.identifier: has_course_team_access, + COURSES_MANAGE_COURSE_TEAM.identifier: has_course_team_access, + COURSES_VIEW_GRADEBOOK.identifier: has_gradebook_access, + COURSES_VIEW_GRADING_SETTINGS.identifier: has_grading_settings_access, + COURSES_MANAGE_LEARNER_GRADING.identifier: bridgekeeper_check(permissions.OVERRIDE_GRADES), + COURSES_VIEW_LEARNER_EXTENSIONS.identifier: bridgekeeper_check(permissions.VIEW_DASHBOARD), + COURSES_MANAGE_LEARNER_EXTENSIONS.identifier: bridgekeeper_check(permissions.GIVE_STUDENT_EXTENSION), + COURSES_VIEW_COHORTS.identifier: has_cohort_view_access, + COURSES_MANAGE_COHORTS.identifier: has_cohort_manage_access, +} diff --git a/lms/djangoapps/instructor/authz/permissions.py b/lms/djangoapps/instructor/authz/permissions.py new file mode 100644 index 000000000000..f0dc8c4ae25b --- /dev/null +++ b/lms/djangoapps/instructor/authz/permissions.py @@ -0,0 +1,110 @@ +""" +DRF permission class to enforce AuthZ in the Instructor Dashboard views. +""" + +import logging +from collections.abc import Mapping + +from django.core.exceptions import ImproperlyConfigured +from django.http import Http404 +from opaque_keys import InvalidKeyError +from opaque_keys.edx.keys import CourseKey +from rest_framework.permissions import BasePermission + +from common.djangoapps.student.roles import enable_authz_course_authoring +from lms.djangoapps.instructor.authz.api import user_has_any_instructor_permission +from lms.djangoapps.instructor.authz.legacy import bridgekeeper_check + +log = logging.getLogger(__name__) + + +class InstructorAuthzPermission(BasePermission): + """ + Replacement of ``InstructorPermission`` for views migrated to AuthZ. + + It is a drop-in replacement of + ``lms.djangoapps.instructor.permissions.InstructorPermission``. + + With ``authz.enable_course_authoring`` enabled for the course only AuthZ is + consulted; legacy roles are ignored. + + Attributes expected in the view: + authz_permissions (Collection[str] | Mapping[str, Collection[str]]): + The AuthZ permission identifiers required, or a mapping of HTTP + method to them when the view needs different permissions per + method. It is always a collection, even for a single permission, + like ``permission_classes``. Unlike ``permission_classes``, where + all the classes must pass (AND), holding any one of the + permissions is enough (OR). Methods missing from the mapping are + denied with ``authz.enable_course_authoring`` enabled for the + course. + permission_name (str): The legacy ``bridgekeeper`` permission, the one + ``InstructorPermission`` uses. It is enforced when + ``authz.enable_course_authoring`` is disabled for the course. + legacy_permission_check (Callable[[User, CourseKey], bool]): Optional. + Replaces the ``permission_name`` check, for legacy rules that are + not a bridgekeeper permission. + """ + + def has_permission(self, request, view): + """ + Check whether the user holds the permission the view requires. + + Args: + request (Request): The DRF request. + view (APIView): The view, with ``authz_permissions`` and the legacy + permission attributes. + + Returns: + bool: True if access is granted. + + Raises: + Http404: If the ``course_id`` kwarg of the view is not a valid + course key. + ImproperlyConfigured: If the view does not define + ``authz_permissions``, or defines a bare string instead of a + collection. + """ + try: + course_key = CourseKey.from_string(view.kwargs.get("course_id")) + except InvalidKeyError as exc: + raise Http404("Invalid course key") from exc + + authz_permissions = getattr(view, "authz_permissions", None) + if authz_permissions is None: + raise ImproperlyConfigured(f"{type(view).__name__} must define 'authz_permissions'.") + _validate_authz_permissions(view, authz_permissions) + if isinstance(authz_permissions, Mapping): + authz_permissions = authz_permissions.get(request.method) + + legacy_check = getattr(view, "legacy_permission_check", None) + if legacy_check is None and getattr(view, "permission_name", None): + legacy_check = bridgekeeper_check(view.permission_name) + + if authz_permissions is None: + if enable_authz_course_authoring(course_key): + # Fail closed: a method without an AuthZ permission is never allowed by AuthZ. + log.warning( + "%s %s has no AuthZ permission, denying access", + type(view).__name__, + request.method, + extra={"course_key": str(course_key)}, + ) + return False + return bool(legacy_check and legacy_check(request.user, course_key)) + return user_has_any_instructor_permission(request.user, authz_permissions, course_key, legacy_check) + + +def _validate_authz_permissions(view, authz_permissions): + """ + Reject a bare string where a collection is expected. + + A string is iterable, so a forgotten comma in ``(PERMISSION)`` would be + read character by character instead of failing. + """ + values = authz_permissions.values() if isinstance(authz_permissions, Mapping) else (authz_permissions,) + if any(isinstance(value, str) for value in values): + raise ImproperlyConfigured( + f"{type(view).__name__}.authz_permissions must be a collection of permissions, " + "e.g. (PERMISSION,), not a string." + ) diff --git a/lms/djangoapps/instructor/authz/tests/__init__.py b/lms/djangoapps/instructor/authz/tests/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/lms/djangoapps/instructor/authz/tests/mixins.py b/lms/djangoapps/instructor/authz/tests/mixins.py new file mode 100644 index 000000000000..51005a514534 --- /dev/null +++ b/lms/djangoapps/instructor/authz/tests/mixins.py @@ -0,0 +1,32 @@ +""" +Test helpers to assign AuthZ roles in Instructor Dashboard tests. +""" + +from common.djangoapps.student.tests.factories import UserFactory +from openedx.core.djangoapps.authz.tests.mixins import AuthzTestMixin + + +class InstructorAuthzTestMixin(AuthzTestMixin): + """ + Mixin to test the Instructor Dashboard with the AuthZ flag on or off. + + By default the flag is enabled; call ``set_authz_enabled(False)`` to test + the legacy behavior. The enforcer is seeded with the static AuthZ schema, + which already grants the Instructor Dashboard permissions to the default roles. + """ + + def create_user_with_authz_role(self, role, course_key, **kwargs): + """ + Create a user and assign it an AuthZ role in the course. + + Args: + role (str): The AuthZ role external key. + course_key (CourseKey): The course where the role is assigned. + **kwargs: Extra arguments for ``UserFactory``. + + Returns: + User: The new user. + """ + user = UserFactory(**kwargs) + self.assign_authz_role(user, role, course_key) + return user diff --git a/lms/djangoapps/instructor/authz/tests/test_api.py b/lms/djangoapps/instructor/authz/tests/test_api.py new file mode 100644 index 000000000000..d44e293d3ad7 --- /dev/null +++ b/lms/djangoapps/instructor/authz/tests/test_api.py @@ -0,0 +1,208 @@ +""" +Tests for the Instructor Dashboard AuthZ API. +""" + +from unittest.mock import Mock, patch + +import ddt +from django.test import TestCase +from opaque_keys.edx.locator import CourseLocator +from openedx_authz.applets.course_team_roles.constants import COURSE_DATA_RESEARCHER, COURSE_LIMITED_STAFF +from openedx_authz.applets.enrollments.constants import COURSES_ENROLL_LEARNERS, COURSES_VIEW_ENROLLMENTS +from openedx_authz.applets.learner_administration.constants import COURSES_MANAGE_COHORTS, COURSES_VIEW_COURSE_INFO +from openedx_authz.applets.learner_grading.constants import COURSES_VIEW_GRADEBOOK +from openedx_authz.authz import COURSE_ADMIN, COURSE_AUDITOR, COURSE_STAFF, COURSES_MANAGE_COURSE_TEAM + +from common.djangoapps.student.tests.factories import UserFactory +from lms.djangoapps.instructor.authz.api import ( + user_has_any_instructor_permission, + user_has_instructor_permission, +) +from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin + +COURSE_KEY = CourseLocator("edX", "Demo", "2026") +API = "lms.djangoapps.instructor.authz.api" + + +@ddt.ddt +class UserHasInstructorPermissionTest(InstructorAuthzTestMixin, TestCase): + """ + Permissions use AuthZ with the flag on, and legacy checks otherwise. + """ + + def setUp(self): + super().setUp() + self.user = UserFactory() + + @ddt.data( + (COURSE_ADMIN.external_key, COURSES_VIEW_COURSE_INFO.identifier, True), + (COURSE_STAFF.external_key, COURSES_ENROLL_LEARNERS.identifier, True), + (COURSE_STAFF.external_key, COURSES_MANAGE_COHORTS.identifier, True), + (COURSE_ADMIN.external_key, COURSES_MANAGE_COURSE_TEAM.identifier, True), + # Course Staff must not get ``manage_course_team``. + (COURSE_STAFF.external_key, COURSES_MANAGE_COURSE_TEAM.identifier, False), + (COURSE_AUDITOR.external_key, COURSES_VIEW_ENROLLMENTS.identifier, False), + ) + @ddt.unpack + def test_flag_enabled_uses_authz(self, role, permission, expected): + """With the flag on, the result is the one of the AuthZ role of the user.""" + self.assign_authz_role(self.user, role, COURSE_KEY) + + assert user_has_instructor_permission(self.user, permission, COURSE_KEY) == expected + + @ddt.data(COURSE_LIMITED_STAFF.external_key, COURSE_DATA_RESEARCHER.external_key) + def test_flag_enabled_legacy_role_uses_legacy_check(self, role): + """With the flag on, a legacy role without dashboard permissions is decided by the legacy check.""" + self.assign_authz_role(self.user, role, COURSE_KEY) + + assert user_has_instructor_permission( + self.user, COURSES_VIEW_ENROLLMENTS.identifier, COURSE_KEY, Mock(return_value=True) + ) + assert not user_has_instructor_permission( + self.user, COURSES_VIEW_ENROLLMENTS.identifier, COURSE_KEY, Mock(return_value=False) + ) + + def test_any_permission_flag_enabled_legacy_role_uses_legacy_check_once(self): + """With the flag on, a collection is decided by the legacy check, evaluated once.""" + self.assign_authz_role(self.user, COURSE_LIMITED_STAFF.external_key, COURSE_KEY) + legacy_check = Mock(return_value=True) + + assert user_has_any_instructor_permission( + self.user, + (COURSES_VIEW_ENROLLMENTS.identifier, COURSES_VIEW_GRADEBOOK.identifier), + COURSE_KEY, + legacy_check, + ) + legacy_check.assert_called_once_with(self.user, COURSE_KEY) + + def test_flag_enabled_role_with_dashboard_permissions_ignores_legacy_check(self): + """With the flag on, a denial is final for a role that holds dashboard permissions.""" + self.assign_authz_role(self.user, COURSE_AUDITOR.external_key, COURSE_KEY) + legacy_check = Mock(return_value=True) + + assert not user_has_instructor_permission( + self.user, COURSES_MANAGE_COURSE_TEAM.identifier, COURSE_KEY, legacy_check + ) + legacy_check.assert_not_called() + + def test_flag_enabled_ignores_legacy_check(self): + """With the flag on, the legacy check is never called.""" + legacy_check = Mock(return_value=True) + + allowed = user_has_instructor_permission( + self.user, COURSES_VIEW_ENROLLMENTS.identifier, COURSE_KEY, legacy_check + ) + + assert not allowed + legacy_check.assert_not_called() + + def test_flag_disabled_ignores_authz(self): + """With the flag off, AuthZ roles are ignored and only the legacy check is called.""" + self.set_authz_enabled(False) + self.assign_authz_role(self.user, COURSE_ADMIN.external_key, COURSE_KEY) + legacy_check = Mock(return_value=False) + + allowed = user_has_instructor_permission( + self.user, COURSES_VIEW_ENROLLMENTS.identifier, COURSE_KEY, legacy_check + ) + + assert not allowed + legacy_check.assert_called_once_with(self.user, COURSE_KEY) + + @ddt.data(True, False) + def test_flag_disabled_returns_legacy_result(self, legacy_result): + """With the flag off, the result is the one of the legacy check.""" + self.set_authz_enabled(False) + + allowed = user_has_instructor_permission( + self.user, + COURSES_VIEW_ENROLLMENTS.identifier, + COURSE_KEY, + Mock(return_value=legacy_result), + ) + + assert allowed == legacy_result + + def test_flag_disabled_uses_default_legacy_check(self): + """With the flag off and no legacy check given, the one registered for the permission is used.""" + self.set_authz_enabled(False) + default_check = Mock(return_value=True) + + with patch.dict(f"{API}.LEGACY_PERMISSION_CHECKS", {COURSES_VIEW_GRADEBOOK.identifier: default_check}): + allowed = user_has_instructor_permission(self.user, COURSES_VIEW_GRADEBOOK.identifier, COURSE_KEY) + + assert allowed + default_check.assert_called_once_with(self.user, COURSE_KEY) + + def test_flag_disabled_without_legacy_check_denies(self): + """With the flag off, a permission without any legacy check is denied.""" + self.set_authz_enabled(False) + + assert not user_has_instructor_permission(self.user, "courses.unknown_permission", COURSE_KEY) + + def test_enabled_per_course(self): + """The flag is evaluated for the course being checked.""" + self.authz_flag_mock.side_effect = lambda course_key=None: course_key == COURSE_KEY + other_course = CourseLocator("edX", "Other", "2026") + self.assign_authz_role(self.user, COURSE_ADMIN.external_key, COURSE_KEY) + legacy_check = Mock(return_value=False) + + assert user_has_instructor_permission(self.user, COURSES_VIEW_ENROLLMENTS.identifier, COURSE_KEY, legacy_check) + assert not user_has_instructor_permission( + self.user, COURSES_VIEW_ENROLLMENTS.identifier, other_course, legacy_check + ) + + def test_logs_the_access_path(self): + """Each decision is logged with the path (``authz`` or ``legacy``) that resolved it.""" + self.assign_authz_role(self.user, COURSE_STAFF.external_key, COURSE_KEY) + + with self.assertLogs(API, level="DEBUG") as logs: + user_has_instructor_permission(self.user, COURSES_VIEW_ENROLLMENTS.identifier, COURSE_KEY) + self.set_authz_enabled(False) + user_has_instructor_permission(self.user, COURSES_VIEW_ENROLLMENTS.identifier, COURSE_KEY, lambda *_: True) + + assert [record.access_path for record in logs.records] == ["authz", "legacy"] + assert [record.getMessage() for record in logs.records] == [ + "Instructor dashboard permission granted via authz", + "Instructor dashboard permission granted via legacy", + ] + + def test_any_permission_flag_enabled(self): + """With the flag on, one granted permission of the set is enough.""" + self.set_authz_enabled(True) + with patch(f"{API}.authz_api.is_user_allowed", side_effect=lambda _u, perm, _s: perm == "b"): + assert user_has_any_instructor_permission(self.user, ["a", "b"], COURSE_KEY) + assert not user_has_any_instructor_permission(self.user, ["a", "c"], COURSE_KEY) + + def test_any_permission_flag_disabled_uses_default_checks(self): + """With the flag off, the default legacy check of any permission grants access.""" + self.set_authz_enabled(False) + checks = {"a": lambda *_: False, "b": lambda *_: True} + with patch.dict(f"{API}.LEGACY_PERMISSION_CHECKS", checks, clear=True): + assert user_has_any_instructor_permission(self.user, ["a", "b"], COURSE_KEY) + assert not user_has_any_instructor_permission(self.user, ["a"], COURSE_KEY) + + def test_any_permission_flag_disabled_explicit_legacy_check(self): + """With the flag off, an explicit legacy check replaces the defaults.""" + self.set_authz_enabled(False) + assert user_has_any_instructor_permission(self.user, ["a", "b"], COURSE_KEY, lambda *_: True) + assert not user_has_any_instructor_permission(self.user, ["a", "b"], COURSE_KEY, lambda *_: False) + + def test_any_permission_flag_disabled_explicit_legacy_check_runs_once(self): + """With the flag off, an explicit legacy check covers the whole set: it runs and is logged once.""" + self.set_authz_enabled(False) + legacy_check = Mock(return_value=False) + + with self.assertLogs(API, level="DEBUG") as logs: + assert not user_has_any_instructor_permission(self.user, ["a", "b", "c"], COURSE_KEY, legacy_check) + + legacy_check.assert_called_once_with(self.user, COURSE_KEY) + assert [record.access_path for record in logs.records] == ["legacy"] + assert logs.records[0].authz_permissions == ["a", "b", "c"] + + def test_any_permission_empty_collection_denies(self): + """An empty collection denies instead of raising, whatever the flag and the legacy check.""" + for enabled in (True, False): + self.set_authz_enabled(enabled) + assert not user_has_any_instructor_permission(self.user, [], COURSE_KEY) + assert not user_has_any_instructor_permission(self.user, [], COURSE_KEY, lambda *_: True) diff --git a/lms/djangoapps/instructor/authz/tests/test_compat.py b/lms/djangoapps/instructor/authz/tests/test_compat.py new file mode 100644 index 000000000000..1a3c6f0940ff --- /dev/null +++ b/lms/djangoapps/instructor/authz/tests/test_compat.py @@ -0,0 +1,55 @@ +""" +Tests for the compatibility of the legacy roles with the Instructor Dashboard AuthZ enforcement. +""" + +import ddt +from django.test import TestCase +from opaque_keys.edx.locator import CourseLocator +from openedx_authz.applets.course_team_roles.constants import ( + COURSE_BETA_TESTER, + COURSE_DATA_RESEARCHER, + COURSE_LIMITED_STAFF, +) +from openedx_authz.authz import COURSE_ADMIN, COURSE_AUDITOR, COURSE_STAFF + +from common.djangoapps.student.tests.factories import UserFactory +from lms.djangoapps.instructor.authz.compat import holds_legacy_role_compat_permission +from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin + +COURSE_KEY = CourseLocator("edX", "Demo", "2026") +OTHER_COURSE_KEY = CourseLocator("edX", "Demo", "2027") + + +@ddt.ddt +class HoldsLegacyRoleCompatPermissionTest(InstructorAuthzTestMixin, TestCase): + """Only the legacy roles that AuthZ maps without dashboard permissions hold a compatibility permission.""" + + def setUp(self): + super().setUp() + self.user = UserFactory() + + @ddt.data( + (COURSE_LIMITED_STAFF.external_key, True), + (COURSE_DATA_RESEARCHER.external_key, True), + (COURSE_BETA_TESTER.external_key, True), + # These hold real dashboard permissions: AuthZ is authoritative for them. + (COURSE_ADMIN.external_key, False), + (COURSE_STAFF.external_key, False), + (COURSE_AUDITOR.external_key, False), + ) + @ddt.unpack + def test_role(self, role, expected): + """The result depends on the AuthZ role of the user.""" + self.assign_authz_role(self.user, role, COURSE_KEY) + + assert holds_legacy_role_compat_permission(self.user, COURSE_KEY) == expected + + def test_without_role(self): + """A user without roles holds no compatibility permission.""" + assert not holds_legacy_role_compat_permission(self.user, COURSE_KEY) + + def test_scoped_to_the_course(self): + """The role only counts in the course where it is assigned.""" + self.assign_authz_role(self.user, COURSE_LIMITED_STAFF.external_key, COURSE_KEY) + + assert not holds_legacy_role_compat_permission(self.user, OTHER_COURSE_KEY) diff --git a/lms/djangoapps/instructor/authz/tests/test_permissions.py b/lms/djangoapps/instructor/authz/tests/test_permissions.py new file mode 100644 index 000000000000..d8f5df6cd21a --- /dev/null +++ b/lms/djangoapps/instructor/authz/tests/test_permissions.py @@ -0,0 +1,180 @@ +""" +Tests for the ``InstructorAuthzPermission`` DRF permission class. +""" + +from unittest.mock import Mock, patch + +import ddt +import pytest +from django.core.exceptions import ImproperlyConfigured +from django.http import Http404 +from django.test import TestCase +from opaque_keys.edx.locator import CourseLocator +from openedx_authz.applets.enrollments.constants import COURSES_VIEW_ENROLLMENTS +from openedx_authz.applets.learner_grading.constants import COURSES_VIEW_GRADEBOOK +from openedx_authz.authz import COURSE_ADMIN, COURSE_STAFF, COURSES_MANAGE_COURSE_TEAM, COURSES_VIEW_COURSE_TEAM +from rest_framework.test import APIRequestFactory + +from common.djangoapps.student.tests.factories import UserFactory +from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission +from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin + +COURSE_KEY = CourseLocator("edX", "Demo", "2026") + + +class FakeView: + """Minimal view with the attributes read by the permission class.""" + + def __init__(self, course_id=str(COURSE_KEY), **attrs): + self.kwargs = {"course_id": course_id} + for name, value in attrs.items(): + setattr(self, name, value) + + +@ddt.ddt +class InstructorAuthzPermissionTest(InstructorAuthzTestMixin, TestCase): + """Checks the AuthZ and legacy paths of the permission class.""" + + def setUp(self): + super().setUp() + self.user = UserFactory() + self.factory = APIRequestFactory() + + def _request(self, method="get"): + request = getattr(self.factory, method)("/") + request.user = self.user + return request + + def test_authz_enabled_grants_access_by_authz_role(self): + """With the flag on, an AuthZ role grants access even if the legacy check denies.""" + self.assign_authz_role(self.user, COURSE_STAFF.external_key, COURSE_KEY) + view = FakeView( + authz_permissions=(COURSES_VIEW_ENROLLMENTS.identifier,), + legacy_permission_check=lambda *_: False, + ) + + assert InstructorAuthzPermission().has_permission(self._request(), view) + + def test_authz_collection_grants_access_with_any_permission(self): + """With the flag on, a collection of permissions grants access when the user holds any one of them.""" + view = FakeView( + authz_permissions=( + COURSES_VIEW_ENROLLMENTS.identifier, + COURSES_VIEW_GRADEBOOK.identifier, + ), + legacy_permission_check=lambda *_: False, + ) + + with patch( + "lms.djangoapps.instructor.authz.api.authz_api.is_user_allowed", + side_effect=lambda _u, permission, _s: permission == COURSES_VIEW_GRADEBOOK.identifier, + ): + assert InstructorAuthzPermission().has_permission(self._request(), view) + + def test_authz_collection_denied_without_any_permission(self): + """With the flag on, a collection of permissions denies a user that holds none of them.""" + view = FakeView( + authz_permissions=( + COURSES_VIEW_ENROLLMENTS.identifier, + COURSES_VIEW_GRADEBOOK.identifier, + ), + legacy_permission_check=lambda *_: True, + ) + + assert not InstructorAuthzPermission().has_permission(self._request(), view) + + def test_authz_disabled_collection_uses_legacy_check_once(self): + """With the flag off, a collection of permissions is resolved by the view legacy check alone.""" + self.set_authz_enabled(False) + legacy_check = Mock(return_value=True) + view = FakeView( + authz_permissions=( + COURSES_VIEW_ENROLLMENTS.identifier, + COURSES_VIEW_GRADEBOOK.identifier, + ), + legacy_permission_check=legacy_check, + ) + + assert InstructorAuthzPermission().has_permission(self._request(), view) + legacy_check.assert_called_once_with(self.user, COURSE_KEY) + + def test_authz_enabled_ignores_legacy(self): + """With the flag on, a passing legacy check does not grant access without an AuthZ role.""" + view = FakeView( + authz_permissions=(COURSES_VIEW_ENROLLMENTS.identifier,), + legacy_permission_check=lambda *_: True, + ) + + assert not InstructorAuthzPermission().has_permission(self._request(), view) + + def test_authz_disabled_uses_legacy_permission_check(self): + """With the flag off, the view legacy check decides and AuthZ roles are ignored.""" + self.set_authz_enabled(False) + self.assign_authz_role(self.user, COURSE_ADMIN.external_key, COURSE_KEY) + legacy_check = Mock(return_value=True) + view = FakeView( + authz_permissions=(COURSES_VIEW_ENROLLMENTS.identifier,), + legacy_permission_check=legacy_check, + ) + + assert InstructorAuthzPermission().has_permission(self._request(), view) + legacy_check.assert_called_once_with(self.user, COURSE_KEY) + + def test_authz_disabled_uses_bridgekeeper_permission_name(self): + """With the flag off and no legacy check, ``permission_name`` is evaluated as a bridgekeeper permission.""" + self.set_authz_enabled(False) + view = FakeView( + authz_permissions=(COURSES_VIEW_ENROLLMENTS.identifier,), + permission_name="instructor.dashboard", + ) + with patch.object(type(self.user), "has_perm", return_value=True) as has_perm: + assert InstructorAuthzPermission().has_permission(self._request(), view) + has_perm.assert_called_once_with("instructor.dashboard", COURSE_KEY) + + @ddt.data(("get", True), ("post", False)) + @ddt.unpack + def test_permission_per_http_method(self, method, expected): + """The AuthZ permission is picked from the mapping by HTTP method.""" + self.assign_authz_role(self.user, COURSE_STAFF.external_key, COURSE_KEY) + view = FakeView( + authz_permissions={ + "GET": (COURSES_VIEW_COURSE_TEAM.identifier,), + # Course Staff does not hold it. + "POST": (COURSES_MANAGE_COURSE_TEAM.identifier,), + } + ) + + assert InstructorAuthzPermission().has_permission(self._request(method), view) == expected + + @ddt.data((True, False), (False, True)) + @ddt.unpack + def test_method_missing_from_mapping(self, authz_enabled, expected): + """A method missing from the mapping is denied with the flag on, and uses the legacy rule with it off.""" + self.set_authz_enabled(authz_enabled) + view = FakeView( + authz_permissions={"GET": (COURSES_VIEW_COURSE_TEAM.identifier,)}, + legacy_permission_check=lambda *_: True, + ) + + assert InstructorAuthzPermission().has_permission(self._request("delete"), view) == expected + + def test_invalid_course_key(self): + """An invalid ``course_id`` raises ``Http404``.""" + view = FakeView(course_id="not-a-course", authz_permissions=(COURSES_VIEW_ENROLLMENTS.identifier,)) + + with pytest.raises(Http404): + InstructorAuthzPermission().has_permission(self._request(), view) + + @ddt.data( + COURSES_VIEW_ENROLLMENTS.identifier, + {"GET": COURSES_VIEW_ENROLLMENTS.identifier}, + ) + def test_bare_string_raises(self, authz_permissions): + """A string instead of a collection, alone or in a mapping, raises ``ImproperlyConfigured``.""" + with pytest.raises(ImproperlyConfigured): + InstructorAuthzPermission().has_permission(self._request(), FakeView(authz_permissions=authz_permissions)) + + def test_view_without_authz_permission(self): + """A view that does not define ``authz_permissions`` raises ``ImproperlyConfigured``.""" + with pytest.raises(ImproperlyConfigured): + InstructorAuthzPermission().has_permission(self._request(), FakeView()) diff --git a/lms/djangoapps/instructor/tests/test_api_v2.py b/lms/djangoapps/instructor/tests/test_api_v2.py index 9641af860731..164ce6e87ce6 100644 --- a/lms/djangoapps/instructor/tests/test_api_v2.py +++ b/lms/djangoapps/instructor/tests/test_api_v2.py @@ -267,8 +267,11 @@ def test_get_course_metadata_invalid_course_id(self): def test_get_course_metadata_nonexistent_course(self): """ Test error handling for non-existent course. + + The permission check does not load the course, so only a user that passes it + (global staff) reaches the view and gets the 404. """ - self.client.force_authenticate(user=self.instructor) + self.client.force_authenticate(user=self.admin) nonexistent_course_id = 'course-v1:edX+NonExistent+2024' response = self.client.get(self._get_url(course_id=nonexistent_course_id)) @@ -276,6 +279,15 @@ def test_get_course_metadata_nonexistent_course(self): error_code = "Course not found: course-v1:edX+NonExistent+2024." self.assertEqual(response.data['developer_message'], error_code) # noqa: PT009 + def test_get_course_metadata_nonexistent_course_without_access(self): + """ + A user without access to a non-existent course gets 403, as for any other course. + """ + self.client.force_authenticate(user=self.instructor) + response = self.client.get(self._get_url(course_id='course-v1:edX+NonExistent+2024')) + + assert response.status_code == status.HTTP_403_FORBIDDEN + def test_instructor_permissions_reflected(self): """ Test that instructor permissions are correctly reflected in response. diff --git a/lms/djangoapps/instructor/tests/test_api_v2_authz.py b/lms/djangoapps/instructor/tests/test_api_v2_authz.py new file mode 100644 index 000000000000..32d0b552de36 --- /dev/null +++ b/lms/djangoapps/instructor/tests/test_api_v2_authz.py @@ -0,0 +1,314 @@ +""" +Tests for the AuthZ enforcement of the Instructor Dashboard API v2. + +They cover the tabs, ``authz_enabled`` and the migrated endpoints. +""" + +from unittest.mock import patch + +import ddt +from django.urls import reverse +from openedx_authz.applets.course_team_roles.constants import ( + COURSE_AUDITOR, + COURSE_BETA_TESTER, + COURSE_DATA_RESEARCHER, + COURSE_EDITOR, + COURSE_LIMITED_STAFF, +) +from openedx_authz.applets.learner_administration.constants import COURSES_VIEW_COURSE_INFO +from openedx_authz.authz import COURSE_ADMIN, COURSE_STAFF +from rest_framework import status +from rest_framework.test import APIClient + +from common.djangoapps.student.roles import CourseDataResearcherRole, CourseLimitedStaffRole +from common.djangoapps.student.tests.factories import ( + InstructorFactory, + StaffFactory, + UserFactory, +) +from lms.djangoapps.courseware.tabs import get_course_tab_list +from lms.djangoapps.instructor.authz import constants +from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory + +API = "lms.djangoapps.instructor.authz.api" + +# Tabs migrated to AuthZ, each with one of the permissions that show it. +MIGRATED_TABS = {tab: permissions[0] for tab, permissions in constants.TAB_PERMISSIONS.items()} + +# Every (tab, permission) pair: a single permission of the tab is enough to show it. +TAB_PERMISSION_PAIRS = [ + (tab, permission) for tab, permissions in constants.TAB_PERMISSIONS.items() for permission in permissions +] + + +@ddt.ddt +class CourseMetadataViewAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): + """ + ``CourseMetadataView`` tabs and permissions follow the AuthZ flag. + + With the flag on they are resolved through AuthZ, and through the legacy + roles when it is off. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.course = CourseFactory.create() + cls.course_key = cls.course.id + + def setUp(self): + super().setUp() + self.client = APIClient() + # The Date Extensions tab is only shown when edx-when is enabled for the course. + patcher = patch("lms.djangoapps.instructor.views.serializers_v2.is_enabled_for_course", return_value=True) + patcher.start() + self.addCleanup(patcher.stop) + self.url = reverse("instructor_api_v2:course_metadata", kwargs={"course_id": str(self.course_key)}) + + def _get(self, user): + self.client.force_authenticate(user=user) + return self.client.get(self.url) + + def _tab_ids(self, response): + return {tab["tab_id"] for tab in response.data["tabs"]} + + def test_existing_permissions_field_is_unchanged(self): + """The legacy ``permissions`` field keeps the same keys.""" + user = self.create_user_with_authz_role(COURSE_ADMIN.external_key, self.course_key) + + response = self._get(user) + + assert response.status_code == status.HTTP_200_OK + assert set(response.data["permissions"]) == { + "admin", + "instructor", + "finance_admin", + "sales_admin", + "staff", + "forum_admin", + "data_researcher", + } + + @ddt.data(COURSE_ADMIN, COURSE_STAFF) + def test_authz_role_sees_migrated_tabs(self, role): + """A Course Admin and a Course Staff see exactly the migrated tabs, and AuthZ is reported as enabled.""" + user = self.create_user_with_authz_role(role.external_key, self.course_key) + + response = self._get(user) + + assert response.status_code == status.HTTP_200_OK + assert self._tab_ids(response) == set(MIGRATED_TABS) + assert response.data["authz_enabled"] is True + + def test_authz_denied_overrides_legacy_roles(self): + """ + With the flag on, AuthZ denying a legacy instructor means no access. + """ + instructor = InstructorFactory(course_key=self.course_key) + + with patch(f"{API}.authz_api.is_user_allowed", return_value=False): + response = self._get(instructor) + + assert response.status_code == status.HTTP_403_FORBIDDEN + assert response.data["error_code"] == "permission_denied" + assert response.data["developer_message"] + + def test_authz_limited_staff_has_the_legacy_access(self): + """ + With the flag on, the legacy limited staff gets the same tabs as with the flag off. + + AuthZ defines no dashboard permission for ``course_limited_staff``, which had the + access of the course staff before AuthZ. + """ + self.set_authz_enabled(False) + legacy_user = UserFactory() + CourseLimitedStaffRole(self.course_key).add_users(legacy_user) + legacy_response = self._get(legacy_user) + + self.set_authz_enabled(True) + user = self.create_user_with_authz_role(COURSE_LIMITED_STAFF.external_key, self.course_key) + response = self._get(user) + + assert legacy_response.status_code == status.HTTP_200_OK + assert response.status_code == status.HTTP_200_OK + assert self._tab_ids(response) + assert self._tab_ids(response) == self._tab_ids(legacy_response) + + def test_authz_beta_tester_keeps_the_legacy_denial(self): + """With the flag on, the legacy beta tester is denied, as it was before AuthZ.""" + user = self.create_user_with_authz_role(COURSE_BETA_TESTER.external_key, self.course_key) + + assert self._get(user).status_code == status.HTTP_403_FORBIDDEN + + def test_authz_data_researcher_sees_only_data_downloads(self): + """ + With the flag on, a data researcher keeps the access it had before AuthZ. + + It opens the dashboard, but only sees the Data Downloads tab. + """ + user = self.create_user_with_authz_role(COURSE_DATA_RESEARCHER.external_key, self.course_key) + + response = self._get(user) + + assert response.status_code == status.HTTP_200_OK + assert self._tab_ids(response) == {"data_downloads"} + + def test_legacy_data_researcher_sees_only_data_downloads(self): + """With the flag off, a data researcher sees the same tab through the legacy role.""" + self.set_authz_enabled(False) + user = UserFactory() + CourseDataResearcherRole(self.course_key).add_users(user) + + response = self._get(user) + + assert response.status_code == status.HTTP_200_OK + assert self._tab_ids(response) == {"data_downloads"} + + @ddt.data(COURSE_AUDITOR.external_key, COURSE_EDITOR.external_key, COURSE_STAFF.external_key) + def test_authz_other_roles_do_not_get_data_downloads(self, role): + """With the flag on, the data researcher permission does not leak into other roles.""" + user = self.create_user_with_authz_role(role, self.course_key) + + response = self._get(user) + + assert "data_downloads" not in self._tab_ids(response) + + @ddt.data(*constants.INSTRUCTOR_DASHBOARD_PERMISSIONS) + def test_authz_any_dashboard_permission_grants_access(self, permission): + """With the flag on, a single dashboard permission, not only ``view_course_info``, grants access.""" + user = UserFactory() + + with patch(f"{API}.authz_api.is_user_allowed", side_effect=lambda _u, perm, _s: perm == permission): + response = self._get(user) + + assert response.status_code == status.HTTP_200_OK + + @ddt.data(*TAB_PERMISSION_PAIRS) + @ddt.unpack + def test_authz_tab_shown_with_any_of_its_permissions(self, tab_id, tab_permission): + """ + A tab is shown with any one of its permissions, and hidden without all of them. + """ + user = UserFactory() + + def allowed_only(*permissions): + return lambda _username, permission, _scope: permission in permissions + + with patch( + f"{API}.authz_api.is_user_allowed", + side_effect=allowed_only(COURSES_VIEW_COURSE_INFO.identifier), + ): + tabs_without_permission = self._tab_ids(self._get(user)) + with patch( + f"{API}.authz_api.is_user_allowed", + side_effect=allowed_only(COURSES_VIEW_COURSE_INFO.identifier, tab_permission), + ): + tabs_with_permission = self._tab_ids(self._get(user)) + + assert tab_id in tabs_with_permission + if tab_id != "course_info": + assert tab_id not in tabs_without_permission + + @ddt.data( + (InstructorFactory, set()), + # Staff without the forum Administrator role does not see Course Team, and without + # instructor access does not see Date Extensions. + (StaffFactory, {"course_team", "date_extensions"}), + ) + @ddt.unpack + def test_legacy_role_sees_its_migrated_tabs(self, user_factory, hidden_tabs): + """With the flag off, the legacy role decides the migrated tabs and AuthZ is reported as disabled.""" + self.set_authz_enabled(False) + user = user_factory(course_key=self.course_key) + + response = self._get(user) + + assert response.status_code == status.HTTP_200_OK + assert self._tab_ids(response) & set(MIGRATED_TABS) == set(MIGRATED_TABS) - hidden_tabs + assert response.data["authz_enabled"] is False + + def test_legacy_does_not_query_authz(self): + """With the flag off, AuthZ is not queried.""" + self.set_authz_enabled(False) + instructor = InstructorFactory(course_key=self.course_key) + + with patch(f"{API}.authz_api.is_user_allowed") as is_user_allowed: + response = self._get(instructor) + + assert response.status_code == status.HTTP_200_OK + is_user_allowed.assert_not_called() + + +@ddt.ddt +class InstructorDashboardTabAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): + """ + The "Instructor" course tab of the LMS follows the AuthZ flag. + + With the flag on it is shown when the user holds at least one of the Instructor + Dashboard permissions, and through the legacy roles when it is off. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.course = CourseFactory.create() + + def _has_instructor_tab(self, user): + return any(tab.type == "instructor" for tab in get_course_tab_list(user, self.course)) + + def test_authz_role_with_permissions_shown(self): + """With the flag on, a role that holds dashboard permissions sees the tab.""" + user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course.id) + + assert self._has_instructor_tab(user) + + def test_authz_limited_staff_shown(self): + """With the flag on, the legacy limited staff sees the tab, as it did before AuthZ.""" + user = self.create_user_with_authz_role(COURSE_LIMITED_STAFF.external_key, self.course.id) + + assert self._has_instructor_tab(user) + + def test_authz_data_researcher_shown(self): + """With the flag on, a data researcher sees the tab, as it did before AuthZ.""" + user = self.create_user_with_authz_role(COURSE_DATA_RESEARCHER.external_key, self.course.id) + + assert self._has_instructor_tab(user) + + @ddt.data(*constants.INSTRUCTOR_DASHBOARD_PERMISSIONS) + def test_authz_instructor_course_tab_shown_with_any_dashboard_permission(self, permission): + """With the flag on, a single dashboard permission is enough to show the "Instructor" course tab.""" + user = UserFactory() + + with patch(f"{API}.authz_api.is_user_allowed", side_effect=lambda _u, perm, _c: perm == permission): + assert self._has_instructor_tab(user) + + def test_authz_without_permissions_hidden(self): + """With the flag on, a user holding none of the permissions does not see the tab.""" + user = UserFactory() + + assert not self._has_instructor_tab(user) + + def test_authz_denied_overrides_legacy_staff(self): + """With the flag on, legacy staff without AuthZ permissions does not see the tab.""" + staff = StaffFactory(course_key=self.course.id) + + with patch(f"{API}.authz_api.is_user_allowed", return_value=False): + assert not self._has_instructor_tab(staff) + + def test_legacy_staff_shown(self): + """With the flag off, a legacy staff user sees the tab without querying AuthZ.""" + self.set_authz_enabled(False) + staff = StaffFactory(course_key=self.course.id) + + with patch(f"{API}.authz_api.is_user_allowed") as is_user_allowed: + assert self._has_instructor_tab(staff) + + is_user_allowed.assert_not_called() + + def test_legacy_without_role_hidden(self): + """With the flag off, a user without any role does not see the tab.""" + self.set_authz_enabled(False) + + assert not self._has_instructor_tab(UserFactory()) diff --git a/lms/djangoapps/instructor/views/api_v2.py b/lms/djangoapps/instructor/views/api_v2.py index ba4c2770f166..dbf64692a1b7 100644 --- a/lms/djangoapps/instructor/views/api_v2.py +++ b/lms/djangoapps/instructor/views/api_v2.py @@ -103,6 +103,10 @@ revoke_access, update_forum_role, ) +from lms.djangoapps.instructor.authz import constants as authz_constants +from lms.djangoapps.instructor.authz import legacy as authz_legacy +from lms.djangoapps.instructor.authz.api import user_has_any_instructor_permission +from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission from lms.djangoapps.instructor.constants import ReportType from lms.djangoapps.instructor.enrollment import ( enroll_email, @@ -182,6 +186,9 @@ VALID_TEAM_ROLES = frozenset(ROLES.keys()) | frozenset(FORUM_ROLES) +# Legacy check of the dashboard +LEGACY_VIEW_DASHBOARD_CHECK = authz_legacy.bridgekeeper_check(permissions.VIEW_DASHBOARD) + # Shared OpenAPI parameters, each used identically by several endpoints below. COURSE_ID_PATH_PARAMETER = OpenApiParameter( 'course_id', @@ -211,7 +218,9 @@ class CourseMetadataView(DeveloperErrorViewMixin, APIView): permissions, and navigation sections. """ - permission_classes = (IsAuthenticated, permissions.InstructorPermission) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + # Holding any of the dashboard permissions is enough, as for the "Instructor" course tab. + authz_permissions = authz_constants.INSTRUCTOR_DASHBOARD_PERMISSIONS permission_name = permissions.VIEW_DASHBOARD @extend_schema( @@ -306,6 +315,24 @@ def get(self, request, course_id): course_key = CourseKey.from_string(course_id) course = get_course_by_id(course_key) + def can_view_dashboard(user): + """ + Return whether the user can view the instructor dashboard. + + With ``authz.enable_course_authoring`` enabled for the course, holding any of + the dashboard AuthZ permissions is enough. With it disabled, the legacy + dashboard permission is used. + """ + return user_has_any_instructor_permission( + user, + authz_constants.INSTRUCTOR_DASHBOARD_PERMISSIONS, + course_key, + LEGACY_VIEW_DASHBOARD_CHECK, + ) + + # Masquerading is not migrated to AuthZ yet: it keeps requiring legacy staff access. + # The AuthZ course staff and course admin roles satisfy it through the legacy + # compatibility layer, which maps them to the legacy roles. original_user_is_staff = has_access(request.user, 'staff', course_key).has_access _, request.user = setup_masquerade( request, @@ -313,8 +340,7 @@ def get(self, request, course_id): staff_access=original_user_is_staff, ) - if get_masquerade_role(request.user, course_key) == 'student' or \ - not request.user.has_perm(permissions.VIEW_DASHBOARD, course): + if get_masquerade_role(request.user, course_key) == 'student' or not can_view_dashboard(request.user): raise PermissionDenied('This user does not have access to the instructor dashboard.') tabs = get_course_tab_list(request.user, course) diff --git a/lms/djangoapps/instructor/views/instructor_dashboard.py b/lms/djangoapps/instructor/views/instructor_dashboard.py index 9ac12fde0e7d..e5a8ecd53dde 100644 --- a/lms/djangoapps/instructor/views/instructor_dashboard.py +++ b/lms/djangoapps/instructor/views/instructor_dashboard.py @@ -46,6 +46,9 @@ from lms.djangoapps.courseware.masquerade import get_masquerade_role from lms.djangoapps.discussion.django_comment_client.utils import has_forum_access from lms.djangoapps.grades.api import is_writable_gradebook_enabled +from lms.djangoapps.instructor.authz import constants as authz_constants +from lms.djangoapps.instructor.authz import legacy as authz_legacy +from lms.djangoapps.instructor.authz.api import user_has_any_instructor_permission from lms.djangoapps.instructor.constants import INSTRUCTOR_DASHBOARD_PLUGIN_VIEW_NAME from openedx.core.djangoapps.course_groups.cohorts import DEFAULT_COHORT_NAME, get_course_cohorts, is_course_cohorted from openedx.core.djangoapps.discussions.config.waffle_utils import legacy_discussion_experience_enabled @@ -90,11 +93,23 @@ def link_func(course, reverse_func): @classmethod def is_enabled(cls, course, user=None): """ - Returns true if the specified user has staff access. + Returns true if the user can see the Instructor Dashboard. + + With ``authz.enable_course_authoring`` enabled for the course, the tab is shown when + the user holds at least one of the Instructor Dashboard AuthZ permissions. Otherwise + the legacy ``VIEW_DASHBOARD`` permission is required. """ - return bool(user and user.is_authenticated and - get_masquerade_role(user, course.id) != 'student' and - user.has_perm(permissions.VIEW_DASHBOARD, course.id)) + return bool( + user + and user.is_authenticated + and get_masquerade_role(user, course.id) != "student" + and user_has_any_instructor_permission( + user, + authz_constants.INSTRUCTOR_DASHBOARD_PERMISSIONS, + course.id, + authz_legacy.bridgekeeper_check(permissions.VIEW_DASHBOARD), + ) + ) def show_analytics_dashboard_message(course_key): diff --git a/lms/djangoapps/instructor/views/serializers_v2.py b/lms/djangoapps/instructor/views/serializers_v2.py index f19a465f43b4..0be57ff435f5 100644 --- a/lms/djangoapps/instructor/views/serializers_v2.py +++ b/lms/djangoapps/instructor/views/serializers_v2.py @@ -24,6 +24,7 @@ CourseInstructorRole, CourseSalesAdminRole, CourseStaffRole, + enable_authz_course_authoring, ) from lms.djangoapps.bulk_email.api import is_bulk_email_feature_enabled from lms.djangoapps.certificates.models import CertificateGenerationConfiguration @@ -33,6 +34,9 @@ from lms.djangoapps.grades.api import is_writable_gradebook_enabled from lms.djangoapps.instructor import permissions from lms.djangoapps.instructor.access import FORUM_ROLES, ROLES +from lms.djangoapps.instructor.authz import constants as authz_constants +from lms.djangoapps.instructor.authz import legacy as authz_legacy +from lms.djangoapps.instructor.authz.api import user_has_any_instructor_permission from lms.djangoapps.instructor.views.instructor_dashboard import get_analytics_dashboard_message from openedx.core.djangoapps.django_comment_common.models import FORUM_ROLE_ADMINISTRATOR from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers @@ -84,6 +88,13 @@ class CourseInformationSerializerV2(serializers.Serializer): help_text="URL to the admin console (requires instructor access and MFE configuration, null if not accessible)" ) permissions = serializers.SerializerMethodField(help_text="User permissions for instructor dashboard features") + authz_enabled = serializers.SerializerMethodField( + help_text=( + "Whether the AuthZ permissions are enabled for the course (``authz.enable_course_authoring`` flag). " + "The MFE uses it to decide whether to check the user's permissions through AuthZ or keep the legacy " + "behavior." + ) + ) tabs = serializers.SerializerMethodField(help_text="List of course tabs with configuration and display information") disable_buttons = serializers.SerializerMethodField( help_text="Whether to disable certain bulk action buttons due to large course size" @@ -149,7 +160,6 @@ def get_tabs(self, data): 'finance_admin': CourseFinanceAdminRole(course_key).has_user(request.user), 'sales_admin': CourseSalesAdminRole(course_key).has_user(request.user), 'staff': bool(has_access(request.user, 'staff', course)), - 'forum_admin': has_forum_access(request.user, course_key, FORUM_ROLE_ADMINISTRATOR), 'data_researcher': request.user.has_perm(permissions.CAN_RESEARCH, course_key), } tabs = [] @@ -161,61 +171,47 @@ def get_tabs(self, data): # Without explicit sort_order values, there's no deterministic way to interleave # backend tabs with plugin-inserted tabs, and tab order could shift based on # load/config timing. - if access['staff']: - tabs.extend([ - { - 'tab_id': 'course_info', - 'title': _('Course Info'), - 'url': self._build_tab_url( - 'INSTRUCTOR_MICROFRONTEND_URL', - course_key, - 'course_info' - ), - 'sort_order': 10, - }, - { - 'tab_id': 'enrollments', - 'title': _('Enrollments'), - 'url': self._build_tab_url( - 'INSTRUCTOR_MICROFRONTEND_URL', - course_key, - 'enrollments' - ), - 'sort_order': 20, - }, - { - 'tab_id': 'grading', - 'title': _('Grading'), - 'url': self._build_tab_url( - 'INSTRUCTOR_MICROFRONTEND_URL', - course_key, - 'grading' - ), - 'sort_order': 40, - }, - { - 'tab_id': 'cohorts', - 'title': _('Cohorts'), - 'url': self._build_tab_url( - 'INSTRUCTOR_MICROFRONTEND_URL', - course_key, - 'cohorts' - ), - 'sort_order': 90, - }, - ]) - if access['instructor'] or (access['staff'] and access['forum_admin']): - tabs.append({ - 'tab_id': 'course_team', - 'title': _('Course Team'), - 'url': self._build_tab_url( - 'INSTRUCTOR_MICROFRONTEND_URL', - course_key, - 'course_team' - ), - 'sort_order': 30, - }) + # The tabs below are enforced through AuthZ when ``authz.enable_course_authoring`` + # is enabled for the course. A tab is shown when the user holds at least one of + # its permissions (``authz_constants.TAB_PERMISSIONS``). Otherwise they keep the + # legacy role check passed as the second argument, or the default ones of the + # permissions when it is ``None``. + def can_see(tab, legacy_check=None): + return user_has_any_instructor_permission( + request.user, authz_constants.TAB_PERMISSIONS[tab], course_key, legacy_check + ) + + # (tab_id, title, sort_order, legacy check). The legacy check is + # explicit when the default ones of the permissions are broader than + # the tab condition, which has always required staff access. + authz_tabs = [ + ("course_info", _("Course Info"), 10, authz_legacy.has_staff_access), + ("enrollments", _("Enrollments"), 20, None), + ("grading", _("Grading"), 40, authz_legacy.has_staff_access), + ("cohorts", _("Cohorts"), 90, authz_legacy.has_staff_access), + ] + + for tab, title, sort_order, legacy_check in authz_tabs: + if can_see(tab, legacy_check): + tabs.append( + { + "tab_id": tab, + "title": title, + "url": self._build_tab_url("INSTRUCTOR_MICROFRONTEND_URL", course_key, tab), + "sort_order": sort_order, + } + ) + + if can_see("course_team"): + tabs.append( + { + "tab_id": "course_team", + "title": _("Course Team"), + "url": self._build_tab_url("INSTRUCTOR_MICROFRONTEND_URL", course_key, "course_team"), + "sort_order": 30, + } + ) if access['staff'] and is_bulk_email_feature_enabled(course_key): tabs.append( @@ -229,7 +225,7 @@ def get_tabs(self, data): } ) - if access['instructor'] and is_enabled_for_course(course_key): + if is_enabled_for_course(course_key) and can_see("date_extensions", authz_legacy.has_instructor_access): tabs.append({ 'tab_id': 'date_extensions', 'title': _('Date Extensions'), @@ -424,6 +420,18 @@ def get_num_sections(self, data): course = data['course'] return len(course.get_children()) if hasattr(course, 'get_children') else 0 + def get_authz_enabled(self, data) -> bool: + """ + Get whether AuthZ is enabled for the course. + + Args: + data (dict): The serializer context, with ``course``. + + Returns: + bool: True if ``authz.enable_course_authoring`` is enabled for the course. + """ + return enable_authz_course_authoring(data['course'].id) + def get_permissions(self, data): """Get user permissions for the course.""" user = data['user'] diff --git a/openedx/core/djangoapps/authz/tests/fixtures.py b/openedx/core/djangoapps/authz/tests/fixtures.py index 80831246bd61..d5738b069f7b 100644 --- a/openedx/core/djangoapps/authz/tests/fixtures.py +++ b/openedx/core/djangoapps/authz/tests/fixtures.py @@ -1,26 +1,32 @@ -""" Fixtures for AuthZ-aware tests """ -import casbin -import pkg_resources +"""Fixtures for AuthZ-aware tests""" + +from functools import lru_cache + from openedx_authz.engine.enforcer import AuthzEnforcer -from openedx_authz.engine.utils import migrate_policy_between_enforcers +from openedx_authz.engine.renderer import PolicyRenderer, SchemaApplier +from openedx_authz.engine.schema.pipeline import SchemaPipeline + + +@lru_cache(maxsize=1) +def _compiled_schema(): + """ + Compile and render the static AuthZ schema once per process. + + Discovering, validating and compiling the schema is the expensive part of + ``load_authz_schema`` and does not depend on the database, so it is shared + by every test. + """ + schema = SchemaPipeline().compile() + return schema, PolicyRenderer().render(schema) def seed_policies(): - """Seed the database with AuthZ policies.""" - global_enforcer = AuthzEnforcer.get_enforcer() - global_enforcer.load_policy() - - model_path = pkg_resources.resource_filename( - "openedx_authz.engine", - "config/model.conf", - ) - - policy_path = pkg_resources.resource_filename( - "openedx_authz.engine", - "config/authz.policy", - ) - - migrate_policy_between_enforcers( - source_enforcer=casbin.Enforcer(model_path, policy_path), - target_enforcer=global_enforcer, - ) + """ + Seed the database with the static AuthZ schema and load it into the enforcer. + + It applies the same schema as the ``load_authz_schema`` command, but reuses + the compiled schema, so only the (per test) database write is repeated. + """ + schema, rendered = _compiled_schema() + SchemaApplier().apply(rendered, schema) + AuthzEnforcer.get_enforcer().load_policy() diff --git a/openedx/core/djangoapps/authz/tests/mixins.py b/openedx/core/djangoapps/authz/tests/mixins.py index 2c2f227875ae..74ff2ba27133 100644 --- a/openedx/core/djangoapps/authz/tests/mixins.py +++ b/openedx/core/djangoapps/authz/tests/mixins.py @@ -12,15 +12,17 @@ from openedx.core.djangoapps.authz.tests.fixtures import seed_policies -class CourseAuthoringAuthzTestMixin: +class AuthzTestMixin: """ - Base mixin for testing AuthZ in the course authoring context. + Base mixin for tests that run with the AuthZ course authoring flag. Responsibilities: - - Enable course authoring AuthZ feature flag - - Seed policies into the AuthZ enforcer - - Provide authenticated test clients - - Provide helpers for assigning roles within a course scope + - Enable the ``authz.enable_course_authoring`` flag, and let tests change it + - Seed policies into the AuthZ enforcer and clear them afterwards + - Provide a helper to assign roles within a course scope + + The flag is enabled for every course at the start of each test. The patched + ``is_enabled`` is available as ``authz_flag_mock``. """ @classmethod @@ -30,8 +32,7 @@ def setUpClass(cls): "is_enabled", return_value=True, ) - cls.toggle_patcher.start() - cls.password = 'test' + cls.authz_flag_mock = cls.toggle_patcher.start() super().setUpClass() @classmethod @@ -41,9 +42,63 @@ def tearDownClass(cls): def setUp(self): super().setUp() - + self.set_authz_enabled(True) seed_policies() + def tearDown(self): + super().tearDown() + AuthzEnforcer.get_enforcer().clear_policy() + + def set_authz_enabled(self, enabled: bool): + """ + Enable or disable ``authz.enable_course_authoring`` for every course. + + Args: + enabled (bool): The value of the flag. + """ + self.authz_flag_mock.side_effect = None + self.authz_flag_mock.return_value = enabled + + def set_authz_enabled_for(self, *course_keys): + """ + Enable ``authz.enable_course_authoring`` only for the given courses. + + It is disabled for any other course and when no course is given. + + Args: + *course_keys (CourseKey): The courses with the flag enabled. + """ + enabled_keys = {str(course_key) for course_key in course_keys} + self.authz_flag_mock.side_effect = lambda course_key=None, **_: str(course_key) in enabled_keys + + def assign_authz_role(self, user, role, course_key): + """ + Assign an AuthZ role to the user in the course. + + Args: + user (User): The user receiving the role. + role (str): The AuthZ role external key. + course_key (CourseKey): The course where the role is assigned. + """ + assign_role_to_user_in_scope(user.username, role, str(course_key)) + + +class CourseAuthoringAuthzTestMixin(AuthzTestMixin): + """ + Base mixin for testing AuthZ in the course authoring context. + + Besides what ``AuthzTestMixin`` provides: + - Provide authenticated test clients + """ + + @classmethod + def setUpClass(cls): + cls.password = 'test' + super().setUpClass() + + def setUp(self): + super().setUp() + self.authorized_user = UserFactory(password=self.password) self.unauthorized_user = UserFactory(password=self.password) @@ -61,18 +116,9 @@ def setUp(self): self.staff_client = APIClient() self.staff_client.force_authenticate(user=self.staff_user) - def tearDown(self): - super().tearDown() - AuthzEnforcer.get_enforcer().clear_policy() - def add_user_to_role_in_course(self, user, role, course_key): """Helper method to add a user to a role for the course.""" - assign_role_to_user_in_scope( - user.username, - role, - str(course_key) - ) - AuthzEnforcer.get_enforcer().load_policy() + self.assign_authz_role(user, role, course_key) class CourseAuthzTestMixin(CourseAuthoringAuthzTestMixin): diff --git a/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py b/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py index d36f45ad1b92..d82c60a4da62 100644 --- a/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py +++ b/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py @@ -31,6 +31,7 @@ from user_tasks.models import UserTaskArtifact, UserTaskStatus from common.djangoapps.student.tests.factories import UserFactory +from openedx.core.djangoapps.authz.tests.fixtures import seed_policies from openedx.core.djangoapps.content_libraries.constants import CC_4_BY from openedx.core.djangoapps.content_libraries.tasks import LibraryRestoreTask from openedx.core.djangoapps.content_libraries.tests.base import ( @@ -2432,7 +2433,8 @@ class ContentLibrariesRestAPIAuthzIntegrationTestCase(ContentLibrariesRestApiTes def setUp(self): super().setUp() - self._seed_database_with_policies() + seed_policies() + AuthzEnforcer.get_enforcer().clear_policy() # Clear to simulate fresh start for each test self.library_admin = UserFactory.create( username="library_admin", @@ -2491,28 +2493,6 @@ def tearDown(self): super().tearDown() AuthzEnforcer.get_enforcer().clear_policy() # Clear policies after each test to ensure isolation - @classmethod - def _seed_database_with_policies(cls): - """Seed the database with policies from the policy file. - - This simulates the one-time database seeding that would happen - during application deployment, separate from the runtime policy loading. - """ - import casbin - import pkg_resources - from openedx_authz.engine.utils import migrate_policy_between_enforcers - - global_enforcer = AuthzEnforcer.get_enforcer() - global_enforcer.load_policy() - model_path = pkg_resources.resource_filename("openedx_authz.engine", "config/model.conf") - policy_path = pkg_resources.resource_filename("openedx_authz.engine", "config/authz.policy") - - migrate_policy_between_enforcers( - source_enforcer=casbin.Enforcer(model_path, policy_path), - target_enforcer=global_enforcer, - ) - global_enforcer.clear_policy() # Clear to simulate fresh start for each test - def _all_users_excluding(self, excluded_users): return set(self.list_of_all_users) - set(excluded_users) diff --git a/openedx/core/lib/api/view_utils.py b/openedx/core/lib/api/view_utils.py index 57cc9d0de95f..b9c68ae187ed 100644 --- a/openedx/core/lib/api/view_utils.py +++ b/openedx/core/lib/api/view_utils.py @@ -13,7 +13,7 @@ from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from rest_framework import serializers, status -from rest_framework.exceptions import APIException, ErrorDetail +from rest_framework.exceptions import APIException, ErrorDetail, PermissionDenied from rest_framework.generics import GenericAPIView from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin from rest_framework.permissions import IsAuthenticated @@ -90,6 +90,8 @@ def handle_exception(self, exc): """ if isinstance(exc, DeveloperErrorResponseException): return exc.response + elif isinstance(exc, PermissionDenied): + return self._make_error_response(exc.status_code, exc.detail, exc.get_codes()) elif isinstance(exc, APIException): return self._make_error_response(exc.status_code, exc.detail) elif isinstance(exc, (Http404, ObjectDoesNotExist)): diff --git a/requirements/edx/base.txt b/requirements/edx/base.txt index 8a32db061fbc..cb4f53895c96 100644 --- a/requirements/edx/base.txt +++ b/requirements/edx/base.txt @@ -832,7 +832,7 @@ openedx-atlas==0.7.2 # openedx-authz # openedx-forum # openedx-platform -openedx-authz==2.2.0 +openedx-authz==3.1.0 # via openedx-platform openedx-calc==5.1.0 # via diff --git a/requirements/edx/development.txt b/requirements/edx/development.txt index 148055593417..d4ca954a1ebd 100644 --- a/requirements/edx/development.txt +++ b/requirements/edx/development.txt @@ -939,7 +939,7 @@ openedx-atlas==0.7.2 # openedx-authz # openedx-forum # openedx-platform -openedx-authz==2.2.0 +openedx-authz==3.1.0 # via openedx-platform openedx-calc==5.1.0 # via diff --git a/uv.lock b/uv.lock index 45f3a150eae7..05a075a8a68f 100644 --- a/uv.lock +++ b/uv.lock @@ -4601,7 +4601,7 @@ wheels = [ [[package]] name = "openedx-authz" -version = "2.2.0" +version = "3.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, @@ -4623,9 +4623,9 @@ dependencies = [ { name = "openedx-filters" }, { name = "pycasbin" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0b/fe/c27067d42c10b1e92b90abcb5c616bccb2ba8651cf54231ef99a7f0777bc/openedx_authz-2.2.0.tar.gz", hash = "sha256:9d9c17d3fb0f9cdcd5fd9842194e187efe75e05edd2fa564a0cb2121318c88af", size = 874014, upload-time = "2026-10-28T17:39:47.443Z" } +sdist = { url = "https://files.pythonhosted.org/packages/5d/97/2d0002ddfee0afe9e107039fdc003516a16fd8c046c74420a5972fef91a4/openedx_authz-3.1.0.tar.gz", hash = "sha256:b92fa5fae00901de47c6c15507c8ca6161b0bb2be415f46f23ba8271f1f59958", size = 899136, upload-time = "2026-11-06T17:33:39.323Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/50/9c/ec5d5912b0ef0104335e72cdcdb4fa8fe8d05ef705ee0e1942e450e29e78/openedx_authz-2.2.0-py3-none-any.whl", hash = "sha256:5fe21525761303713bce7f77c7f9be60ea2a70ec80ffd853d623d566f2fca621", size = 225687, upload-time = "2026-10-28T17:39:45.921Z" }, + { url = "https://files.pythonhosted.org/packages/f7/dc/b1f570e7cb81b9756605f285cce0807b0e1711b97b96c80150f7465de40d/openedx_authz-3.1.0-py3-none-any.whl", hash = "sha256:ba92f5b6dcb88d84d80d0f6f6870dbc051f85d9a13c293843b84362b6fb726a4", size = 238196, upload-time = "2026-11-06T17:33:37.83Z" }, ] [[package]]