sandboxing.py 1.58 KB
Newer Older
1
import re
2

3 4
from django.conf import settings

5 6 7
# We'll make assets named this be importable by Python code in the sandbox.
PYTHON_LIB_ZIP = "python_lib.zip"

8 9

def can_execute_unsafe_code(course_id):
10
    """
11 12 13 14 15 16 17
    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.

18
    """
19 20
    # To decide if we can run unsafe code, we check the course id against
    # a list of regexes configured on the server.
21 22
    # If this is not defined in the environment variables then default to the most restrictive, which
    # is 'no unsafe courses'
23 24 25 26 27
    # 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
28
    for regex in getattr(settings, 'COURSES_WITH_UNSAFE_CODE', []):
29
        if re.match(regex, unicode(course_id)):
30 31
            return True
    return False
32 33 34 35 36 37 38 39 40 41


def get_python_lib_zip(contentstore, course_id):
    """Return the bytes of the python_lib.zip file, if any."""
    asset_key = course_id.make_asset_key("asset", PYTHON_LIB_ZIP)
    zip_lib = contentstore().find(asset_key, throw_on_not_found=False)
    if zip_lib is not None:
        return zip_lib.data
    else:
        return None