From c25bee6f848b1e909ef9b7e659b0b4616152df1d Mon Sep 17 00:00:00 2001 From: carlos-marquez-wgu Date: Wed, 4 Nov 2026 15:49:22 -0600 Subject: [PATCH] feat: enforce AuthZ permissions in the Grading endpoints Migrate the Grading tab endpoints of the Instructor Dashboard API v2 from InstructorPermission to InstructorAuthzPermission: - LearnerView (GET): courses.view_gradebook - ProblemView (GET): courses.view_gradebook - GradingConfigView (GET): courses.view_grading_settings - ResetAttemptsView (POST): courses.manage_learner_grading - DeleteStateView (DELETE): courses.manage_learner_grading - RescoreView (POST): courses.manage_learner_grading - ScoreOverrideView (PUT): courses.manage_learner_grading --- .../instructor/tests/test_api_v2_authz.py | 269 +++++++++++++++++- lms/djangoapps/instructor/views/api_v2.py | 64 +++-- 2 files changed, 307 insertions(+), 26 deletions(-) diff --git a/lms/djangoapps/instructor/tests/test_api_v2_authz.py b/lms/djangoapps/instructor/tests/test_api_v2_authz.py index 32d0b552de36..027e49ec6660 100644 --- a/lms/djangoapps/instructor/tests/test_api_v2_authz.py +++ b/lms/djangoapps/instructor/tests/test_api_v2_authz.py @@ -4,6 +4,9 @@ They cover the tabs, ``authz_enabled`` and the migrated endpoints. """ +import json +from itertools import product +from textwrap import dedent from unittest.mock import patch import ddt @@ -16,21 +19,26 @@ COURSE_LIMITED_STAFF, ) from openedx_authz.applets.learner_administration.constants import COURSES_VIEW_COURSE_INFO -from openedx_authz.authz import COURSE_ADMIN, COURSE_STAFF +from openedx_authz.applets.learner_grading.constants import COURSES_MANAGE_LEARNER_GRADING, COURSES_VIEW_GRADEBOOK +from openedx_authz.authz import COURSE_ADMIN, COURSE_STAFF, COURSES_VIEW_GRADING_SETTINGS from rest_framework import status from rest_framework.test import APIClient -from common.djangoapps.student.roles import CourseDataResearcherRole, CourseLimitedStaffRole +from common.djangoapps.student.models import CourseEnrollment +from common.djangoapps.student.roles import CourseBetaTesterRole, CourseDataResearcherRole, CourseLimitedStaffRole from common.djangoapps.student.tests.factories import ( InstructorFactory, StaffFactory, UserFactory, ) +from lms.djangoapps.courseware.models import StudentModule from lms.djangoapps.courseware.tabs import get_course_tab_list from lms.djangoapps.instructor.authz import constants +from lms.djangoapps.instructor.authz.compat import LEGACY_ROLE_COMPAT_PERMISSIONS from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin +from lms.djangoapps.instructor_task.models import InstructorTask from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory +from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory API = "lms.djangoapps.instructor.authz.api" @@ -43,6 +51,20 @@ ] +def allowed_only(*permissions): + """ + Build an ``is_user_allowed`` side effect that grants only the given permissions. + """ + return lambda _username, permission, _scope: permission in permissions + + +def allowed_all_except(*permissions): + """ + Build an ``is_user_allowed`` side effect that grants every permission but the given ones. + """ + return lambda _username, permission, _scope: permission not in permissions + + @ddt.ddt class CourseMetadataViewAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): """ @@ -193,9 +215,6 @@ def test_authz_tab_shown_with_any_of_its_permissions(self, tab_id, tab_permissio """ user = UserFactory() - def allowed_only(*permissions): - return lambda _username, permission, _scope: permission in permissions - with patch( f"{API}.authz_api.is_user_allowed", side_effect=allowed_only(COURSES_VIEW_COURSE_INFO.identifier), @@ -312,3 +331,241 @@ def test_legacy_without_role_hidden(self): self.set_authz_enabled(False) assert not self._has_instructor_tab(UserFactory()) + + +# Grading tab requests: the AuthZ permission each one requires and the status it returns on success. +GRADING_ACTIONS = { + "view_learner": (COURSES_VIEW_GRADEBOOK.identifier, status.HTTP_200_OK), + "view_problem": (COURSES_VIEW_GRADEBOOK.identifier, status.HTTP_200_OK), + "view_grading_config": (COURSES_VIEW_GRADING_SETTINGS.identifier, status.HTTP_200_OK), + "reset_attempts": (COURSES_MANAGE_LEARNER_GRADING.identifier, status.HTTP_200_OK), + "delete_state": (COURSES_MANAGE_LEARNER_GRADING.identifier, status.HTTP_200_OK), + "rescore": (COURSES_MANAGE_LEARNER_GRADING.identifier, status.HTTP_202_ACCEPTED), + "override_score": (COURSES_MANAGE_LEARNER_GRADING.identifier, status.HTTP_202_ACCEPTED), + "reset_attempts_all_learners": (COURSES_MANAGE_LEARNER_GRADING.identifier, status.HTTP_202_ACCEPTED), + "rescore_all_learners": (COURSES_MANAGE_LEARNER_GRADING.identifier, status.HTTP_202_ACCEPTED), +} + +# All Learners actions. With the flag off, they also require instructor access. +ALL_LEARNERS_GRADING_ACTIONS = ("reset_attempts_all_learners", "rescore_all_learners") + +# The reads and the Single Learner actions, which legacy course staff can use with the flag off. +LEGACY_STAFF_GRADING_ACTIONS = tuple( + action for action in GRADING_ACTIONS if action not in ALL_LEARNERS_GRADING_ACTIONS +) + +# Legacy roles that openedx-authz maps without dashboard permissions (see ``authz/compat.py``), +# each with its AuthZ role. +LEGACY_COMPAT_ROLES = ( + (COURSE_LIMITED_STAFF.external_key, CourseLimitedStaffRole), + (COURSE_DATA_RESEARCHER.external_key, CourseDataResearcherRole), + (COURSE_BETA_TESTER.external_key, CourseBetaTesterRole), +) + + +@ddt.ddt +class GradingTabAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): + """ + The Grading tab endpoints follow the AuthZ flag. + + With the flag on, ``LearnerView`` and ``ProblemView`` require + ``courses.view_gradebook``, ``GradingConfigView`` requires + ``courses.view_grading_settings``, and the Single Learner and All Learners + actions require ``courses.manage_learner_grading``. With the flag off, + each view uses its legacy bridgekeeper permission, and the All Learners + actions also require instructor access. + + The functional behavior of each endpoint, with a legacy instructor, is + covered in ``tests/views/test_api_v2.py``. + """ + + PROBLEM_XML = dedent("""\ + + + + + + """) + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.course = CourseFactory.create() + cls.course_key = cls.course.id + chapter = BlockFactory.create(parent=cls.course, category="chapter") + sequential = BlockFactory.create(parent=chapter, category="sequential") + cls.problem = BlockFactory.create(parent=sequential, category="problem", data=cls.PROBLEM_XML) + + def setUp(self): + super().setUp() + self.client = APIClient() + # The asynchronous actions only queue their task, and deleting state skips the grade signal. + for target in ( + "lms.djangoapps.instructor_task.tasks.reset_problem_attempts.apply_async", + "lms.djangoapps.instructor_task.tasks.rescore_problem.apply_async", + "lms.djangoapps.instructor_task.tasks.override_problem_score.apply_async", + "lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send", + ): + patcher = patch(target) + patcher.start() + self.addCleanup(patcher.stop) + self.learner = UserFactory() + CourseEnrollment.enroll(self.learner, self.course_key) + self._reset_learner_state() + + def _reset_learner_state(self): + """Give the learner problem state and drop the queued tasks, so an action can be sent again.""" + InstructorTask.objects.filter(course_id=self.course_key).delete() + StudentModule.objects.update_or_create( + student=self.learner, + course_id=self.course_key, + module_state_key=self.problem.location, + defaults={"state": json.dumps({"attempts": 1})}, + ) + + def _request(self, action, user): + """Send the request of a Grading tab action as ``user``.""" + self.client.force_authenticate(user=user) + course_id = str(self.course_key) + problem = str(self.problem.location) + single_learner = f"?learner={self.learner.username}" + + def grading_url(name): + return reverse(f"instructor_api_v2:{name}", kwargs={"course_id": course_id, "problem": problem}) + + requests = { + "view_learner": lambda: self.client.get(reverse( + "instructor_api_v2:learner_detail", + kwargs={"course_id": course_id, "email_or_username": self.learner.username}, + )), + "view_problem": lambda: self.client.get(reverse( + "instructor_api_v2:problem_detail", kwargs={"course_id": course_id, "location": problem}, + )), + "view_grading_config": lambda: self.client.get(reverse( + "instructor_api_v2:grading_config", kwargs={"course_id": course_id}, + )), + "reset_attempts": lambda: self.client.post(grading_url("reset_attempts") + single_learner), + "delete_state": lambda: self.client.delete(grading_url("delete_state") + single_learner), + "rescore": lambda: self.client.post(grading_url("rescore") + single_learner), + "override_score": lambda: self.client.put( + grading_url("score_override") + single_learner, {"score": 0.5}, format="json", + ), + "reset_attempts_all_learners": lambda: self.client.post(grading_url("reset_attempts")), + "rescore_all_learners": lambda: self.client.post(grading_url("rescore")), + } + return requests[action]() + + def _has_queued_task(self): + """Check whether any instructor task was submitted for the course.""" + return InstructorTask.objects.filter(course_id=self.course_key).exists() + + @ddt.data(*product((COURSE_ADMIN.external_key, COURSE_STAFF.external_key), GRADING_ACTIONS)) + @ddt.unpack + def test_authz_course_role_allowed(self, authz_role, action): + """ + With the flag on, Course Admin and Course Staff can use every Grading tab + action, including the All Learners actions that legacy course staff cannot run. + """ + user = self.create_user_with_authz_role(authz_role, self.course_key) + + response = self._request(action, user) + + assert response.status_code == GRADING_ACTIONS[action][1] + + @ddt.data(*GRADING_ACTIONS) + def test_authz_without_permission_denied(self, action): + """With the flag on, a user without AuthZ permissions is denied every Grading tab action.""" + user = UserFactory() + + response = self._request(action, user) + + assert response.status_code == status.HTTP_403_FORBIDDEN + assert not self._has_queued_task() + + @ddt.data(*GRADING_ACTIONS) + def test_authz_requires_permission(self, action): + """ + With the flag on, each action requires its own permission: no other + permission grants it, even to a Course Admin. + """ + permission = GRADING_ACTIONS[action][0] + user = self.create_user_with_authz_role(COURSE_ADMIN.external_key, self.course_key) + + # A Course Admin does not hold the legacy compatibility permissions; granting them + # would send the check to the legacy rule, which a Course Admin passes. + denied = allowed_all_except(permission, *LEGACY_ROLE_COMPAT_PERMISSIONS) + with patch(f"{API}.authz_api.is_user_allowed", side_effect=denied): + response = self._request(action, user) + + assert response.status_code == status.HTTP_403_FORBIDDEN + assert not self._has_queued_task() + + @ddt.data(*GRADING_ACTIONS) + def test_authz_permission_alone_grants(self, action): + """With the flag on, the action's permission grants it to a user without any course role.""" + permission, expected_status = GRADING_ACTIONS[action] + user = UserFactory() + + with patch(f"{API}.authz_api.is_user_allowed", side_effect=allowed_only(permission)): + response = self._request(action, user) + + assert response.status_code == expected_status + + @ddt.data(*product(LEGACY_COMPAT_ROLES, GRADING_ACTIONS)) + @ddt.unpack + def test_authz_legacy_compat_role_keeps_legacy_access(self, roles, action): + """ + With the flag on, a legacy role that openedx-authz maps without dashboard + permissions gets the same result as the legacy role with the flag off. + """ + authz_role, legacy_role = roles + authz_user = self.create_user_with_authz_role(authz_role, self.course_key) + + authz_status = self._request(action, authz_user).status_code + + self._reset_learner_state() + self.set_authz_enabled(False) + legacy_user = UserFactory() + legacy_role(self.course_key).add_users(legacy_user) + + legacy_status = self._request(action, legacy_user).status_code + + assert authz_status == legacy_status + + @ddt.data(*LEGACY_STAFF_GRADING_ACTIONS) + def test_legacy_staff_allowed(self, action): + """With the flag off, legacy course staff can use the reads and the Single Learner actions.""" + self.set_authz_enabled(False) + staff = StaffFactory(course_key=self.course_key) + + with patch(f"{API}.authz_api.is_user_allowed") as is_user_allowed: + response = self._request(action, staff) + + assert response.status_code == GRADING_ACTIONS[action][1] + is_user_allowed.assert_not_called() + + @ddt.data(*ALL_LEARNERS_GRADING_ACTIONS) + def test_legacy_staff_cannot_run_all_learners_action(self, action): + """With the flag off, legacy course staff cannot run an All Learners action: it needs instructor access.""" + self.set_authz_enabled(False) + staff = StaffFactory(course_key=self.course_key) + + with patch(f"{API}.authz_api.is_user_allowed") as is_user_allowed: + response = self._request(action, staff) + + assert response.status_code == status.HTTP_403_FORBIDDEN + # Denied by the view's own check, not by the permission class (which answers with ``developer_message``). + assert "error" in response.data + assert not self._has_queued_task() + is_user_allowed.assert_not_called() + + @ddt.data(*GRADING_ACTIONS) + def test_legacy_without_role_denied(self, action): + """With the flag off, a user without a course role is denied every Grading tab action.""" + self.set_authz_enabled(False) + user = UserFactory() + + response = self._request(action, user) + + assert response.status_code == status.HTTP_403_FORBIDDEN + assert not self._has_queued_task() diff --git a/lms/djangoapps/instructor/views/api_v2.py b/lms/djangoapps/instructor/views/api_v2.py index dbf64692a1b7..ad257789a8ae 100644 --- a/lms/djangoapps/instructor/views/api_v2.py +++ b/lms/djangoapps/instructor/views/api_v2.py @@ -51,6 +51,8 @@ from edx_when import api as edx_when_api from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey +from openedx_authz.applets.learner_grading.constants import COURSES_MANAGE_LEARNER_GRADING, COURSES_VIEW_GRADEBOOK +from openedx_authz.authz import COURSES_VIEW_GRADING_SETTINGS from pytz import UTC from rest_framework import status from rest_framework.exceptions import NotFound, PermissionDenied @@ -86,7 +88,6 @@ ) from lms.djangoapps.course_home_api.toggles import course_home_mfe_progress_tab_is_active from lms.djangoapps.courseware.access import has_access -from lms.djangoapps.courseware.courses import get_course_with_access from lms.djangoapps.courseware.masquerade import get_masquerade_role, setup_masquerade from lms.djangoapps.courseware.models import StudentModule from lms.djangoapps.courseware.tabs import get_course_tab_list @@ -105,7 +106,7 @@ ) from lms.djangoapps.instructor.authz import constants as authz_constants from lms.djangoapps.instructor.authz import legacy as authz_legacy -from lms.djangoapps.instructor.authz.api import user_has_any_instructor_permission +from lms.djangoapps.instructor.authz.api import user_has_any_instructor_permission, user_has_instructor_permission from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission from lms.djangoapps.instructor.constants import ReportType from lms.djangoapps.instructor.enrollment import ( @@ -2565,7 +2566,10 @@ class LearnerView(DeveloperErrorViewMixin, APIView): } ``` """ - permission_classes = (IsAuthenticated, permissions.InstructorPermission) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = { + "GET": (COURSES_VIEW_GRADEBOOK.identifier,), + } permission_name = permissions.VIEW_DASHBOARD @extend_schema( @@ -2663,7 +2667,10 @@ class ProblemView(DeveloperErrorViewMixin, APIView): } ``` """ - permission_classes = (IsAuthenticated, permissions.InstructorPermission) + permission_classes = (IsAuthenticated, InstructorAuthzPermission) + authz_permissions = { + "GET": (COURSES_VIEW_GRADEBOOK.identifier,), + } permission_name = permissions.VIEW_DASHBOARD @extend_schema( @@ -2896,7 +2903,10 @@ class GradingConfigView(DeveloperErrorViewMixin, APIView): ``text/html`` so the MFE can render it directly inside a ``
`` block
     without additional parsing.
     """
-    permission_classes = (IsAuthenticated, permissions.InstructorPermission)
+    permission_classes = (IsAuthenticated, InstructorAuthzPermission)
+    authz_permissions = {
+        "GET": (COURSES_VIEW_GRADING_SETTINGS.identifier,),
+    }
     permission_name = permissions.VIEW_DASHBOARD
 
     @extend_schema(
@@ -3735,7 +3745,10 @@ class ResetAttemptsView(DeveloperErrorViewMixin, APIView):
     **POST** with `learner` query param: resets a single learner's attempts (synchronous).
     **POST** without `learner`: queues a background task to reset all learners (asynchronous).
     """
-    permission_classes = (IsAuthenticated, permissions.InstructorPermission)
+    permission_classes = (IsAuthenticated, InstructorAuthzPermission)
+    authz_permissions = {
+        "POST": (COURSES_MANAGE_LEARNER_GRADING.identifier,),
+    }
     permission_name = permissions.GIVE_STUDENT_EXTENSION
 
     @extend_schema(
@@ -3801,8 +3814,12 @@ def post(self, request, course_id, problem):
             return Response(serializer.data, status=status.HTTP_200_OK)
 
         else:
-            course = get_course_with_access(request.user, 'staff', course_key, depth=None)
-            if not has_access(request.user, 'instructor', course):
+            if not user_has_instructor_permission(
+                request.user,
+                COURSES_MANAGE_LEARNER_GRADING.identifier,
+                course_key,
+                authz_legacy.has_instructor_access,
+            ):
                 return Response(
                     {'error': 'Instructor access required for bulk operations'},
                     status=status.HTTP_403_FORBIDDEN,
@@ -3834,7 +3851,10 @@ class DeleteStateView(DeveloperErrorViewMixin, APIView):
     The `learner` query parameter is required. This operation is destructive
     and cannot be undone.
     """
-    permission_classes = (IsAuthenticated, permissions.InstructorPermission)
+    permission_classes = (IsAuthenticated, InstructorAuthzPermission)
+    authz_permissions = {
+        "DELETE": (COURSES_MANAGE_LEARNER_GRADING.identifier,),
+    }
     permission_name = permissions.GIVE_STUDENT_EXTENSION
 
     @extend_schema(
@@ -3914,7 +3934,10 @@ class RescoreView(DeveloperErrorViewMixin, APIView):
     Optionally accepts `only_if_higher=true` (query param or request body) to only
     update if the new score is higher.
     """
-    permission_classes = (IsAuthenticated, permissions.InstructorPermission)
+    permission_classes = (IsAuthenticated, InstructorAuthzPermission)
+    authz_permissions = {
+        "POST": (COURSES_MANAGE_LEARNER_GRADING.identifier,),
+    }
     permission_name = permissions.OVERRIDE_GRADES
 
     @extend_schema(
@@ -3984,8 +4007,12 @@ def post(self, request, course_id, problem):
             )
 
         else:
-            course = get_course_with_access(request.user, 'staff', course_key)
-            if not has_access(request.user, 'instructor', course):
+            if not user_has_instructor_permission(
+                request.user,
+                COURSES_MANAGE_LEARNER_GRADING.identifier,
+                course_key,
+                authz_legacy.has_instructor_access,
+            ):
                 return Response(
                     {'error': 'Instructor access required for bulk operations'},
                     status=status.HTTP_403_FORBIDDEN,
@@ -4021,7 +4048,10 @@ class ScoreOverrideView(DeveloperErrorViewMixin, APIView):
 
     The `learner` query parameter is required. Accepts a JSON body with `score` field.
     """
-    permission_classes = (IsAuthenticated, permissions.InstructorPermission)
+    permission_classes = (IsAuthenticated, InstructorAuthzPermission)
+    authz_permissions = {
+        "PUT": (COURSES_MANAGE_LEARNER_GRADING.identifier,),
+    }
     permission_name = permissions.OVERRIDE_GRADES
 
     @extend_schema(
@@ -4070,19 +4100,13 @@ def put(self, request, course_id, problem):
         score = body_serializer.validated_data['score']
 
         try:
-            block = modulestore().get_item(usage_key)
+            modulestore().get_item(usage_key)
         except ItemNotFoundError:
             return Response(
                 {'error': 'Problem not found'},
                 status=status.HTTP_404_NOT_FOUND,
             )
 
-        if not has_access(request.user, 'staff', block):
-            return Response(
-                {'error': 'You do not have permission to override scores for this problem'},
-                status=status.HTTP_403_FORBIDDEN,
-            )
-
         try:
             instructor_task = task_api.submit_override_score(
                 request, usage_key, student, score,