-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add codejail_service app for transition to containerized codejail #530
Merged
Merged
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
ecc21eb
feat: Add codejail_service app for transition to containerized codejail
timmc-edx d520843
Merge branch 'main' into timmc/codejail-service
timmc-edx 30043a6
fixup! Use single-quotes for identifier string (personal preference)
timmc-edx 21adbfd
fixup! Move no-relays check higher in method
timmc-edx 92ffa67
fixup! Make globals_dict required
timmc-edx 9bb44ee
fixup! Convert some exceptions into responses
timmc-edx 6c02d0e
fixup! JSON for all responses, and document response format
timmc-edx 448bb1f
fixup! Fix file uploading and add unit tests
timmc-edx d1e0a74
fixup! Also clean up and test reporting of sandboxed exceptions
timmc-edx acb08dd
fixup! Document remaining test util args; move files kwarg later
timmc-edx File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
Codejail Service | ||
################ | ||
|
||
When installed in the LMS as a plugin app, the ``codejail_service`` app allows the CMS to delegate codejail executions to the LMS across the network. | ||
|
||
This is intended as a `temporary situation <https://github.com/openedx/edx-platform/issues/33538>`_ with the following goals: | ||
|
||
- Unblock containerization of the CMS. Codejail cannot be readily containerized due to its reliance on AppArmor, but if codejail execution is outsourced, then we can containerize CMS first and will be in a better position to containerize the LMS afterwards. | ||
- Exercise the remote-codejail pathway and have an opportunity to discover and implement needed improvements before fully building out a separate, dedicated codejail service. | ||
|
||
Usage | ||
***** | ||
|
||
In LMS: | ||
|
||
- Install ``edx-arch-experiments`` as a dependency | ||
- Identify a service account that will be permitted to make calls to the codejail service and ensure it has the ``is_staff`` Django flag. In devstack, this would be ``cms_worker``. | ||
- In Djano admin, under ``Django OAuth Toolkit > Applications``, find or create a Client Credentials application for that service user. | ||
|
||
In CMS: | ||
|
||
- Set ``ENABLE_CODEJAIL_REST_SERVICE`` to ``True`` | ||
- Set ``CODE_JAIL_REST_SERVICE_HOST`` to the URL origin of the LMS (e.g. ``http://edx.devstack.lms:18000`` in devstack) | ||
- Keep ``CODE_JAIL_REST_SERVICE_REMOTE_EXEC`` at its default of ``xmodule.capa.safe_exec.remote_exec.send_safe_exec_request_v0`` | ||
- Adjust ``CODE_JAIL_REST_SERVICE_CONNECT_TIMEOUT`` and ``CODE_JAIL_REST_SERVICE_READ_TIMEOUT`` if needed | ||
- Set ``CODE_JAIL_REST_SERVICE_OAUTH_URL`` to the LMS OAuth endpoint (e.g. ``http://edx.devstack.lms:18000`` in devstack) | ||
- Set ``CODE_JAIL_REST_SERVICE_OAUTH_CLIENT_ID`` and ``CODE_JAIL_REST_SERVICE_OAUTH_CLIENT_SECRET`` to the client credentials app ID and secret that you identified in the LMS. (In devstack, these would be ``cms-backend-service-key`` and ``cms-backend-service-secret``.) |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
""" | ||
App for running answer submissions inside of codejail. | ||
""" | ||
|
||
from django.apps import AppConfig | ||
from edx_django_utils.plugins.constants import PluginURLs | ||
|
||
|
||
class CodejailService(AppConfig): | ||
""" | ||
Django application to run things in codejail. | ||
""" | ||
name = 'edx_arch_experiments.codejail_service' | ||
|
||
plugin_app = { | ||
PluginURLs.CONFIG: { | ||
'lms.djangoapp': { | ||
PluginURLs.NAMESPACE: 'codejail_service', | ||
} | ||
}, | ||
} |
Binary file added
BIN
+238 Bytes
edx_arch_experiments/codejail_service/tests/test_course_library.zip
Binary file not shown.
149 changes: 149 additions & 0 deletions
149
edx_arch_experiments/codejail_service/tests/test_views.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
""" | ||
Test codejail service views. | ||
""" | ||
|
||
import json | ||
import textwrap | ||
from os import path | ||
|
||
import ddt | ||
from django.contrib.auth import get_user_model | ||
from django.test import TestCase, override_settings | ||
from django.urls import reverse | ||
from rest_framework.test import APIClient | ||
|
||
from edx_arch_experiments.codejail_service import views | ||
|
||
|
||
@override_settings( | ||
ROOT_URLCONF='edx_arch_experiments.codejail_service.urls', | ||
MIDDLEWARE=[ | ||
'django.contrib.sessions.middleware.SessionMiddleware', | ||
], | ||
) | ||
@ddt.ddt | ||
class TestExecService(TestCase): | ||
"""Test the v0 code exec view.""" | ||
|
||
def setUp(self): | ||
super().setUp() | ||
user_model = get_user_model() | ||
self.admin_user = user_model.objects.create_user('cms_worker', is_staff=True) | ||
self.other_user = user_model.objects.create_user('student', is_staff=False) | ||
self.standard_params = {'code': 'retval = 3 + 4', 'globals_dict': {}} | ||
|
||
def _test_codejail_api(self, *, user=None, files=None, skip_auth=False, params=None, exp_status, exp_body): | ||
""" | ||
Call the view and make assertions. | ||
|
||
Arguments: | ||
user: User to authenticate as when calling view (None for unauthenticated) | ||
exp_status: Assert that the response HTTP status code is this value | ||
exp_body: Assert that the response body JSON is this value | ||
""" | ||
assert not (user and skip_auth) | ||
|
||
client = APIClient() | ||
user = user or self.admin_user | ||
if not skip_auth: | ||
client.force_authenticate(user) | ||
|
||
params = self.standard_params if params is None else params | ||
payload = json.dumps(params) | ||
req_body = {'payload': payload, **(files or {})} | ||
|
||
resp = client.post(reverse('code_exec_v0'), req_body, format='multipart') | ||
|
||
assert resp.status_code == exp_status | ||
assert json.loads(resp.content) == exp_body | ||
|
||
def test_success(self): | ||
"""Regular successful call.""" | ||
self._test_codejail_api( | ||
exp_status=200, exp_body={'globals_dict': {'retval': 7}}, | ||
) | ||
|
||
@override_settings(CODEJAIL_SERVICE_ENABLED=False) | ||
def test_feature_disabled(self): | ||
"""Service can be disabled.""" | ||
self._test_codejail_api( | ||
exp_status=500, exp_body={'error': "Codejail service not enabled"}, | ||
) | ||
|
||
@override_settings(ENABLE_CODEJAIL_REST_SERVICE=True) | ||
def test_misconfigured_as_relay(self): | ||
"""Don't accept codejail requests if we're going to send them elsewhere.""" | ||
self._test_codejail_api( | ||
exp_status=500, exp_body={'error': "Codejail service is misconfigured. (Refusing to act as relay.)"}, | ||
) | ||
|
||
def test_unauthenticated(self): | ||
"""Anonymous requests are rejected.""" | ||
self._test_codejail_api( | ||
skip_auth=True, | ||
exp_status=403, exp_body={'detail': "Authentication credentials were not provided."}, | ||
) | ||
|
||
def test_unprivileged(self): | ||
"""Anonymous requests are rejected.""" | ||
self._test_codejail_api( | ||
user=self.other_user, | ||
exp_status=403, exp_body={'detail': "You do not have permission to perform this action."}, | ||
) | ||
|
||
def test_unsafely(self): | ||
"""unsafely=true is rejected""" | ||
self._test_codejail_api( | ||
params=dict(**self.standard_params, unsafely=True), | ||
exp_status=400, exp_body={'error': "Refusing codejail execution with unsafely=true"}, | ||
) | ||
|
||
@ddt.unpack | ||
@ddt.data( | ||
({'globals_dict': {}}, 'code'), | ||
({'code': 'retval = 3 + 4'}, 'globals_dict'), | ||
({}, 'code'), | ||
) | ||
def test_missing_params(self, params, missing): | ||
"""Two code and globals_dict params are required.""" | ||
self._test_codejail_api( | ||
params=params, | ||
exp_status=400, exp_body={ | ||
'error': f"Payload JSON did not match schema: '{missing}' is a required property", | ||
}, | ||
) | ||
|
||
def test_extra_files(self): | ||
"""Check that we can include a course library.""" | ||
# "Course library" containing `course_library.triangular_number`. | ||
# | ||
# It's tempting to use zipfile to write to an io.BytesIO so | ||
# that the test library is in plaintext. Django's request | ||
# factory will indeed see that as a file to use in a multipart | ||
# upload, but it will see it as an empty bytestring. (read() | ||
# returns empty bytestring, while getvalue() returns the | ||
# desired data). So instead we just have a small zip file on | ||
# disk here. | ||
library_path = path.join(path.dirname(__file__), 'test_course_library.zip') | ||
|
||
with open(library_path, 'rb') as lib_zip: | ||
self._test_codejail_api( | ||
params={ | ||
'code': textwrap.dedent(""" | ||
from course_library import triangular_number | ||
|
||
result = triangular_number(6) | ||
"""), | ||
'globals_dict': {}, | ||
'python_path': ['python_lib.zip'], | ||
}, | ||
files={'python_lib.zip': lib_zip}, | ||
exp_status=200, exp_body={'globals_dict': {'result': 21}}, | ||
) | ||
|
||
def test_exception(self): | ||
"""Report exceptions from jailed code.""" | ||
self._test_codejail_api( | ||
params={'code': '1/0', 'globals_dict': {}}, | ||
exp_status=200, exp_body={'emsg': 'ZeroDivisionError: division by zero'}, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
""" | ||
Codejail service URLs. | ||
""" | ||
|
||
from django.urls import path | ||
|
||
from . import views | ||
|
||
urlpatterns = [ | ||
path('api/v0/code-exec', views.code_exec_view_v0, name='code_exec_v0'), | ||
] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
missing a few arguments here
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, fixed. And one of the lines was a lie, too.