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
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,19 @@
import json
from unittest.mock import patch

import casbin
import ddt
import pkg_resources
from django.test import override_settings
from django.urls import reverse
from milestones.tests.utils import MilestonesTestCaseMixin
from openedx_authz.api.users import assign_role_to_user_in_scope
from openedx_authz.constants.roles import COURSE_AUDITOR, COURSE_EDITOR, COURSE_STAFF
from openedx_authz.engine.enforcer import AuthzEnforcer
from openedx_authz.engine.utils import migrate_policy_between_enforcers
from rest_framework.test import APIClient

from cms.djangoapps.contentstore.tests.utils import CourseTestCase
from common.djangoapps.student.tests.factories import UserFactory
from openedx.core import toggles as core_toggles
from openedx.core.djangoapps.authz.tests.fixtures import seed_policies


@ddt.ddt
Expand Down Expand Up @@ -114,7 +112,7 @@ class AdvancedSettingsAuthzTest(CourseTestCase):

def setUp(self):
super().setUp()
self._seed_database_with_policies()
seed_policies()
self.url = reverse(
"cms.djangoapps.contentstore:v0:course_advanced_settings",
kwargs={"course_id": self.course.id},
Expand Down Expand Up @@ -142,18 +140,6 @@ def tearDown(self):
super().tearDown()
AuthzEnforcer.get_enforcer().clear_policy()

@classmethod
def _seed_database_with_policies(cls):
"""Seed the database with policies from the policy file."""
global_enforcer = AuthzEnforcer.get_enforcer()
global_enforcer.load_policy()
model_path = pkg_resources.resource_filename("openedx_authz.engine", "config/model.conf")
policy_path = pkg_resources.resource_filename("openedx_authz.engine", "config/authz.policy")
migrate_policy_between_enforcers(
source_enforcer=casbin.Enforcer(model_path, policy_path),
target_enforcer=global_enforcer,
)

def test_authorized_for_specific_course(self, mock_flag):
"""User authorized for specific course can access."""
response = self.authorized_client.get(self.url)
Expand Down
26 changes: 3 additions & 23 deletions common/djangoapps/student/tests/test_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
)
from common.djangoapps.student.tests.factories import AnonymousUserFactory, InstructorFactory, StaffFactory, UserFactory
from lms.djangoapps.instructor import permissions as instructor_permissions
from openedx.core.djangoapps.authz.tests.fixtures import seed_policies
from openedx.core.djangoapps.content.course_overviews.tests.factories import CourseOverviewFactory
from openedx.core.toggles import AUTHZ_COURSE_AUTHORING_FLAG

Expand All @@ -67,7 +68,8 @@ class RolesTestCase(TestCase):

def setUp(self):
super().setUp()
self._seed_database_with_policies()
seed_policies()
AuthzEnforcer.get_enforcer().clear_policy() # Clear to simulate fresh start for each test
self.course_key = CourseKey.from_string('course-v1:course-v1:edX+toy+2012_Fall')
self.course_loc = self.course_key.make_usage_key('course', '2012_Fall')
self.course = CourseOverviewFactory.create(id=self.course_key)
Expand All @@ -78,28 +80,6 @@ def setUp(self):
self.course_instructor = InstructorFactory(course_key=self.course_key)
self.orgs = ["Marvel", "DC"]

@classmethod
def _seed_database_with_policies(cls):
"""Seed the database with policies from the policy file for openedx_authz tests.

This simulates the one-time database seeding that would happen
during application deployment, separate from the runtime policy loading.
"""
import casbin
import pkg_resources
from openedx_authz.engine.utils import migrate_policy_between_enforcers

global_enforcer = AuthzEnforcer.get_enforcer()
global_enforcer.load_policy()
model_path = pkg_resources.resource_filename("openedx_authz.engine", "config/model.conf")
policy_path = pkg_resources.resource_filename("openedx_authz.engine", "config/authz.policy")

migrate_policy_between_enforcers(
source_enforcer=casbin.Enforcer(model_path, policy_path),
target_enforcer=global_enforcer,
)
global_enforcer.clear_policy() # Clear to simulate fresh start for each test

@ddt.data(True, False)
def test_global_staff(self, authz_enabled):
with override_waffle_flag(AUTHZ_COURSE_AUTHORING_FLAG, active=authz_enabled):
Expand Down
126 changes: 126 additions & 0 deletions lms/djangoapps/instructor/authz/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
Instructor Dashboard AuthZ
##########################

Integration of the Instructor Dashboard (``/api/instructor/v2``) with ``openedx-authz``.

What it contains
****************

- ``constants.py``: groups of permission identifiers (all the dashboard permissions, and the ones of each tab). The permissions themselves come from the ``constants`` module of each ``openedx_authz.applets`` package; use their ``.identifier`` and do not repeat the strings in the code.
- ``api.py``: ``user_has_instructor_permission`` and ``user_has_any_instructor_permission``.
- ``permissions.py``: ``InstructorAuthzPermission``, the DRF permission class for the views.
- ``legacy.py``: the pre-AuthZ check equivalent to each permission.
- ``compat.py``: the legacy roles that keep their legacy access with AuthZ enabled.
- ``tests/mixins.py``: ``InstructorAuthzTestMixin`` to assign AuthZ roles in tests.

Behavior
********

It is driven by the ``authz.enable_course_authoring`` waffle flag, evaluated per course, with the same semantics as Studio:

- **Flag enabled:** only AuthZ is consulted. Legacy roles are ignored (openedx-authz already grants the global staff and superuser bypass).
- **Flag disabled:** only the legacy check runs, so the previous behavior is unchanged.

The exception are the legacy roles that openedx-authz maps without dashboard permissions (``course_limited_staff``, ``course_data_researcher`` and ``course_beta_tester``). They only hold a compatibility permission (``courses.legacy_*_permissions``), so with the flag enabled, when AuthZ denies, they are evaluated with the legacy check, the same one used with the flag disabled. They keep exactly the access their legacy role had. To cover another legacy role, add its compatibility permission to ``LEGACY_ROLE_COMPAT_PERMISSIONS`` in ``compat.py``. ``course_admin`` and ``course_staff`` are not in it: they hold dashboard permissions, so a denial is final.

Every decision is logged with the path that resolved it (``authz`` or ``legacy``) in ``access_path``.

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:

Case 1: Same permissions for every HTTP method
==============================================

``authz_permissions`` is always a collection, like ``permission_classes``, even for a single permission. Unlike ``permission_classes``, where all the classes must pass (AND), holding **any one** of the permissions is enough (OR). Declare it with the legacy bridgekeeper permission the view already used:

.. code-block:: python

from openedx_authz.applets.enrollments.constants import COURSES_VIEW_ENROLLMENTS
from lms.djangoapps.instructor.authz import constants as authz_constants
from lms.djangoapps.instructor.authz.permissions import InstructorAuthzPermission

class MyView(APIView):
permission_classes = (IsAuthenticated, InstructorAuthzPermission)
authz_permissions = (COURSES_VIEW_ENROLLMENTS.identifier,)
# The legacy bridgekeeper permission.
permission_name = permissions.VIEW_ENROLLMENTS

A bare string raises ``ImproperlyConfigured``. With several permissions and ``authz.enable_course_authoring`` disabled for the course, the legacy check of the view decides, evaluated once:

.. code-block:: python

class MyView(APIView):
permission_classes = (IsAuthenticated, InstructorAuthzPermission)
authz_permissions = authz_constants.INSTRUCTOR_DASHBOARD_PERMISSIONS
permission_name = permissions.VIEW_DASHBOARD

Case 2: Different permissions per HTTP method
=============================================

Use a mapping when reading and changing need different permissions. Each value is a collection of permissions. A method missing from the mapping is denied (``403``) with ``authz.enable_course_authoring`` enabled for the course, so a method is never left on the legacy rule by mistake. With it disabled, the legacy check decides as usual:

.. code-block:: python

class MyView(APIView):
permission_classes = (IsAuthenticated, InstructorAuthzPermission)
authz_permissions = {
"GET": (COURSES_VIEW_ENROLLMENTS.identifier,),
"POST": (COURSES_ENROLL_LEARNERS.identifier,),
}
permission_name = permissions.CAN_ENROLL

Case 3: Legacy rule that is not a bridgekeeper permission
=========================================================

Define ``legacy_permission_check(user, course_key)`` on the view. It replaces ``permission_name`` and receives the same arguments for every method. Reuse the checks of ``legacy.py`` when one matches:

.. code-block:: python

from lms.djangoapps.instructor.authz import legacy as authz_legacy

class MyView(APIView):
permission_classes = (IsAuthenticated, InstructorAuthzPermission)
authz_permissions = {
"GET": (COURSES_VIEW_COHORTS.identifier,),
"POST": (COURSES_MANAGE_COHORTS.identifier,),
}

@staticmethod
def legacy_permission_check(user, course_key):
return authz_legacy.has_cohort_manage_access(user, course_key)

Without ``@staticmethod`` the method would receive ``self`` as the first argument. The legacy check does not receive the request, so it cannot vary by HTTP method. If the legacy rule differs per method, call ``user_has_instructor_permission`` in the handler with the legacy check of each case.

Checking a permission in other code
===================================

Use ``user_has_instructor_permission`` inside a handler, a serializer or any other code. The legacy check is optional and defaults to the one registered in ``legacy.LEGACY_PERMISSION_CHECKS``:

.. code-block:: python

from opaque_keys.edx.keys import CourseKey
from lms.djangoapps.instructor.authz.api import user_has_instructor_permission

def post(self, request, course_id):
course_key = CourseKey.from_string(course_id)
if user_has_instructor_permission(request.user, COURSES_MANAGE_COHORTS.identifier, course_key):
...

# With an explicit legacy check, used only when ``authz.enable_course_authoring`` is disabled.
user_has_instructor_permission(
request.user,
COURSES_VIEW_ENROLLMENTS.identifier,
course_key,
authz_legacy.has_instructor_access,
)

``CourseMetadataView`` returns ``authz_enabled``, whether AuthZ is enabled for the course. The MFE passes it as ``featureEnabled`` to the shared ``usePermissions`` hook of ``frontend-base``, so it checks the permissions through AuthZ only when it is enabled.

Errors
======

- No ``authz_permissions`` on the view, or a bare string instead of a collection: ``ImproperlyConfigured``.
- Invalid ``course_id``: ``404``.
- Denied by the active path (AuthZ with ``authz.enable_course_authoring`` enabled, legacy otherwise): ``403``.
3 changes: 3 additions & 0 deletions lms/djangoapps/instructor/authz/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
AuthZ integration for the Instructor Dashboard.
"""
146 changes: 146 additions & 0 deletions lms/djangoapps/instructor/authz/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""
Public API to enforce AuthZ permissions in the Instructor Dashboard.

When the ``authz.enable_course_authoring`` flag is enabled for a course, the
permission is resolved exclusively through AuthZ (same semantics as Studio, see
``openedx.core.djangoapps.authz.decorators``). When it is disabled, the legacy
check is used, so the pre-AuthZ behavior is preserved.

The legacy roles that AuthZ maps without dashboard permissions are the exception,
see ``compat.py``: with AuthZ enabled they are evaluated with the legacy check.
"""

import logging
from collections.abc import Callable, Iterable

from django.contrib.auth.models import AbstractUser
from opaque_keys.edx.keys import CourseKey
from openedx_authz import api as authz_api

from common.djangoapps.student.roles import enable_authz_course_authoring
from lms.djangoapps.instructor.authz.compat import holds_legacy_role_compat_permission
from lms.djangoapps.instructor.authz.legacy import LEGACY_PERMISSION_CHECKS

log = logging.getLogger(__name__)

# Signature of a legacy check: ``(user, course_key) -> bool``.
LegacyCheck = Callable[[AbstractUser, CourseKey], bool]

ACCESS_PATH_AUTHZ = "authz"
ACCESS_PATH_LEGACY = "legacy"


def user_has_instructor_permission(
Comment thread
BryanttV marked this conversation as resolved.
Resolved
user: AbstractUser,
authz_permission: str,
course_key: CourseKey,
legacy_check: LegacyCheck | None = None,
) -> bool:
"""
Return whether the user holds an AuthZ permission in the course.

When ``authz.enable_course_authoring`` is enabled for the course, only AuthZ
is consulted and legacy roles are ignored, except those of ``compat.py``, which
fall back to the legacy check when AuthZ denies. When it is disabled, only the
legacy check is evaluated. The path that resolved the check (``authz`` or
``legacy``) is logged.

Args:
user (AbstractUser): The user whose access is checked.
authz_permission (str): The AuthZ permission identifier, e.g.
``courses.view_enrollments``.
course_key (CourseKey): The course where the permission is checked.
legacy_check (LegacyCheck | None): The pre-AuthZ check, used only when
AuthZ is disabled for the course. If omitted, the default one
registered for ``authz_permission`` in ``LEGACY_PERMISSION_CHECKS``
is used, and a permission without any legacy check is denied.

Returns:
bool: True if the user holds the permission.
"""
if enable_authz_course_authoring(course_key):
is_allowed = authz_api.is_user_allowed(user.username, authz_permission, str(course_key))
if is_allowed or not holds_legacy_role_compat_permission(user, course_key):
_log_decision(ACCESS_PATH_AUTHZ, is_allowed, user, (authz_permission,), course_key)
return is_allowed

legacy_check = legacy_check or LEGACY_PERMISSION_CHECKS.get(authz_permission)
is_allowed = bool(legacy_check and legacy_check(user, course_key))
_log_decision(ACCESS_PATH_LEGACY, is_allowed, user, (authz_permission,), course_key)
return is_allowed


def user_has_any_instructor_permission(
user: AbstractUser,
authz_permissions: Iterable[str],
course_key: CourseKey,
legacy_check: LegacyCheck | None = None,
) -> bool:
"""
Return whether the user holds at least one of the AuthZ permissions.

An empty collection grants no access.

It is meant for the visibility of a tab, which is shown when the user can do
anything in it, not only a specific action. With ``authz.enable_course_authoring``
enabled for the course, only AuthZ is consulted, except for the legacy roles of
``compat.py``. With it disabled, ``legacy_check`` is used if given; otherwise the
default legacy check of each permission is tried.

Args:
user (AbstractUser): The user whose access is checked.
authz_permissions (Iterable[str]): The AuthZ permission identifiers, any
of which grants access.
course_key (CourseKey): The course where the permissions are checked.
legacy_check (LegacyCheck | None): The pre-AuthZ check of the whole set,
used when AuthZ is disabled for the course, and for the legacy roles of ``compat.py``.

Returns:
bool: True if the user holds at least one of the permissions.
"""
permissions = tuple(authz_permissions)
if not permissions:
return False

if enable_authz_course_authoring(course_key):
course_id = str(course_key)
if any(authz_api.is_user_allowed(user.username, p, course_id) for p in permissions):
_log_decision(ACCESS_PATH_AUTHZ, True, user, permissions, course_key)
return True
if not holds_legacy_role_compat_permission(user, course_key):
_log_decision(ACCESS_PATH_AUTHZ, False, user, permissions, course_key)
return False

if legacy_check is not None:
# The legacy check covers the whole set: run and log it once.
is_allowed = bool(legacy_check(user, course_key))
_log_decision(ACCESS_PATH_LEGACY, is_allowed, user, permissions, course_key)
return is_allowed

return any(user_has_instructor_permission(user, p, course_key) for p in permissions)


def _log_decision(
path: str, is_allowed: bool, user: AbstractUser, authz_permissions: Iterable[str], course_key: CourseKey
):
"""
Log the path that resolved a permission check, and its outcome.

Args:
path (str): The path that resolved the check.
is_allowed (bool): Whether access was granted.
user (AbstractUser): The user checked.
authz_permissions (Iterable[str]): The AuthZ permission identifiers checked.
course_key (CourseKey): The course where it was checked.
"""
log.debug(
"Instructor dashboard permission %s via %s",
"granted" if is_allowed else "denied",
path,
extra={
"user_id": user.id,
"authz_permissions": list(authz_permissions),
"course_key": str(course_key),
"access_path": path,
},
)
Loading
Loading