Skip to content
Draft
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
10 changes: 7 additions & 3 deletions openedx/core/djangoapps/content_libraries/rest_api/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,9 +503,13 @@
# Permissions check...
learning_package = component_version.component.learning_package
library_key = LibraryLocatorV2.from_string(learning_package.package_ref)
api.require_permission_for_library_key(
library_key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRARY,
)
upstream_key = api.library_component_usage_key(library_key, component_version.component)
if not user_has_course_permission_for_upstream(
request, authz_permissions.COURSES_VIEW_LIBRARY_UPDATES.identifier, upstream_key

Check failure on line 508 in openedx/core/djangoapps/content_libraries/rest_api/blocks.py

View workflow job for this annotation

GitHub Actions / Quality Others (ubuntu-24.04, 3.12, 20)

ruff (F821)

openedx/core/djangoapps/content_libraries/rest_api/blocks.py:508:18: F821 Undefined name `authz_permissions`
):
api.require_permission_for_library_key(
library_key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRARY,
)

# We already have logic for getting the correct content and generating the
# proper headers in openedx_content, but the response generated here is an
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
This view is used in the MFE to preview XBlocks that are in the library.
"""
import re
from urllib.parse import parse_qs, urlparse

import ddt
import pytest
Expand Down Expand Up @@ -384,3 +385,100 @@ def test_library_permission_alone_still_works_without_course_id(self):
"""Backward compatibility: a user with direct library access keeps working as before."""
response = self.client.get(URL_LIB_BLOCK.format(block_key=self.block_id))
assert response.status_code == 200


@skip_unless_cms
class LibraryComponentAssetAuthzBypassTest(
CourseAuthoringAuthzTestMixin, ContentLibrariesRestApiTest, ModuleStoreTestCase,
):
"""
Same bypass as EmbedViewAuthzBypassTest above, but for the static asset URLs (images,
etc.) embedded inside a block's rendered content. The browser requests these directly,
not through a call the frontend controls, so the embed view's runtime has to bake
downstream_block_id into the asset URLs it generates, and LibraryComponentAssetView has
to do its own upstream-link check when those URLs are requested.

See openedx-authz#473.
"""

def setUp(self):
super().setUp()
self.course = CourseFactory.create()
self.add_user_to_role_in_course(self.authorized_user, COURSE_AUDITOR.external_key, str(self.course.id))

lib = self._create_library(slug="asset-authz-bypass-lib", title="Asset AuthZ Bypass Test Library")
create_response = self._add_block_to_library(lib["id"], "html", "block1")
self.block_id = create_response["id"]
self._set_library_block_olx(self.block_id, '<html><![CDATA[<img src="/static/deer.jpg"/>]]></html>')
self._set_library_block_asset(self.block_id, "static/deer.jpg", b"This is not a valid JPEG file")
self._commit_library_changes(lib["id"])

self.linked_downstream_id = str(
BlockFactory.create(category="html", parent=self.course, upstream=self.block_id).location
)
self.unrelated_downstream_id = str(
BlockFactory.create(category="html", parent=self.course).location
)

def _embed_html(self, downstream_block_id=None):
"""Render the published embed view and return its HTML, as whichever user is active."""
params = {"version": "published"}
if downstream_block_id is not None:
params["downstream_block_id"] = downstream_block_id
response = self.client.get(
URL_BLOCK_EMBED_VIEW.format(block_key=self.block_id, view_name="student_view"), params,
)
assert response.status_code == 200
return response.content.decode()

@staticmethod
def _extract_asset_url(html):
match = re.search(r'src="(https?://[^"]*/library_assets/component_versions/[^"]*/static/deer\.jpg[^"]*)"', html)
assert match, html
return match.group(1)

@staticmethod
def _downstream_block_id_param(asset_url):
return parse_qs(urlparse(asset_url).query).get("downstream_block_id", [None])[0]

def test_asset_allowed_with_linked_downstream(self):
"""
A course auditor can load an asset embedded in content they're reviewing via
downstream_block_id: the runtime bakes the param into the asset URL, and the asset
endpoint honors it because the downstream is actually linked to this block.
"""
with self.as_user(self.authorized_user):
html = self._embed_html(downstream_block_id=self.linked_downstream_id)
asset_url = self._extract_asset_url(html)
assert self._downstream_block_id_param(asset_url) == self.linked_downstream_id

with self.as_user(self.authorized_user):
response = self.client.get(asset_url)
assert response.status_code == 200

def test_asset_denied_without_downstream_block_id(self):
"""
Without downstream_block_id, a course auditor with no direct library access is
denied, same as before this fix (this was the actual bug report: the image was
broken because this always failed, even when the embed view itself was allowed).
"""
asset_url = self._extract_asset_url(self._embed_html()) # as self.user, who has direct access

with self.as_user(self.authorized_user), self.allow_transaction_exception():
response = self.client.get(asset_url)
assert response.status_code == 403

def test_asset_downstream_not_linked_to_this_block_is_denied(self):
"""A downstream in the user's course, but not linked to this block, must not grant access."""
asset_url = self._extract_asset_url(self._embed_html())
asset_url += f"?downstream_block_id={self.unrelated_downstream_id}"

with self.as_user(self.authorized_user), self.allow_transaction_exception():
response = self.client.get(asset_url)
assert response.status_code == 403

def test_library_permission_alone_still_works_without_downstream_block_id(self):
"""Backward compatibility: a user with direct library access keeps working as before."""
asset_url = self._extract_asset_url(self._embed_html())
response = self.client.get(asset_url)
assert response.status_code == 200
15 changes: 12 additions & 3 deletions openedx/core/djangoapps/xblock/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,27 @@
log = logging.getLogger(__name__)


def get_runtime(user: UserType | None) -> OpenedXContentRuntime:
def get_runtime(user: UserType | None, *, downstream_block_id: str | None = None) -> OpenedXContentRuntime:
"""
Return a new XBlockRuntime.

Each XBlockRuntime is bound to one user (and usually one request or one
celery task). It is typically used just to load and render a single block,
but the API _does_ allow a single runtime instance to load multiple blocks
(as long as they're for the same user).

``downstream_block_id`` is the usage key of the downstream course block this
runtime is rendering content on behalf of, if any (see ``load_block``). It's
threaded through so that any static asset URLs generated while rendering can
carry it too, since the browser requests those directly and isn't going
through a caller that could add the param itself.
"""
params = get_xblock_app_config().get_runtime_params()
params.update(
handler_url=get_handler_url,
authored_data_store=OpenedXContentFieldData(),
)
runtime = OpenedXContentRuntime(user, **params)
runtime = OpenedXContentRuntime(user, downstream_block_id=downstream_block_id, **params)

return runtime

Expand All @@ -72,6 +78,7 @@ def load_block(
*,
check_permission: CheckPerm | None = CheckPerm.CAN_LEARN,
version: int | LatestVersion = LatestVersion.AUTO,
downstream_block_id: str | None = None,
):
"""
Load the specified XBlock for the given user.
Expand All @@ -85,6 +92,8 @@ def load_block(
Args:
usage_key(OpaqueKey): block identifier
user(User): user requesting the block
downstream_block_id: the usage key of the downstream course block this block is
being rendered on behalf of, if any. See ``get_runtime``.
"""
# Is this block part of a course, a library, or what?
# Get the Learning Context Implementation based on the usage key
Expand All @@ -108,7 +117,7 @@ def load_block(
# e.g. a course might specify that all 'problem' XBlocks have 'max_attempts'
# set to 3.
# field_overrides = context_impl.get_field_overrides(usage_key)
runtime = get_runtime(user=user)
runtime = get_runtime(user=user, downstream_block_id=downstream_block_id)

try:
return runtime.get_block(usage_key, version=version)
Expand Down
14 changes: 13 additions & 1 deletion openedx/core/djangoapps/xblock/rest_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,20 @@ def embed_block_view(request, usage_key: UsageKeyV2, view_name: str):
):
check_permission = None

# Forwarded to the runtime so any static asset URLs it renders into this block's
# content (e.g. <img> tags) can carry it too: LibraryComponentAssetView does its own
# upstream-link check when the browser requests those directly, so it's safe to pass
# through unconditionally even when the bypass above didn't apply.
downstream_block_id = request.GET.get("downstream_block_id")

try:
block = load_block(usage_key, request.user, check_permission=check_permission, version=version)
block = load_block(
usage_key,
request.user,
check_permission=check_permission,
version=version,
downstream_block_id=downstream_block_id,
)
except NoSuchUsage as exc:
raise NotFound(f"{usage_key} not found") from exc

Expand Down
20 changes: 18 additions & 2 deletions openedx/core/djangoapps/xblock/runtime/openedx_content_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import logging
from collections import defaultdict
from datetime import datetime, timezone
from urllib.parse import unquote
from urllib.parse import quote, unquote

from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.transaction import atomic
Expand Down Expand Up @@ -164,6 +164,12 @@ class OpenedXContentRuntime(XBlockRuntime):
(eventually) asset storage.
"""

def __init__(self, user, *, downstream_block_id: str | None = None, **kwargs):
super().__init__(user, **kwargs)
# The usage key of the downstream course block this runtime is rendering content
# on behalf of, if any. See _absolute_url_for_asset for why this is needed.
self.downstream_block_id = downstream_block_id

def get_block(self, usage_key, for_parent=None, *, version: int | LatestVersion = LatestVersion.AUTO):
"""
Fetch an XBlock from openedx_content data models.
Expand Down Expand Up @@ -360,17 +366,27 @@ def _absolute_url_for_asset(self, component_version, asset_path):

This does not check for whether the path actually exists–it just returns
where it would be if it did exist.

If this runtime was constructed with a ``downstream_block_id`` (see
``OpenedXContentRuntime.__init__``), it's appended as a query param so that
a user reviewing pending library updates from a course they don't otherwise
have library access to (e.g. a Course Auditor) can still load the asset: the
browser requests this URL directly, so there's no other way to carry that
context to LibraryComponentAssetView's own permission check.
"""
# This function should return absolute URLs, so we need the site root.
site_root_url = get_xblock_app_config().get_site_root_url()

return site_root_url + reverse(
url = site_root_url + reverse(
'content_libraries:library-assets',
kwargs={
'component_version_uuid': component_version.uuid,
'asset_path': f"static/{asset_path}",
}
)
if self.downstream_block_id:
url += f"?downstream_block_id={quote(self.downstream_block_id)}"
return url

def _lookup_asset_url(self, block: XBlock, asset_path: str) -> str | None:
"""
Expand Down
Loading