diff --git a/lms/djangoapps/instructor/authz/README.rst b/lms/djangoapps/instructor/authz/README.rst index 5fb450d5ef1a..eaf5a91ead81 100644 --- a/lms/djangoapps/instructor/authz/README.rst +++ b/lms/djangoapps/instructor/authz/README.rst @@ -28,7 +28,7 @@ Every decision is logged with the path that resolved it (``authz`` or ``legacy`` 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: +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. If the view's URL pattern names that kwarg something else (e.g. the cohorts API's ``course_key_string``), set ``course_id_url_kwarg`` on the view to match. Pick the case that matches the view: Case 1: Same permissions for every HTTP method ============================================== diff --git a/lms/djangoapps/instructor/authz/legacy.py b/lms/djangoapps/instructor/authz/legacy.py index 78091ec2f1ae..048f95ca1caa 100644 --- a/lms/djangoapps/instructor/authz/legacy.py +++ b/lms/djangoapps/instructor/authz/legacy.py @@ -36,6 +36,26 @@ ) +def is_django_staff(user: AbstractUser, course_key: CourseKey) -> bool: # pylint: disable=unused-argument + """ + Check the legacy access of the endpoints restricted to Django staff. + + It follows the same rule as DRF's ``IsAdminUser`` (``user.is_staff``), regardless + of the course. It is not a default of ``LEGACY_PERMISSION_CHECKS``: views pass it + as their ``legacy_permission_check``. + + Args: + user (AbstractUser): The user to check. + course_key (CourseKey): The course to check. It is not used, as the rule + does not depend on the course. + + Returns: + bool: True for Django staff. Course staff and course instructors are not + included. + """ + return bool(user and user.is_staff) + + def has_staff_access(user: AbstractUser, course_key: CourseKey) -> bool: """ Check whether the user has course staff access. @@ -88,9 +108,9 @@ 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. + It applies to any non-GET request of the cohorts API. Forum roles are not + enough here: only global staff, superusers and course staff or instructors + can change cohorts. Args: user (AbstractUser): The user to check. @@ -110,8 +130,8 @@ 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. + It applies to GET requests of the cohorts API, where the forum Administrator, + Moderator and Community TA roles are also allowed to read. Args: user (AbstractUser): The user to check. diff --git a/lms/djangoapps/instructor/authz/permissions.py b/lms/djangoapps/instructor/authz/permissions.py index f0dc8c4ae25b..c38a556681d5 100644 --- a/lms/djangoapps/instructor/authz/permissions.py +++ b/lms/djangoapps/instructor/authz/permissions.py @@ -44,6 +44,11 @@ class InstructorAuthzPermission(BasePermission): legacy_permission_check (Callable[[User, CourseKey], bool]): Optional. Replaces the ``permission_name`` check, for legacy rules that are not a bridgekeeper permission. + course_id_url_kwarg (str): Optional. The name of the URL kwarg holding + the course key. Defaults to ``"course_id"``, the one every + Instructor Dashboard v2 view uses; set it on the view when a + migrated endpoint uses a different name (e.g. the cohorts API's + ``course_key_string``). """ def has_permission(self, request, view): @@ -59,15 +64,16 @@ def has_permission(self, request, view): bool: True if access is granted. Raises: - Http404: If the ``course_id`` kwarg of the view is not a valid - course key. + Http404: If the course key URL kwarg of the view is missing or not + a valid course key. ImproperlyConfigured: If the view does not define ``authz_permissions``, or defines a bare string instead of a collection. """ + course_id_url_kwarg = getattr(view, "course_id_url_kwarg", "course_id") try: - course_key = CourseKey.from_string(view.kwargs.get("course_id")) - except InvalidKeyError as exc: + course_key = CourseKey.from_string(view.kwargs.get(course_id_url_kwarg)) + except (InvalidKeyError, TypeError) as exc: raise Http404("Invalid course key") from exc authz_permissions = getattr(view, "authz_permissions", None) diff --git a/lms/djangoapps/instructor/authz/tests/test_legacy.py b/lms/djangoapps/instructor/authz/tests/test_legacy.py new file mode 100644 index 000000000000..fa6a05762ebc --- /dev/null +++ b/lms/djangoapps/instructor/authz/tests/test_legacy.py @@ -0,0 +1,381 @@ +""" +Tests for the legacy (pre-AuthZ) checks of the Instructor Dashboard. +""" + +import ddt +from django.contrib.auth.models import AbstractUser +from django.test import TestCase +from opaque_keys.edx.locator import CourseLocator +from openedx_authz.authz import ( + COURSES_ENROLL_LEARNERS, + COURSES_MANAGE_COHORTS, + COURSES_MANAGE_COURSE_TEAM, + COURSES_MANAGE_LEARNER_EXTENSIONS, + COURSES_MANAGE_LEARNER_GRADING, + COURSES_UNENROLL_LEARNERS, + COURSES_VIEW_COHORTS, + COURSES_VIEW_COURSE_INFO, + COURSES_VIEW_COURSE_TEAM, + COURSES_VIEW_ENROLLMENTS, + COURSES_VIEW_GRADEBOOK, + COURSES_VIEW_GRADING_SETTINGS, + COURSES_VIEW_LEARNER_EXTENSIONS, +) + +from common.djangoapps.student.roles import ( + CourseDataResearcherRole, + CourseInstructorRole, + CourseLimitedStaffRole, + CourseStaffRole, + OrgInstructorRole, + OrgStaffRole, +) +from common.djangoapps.student.tests.factories import InstructorFactory, UserFactory +from lms.djangoapps.instructor import permissions +from lms.djangoapps.instructor.authz.legacy import ( + LEGACY_PERMISSION_CHECKS, + bridgekeeper_check, + has_cohort_manage_access, + has_cohort_view_access, + has_course_team_access, + has_gradebook_access, + has_grading_settings_access, + has_instructor_access, + has_staff_access, + is_django_staff, +) +from openedx.core.djangoapps.django_comment_common.models import ( + FORUM_ROLE_ADMINISTRATOR, + FORUM_ROLE_COMMUNITY_TA, + FORUM_ROLE_MODERATOR, + Role, +) +from openedx.core.djangolib.testing.utils import skip_unless_lms + +COURSE_KEY = CourseLocator("edX", "Demo", "2026") +OTHER_COURSE_KEY = CourseLocator("edX", "Demo", "2027") +FORUM_ROLES = (FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA) + +USER_TYPES = ( + "no_roles", + "global_staff", + "course_staff", + "course_instructor", + "limited_staff", + "data_researcher", + "org_staff", + "org_instructor", + "forum_administrator", + "course_staff_forum_administrator", + "other_course_instructor", +) + +# User types with course staff access in the LMS. +STAFF_ACCESS = frozenset( + { + "global_staff", + "course_staff", + "course_instructor", + "limited_staff", + "org_staff", + "org_instructor", + "course_staff_forum_administrator", + } +) +INSTRUCTOR_ACCESS = frozenset({"global_staff", "course_instructor", "org_instructor"}) +COURSE_TEAM_ACCESS = INSTRUCTOR_ACCESS | {"course_staff_forum_administrator"} +# Limited Staff has no Studio read access, but keeps course author access in the LMS. +STUDIO_READ_ACCESS = STAFF_ACCESS - {"limited_staff"} +DASHBOARD_ACCESS = STAFF_ACCESS | {"data_researcher"} +COHORT_VIEW_ACCESS = STAFF_ACCESS | {"forum_administrator"} + + +def create_user_with_roles(user_type: str) -> AbstractUser: + """ + Create a user holding the roles of a user type. + + Course and forum roles are granted in ``COURSE_KEY``, except those of + ``other_course_instructor``, granted in ``OTHER_COURSE_KEY``. + + Args: + user_type (str): One of ``USER_TYPES``. + + Returns: + User: The new user. + """ + user = UserFactory(is_staff=user_type == "global_staff") + course_roles = { + "course_staff": CourseStaffRole(COURSE_KEY), + "course_instructor": CourseInstructorRole(COURSE_KEY), + "limited_staff": CourseLimitedStaffRole(COURSE_KEY), + "data_researcher": CourseDataResearcherRole(COURSE_KEY), + "org_staff": OrgStaffRole(COURSE_KEY.org), + "org_instructor": OrgInstructorRole(COURSE_KEY.org), + "course_staff_forum_administrator": CourseStaffRole(COURSE_KEY), + "other_course_instructor": CourseInstructorRole(OTHER_COURSE_KEY), + } + if user_type in course_roles: + course_roles[user_type].add_users(user) + if user_type in ("forum_administrator", "course_staff_forum_administrator"): + Role.objects.get_or_create(name=FORUM_ROLE_ADMINISTRATOR, course_id=COURSE_KEY)[0].users.add(user) + return user + + +@skip_unless_lms +class IsDjangoStaffTest(TestCase): + """ + ``is_django_staff`` must behave as DRF's ``IsAdminUser``. + """ + + def test_django_staff_is_allowed(self): + """A user with the Django ``is_staff`` flag is allowed.""" + assert is_django_staff(UserFactory(is_staff=True), COURSE_KEY) + + def test_regular_user_is_denied(self): + """A user without the ``is_staff`` flag is denied.""" + assert not is_django_staff(UserFactory(), COURSE_KEY) + + def test_course_instructor_without_is_staff_is_denied(self): + """Course-level roles do not grant access, only the Django ``is_staff`` flag does.""" + instructor = InstructorFactory(course_key=COURSE_KEY) + assert not is_django_staff(instructor, COURSE_KEY) + + def test_missing_user_is_denied(self): + """A missing user is denied instead of raising.""" + assert not is_django_staff(None, COURSE_KEY) + + +@skip_unless_lms +@ddt.ddt +class CohortLegacyAccessTest(TestCase): + """ + ``has_cohort_view_access`` and ``has_cohort_manage_access`` must keep the rule of + the removed ``IsStaffOrAdmin`` permission class for reads and writes. + """ + + def _assert_access(self, user, can_view, can_manage): + """ + Assert the result of both cohort checks for the user in ``COURSE_KEY``. + + Args: + user (User): The user to check. + can_view (bool): The expected result of ``has_cohort_view_access``. + can_manage (bool): The expected result of ``has_cohort_manage_access``. + """ + assert has_cohort_view_access(user, COURSE_KEY) == can_view + assert has_cohort_manage_access(user, COURSE_KEY) == can_manage + + @ddt.data({"is_staff": True}, {"is_superuser": True}) + def test_platform_users_can_view_and_manage(self, user_flags): + """ + Global staff and superusers without ``is_staff`` can view and manage. + + Args: + user_flags (dict): The Django user flags to set. + """ + self._assert_access(UserFactory(**user_flags), can_view=True, can_manage=True) + + @ddt.data(CourseStaffRole, CourseInstructorRole) + def test_course_roles_can_view_and_manage(self, role_class): + """ + Course staff and course instructors can view and manage. + + Args: + role_class (type): The course role to grant. + """ + user = UserFactory() + role_class(COURSE_KEY).add_users(user) + + self._assert_access(user, can_view=True, can_manage=True) + + @ddt.data(OrgStaffRole, OrgInstructorRole) + def test_org_roles_can_view_and_manage(self, role_class): + """ + Organization staff and instructors can view and manage the courses of the org. + + Args: + role_class (type): The organization role to grant. + """ + user = UserFactory() + role_class(COURSE_KEY.org).add_users(user) + + self._assert_access(user, can_view=True, can_manage=True) + + @ddt.data(*FORUM_ROLES) + def test_forum_roles_can_only_view(self, role_name): + """ + The privileged forum roles pass the view check but not the manage check. + + Args: + role_name (str): The forum role to grant. + """ + user = UserFactory() + Role.objects.get_or_create(name=role_name, course_id=COURSE_KEY)[0].users.add(user) + + self._assert_access(user, can_view=True, can_manage=False) + + def test_user_without_roles_is_denied(self): + """A user without roles can neither view nor manage.""" + self._assert_access(UserFactory(), can_view=False, can_manage=False) + + def test_roles_in_another_course_are_denied(self): + """Course and forum roles of another course do not grant access.""" + user = UserFactory() + CourseStaffRole(OTHER_COURSE_KEY).add_users(user) + Role.objects.get_or_create(name=FORUM_ROLE_MODERATOR, course_id=OTHER_COURSE_KEY)[0].users.add(user) + + self._assert_access(user, can_view=False, can_manage=False) + + +@skip_unless_lms +@ddt.ddt +class CourseAccessTest(TestCase): + """ + ``has_staff_access`` and ``has_instructor_access`` follow the courseware access levels. + """ + + @ddt.data(*USER_TYPES) + def test_staff_access(self, user_type): + """ + Course and org staff and instructors, and global staff, have staff access. + + Args: + user_type (str): The user type to check. + """ + assert has_staff_access(create_user_with_roles(user_type), COURSE_KEY) == (user_type in STAFF_ACCESS) + + @ddt.data(*USER_TYPES) + def test_instructor_access(self, user_type): + """ + Only course and org instructors, and global staff, have instructor access. + + Args: + user_type (str): The user type to check. + """ + assert has_instructor_access(create_user_with_roles(user_type), COURSE_KEY) == (user_type in INSTRUCTOR_ACCESS) + + +@skip_unless_lms +@ddt.ddt +class CourseTeamAccessTest(TestCase): + """ + ``has_course_team_access`` follows the rule of ``CourseTeamPermission``. + """ + + @ddt.data(*USER_TYPES) + def test_course_team_access(self, user_type): + """ + It requires instructor access, or staff access plus the forum Administrator role. + + Args: + user_type (str): The user type to check. + """ + user = create_user_with_roles(user_type) + + assert has_course_team_access(user, COURSE_KEY) == (user_type in COURSE_TEAM_ACCESS) + + +@skip_unless_lms +@ddt.ddt +class GradingAccessTest(TestCase): + """ + ``has_gradebook_access`` and ``has_grading_settings_access`` follow the Studio rules. + """ + + @ddt.data(*USER_TYPES) + def test_gradebook_access(self, user_type): + """ + The gradebook requires course author access, which Limited Staff holds in the LMS. + + Args: + user_type (str): The user type to check. + """ + assert has_gradebook_access(create_user_with_roles(user_type), COURSE_KEY) == (user_type in STAFF_ACCESS) + + @ddt.data(*USER_TYPES) + def test_grading_settings_access(self, user_type): + """ + The grading settings require Studio read access, which Limited Staff lacks. + + Args: + user_type (str): The user type to check. + """ + user = create_user_with_roles(user_type) + + assert has_grading_settings_access(user, COURSE_KEY) == (user_type in STUDIO_READ_ACCESS) + + +@skip_unless_lms +@ddt.ddt +class BridgekeeperCheckTest(TestCase): + """ + ``bridgekeeper_check`` evaluates the given permission against the course. + """ + + @ddt.data( + ("data_researcher", True), + ("global_staff", True), + ("course_staff", False), + ("no_roles", False), + ) + @ddt.unpack + def test_evaluates_the_given_permission(self, user_type, expected): + """ + The check follows the rule of the permission it was built with. + + Args: + user_type (str): The user type to check. + expected (bool): Whether ``instructor.research`` is granted. + """ + check = bridgekeeper_check(permissions.CAN_RESEARCH) + + assert check(create_user_with_roles(user_type), COURSE_KEY) == expected + + def test_is_scoped_to_the_course(self): + """A role only grants the permission in its own course.""" + check = bridgekeeper_check(permissions.CAN_RESEARCH) + user = create_user_with_roles("data_researcher") + + assert not check(user, OTHER_COURSE_KEY) + + +@skip_unless_lms +@ddt.ddt +class LegacyPermissionChecksTest(TestCase): + """ + ``LEGACY_PERMISSION_CHECKS`` maps every AuthZ permission to its legacy rule. + """ + + EXPECTED_ACCESS = { + COURSES_VIEW_COURSE_INFO.identifier: DASHBOARD_ACCESS, + COURSES_VIEW_ENROLLMENTS.identifier: STAFF_ACCESS, + COURSES_ENROLL_LEARNERS.identifier: STAFF_ACCESS, + COURSES_UNENROLL_LEARNERS.identifier: STAFF_ACCESS, + COURSES_VIEW_COURSE_TEAM.identifier: COURSE_TEAM_ACCESS, + COURSES_MANAGE_COURSE_TEAM.identifier: COURSE_TEAM_ACCESS, + COURSES_VIEW_GRADEBOOK.identifier: STAFF_ACCESS, + COURSES_VIEW_GRADING_SETTINGS.identifier: STUDIO_READ_ACCESS, + COURSES_MANAGE_LEARNER_GRADING.identifier: STAFF_ACCESS, + COURSES_VIEW_LEARNER_EXTENSIONS.identifier: DASHBOARD_ACCESS, + COURSES_MANAGE_LEARNER_EXTENSIONS.identifier: STAFF_ACCESS, + COURSES_VIEW_COHORTS.identifier: COHORT_VIEW_ACCESS, + COURSES_MANAGE_COHORTS.identifier: STAFF_ACCESS, + } + + def test_every_permission_has_an_expected_rule(self): + """A permission added to the mapping must also be added to this test.""" + assert set(LEGACY_PERMISSION_CHECKS) == set(self.EXPECTED_ACCESS) + + @ddt.data(*USER_TYPES) + def test_access_of_user_type(self, user_type): + """ + Each permission grants the user type the access its legacy rule gives. + + Args: + user_type (str): The user type to check. + """ + user = create_user_with_roles(user_type) + + for permission, allowed_user_types in self.EXPECTED_ACCESS.items(): + with self.subTest(permission=permission): + assert LEGACY_PERMISSION_CHECKS[permission](user, COURSE_KEY) == (user_type in allowed_user_types) diff --git a/lms/djangoapps/instructor/authz/tests/test_permissions.py b/lms/djangoapps/instructor/authz/tests/test_permissions.py index 263b5758293f..f875fa2bb488 100644 --- a/lms/djangoapps/instructor/authz/tests/test_permissions.py +++ b/lms/djangoapps/instructor/authz/tests/test_permissions.py @@ -163,6 +163,16 @@ def test_method_missing_from_mapping(self, authz_enabled, expected): assert InstructorAuthzPermission().has_permission(self._request("delete"), view) == expected + def test_custom_course_id_url_kwarg(self): + """A view can read the course key from a differently named URL kwarg.""" + self.assign_authz_role(self.user, COURSE_STAFF.external_key, COURSE_KEY) + view = FakeView( + authz_permissions=(COURSES_VIEW_ENROLLMENTS.identifier,), course_id_url_kwarg="course_key_string" + ) + view.kwargs = {"course_key_string": str(COURSE_KEY)} + + assert InstructorAuthzPermission().has_permission(self._request(), view) + 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,)) diff --git a/lms/djangoapps/instructor/views/api.py b/lms/djangoapps/instructor/views/api.py index 1f6cd4ec6215..bcb25d87295a 100644 --- a/lms/djangoapps/instructor/views/api.py +++ b/lms/djangoapps/instructor/views/api.py @@ -38,12 +38,11 @@ from edx_when.api import get_date_for_block from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey -from openedx_authz.authz import COURSES_VIEW_ENROLLMENTS +from openedx_authz.authz import COURSES_MANAGE_COHORTS, COURSES_VIEW_ENROLLMENTS from rest_framework import serializers, status # pylint: disable=wrong-import-order from rest_framework.exceptions import MethodNotAllowed from rest_framework.permissions import ( # pylint: disable=wrong-import-order BasePermission, - IsAdminUser, IsAuthenticated, ) from rest_framework.response import Response # pylint: disable=wrong-import-order @@ -82,6 +81,7 @@ from lms.djangoapps.courseware.models import StudentModule from lms.djangoapps.instructor import enrollment from lms.djangoapps.instructor.access import ROLES, allow_access, list_with_level, revoke_access, update_forum_role +from lms.djangoapps.instructor.authz.legacy import is_django_staff from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission from lms.djangoapps.instructor.constants import INVOICE_KEY from lms.djangoapps.instructor.enrollment import ( @@ -1852,12 +1852,16 @@ class CohortCSV(DeveloperErrorViewMixin, APIView): **Response Values** * Empty as this is executed asynchronously. """ + authentication_classes = ( JwtAuthentication, BearerAuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) - permission_classes = (IsAuthenticated, IsAdminUser) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = (COURSES_MANAGE_COHORTS.identifier,) + course_id_url_kwarg = "course_key_string" + legacy_permission_check = staticmethod(is_django_staff) def post(self, request, course_key_string): """ diff --git a/openedx/core/djangoapps/course_groups/permissions.py b/openedx/core/djangoapps/course_groups/permissions.py deleted file mode 100644 index 29e953321b1a..000000000000 --- a/openedx/core/djangoapps/course_groups/permissions.py +++ /dev/null @@ -1,38 +0,0 @@ -""" -Permissions for cohorts API -""" - -from opaque_keys.edx.keys import CourseKey -from rest_framework import permissions - -from common.djangoapps.student.roles import GlobalStaff -from lms.djangoapps.courseware.access import administrative_accesses_to_course_for_user -from lms.djangoapps.discussion.django_comment_client.utils import get_user_role_names -from openedx.core.djangoapps.django_comment_common.models import ( - FORUM_ROLE_ADMINISTRATOR, - FORUM_ROLE_COMMUNITY_TA, - FORUM_ROLE_MODERATOR, -) - - -class IsStaffOrAdmin(permissions.BasePermission): - """ - Permission that checks if the user is staff or an admin. - """ - - def has_permission(self, request, view): - """Returns true if the user is admin or staff and request method is GET.""" - if GlobalStaff().has_user(request.user) or request.user.is_superuser: - return True - course_key = CourseKey.from_string(view.kwargs.get("course_key_string")) - user_roles = get_user_role_names(request.user, course_key) - has_discussion_privileges = bool( - user_roles - & { - FORUM_ROLE_ADMINISTRATOR, - FORUM_ROLE_MODERATOR, - FORUM_ROLE_COMMUNITY_TA, - } - ) - _, staff_access, instructor_access = administrative_accesses_to_course_for_user(request.user, course_key) - return staff_access or instructor_access or (has_discussion_privileges and request.method == "GET") diff --git a/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py b/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py index fb22189eb866..861e7ed25ad6 100644 --- a/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py +++ b/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py @@ -4,10 +4,12 @@ from unittest.mock import patch from django.test import override_settings +from openedx_authz.authz import COURSE_STAFF from rest_framework import status from rest_framework.test import APIClient -from common.djangoapps.student.tests.factories import UserFactory +from common.djangoapps.student.tests.factories import InstructorFactory, UserFactory +from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin from openedx.core.djangoapps.course_groups.constants import COHORT_SCHEME from openedx.core.djangolib.testing.utils import skip_unless_lms from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase @@ -41,7 +43,7 @@ def _get_expected_studio_url(self, course_id=None): return f'{TEST_STUDIO_BASE_URL}/course/{course_id}/group_configurations' @override_settings(MFE_CONFIG={"STUDIO_BASE_URL": TEST_STUDIO_BASE_URL}) - @patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission') + @patch('lms.djangoapps.instructor.authz.permissions.InstructorAuthzPermission.has_permission') def test_list_content_groups_returns_json(self, mock_perm): """Verify endpoint returns JSON with correct structure""" mock_perm.return_value = True @@ -83,7 +85,7 @@ def test_list_content_groups_returns_json(self, mock_perm): expected_studio_url = self._get_expected_studio_url() self.assertEqual(data['studio_content_groups_link'], expected_studio_url) # noqa: PT009 - @patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission') + @patch('lms.djangoapps.instructor.authz.permissions.InstructorAuthzPermission.has_permission') def test_list_content_groups_filters_non_cohort_partitions(self, mock_perm): """Verify only groups from cohort-scheme partitions are returned""" mock_perm.return_value = True @@ -119,7 +121,7 @@ def test_list_content_groups_filters_non_cohort_partitions(self, mock_perm): self.assertEqual(groups[0]['name'], 'Group A') # noqa: PT009 @override_settings(MFE_CONFIG={"STUDIO_BASE_URL": TEST_STUDIO_BASE_URL}) - @patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission') + @patch('lms.djangoapps.instructor.authz.permissions.InstructorAuthzPermission.has_permission') def test_list_returns_empty_groups_when_none_exist(self, mock_perm): """Verify empty groups array and null id when no content groups exist""" mock_perm.return_value = True @@ -142,7 +144,7 @@ def test_list_requires_authentication(self): response = client.get(self._get_url()) self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009 - @patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission') + @patch('lms.djangoapps.instructor.authz.permissions.InstructorAuthzPermission.has_permission') def test_list_invalid_course_key_returns_400(self, mock_perm): """Verify invalid course key returns 400""" mock_perm.return_value = True @@ -182,7 +184,7 @@ def _get_url(self, configuration_id=50): """Helper to get detail URL""" return f'/api/cohorts/v2/courses/{self.course.id}/group_configurations/{configuration_id}' - @patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission') + @patch('lms.djangoapps.instructor.authz.permissions.InstructorAuthzPermission.has_permission') def test_get_configuration_details(self, mock_perm): """Verify GET returns full configuration details""" mock_perm.return_value = True @@ -214,7 +216,7 @@ def _get_url(self): """Helper to get list URL""" return f'/api/cohorts/v2/courses/{self.course.id}/group_configurations' - @patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission') + @patch('lms.djangoapps.instructor.authz.permissions.InstructorAuthzPermission.has_permission') def test_staff_user_can_access(self, mock_perm): """Verify staff users can access the endpoint""" mock_perm.return_value = True @@ -230,3 +232,62 @@ def test_unauthenticated_user_denied(self): client = APIClient() response = client.get(self._get_url()) self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009 + + +@skip_unless_lms +class ContentGroupsAuthzTestCase(InstructorAuthzTestMixin, ModuleStoreTestCase): + """ + AuthZ enforcement (courses.view_cohorts) for the content groups endpoints. + """ + + def setUp(self): + super().setUp() + self.course = CourseFactory.create() + self.course.user_partitions = [ + UserPartition( + id=50, + name='Content Groups', + description='Test description', + groups=[Group(id=1, name='Content Group A')], + scheme_id=COHORT_SCHEME, + ) + ] + self.update_course(self.course, UserFactory().id) + self.client = APIClient() + self.urls = ( + f'/api/cohorts/v2/courses/{self.course.id}/group_configurations', + f'/api/cohorts/v2/courses/{self.course.id}/group_configurations/50', + ) + + def _assert_status(self, user, expected_status): + self.client.force_authenticate(user=user) + for url in self.urls: + assert self.client.get(url).status_code == expected_status, url + + def test_course_staff_can_access(self): + """A Course Staff holds courses.view_cohorts.""" + user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course.id) + self._assert_status(user, status.HTTP_200_OK) + + def test_authz_role_without_legacy_equivalent_can_access(self): + """With the flag on, AuthZ alone decides: no legacy role (or compat projection) is needed.""" + user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course.id) + with patch( + "common.djangoapps.student.roles.get_authz_compat_course_access_roles_for_user", + return_value=set(), + ): + self._assert_status(user, status.HTTP_200_OK) + + def test_user_without_permission_is_denied(self): + """A user with no AuthZ role in the course is denied.""" + self._assert_status(UserFactory(), status.HTTP_403_FORBIDDEN) + + def test_legacy_instructor_keeps_access_with_flag_off(self): + """With the flag off, the legacy instructor.dashboard rule applies.""" + self.set_authz_enabled(False) + self._assert_status(InstructorFactory(course_key=self.course.id), status.HTTP_200_OK) + + def test_legacy_student_is_denied_with_flag_off(self): + """With the flag off, a user without a legacy role is denied.""" + self.set_authz_enabled(False) + self._assert_status(UserFactory(), status.HTTP_403_FORBIDDEN) diff --git a/openedx/core/djangoapps/course_groups/rest_api/views.py b/openedx/core/djangoapps/course_groups/rest_api/views.py index 3882e3b3b3a0..1cfcdece4f09 100644 --- a/openedx/core/djangoapps/course_groups/rest_api/views.py +++ b/openedx/core/djangoapps/course_groups/rest_api/views.py @@ -6,12 +6,14 @@ from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey +from openedx_authz.authz import COURSES_VIEW_COHORTS from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from lms.djangoapps.instructor import permissions +from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission from openedx.core.djangoapps.course_groups.constants import COHORT_SCHEME from openedx.core.djangoapps.course_groups.partition_scheme import get_cohorted_user_partition from openedx.core.djangoapps.course_groups.rest_api.serializers import ( @@ -28,7 +30,8 @@ class GroupConfigurationsListView(DeveloperErrorViewMixin, APIView): """ API view for listing content group configurations. """ - permission_classes = (IsAuthenticated, permissions.InstructorPermission) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = (COURSES_VIEW_COHORTS.identifier,) permission_name = permissions.VIEW_DASHBOARD @extend_schema( @@ -97,7 +100,8 @@ class GroupConfigurationDetailView(DeveloperErrorViewMixin, APIView): """ API view for retrieving a specific content group configuration. """ - permission_classes = (IsAuthenticated, permissions.InstructorPermission) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = (COURSES_VIEW_COHORTS.identifier,) permission_name = permissions.VIEW_DASHBOARD @extend_schema( diff --git a/openedx/core/djangoapps/course_groups/tests/test_views_authz.py b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py new file mode 100644 index 000000000000..db91f65ecd1a --- /dev/null +++ b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py @@ -0,0 +1,338 @@ +""" +Tests for the AuthZ enforcement of the Cohorts tab endpoints: CohortSettings, +CohortHandler, CohortUsers, CohortCSV, and the legacy course_cohort_settings_handler. +""" + +import tempfile +from unittest.mock import patch + +import ddt +from django.urls import reverse +from openedx_authz.authz import COURSE_ADMIN, COURSE_BETA_TESTER, COURSE_LIMITED_STAFF, COURSE_STAFF +from rest_framework import status +from rest_framework.test import APIClient + +from common.djangoapps.student.tests.factories import InstructorFactory, UserFactory +from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin +from openedx.core.djangoapps.course_groups import cohorts +from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory +from openedx.core.djangoapps.django_comment_common.models import ( + FORUM_ROLE_ADMINISTRATOR, + FORUM_ROLE_COMMUNITY_TA, + FORUM_ROLE_MODERATOR, + Role, +) +from openedx.core.djangolib.testing.utils import skip_unless_lms +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory + +API = "lms.djangoapps.instructor.authz.api" + + +# (name, url kwargs, http method, request kwargs). A ``None`` cohort_id stands for the test cohort. +VIEW_REQUESTS = ( + ("cohort_settings", {}, "get", {}), + ("cohort_handler", {}, "get", {}), + ("cohort_users", {"cohort_id": None}, "get", {}), +) +MANAGE_REQUESTS = ( + ("cohort_settings", {}, "put", {"data": {"is_cohorted": True}, "format": "json"}), + ( + "cohort_handler", + {}, + "post", + {"data": {"name": "New", "assignment_type": "manual"}, "format": "json"}, + ), + ("cohort_users", {"cohort_id": None}, "post", {"data": {"users": ["nonexistent_user"]}, "format": "json"}), +) +ALL_REQUESTS = (*VIEW_REQUESTS, *MANAGE_REQUESTS) +FORUM_ROLES = (FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA) + + +@skip_unless_lms +@ddt.ddt +class CohortsAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): + """ + AuthZ enforcement across every endpoint behind the Cohorts tab. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.course = CourseFactory.create() + cls.course_key = cls.course.id + + def setUp(self): + super().setUp() + self.client = APIClient() + self.cohort = CohortFactory(course_id=self.course_key) + + def _url(self, name, **kwargs): + return reverse(f"api_cohorts:{name}", kwargs={"course_key_string": str(self.course_key), **kwargs}) + + def _request(self, user, name, url_kwargs, method, request_kwargs): + if "cohort_id" in url_kwargs and url_kwargs["cohort_id"] is None: + url_kwargs = {**url_kwargs, "cohort_id": self.cohort.id} + self.client.force_authenticate(user=user) + return getattr(self.client, method)(self._url(name, **url_kwargs), **request_kwargs) + + def _grant_forum_role(self, user, role_name): + """ + Grant a forum role to the user in the course. + + Args: + user (User): The user to grant the role to. + role_name (str): The forum role to grant. + """ + Role.objects.get_or_create(name=role_name, course_id=self.course_key)[0].users.add(user) + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_course_admin_can_view_and_manage(self, name, url_kwargs, method, request_kwargs): + """A Course Admin can use every GET and write endpoint.""" + user = self.create_user_with_authz_role(COURSE_ADMIN.external_key, self.course_key) + + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_course_staff_can_view_and_manage(self, name, url_kwargs, method, request_kwargs): + """A Course Staff can use every GET and write endpoint.""" + user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course_key) + + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_authz_role_without_legacy_equivalent_can_view_and_manage(self, name, url_kwargs, method, request_kwargs): + """With the flag on, AuthZ alone decides: no legacy role (or compat projection) is needed.""" + user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course_key) + + with patch( + "common.djangoapps.student.roles.get_authz_compat_course_access_roles_for_user", + return_value=set(), + ): + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_user_without_permission_is_denied(self, name, url_kwargs, method, request_kwargs): + """A user with no AuthZ role in the course is denied every endpoint.""" + response = self._request(UserFactory(), name, url_kwargs, method, request_kwargs) + + assert response.status_code == status.HTTP_403_FORBIDDEN + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_authz_denied_overrides_legacy_roles(self, name, url_kwargs, method, request_kwargs): + """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._request(instructor, name, url_kwargs, method, request_kwargs) + + assert response.status_code == status.HTTP_403_FORBIDDEN + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_legacy_instructor_keeps_access(self, name, url_kwargs, method, request_kwargs): + """With the flag off, a legacy instructor keeps the view/manage access it always had.""" + self.set_authz_enabled(False) + instructor = InstructorFactory(course_key=self.course_key) + + response = self._request(instructor, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_legacy_student_is_denied(self, name, url_kwargs, method, request_kwargs): + """With the flag off, a user with no legacy role is denied every endpoint.""" + self.set_authz_enabled(False) + + response = self._request(UserFactory(), name, url_kwargs, method, request_kwargs) + + assert response.status_code == status.HTTP_403_FORBIDDEN + + 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._request(instructor, "cohort_settings", {}, "get", {}) + + assert response.status_code == status.HTTP_200_OK + is_user_allowed.assert_not_called() + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_legacy_forum_role_access_per_endpoint(self, name, url_kwargs, method, request_kwargs): + """ + With the flag off, forum roles only read through the ``CohortHandler`` GET. + + Every other endpoint is denied by the permission class. + """ + self.set_authz_enabled(False) + is_allowed = (name, method) == ("cohort_handler", "get") + expected_status = status.HTTP_200_OK if is_allowed else status.HTTP_403_FORBIDDEN + + for role_name in FORUM_ROLES: + with self.subTest(role_name=role_name): + user = UserFactory() + self._grant_forum_role(user, role_name) + + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code == expected_status + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_forum_role_is_denied_with_flag_on(self, name, url_kwargs, method, request_kwargs): + """With the flag on, a forum role without an AuthZ role grants no access.""" + for role_name in FORUM_ROLES: + with self.subTest(role_name=role_name): + user = UserFactory() + self._grant_forum_role(user, role_name) + + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code == status.HTTP_403_FORBIDDEN + + @ddt.data("cohort_settings", "cohort_users") + def test_compat_role_with_forum_role_cannot_read_staff_endpoints(self, name): + """ + With the flag on, the ``compat.py`` fallback does not let a forum role read the + endpoints that required course staff. + + Args: + name (str): The URL name of the endpoint. + """ + url_kwargs = {"cohort_id": self.cohort.id} if name == "cohort_users" else {} + + for role_name in FORUM_ROLES: + with self.subTest(role_name=role_name): + user = self.create_user_with_authz_role(COURSE_BETA_TESTER.external_key, self.course_key) + self._grant_forum_role(user, role_name) + + response = self._request(user, name, url_kwargs, "get", {}) + + assert response.status_code == status.HTTP_403_FORBIDDEN + + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_compat_legacy_role_keeps_access(self, name, url_kwargs, method, request_kwargs): + """With the flag on, Course Limited Staff keeps its legacy access through ``compat.py``.""" + user = self.create_user_with_authz_role(COURSE_LIMITED_STAFF.external_key, self.course_key) + + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data + + +@skip_unless_lms +class CohortSettingsHandlerAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): + """ + AuthZ enforcement of the legacy ``course_cohort_settings_handler`` view + (``courses/{course_id}/cohorts/settings``), still used by Studio. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.course = CourseFactory.create() + cls.course_key = cls.course.id + + def setUp(self): + super().setUp() + self.client = APIClient() + self.url = reverse("course_cohort_settings", kwargs={"course_key_string": str(self.course_key)}) + + def _get(self, user): + # This is a plain Django view (not DRF), so force_authenticate doesn't apply: + # @login_required needs an actual logged-in session. + self.client.login(username=user.username, password="Password1234") + return self.client.get(self.url) + + def _patch(self, user): + self.client.login(username=user.username, password="Password1234") + return self.client.patch(self.url, data={"is_cohorted": True}, format="json") + + def test_course_admin_can_view_and_manage(self): + user = self.create_user_with_authz_role(COURSE_ADMIN.external_key, self.course_key) + + assert self._get(user).status_code == status.HTTP_200_OK + assert self._patch(user).status_code == status.HTTP_200_OK + + def test_user_without_permission_is_denied(self): + user = UserFactory() + + assert self._get(user).status_code == status.HTTP_404_NOT_FOUND + assert self._patch(user).status_code == status.HTTP_404_NOT_FOUND + + def test_legacy_staff_keeps_access(self): + """With the flag off, course staff keeps the access it always had (404 if not staff).""" + self.set_authz_enabled(False) + instructor = InstructorFactory(course_key=self.course_key) + student = UserFactory() + + assert self._get(instructor).status_code == status.HTTP_200_OK + assert self._get(student).status_code == status.HTTP_404_NOT_FOUND + + +@skip_unless_lms +class CohortCSVAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): + """ + AuthZ enforcement of ``CohortCSV``. Its legacy fallback was never gated on course + staff access like the rest of the cohorts endpoints, only on Django's own + ``user.is_staff``, so that specific check is preserved rather than reused. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.course = CourseFactory.create() + cls.course_key = cls.course.id + + def setUp(self): + super().setUp() + self.client = APIClient() + cohorts.add_cohort(self.course_key, "DEFAULT", "random") + + def _post_csv(self, user): + """Upload a minimal valid cohorts CSV as ``user`` and return the response.""" + self.client.force_authenticate(user=user) + __, file_name = tempfile.mkstemp(suffix=".csv", dir=tempfile.mkdtemp()) + with open(file_name, "w") as file_pointer: + file_pointer.write("email,cohort\nstudent@example.com,DEFAULT") + url = reverse("api_cohorts:cohort_users_csv", kwargs={"course_key_string": str(self.course_key)}) + with open(file_name) as file_pointer: + return self.client.post(url, data={"uploaded-file": file_pointer}) + + def test_course_admin_can_upload(self): + user = self.create_user_with_authz_role(COURSE_ADMIN.external_key, self.course_key) + + assert self._post_csv(user).status_code == status.HTTP_204_NO_CONTENT + + def test_user_without_permission_is_denied(self): + user = UserFactory() + + assert self._post_csv(user).status_code == status.HTTP_403_FORBIDDEN + + def test_legacy_django_staff_keeps_access_course_staff_does_not(self): + """ + With the flag off, this endpoint still only grants Django-staff users, unlike + every other cohorts endpoint (which grants any course staff/instructor). + """ + self.set_authz_enabled(False) + django_staff = UserFactory(is_staff=True) + course_instructor = InstructorFactory(course_key=self.course_key) + + assert self._post_csv(django_staff).status_code == status.HTTP_204_NO_CONTENT + assert self._post_csv(course_instructor).status_code == status.HTTP_403_FORBIDDEN diff --git a/openedx/core/djangoapps/course_groups/views.py b/openedx/core/djangoapps/course_groups/views.py index d5e147afe870..12ffb70d6abc 100644 --- a/openedx/core/djangoapps/course_groups/views.py +++ b/openedx/core/djangoapps/course_groups/views.py @@ -19,6 +19,7 @@ from edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser from edx_rest_framework_extensions.paginators import NamespacedPageNumberPagination from opaque_keys.edx.keys import CourseKey +from openedx_authz.authz import COURSES_MANAGE_COHORTS, COURSES_VIEW_COHORTS from rest_framework import permissions, status from rest_framework.generics import GenericAPIView from rest_framework.response import Response @@ -26,14 +27,17 @@ from common.djangoapps.edxmako.shortcuts import render_to_response from common.djangoapps.student.auth import has_course_author_access +from common.djangoapps.student.roles import enable_authz_course_authoring from common.djangoapps.util.json_request import JsonResponse, expect_json -from lms.djangoapps.courseware.courses import get_course, get_course_with_access +from lms.djangoapps.courseware.courses import get_course, get_course_by_id, get_course_with_access +from lms.djangoapps.instructor.authz.api import user_has_instructor_permission +from lms.djangoapps.instructor.authz.legacy import has_cohort_manage_access +from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission from openedx.core.djangoapps.course_groups.models import ( CohortAssignmentNotAllowed, CohortChangeNotAllowed, CohortMembership, ) -from openedx.core.djangoapps.course_groups.permissions import IsStaffOrAdmin from openedx.core.lib.api.authentication import BearerAuthenticationAllowInactiveUser from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin @@ -117,6 +121,18 @@ def _get_cohort_representation(cohort, course): } +def _legacy_cohort_staff_access(user, course_key): + """ + Reproduce this view's pre-AuthZ access check (course staff, for both GET and PATCH), + used as the fallback when ``authz.enable_course_authoring`` is disabled for the course. + """ + try: + get_course_with_access(user, 'staff', course_key) + except Http404: + return False + return True + + @require_http_methods(("GET", "PATCH")) @ensure_csrf_cookie @expect_json @@ -131,8 +147,12 @@ def course_cohort_settings_handler(request, course_key_string): Updates the cohort settings for the course. Returns the JSON representation of updated settings. """ course_key = CourseKey.from_string(course_key_string) - # Although this course data is not used this method will return 404 is user is not staff - get_course_with_access(request.user, 'staff', course_key) + authz_permission = ( + COURSES_MANAGE_COHORTS.identifier if request.method == 'PATCH' + else COURSES_VIEW_COHORTS.identifier + ) + if not user_has_instructor_permission(request.user, authz_permission, course_key, _legacy_cohort_staff_access): + raise Http404('The requesting user does not have course staff permissions.') if request.method == 'PATCH': if 'is_cohorted' not in request.json: @@ -411,9 +431,26 @@ def debug_cohort_mgmt(request, course_key_string): def _get_course_with_access(request, course_key_string, action='staff'): """ - Fetching a course with expected permission level + Fetch the course the cohorts API view is operating on. + + The permission itself is enforced by ``InstructorAuthzPermission`` before the view runs. + + With ``authz.enable_course_authoring`` enabled for the course, that class is the only + permission check: a ``staff`` action just loads the course, because the legacy + ``get_course_with_access(..., 'staff')`` only recognizes legacy roles (or AuthZ roles that + have a legacy equivalent) and would reject users that AuthZ already allowed. Any other + action (``load``) keeps going through ``get_course_with_access`` so the course visibility, + start/end dates and prerequisites checks still apply. + + With the flag disabled the legacy behavior is kept as is. + + The legacy roles of ``compat.py`` are evaluated with the legacy check while the flag is + enabled, and a ``staff`` action does not check course staff access for them either. So the + legacy check of an endpoint that requires course staff must not admit anyone else. """ course_key = CourseKey.from_string(course_key_string) + if action == 'staff' and enable_authz_course_authoring(course_key): + return course_key, get_course_by_id(course_key) return course_key, get_course_with_access(request.user, action, course_key) @@ -478,7 +515,10 @@ class APIPermissions(GenericAPIView): BearerAuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) - permission_classes = (permissions.IsAuthenticated, IsStaffOrAdmin) + permission_classes = (permissions.IsAuthenticated, InstructorAuthzPermission) + # The cohorts API uses course_key_string, not the course_id every other + # Instructor Dashboard v2 view uses. + course_id_url_kwarg = "course_key_string" serializer_class = Serializer @@ -502,6 +542,13 @@ class CohortSettings(DeveloperErrorViewMixin, APIPermissions): * is_cohorted: current status of the cohort setting """ + authz_permissions = { + "GET": (COURSES_VIEW_COHORTS.identifier,), + "PUT": (COURSES_MANAGE_COHORTS.identifier,), + } + # Excludes forum roles from GET: the default view check admits them, and the ``compat.py`` + # fallback has no later course staff check to stop them. + legacy_permission_check = staticmethod(has_cohort_manage_access) def get(self, request, course_key_string): """ @@ -585,6 +632,11 @@ class CohortHandler(DeveloperErrorViewMixin, APIPermissions): * group_id: The integer identifier of the specific group in the partition. """ queryset = [] + authz_permissions = { + "GET": (COURSES_VIEW_COHORTS.identifier,), + "POST": (COURSES_MANAGE_COHORTS.identifier,), + "PATCH": (COURSES_MANAGE_COHORTS.identifier,), + } def get(self, request, course_key_string, cohort_id=None): """ @@ -775,6 +827,13 @@ class CohortUsers(DeveloperErrorViewMixin, APIPermissions): Returns a HTTP 204 No Content response status code to indicate success. """ serializer_class = CohortUsersAPISerializer + authz_permissions = { + "GET": (COURSES_VIEW_COHORTS.identifier,), + "POST": (COURSES_MANAGE_COHORTS.identifier,), + "DELETE": (COURSES_MANAGE_COHORTS.identifier,), + } + # Excludes forum roles from GET, as in CohortSettings. + legacy_permission_check = staticmethod(has_cohort_manage_access) def _get_course_and_cohort(self, request, course_key_string, cohort_id): """