From 8a076e883a38ed71dcc7a9c21ba6ef34c47e49e7 Mon Sep 17 00:00:00 2001 From: Bryann Valderrama Date: Thu, 19 Nov 2026 17:05:57 -0500 Subject: [PATCH] fix: create duplicated xblocks in the destination course POST /xblock/ with a duplicate_source_locator and a parent_locator from two different courses created the new block in the source course (the key is built from the source location) and attached it as a child of a parent in another course. With authz enabled the source course was never checked, so a user without access to it could write there, and the destination course was left with a dangling child that could not be loaded or deleted. - Build the key of the duplicated block in the parent's course (or library) instead of the source's. This also fixes duplicating a v1 library block into a course, which returned 200 but created the copy in the library and left the course with a dangling child. - Require view access on the source course in the xblock handler in both modes: courses.view_course when authz is enabled for the source course, has_studio_read_access otherwise (including v1 libraries). Write access on the destination is still required as before. Part of openedx/openedx-authz#602. Co-Authored-By: Claude Sonnet 5.5 --- .../contentstore/tests/test_libraries.py | 25 ++++ .../tests/test_xblock_handler_permissions.py | 125 +++++++++++++++++- cms/djangoapps/contentstore/utils.py | 12 +- .../xblock_storage_handlers/view_handlers.py | 39 +++++- 4 files changed, 188 insertions(+), 13 deletions(-) diff --git a/cms/djangoapps/contentstore/tests/test_libraries.py b/cms/djangoapps/contentstore/tests/test_libraries.py index 8b80f83f2933..0c5c1996c8f9 100644 --- a/cms/djangoapps/contentstore/tests/test_libraries.py +++ b/cms/djangoapps/contentstore/tests/test_libraries.py @@ -7,6 +7,7 @@ import ddt from django.test.utils import override_settings +from opaque_keys.edx.keys import UsageKey from opaque_keys.edx.locator import CourseKey, LibraryLocator from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient, parse_json @@ -747,6 +748,30 @@ def test_duplicate_across_courses(self, library_role, course_role, expected_resu duplicate_action_allowed = (response.status_code == 200) self.assertEqual(duplicate_action_allowed, expected_result) # noqa: PT009 + def test_duplicate_library_block_into_course_creates_block_in_course(self): + """ + Duplicating a library block into a course creates the copy in that course, + leaves the library untouched, and the new child resolves under its parent. + """ + block = self._add_simple_content_block() + with modulestore().default_store(ModuleStoreEnum.Type.split): + course = CourseFactory.create() + store = modulestore() + library_items_before = len(store.get_items(self.library.location.library_key)) + + response = self.client.ajax_post(reverse_url("xblock_handler"), { + "parent_locator": str(course.location), + "duplicate_source_locator": str(block.location), + }) + + assert response.status_code == 200 + new_key = UsageKey.from_string(parse_json(response)["locator"]) + assert new_key.course_key == course.id + assert len(store.get_items(self.library.location.library_key)) == library_items_before + parent = store.get_item(course.location) + assert new_key in parent.children + assert store.get_item(new_key).location == new_key + @ddt.data( (LibraryUserRole, CourseStaffRole, True), (CourseStaffRole, CourseStaffRole, True), diff --git a/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py b/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py index cc7b53ca0991..b4aabde6db0b 100644 --- a/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py +++ b/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py @@ -1,11 +1,15 @@ """ Tests verifying that xblock_handler enforces the correct permissions. """ +import json from unittest.mock import patch +from opaque_keys.edx.keys import UsageKey + from cms.djangoapps.contentstore.tests.utils import CourseTestCase +from common.djangoapps.student.roles import CourseStaffRole from openedx.core import toggles as core_toggles -from xmodule.modulestore.tests.factories import BlockFactory +from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory class XBlockHandlerPermissionsTest(CourseTestCase): @@ -22,7 +26,7 @@ def setUp(self): self.vertical = BlockFactory.create(category='vertical', parent_location=self.sequential.location) self.html_block = BlockFactory.create(category='html', parent_location=self.vertical.location) self.static_tab = BlockFactory.create(category='static_tab', parent_location=self.course.location) - self.non_staff_client, _ = self.create_non_staff_authed_user_client() + self.non_staff_client, self.non_staff_user = self.create_non_staff_authed_user_client() # --- GET /xblock/{blockId} --- @@ -82,6 +86,59 @@ def test_post_duplicate_non_staff_forbidden(self): } self.assertEqual(self.non_staff_client.ajax_post('/xblock/', data=data).status_code, 403) # noqa: PT009 + def _create_other_course_with_vertical(self, number): + """Create a second course with a vertical, and return (course, vertical).""" + other_course = CourseFactory.create(org="OtherOrg", number=number, run="2026_T1") + chapter = BlockFactory.create(category="chapter", parent_location=other_course.location) + sequential = BlockFactory.create(category="sequential", parent_location=chapter.location) + vertical = BlockFactory.create(category="vertical", parent_location=sequential.location) + return other_course, vertical + + def test_post_duplicate_cross_course_staff_creates_block_in_destination(self): + """Users with access to both courses can duplicate across them; the copy lives in the destination.""" + other_course, other_vertical = self._create_other_course_with_vertical("OC1") + source_items = len(self.store.get_items(self.course.id)) + + resp = self.client.ajax_post("/xblock/", data={ + "duplicate_source_locator": str(self.html_block.location), + "parent_locator": str(other_vertical.location), + }) + + assert resp.status_code == 200 + new_key = UsageKey.from_string(json.loads(resp.content)["locator"]) + assert new_key.course_key == other_course.id + assert new_key in self.store.get_item(other_vertical.location).children + assert self.store.get_item(new_key).location == new_key + assert len(self.store.get_items(self.course.id)) == source_items + + def test_post_duplicate_cross_course_without_source_view_access_forbidden(self): + """Write access on the destination is not enough: the user must also be able to view the source.""" + other_course, other_vertical = self._create_other_course_with_vertical("OC2") + CourseStaffRole(other_course.id).add_users(self.non_staff_user) + children_before = list(self.store.get_item(other_vertical.location).children) + + resp = self.non_staff_client.ajax_post("/xblock/", data={ + "duplicate_source_locator": str(self.html_block.location), + "parent_locator": str(other_vertical.location), + }) + + assert resp.status_code == 403 + assert self.store.get_item(other_vertical.location).children == children_before + + def test_post_duplicate_cross_course_without_destination_write_access_forbidden(self): + """View access on the source is not enough: the user must also be able to edit the destination.""" + _other_course, other_vertical = self._create_other_course_with_vertical("OC3") + CourseStaffRole(self.course.id).add_users(self.non_staff_user) + children_before = list(self.store.get_item(other_vertical.location).children) + + resp = self.non_staff_client.ajax_post("/xblock/", data={ + "duplicate_source_locator": str(self.html_block.location), + "parent_locator": str(other_vertical.location), + }) + + assert resp.status_code == 403 + assert self.store.get_item(other_vertical.location).children == children_before + def test_post_add_component_staff_allowed(self): data = {'category': 'html', 'parent_locator': str(self.vertical.location)} self.assertEqual(self.client.ajax_post('/xblock/', data=data).status_code, 200) # noqa: PT009 @@ -367,12 +424,74 @@ def test_duplicate_block_checks_edit_course_content(self, _mock_flag, mock_is_al 'parent_locator': str(self.vertical.location), } ) - mock_is_allowed.assert_called_with( + mock_is_allowed.assert_any_call( self.user.username, 'courses.edit_course_content', str(self.course.id) ) + def _duplicate_cross_course(self, other_vertical): + """Send a request to duplicate ``self.html_block`` under ``other_vertical``, in another course.""" + return self.client.ajax_post( + "/xblock/", + data={ + "duplicate_source_locator": str(self.html_block.location), + "parent_locator": str(other_vertical.location), + } + ) + + def _create_other_course_with_vertical(self): + """Create a second course with a vertical, and return (course, vertical).""" + other_course = CourseFactory.create(org="OtherOrg", number="OC4", run="2026_T1") + chapter = BlockFactory.create(category="chapter", parent_location=other_course.location) + sequential = BlockFactory.create(category="sequential", parent_location=chapter.location) + vertical = BlockFactory.create(category="vertical", parent_location=sequential.location) + return other_course, vertical + + def test_duplicate_cross_course_checks_view_on_source_and_edit_on_destination( + self, _mock_flag, mock_is_allowed # noqa: PT019 + ): + """Cross-course duplicate checks courses.view_course on the source and edit_course_content on the target.""" + other_course, other_vertical = self._create_other_course_with_vertical() + + resp = self._duplicate_cross_course(other_vertical) + + assert resp.status_code == 200 + mock_is_allowed.assert_any_call(self.user.username, "courses.edit_course_content", str(other_course.id)) + mock_is_allowed.assert_any_call(self.user.username, "courses.view_course", str(self.course.id)) + new_key = UsageKey.from_string(json.loads(resp.content)["locator"]) + assert new_key.course_key == other_course.id + + def test_duplicate_cross_course_denied_without_source_view(self, _mock_flag, mock_is_allowed): # noqa: PT019 + """No courses.view_course on the source course: forbidden, and nothing is written anywhere.""" + other_course, other_vertical = self._create_other_course_with_vertical() + mock_is_allowed.side_effect = lambda _user, permission, scope: not ( + permission == "courses.view_course" and scope == str(self.course.id) + ) + source_items = len(self.store.get_items(self.course.id)) + dest_items = len(self.store.get_items(other_course.id)) + children_before = list(self.store.get_item(other_vertical.location).children) + + resp = self._duplicate_cross_course(other_vertical) + + assert resp.status_code == 403 + assert len(self.store.get_items(self.course.id)) == source_items + assert len(self.store.get_items(other_course.id)) == dest_items + assert self.store.get_item(other_vertical.location).children == children_before + + def test_duplicate_cross_course_denied_without_destination_edit(self, _mock_flag, mock_is_allowed): # noqa: PT019 + """No courses.edit_course_content on the destination course: forbidden.""" + other_course, other_vertical = self._create_other_course_with_vertical() + mock_is_allowed.side_effect = lambda _user, permission, scope: not ( + permission == "courses.edit_course_content" and scope == str(other_course.id) + ) + source_items = len(self.store.get_items(self.course.id)) + + resp = self._duplicate_cross_course(other_vertical) + + assert resp.status_code == 403 + assert len(self.store.get_items(self.course.id)) == source_items + # --- PUT /xblock/{blockId} (reorder) --- def test_put_reorder_checks_edit_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019 diff --git a/cms/djangoapps/contentstore/utils.py b/cms/djangoapps/contentstore/utils.py index c7647e0959b2..646a402b8b19 100644 --- a/cms/djangoapps/contentstore/utils.py +++ b/cms/djangoapps/contentstore/utils.py @@ -1121,11 +1121,17 @@ def duplicate_block( blocks. """ store = modulestore() - with store.bulk_operations(duplicate_source_usage_key.course_key): + + source_course_key = duplicate_source_usage_key.course_key + dest_course_key = dest_usage_key.course_key if dest_usage_key else parent_usage_key.course_key + + with store.bulk_operations(source_course_key), store.bulk_operations(dest_course_key): source_item = store.get_item(duplicate_source_usage_key) if not dest_usage_key: - # Change the blockID to be unique. - dest_usage_key = source_item.location.replace(name=uuid4().hex) + # Create the copy in the same course (or library) as its parent, with a unique block ID. Building the key + # from the source location would create the block in the source course and then attach it to a parent + # living somewhere else, leaving a child that does not exist in the parent's structure. + dest_usage_key = dest_course_key.make_usage_key(source_item.location.block_type, uuid4().hex) category = dest_usage_key.block_type diff --git a/cms/djangoapps/contentstore/xblock_storage_handlers/view_handlers.py b/cms/djangoapps/contentstore/xblock_storage_handlers/view_handlers.py index 59c219729641..a58e5e3db08d 100644 --- a/cms/djangoapps/contentstore/xblock_storage_handlers/view_handlers.py +++ b/cms/djangoapps/contentstore/xblock_storage_handlers/view_handlers.py @@ -27,6 +27,7 @@ ) from edx_proctoring.exceptions import ProctoredExamNotFoundException from help_tokens.core import HelpUrlExpert +from opaque_keys.edx.keys import UsageKey from opaque_keys.edx.locator import LibraryUsageLocator, LibraryUsageLocatorV2 from openedx_authz import api as authz_api from openedx_authz.authz import ( @@ -50,6 +51,7 @@ from cms.lib.xblock.upstream_sync_container import sync_from_upstream_container from common.djangoapps.static_replace import replace_static_urls from common.djangoapps.student.auth import has_studio_read_access, has_studio_write_access +from common.djangoapps.student.roles import enable_authz_course_authoring from common.djangoapps.util.date_utils import get_default_time_display from common.djangoapps.util.json_request import JsonResponse, expect_json from common.djangoapps.util.proctoring import show_review_rules @@ -257,6 +259,33 @@ def _check_xblock_permission(request, usage_key, category=None): return permission +def _check_duplicate_source_view_access(user: User, source_usage_key: UsageKey) -> None: + """ + Check that the user can view the course (or v1 library) a block is duplicated from. + + Uses the authz ``courses.view_course`` permission when authz is enabled for the source course, and the + legacy ``has_studio_read_access`` check otherwise (including v1 libraries, which authz does not cover). + + Args: + user (User): The user requesting the duplication. + source_usage_key (UsageKey): The usage key of the block being duplicated. + + Raises: + PermissionDenied: If the user cannot view the source course or library. + """ + source_course_key = source_usage_key.course_key + use_authz = ( + not isinstance(source_usage_key, LibraryUsageLocator) + and enable_authz_course_authoring(source_course_key) + ) + if use_authz: + allowed = authz_api.is_user_allowed(user.username, COURSES_VIEW_COURSE.identifier, str(source_course_key)) + else: + allowed = has_studio_read_access(user, source_course_key) + if not allowed: + raise PermissionDenied() + + def handle_xblock(request, usage_key_string=None): """ Service method with all business logic for handling xblock requests. @@ -355,14 +384,10 @@ def _duplicate_xblock(request): duplicate_source_usage_key = usage_key_with_run( request.json["duplicate_source_locator"] ) - source_course = duplicate_source_usage_key.course_key - # Check authz permission for destination - permission = _check_xblock_permission(request, parent_usage_key) - # Legacy path also requires read access on the source course - if permission is None: - if not has_studio_read_access(request.user, source_course): - raise PermissionDenied() + # Write access on the destination, and view access on the source. + _check_xblock_permission(request, parent_usage_key) + _check_duplicate_source_view_access(request.user, duplicate_source_usage_key) # Libraries have a maximum component limit enforced on them if isinstance(