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/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 d8f5df6cd21a..dc25720171fd 100644 --- a/lms/djangoapps/instructor/authz/tests/test_permissions.py +++ b/lms/djangoapps/instructor/authz/tests/test_permissions.py @@ -158,6 +158,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=(constants.COURSES_VIEW_ENROLLMENTS,), 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..4918e1996379 100644 --- a/lms/djangoapps/instructor/views/api.py +++ b/lms/djangoapps/instructor/views/api.py @@ -42,7 +42,6 @@ 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 +80,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 import constants as authz_constants +from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission from lms.djangoapps.instructor.constants import INVOICE_KEY from lms.djangoapps.instructor.enrollment import ( enroll_email, @@ -1855,7 +1856,18 @@ class CohortCSV(DeveloperErrorViewMixin, APIView): BearerAuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) - permission_classes = (IsAuthenticated, IsAdminUser) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = (authz_constants.COURSES_MANAGE_COHORTS,) + 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..c4f892ee03ab --- /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.constants.roles 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 4f42516fda14..dded159add30 100644 --- a/openedx/core/djangoapps/course_groups/views.py +++ b/openedx/core/djangoapps/course_groups/views.py @@ -28,12 +28,14 @@ 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 import constants as authz_constants +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 = ( + authz_constants.COURSES_MANAGE_COHORTS if request.method == 'PATCH' + else authz_constants.COURSES_VIEW_COHORTS + ) + 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 @@ -498,6 +519,10 @@ class CohortSettings(DeveloperErrorViewMixin, APIPermissions): * is_cohorted: current status of the cohort setting """ + authz_permissions = { + "GET": (authz_constants.COURSES_VIEW_COHORTS,), + "PUT": (authz_constants.COURSES_MANAGE_COHORTS,), + } def get(self, request, course_key_string): """ @@ -575,6 +600,11 @@ class CohortHandler(DeveloperErrorViewMixin, APIPermissions): * group_id: The integer identifier of the specific group in the partition. """ queryset = [] + authz_permissions = { + "GET": (authz_constants.COURSES_VIEW_COHORTS,), + "POST": (authz_constants.COURSES_MANAGE_COHORTS,), + "PATCH": (authz_constants.COURSES_MANAGE_COHORTS,), + } def get(self, request, course_key_string, cohort_id=None): """ @@ -760,6 +790,11 @@ class CohortUsers(DeveloperErrorViewMixin, APIPermissions): Returns a HTTP 204 No Content response status code to indicate success. """ serializer_class = CohortUsersAPISerializer + authz_permissions = { + "GET": (authz_constants.COURSES_VIEW_COHORTS,), + "POST": (authz_constants.COURSES_MANAGE_COHORTS,), + "DELETE": (authz_constants.COURSES_MANAGE_COHORTS,), + } def _get_course_and_cohort(self, request, course_key_string, cohort_id): """