From 25d82d228180b7262e5c1cc89f64c8cce20d4f16 Mon Sep 17 00:00:00 2001 From: Ty Tremblay Date: Mon, 23 Nov 2026 22:37:10 -0500 Subject: [PATCH 1/2] Add sandboxed Python runner sidecar and /api/run endpoints --- .github/workflows/ci.yml | 2 + .github/workflows/docker.yml | 87 ++++++- .gitignore | 3 + .hawk/app.json | 1 + docker-compose.dev.yml | 36 +++ runner/Dockerfile | 23 ++ runner/__init__.py | 0 runner/maze_driver.py | 64 +++++ runner/maze_solver.py | 170 +++++++++++++ runner/server.py | 339 +++++++++++++++++++++++++ runner/test_runner.py | 168 ++++++++++++ scripts/deploy-check.mjs | 2 +- scripts/smoke-runner.sh | 65 +++++ server.mjs | 198 ++++++++++++++- site/package-lock.json | 25 ++ site/package.json | 1 + site/src/components/CodeBlock.tsx | 14 +- site/src/components/JavaRunner.tsx | 15 +- site/src/components/MazePlayground.tsx | 121 ++++++++- site/src/lib/lessons.ts | 24 +- site/src/lib/pythonRuntime.ts | 81 ++++++ site/src/routes/LessonView.tsx | 9 +- site/vite.config.ts | 3 + 23 files changed, 1422 insertions(+), 29 deletions(-) create mode 100644 .gitignore create mode 100644 docker-compose.dev.yml create mode 100644 runner/Dockerfile create mode 100644 runner/__init__.py create mode 100644 runner/maze_driver.py create mode 100644 runner/maze_solver.py create mode 100644 runner/server.py create mode 100644 runner/test_runner.py create mode 100755 scripts/smoke-runner.sh create mode 100644 site/src/lib/pythonRuntime.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 74da8bc..2284399 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,3 +27,5 @@ jobs: working-directory: site - name: Validate Hawk app contract run: node scripts/deploy-check.mjs --contract >/dev/null + - name: Test Python runner + run: python3 -m unittest discover -t . -s runner -p "test_*.py" -v diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 3b887c7..c8677ed 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,7 +1,9 @@ name: Publish container # Build and smoke test run alongside CI; only the push waits for it. -# The steps live in FRC2713/hawk_suite/.github/workflows/publish-app.yml. +# The hawk-learn steps live in FRC2713/hawk_suite/.github/workflows/publish-app.yml. +# hawk-learn-runner is built, smoke-tested under hardened sandbox flags, and +# published to ghcr.io/frc2713/hawk-learn-runner on the same sha- tag. on: workflow_dispatch: @@ -15,6 +17,7 @@ permissions: jobs: verify: uses: ./.github/workflows/ci.yml + build: uses: FRC2713/hawk_suite/.github/workflows/publish-app.yml@main permissions: @@ -23,6 +26,7 @@ jobs: with: app: hawk-learn stage: build + push: needs: [verify, build] uses: FRC2713/hawk_suite/.github/workflows/publish-app.yml@main @@ -32,3 +36,84 @@ jobs: with: app: hawk-learn stage: push + + build-runner: + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + env: + CANDIDATE: hawk-learn-runner-candidate:${{ github.sha }} + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - name: Build runner candidate + uses: docker/build-push-action@v6 + with: + context: . + file: runner/Dockerfile + load: true + platforms: linux/amd64 + tags: ${{ env.CANDIDATE }} + build-args: APP_REVISION=${{ github.sha }} + cache-from: type=gha,scope=runner + cache-to: type=gha,mode=max,scope=runner + - name: Smoke test runner candidate + env: + IMAGE: ${{ env.CANDIDATE }} + run: bash scripts/smoke-runner.sh + - name: Save tested runner image + run: docker save "$CANDIDATE" -o "$RUNNER_TEMP/runner-candidate.tar" + - uses: actions/upload-artifact@v4 + with: + name: hawk-learn-runner-candidate + path: ${{ runner.temp }}/runner-candidate.tar + retention-days: 1 + compression-level: 1 + if-no-files-found: error + + push-runner: + needs: [verify, build-runner] + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + packages: write + env: + CANDIDATE: hawk-learn-runner-candidate:${{ github.sha }} + steps: + - uses: actions/download-artifact@v4 + with: + name: hawk-learn-runner-candidate + path: ${{ runner.temp }} + - name: Load tested runner image + run: docker load -i "$RUNNER_TEMP/runner-candidate.tar" + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Publish tested runner image + env: + REVISION: ${{ github.sha }} + run: | + set -euo pipefail + if [[ $GITHUB_REF != refs/heads/main && $GITHUB_REF != refs/tags/v* ]]; then + echo "Refusing to publish from $GITHUB_REF; run from main or a v* tag." >&2 + exit 1 + fi + image="ghcr.io/frc2713/hawk-learn-runner" + docker tag "$CANDIDATE" "$image:sha-$REVISION" + docker push "$image:sha-$REVISION" + digest=$(docker buildx imagetools inspect "$image:sha-$REVISION" --format '{{.Manifest.Digest}}') + [[ $digest =~ ^sha256:[a-f0-9]{64}$ ]] + echo "Published $image@$digest from $REVISION" >> "$GITHUB_STEP_SUMMARY" + if [[ $GITHUB_REF == refs/heads/main ]]; then + aliases=(main latest) + else + aliases=("${GITHUB_REF#refs/tags/v}") + fi + for tag in "${aliases[@]}"; do + docker tag "$CANDIDATE" "$image:$tag" + docker push "$image:$tag" + done diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..41c33c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ + +__pycache__/ +*.pyc diff --git a/.hawk/app.json b/.hawk/app.json index a621427..1693419 100644 --- a/.hawk/app.json +++ b/.hawk/app.json @@ -12,6 +12,7 @@ "optional_env": [ "PORT", "HOST", + "RUNNER_URL", "HAWK_SUITE_ISSUER", "HAWK_SUITE_TRUST_PROXY", "HAWK_SUITE_TEAM_ID" diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..1422a3b --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,36 @@ +services: + hawk-learn: + build: + context: . + dockerfile: Dockerfile + ports: + - "3000:3000" + environment: + APP_URL: http://localhost:3000 + RUNNER_URL: http://hawk-learn-runner:4000 + networks: + - default + - learn_runner + depends_on: + - hawk-learn-runner + + hawk-learn-runner: + build: + context: . + dockerfile: runner/Dockerfile + networks: + - learn_runner + read_only: true + tmpfs: + - /tmp:rw,noexec,nosuid,nodev,size=32m + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + pids_limit: 64 + mem_limit: 256m + cpus: 1.0 + +networks: + learn_runner: + internal: true diff --git a/runner/Dockerfile b/runner/Dockerfile new file mode 100644 index 0000000..d5563d0 --- /dev/null +++ b/runner/Dockerfile @@ -0,0 +1,23 @@ +# syntax=docker/dockerfile:1 +FROM python:3.12-slim + +ARG APP_REVISION=development +ENV APP_REVISION=${APP_REVISION} +LABEL org.opencontainers.image.revision=${APP_REVISION} + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + HOST=0.0.0.0 \ + PORT=4000 + +WORKDIR /opt/runner +COPY runner/maze_solver.py runner/maze_driver.py runner/server.py ./ +RUN chmod 0555 /opt/runner && chmod 0444 /opt/runner/*.py + +USER 65534:65534 +EXPOSE 4000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4000/health', timeout=2)" + +CMD ["python3", "-I", "/opt/runner/server.py"] diff --git a/runner/__init__.py b/runner/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/runner/maze_driver.py b/runner/maze_driver.py new file mode 100644 index 0000000..66c57ce --- /dev/null +++ b/runner/maze_driver.py @@ -0,0 +1,64 @@ +"""Trusted driver executed inside the sandboxed subprocess for maze runs. + +Reads the student's solution.py, runs solve(robot) or solve(maze, robot) with +exact solution.py line numbers in tracebacks, and writes the JSON trail to a +dedicated pipe fd so student stdout never collides with the trail payload. +""" + +from __future__ import annotations + +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from maze_solver import Cell, Direction, GridMaze, Robot # noqa: E402 + + +def main() -> None: + solution_path = sys.argv[1] + grid_path = sys.argv[2] + mode = sys.argv[3] + trail_fd = int(sys.argv[4]) + + with open(grid_path, "r", encoding="utf-8") as f: + grid = json.load(f) + with open(solution_path, "r", encoding="utf-8") as f: + source = f.read() + + maze = GridMaze(grid) + robot = maze.robot() + + namespace: dict[str, object] = { + "__name__": "__main__", + "__file__": "solution.py", + "Direction": Direction, + "Cell": Cell, + "Robot": Robot, + "GridMaze": GridMaze, + } + compiled = compile(source, "solution.py", "exec") + exec(compiled, namespace) + + solve_fn = namespace.get("solve") + if not callable(solve_fn): + raise RuntimeError( + "Expected a `solve(maze, robot)` function in your code." + if mode == "astar" + else "Expected a `solve(robot)` function in your code." + ) + + if mode == "astar": + solve_fn(maze, robot) + else: + solve_fn(robot) + + # Convert [row, col] to [x, y] = [col, row] for the frontend MazePlayground. + trail_xy = [[col, row] for row, col in robot.trail()] + payload = json.dumps(trail_xy).encode("utf-8") + with os.fdopen(trail_fd, "wb") as out: + out.write(payload) + + +if __name__ == "__main__": + main() diff --git a/runner/maze_solver.py b/runner/maze_solver.py new file mode 100644 index 0000000..106250f --- /dev/null +++ b/runner/maze_solver.py @@ -0,0 +1,170 @@ +"""Pure-Python maze solver API matching FRC2713/maze-solver-java CONTRACT.md. + +Wire format: grid[row][col] is a bitmask of OPEN sides: + UP = 1, DOWN = 2, RIGHT = 4, LEFT = 8 +Start is (0, 0); goal is (rows - 1, cols - 1). +""" + +from __future__ import annotations + +from enum import Enum +from typing import Sequence + + +class Direction(Enum): + UP = 1 + DOWN = 2 + RIGHT = 4 + LEFT = 8 + + def bit(self) -> int: + return self.value + + def opposite(self) -> "Direction": + return _OPPOSITE[self] + + def clockwise(self) -> "Direction": + return _CLOCKWISE[self] + + def counter_clockwise(self) -> "Direction": + return _COUNTER_CLOCKWISE[self] + + def delta(self) -> tuple[int, int]: + return _DELTA[self] + + +_OPPOSITE = { + Direction.UP: Direction.DOWN, + Direction.DOWN: Direction.UP, + Direction.LEFT: Direction.RIGHT, + Direction.RIGHT: Direction.LEFT, +} + +_CLOCKWISE = { + Direction.UP: Direction.RIGHT, + Direction.RIGHT: Direction.DOWN, + Direction.DOWN: Direction.LEFT, + Direction.LEFT: Direction.UP, +} + +_COUNTER_CLOCKWISE = { + Direction.UP: Direction.LEFT, + Direction.LEFT: Direction.DOWN, + Direction.DOWN: Direction.RIGHT, + Direction.RIGHT: Direction.UP, +} + +_DELTA = { + Direction.UP: (-1, 0), + Direction.DOWN: (1, 0), + Direction.LEFT: (0, -1), + Direction.RIGHT: (0, 1), +} + + +class Cell: + def __init__(self, row: int, col: int, mask: int, rows: int, cols: int) -> None: + self._row = row + self._col = col + self._mask = mask + self._rows = rows + self._cols = cols + + @property + def row(self) -> int: + return self._row + + @property + def col(self) -> int: + return self._col + + def wall(self, direction: Direction) -> bool: + if not isinstance(direction, Direction): + raise TypeError(f"Expected Direction, got {type(direction).__name__}") + return (self._mask & direction.bit()) == 0 + + def is_start(self) -> bool: + return self._row == 0 and self._col == 0 + + def is_goal(self) -> bool: + return self._row == self._rows - 1 and self._col == self._cols - 1 + + def __repr__(self) -> str: + return f"Cell(row={self._row}, col={self._col})" + + +class Robot: + def __init__(self, maze: "GridMaze") -> None: + self._maze = maze + self._row = 0 + self._col = 0 + self._facing = Direction.RIGHT + self._trail: list[list[int]] = [[0, 0]] + + def read_wall_sensor(self, direction: Direction) -> bool: + return self.cell().wall(direction) + + def drive(self, direction: Direction) -> None: + if self.read_wall_sensor(direction): + return + dr, dc = direction.delta() + nr, nc = self._row + dr, self._col + dc + if 0 <= nr < self._maze.rows and 0 <= nc < self._maze.cols: + self._row = nr + self._col = nc + self._facing = direction + self._trail.append([nr, nc]) + + def facing(self) -> Direction: + return self._facing + + def at_goal(self) -> bool: + return self._maze.is_goal_cell(self._row, self._col) + + @property + def row(self) -> int: + return self._row + + @property + def col(self) -> int: + return self._col + + def cell(self) -> Cell: + return self._maze.cell_at(self._row, self._col) + + def trail(self) -> list[list[int]]: + return [list(pair) for pair in self._trail] + + +class GridMaze: + def __init__(self, grid: Sequence[Sequence[int]]) -> None: + if not grid or not grid[0]: + raise ValueError("Maze grid must be non-empty") + cols = len(grid[0]) + if any(len(row) != cols for row in grid): + raise ValueError("Maze grid must be rectangular") + self._rows = len(grid) + self._cols = cols + self._cells = [ + [Cell(r, c, int(grid[r][c]), self._rows, self._cols) for c in range(cols)] + for r in range(self._rows) + ] + + @property + def rows(self) -> int: + return self._rows + + @property + def cols(self) -> int: + return self._cols + + def cell_at(self, row: int, col: int) -> Cell: + if not (0 <= row < self._rows and 0 <= col < self._cols): + raise IndexError(f"Cell ({row}, {col}) out of bounds for {self._rows}x{self._cols} maze") + return self._cells[row][col] + + def robot(self) -> Robot: + return Robot(self) + + def is_goal_cell(self, row: int, col: int) -> bool: + return row == self._rows - 1 and col == self._cols - 1 diff --git a/runner/server.py b/runner/server.py new file mode 100644 index 0000000..5452954 --- /dev/null +++ b/runner/server.py @@ -0,0 +1,339 @@ +"""Isolated Python execution HTTP service for hawk-learn. + +Runs student Python code in a short-lived subprocess with resource limits, +wall-clock timeout, process-group cleanup, and combined output capping. +Designed to run inside a hardened Docker container on an internal-only network. +""" + +from __future__ import annotations + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +import resource +import selectors +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +from typing import Any + +HOST = os.environ.get("HOST", "0.0.0.0") +PORT = int(os.environ.get("PORT", "4000")) +MAX_BODY_BYTES = 64 * 1024 +MAX_CODE_BYTES = 32 * 1024 +MAX_OUTPUT_BYTES = 32 * 1024 +WALL_TIMEOUT_SECONDS = float(os.environ.get("WALL_TIMEOUT_SECONDS", "3.0")) +CPU_LIMIT_SECONDS = int(os.environ.get("CPU_LIMIT_SECONDS", "2")) +MEMORY_LIMIT_BYTES = int(os.environ.get("MEMORY_LIMIT_MB", "128")) * 1024 * 1024 +MAX_CONCURRENT_RUNS = int(os.environ.get("MAX_CONCURRENT_RUNS", "6")) +MAX_MAZE_DIM = 64 + +RUNNER_DIR = os.path.dirname(os.path.abspath(__file__)) +MAZE_DRIVER = os.path.join(RUNNER_DIR, "maze_driver.py") + +_concurrency = threading.BoundedSemaphore(MAX_CONCURRENT_RUNS) + + +def _apply_child_limits() -> None: + os.setsid() + resource.setrlimit(resource.RLIMIT_CPU, (CPU_LIMIT_SECONDS, CPU_LIMIT_SECONDS)) + resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0)) + if sys.platform == "linux": + resource.setrlimit(resource.RLIMIT_AS, (MEMORY_LIMIT_BYTES, MEMORY_LIMIT_BYTES)) + + +def _kill_process_group(pid: int) -> None: + try: + os.killpg(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def _clean_traceback(stderr: str, tmpdir: str) -> str: + return stderr.replace(tmpdir + os.sep, "") + + +def _validate_maze(maze: Any) -> tuple[list[list[int]], str] | None: + if not isinstance(maze, dict): + return None + grid = maze.get("grid") + mode = maze.get("mode", "wall") + if mode not in ("wall", "astar"): + return None + if not isinstance(grid, list) or not grid or len(grid) > MAX_MAZE_DIM: + return None + cols = None + cleaned: list[list[int]] = [] + for row in grid: + if not isinstance(row, list) or not row or len(row) > MAX_MAZE_DIM: + return None + if cols is None: + cols = len(row) + elif len(row) != cols: + return None + int_row: list[int] = [] + for cell in row: + if not isinstance(cell, int) or isinstance(cell, bool) or not (0 <= cell <= 15): + return None + int_row.append(cell) + cleaned.append(int_row) + return cleaned, mode + + +def execute_python(code: str, maze: tuple[list[list[int]], str] | None = None) -> dict[str, Any]: + tmpdir = tempfile.mkdtemp(prefix="run-", dir="/tmp") + trail_r: int | None = None + trail_w: int | None = None + start = time.monotonic() + + try: + pass_fds: tuple[int, ...] = () + if maze is not None: + grid, mode = maze + solution_path = os.path.join(tmpdir, "solution.py") + grid_path = os.path.join(tmpdir, "grid.json") + with open(solution_path, "w", encoding="utf-8") as f: + f.write(code) + with open(grid_path, "w", encoding="utf-8") as f: + json.dump(grid, f) + trail_r, trail_w = os.pipe() + pass_fds = (trail_w,) + cmd = [ + sys.executable, + "-I", + "-B", + MAZE_DRIVER, + solution_path, + grid_path, + mode, + str(trail_w), + ] + else: + script_path = os.path.join(tmpdir, "main.py") + with open(script_path, "w", encoding="utf-8") as f: + f.write(code) + cmd = [sys.executable, "-I", "-B", script_path] + + proc = subprocess.Popen( + cmd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=tmpdir, + env={"PYTHONUNBUFFERED": "1"}, + pass_fds=pass_fds, + preexec_fn=_apply_child_limits, + ) + + if trail_w is not None: + os.close(trail_w) + trail_w = None + + stdout_buf = bytearray() + stderr_buf = bytearray() + trail_buf = bytearray() + total_output = 0 + timed_out = False + truncated = False + + sel = selectors.DefaultSelector() + assert proc.stdout is not None and proc.stderr is not None + os.set_blocking(proc.stdout.fileno(), False) + os.set_blocking(proc.stderr.fileno(), False) + sel.register(proc.stdout, selectors.EVENT_READ, "stdout") + sel.register(proc.stderr, selectors.EVENT_READ, "stderr") + if trail_r is not None: + os.set_blocking(trail_r, False) + sel.register(trail_r, selectors.EVENT_READ, "trail") + + deadline = start + WALL_TIMEOUT_SECONDS + try: + while sel.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + timed_out = True + _kill_process_group(proc.pid) + break + + events = sel.select(timeout=min(remaining, 0.1)) + for key, _ in events: + tag = key.data + fd = key.fd + try: + chunk = os.read(fd, 4096) + except BlockingIOError: + continue + if not chunk: + sel.unregister(key.fileobj) + continue + if tag == "trail": + if len(trail_buf) < 256 * 1024: + trail_buf.extend(chunk) + continue + target = stdout_buf if tag == "stdout" else stderr_buf + allowed = MAX_OUTPUT_BYTES - total_output + if allowed > 0: + target.extend(chunk[:allowed]) + total_output += min(len(chunk), allowed) + if len(chunk) > allowed: + truncated = True + _kill_process_group(proc.pid) + sel.unregister(key.fileobj) + break + if truncated: + break + finally: + sel.close() + proc.stdout.close() + proc.stderr.close() + + try: + exit_code = proc.wait(timeout=0.5) + except subprocess.TimeoutExpired: + _kill_process_group(proc.pid) + exit_code = proc.wait(timeout=1.0) + + if exit_code == -signal.SIGXCPU: + timed_out = True + + duration_ms = int((time.monotonic() - start) * 1000) + stdout_text = stdout_buf.decode("utf-8", errors="replace") + stderr_text = _clean_traceback(stderr_buf.decode("utf-8", errors="replace"), tmpdir) + + trail: list[list[int]] | None = None + if maze is not None and trail_buf and exit_code == 0 and not timed_out and not truncated: + try: + parsed = json.loads(trail_buf.decode("utf-8")) + if isinstance(parsed, list): + trail = parsed + except (UnicodeDecodeError, json.JSONDecodeError): + trail = None + + ok = exit_code == 0 and not timed_out and not truncated + result: dict[str, Any] = { + "ok": ok, + "stdout": stdout_text, + "stderr": stderr_text, + "exitCode": exit_code, + "timedOut": timed_out, + "truncated": truncated, + "durationMs": duration_ms, + } + if maze is not None: + result["trail"] = trail + return result + finally: + if trail_r is not None: + try: + os.close(trail_r) + except OSError: + pass + if trail_w is not None: + try: + os.close(trail_w) + except OSError: + pass + shutil.rmtree(tmpdir, ignore_errors=True) + + +class RunnerHandler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, format: str, *args: object) -> None: + # Keep container logs quiet for routine health checks and runs. + return + + def _send_json(self, status: int, payload: dict[str, Any]) -> None: + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def do_HEAD(self) -> None: + if self.path == "/health": + self._send_json(200, {"status": "ok"}) + return + self._send_json(404, {"error": "Not found"}) + + def do_GET(self) -> None: + if self.path == "/health": + self._send_json(200, {"status": "ok"}) + return + self._send_json(404, {"error": "Not found"}) + + def do_POST(self) -> None: + if self.path != "/execute": + self._send_json(404, {"error": "Not found"}) + return + + length_header = self.headers.get("Content-Length") + if length_header is None: + self._send_json(411, {"error": "Content-Length required"}) + return + try: + length = int(length_header) + except ValueError: + self._send_json(400, {"error": "Invalid Content-Length"}) + return + if length < 0 or length > MAX_BODY_BYTES: + self._send_json(413, {"error": "Request body too large"}) + return + + raw = self.rfile.read(length) + try: + body = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + self._send_json(400, {"error": "Invalid JSON"}) + return + + if not isinstance(body, dict) or not isinstance(body.get("code"), str): + self._send_json(400, {"error": "Field `code` (string) is required"}) + return + + code = body["code"] + if len(code.encode("utf-8")) > MAX_CODE_BYTES: + self._send_json(413, {"error": "Code exceeds 32 KB limit"}) + return + + maze_spec = None + if "maze" in body and body["maze"] is not None: + maze_spec = _validate_maze(body["maze"]) + if maze_spec is None: + self._send_json(400, {"error": "Invalid maze specification"}) + return + + if not _concurrency.acquire(blocking=True, timeout=5.0): + self._send_json(429, {"error": "Runner busy"}) + return + + try: + outcome = execute_python(code, maze_spec) + finally: + _concurrency.release() + + self._send_json(200, outcome) + + +def main() -> None: + server = ThreadingHTTPServer((HOST, PORT), RunnerHandler) + server.daemon_threads = True + + def _shutdown(_signum: int, _frame: object) -> None: + threading.Thread(target=server.shutdown, daemon=True).start() + + signal.signal(signal.SIGTERM, _shutdown) + signal.signal(signal.SIGINT, _shutdown) + print(f"hawk-learn-runner listening on http://{HOST}:{PORT}", flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/runner/test_runner.py b/runner/test_runner.py new file mode 100644 index 0000000..c847b24 --- /dev/null +++ b/runner/test_runner.py @@ -0,0 +1,168 @@ +"""Unit and sandbox-limit tests for the Python execution runner.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from http.server import ThreadingHTTPServer +import json +import sys +import threading +import unittest +import urllib.error +import urllib.request + +from runner.server import RunnerHandler, execute_python + + +class ExecutePythonTests(unittest.TestCase): + def test_basic_stdout(self) -> None: + res = execute_python('print("hello", 2 + 2)\n') + self.assertTrue(res["ok"]) + self.assertEqual(res["stdout"], "hello 4\n") + self.assertEqual(res["stderr"], "") + self.assertEqual(res["exitCode"], 0) + self.assertFalse(res["timedOut"]) + self.assertFalse(res["truncated"]) + + def test_syntax_error_reports_clean_filename_and_line(self) -> None: + res = execute_python("x = 1\ny = (\n") + self.assertFalse(res["ok"]) + self.assertIn('File "main.py", line 2', res["stderr"]) + self.assertNotIn("/tmp/run-", res["stderr"]) + + def test_runtime_error_reports_exact_line(self) -> None: + res = execute_python("a = 10\nb = 0\nprint(a / b)\n") + self.assertFalse(res["ok"]) + self.assertIn('File "main.py", line 3', res["stderr"]) + self.assertIn("ZeroDivisionError", res["stderr"]) + + def test_infinite_loop_times_out(self) -> None: + res = execute_python("while True:\n pass\n") + self.assertFalse(res["ok"]) + self.assertTrue(res["timedOut"]) + + def test_sleep_hits_wall_timeout(self) -> None: + res = execute_python("import time\ntime.sleep(10)\n") + self.assertFalse(res["ok"]) + self.assertTrue(res["timedOut"]) + + def test_output_flood_truncates_and_kills(self) -> None: + res = execute_python('while True:\n print("x" * 1000)\n') + self.assertFalse(res["ok"]) + self.assertTrue(res["truncated"]) + self.assertLessEqual(len(res["stdout"].encode("utf-8")), 32 * 1024) + + def test_disk_write_blocked_by_fsize_limit(self) -> None: + res = execute_python('with open("evil.txt", "w") as f:\n f.write("data")\n') + self.assertFalse(res["ok"]) + + @unittest.skipUnless(sys.platform == "linux", "RLIMIT_AS enforced on Linux") + def test_memory_bomb_blocked(self) -> None: + res = execute_python("x = bytearray(200_000_000)\n") + self.assertFalse(res["ok"]) + + def test_maze_wall_follower_and_stdout_separation(self) -> None: + # 2x2 maze: + # (0,0) open RIGHT(4) -> (0,1) open LEFT(8)|DOWN(2) -> (1,1) open UP(1) + # (1,0) closed (0) + grid = [ + [4, 8 | 2], + [0, 1], + ] + code = ( + "def solve(robot):\n" + ' print("starting")\n' + " robot.drive(Direction.UP) # wall: no-op\n" + " robot.drive(Direction.RIGHT)\n" + " robot.drive(Direction.DOWN)\n" + ' print("at goal:", robot.at_goal())\n' + ) + res = execute_python(code, maze=(grid, "wall")) + self.assertTrue(res["ok"], res["stderr"]) + self.assertEqual(res["stdout"], "starting\nat goal: True\n") + # Trail is [x, y] = [col, row] + self.assertEqual(res["trail"], [[0, 0], [1, 0], [1, 1]]) + + def test_maze_astar_receives_maze_and_robot(self) -> None: + grid = [ + [4, 8 | 2], + [0, 1], + ] + code = ( + "def solve(maze, robot):\n" + " assert maze.rows == 2 and maze.cols == 2\n" + " assert not maze.cell_at(0, 0).wall(Direction.RIGHT)\n" + " assert maze.cell_at(0, 0).wall(Direction.DOWN)\n" + " robot.drive(Direction.RIGHT)\n" + " robot.drive(Direction.DOWN)\n" + ) + res = execute_python(code, maze=(grid, "astar")) + self.assertTrue(res["ok"], res["stderr"]) + self.assertEqual(res["trail"], [[0, 0], [1, 0], [1, 1]]) + + def test_maze_error_reports_solution_line(self) -> None: + grid = [[4, 8]] + code = "def solve(robot):\n x = 1 / 0\n" + res = execute_python(code, maze=(grid, "wall")) + self.assertFalse(res["ok"]) + self.assertIn('File "solution.py", line 2', res["stderr"]) + self.assertIsNone(res["trail"]) + + +class RunnerHttpTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.server = ThreadingHTTPServer(("127.0.0.1", 0), RunnerHandler) + cls.port = cls.server.server_address[1] + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + + @classmethod + def tearDownClass(cls) -> None: + cls.server.shutdown() + cls.server.server_close() + + def _post(self, path: str, payload: dict) -> tuple[int, dict]: + data = json.dumps(payload).encode("utf-8") + req = urllib.request.Request( + f"http://127.0.0.1:{self.port}{path}", + data=data, + headers={"Content-Type": "application/json"}, + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=10) as resp: + return resp.status, json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as err: + with err: + return err.code, json.loads(err.read().decode("utf-8")) + + def test_health(self) -> None: + with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/health", timeout=5) as resp: + self.assertEqual(resp.status, 200) + self.assertEqual(json.loads(resp.read().decode("utf-8")), {"status": "ok"}) + + def test_rejects_oversized_code(self) -> None: + status, body = self._post("/execute", {"code": "a" * (33 * 1024)}) + self.assertEqual(status, 413) + self.assertIn("error", body) + + def test_rejects_invalid_maze_grid(self) -> None: + status, _ = self._post("/execute", {"code": "pass", "maze": {"grid": [[1, 2], [3]], "mode": "wall"}}) + self.assertEqual(status, 400) + + def test_concurrent_burst(self) -> None: + def run_one(i: int) -> tuple[int, dict]: + return self._post("/execute", {"code": f"print({i} * 2)\n"}) + + with ThreadPoolExecutor(max_workers=15) as pool: + results = list(pool.map(run_one, range(15))) + + for i, (status, body) in enumerate(results): + self.assertEqual(status, 200) + self.assertTrue(body["ok"]) + self.assertEqual(body["stdout"], f"{i * 2}\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/deploy-check.mjs b/scripts/deploy-check.mjs index 4748052..ab61cb4 100644 --- a/scripts/deploy-check.mjs +++ b/scripts/deploy-check.mjs @@ -13,7 +13,7 @@ if (process.argv.includes("--contract")) { process.exit(1); } try { - for (const name of ["APP_URL", "HAWK_SUITE_ISSUER"]) { + for (const name of ["APP_URL", "HAWK_SUITE_ISSUER", "RUNNER_URL"]) { if (process.env[name]) { const url = new URL(process.env[name]); if (!["http:", "https:"].includes(url.protocol)) throw new Error(); diff --git a/scripts/smoke-runner.sh b/scripts/smoke-runner.sh new file mode 100755 index 0000000..9afe415 --- /dev/null +++ b/scripts/smoke-runner.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Smoke-test the candidate hawk-learn-runner container image under hardened +# sandbox flags with no network access. +set -euo pipefail + +name="hawk-runner-smoke-${RANDOM}-${RANDOM}" +# shellcheck disable=SC2329 +cleanup() { docker rm -fv "$name" >/dev/null 2>&1 || true; } +trap cleanup EXIT + +docker run -d \ + --name "$name" \ + --network none \ + --read-only \ + --tmpfs /tmp:rw,noexec,nosuid,nodev,size=32m \ + --cap-drop ALL \ + --security-opt no-new-privileges:true \ + --pids-limit 64 \ + --memory 256m \ + "$IMAGE" >/dev/null + +for _attempt in $(seq 1 30); do + state=$(docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$name") + if [[ $state == 'running healthy' ]]; then + docker exec "$name" python3 -c ' +import json, urllib.request + +def post(payload): + req = urllib.request.Request( + "http://127.0.0.1:4000/execute", + data=json.dumps(payload).encode("utf-8"), + headers={"Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=10) as resp: + assert resp.status == 200 + return json.loads(resp.read().decode("utf-8")) + +r = post({"code": "print(6 * 7)"}) +assert r["ok"] and r["stdout"] == "42\n", r + +r = post({"code": "x = bytearray(200_000_000)"}) +assert not r["ok"], r + +r = post({"code": "with open(\"/tmp/evil\", \"w\") as f:\n f.write(\"x\")\n"}) +assert not r["ok"], r + +r = post({"code": "import urllib.request; urllib.request.urlopen(\"https://example.com\", timeout=2)"}) +assert not r["ok"], r + +r = post({ + "code": "def solve(robot):\n robot.drive(Direction.RIGHT)\n", + "maze": {"grid": [[4, 8]], "mode": "wall"}, +}) +assert r["ok"] and r["trail"] == [[0, 0], [1, 0]], r +' + exit 0 + fi + if [[ $state == exited* || $state == dead* ]]; then break; fi + sleep 1 +done + +docker logs --tail=40 "$name" +echo 'Candidate runner image failed readiness' >&2 +exit 1 diff --git a/server.mjs b/server.mjs index 3e77ae0..1231082 100644 --- a/server.mjs +++ b/server.mjs @@ -8,6 +8,16 @@ const distDir = path.resolve(process.env.DIST_DIR || path.join(rootDir, 'site', const host = process.env.HOST || '0.0.0.0' const port = Number(process.env.PORT || 3000) const revision = process.env.APP_REVISION || 'development' +const runnerUrl = (process.env.RUNNER_URL || '').replace(/\/+$/, '') +const trustProxy = process.env.HAWK_SUITE_TRUST_PROXY === 'true' +const expectedTeamId = process.env.HAWK_SUITE_TEAM_ID || '' + +const MAX_BODY_BYTES = 64 * 1024 +const RATE_LIMIT_BURST = 5 +const RATE_LIMIT_REFILL_PER_SEC = 0.5 // 30 runs/minute per user +const MAX_CONCURRENT_RUNS = 4 +const MAX_QUEUED_RUNS = 16 +const RUNNER_FETCH_TIMEOUT_MS = 10_000 const MIME_TYPES = { '.css': 'text/css; charset=utf-8', @@ -29,6 +39,173 @@ const MIME_TYPES = { '.woff2': 'font/woff2', } +// Per-user token bucket for /api/run*. +const buckets = new Map() + +function takeRateLimitToken(userKey) { + const now = Date.now() + let bucket = buckets.get(userKey) + if (!bucket) { + bucket = { tokens: RATE_LIMIT_BURST, updatedAt: now } + buckets.set(userKey, bucket) + } else { + const elapsedSec = (now - bucket.updatedAt) / 1000 + bucket.tokens = Math.min(RATE_LIMIT_BURST, bucket.tokens + elapsedSec * RATE_LIMIT_REFILL_PER_SEC) + bucket.updatedAt = now + } + if (bucket.tokens < 1) { + const retryAfter = Math.ceil((1 - bucket.tokens) / RATE_LIMIT_REFILL_PER_SEC) + return { allowed: false, retryAfter } + } + bucket.tokens -= 1 + return { allowed: true, retryAfter: 0 } +} + +// Bounded FIFO semaphore for runner requests. +let activeRuns = 0 +const runWaiters = [] + +function acquireRunSlot() { + if (activeRuns < MAX_CONCURRENT_RUNS) { + activeRuns += 1 + return Promise.resolve(true) + } + if (runWaiters.length >= MAX_QUEUED_RUNS) { + return Promise.resolve(false) + } + return new Promise((resolve) => { + runWaiters.push(() => { + activeRuns += 1 + resolve(true) + }) + }) +} + +function releaseRunSlot() { + activeRuns -= 1 + const next = runWaiters.shift() + if (next) next() +} + +function sendJson(res, status, payload, extraHeaders = {}) { + const body = JSON.stringify(payload) + res.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': Buffer.byteLength(body), + 'Cache-Control': 'no-store', + ...extraHeaders, + }) + res.end(body) +} + +function readJsonBody(req) { + return new Promise((resolve, reject) => { + const chunks = [] + let total = 0 + req.on('data', (chunk) => { + total += chunk.length + if (total > MAX_BODY_BYTES) { + reject(Object.assign(new Error('Request body too large'), { status: 413 })) + req.destroy() + return + } + chunks.push(chunk) + }) + req.on('end', () => { + try { + const text = Buffer.concat(chunks).toString('utf8') + resolve(JSON.parse(text)) + } catch { + reject(Object.assign(new Error('Invalid JSON'), { status: 400 })) + } + }) + req.on('error', () => { + reject(Object.assign(new Error('Failed to read request body'), { status: 400 })) + }) + }) +} + +function resolveUserKey(req) { + if (!trustProxy) return 'local-dev' + const user = String(req.headers['x-hawk-slack-user'] || '').trim() + const team = String(req.headers['x-hawk-slack-team'] || '').trim() + if (!user) return null + if (expectedTeamId && team !== expectedTeamId) return null + return `${team}:${user}` +} + +async function handleRunApi(req, res, isMaze) { + const userKey = resolveUserKey(req) + if (!userKey) { + sendJson(res, 401, { error: 'Sign in with Hawk Suite to run code.' }) + return + } + + if (!runnerUrl) { + sendJson(res, 503, { error: 'Python code runner is not configured.' }) + return + } + + let body + try { + body = await readJsonBody(req) + } catch (err) { + sendJson(res, err.status || 400, { error: err.message || 'Bad request' }) + return + } + + if (!body || typeof body !== 'object' || typeof body.code !== 'string') { + sendJson(res, 400, { error: 'Field `code` (string) is required.' }) + return + } + + const payload = { code: body.code } + if (isMaze) { + if (!Array.isArray(body.grid) || (body.mode !== 'wall' && body.mode !== 'astar')) { + sendJson(res, 400, { error: 'Fields `grid` (array) and `mode` ("wall" | "astar") are required.' }) + return + } + payload.maze = { grid: body.grid, mode: body.mode } + } + + const rate = takeRateLimitToken(userKey) + if (!rate.allowed) { + sendJson( + res, + 429, + { error: 'Too many runs. Wait a moment and try again.' }, + { 'Retry-After': String(rate.retryAfter) }, + ) + return + } + + const acquired = await acquireRunSlot() + if (!acquired) { + sendJson(res, 429, { error: 'Runner is busy. Try again in a moment.' }, { 'Retry-After': '2' }) + return + } + + try { + const upstream = await fetch(`${runnerUrl}/execute`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(RUNNER_FETCH_TIMEOUT_MS), + }) + const text = await upstream.text() + res.writeHead(upstream.status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': Buffer.byteLength(text), + 'Cache-Control': 'no-store', + }) + res.end(text) + } catch { + sendJson(res, 502, { error: 'Code runner is temporarily unavailable.' }) + } finally { + releaseRunSlot() + } +} + function sendFile(res, filePath, method, cacheControl) { const stat = statSync(filePath) const ext = path.extname(filePath).toLowerCase() @@ -56,11 +233,6 @@ function tryFile(filePath) { const server = http.createServer((req, res) => { const method = req.method || 'GET' - if (method !== 'GET' && method !== 'HEAD') { - res.writeHead(405, { Allow: 'GET, HEAD', 'Content-Type': 'text/plain; charset=utf-8' }) - res.end('Method Not Allowed') - return - } let pathname try { @@ -71,6 +243,22 @@ const server = http.createServer((req, res) => { return } + if (pathname === '/api/run' || pathname === '/api/run/maze') { + if (method !== 'POST') { + res.writeHead(405, { Allow: 'POST', 'Content-Type': 'text/plain; charset=utf-8' }) + res.end('Method Not Allowed') + return + } + void handleRunApi(req, res, pathname === '/api/run/maze') + return + } + + if (method !== 'GET' && method !== 'HEAD') { + res.writeHead(405, { Allow: 'GET, HEAD', 'Content-Type': 'text/plain; charset=utf-8' }) + res.end('Method Not Allowed') + return + } + if (pathname === '/health') { const body = JSON.stringify({ status: 'ok', revision }) res.writeHead(200, { diff --git a/site/package-lock.json b/site/package-lock.json index bbf0ca6..b55490b 100644 --- a/site/package-lock.json +++ b/site/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "dependencies": { "@codemirror/lang-java": "^6.0.2", + "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@radix-ui/react-dialog": "^1.1.18", "@radix-ui/react-separator": "^1.1.11", @@ -85,6 +86,19 @@ "@lezer/java": "^1.0.0" } }, + "node_modules/@codemirror/lang-python": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", + "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==", + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.3.2", + "@codemirror/language": "^6.8.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.2.1", + "@lezer/python": "^1.1.4" + } + }, "node_modules/@codemirror/language": { "version": "6.12.4", "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz", @@ -311,6 +325,17 @@ "@lezer/common": "^1.0.0" } }, + "node_modules/@lezer/python": { + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.19.tgz", + "integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, "node_modules/@marijn/find-cluster-break": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz", diff --git a/site/package.json b/site/package.json index 6c47cc3..562008b 100644 --- a/site/package.json +++ b/site/package.json @@ -12,6 +12,7 @@ }, "dependencies": { "@codemirror/lang-java": "^6.0.2", + "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@radix-ui/react-dialog": "^1.1.18", "@radix-ui/react-separator": "^1.1.11", diff --git a/site/src/components/CodeBlock.tsx b/site/src/components/CodeBlock.tsx index 9c1a2d4..c3aca09 100644 --- a/site/src/components/CodeBlock.tsx +++ b/site/src/components/CodeBlock.tsx @@ -1,21 +1,25 @@ import { useMemo } from 'react' import CodeMirror, { EditorView } from '@uiw/react-codemirror' import { java } from '@codemirror/lang-java' +import { python } from '@codemirror/lang-python' import { oneDark } from '@codemirror/theme-one-dark' import { editorTheme, usePrefersDark } from '@/lib/editorTheme' // A read-only, syntax-highlighted rendering of a fenced code block in the prose. -// Java blocks get language highlighting + line numbers; other fences (e.g. -// ```text``` output samples) get the same themed surface without either. +// Python and Java blocks get language highlighting + line numbers; other fences +// (e.g. ```text``` output samples) get the same themed surface without either. export function CodeBlock({ code, language }: { code: string; language?: string }) { const dark = usePrefersDark() const isJava = language === 'java' + const isPython = language === 'python' + const isCode = isJava || isPython const extensions = useMemo(() => { const ext = [editorTheme, EditorView.lineWrapping] - if (isJava) ext.unshift(java()) + if (isPython) ext.unshift(python()) + else if (isJava) ext.unshift(java()) return ext - }, [isJava]) + }, [isJava, isPython]) return (
@@ -25,7 +29,7 @@ export function CodeBlock({ code, language }: { code: string; language?: string extensions={extensions} theme={dark ? oneDark : 'light'} basicSetup={{ - lineNumbers: isJava, + lineNumbers: isCode, foldGutter: false, highlightActiveLine: false, highlightActiveLineGutter: false, diff --git a/site/src/components/JavaRunner.tsx b/site/src/components/JavaRunner.tsx index 4fc9c0a..05ac802 100644 --- a/site/src/components/JavaRunner.tsx +++ b/site/src/components/JavaRunner.tsx @@ -1,8 +1,11 @@ import { useMemo, useState } from 'react' import CodeMirror, { EditorView } from '@uiw/react-codemirror' import { java } from '@codemirror/lang-java' +import { python } from '@codemirror/lang-python' import { oneDark } from '@codemirror/theme-one-dark' import { getJavaRuntimeStatus, runJava } from '@/lib/javaRuntime' +import { runPython } from '@/lib/pythonRuntime' +import type { RunnableLanguage } from '@/lib/lessons' import { editorTheme, usePrefersDark } from '@/lib/editorTheme' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' @@ -10,9 +13,11 @@ import { cn } from '@/lib/utils' export function JavaRunner({ initialCode, storageKey, + language = 'java', }: { initialCode: string storageKey: string + language?: RunnableLanguage }) { const originalCode = initialCode.trimEnd() const [code, setCode] = useState(() => localStorage.getItem(storageKey) ?? originalCode) @@ -21,13 +26,17 @@ export function JavaRunner({ const [running, setRunning] = useState(false) const dark = usePrefersDark() - const extensions = useMemo(() => [java(), editorTheme, EditorView.lineWrapping], []) + const extensions = useMemo( + () => [language === 'python' ? python() : java(), editorTheme, EditorView.lineWrapping], + [language], + ) const handleRun = async () => { - const label = getJavaRuntimeStatus() === 'ready' ? 'Running…' : 'Loading Java…' + const label = + language === 'python' || getJavaRuntimeStatus() === 'ready' ? 'Running…' : 'Loading Java…' setRunning(true) setOutput(label) - const result = await runJava(code) + const result = language === 'python' ? await runPython(code) : await runJava(code) setOk(result.ok) setOutput(result.output || '(no output)') setRunning(false) diff --git a/site/src/components/MazePlayground.tsx b/site/src/components/MazePlayground.tsx index e84b586..565763b 100644 --- a/site/src/components/MazePlayground.tsx +++ b/site/src/components/MazePlayground.tsx @@ -1,8 +1,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import CodeMirror, { EditorView } from '@uiw/react-codemirror' import { java } from '@codemirror/lang-java' +import { python } from '@codemirror/lang-python' import { oneDark } from '@codemirror/theme-one-dark' import { getJavaRuntimeStatus, runJava } from '@/lib/javaRuntime' +import { runPythonMaze } from '@/lib/pythonRuntime' +import type { SolverMode as LessonSolverMode } from '@/lib/lessons' import { editorTheme, usePrefersDark } from '@/lib/editorTheme' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' @@ -113,7 +116,7 @@ const NAIVE_ORDER = [0, 3, 2, 1] // The three canned JS-animated demos, plus `java` — the student writes a real // solver run through the maze round-trip (see lib/mazeHarness.ts). type CannedMode = 'random' | 'naive' | 'wall' -export type SolverMode = CannedMode | 'java' | 'astar' +export type SolverMode = LessonSolverMode const SOLVER_LABEL: Record = { random: 'Move at random', @@ -227,6 +230,80 @@ Direction step(int[] from, int[] to) { return Direction.RIGHT; }` +const DEFAULT_PYTHON_SOLVE = `# Drive the robot from start (green) to goal (red). Your robot can: +# robot.read_wall_sensor(Direction.UP/DOWN/LEFT/RIGHT) — is that side a wall? +# robot.drive(Direction.UP/DOWN/LEFT/RIGHT) — move one cell that way +# robot.facing() — the way it last drove +# robot.at_goal(), robot.row, robot.col +# +# This starter is the "keep your right hand on the wall" follower. +def solve(robot): + for _ in range(1000): + if robot.at_goal(): + break + ahead = robot.facing() + order = [ + ahead.clockwise(), + ahead, + ahead.counter_clockwise(), + ahead.opposite(), + ] + for direction in order: + if not robot.read_wall_sensor(direction): + robot.drive(direction) + break` + +const DEFAULT_PYTHON_ASTAR_SOLVE = `import heapq + +# A* finds the shortest path, then drives it. You get the whole map: +# maze.rows, maze.cols — the grid size +# maze.cell_at(r, c).wall(direction) — is there a wall on that side? +# robot.drive(Direction.UP/DOWN/LEFT/RIGHT) — move the robot one cell +def solve(maze, robot): + rows, cols = maze.rows, maze.cols + goal = (rows - 1, cols - 1) + + def heuristic(r, c): + return abs(r - goal[0]) + abs(c - goal[1]) + + g = {(0, 0): 0} + came_from = {} + frontier = [(heuristic(0, 0), 0, 0)] + + while frontier: + _, r, c = heapq.heappop(frontier) + if (r, c) == goal: + break + cell = maze.cell_at(r, c) + for direction in Direction: + if cell.wall(direction): + continue + dr, dc = direction.delta() + nr, nc = r + dr, c + dc + tentative = g[(r, c)] + 1 + if tentative < g.get((nr, nc), float("inf")): + g[(nr, nc)] = tentative + came_from[(nr, nc)] = (r, c) + heapq.heappush(frontier, (tentative + heuristic(nr, nc), nr, nc)) + + path = [] + cur = goal + while cur in came_from: + path.append(cur) + cur = came_from[cur] + path.append((0, 0)) + path.reverse() + + for (r1, c1), (r2, c2) in zip(path, path[1:]): + if r2 < r1: + robot.drive(Direction.UP) + elif r2 > r1: + robot.drive(Direction.DOWN) + elif c2 < c1: + robot.drive(Direction.LEFT) + else: + robot.drive(Direction.RIGHT)` + export function MazePlayground({ solver = null }: { solver?: SolverMode | null }) { const [grid, setGrid] = useState(() => generateMaze(SIZE)) const [robot, setRobot] = useState<[number, number]>(START) @@ -240,14 +317,26 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } // the harness it runs through (it's handed the whole Maze, not just a Robot). const isJava = solver === 'java' const isAstar = solver === 'astar' - const isEditable = isJava || isAstar - const harnessMode = isAstar ? 'astar' : 'wall' - const starterCode = isAstar ? DEFAULT_ASTAR_SOLVE : DEFAULT_JAVA_SOLVE + const isPython = solver === 'python' + const isPythonAstar = solver === 'python-astar' + const isPythonMode = isPython || isPythonAstar + const isEditable = isJava || isAstar || isPythonMode + const harnessMode = isAstar || isPythonAstar ? 'astar' : 'wall' + const starterCode = isPythonAstar + ? DEFAULT_PYTHON_ASTAR_SOLVE + : isPython + ? DEFAULT_PYTHON_SOLVE + : isAstar + ? DEFAULT_ASTAR_SOLVE + : DEFAULT_JAVA_SOLVE const [code, setCode] = useState(starterCode) const [javaOutput, setJavaOutput] = useState(null) const [javaOk, setJavaOk] = useState(true) const dark = usePrefersDark() - const editorExtensions = useMemo(() => [java(), editorTheme, EditorView.lineWrapping], []) + const editorExtensions = useMemo( + () => [isPythonMode ? python() : java(), editorTheme, EditorView.lineWrapping], + [isPythonMode], + ) const copyForJava = () => { const java = serializeToJava(grid) @@ -373,6 +462,26 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } setStuck(false) setRobot(START) setJavaOk(true) + if (isPythonMode) { + setJavaOutput('Running…') + const result = await runPythonMaze(code, grid, harnessMode) + if (!result.ok) { + setJavaOk(false) + setJavaOutput(result.output || '(error)') + return + } + if (!result.trail) { + setJavaOk(false) + setJavaOutput( + 'Ran, but produced no Maze Trail. Make sure solve(robot) moves the robot.', + ) + return + } + setJavaOk(true) + setJavaOutput(result.output || null) + animateTrail(result.trail) + return + } setJavaOutput(getJavaRuntimeStatus() === 'ready' ? 'Running…' : 'Loading Java…') const harness = buildMazeHarness(grid, code, harnessMode) const result = await runJava(harness) @@ -399,7 +508,7 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } setJavaOk(true) setJavaOutput(debug || null) animateTrail(trail.cells) - }, [grid, code, harnessMode, stopSolver, animateTrail]) + }, [grid, code, harnessMode, isPythonMode, stopSolver, animateTrail]) const generate = () => { stopSolver() diff --git a/site/src/lib/lessons.ts b/site/src/lib/lessons.ts index 877c13d..28e0316 100644 --- a/site/src/lib/lessons.ts +++ b/site/src/lib/lessons.ts @@ -121,9 +121,25 @@ export function nextLesson(slug: string): Lesson | undefined { return index === -1 ? undefined : lessons[index + 1] } -// Drives the playground panel: a page's first ```java fence is what gets -// loaded into it. Pages can still show other code samples in their prose; +export type RunnableLanguage = 'python' | 'java' + +export interface RunnableSnippet { + language: RunnableLanguage + code: string +} + +// Drives the playground panel: a page's first ```python or ```java fence is +// what gets loaded into it. Pages can still show other code samples in prose; // only this one is treated as "the" runnable snippet for the page. +export function firstRunnableSnippet(markdown: string): RunnableSnippet | null { + const match = /```(python|java)\r?\n([\s\S]*?)```/.exec(markdown) + if (!match) return null + return { + language: match[1] as RunnableLanguage, + code: match[2].trimEnd(), + } +} + export function firstJavaSnippet(markdown: string): string | null { const match = /```java\r?\n([\s\S]*?)```/.exec(markdown) return match ? match[1].trimEnd() : null @@ -167,11 +183,11 @@ export function hasMaze(markdown: string): boolean { // writes their own reactive solver in real Java, run through the maze round-trip. // The fifth, `astar`, is the same editor but its harness also hands the student // the whole Maze so they can plan a global shortest path (the A* lesson). -export type SolverMode = 'random' | 'naive' | 'wall' | 'java' | 'astar' +export type SolverMode = 'random' | 'naive' | 'wall' | 'java' | 'astar' | 'python' | 'python-astar' export function mazeSolver(markdown: string): SolverMode | null { const match = MAZE_FENCE.exec(markdown) if (!match) return null - const m = /solver:\s*(random|naive|wall|java|astar)/.exec(match[1]) + const m = /solver:\s*(python-astar|python|random|naive|wall|java|astar)/.exec(match[1]) return m ? (m[1] as SolverMode) : null } diff --git a/site/src/lib/pythonRuntime.ts b/site/src/lib/pythonRuntime.ts new file mode 100644 index 0000000..992cf3b --- /dev/null +++ b/site/src/lib/pythonRuntime.ts @@ -0,0 +1,81 @@ +import type { RunOutcome } from './javaRuntime' + +export interface RunnerResponse { + ok: boolean + stdout: string + stderr: string + exitCode: number | null + timedOut: boolean + truncated: boolean + durationMs: number + trail?: [number, number][] | null + error?: string +} + +export interface MazeRunOutcome extends RunOutcome { + trail: [number, number][] | null +} + +function formatRunnerOutput(data: RunnerResponse): string { + const parts: string[] = [] + if (data.stdout) parts.push(data.stdout.replace(/\n$/, '')) + if (data.stderr) parts.push(data.stderr.replace(/\n$/, '')) + if (data.timedOut) parts.push('Timed out after 3 seconds (check for an infinite loop).') + if (data.truncated) parts.push('Output exceeded 32 KB limit and was stopped.') + return parts.join('\n').trim() +} + +async function postRunner(path: string, body: unknown): Promise<{ ok: boolean; data?: RunnerResponse; error?: string }> { + let res: Response + try { + res = await fetch(path, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) + } catch { + return { ok: false, error: 'Could not reach the code runner.' } + } + + if (res.redirected || res.status === 401 || res.status === 403) { + return { ok: false, error: 'Session expired. Reload the page to sign in again.' } + } + + const contentType = res.headers.get('content-type') || '' + if (!contentType.includes('application/json')) { + return { ok: false, error: 'Session expired or runner returned an unexpected response. Reload and try again.' } + } + + const data = (await res.json()) as RunnerResponse + if (!res.ok) { + return { ok: false, error: data.error || `Runner error (HTTP ${res.status}).` } + } + return { ok: true, data } +} + +export async function runPython(code: string): Promise { + const result = await postRunner('/api/run', { code }) + if (!result.ok || !result.data) { + return { ok: false, output: result.error ?? 'Unknown runner error.' } + } + return { + ok: result.data.ok, + output: formatRunnerOutput(result.data), + } +} + +export async function runPythonMaze( + code: string, + grid: number[][], + mode: 'wall' | 'astar', +): Promise { + const result = await postRunner('/api/run/maze', { code, grid, mode }) + if (!result.ok || !result.data) { + return { ok: false, output: result.error ?? 'Unknown runner error.', trail: null } + } + return { + ok: result.data.ok, + output: formatRunnerOutput(result.data), + trail: Array.isArray(result.data.trail) ? result.data.trail : null, + } +} diff --git a/site/src/routes/LessonView.tsx b/site/src/routes/LessonView.tsx index ff639f6..ba81418 100644 --- a/site/src/routes/LessonView.tsx +++ b/site/src/routes/LessonView.tsx @@ -5,7 +5,7 @@ import type { Components } from 'react-markdown' import remarkGfm from 'remark-gfm' import { blocksPreset, - firstJavaSnippet, + firstRunnableSnippet, getLesson, hasMaze, mazeSolver, @@ -93,8 +93,8 @@ export function LessonView() { const maze = hasMaze(currentPage.markdown) const prose = preset || maze ? stripBlocksFence(currentPage.markdown) : currentPage.markdown - const javaSnippet = firstJavaSnippet(currentPage.markdown) - const hasPlayground = preset != null || maze || javaSnippet != null + const snippet = firstRunnableSnippet(currentPage.markdown) + const hasPlayground = preset != null || maze || snippet != null const goTo = (index: number) => navigate(`/lesson/${lesson.slug}/${index + 1}`) @@ -141,7 +141,8 @@ export function LessonView() { <> diff --git a/site/vite.config.ts b/site/vite.config.ts index 71b56cd..292921d 100644 --- a/site/vite.config.ts +++ b/site/vite.config.ts @@ -14,6 +14,9 @@ export default defineConfig({ }, server: { port: process.env.PORT ? Number(process.env.PORT) : 5173, + proxy: { + '/api': 'http://127.0.0.1:3000', + }, fs: { // allow the dev server to read lesson content from ../lessons allow: ['..'], From 775981b9c7eff02992f80728d024b9e760e2dae5 Mon Sep 17 00:00:00 2001 From: Ty Tremblay Date: Mon, 23 Nov 2026 22:42:37 -0500 Subject: [PATCH 2/2] Use soft/hard RLIMIT_CPU split so Linux raises SIGXCPU on timeout --- runner/server.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runner/server.py b/runner/server.py index 5452954..a325145 100644 --- a/runner/server.py +++ b/runner/server.py @@ -40,7 +40,9 @@ def _apply_child_limits() -> None: os.setsid() - resource.setrlimit(resource.RLIMIT_CPU, (CPU_LIMIT_SECONDS, CPU_LIMIT_SECONDS)) + # Soft limit triggers SIGXCPU on both Linux and macOS; hard limit (+1s) + # enforces SIGKILL if a child ignores SIGXCPU. + resource.setrlimit(resource.RLIMIT_CPU, (CPU_LIMIT_SECONDS, CPU_LIMIT_SECONDS + 1)) resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0)) if sys.platform == "linux": resource.setrlimit(resource.RLIMIT_AS, (MEMORY_LIMIT_BYTES, MEMORY_LIMIT_BYTES))