Skip to content

fix: let course_id bypass library access when reviewing pending updates - #39107

Open
efortish wants to merge 8 commits into
openedx:masterfrom
eduNEXT:ks/issue-441-library-review-authz
Open

efortish wants to merge 8 commits into
openedx:masterfrom
eduNEXT:ks/issue-441-library-review-authz

Conversation

@efortish

@efortish efortish commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Description

The library container endpoints and the xblock embed endpoint used by the "review pending changes" modal (opened from a course unit when a library-sourced component has updates available) only checked direct library permissions. That means a Course Auditor, or anyone else holding courses.view_library_updates at the course level, gets a 403 trying to review changes even though they can view everything else about that course.

This adds an optional course_id query param to the three affected endpoints:

  • GET /api/libraries/v2/containers/<container_id>/
  • GET /api/libraries/v2/containers/<container_id>/children/
  • GET /xblocks/v2/<usage_key>/embed/<view_name>/

When course_id is present and the requesting user holds courses.view_library_updates in that course, access is granted without requiring direct library permissions. Without it, or if the check fails, the existing library-level permission check runs exactly as before, so nothing changes for callers that don't pass it.

This is the same approach already used for the sync endpoint in #39009 and #39055.

The companion frontend change (threading the course id through to these three calls) is in openedx/frontend-app-authoring#3251.

Related to openedx/openedx-authz#441

Testing

  • Added regression tests covering the course_id bypass and the "no access to an unrelated course" case for all three endpoints, plus unit tests for the new user_has_course_permission_from_query_param helper.
  • Verified manually end to end against a devstack: a Course Auditor with zero library permissions gets 403 on all three endpoints without course_id, and 200 once course_id points at their course.

Deadline

None

@openedx-webhooks openedx-webhooks added the open-source-contribution PR author is not from Axim or 2U label Sep 16, 2026
@openedx-webhooks

openedx-webhooks commented Sep 16, 2026 •

Copy link
Copy Markdown

Thanks for the pull request, @efortish!

This repository is currently maintained by @openedx/wg-maintenance-openedx-platform-oncall.

Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review.

🔘 Get product approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Get a green build

If one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green.

Details
Where can I find more information?

If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources:

When can I expect my changes to be merged?

Our goal is to get community contributions seen and reviewed as efficiently as possible.

However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

request.user,
permissions.CAN_VIEW_THIS_CONTENT_LIBRARY,
)
if not user_has_course_permission_from_query_param(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a decorator or a utility function? I ask because it is implemented in the decorator modules so I'd expect it could be used as a decorator. Although I see we've been using the pattern of defining non-decorator helpers in that module.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a plain helper, not a decorator. Kept it in this module because that's where the other course-permission helpers already live (user_has_course_permission, get_course_key). Happy to split decorators from plain utilities into their own file if you'd rather.

self.lib = self._create_library(slug="library-updates-lib", title="Library Updates Test Library")
self.unit = self._create_container(self.lib["id"], "unit", display_name="Reviewable Unit", slug=None)

def test_container_detail_denied_without_course_id(self):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please add docstrings so we follow the same conventions as the other test suites?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added, thanks.

Comment on lines +1363 to +1366
def test_container_children_denied_without_course_id(self):
with self.as_user(self.authorized_user):
response = self.client.get(URL_LIB_CONTAINER_CHILDREN.format(container_key=self.unit["id"]))
assert response.status_code == 403

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So how does this hold "Without it, or if the check fails, the existing library-level permission check runs exactly as before, so nothing changes for callers that don't pass it." ? What are the cases when the this is backward compatible without the course ID param? Can we add a test for it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, there wasn't one. Added test_library_permission_alone_still_works_without_course_id: a user with direct library access, no course_id passed at all, still gets 200 exactly like before.



@skip_unless_cms
@override_settings(CORS_ORIGIN_WHITELIST=[]) # For some reason, this setting isn't defined in our test environment?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is the correct approach. Can you please attach the error that's raised without this setting? Thanks!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, copying the workaround was the wrong call. Root cause: embed_block_view reads settings.CORS_ORIGIN_WHITELIST directly with no fallback, and cms/envs/test.py never defined it (lms/envs/test.py does). Fixed the actual setting in cms/envs/test.py and dropped the override_settings from both test classes in this file.

@dcoa

dcoa commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

I was testing the frontend part and i just want to flag one thing that I just noticed and that is the assets from that particular library still returning 403.

image

@BryanttV BryanttV left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @efortish!

Comment on lines +84 to +91
if not user_has_course_permission_from_query_param(
request, authz_permissions.COURSES_VIEW_LIBRARY_UPDATES.identifier
):
api.require_permission_for_library_key(
container_key.lib_key,
request.user,
permissions.CAN_VIEW_THIS_CONTENT_LIBRARY,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem with this specific approach is that it grants access based solely on the user having the courses.view_library_updates permission in the course specified by the course_id query parameter, but it never verifies whether that course is actually linked to the requested library/container/block, which could lead to unintended access.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, this checked the permission but never the relationship. Fixed: the param now has to be the downstream's own usage key, I resolve its UpstreamLink and compare it against the resource being requested before granting anything. Added a regression test for this exact case (a downstream in an accessible course that's linked to something else).

@efortish

Copy link
Copy Markdown
Contributor Author

Good catch. That one's a different beast though: the asset URL gets baked into the rendered HTML by the runtime itself (openedx_content_runtime.py), not requested by our frontend, so it needs its own fix (threading course_id through the render pipeline, plus its own UpstreamLink check on the asset endpoint). Filed it separately so it doesn't block this PR: openedx/openedx-authz#473

Comment on lines +159 to +165
from opaque_keys.edx.locator import ( # pylint: disable=import-outside-toplevel
LibraryContainerLocator,
LibraryUsageLocatorV2,
)

from xmodule.modulestore.django import modulestore # pylint: disable=import-outside-toplevel
from xmodule.modulestore.exceptions import ItemNotFoundError # pylint: disable=import-outside-toplevel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we move these imports to the top of the module? I'd rather avoid function-level imports, since they hide the dependency until the function runs and can produce import-order surprises later. I checked, and moving them seems safe:

  • opaque_keys is already imported at the top of this module (UsageKey, InvalidKeyError), so the locators don't need to be local.
  • xmodule is available in LMS too. Other core apps already import modulestore at the top level, e.g. openedx/core/djangoapps/heartbeat/default_checks.py and openedx/core/djangoapps/user_api/accounts/utils.py.
  • lint-imports reports the same dependency graph either way, since grimp also counts imports inside functions. So the local imports weren't keeping this module out of the layering contracts.

With the change applied I ran:

  • lint-imports: 4 contracts kept, 0 broken.
  • import openedx.core.djangoapps.authz.decorators after django.setup() in both LMS and CMS, directly and through lms.djangoapps.courseware.access, with no circular import.
  • authz/tests/test_decorators.py, content_libraries/tests/test_containers.py and content_libraries/tests/test_embed_block.py: 78 passed.

The tests need their patch target updated, because modulestore becomes a name in decorators.py:

# decorators.py
 from opaque_keys.edx.keys import CourseKey, UsageKey
+from opaque_keys.edx.locator import LibraryContainerLocator, LibraryUsageLocatorV2
 ...
 from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin
+from xmodule.modulestore.django import modulestore
+from xmodule.modulestore.exceptions import ItemNotFoundError
 ...
-    # Imported locally: this pulls in xmodule-only code, which isn't available to every
-    # process that imports this module (e.g. a pure LMS process without Studio installed).
-    from opaque_keys.edx.locator import (  # pylint: disable=import-outside-toplevel
-        LibraryContainerLocator,
-        LibraryUsageLocatorV2,
-    )
-
-    from xmodule.modulestore.django import modulestore  # pylint: disable=import-outside-toplevel
-    from xmodule.modulestore.exceptions import ItemNotFoundError  # pylint: disable=import-outside-toplevel
-

# tests/test_decorators.py (all 9 occurrences)
-        with patch("xmodule.modulestore.django.modulestore") as mock_modulestore:
+        with patch("openedx.core.djangoapps.authz.decorators.modulestore") as mock_modulestore:

Also move the ItemNotFoundError import in test_downstream_not_found_denies to the top of the test module.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, moved both imports to module level and updated the patch targets in the tests.

Confirmed it holds in both processes, not just CMS: imported openedx.core.djangoapps.authz.decorators after django.setup() in the LMS container directly (not just CMS) and it resolves modulestore fine, then ran test_decorators.py under lms.envs.test (16 passed). Also reran lint-imports (4 contracts kept) and all 78 tests across test_decorators.py, test_containers.py and test_embed_block.py under CMS settings. So the old docstring concern about a pure-LMS process not having Studio installed doesn't hold here, xmodule is a hard dependency either way.

The library container and xblock embed endpoints used by the "review
pending changes" modal only checked direct library permissions, so a
Course Auditor (or any role holding courses.view_library_updates) got
a 403 even though they should be able to review changes from their
course.

Accept an optional course_id query param on these three endpoints and
grant access via courses.view_library_updates when it points to a
course the user can review from, falling back to the existing
library-level check otherwise. Same pattern already used for the sync
endpoint in openedx#39009 and openedx#39055.

Related to openedx/openedx-authz#441
mypy needs check_permission annotated as CheckPerm | None explicitly,
since the first assignment alone made it infer plain CheckPerm.

Move the embed view's authz bypass test out of test_runtime.py (a
plain TestCase, missing CORS_ORIGIN_WHITELIST in the CMS test
environment) into test_embed_block.py, next to the other embed view
tests, using the same override_settings(CORS_ORIGIN_WHITELIST=[])
workaround already in place there for the same reason.
The course_id bypass only checked that the user held
courses.view_library_updates in the given course, never that the
course actually used the requested library resource. That meant
holding the permission in any course was enough to read any library
container or block in the system.

Require the query param to be a real downstream usage key, resolve
its UpstreamLink, and only grant access when that link points at the
resource being requested. Same approach already used by
upstream_sync_block.py/upstream_sync_container.py for the sync
endpoint.

Also:
- add regression tests for the mismatched-downstream case and for
  existing library-permission callers who never pass course_id
- fix cms/envs/test.py to actually define CORS_ORIGIN_WHITELIST
  instead of overriding it per test class, embed_block_view reads it
  directly with no fallback

Addresses review from @mariajgrimaldi and @BryanttV.
user_has_course_permission_for_upstream imported UpstreamLink from
cms.lib.xblock.upstream_sync, which import-linter's layers contract
places above content_libraries, content_staging and xblock. Those
apps import authz.decorators, so the import violated the contract
even though it was function-local, and broke CI's Lint Python
Imports job for all three.

Read the downstream block's upstream field directly instead of going
through UpstreamLink, and parse it with LibraryUsageLocatorV2 or
LibraryContainerLocator from opaque_keys, which isn't subject to the
layers contract. Updated the tests to match: they now use real
library keys and mock modulestore().get_item() to return an object
with a plain upstream attribute, instead of mocking UpstreamLink.
Under ModuleStoreTestCase, ATOMIC_REQUESTS wraps each request in a
savepoint nested inside the test's own outer transaction. When a view
returns a DRF PermissionDenied, DRF marks that savepoint for rollback,
and response middleware that runs a query afterward (lang_pref's
process_response, checking the user's language preference) hits
TransactionManagementError because the savepoint hasn't been rolled
back yet.

Wrap the requests that intentionally get a 403 in
self.allow_transaction_exception(), the same pattern already used in
test_clipboard.py for the same kind of test.
Function-level imports hid the dependency until the function ran and
could produce import-order surprises later. Moving opaque_keys locators
and xmodule.modulestore to the top is safe here: opaque_keys is already
imported at the top of this module, xmodule is available in both LMS
and CMS, other core apps already import modulestore at module level,
and lint-imports reports the same dependency graph either way since
grimp counts function-level imports too.

Update test_decorators.py to patch the new module-level name
(openedx.core.djangoapps.authz.decorators.modulestore) and move the
local ItemNotFoundError import in test_downstream_not_found_denies to
the top of the test module.
@efortish
efortish force-pushed the ks/issue-441-library-review-authz branch from 2ea06f6 to f38325c Compare October 14, 2026 20:23
The param was never actually a course id, it's always been the
downstream block's usage key (the decorator derives the course from
it after verifying the upstream link), so the name was misleading to
API consumers. Matches the frontend-app-authoring PR's own rename of
the prop from courseId to downstreamBlockId for the same reason.

No call site passes param_name explicitly, so this only changes the
function's default and the tests that exercise it directly.
efortish added a commit to eduNEXT/frontend-app-authoring that referenced this pull request Oct 15, 2026
Matches the backend rename in openedx/openedx-platform#39107: the
param was never actually a course id, it's always been the downstream
block's usage key, so course_id was a misleading name for API
consumers on both ends.
@efortish

Copy link
Copy Markdown
Contributor Author

Renamed the course_id query param to downstream_block_id (per feedback on the frontend-app-authoring PR, openedx/frontend-app-authoring#3251#discussion_r4151370889: the param was never actually a course id, so the old name was misleading to API consumers). Updated the decorator's default, and the companion frontend PR to match.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open-source-contribution PR author is not from Axim or 2U

Projects

Status: Ready for Review

Development

Successfully merging this pull request may close these issues.

Fix review endpoints to allow access for users with courses.view_library_updates permission

6 participants