steveyehtw commited on
Commit
4415019
·
1 Parent(s): 81f4613

Restore HF demo execution with explicit resource-limited process mode

Browse files
Files changed (4) hide show
  1. Dockerfile +1 -0
  2. SECURITY.md +3 -2
  3. server.py +50 -7
  4. tests/test_security.py +23 -0
Dockerfile CHANGED
@@ -36,6 +36,7 @@ ENV PYTHONUNBUFFERED=1 \
36
  SDL_AUDIODRIVER=dummy \
37
  PORT=7860 \
38
  MAX_CONCURRENT_RUNNERS=3 \
 
39
  RUNNER_STARTS_PER_IP_PER_HOUR=120 \
40
  RUNNER_START_COOLDOWN_SEC=0.75 \
41
  SESSION_TIMEOUT_SEC=900 \
 
36
  SDL_AUDIODRIVER=dummy \
37
  PORT=7860 \
38
  MAX_CONCURRENT_RUNNERS=3 \
39
+ RUNNER_ISOLATION_MODE=process \
40
  RUNNER_STARTS_PER_IP_PER_HOUR=120 \
41
  RUNNER_START_COOLDOWN_SEC=0.75 \
42
  SESSION_TIMEOUT_SEC=900 \
SECURITY.md CHANGED
@@ -3,8 +3,9 @@
3
  ## Student Python execution
4
 
5
  - Docker installs Bubblewrap and `prlimit`; the app runs as the unprivileged `telearn` account.
6
- - Each public Python run gets a copied, size-limited project workspace, Linux user/PID/network namespaces, read-only system mounts, and CPU/address-space/file/process limits. Runner environments are cleared and no network is exposed.
7
- - The runner fails closed when the host does not support the required Linux sandbox. Confirm namespace creation in the Hugging Face Space after deployment; do not restore a direct, unsandboxed runner as a workaround.
 
8
  - Uvicorn caps WebSocket frames at 1 MiB. Classroom sockets also have per-IP handshake and per-student message budgets; saved checkpoints/submissions have per-hour limits, cooldowns, a per-course quota, and a rolling retention cap.
9
 
10
  ## Classroom storage
 
3
  ## Student Python execution
4
 
5
  - Docker installs Bubblewrap and `prlimit`; the app runs as the unprivileged `telearn` account.
6
+ - Each public Python run gets a copied, size-limited project workspace and CPU/address-space/file/process limits. Child environments use an allowlist and do not inherit application tokens or admin credentials.
7
+ - `RUNNER_ISOLATION_MODE=sandbox` (the source default) additionally requires Linux user/PID/network namespaces and read-only system mounts, and fails closed if the host blocks namespace creation.
8
+ - At the owner's request, the Docker image explicitly sets `RUNNER_ISOLATION_MODE=process` to restore Python demos on Hugging Face, whose current host rejects unprivileged namespace creation. This mode runs a separate, resource-limited process as `telearn`, but provides **no filesystem, network, or same-user process isolation**. Environment filtering and temporary project copies are not a security sandbox. Set the mode back to `sandbox` on a compatible execution host.
9
  - Uvicorn caps WebSocket frames at 1 MiB. Classroom sockets also have per-IP handshake and per-student message budgets; saved checkpoints/submissions have per-hour limits, cooldowns, a per-course quota, and a rolling retention cap.
10
 
11
  ## Classroom storage
server.py CHANGED
@@ -66,6 +66,7 @@ ENABLE_HSTS = os.environ.get("ENABLE_HSTS", "false").lower() in {"1", "true", "y
66
  HSTS_MAX_AGE_SEC = max(0, int(os.environ.get("HSTS_MAX_AGE_SEC", "31536000")))
67
  BWRAP_PATH = shutil.which("bwrap")
68
  PRLIMIT_PATH = shutil.which("prlimit")
 
69
 
70
  os.makedirs(PROJECTS_DIR, exist_ok=True)
71
  os.makedirs(TEMPLATES_DIR, exist_ok=True)
@@ -488,6 +489,12 @@ def _runner_sandbox_command(workspace: str, socket_path: str) -> list[str]:
488
  "--socket-path", "/run-ipc/runner.sock",
489
  "--models_dir", "/models",
490
  ))
 
 
 
 
 
 
491
  memory_bytes = RUNNER_MEMORY_LIMIT_MB * 1024 * 1024
492
  file_bytes = 128 * 1024 * 1024
493
  return [
@@ -499,10 +506,40 @@ def _runner_sandbox_command(workspace: str, socket_path: str) -> list[str]:
499
  "--nofile=128:128",
500
  "--core=0:0",
501
  "--",
502
- *bwrap,
503
  ]
504
 
505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  # ---------------------------------------------------------------------------
507
  # Static / logo
508
  # ---------------------------------------------------------------------------
@@ -883,20 +920,22 @@ async def play_project_ws_internal(
883
  ipc_dir = os.path.join(session_root, "ipc")
884
  os.mkdir(ipc_dir, 0o700)
885
  socket_path = os.path.join(ipc_dir, "runner.sock")
886
- cmd = _runner_sandbox_command(workspace, socket_path)
887
  ipc_server = await asyncio.start_unix_server(
888
  handle_runner_conn, path=socket_path
889
  )
890
  os.chmod(socket_path, 0o600)
891
  except (OSError, RuntimeError, ValueError) as exc:
892
- log.warning("Refused to start unsandboxed runner: %s", exc)
893
- await websocket.send_json({"type": "log", "data": f"安全執行環境無法啟動,已停止執行:{exc}\n"})
894
  await websocket.send_json({"type": "status", "data": "error"})
895
  return
896
 
897
  popen_kwargs: dict[str, Any] = {
898
  "stdout": subprocess.DEVNULL,
899
  "stderr": subprocess.PIPE,
 
 
900
  }
901
  if sys.platform != "win32":
902
  popen_kwargs["start_new_session"] = True
@@ -906,7 +945,7 @@ async def play_project_ws_internal(
906
  process_stderr_task = asyncio.create_task(
907
  _capture_bounded_stderr(process.stderr, process_stderr)
908
  )
909
- log.info("Started sandboxed runner pid=%s session=%s", process.pid, session_id)
910
 
911
  try:
912
  await asyncio.wait_for(
@@ -933,13 +972,17 @@ async def play_project_ws_internal(
933
  await asyncio.gather(process_stderr_task, return_exceptions=True)
934
  stderr_detail = process_stderr.decode("utf-8", errors="replace").strip()
935
  log.error(
936
- "Runner pid=%s sandbox IPC connect timeout; returncode=%s; stderr=%s",
937
  process.pid,
938
  process.returncode,
939
  stderr_detail or "<empty>",
940
  )
941
  await websocket.send_json(
942
- {"type": "log", "data": "安全執行環境無法連線(可能是主機未啟用 Linux namespace);已拒絕未隔離執行。\n"}
 
 
 
 
943
  )
944
  await websocket.send_json({"type": "status", "data": "error"})
945
  return
 
66
  HSTS_MAX_AGE_SEC = max(0, int(os.environ.get("HSTS_MAX_AGE_SEC", "31536000")))
67
  BWRAP_PATH = shutil.which("bwrap")
68
  PRLIMIT_PATH = shutil.which("prlimit")
69
+ RUNNER_ISOLATION_MODE = os.environ.get("RUNNER_ISOLATION_MODE", "sandbox").lower()
70
 
71
  os.makedirs(PROJECTS_DIR, exist_ok=True)
72
  os.makedirs(TEMPLATES_DIR, exist_ok=True)
 
489
  "--socket-path", "/run-ipc/runner.sock",
490
  "--models_dir", "/models",
491
  ))
492
+ return _runner_with_resource_limits(bwrap)
493
+
494
+
495
+ def _runner_with_resource_limits(command: list[str]) -> list[str]:
496
+ if not PRLIMIT_PATH:
497
+ raise RuntimeError("伺服器缺少 prlimit,無法套用執行資源限制。")
498
  memory_bytes = RUNNER_MEMORY_LIMIT_MB * 1024 * 1024
499
  file_bytes = 128 * 1024 * 1024
500
  return [
 
506
  "--nofile=128:128",
507
  "--core=0:0",
508
  "--",
509
+ *command,
510
  ]
511
 
512
 
513
+ def _runner_command(workspace: str, socket_path: str) -> list[str]:
514
+ if RUNNER_ISOLATION_MODE == "sandbox":
515
+ return _runner_sandbox_command(workspace, socket_path)
516
+ if RUNNER_ISOLATION_MODE != "process" or sys.platform != "linux":
517
+ raise RuntimeError("不支援的 Python 執行模式。")
518
+ return _runner_with_resource_limits([
519
+ sys.executable,
520
+ os.path.join(BASE_DIR, "runner.py"),
521
+ "--project_path", os.path.join(workspace, "main.py"),
522
+ "--socket-path", socket_path,
523
+ "--models_dir", MODELS_DIR,
524
+ ])
525
+
526
+
527
+ def _runner_environment(workspace: str) -> dict[str, str]:
528
+ """Do not pass application tokens or admin credentials to child processes."""
529
+ return {
530
+ "PATH": "/usr/local/bin:/usr/bin:/bin",
531
+ "HOME": workspace,
532
+ "LANG": "C.UTF-8",
533
+ "PYTHONNOUSERSITE": "1",
534
+ "PYTHONDONTWRITEBYTECODE": "1",
535
+ "PYTHONUNBUFFERED": "1",
536
+ "SDL_VIDEODRIVER": "dummy",
537
+ "SDL_AUDIODRIVER": "dummy",
538
+ "OPENBLAS_NUM_THREADS": "1",
539
+ "OMP_NUM_THREADS": "1",
540
+ }
541
+
542
+
543
  # ---------------------------------------------------------------------------
544
  # Static / logo
545
  # ---------------------------------------------------------------------------
 
920
  ipc_dir = os.path.join(session_root, "ipc")
921
  os.mkdir(ipc_dir, 0o700)
922
  socket_path = os.path.join(ipc_dir, "runner.sock")
923
+ cmd = _runner_command(workspace, socket_path)
924
  ipc_server = await asyncio.start_unix_server(
925
  handle_runner_conn, path=socket_path
926
  )
927
  os.chmod(socket_path, 0o600)
928
  except (OSError, RuntimeError, ValueError) as exc:
929
+ log.warning("Unable to prepare runner: %s", exc)
930
+ await websocket.send_json({"type": "log", "data": f"專案執行器無法啟動,已停止執行:{exc}\n"})
931
  await websocket.send_json({"type": "status", "data": "error"})
932
  return
933
 
934
  popen_kwargs: dict[str, Any] = {
935
  "stdout": subprocess.DEVNULL,
936
  "stderr": subprocess.PIPE,
937
+ "cwd": workspace,
938
+ "env": _runner_environment(workspace),
939
  }
940
  if sys.platform != "win32":
941
  popen_kwargs["start_new_session"] = True
 
945
  process_stderr_task = asyncio.create_task(
946
  _capture_bounded_stderr(process.stderr, process_stderr)
947
  )
948
+ log.info("Started runner mode=%s pid=%s session=%s", RUNNER_ISOLATION_MODE, process.pid, session_id)
949
 
950
  try:
951
  await asyncio.wait_for(
 
972
  await asyncio.gather(process_stderr_task, return_exceptions=True)
973
  stderr_detail = process_stderr.decode("utf-8", errors="replace").strip()
974
  log.error(
975
+ "Runner pid=%s IPC connect timeout; returncode=%s; stderr=%s",
976
  process.pid,
977
  process.returncode,
978
  stderr_detail or "<empty>",
979
  )
980
  await websocket.send_json(
981
+ {"type": "log", "data": (
982
+ "安全執行環境無法連線(可能是主機未啟用 Linux namespace);已拒絕未隔離執行。\n"
983
+ if RUNNER_ISOLATION_MODE == "sandbox"
984
+ else "專案執行器啟動失敗,請稍後重試或請老師查看伺服器日誌。\n"
985
+ )}
986
  )
987
  await websocket.send_json({"type": "status", "data": "error"})
988
  return
tests/test_security.py CHANGED
@@ -66,6 +66,29 @@ class ServerSecurityTests(unittest.TestCase):
66
 
67
  self.assertEqual(len(asyncio.run(capture())), 4096)
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  def test_homepage_renders_template(self):
70
  with TestClient(server.app) as client:
71
  response = client.get("/")
 
66
 
67
  self.assertEqual(len(asyncio.run(capture())), 4096)
68
 
69
+ def test_explicit_process_mode_keeps_limits_and_uses_private_socket(self):
70
+ with patch.object(server, "RUNNER_ISOLATION_MODE", "process"), \
71
+ patch.object(server.sys, "platform", "linux"), \
72
+ patch.object(server, "PRLIMIT_PATH", "/usr/bin/prlimit"):
73
+ command = server._runner_command("/tmp/project", "/tmp/session/runner.sock")
74
+ self.assertEqual(command[0], "/usr/bin/prlimit")
75
+ self.assertIn("--nproc=64:64", command)
76
+ self.assertIn("/tmp/project/main.py", command)
77
+ self.assertIn("/tmp/session/runner.sock", command)
78
+ self.assertNotIn("--unshare-user", command)
79
+
80
+ def test_runner_environment_does_not_inherit_application_secrets(self):
81
+ with patch.dict(server.os.environ, {"HF_TOKEN": "private", "ADMIN_PASSWORD": "private"}):
82
+ environment = server._runner_environment("/tmp/project")
83
+ self.assertNotIn("HF_TOKEN", environment)
84
+ self.assertNotIn("ADMIN_PASSWORD", environment)
85
+ self.assertEqual(environment["SDL_VIDEODRIVER"], "dummy")
86
+
87
+ def test_invalid_mode_cannot_silently_disable_isolation(self):
88
+ with patch.object(server, "RUNNER_ISOLATION_MODE", "typo"):
89
+ with self.assertRaises(RuntimeError):
90
+ server._runner_command("/tmp/project", "/tmp/session/runner.sock")
91
+
92
  def test_homepage_renders_template(self):
93
  with TestClient(server.app) as client:
94
  response = client.get("/")