Skip to content
Merged
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
5 changes: 2 additions & 3 deletions .github/workflows/check-consistent-dependencies.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ jobs:

# The ^"? is because git may quote weird file paths
#
# This still watches requirements/ because requirements/edx-sandbox
# (its own uv project) and the requirements/edx/*.txt compatibility
# exports still live there. A planned follow-up will remove the
# This still watches requirements/ because the requirements/edx/*.txt
# compatibility exports still live there. A planned follow-up will remove the
# requirements/ folder entirely (see public-engineering#543), at
# which point this pattern will need updating again.
if git diff --name-only "$BASE_SHA" | grep -P '^"?((requirements/)|(scripts/.*?/requirements/)|(scripts/[^/]+/pyproject\.toml)|(scripts/[^/]+/uv\.lock)|(pyproject\.toml)|(uv\.lock))'; then
Expand Down
18 changes: 8 additions & 10 deletions cms/djangoapps/contentstore/tests/test_contentstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -785,20 +785,18 @@ def test_import_polls(self):
# check that there's actually content in the 'question' field
self.assertGreater(len(items[0].question), 0) # noqa: PT009

def test_module_preview_in_whitelist(self):
def test_module_preview(self):
"""
Tests the ajax callback to render an XBlock
"""
with override_settings(COURSES_WITH_UNSAFE_CODE=[str(self.course.id)]):
# also try a custom response which will trigger the 'is this course in whitelist' logic
resp = self.client.get_json(
get_url('xblock_view_handler', self.vert_loc, kwargs={'view_name': 'container_preview'})
)
self.assertEqual(resp.status_code, 200) # noqa: PT009
resp = self.client.get_json(
get_url('xblock_view_handler', self.vert_loc, kwargs={'view_name': 'container_preview'})
)
self.assertEqual(resp.status_code, 200) # noqa: PT009

vertical = self.store.get_item(self.vert_loc)
for child in vertical.children:
self.assertContains(resp, str(child))
vertical = self.store.get_item(self.vert_loc)
for child in vertical.children:
self.assertContains(resp, str(child))

def test_delete(self):
# make sure the parent points to the child object which is to be deleted
Expand Down
5 changes: 1 addition & 4 deletions cms/djangoapps/contentstore/views/tests/test_preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,7 @@ def test_render_template(self):
assert '<div id="142" ns="main">Testing the MakoService</div>' in html

@override_settings(COURSES_WITH_UNSAFE_CODE=[r'course-v1:edX\+LmsModuleShimTest\+2021_Fall'])
def test_can_execute_unsafe_code(self):
assert self.block.runtime.can_execute_unsafe_code()

def test_cannot_execute_unsafe_code(self):
def test_cannot_execute_unsafe_code_even_when_listed(self):
assert not self.block.runtime.can_execute_unsafe_code()

@override_settings(PYTHON_LIB_FILENAME=PYTHON_LIB_FILENAME)
Expand Down
1 change: 0 additions & 1 deletion cms/envs/mock.yml
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,6 @@ FEATURES:
ENABLE_CREDIT_ELIGIBILITY: true
ENABLE_CROSS_DOMAIN_CSRF_COOKIE: true
ENABLE_CSMH_EXTENDED: true
ENABLE_DEBUG_RUN_PYTHON: true
ENABLE_DISCUSSION_HOME_PANEL: true
ENABLE_DISCUSSION_SERVICE: true
ENABLE_EDXNOTES: true
Expand Down
71 changes: 4 additions & 67 deletions common/djangoapps/util/tests/test_sandboxing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,42 +6,11 @@
import ddt
from django.test import TestCase
from django.test.utils import override_settings
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import CourseLocator, LibraryLocator, LibraryLocatorV2

from xmodule.contentstore.django import contentstore
from xmodule.modulestore.tests.django_utils import upload_file_to_course
from xmodule.util.sandboxing import SandboxService, can_execute_unsafe_code


class SandboxingTest(TestCase):
"""
Test sandbox whitelisting
"""
@override_settings(COURSES_WITH_UNSAFE_CODE=['edX/full/.*', 'library:v1-edX+.*'])
def test_sandbox_exclusion(self):
"""
Test to make sure that a non-match returns false
"""
assert not can_execute_unsafe_code(CourseLocator('edX', 'notful', 'empty'))
assert not can_execute_unsafe_code(LibraryLocator('edY', 'test_bank'))

@override_settings(COURSES_WITH_UNSAFE_CODE=['edX/full/.*'])
def test_sandbox_inclusion(self):
"""
Test to make sure that a match works across course runs
"""
assert can_execute_unsafe_code(CourseKey.from_string('edX/full/2012_Fall'))
assert can_execute_unsafe_code(CourseKey.from_string('edX/full/2013_Spring'))
assert not can_execute_unsafe_code(LibraryLocator('edX', 'test_bank'))

def test_courselikes_with_unsafe_code_default(self):
"""
Test that the default setting for COURSES_WITH_UNSAFE_CODE is an empty setting, e.g. we don't use @override_settings in these tests # pylint: disable=line-too-long
"""
assert not can_execute_unsafe_code(CourseLocator('edX', 'full', '2012_Fall'))
assert not can_execute_unsafe_code(CourseLocator('edX', 'full', '2013_Spring'))
assert not can_execute_unsafe_code(LibraryLocator('edX', 'test_bank'))
from xmodule.util.sandboxing import SandboxService


@ddt.ddt
Expand All @@ -68,45 +37,13 @@ def setUpClass(cls):
target_filename=cls.PYTHON_LIB_FILENAME,
)

@staticmethod
def validate_can_execute_unsafe_code(context_key, expected_result):
sandbox_service = SandboxService(course_id=context_key, contentstore=None)
assert expected_result == sandbox_service.can_execute_unsafe_code()

@ddt.data(
CourseLocator('edX', 'notful', 'empty'),
LibraryLocator('edY', 'test_bank'),
)
@override_settings(COURSES_WITH_UNSAFE_CODE=['edX/full/.*', 'library:v1-edX+.*'])
def test_sandbox_exclusion(self, context_key):
"""
Test to make sure that a non-match returns false
"""
self.validate_can_execute_unsafe_code(context_key, False)

@ddt.data(
CourseKey.from_string('edX/full/2012_Fall'),
CourseKey.from_string('edX/full/2013_Spring'),
)
@override_settings(COURSES_WITH_UNSAFE_CODE=['edX/full/.*'])
def test_sandbox_inclusion(self, context_key):
"""
Test to make sure that a match works across course runs
"""
self.validate_can_execute_unsafe_code(context_key, True)
self.validate_can_execute_unsafe_code(LibraryLocator('edX', 'test_bank'), False)

@ddt.data(
CourseLocator('edX', 'full', '2012_Fall'),
CourseLocator('edX', 'full', '2013_Spring'),
LibraryLocator('edX', 'test_bank'),
)
def test_courselikes_with_unsafe_code_default(self, context_key):
"""
Test that the default setting for COURSES_WITH_UNSAFE_CODE is an empty setting,
i.e., we don't use @override_settings in these tests
"""
self.validate_can_execute_unsafe_code(context_key, False)
def test_cannot_execute_unsafe_code(self, context_key):
sandbox_service = SandboxService(course_id=context_key, contentstore=None)
assert sandbox_service.can_execute_unsafe_code() is False

@override_settings(PYTHON_LIB_FILENAME=PYTHON_LIB_FILENAME)
def test_get_python_lib_zip(self):
Expand Down
9 changes: 1 addition & 8 deletions lms/djangoapps/courseware/tests/test_block_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -2883,14 +2883,7 @@ def test_render_template(self):
assert rendered == '<div id="hi" ns="main">Testing the MakoService</div>\n'

@override_settings(COURSES_WITH_UNSAFE_CODE=[r'course-v1:edX\+LmsModuleShimTest\+2021_Fall'])
def test_can_execute_unsafe_code_when_allowed(self):
assert self.block.runtime.can_execute_unsafe_code()

@override_settings(COURSES_WITH_UNSAFE_CODE=[r'course-v1:edX\+full\+2021_Fall'])
def test_cannot_execute_unsafe_code_when_disallowed(self):
assert not self.block.runtime.can_execute_unsafe_code()

def test_cannot_execute_unsafe_code(self):
def test_cannot_execute_unsafe_code_even_when_listed(self):
assert not self.block.runtime.can_execute_unsafe_code()

@override_settings(PYTHON_LIB_FILENAME=PYTHON_LIB_FILENAME)
Expand Down
41 changes: 1 addition & 40 deletions lms/djangoapps/debug/views.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,13 @@
"""Views for debugging and diagnostics"""


import pprint
import traceback

from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.http import HttpResponse
from django.utils.html import escape
from django.views.decorators.csrf import ensure_csrf_cookie
from xblock_problem.capa.safe_exec import safe_exec

from common.djangoapps.edxmako.shortcuts import render_to_response
from openedx.core.djangolib.markup import HTML


@login_required
@ensure_csrf_cookie
def run_python(request):
"""
A page to allow testing the Python sandbox on a production server.

Runs in the override context "debug_run_python", so resource limits with come first from:
CODE_JAIL['limit_overrides']['debug_run_python']
and then from:
CODE_JAIL['limits']
"""
if not request.user.is_staff:
raise Http404
c = {}
c['code'] = ''
c['results'] = None
if request.method == 'POST':
py_code = c['code'] = request.POST.get('code')
g = {}
try:
safe_exec(
code=py_code,
globals_dict=g,
slug="debug_run_python",
limit_overrides_context="debug_run_python",
)
except Exception: # pylint: disable=broad-except
c['results'] = traceback.format_exc()
else:
c['results'] = pprint.pformat(g)
return render_to_response("debug/run_python_form.html", c)


@login_required
def show_parameters(request):
"""A page that shows what parameters were on the URL and post."""
Expand Down
4 changes: 0 additions & 4 deletions lms/envs/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,6 @@
# .. toggle_tickets: https://github.com/openedx/edx-platform/commit/8f17e6ae9ed76fa75b3caf867b65ccb632cb6870
ENABLE_STUDENT_HISTORY_VIEW = True

# Turn on a page that lets staff enter Python code to be run in the
# sandbox, for testing whether it's enabled properly.
ENABLE_DEBUG_RUN_PYTHON = False

# Enable instructor dash to submit background tasks
ENABLE_INSTRUCTOR_BACKGROUND_TASKS = True

Expand Down
1 change: 0 additions & 1 deletion lms/envs/mock.yml
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,6 @@ FEATURES:
ENABLE_CREDIT_ELIGIBILITY: true
ENABLE_CROSS_DOMAIN_CSRF_COOKIE: true
ENABLE_CSMH_EXTENDED: true
ENABLE_DEBUG_RUN_PYTHON: true
ENABLE_DISCUSSION_HOME_PANEL: true
ENABLE_DISCUSSION_SERVICE: true
ENABLE_EDXNOTES: true
Expand Down
21 changes: 0 additions & 21 deletions lms/templates/debug/run_python_form.html

This file was deleted.

5 changes: 0 additions & 5 deletions lms/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,11 +850,6 @@
),
]

if settings.ENABLE_DEBUG_RUN_PYTHON:
urlpatterns += [
path('debug/run_python', debug_views.run_python),
]

urlpatterns += [
path('debug/show_parameters', debug_views.show_parameters),
]
Expand Down
10 changes: 5 additions & 5 deletions openedx/core/djangoapps/xblock/runtime/shims.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,13 @@ def cache(self):
@property
def can_execute_unsafe_code(self):
"""
Determine if capa problems in this context/course are allowed to run
unsafe code. See xmodule/util/sandboxing.py
Always False.

Seems only to be used by capa.
Course code always runs in the codejail sandbox now, so there is no
unsafe execution to allow. Kept so that XBlocks that still read it
don't break.
"""
# TODO: Refactor capa to access this directly, don't bother the runtime. Then remove it from here.
return False # Change this if/when we need to support unsafe courses in the new runtime.
return False

def get_python_lib_zip(self):
"""
Expand Down
4 changes: 1 addition & 3 deletions requirements/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ The main application's Python dependencies are declared in the root
and ``[tool.edx_lint].uv_constraints`` for repo-specific version pins) and
locked in the root ``uv.lock``, managed with `uv`_.

This ``requirements/`` directory now holds ``edx-sandbox``, its own
standalone ``uv``-managed project (``pyproject.toml`` + ``uv.lock``) for
Codejail's isolated sandbox environment, plus ``requirements/edx/*.txt`` --
This ``requirements/`` directory now holds ``requirements/edx/*.txt`` --
generated compatibility exports of the main app's dependencies (regenerated
by ``make compile-requirements``, not hand-edited) for external tools like
Tutor/Devstack that still do ``pip install -r requirements/edx/base.txt``
Expand Down
Empty file.
20 changes: 0 additions & 20 deletions xmodule/capa/safe_exec/remote_exec.py

This file was deleted.

3 changes: 2 additions & 1 deletion xmodule/capa_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -838,7 +838,8 @@ def new_lcp(self, state, text=None):
ajax_url=self.ajax_url,
anonymous_student_id=anonymous_student_id,
cache=cache_service,
can_execute_unsafe_code=sandbox_service.can_execute_unsafe_code,
# Remove with https://github.com/openedx/xblocks-core/issues/350
can_execute_unsafe_code=lambda: False,
get_python_lib_zip=sandbox_service.get_python_lib_zip,
DEBUG=self.debug,
i18n=self.runtime.service(self, "i18n"),
Expand Down
34 changes: 5 additions & 29 deletions xmodule/util/sandboxing.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""Utilities for managing course code libraries and sandbox execution."""

import re

from django.conf import settings
from opaque_keys.edx.keys import CourseKey, LearningContextKey

Expand All @@ -15,31 +13,6 @@ def course_code_library_asset_name():
return getattr(settings, "PYTHON_LIB_FILENAME", DEFAULT_PYTHON_LIB_FILENAME)


def can_execute_unsafe_code(course_id):
"""
Determine if this course is allowed to run unsafe code.

For use from the ModuleStore. Checks the `course_id` against a list of whitelisted
regexes.

Returns a boolean, true if the course can run outside the sandbox.

"""
# To decide if we can run unsafe code, we check the course id against
# a list of regexes configured on the server.
# If this is not defined in the environment variables then default to the most restrictive, which
# is 'no unsafe courses'
# TODO: This should be a database configuration, where we can mark individual courses as being
# safe/unsafe. Someone in the future should switch us over to that rather than using regexes
# in a settings file
# To others using this: the code as-is is brittle and likely to be changed in the future,
# as per the TODO, so please consider carefully before adding more values to COURSES_WITH_UNSAFE_CODE
for regex in getattr(settings, "COURSES_WITH_UNSAFE_CODE", []):
if re.match(regex, str(course_id)):
return True
return False


def get_python_lib_zip(contentstore, context_key: LearningContextKey):
"""Return the bytes of the course code library file, if it exists."""
if not isinstance(context_key, CourseKey):
Expand Down Expand Up @@ -71,9 +44,12 @@ def __init__(self, contentstore, course_id, **kwargs):

def can_execute_unsafe_code(self):
"""
Returns a boolean, true if the course can run outside the sandbox.
Always False: course code only runs in the codejail service.

Kept only because xblocks-core's ProblemBlock still reads it from this service.
Remove it with https://github.com/openedx/xblocks-core/issues/350
"""
return can_execute_unsafe_code(self.course_id)
return False

def get_python_lib_zip(self):
"""
Expand Down
Loading
Loading