mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-20 17:02:01 +00:00
dd57c12016
跑一段不可信代码不需要一整套容器运行时。macOS 用 Seatbelt (sandbox-exec,系统自带),Linux 用 bubblewrap;冷启动从 ~250ms 降到 ~25ms,且不再需要装任何东西。 守住三件事:默认断网、家目录不可读、只有工作区可写。策略由内核 强制且对子进程继承——沙箱内 subprocess 出来的 cat 读家目录同样是 Operation not permitted。解释器改用 sys.base_prefix 下那个干净的 Python,沙箱代码因此 import 不到后端的 FastAPI、SQLAlchemy 和凭据 处理代码。 如实标注能力边界,不给虚假的安全感: - macOS 不强制 RLIMIT_AS,内存限不住(实测设 256MB 仍可分配 900MB), health 接口申报 enforced 字段,界面把限不住的项划掉 - Seatbelt 是访问控制而非虚拟化:进程表共享,以当前用户身份运行 - bubblewrap 侧多隔离 PID/IPC/挂载视图,内存限额真实生效 顺带修两个 bug: - LocalSandbox 设 RLIMIT_NPROC=64 会误伤——macOS 上它按 uid 全局 计数,用户已有上千进程时沙箱内任何 fork 都失败,连 bash 都起不来 - 模型所属 provider 被停用时,原先静默换一家继续用原模型名,必然 404 且报错指不到原因;改为直接说清是哪个 provider 被停用了 写 SBPL 的坑记在注释里:(deny default) 会让 Python 直接 SIGABRT, 改用「默认允许 + 精确拒绝」。 7 个模板全部回归通过。
165 lines
6.3 KiB
Python
165 lines
6.3 KiB
Python
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import os
|
||
import resource
|
||
import shutil
|
||
import sys
|
||
import time
|
||
from pathlib import Path
|
||
|
||
from app.core.config import settings
|
||
from app.sandbox.base import ExecResult, Sandbox, SandboxLimits, truncate
|
||
|
||
_LANG = {
|
||
"python": ("main.py", [sys.executable, "-u", "main.py"]),
|
||
"bash": ("main.sh", ["bash", "main.sh"]),
|
||
"sh": ("main.sh", ["sh", "main.sh"]),
|
||
"node": ("main.js", ["node", "main.js"]),
|
||
"javascript": ("main.js", ["node", "main.js"]),
|
||
}
|
||
|
||
|
||
class LocalSandbox(Sandbox):
|
||
"""裸子进程执行,所有隔离后端都不可用时的最后兜底。
|
||
|
||
只有 rlimit 和一个独立工作目录,**没有任何访问控制**:代码能读你的整个
|
||
文件系统、能联网。正常情况下不会走到这里 —— macOS 有 Seatbelt、
|
||
Linux 装个 bubblewrap 即可。真要用它跑不信任的代码,别。
|
||
"""
|
||
|
||
name = "local"
|
||
|
||
def __init__(self) -> None:
|
||
self._root = settings.workspace_dir / "local"
|
||
self._root.mkdir(parents=True, exist_ok=True)
|
||
|
||
async def health(self) -> dict[str, object]:
|
||
return {
|
||
"backend": self.name,
|
||
"available": True,
|
||
"isolated": False,
|
||
"warning": "裸子进程执行,无访问控制,不要跑不信任的代码",
|
||
"enforced": {"timeout": True, "cpu": True,
|
||
"memory": not sys.platform == "darwin", "network": False, "fsize": True},
|
||
"root": str(self._root),
|
||
}
|
||
|
||
def _session_dir(self, session_id: str) -> Path:
|
||
safe = "".join(c for c in session_id if c.isalnum() or c in "-_")[:64] or "default"
|
||
path = self._root / safe
|
||
path.mkdir(parents=True, exist_ok=True)
|
||
return path
|
||
|
||
@staticmethod
|
||
def _preexec(limits: SandboxLimits): # pragma: no cover - 只在子进程里跑
|
||
def _apply() -> None:
|
||
resource.setrlimit(resource.RLIMIT_CPU, (limits.timeout, limits.timeout + 2))
|
||
# 注意 macOS 不强制执行 RLIMIT_AS,这条在 Darwin 上是无效的
|
||
nbytes = limits.memory_mb * 1024 * 1024
|
||
for res_name in ("RLIMIT_AS", "RLIMIT_DATA"):
|
||
res_id = getattr(resource, res_name, None)
|
||
if res_id is not None:
|
||
try:
|
||
resource.setrlimit(res_id, (nbytes, nbytes))
|
||
except (ValueError, OSError):
|
||
pass
|
||
resource.setrlimit(resource.RLIMIT_FSIZE, (64 * 1024 * 1024,) * 2)
|
||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
||
# 不设 RLIMIT_NPROC:macOS 上它按 uid 全局计数,设小了会让沙箱里
|
||
# 任何 fork 都失败(bash 直接起不来),而不是只限制沙箱自己。
|
||
os.setsid() # 独立进程组,超时时能整组 kill
|
||
|
||
return _apply
|
||
|
||
async def run(
|
||
self,
|
||
code: str,
|
||
*,
|
||
language: str = "python",
|
||
limits: SandboxLimits | None = None,
|
||
session_id: str | None = None,
|
||
env: dict[str, str] | None = None,
|
||
files: dict[str, str] | None = None,
|
||
) -> ExecResult:
|
||
limits = limits or SandboxLimits()
|
||
language = (language or "python").lower()
|
||
if language not in _LANG:
|
||
return ExecResult(ok=False, backend=self.name, error=f"不支持的语言:{language}")
|
||
|
||
filename, argv = _LANG[language]
|
||
if shutil.which(argv[0]) is None and argv[0] != sys.executable:
|
||
return ExecResult(
|
||
ok=False, backend=self.name, error=f"宿主机上找不到 {argv[0]}"
|
||
)
|
||
|
||
workdir = self._session_dir(session_id or f"tmp-{int(time.time()*1000)}")
|
||
(workdir / filename).write_text(code)
|
||
for rel, content in (files or {}).items():
|
||
target = (workdir / rel).resolve()
|
||
if not str(target).startswith(str(workdir.resolve())):
|
||
return ExecResult(ok=False, backend=self.name, error=f"非法文件路径:{rel}")
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
target.write_text(content)
|
||
|
||
# 只透传最小环境变量,避免把宿主机的 API key 泄漏给被执行的代码
|
||
child_env = {
|
||
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
|
||
"HOME": str(workdir),
|
||
"LANG": "en_US.UTF-8",
|
||
"PYTHONDONTWRITEBYTECODE": "1",
|
||
**(env or {}),
|
||
}
|
||
|
||
started = time.perf_counter()
|
||
try:
|
||
proc = await asyncio.create_subprocess_exec(
|
||
*argv,
|
||
cwd=str(workdir),
|
||
env=child_env,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.PIPE,
|
||
preexec_fn=self._preexec(limits),
|
||
)
|
||
except Exception as e: # noqa: BLE001
|
||
return ExecResult(ok=False, backend=self.name, error=f"{type(e).__name__}: {e}")
|
||
|
||
try:
|
||
out, err = await asyncio.wait_for(proc.communicate(), timeout=limits.timeout)
|
||
except asyncio.TimeoutError:
|
||
try:
|
||
os.killpg(os.getpgid(proc.pid), 9)
|
||
except (ProcessLookupError, PermissionError):
|
||
proc.kill()
|
||
await proc.wait()
|
||
return ExecResult(
|
||
ok=False,
|
||
backend=self.name,
|
||
timed_out=True,
|
||
exit_code=124,
|
||
duration_ms=int((time.perf_counter() - started) * 1000),
|
||
error=f"执行超过 {limits.timeout}s 被终止",
|
||
)
|
||
|
||
stdout, t1 = truncate(out.decode(errors="replace"), limits.max_output)
|
||
stderr, t2 = truncate(err.decode(errors="replace"), limits.max_output)
|
||
written = [
|
||
p.name
|
||
for p in workdir.iterdir()
|
||
if p.is_file() and p.name != filename
|
||
][:50]
|
||
return ExecResult(
|
||
ok=proc.returncode == 0,
|
||
exit_code=proc.returncode or 0,
|
||
stdout=stdout,
|
||
stderr=stderr,
|
||
truncated=t1 or t2,
|
||
backend=self.name,
|
||
duration_ms=int((time.perf_counter() - started) * 1000),
|
||
files_written=written,
|
||
)
|
||
|
||
async def cleanup(self, session_id: str) -> None:
|
||
path = self._session_dir(session_id)
|
||
await asyncio.to_thread(shutil.rmtree, path, True)
|