From 352764ade16d46d38e26b791fdd1d378aa612806 Mon Sep 17 00:00:00 2001 From: Taylor Payne Date: Fri, 6 Nov 2026 15:39:13 -0700 Subject: [PATCH 1/3] feat: hide Course Info fields without courses.view_course_info CourseMetadataView now returns the Course Info fields only to users who hold courses.view_course_info. Other users who can open the Instructor Dashboard still get 200, with those fields set to null and the header and tab fields unchanged. Fields set to null: enrollment_start, enrollment_end, start, end, pacing, has_started, has_ended, total_enrollment, learner_count, staff_count, enrollment_counts, num_sections, grade_cutoffs, course_errors and studio_url. They are marked nullable in the OpenAPI schema. - The permission is resolved once per response, and the hidden fields are not computed, so their enrollment and modulestore queries are skipped. - With authz.enable_course_authoring off, the default legacy check of the permission (VIEW_DASHBOARD) applies, so legacy staff, instructors and data researchers keep every field. The same check covers the AuthZ data researcher role through the legacy-role compatibility fallback. Closes openedx/openedx-authz#487 --- .../instructor/tests/test_api_v2_authz.py | 187 ++++++++++++++++++ .../instructor/views/serializers_v2.py | 109 ++++++++-- 2 files changed, 279 insertions(+), 17 deletions(-) diff --git a/lms/djangoapps/instructor/tests/test_api_v2_authz.py b/lms/djangoapps/instructor/tests/test_api_v2_authz.py index a37c6087a768..09724eab0366 100644 --- a/lms/djangoapps/instructor/tests/test_api_v2_authz.py +++ b/lms/djangoapps/instructor/tests/test_api_v2_authz.py @@ -17,10 +17,12 @@ COURSE_LIMITED_STAFF, COURSE_STAFF, COURSES_VIEW_COURSE_INFO, + COURSES_VIEW_ENROLLMENTS, ) from rest_framework import status from rest_framework.test import APIClient +from common.djangoapps.student.models import CourseEnrollment from common.djangoapps.student.roles import CourseDataResearcherRole, CourseLimitedStaffRole from common.djangoapps.student.tests.factories import ( InstructorFactory, @@ -29,6 +31,7 @@ ) from lms.djangoapps.courseware.tabs import get_course_tab_list from lms.djangoapps.instructor.authz import constants +from lms.djangoapps.instructor.authz.api import user_has_instructor_permission from lms.djangoapps.instructor.authz.tests.mixins import InstructorAuthzTestMixin from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory @@ -313,3 +316,187 @@ def test_legacy_without_role_hidden(self): self.set_authz_enabled(False) assert not self._has_instructor_tab(UserFactory()) + + +@ddt.ddt +class CourseMetadataViewCourseInfoAuthzTest(InstructorAuthzTestMixin, SharedModuleStoreTestCase): + """ + ``CourseMetadataView`` returns the Course Info fields only with ``courses.view_course_info``. + + Without it, a user who can open the dashboard gets ``200`` with those fields set to ``null``, + and the header and tab fields unchanged. + """ + + # Fields only the Course Info tab reads. + COURSE_INFO_FIELDS = ( + "enrollment_start", + "enrollment_end", + "start", + "end", + "pacing", + "has_started", + "has_ended", + "total_enrollment", + "learner_count", + "staff_count", + "enrollment_counts", + "num_sections", + "grade_cutoffs", + "course_errors", + "studio_url", + ) + # Course Info fields that always have a value for the test course when shown. + VALUED_COURSE_INFO_FIELDS = ( + "start", + "pacing", + "has_started", + "has_ended", + "total_enrollment", + "learner_count", + "staff_count", + "enrollment_counts", + "num_sections", + "grade_cutoffs", + "course_errors", + ) + # Fields the page header and the other tabs read, always returned. + SHARED_FIELDS = ( + "course_id", + "username", + "display_name", + "org", + "course_number", + "course_run", + "tabs", + "permissions", + "authz_enabled", + "disable_buttons", + "gradebook_url", + "studio_grading_url", + "admin_console_url", + "certificates_enabled", + "analytics_dashboard_message", + "proctored_exams_enabled", + ) + + @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("instructor_api_v2:course_metadata", kwargs={"course_id": str(self.course_key)}) + + def _get(self, user): + self.client.force_authenticate(user=user) + return self.client.get(self.url) + + @staticmethod + def _allow_only(*permissions): + """Return an ``is_user_allowed`` side effect that grants only the given permissions.""" + identifiers = {permission.identifier for permission in permissions} + return lambda _user, permission, _scope: permission in identifiers + + def _assert_course_info_shown(self, response): + """Assert a ``200`` with the Course Info fields filled in.""" + assert response.status_code == status.HTTP_200_OK + for field in self.VALUED_COURSE_INFO_FIELDS: + assert response.data[field] is not None, field + + def _assert_course_info_hidden(self, response): + """Assert a ``200`` with the Course Info fields ``null`` and the shared fields returned.""" + assert response.status_code == status.HTTP_200_OK + for field in self.COURSE_INFO_FIELDS: + assert response.data[field] is None, field + for field in self.SHARED_FIELDS: + assert field in response.data, field + assert response.data["course_id"] == str(self.course_key) + assert response.data["display_name"] == self.course.display_name + assert response.data["org"] == self.course_key.org + assert response.data["course_number"] == self.course_key.course + + @ddt.data(COURSE_ADMIN, COURSE_STAFF) + def test_authz_role_sees_course_info(self, role): + """With the flag on, Course Admin and Course Staff get the Course Info fields.""" + user = self.create_user_with_authz_role(role.external_key, self.course_key) + + self._assert_course_info_shown(self._get(user)) + + def test_authz_view_course_info_alone_shows_course_info(self): + """With the flag on, ``courses.view_course_info`` alone is enough to get the Course Info fields.""" + user = UserFactory() + + with patch(f"{API}.authz_api.is_user_allowed", side_effect=self._allow_only(COURSES_VIEW_COURSE_INFO)): + self._assert_course_info_shown(self._get(user)) + + @ddt.data(*(p for p in constants.INSTRUCTOR_DASHBOARD_PERMISSIONS if p != COURSES_VIEW_COURSE_INFO.identifier)) + def test_authz_other_dashboard_permission_hides_course_info(self, permission): + """ + With the flag on, a user who opens the dashboard without ``courses.view_course_info`` + gets the Course Info fields as ``null`` and the shared fields unchanged. + """ + user = UserFactory() + + with patch(f"{API}.authz_api.is_user_allowed", side_effect=lambda _u, perm, _s: perm == permission): + self._assert_course_info_hidden(self._get(user)) + + def test_authz_denied_hides_course_info_from_legacy_staff(self): + """With the flag on, AuthZ decides: legacy staff without ``courses.view_course_info`` gets no fields.""" + staff = StaffFactory(course_key=self.course_key) + + with patch(f"{API}.authz_api.is_user_allowed", side_effect=self._allow_only(COURSES_VIEW_ENROLLMENTS)): + self._assert_course_info_hidden(self._get(staff)) + + def test_authz_data_researcher_keeps_course_info(self): + """ + With the flag on, a data researcher keeps the Course Info fields it had before AuthZ. + + Its AuthZ role holds no dashboard permission, so the legacy ``VIEW_DASHBOARD`` rule decides. + """ + user = self.create_user_with_authz_role(COURSE_DATA_RESEARCHER.external_key, self.course_key) + + self._assert_course_info_shown(self._get(user)) + + def test_hidden_fields_are_not_computed(self): + """Without ``courses.view_course_info``, the enrollment counts are not queried.""" + user = UserFactory() + + with patch(f"{API}.authz_api.is_user_allowed", side_effect=self._allow_only(COURSES_VIEW_ENROLLMENTS)): + with patch.object(CourseEnrollment.objects, "enrollment_counts") as enrollment_counts: + self._assert_course_info_hidden(self._get(user)) + + enrollment_counts.assert_not_called() + + def test_view_course_info_is_resolved_once(self): + """``courses.view_course_info`` is checked once per response, not once per field.""" + user = self.create_user_with_authz_role(COURSE_STAFF.external_key, self.course_key) + + with patch( + "lms.djangoapps.instructor.views.serializers_v2.user_has_instructor_permission", + wraps=user_has_instructor_permission, + ) as check: + self._assert_course_info_shown(self._get(user)) + + assert check.call_count == 1 + + @ddt.data(StaffFactory, InstructorFactory) + def test_legacy_role_sees_course_info(self, user_factory): + """With the flag off, legacy staff and instructors get the Course Info fields without querying AuthZ.""" + self.set_authz_enabled(False) + user = user_factory(course_key=self.course_key) + + with patch(f"{API}.authz_api.is_user_allowed") as is_user_allowed: + self._assert_course_info_shown(self._get(user)) + + is_user_allowed.assert_not_called() + + def test_legacy_data_researcher_sees_course_info(self): + """With the flag off, a data researcher keeps the Course Info fields through ``VIEW_DASHBOARD``.""" + self.set_authz_enabled(False) + user = UserFactory() + CourseDataResearcherRole(self.course_key).add_users(user) + + self._assert_course_info_shown(self._get(user)) diff --git a/lms/djangoapps/instructor/views/serializers_v2.py b/lms/djangoapps/instructor/views/serializers_v2.py index 0be57ff435f5..3711e7affeec 100644 --- a/lms/djangoapps/instructor/views/serializers_v2.py +++ b/lms/djangoapps/instructor/views/serializers_v2.py @@ -13,6 +13,7 @@ from django.utils.html import escape from django.utils.translation import gettext as _ from edx_when.api import is_enabled_for_course +from openedx_authz.authz import COURSES_VIEW_COURSE_INFO from openedx_filters.learning.filters import InstructorDashboardTabsRequested from rest_framework import serializers @@ -36,7 +37,7 @@ from lms.djangoapps.instructor.access import FORUM_ROLES, ROLES 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.views.instructor_dashboard import get_analytics_dashboard_message from openedx.core.djangoapps.django_comment_common.models import FORUM_ROLE_ADMINISTRATOR from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers @@ -54,6 +55,10 @@ class CourseInformationSerializerV2(serializers.Serializer): This serializer handles the business logic for gathering all course metadata, enrollment statistics, permissions, and dashboard configuration. + + The Course Info fields (dates, pacing, enrollment counts, sections, grade cutoffs, + course errors and the Studio URL) are ``null`` when the user lacks + ``courses.view_course_info``. The header and tab fields are always returned. """ course_id = serializers.SerializerMethodField(help_text="Course run key") username = serializers.SerializerMethodField(help_text="Username of the current authenticated user") @@ -61,23 +66,51 @@ class CourseInformationSerializerV2(serializers.Serializer): org = serializers.SerializerMethodField(help_text="Organization identifier") course_number = serializers.SerializerMethodField(help_text="Course number") course_run = serializers.SerializerMethodField(help_text="Course run identifier") - enrollment_start = serializers.SerializerMethodField(help_text="Enrollment start date (ISO 8601 with timezone)") - enrollment_end = serializers.SerializerMethodField(help_text="Enrollment end date (ISO 8601 with timezone)") - start = serializers.SerializerMethodField(help_text="Course start date (ISO 8601 with timezone)") - end = serializers.SerializerMethodField(help_text="Course end date (ISO 8601 with timezone)") - pacing = serializers.SerializerMethodField(help_text="Course pacing type (self or instructor)") - has_started = serializers.SerializerMethodField(help_text="Whether the course has started based on current time") - has_ended = serializers.SerializerMethodField(help_text="Whether the course has ended based on current time") - total_enrollment = serializers.SerializerMethodField(help_text="Total number of enrollments across all modes") + enrollment_start = serializers.SerializerMethodField( + allow_null=True, help_text="Enrollment start date (ISO 8601 with timezone)" + ) + enrollment_end = serializers.SerializerMethodField( + allow_null=True, help_text="Enrollment end date (ISO 8601 with timezone)" + ) + start = serializers.SerializerMethodField( + allow_null=True, help_text="Course start date (ISO 8601 with timezone)" + ) + end = serializers.SerializerMethodField( + allow_null=True, help_text="Course end date (ISO 8601 with timezone)" + ) + pacing = serializers.SerializerMethodField( + allow_null=True, help_text="Course pacing type (self or instructor)" + ) + has_started = serializers.SerializerMethodField( + allow_null=True, help_text="Whether the course has started based on current time" + ) + has_ended = serializers.SerializerMethodField( + allow_null=True, help_text="Whether the course has ended based on current time" + ) + total_enrollment = serializers.SerializerMethodField( + allow_null=True, help_text="Total number of enrollments across all modes" + ) learner_count = serializers.SerializerMethodField( - help_text="Number of enrolled learners (excludes staff and admins)" - ) - staff_count = serializers.SerializerMethodField(help_text="Number of enrolled staff and admins") - enrollment_counts = serializers.SerializerMethodField(help_text="Enrollment count breakdown by mode") - num_sections = serializers.SerializerMethodField(help_text="Number of sections/chapters in the course") - grade_cutoffs = serializers.SerializerMethodField(help_text="Formatted string of grade cutoffs") - course_errors = serializers.SerializerMethodField(help_text="List of course validation errors from modulestore") - studio_url = serializers.SerializerMethodField(help_text="URL to view/edit course in Studio") + allow_null=True, help_text="Number of enrolled learners (excludes staff and admins)" + ) + staff_count = serializers.SerializerMethodField( + allow_null=True, help_text="Number of enrolled staff and admins" + ) + enrollment_counts = serializers.SerializerMethodField( + allow_null=True, help_text="Enrollment count breakdown by mode" + ) + num_sections = serializers.SerializerMethodField( + allow_null=True, help_text="Number of sections/chapters in the course" + ) + grade_cutoffs = serializers.SerializerMethodField( + allow_null=True, help_text="Formatted string of grade cutoffs" + ) + course_errors = serializers.SerializerMethodField( + allow_null=True, help_text="List of course validation errors from modulestore" + ) + studio_url = serializers.SerializerMethodField( + allow_null=True, help_text="URL to view/edit course in Studio" + ) gradebook_url = serializers.SerializerMethodField( help_text="URL to the MFE gradebook for the course (null if not configured)" ) @@ -109,6 +142,18 @@ class CourseInformationSerializerV2(serializers.Serializer): help_text="Whether proctored exams, and the proctored exam results report, are enabled for this course" ) + # Whether the user holds ``courses.view_course_info``, resolved in ``to_representation``. + _can_view_course_info = False + + def to_representation(self, instance): + """ + Serialize the course, resolving ``courses.view_course_info`` once for the Course Info fields. + """ + self._can_view_course_info = user_has_instructor_permission( + instance['user'], COURSES_VIEW_COURSE_INFO.identifier, instance['course'].id + ) + return super().to_representation(instance) + @staticmethod def _build_tab_url(setting_name, *path_parts, strip_url=True): """ @@ -364,46 +409,68 @@ def get_course_run(self, data): def get_enrollment_start(self, data): """Get enrollment start date.""" + if not self._can_view_course_info: + return None return data['course'].enrollment_start def get_enrollment_end(self, data): """Get enrollment end date.""" + if not self._can_view_course_info: + return None return data['course'].enrollment_end def get_start(self, data): """Get course start date.""" + if not self._can_view_course_info: + return None return data['course'].start def get_end(self, data): """Get course end date.""" + if not self._can_view_course_info: + return None return data['course'].end def get_pacing(self, data): """Get course pacing type (self or instructor).""" + if not self._can_view_course_info: + return None return 'self' if data['course'].self_paced else 'instructor' def get_has_started(self, data): """Check if course has started.""" + if not self._can_view_course_info: + return None return data['course'].has_started() def get_has_ended(self, data): """Check if course has ended.""" + if not self._can_view_course_info: + return None return data['course'].has_ended() def get_total_enrollment(self, data): """Get total enrollment count.""" + if not self._can_view_course_info: + return None return self.get_enrollment_counts(data)['total'] def get_learner_count(self, data): """Get enrollment count excluding staff and admins.""" + if not self._can_view_course_info: + return None return CourseEnrollment.objects.num_enrolled_in_exclude_admins(data['course'].id) def get_staff_count(self, data): """Get enrollment count for staff and admins only.""" + if not self._can_view_course_info: + return None return self.get_total_enrollment(data) - self.get_learner_count(data) def get_enrollment_counts(self, data): """Get enrollment counts for all configured modes and any mode with active enrollments.""" + if not self._can_view_course_info: + return None course_id = data['course'].id counts = CourseEnrollment.objects.enrollment_counts(course_id) configured_modes = CourseMode.modes_for_course(course_id) @@ -417,6 +484,8 @@ def get_enrollment_counts(self, data): def get_num_sections(self, data): """Get number of sections in the course.""" + if not self._can_view_course_info: + return None course = data['course'] return len(course.get_children()) if hasattr(course, 'get_children') else 0 @@ -456,6 +525,8 @@ def get_grade_cutoffs(self, data): Returns: str: Formatted grade cutoffs (e.g., "A is 0.9, B is 0.8, C is 0.7") """ + if not self._can_view_course_info: + return None course = data['course'] if not hasattr(course, 'grading_policy') or not course.grading_policy: return "" @@ -477,6 +548,8 @@ def get_grade_cutoffs(self, data): def get_course_errors(self, data): """Get course validation errors from modulestore.""" + if not self._can_view_course_info: + return None course = data['course'] try: errors = modulestore().get_course_errors(course.id) @@ -487,6 +560,8 @@ def get_course_errors(self, data): def get_studio_url(self, data): """Get Studio URL for the course.""" + if not self._can_view_course_info: + return None return get_studio_url(data['course'], 'course') def get_gradebook_url(self, data): From e9b6e9605c355aabdb83c5f5dbeaa2c053bd21fd Mon Sep 17 00:00:00 2001 From: Taylor Payne Date: Tue, 24 Nov 2026 09:10:27 -0700 Subject: [PATCH 2/3] test: cover the Course Info tab and legacy-only roles with AuthZ enabled --- .../instructor/tests/test_api_v2_authz.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lms/djangoapps/instructor/tests/test_api_v2_authz.py b/lms/djangoapps/instructor/tests/test_api_v2_authz.py index 09724eab0366..a48af5a2ddf8 100644 --- a/lms/djangoapps/instructor/tests/test_api_v2_authz.py +++ b/lms/djangoapps/instructor/tests/test_api_v2_authz.py @@ -407,10 +407,11 @@ def _assert_course_info_shown(self, response): assert response.data[field] is not None, field def _assert_course_info_hidden(self, response): - """Assert a ``200`` with the Course Info fields ``null`` and the shared fields returned.""" + """Assert a ``200`` with the Course Info fields ``null``, no Course Info tab, and the shared fields returned.""" assert response.status_code == status.HTTP_200_OK for field in self.COURSE_INFO_FIELDS: assert response.data[field] is None, field + assert "course_info" not in {tab["tab_id"] for tab in response.data["tabs"]} for field in self.SHARED_FIELDS: assert field in response.data, field assert response.data["course_id"] == str(self.course_key) @@ -482,6 +483,20 @@ def test_view_course_info_is_resolved_once(self): assert check.call_count == 1 + @ddt.data(StaffFactory, InstructorFactory) + def test_authz_legacy_role_without_authz_role_is_denied(self, user_factory): + """With the flag on, legacy staff and instructors without an AuthZ role get the standard ``403``.""" + # With the flag on, adding a legacy role assigns its AuthZ equivalent instead, + # so the legacy-only user is created with the flag off. + self.set_authz_enabled(False) + user = user_factory(course_key=self.course_key) + self.set_authz_enabled(True) + + response = self._get(user) + + assert response.status_code == status.HTTP_403_FORBIDDEN + assert response.data["error_code"] == "permission_denied" + @ddt.data(StaffFactory, InstructorFactory) def test_legacy_role_sees_course_info(self, user_factory): """With the flag off, legacy staff and instructors get the Course Info fields without querying AuthZ.""" From 0d0b6e7cfe266b9259f339306dc04282becbef2a Mon Sep 17 00:00:00 2001 From: Taylor Payne Date: Tue, 24 Nov 2026 13:50:56 -0700 Subject: [PATCH 3/3] chore: retrigger docs build