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
37 changes: 27 additions & 10 deletions cms/djangoapps/contentstore/views/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@
from django.views.decorators.http import require_GET
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import UsageKey
from openedx_authz.authz import COURSES_VIEW_COURSE
from openedx_authz.authz import COURSES_EDIT_COURSE_CONTENT, COURSES_VIEW_COURSE
from xblock.core import XBlock
from xblock.django.request import django_to_webob_request, webob_to_django_response
from xblock.exceptions import NoSuchHandlerError
from xblock.fields import Scope
from xblock.plugin import PluginMissingError
from xblock.runtime import Mixologist

from cms.djangoapps.contentstore.helpers import get_parent_if_split_test, xblock_has_own_studio_page
from cms.djangoapps.contentstore.toggles import libraries_v2_enabled
from cms.djangoapps.contentstore.xblock_storage_handlers.view_handlers import load_services_for_studio
from common.djangoapps.edxmako.shortcuts import render_to_response
from common.djangoapps.student.auth import has_course_author_access
from common.djangoapps.xblock_django.api import authorable_xblocks, disabled_xblocks
from common.djangoapps.xblock_django.models import XBlockStudioConfigurationFlag
from openedx.core.djangoapps.authz.constants import LegacyAuthoringPermission
Expand Down Expand Up @@ -491,7 +491,7 @@ def _get_item_in_course(request, usage_key):
(container_handler, container_embed_handler, xblock_edit_view, and the REST API v1
ContainerHandlerView) are read-only, so this only requires view access, not write
access — actual mutations are gated separately (e.g. component_handler's own
has_course_author_access check before persisting).
edit permission check before persisting).
"""

from ..utils import get_lms_link_for_item
Expand Down Expand Up @@ -536,6 +536,13 @@ def component_handler(request, usage_key_string, handler, suffix=''):
# Let the block handle the AJAX
req = django_to_webob_request(request)

can_edit = user_has_course_permission(
request.user,
COURSES_EDIT_COURSE_CONTENT.identifier,
usage_key.course_key,
LegacyAuthoringPermission.WRITE,
)

try:
if is_xblock_aside(usage_key):
# Get the block being wrapped by the aside (not the aside itself)
Expand All @@ -546,21 +553,22 @@ def component_handler(request, usage_key_string, handler, suffix=''):
block = modulestore().get_item(usage_key)
handler_block = block
asides = []
if not can_edit:
fields_before = _persistable_fields([block, *asides])
load_services_for_studio(handler_block.runtime, request.user)
resp = handler_block.handle(handler, req, suffix)
except NoSuchHandlerError:
log.info("XBlock %s attempted to access missing handler %r", handler_block, handler, exc_info=True)
raise Http404 # pylint: disable=raise-missing-from # noqa: B904

# unintentional update to handle any side effects of handle call
# could potentially be updating actual course data or simply caching its values
# Addendum:
# TNL 101-62 studio write permission is also checked for editing content.

if has_course_author_access(request.user, usage_key.course_key):
# Persist whatever the handler changed on the block (or its asides).
if can_edit:
modulestore().update_item(block, request.user.id, asides=asides)
elif _persistable_fields([block, *asides]) != fields_before:
# Read-only handlers keep working for users without edit permission, but a handler
# that changed fields must not report success when nothing is going to be saved.
raise PermissionDenied()
else:
#fail quietly if user is not course author.
log.warning(
"%s does not have have studio write permissions on course: %s. write operations not performed on %r",
request.user.id,
Expand All @@ -571,6 +579,15 @@ def component_handler(request, usage_key_string, handler, suffix=''):
return webob_to_django_response(resp)


def _persistable_fields(blocks):
"""
Return a JSON snapshot of the fields ``update_item`` would persist for each block,
so callers can tell whether an XBlock handler changed any of them.
"""
scopes = (Scope.content, Scope.settings, Scope.children)
return [{scope: block.get_explicitly_set_fields_by_scope(scope) for scope in scopes} for block in blocks]


def get_unit_tags(usage_key):
"""
Get the tags of a Unit and build a json to be read by the UI
Expand Down
88 changes: 87 additions & 1 deletion cms/djangoapps/contentstore/views/tests/test_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from pytz import UTC
from web_fragments.fragment import Fragment
from webob import Response
from xblock.core import XBlockAside
from xblock.core import XBlock, XBlockAside
from xblock.exceptions import NoSuchHandlerError
from xblock.fields import Scope, ScopeIds, String
from xblock.runtime import DictKeyValueStore, KvsFieldData
Expand Down Expand Up @@ -3222,6 +3222,92 @@ def get_usage_key():
assert mocked_get_aside_from_xblock.called is is_get_aside_called


class HandlerTestBlock(XBlock):
"""
XBlock with one studio handler that changes a field and one that only reads it.
"""

text = String(default="", scope=Scope.content)

@XBlock.json_handler
def write_text(self, data, _suffix=""):
self.text = data["text"]
return {}

@XBlock.json_handler
def read_text(self, _data, _suffix=""):
return {"text": self.text}


@ddt.ddt
class TestComponentHandlerAuthz(CourseAuthoringAuthzTestMixin, ItemTest):
"""
Tests that component_handler only persists handler changes for users with
``courses.edit_course_content``, and rejects them with a 403 for everyone else
instead of reporting a success that was never saved.
"""

def _call_handler(self, user, handler, data):
"""
Create a HandlerTestBlock in the course, call ``handler`` on it as ``user`` and
return the response along with the block as stored afterwards.
"""
block = BlockFactory.create(parent=self.course, category="handlertestblock", user_id=self.user.id)
url = reverse(
"component_handler",
kwargs={"usage_key_string": str(block.location), "handler": handler},
)
self.client.login(username=user.username, password=self.password)
response = self.client.post(url, json.dumps(data), content_type="application/json")
return response, self.store.get_item(block.location)

@XBlock.register_temp_plugin(HandlerTestBlock)
@ddt.data(COURSE_EDITOR.external_key, COURSE_STAFF.external_key, COURSE_ADMIN.external_key)
def test_user_with_edit_permission_persists_changes(self, role_key):
self.add_user_to_role_in_course(self.authorized_user, role_key, self.course.id)

response, block = self._call_handler(self.authorized_user, "write_text", {"text": "saved"})

assert response.status_code == 200
assert block.text == "saved"

@XBlock.register_temp_plugin(HandlerTestBlock)
def test_user_without_edit_permission_gets_403_on_changes(self):
self.add_user_to_role_in_course(self.authorized_user, COURSE_AUDITOR.external_key, self.course.id)

response, block = self._call_handler(self.authorized_user, "write_text", {"text": "saved"})

assert response.status_code == 403
assert block.text == ""

@XBlock.register_temp_plugin(HandlerTestBlock)
def test_user_without_edit_permission_can_call_read_only_handler(self):
self.add_user_to_role_in_course(self.authorized_user, COURSE_AUDITOR.external_key, self.course.id)

response, _block = self._call_handler(self.authorized_user, "read_text", {})

assert response.status_code == 200
assert json.loads(response.content) == {"text": ""}

@XBlock.register_temp_plugin(HandlerTestBlock)
def test_legacy_staff_persists_changes_when_authz_disabled(self):
self.set_authz_enabled(False)

response, block = self._call_handler(self.staff_user, "write_text", {"text": "saved"})

assert response.status_code == 200
assert block.text == "saved"

@XBlock.register_temp_plugin(HandlerTestBlock)
def test_legacy_user_without_write_access_gets_403_when_authz_disabled(self):
self.set_authz_enabled(False)

response, block = self._call_handler(self.unauthorized_user, "write_text", {"text": "saved"})

assert response.status_code == 403
assert block.text == ""


class TestComponentTemplates(CourseTestCase):
"""
Unit tests for the generation of the component templates for a course.
Expand Down
Loading