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..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/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 e10305a0423c..9c639178ad7d 100644 --- a/lms/djangoapps/instructor/views/api.py +++ b/lms/djangoapps/instructor/views/api.py @@ -38,11 +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_MANAGE_COHORTS 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 @@ -81,6 +81,8 @@ 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 ( enroll_email, @@ -1850,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..6a2a3dbd8576 --- /dev/null +++ b/openedx/core/djangoapps/course_groups/tests/test_views_authz.py @@ -0,0 +1,243 @@ +""" +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_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() + + 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 4f42516fda14..cb74274bc468 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,16 @@ 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 ( 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 +120,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 +146,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 +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) @@ -478,7 +512,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 @@ -498,6 +535,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): """ @@ -575,6 +616,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): """ @@ -760,6 +806,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): """