From c21eb58e0ff6f8a45fffca507555c9198e66d13a Mon Sep 17 00:00:00 2001 From: Kevyn Suarez Date: Wed, 21 Oct 2026 13:19:35 -0500 Subject: [PATCH 1/6] feat: enforce AuthZ permissions in the Cohorts tab endpoints Migrate the cohorts API views to InstructorAuthzPermission, following openedx-authz#486's shared infrastructure: - CohortSettings, CohortHandler and CohortUsers (openedx.core.djangoapps. course_groups.views) now require courses.view_cohorts for GET and courses.manage_cohorts for every write method, through a per-method authz_permissions mapping. No legacy_permission_check is set for these, so each method falls back to the matching default registered in LEGACY_PERMISSION_CHECKS (has_cohort_view_access/has_cohort_manage_access, already built in #486 to reproduce IsStaffOrAdmin), which is what varies the legacy fallback by method without any new code. - CohortCSV (lms.djangoapps.instructor.views.api) now requires courses.manage_cohorts, with a custom legacy_permission_check that keeps its pre-existing is_staff-only fallback: unlike the rest of the cohorts endpoints, this one was never gated on course staff access. - course_cohort_settings_handler, the legacy function-based view still used by Studio, gets the same permission check via user_has_instructor_permission directly, with an explicit legacy check reproducing its existing get_course_with_access(user, 'staff', ...) call so GET and PATCH keep requiring the same access level they always did (the DRF views' IsStaffOrAdmin-derived checks allow broader GET access, which this endpoint never had). Along the way: - InstructorAuthzPermission assumed the URL kwarg was always named course_id. The cohorts API uses course_key_string, so it gained an optional course_id_url_kwarg attribute (defaults to "course_id"), documented in the README for the other per-tab subtasks too. - Deleted course_groups.permissions.IsStaffOrAdmin: it was this migration's only remaining caller, and legacy.has_cohort_view_access/ has_cohort_manage_access already reproduce its exact logic. Add CohortsAuthzTest, CohortSettingsHandlerAuthzTest and CohortCSVAuthzTest covering Course Admin, Course Staff, a user with no permission, AuthZ denying a legacy instructor, and the legacy path with the flag off (including CohortCSV's narrower is_staff-only fallback). Rebased onto the latest instructor-authz-shared-infra (authz_permission renamed to authz_permissions, always a collection) and updated the cohorts views and tests to match. Closes openedx-authz#492. --- lms/djangoapps/instructor/authz/README.rst | 2 +- lms/djangoapps/instructor/authz/legacy.py | 10 +- .../instructor/authz/permissions.py | 14 +- .../authz/tests/test_permissions.py | 10 + lms/djangoapps/instructor/views/api.py | 16 +- .../djangoapps/course_groups/permissions.py | 38 --- .../course_groups/tests/test_views_authz.py | 231 ++++++++++++++++++ .../core/djangoapps/course_groups/views.py | 43 +++- 8 files changed, 309 insertions(+), 55 deletions(-) delete mode 100644 openedx/core/djangoapps/course_groups/permissions.py create mode 100644 openedx/core/djangoapps/course_groups/tests/test_views_authz.py 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..34dd8760711e 100644 --- a/lms/djangoapps/instructor/authz/legacy.py +++ b/lms/djangoapps/instructor/authz/legacy.py @@ -88,9 +88,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 +110,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_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..b4b70e023919 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 @@ -1857,7 +1856,18 @@ class CohortCSV(DeveloperErrorViewMixin, APIView): BearerAuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) - permission_classes = (IsAuthenticated, IsAdminUser) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = (COURSES_MANAGE_COHORTS.identifier,) + course_id_url_kwarg = "course_key_string" + + @staticmethod + def legacy_permission_check(user, course_key): # pylint: disable=unused-argument + """ + Preserve this endpoint's pre-AuthZ access check (Django staff only), used as the + fallback when ``authz.enable_course_authoring`` is disabled for the course. Unlike + the other cohorts endpoints, this one was never gated on course-level staff access. + """ + return bool(user and user.is_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/tests/test_views_authz.py b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py new file mode 100644 index 000000000000..ca36672c06df --- /dev/null +++ b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py @@ -0,0 +1,231 @@ +""" +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 + +from django.urls import reverse +from openedx_authz.authz import COURSE_ADMIN, 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.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" + + +@skip_unless_lms +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}) + + # (name, kwargs, http method, request kwargs) + 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"}), + ) + + 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 test_course_admin_can_view_and_manage(self): + """A Course Admin can use every GET and write endpoint.""" + user = self.create_user_with_authz_role(COURSE_ADMIN.external_key, self.course_key) + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code < 300, (name, method, response.status_code, response.data) + + def test_course_staff_can_view_and_manage(self): + """A Course Staff can use every GET and write endpoint.""" + user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course_key) + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code < 300, (name, method, response.status_code, response.data) + + def test_user_without_permission_is_denied(self): + """A user with no AuthZ role in the course is denied every endpoint.""" + user = UserFactory() + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + + 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) + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + with self.subTest(name=name, method=method): + 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 + + def test_legacy_instructor_keeps_access(self): + """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) + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(instructor, name, url_kwargs, method, request_kwargs) + assert response.status_code < 300, (name, method, response.status_code, response.data) + + def test_legacy_student_is_denied(self): + """With the flag off, a user with no legacy role is denied every endpoint.""" + self.set_authz_enabled(False) + user = UserFactory() + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + + 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() + + +@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..19f8d9dbfaaa 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 @@ -28,12 +29,13 @@ from common.djangoapps.student.auth import has_course_author_access 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.instructor.authz.api import user_has_instructor_permission +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 +119,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 +145,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: @@ -478,7 +496,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 +523,10 @@ class CohortSettings(DeveloperErrorViewMixin, APIPermissions): * is_cohorted: current status of the cohort setting """ + authz_permissions = { + "GET": (COURSES_VIEW_COHORTS.identifier,), + "PUT": (COURSES_MANAGE_COHORTS.identifier,), + } def get(self, request, course_key_string): """ @@ -585,6 +610,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 +805,11 @@ 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,), + } def _get_course_and_cohort(self, request, course_key_string, cohort_id): """ From 2ded1794e96a7fce350a53eae720686a8853e5a4 Mon Sep 17 00:00:00 2001 From: Bryann Valderrama Date: Tue, 10 Nov 2026 16:49:15 -0500 Subject: [PATCH 2/6] refactor: move the CohortCSV legacy check to a shared is_django_staff Replace the inline legacy_permission_check of CohortCSV with legacy.is_django_staff, a generic equivalent of DRF's IsAdminUser (user.is_staff). It is not registered in LEGACY_PERMISSION_CHECKS, so views opt in explicitly and other endpoints migrated from IsAdminUser can reuse it. Add unit tests for is_django_staff. Co-Authored-By: Claude Sonnet 5.5 --- lms/djangoapps/instructor/authz/legacy.py | 20 +++++++++++ .../instructor/authz/tests/test_legacy.py | 36 +++++++++++++++++++ lms/djangoapps/instructor/views/api.py | 12 ++----- 3 files changed, 59 insertions(+), 9 deletions(-) create mode 100644 lms/djangoapps/instructor/authz/tests/test_legacy.py diff --git a/lms/djangoapps/instructor/authz/legacy.py b/lms/djangoapps/instructor/authz/legacy.py index 34dd8760711e..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. 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..a0268a53d772 --- /dev/null +++ b/lms/djangoapps/instructor/authz/tests/test_legacy.py @@ -0,0 +1,36 @@ +""" +Tests for the legacy (pre-AuthZ) checks of the Instructor Dashboard. +""" + +from django.test import TestCase +from opaque_keys.edx.locator import CourseLocator + +from common.djangoapps.student.tests.factories import InstructorFactory, UserFactory +from lms.djangoapps.instructor.authz.legacy import is_django_staff +from openedx.core.djangolib.testing.utils import skip_unless_lms + +COURSE_KEY = CourseLocator("edX", "Demo", "2026") + + +@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) diff --git a/lms/djangoapps/instructor/views/api.py b/lms/djangoapps/instructor/views/api.py index b4b70e023919..bcb25d87295a 100644 --- a/lms/djangoapps/instructor/views/api.py +++ b/lms/djangoapps/instructor/views/api.py @@ -81,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 ( @@ -1851,6 +1852,7 @@ class CohortCSV(DeveloperErrorViewMixin, APIView): **Response Values** * Empty as this is executed asynchronously. """ + authentication_classes = ( JwtAuthentication, BearerAuthenticationAllowInactiveUser, @@ -1859,15 +1861,7 @@ class CohortCSV(DeveloperErrorViewMixin, APIView): permission_classes = (IsAuthenticated, InstructorAuthzPermission) authz_permissions = (COURSES_MANAGE_COHORTS.identifier,) course_id_url_kwarg = "course_key_string" - - @staticmethod - def legacy_permission_check(user, course_key): # pylint: disable=unused-argument - """ - Preserve this endpoint's pre-AuthZ access check (Django staff only), used as the - fallback when ``authz.enable_course_authoring`` is disabled for the course. Unlike - the other cohorts endpoints, this one was never gated on course-level staff access. - """ - return bool(user and user.is_staff) + legacy_permission_check = staticmethod(is_django_staff) def post(self, request, course_key_string): """ From f4bc94bc7736d3e0e4dfa41eb37480939d6efc20 Mon Sep 17 00:00:00 2001 From: Bryann Valderrama Date: Wed, 11 Nov 2026 13:39:51 -0500 Subject: [PATCH 3/6] fix: rely on InstructorAuthzPermission for the cohorts API course access _get_course_with_access ran get_course_with_access(user, 'staff', ...) after InstructorAuthzPermission had already allowed the request. That check only recognizes legacy roles (or AuthZ roles with a legacy equivalent), so a user holding courses.view_cohorts/manage_cohorts through an AuthZ role without a legacy equivalent got a 404. With authz.enable_course_authoring enabled, a 'staff' action now only loads the course, leaving the permission to InstructorAuthzPermission. The 'load' action 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 unchanged: the check is not redundant there, since the legacy view access also admits the forum Administrator, Moderator and Community TA roles and the 'staff' check is what keeps them out of the endpoints that require course staff. Co-Authored-By: Claude Sonnet 5.5 --- .../course_groups/tests/test_views_authz.py | 12 +++++++++++ .../core/djangoapps/course_groups/views.py | 20 +++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/openedx/core/djangoapps/course_groups/tests/test_views_authz.py b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py index ca36672c06df..6a2a3dbd8576 100644 --- a/openedx/core/djangoapps/course_groups/tests/test_views_authz.py +++ b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py @@ -81,6 +81,18 @@ def test_course_staff_can_view_and_manage(self): response = self._request(user, name, url_kwargs, method, request_kwargs) assert response.status_code < 300, (name, method, response.status_code, response.data) + def test_authz_role_without_legacy_equivalent_can_view_and_manage(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_key) + + with patch( + "common.djangoapps.student.roles.get_authz_compat_course_access_roles_for_user", + return_value=set(), + ): + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code < 300, (name, method, response.status_code, response.data) + def test_user_without_permission_is_denied(self): """A user with no AuthZ role in the course is denied every endpoint.""" user = UserFactory() diff --git a/openedx/core/djangoapps/course_groups/views.py b/openedx/core/djangoapps/course_groups/views.py index 19f8d9dbfaaa..d8e0fb018b86 100644 --- a/openedx/core/djangoapps/course_groups/views.py +++ b/openedx/core/djangoapps/course_groups/views.py @@ -27,8 +27,9 @@ 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.permissions import InstructorAuthzPermission from openedx.core.djangoapps.course_groups.models import ( @@ -429,9 +430,24 @@ 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 check is not redundant there: + the legacy view access also lets forum Administrator, Moderator and Community TA roles in, + and the ``staff`` check is what keeps them out of the endpoints that require course staff. """ 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) From b05e19cee94bb1f05ed4d42ae6bc493aaf4a07d0 Mon Sep 17 00:00:00 2001 From: Bryann Valderrama Date: Wed, 11 Nov 2026 13:39:51 -0500 Subject: [PATCH 4/6] feat: enforce AuthZ permissions in the content groups API v2 Migrate GroupConfigurationsListView and GroupConfigurationDetailView, used by the Cohorts tab of the Instructor Dashboard, to InstructorAuthzPermission. They require courses.view_cohorts, and keep instructor.dashboard as the legacy fallback used when authz.enable_course_authoring is disabled. They previously used InstructorPermission, which only sees legacy roles, so a user with an AuthZ role without a legacy equivalent got a 403 when the tab loaded the content groups. Update the existing tests to patch InstructorAuthzPermission and add ContentGroupsAuthzTestCase covering Course Staff, an AuthZ role without a legacy equivalent, a user with no permission, and the legacy path with the flag off. Co-Authored-By: Claude Sonnet 5.5 --- .../rest_api/tests/test_views.py | 75 +++++++++++++++++-- .../course_groups/rest_api/views.py | 8 +- 2 files changed, 74 insertions(+), 9 deletions(-) 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( From 35e4ddfe8ba679c8c85081ed0be1677ddea1a142 Mon Sep 17 00:00:00 2001 From: Bryann Valderrama Date: Tue, 1 Dec 2026 13:10:14 -0500 Subject: [PATCH 5/6] test: cover the legacy checks and forum role access of the Cohorts tab Add tests for every legacy check of the Instructor Dashboard across the different user types, and make sure each permission in LEGACY_PERMISSION_CHECKS has an expected rule. For the cohorts endpoints, cover the access of the forum roles with the flag on and off, and that Course Limited Staff keeps its legacy access through compat.py with the flag on. Co-Authored-By: Claude Sonnet 5.5 --- .../instructor/authz/tests/test_legacy.py | 347 +++++++++++++++++- .../course_groups/tests/test_views_authz.py | 73 +++- 2 files changed, 418 insertions(+), 2 deletions(-) diff --git a/lms/djangoapps/instructor/authz/tests/test_legacy.py b/lms/djangoapps/instructor/authz/tests/test_legacy.py index a0268a53d772..fa6a05762ebc 100644 --- a/lms/djangoapps/instructor/authz/tests/test_legacy.py +++ b/lms/djangoapps/instructor/authz/tests/test_legacy.py @@ -2,14 +2,123 @@ 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.authz.legacy import is_django_staff +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 @@ -34,3 +143,239 @@ def test_course_instructor_without_is_staff_is_denied(self): 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/openedx/core/djangoapps/course_groups/tests/test_views_authz.py b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py index 6a2a3dbd8576..67263cf92997 100644 --- a/openedx/core/djangoapps/course_groups/tests/test_views_authz.py +++ b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py @@ -6,8 +6,9 @@ import tempfile from unittest.mock import patch +import ddt from django.urls import reverse -from openedx_authz.authz import COURSE_ADMIN, COURSE_STAFF +from openedx_authz.authz import COURSE_ADMIN, COURSE_LIMITED_STAFF, COURSE_STAFF from rest_framework import status from rest_framework.test import APIClient @@ -15,6 +16,12 @@ 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 @@ -23,6 +30,7 @@ @skip_unless_lms +@ddt.ddt class CohortsAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): """ AuthZ enforcement across every endpoint behind the Cohorts tab. @@ -140,6 +148,69 @@ def test_legacy_does_not_query_authz(self): assert response.status_code == status.HTTP_200_OK is_user_allowed.assert_not_called() + def _create_forum_user(self, role_name): + """ + Create a user that only holds a forum role in the course. + + Args: + role_name (str): The forum role to grant. + + Returns: + User: The new user. + """ + user = UserFactory() + Role.objects.get_or_create(name=role_name, course_id=self.course_key)[0].users.add(user) + return user + + @ddt.data(FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA) + def test_legacy_forum_role_access_per_endpoint(self, role_name): + """ + With the flag off, forum roles only read through the ``CohortHandler`` GET. + + The other GET views also require course staff, and every write is denied by + the permission class. + + Args: + role_name (str): The forum role to grant. + """ + self.set_authz_enabled(False) + user = self._create_forum_user(role_name) + expected_view_statuses = { + "cohort_settings": status.HTTP_404_NOT_FOUND, + "cohort_handler": status.HTTP_200_OK, + "cohort_users": status.HTTP_404_NOT_FOUND, + } + + for name, url_kwargs, method, request_kwargs in self.VIEW_REQUESTS: + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code == expected_view_statuses[name], name + + for name, url_kwargs, method, request_kwargs in self.MANAGE_REQUESTS: + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + + @ddt.data(FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA) + def test_forum_role_is_denied_with_flag_on(self, role_name): + """ + With the flag on, a forum role without an AuthZ role grants no access. + + Args: + role_name (str): The forum role to grant. + """ + user = self._create_forum_user(role_name) + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + + def test_compat_legacy_role_keeps_access(self): + """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) + + for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): + response = self._request(user, name, url_kwargs, method, request_kwargs) + assert response.status_code < 300, (name, method, response.status_code, response.data) + @skip_unless_lms class CohortSettingsHandlerAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): From 77dfb5b87a198ac7f4f671fcf26928c801b1e81c Mon Sep 17 00:00:00 2001 From: Bryann Valderrama Date: Tue, 1 Dec 2026 13:34:00 -0500 Subject: [PATCH 6/6] fix: keep forum roles out of the cohort settings and cohort users reads With authz.enable_course_authoring enabled, the legacy roles of compat.py fall back to the legacy check, and the cohorts API no longer checks course staff access afterwards. The default view check admits the forum Administrator, Moderator and Community TA roles, so a user such as a Course Beta Tester who was also a Community TA could read the cohort settings and the users in a cohort, which include usernames, emails and names. CohortSettings and CohortUsers now use has_cohort_manage_access as their legacy check, which matches the access they required before AuthZ. CohortHandler keeps the default, since forum roles could already read it. With the flag disabled, forum roles now get a 403 instead of a 404 on those two GET requests. Also parametrize the endpoint loops of CohortsAuthzTest with ddt. Co-Authored-By: Claude Sonnet 5.5 --- .../course_groups/tests/test_views_authz.py | 214 ++++++++++-------- .../core/djangoapps/course_groups/views.py | 14 +- 2 files changed, 130 insertions(+), 98 deletions(-) diff --git a/openedx/core/djangoapps/course_groups/tests/test_views_authz.py b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py index 67263cf92997..db91f65ecd1a 100644 --- a/openedx/core/djangoapps/course_groups/tests/test_views_authz.py +++ b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py @@ -8,7 +8,7 @@ import ddt from django.urls import reverse -from openedx_authz.authz import COURSE_ADMIN, COURSE_LIMITED_STAFF, COURSE_STAFF +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 @@ -29,6 +29,26 @@ 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): @@ -50,46 +70,45 @@ def setUp(self): def _url(self, name, **kwargs): return reverse(f"api_cohorts:{name}", kwargs={"course_key_string": str(self.course_key), **kwargs}) - # (name, kwargs, http method, request kwargs) - 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"}), - ) - 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 test_course_admin_can_view_and_manage(self): + 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) - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code < 300, (name, method, response.status_code, response.data) + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data - def test_course_staff_can_view_and_manage(self): + @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) - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code < 300, (name, method, response.status_code, response.data) + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data - def test_authz_role_without_legacy_equivalent_can_view_and_manage(self): + @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) @@ -97,45 +116,49 @@ def test_authz_role_without_legacy_equivalent_can_view_and_manage(self): "common.djangoapps.student.roles.get_authz_compat_course_access_roles_for_user", return_value=set(), ): - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code < 300, (name, method, response.status_code, response.data) + response = self._request(user, name, url_kwargs, method, request_kwargs) - def test_user_without_permission_is_denied(self): + 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.""" - user = UserFactory() + response = self._request(UserFactory(), name, url_kwargs, method, request_kwargs) - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + assert response.status_code == status.HTTP_403_FORBIDDEN - def test_authz_denied_overrides_legacy_roles(self): + @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) - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - with self.subTest(name=name, method=method): - 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 + 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 - def test_legacy_instructor_keeps_access(self): + @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) - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(instructor, name, url_kwargs, method, request_kwargs) - assert response.status_code < 300, (name, method, response.status_code, response.data) + response = self._request(instructor, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data - def test_legacy_student_is_denied(self): + @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) - user = UserFactory() - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + 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.""" @@ -148,68 +171,69 @@ def test_legacy_does_not_query_authz(self): assert response.status_code == status.HTTP_200_OK is_user_allowed.assert_not_called() - def _create_forum_user(self, role_name): + @ddt.data(*ALL_REQUESTS) + @ddt.unpack + def test_legacy_forum_role_access_per_endpoint(self, name, url_kwargs, method, request_kwargs): """ - Create a user that only holds a forum role in the course. - - Args: - role_name (str): The forum role to grant. + With the flag off, forum roles only read through the ``CohortHandler`` GET. - Returns: - User: The new user. + Every other endpoint is denied by the permission class. """ - user = UserFactory() - Role.objects.get_or_create(name=role_name, course_id=self.course_key)[0].users.add(user) - return user + 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 - @ddt.data(FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA) - def test_legacy_forum_role_access_per_endpoint(self, role_name): - """ - With the flag off, forum roles only read through the ``CohortHandler`` GET. + for role_name in FORUM_ROLES: + with self.subTest(role_name=role_name): + user = UserFactory() + self._grant_forum_role(user, role_name) - The other GET views also require course staff, and every write is denied by - the permission class. + response = self._request(user, name, url_kwargs, method, request_kwargs) - Args: - role_name (str): The forum role to grant. - """ - self.set_authz_enabled(False) - user = self._create_forum_user(role_name) - expected_view_statuses = { - "cohort_settings": status.HTTP_404_NOT_FOUND, - "cohort_handler": status.HTTP_200_OK, - "cohort_users": status.HTTP_404_NOT_FOUND, - } - - for name, url_kwargs, method, request_kwargs in self.VIEW_REQUESTS: - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code == expected_view_statuses[name], name + assert response.status_code == expected_status - for name, url_kwargs, method, request_kwargs in self.MANAGE_REQUESTS: - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + @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(FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA) - def test_forum_role_is_denied_with_flag_on(self, role_name): + @ddt.data("cohort_settings", "cohort_users") + def test_compat_role_with_forum_role_cannot_read_staff_endpoints(self, name): """ - With the flag on, a forum role without an AuthZ role grants no access. + With the flag on, the ``compat.py`` fallback does not let a forum role read the + endpoints that required course staff. Args: - role_name (str): The forum role to grant. + name (str): The URL name of the endpoint. """ - user = self._create_forum_user(role_name) + url_kwargs = {"cohort_id": self.cohort.id} if name == "cohort_users" else {} - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code == status.HTTP_403_FORBIDDEN, (name, method) + 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) - def test_compat_legacy_role_keeps_access(self): + 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) - for name, url_kwargs, method, request_kwargs in (*self.VIEW_REQUESTS, *self.MANAGE_REQUESTS): - response = self._request(user, name, url_kwargs, method, request_kwargs) - assert response.status_code < 300, (name, method, response.status_code, response.data) + response = self._request(user, name, url_kwargs, method, request_kwargs) + + assert response.status_code < 300, response.data @skip_unless_lms diff --git a/openedx/core/djangoapps/course_groups/views.py b/openedx/core/djangoapps/course_groups/views.py index d8e0fb018b86..12ffb70d6abc 100644 --- a/openedx/core/djangoapps/course_groups/views.py +++ b/openedx/core/djangoapps/course_groups/views.py @@ -31,6 +31,7 @@ from common.djangoapps.util.json_request import JsonResponse, expect_json 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, @@ -441,9 +442,11 @@ def _get_course_with_access(request, course_key_string, action='staff'): 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 check is not redundant there: - the legacy view access also lets forum Administrator, Moderator and Community TA roles in, - and the ``staff`` check is what keeps them out of the endpoints that require course staff. + 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): @@ -543,6 +546,9 @@ class CohortSettings(DeveloperErrorViewMixin, APIPermissions): "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): """ @@ -826,6 +832,8 @@ class CohortUsers(DeveloperErrorViewMixin, APIPermissions): "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): """