Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lms/djangoapps/instructor/authz/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from openedx_authz.authz import (
COURSES_ENROLL_LEARNERS,
COURSES_MANAGE_BULK_LEARNER_GRADING,
COURSES_MANAGE_COHORTS,
COURSES_MANAGE_COURSE_TEAM,
COURSES_MANAGE_LEARNER_EXTENSIONS,
Expand Down Expand Up @@ -36,6 +37,7 @@
COURSES_VIEW_GRADING_SETTINGS.identifier,
COURSES_MANAGE_LEARNER_GRADING.identifier,
COURSES_VIEW_LEARNER_COURSE_STATUS.identifier,
COURSES_MANAGE_BULK_LEARNER_GRADING.identifier,
COURSES_VIEW_LEARNER_EXTENSIONS.identifier,
COURSES_MANAGE_LEARNER_EXTENSIONS.identifier,
COURSES_VIEW_COHORTS.identifier,
Expand Down
2 changes: 2 additions & 0 deletions lms/djangoapps/instructor/authz/legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from opaque_keys.edx.keys import CourseKey
from openedx_authz.authz import (
COURSES_ENROLL_LEARNERS,
COURSES_MANAGE_BULK_LEARNER_GRADING,
COURSES_MANAGE_COHORTS,
COURSES_MANAGE_COURSE_TEAM,
COURSES_MANAGE_LEARNER_EXTENSIONS,
Expand Down Expand Up @@ -216,6 +217,7 @@ def _check(user: AbstractUser, course_key: CourseKey) -> bool:
COURSES_VIEW_GRADING_SETTINGS.identifier: has_grading_settings_access,
COURSES_MANAGE_LEARNER_GRADING.identifier: bridgekeeper_check(permissions.OVERRIDE_GRADES),
COURSES_VIEW_LEARNER_COURSE_STATUS.identifier: bridgekeeper_check(permissions.VIEW_DASHBOARD),
COURSES_MANAGE_BULK_LEARNER_GRADING.identifier: has_instructor_access,
COURSES_VIEW_LEARNER_EXTENSIONS.identifier: bridgekeeper_check(permissions.VIEW_DASHBOARD),
COURSES_MANAGE_LEARNER_EXTENSIONS.identifier: bridgekeeper_check(permissions.GIVE_STUDENT_EXTENSION),
COURSES_VIEW_COHORTS.identifier: has_cohort_view_access,
Expand Down
2 changes: 2 additions & 0 deletions lms/djangoapps/instructor/authz/tests/test_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from opaque_keys.edx.locator import CourseLocator
from openedx_authz.authz import (
COURSES_ENROLL_LEARNERS,
COURSES_MANAGE_BULK_LEARNER_GRADING,
COURSES_MANAGE_COHORTS,
COURSES_MANAGE_COURSE_TEAM,
COURSES_MANAGE_LEARNER_EXTENSIONS,
Expand Down Expand Up @@ -358,6 +359,7 @@ class LegacyPermissionChecksTest(TestCase):
COURSES_VIEW_GRADING_SETTINGS.identifier: STUDIO_READ_ACCESS,
COURSES_MANAGE_LEARNER_GRADING.identifier: STAFF_ACCESS,
COURSES_VIEW_LEARNER_COURSE_STATUS.identifier: DASHBOARD_ACCESS,
COURSES_MANAGE_BULK_LEARNER_GRADING.identifier: INSTRUCTOR_ACCESS,
COURSES_VIEW_LEARNER_EXTENSIONS.identifier: DASHBOARD_ACCESS,
COURSES_MANAGE_LEARNER_EXTENSIONS.identifier: STAFF_ACCESS,
COURSES_VIEW_COHORTS.identifier: COHORT_VIEW_ACCESS,
Expand Down
275 changes: 275 additions & 0 deletions lms/djangoapps/instructor/tests/test_api_v2_authz.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
They cover the tabs, ``authz_enabled`` and the migrated endpoints.
"""

import json
from datetime import datetime
from itertools import product
from textwrap import dedent
from unittest.mock import patch

import ddt
Expand All @@ -23,13 +26,16 @@
COURSE_LIMITED_STAFF,
COURSE_STAFF,
COURSES_ENROLL_LEARNERS,
COURSES_MANAGE_BULK_LEARNER_GRADING,
COURSES_MANAGE_COURSE_TEAM,
COURSES_MANAGE_LEARNER_EXTENSIONS,
COURSES_MANAGE_LEARNER_GRADING,
COURSES_UNENROLL_LEARNERS,
COURSES_VIEW_COURSE_INFO,
COURSES_VIEW_COURSE_TEAM,
COURSES_VIEW_ENROLLMENTS,
COURSES_VIEW_GRADEBOOK,
COURSES_VIEW_GRADING_SETTINGS,
COURSES_VIEW_LEARNER_COURSE_STATUS,
COURSES_VIEW_LEARNER_EXTENSIONS,
)
Expand All @@ -53,12 +59,15 @@
UserFactory,
)
from lms.djangoapps.ccx.tests.utils import CcxTestCase
from lms.djangoapps.courseware.models import StudentModule
from lms.djangoapps.courseware.tabs import get_course_tab_list
from lms.djangoapps.instructor.access import update_forum_role
from lms.djangoapps.instructor.authz import constants
from lms.djangoapps.instructor.authz.api import user_has_instructor_permission
from lms.djangoapps.instructor.authz.compat import LEGACY_ROLE_COMPAT_PERMISSIONS
from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin
from lms.djangoapps.instructor.permissions import OVERRIDE_GRADES
from lms.djangoapps.instructor_task.models import InstructorTask
from openedx.core.djangoapps.course_date_signals.handlers import extract_dates
from openedx.core.djangoapps.django_comment_common.models import (
FORUM_ROLE_ADMINISTRATOR,
Expand Down Expand Up @@ -1599,3 +1608,269 @@ def test_legacy_does_not_query_authz(self):

assert response.status_code == status.HTTP_200_OK
is_user_allowed.assert_not_called()


# Grading tab requests: the AuthZ permission each one requires and the status it returns on success.
GRADING_ACTIONS = {
"view_learner": (COURSES_VIEW_LEARNER_COURSE_STATUS.identifier, status.HTTP_200_OK),
"view_problem": (COURSES_MANAGE_LEARNER_GRADING.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_BULK_LEARNER_GRADING.identifier, status.HTTP_202_ACCEPTED),
"rescore_all_learners": (COURSES_MANAGE_BULK_LEARNER_GRADING.identifier, status.HTTP_202_ACCEPTED),
}

# All Learners actions: Course Admin only with the flag on, instructor access with it off.
ALL_LEARNERS_GRADING_ACTIONS = ("reset_attempts_all_learners", "rescore_all_learners")

# The reads and the Single Learner actions: Course Staff can use them with the flag on, and legacy
# course staff with it off.
STAFF_GRADING_ACTIONS = tuple(
action for action in GRADING_ACTIONS if action not in ALL_LEARNERS_GRADING_ACTIONS
)


@ddt.ddt
class GradingTabAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase):
"""
The Grading tab endpoints follow the AuthZ flag.

With the flag on, ``LearnerView`` requires ``courses.view_learner_course_status``,
``GradingConfigView`` requires ``courses.view_grading_settings``,
``ProblemView`` and the Single Learner actions require
``courses.manage_learner_grading``, and the All Learners actions require
``courses.manage_bulk_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("""\
<problem>
<optionresponse>
<optioninput options="('Option 1','Option 2')" correct="Option 1" />
</optionresponse>
</problem>
""")

@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,), GRADING_ACTIONS),
*product((COURSE_STAFF.external_key,), STAFF_GRADING_ACTIONS),
)
@ddt.unpack
def test_authz_course_role_allowed(self, authz_role, action):
"""
With the flag on, Course Admin can use every Grading tab action, and
Course Staff the reads and the Single Learner actions.
"""
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(*ALL_LEARNERS_GRADING_ACTIONS)
def test_authz_course_staff_cannot_run_all_learners_action(self, action):
"""
With the flag on, Course Staff cannot run an All Learners action: it holds
``courses.manage_learner_grading`` but not ``courses.manage_bulk_learner_grading``.
"""
user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course_key)

response = self._request(action, user)

assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.data["error_code"] == "permission_denied"
assert not self._has_queued_task()

@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(*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()

def test_legacy_single_learner_reset_uses_the_view_permission(self):
"""
With the flag off, a Single Learner reset is decided by the view's legacy permission
(``GIVE_STUDENT_EXTENSION``), not by the default one of ``courses.manage_learner_grading``
(``OVERRIDE_GRADES``).
"""
self.set_authz_enabled(False)
staff = StaffFactory(course_key=self.course_key)
has_perm = get_user_model().has_perm

def has_perm_without_override_grades(user, perm, obj=None):
return perm != OVERRIDE_GRADES and has_perm(user, perm, obj)

with patch.object(get_user_model(), "has_perm", autospec=True, side_effect=has_perm_without_override_grades):
response = self._request("reset_attempts", staff)

assert response.status_code == status.HTTP_200_OK

@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
assert response.data["error_code"] == "permission_denied"
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()
Loading
Loading