Skip to content
Open
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: 1 addition & 1 deletion lms/djangoapps/instructor/authz/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
==============================================
Expand Down
30 changes: 25 additions & 5 deletions lms/djangoapps/instructor/authz/legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down
14 changes: 10 additions & 4 deletions lms/djangoapps/instructor/authz/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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)
Expand Down
36 changes: 36 additions & 0 deletions lms/djangoapps/instructor/authz/tests/test_legacy.py
Original file line number Diff line number Diff line change
@@ -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)
10 changes: 10 additions & 0 deletions lms/djangoapps/instructor/authz/tests/test_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,))
Expand Down
10 changes: 8 additions & 2 deletions lms/djangoapps/instructor/views/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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):
"""
Expand Down
38 changes: 0 additions & 38 deletions openedx/core/djangoapps/course_groups/permissions.py

This file was deleted.

75 changes: 68 additions & 7 deletions openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
8 changes: 6 additions & 2 deletions openedx/core/djangoapps/course_groups/rest_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading