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
25 changes: 25 additions & 0 deletions cms/djangoapps/contentstore/tests/test_libraries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down
125 changes: 122 additions & 3 deletions cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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} ---

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions cms/djangoapps/contentstore/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down
Loading