diff --git a/docker-compose.yml b/docker-compose.yml index 443da1c..ef09331 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,7 +20,7 @@ services: # 加入executor独立服务 - EXECUTOR_URL=http://agent-executor:9000 # 两侧设成同一个值即启用调用鉴权(内网互访,可选): - - EXECUTOR_TOKEN=whoami + - EXECUTOR_TOKEN=b2676884778e373dcd7244c29aadcb82 networks: - my-app-network - agent-internal @@ -32,15 +32,22 @@ services: expose: - "9000" volumes: - - ./tasks:/workspace/tasks # 持久化:任务目录 - - ./skills:/workspace/skills # 技能目录:所有任务/会话共享同一份技能 + # 核心变更:将宿主机 tasks 挂载到非标准路径 /mnt/host-tasks + # 目的:wrapper 启动时先 unmount 此路径,确保未经 wrapper 的进程无法访问其他 session 数据 + - ./tasks:/mnt/host-tasks # 持久化:任务目录 + - ./skills:/workspace/skills:ro # 技能目录:所有任务/会话共享同一份技能 environment: - PORT=9000 # 与 agent-core 侧设成同一个值即启用调用鉴权(可选): - - EXECUTOR_TOKEN=whoami + - EXECUTOR_TOKEN=b2676884778e373dcd7244c29aadcb82 # 日志等级:debug|info|warn|error|none(默认 info); # debug 会把与 core 的完整交互打印出来(请求、/exec 请求体、每条 SSE 帧、JSON 响应): - EXECUTOR_LOG_LEVEL=info + # 防止 Python 在 skills 目录生成 __pycache__ + - PYTHONDONTWRITEBYTECODE=1 + # 定义隔离基路径,server.js 需读取此变量以执行 umount 和 bind mount + - EXECUTOR_ISOLATION_BASE=/mnt/host-tasks + # 资源限制:兜住 AI 失控命令(烧 CPU / 吃内存 / fork 炸弹 / 写盘撞满宿主机磁盘)。cgroup/ulimit 随 fork 继承。 # 这些是性能/容量护栏,不限制可调用的 syscall;执行能力由下方 cap_add/security_opt 控制。 cpus: "2.0" # 容器整体最多用 2 核(超出限流不杀进程),按宿主机核数调整 @@ -53,15 +60,16 @@ services: fsize: soft: 2147483648 hard: 2147483648 - # per-task 隔离需 unshare(2)/mount(2):只需 CAP_SYS_ADMIN(cap_add),不必 privileged。 - # 实测 Docker 29(Ubuntu,AppArmor 启用):默认 AppArmor profile(docker-default)会拦 mount 系统调用, - # 单加 SYS_ADMIN 仍报 Permission denied,需本容器 apparmor unconfined;默认 seccomp profile 对持 CAP_SYS_ADMIN - # 的进程本就放行 mount/unshare,无需改动。相比 privileged: true 去掉的是:宿主机设备透传(/dev 裸盘)、 - # 全套能力集、seccomp 封锁——保留的这三道仍是隔离层。 - # 安全网:容器仅 expose 9000 + agent-internal 外网不可见;cpus/mem/pids/fsize cgroup 仍受控。 + + # 安全加固:显式丢弃所有能力,仅保留必要的 SYS_ADMIN + cap_drop: + - ALL cap_add: - SYS_ADMIN security_opt: + # 禁止提权(SUID/SGID 失效),防止通过二进制漏洞获取更高权限 + - no-new-privileges:true + # 实测 Docker 29 (Ubuntu) 需 unconfined 才能使用 mount/unshare 系统调用 - apparmor=unconfined networks: - agent-internal diff --git a/executor/Dockerfile b/executor/Dockerfile index e8f6f0d..24a0f56 100644 --- a/executor/Dockerfile +++ b/executor/Dockerfile @@ -2,16 +2,21 @@ FROM node:20-slim # MPLBACKEND=Agg:让 matplotlib 使用非交互式后端,避免缺少显示设备报错。 # PYTHONUNBUFFERED=1:实时输出日志。 +# PYTHONPYCACHEPREFIX=/tmp/pycache:把 __pycache__ 统一甩到会话私有 tmpfs,绝不回写 skills(已 :ro)。 +# PIP_BREAK_SYSTEM_PACKAGES=1:允许在系统环境装包。 # TZ=Asia/Shanghai:统一时区。 ENV MPLBACKEND=Agg \ PYTHONUNBUFFERED=1 \ + PYTHONPYCACHEPREFIX=/tmp/pycache \ + PYTHONDONTWRITEBYTECODE=1 \ PIP_BREAK_SYSTEM_PACKAGES=1 \ TZ=Asia/Shanghai # 常用命令行工具:Agent 的 terminal 工具经常用到 +# util-linux 提供 unshare/mount/umount(隔离 wrapper 必需);sudo 已刻意不装。 RUN apt-get update -y && apt-get install -y --no-install-recommends \ ca-certificates curl git python3 python3-pip python3-venv python3-dev \ - ripgrep wget jq p7zip-full unzip unar file \ + ripgrep wget jq p7zip-full unzip unar file tree \ libreoffice-writer libreoffice-calc libreoffice-impress \ fonts-noto-cjk fonts-dejavu fonts-stix \ poppler-utils qpdf ghostscript imagemagick \ @@ -19,9 +24,11 @@ RUN apt-get update -y && apt-get install -y --no-install-recommends \ ffmpeg sqlite3 libsqlite3-dev \ && rm -rf /var/lib/apt/lists/* +# Python 依赖预烘进镜像(W2):skills 目录改为只读后,运行期不得再 pip install 任何技能依赖。 +# 新增技能若需要新包,改这里 rebuild,而不是让 AI 现场装。 RUN pip3 install --no-cache-dir --break-system-packages \ requests beautifulsoup4 lxml \ - numpy matplotlib \ + numpy matplotlib pandas \ openpyxl python-docx python-pptx xlrd \ pymupdf pdfplumber pypdf reportlab \ Pillow python-dateutil python-magic \ @@ -31,12 +38,25 @@ RUN pip3 install --no-cache-dir --break-system-packages \ WORKDIR /app COPY server.js ./ +# 隔离用的空挂载点:必须存在且为空。 +# /workspace/tasks —— wrapper 用 tmpfs 遮盖它,再 bind 回当前 session(虚拟任务根) +# /workspace/scratch —— wrapper 用私有 tmpfs 遮盖它(不给任何真实数据的临时工作区) +# 注意:这两个目录【绝不能】被 compose 挂上宿主机数据卷,否则隔离失效。 +# 放在最后一步创建,确保镜像里其它指令不会往这里留文件。 +RUN mkdir -p /workspace/tasks /workspace/scratch \ + && chmod 755 /workspace/tasks /workspace/scratch \ + && [ -z "$(ls -A /workspace/tasks)" ] && [ -z "$(ls -A /workspace/scratch)" ] + EXPOSE 9000 # EXECUTOR_LOG_LEVEL:日志等级 debug|info|warn|error|none(默认 info)。 # debug 会把与 core 的完整交互逐条打印(请求行、/exec 请求体、每条 SSE 帧、JSON 响应)。 +# EXECUTOR_ISOLATION_BASE:宿主机 tasks 在本容器内的真实挂载点,必须与 compose 的 volumes 一致。 ENV PORT=9000 \ EXECUTOR_ROOTS=/workspace \ EXECUTOR_CWD=/workspace/tasks \ + EXECUTOR_SCRATCH_ROOT=/workspace/scratch \ + EXECUTOR_SKILLS_DIR=/workspace/skills \ + EXECUTOR_ISOLATION_BASE=/mnt/host-tasks \ EXECUTOR_LOG_LEVEL=info CMD ["node", "server.js"] diff --git a/executor/server.js b/executor/server.js index 156903b..b73c811 100644 --- a/executor/server.js +++ b/executor/server.js @@ -1,44 +1,38 @@ // agent-executor:命令执行服务(独立容器,供 agent-core 调用)。单文件零依赖,仅用 Node 内置 http,默认端口 9000。 // // 接口: -// GET /health → {ok, running:[{id,pid,cwd,started_at}]} +// GET /health → {ok, time} // POST /exec body {command, cwd?, timeout_ms?, max_output_chars?, env?} -// 响应 SSE(text/event-stream),每条 data 为一个 JSON: -// {"type":"start","id","pid","cwd"} 进程已启动 -// {"type":"out","chunk"} stdout 增量(实时分块下发) -// {"type":"err","chunk"} stderr 增量 -// {"type":"exit","code","killed_by","stdout_chars","stderr_chars","truncated"} 结束汇总 -// 期间每 15s 发 ": ping" 注释行保活。 -// DELETE /exec/:id → {ok:true} 杀整个进程组(core 侧取消/超时用) +// 响应 SSE:{"type":"start"|"out"|"err"|"exit", ...};期间每 15s 发 ": ping" +// DELETE /exec/:id → {ok:true} 杀整个进程组 // -// 安全约束: -// - 设置 EXECUTOR_TOKEN 后,除 /health 外必须带 Authorization: Bearer (compose 内网互访,token 可选); -// - cwd 必须落在 EXECUTOR_ROOTS(逗号分隔白名单,默认 /workspace)内,先解析再 realpath 校验,防穿越; -// - cwd 不得是任务根(EXECUTOR_CWD)本身:它是全部会话目录的父目录,直接在其下执行会暴露所有会话, -// 隔离 wrapper 在此层也无从生效;缺省 cwd 即落到任务根、同样被拒,等效 cwd 必填; -// - timeout_ms 夹在 [1s, EXECUTOR_MAX_TIMEOUT_MS](默认 30 分钟); -// - stdout/stderr 各自按 max_output_chars 截断(默认 EXECUTOR_MAX_OUTPUT_CHARS=200000),超限后丢弃剩余输出,exit 事件带 truncated 标记。 +// 安全模型(v4): +// 1. 宿主机 ./tasks 挂载到 ISOLATION_BASE(默认 /mnt/host-tasks),该路径【永不在 ROOTS 内】。 +// 2. 每条 /exec 命令都在 unshare --mount --pid --fork --propagation private 的新 mount +// namespace 中运行,不存在“非隔离模式”——杜绝“换个 cwd 就绕过卸载”的降级旁路。 +// 3. wrapper 进 ns 后:先把当前 session bind 到私有 tmpfs 上的 anchor 保命,随后用一层 +// 空 tmpfs【遮盖】整个 /mnt(含 ISOLATION_BASE)。之后 AI 无论从哪条路径探测都拿不到 +// 其它 session 的数据。 // -// per-task 隔离:每条命令默认在新的 mount + pid 命名空间里跑。启动 wrapper 把 EXECUTOR_CWD(任务根,/workspace/tasks) -// 覆盖为 tmpfs,只把当前会话的子目录 bind 回原路径上——结果:AI 命令能读写自己的项目,看不到别人的 task 目录。 -// 同时 unshare --pid + 重挂 /proc:否则 /proc 仍是宿主视图,/proc/1(executor 主进程)的 ns/mnt 符号链接是原始 mount ns -// 的句柄,AI 用 nsenter --mount=/proc/1/ns/mnt 即可逃逸回未隔离视图(已实测复现);重挂后 /proc/1 即命令自身。 -// 新 proc 可写会顶掉 docker 的防护,wrapper 逐项还原:/proc/sys 只读 bind(防 core_pattern 类宿主逃逸)、 -// /dev/null 遮蔽 kcore/keys(docker maskPaths)与 sysrq-trigger(可写 proc 新暴露,echo b 可重启宿主机)。 -// wrapper 还把 server.js 所在目录(镜像 WORKDIR,容器内 /app)用 tmpfs 盖掉,AI 读不到 executor 源码; -// 且下发命令的 env 剥掉 EXECUTOR_TOKEN——否则命令里 env 一 dump 就拿 token 回环 POST /exec 以任意会话目录起命令,绕过隔离。 -// 副作用红利:pid ns 内 ps 只见自家进程树;double-fork 脱管的守护进程随命令退出被内核连带清理。 -// 任务根以外的路径(/workspace/skills、/tmp、/usr、依赖包等)不受影响。mount 命名空间随进程退出自动销毁。 -// 需 CAP_SYS_ADMIN,且 AppArmor 不能拦 mount(Docker 默认 docker-default profile 会拦):compose 里 agent-executor 配 cap_add SYS_ADMIN + apparmor=unconfined,不用 privileged(实测默认 seccomp 对持 CAP_SYS_ADMIN 的进程放行 mount/unshare)。 +// ⚠️ 关键教训(v4 曾因此把数据卷从父 ns 卸掉,导致服务半死): +// 绝对不要在子 ns 里对 ISOLATION_BASE 执行 umount。Docker 容器根 mount table 默认是 +// shared,`unshare --propagation private` 并不可靠地阻断 umount 的反向传播,一旦泄漏 +// 父 ns 就永久失去该挂载(只能重启容器恢复)。遮盖(mount over)是本 ns 局部操作, +// 不改动原挂载条目,ns 销毁即无痕,才是安全做法。 +// 4. /tmp、anchor 目录、scratch 都是 per-session 私有 tmpfs,跨会话不可见,崩溃残留随 ns 消失。 +// 5. 只用 POSIX sh 兼容语法(镜像默认 dash):不使用 trap ERR、不使用 bash 数组/[[ ]]。 +// 隔离层自身失败以退出码 90-99 回传,便于与 AI 命令的失败区分。 +// 6. DEFAULT_CWD / SCRATCH_ROOT 在父 ns 中必须是【存在的空目录】(由 Dockerfile 预建): +// 存在才能当挂载点,为空才不会成为数据旁路。selfCheck 会校验这两点。 // -// 日志:EXECUTOR_LOG_LEVEL=debug|info|warn|error|none(默认 info,none/off 全静默),分级语义与 core 的 log.js 一致。 -// info = 关键动作(启动/进程 start/exit/取消/关闭);debug = 额外打印与 core 的完整交互: -// 每个请求行、/exec 请求体、每条 SSE 下发帧、每个 JSON 响应(超长内容截断显示)。改环境配置后重启容器生效。 +// 约束: +// - 设置 EXECUTOR_TOKEN 后除 /health 外必须带 Authorization: Bearer ; +// - cwd 必须落在 EXECUTOR_ROOTS(逗号分隔白名单)内,且不得是任务根本身; +// - session 目录及其链上不得含符号链接(防解析后逃逸); +// - timeout_ms 夹在 [1s, EXECUTOR_MAX_TIMEOUT_MS];stdout/stderr 各自按 max_output_chars 截断。 // -// 资源护栏(CPU/内存/进程数/单文件大小)不在本进程内实现,由 docker-compose 的 cgroup/ulimit 限制,见顶层 docker-compose.yml agent-executor 段。 -// -// 约定:core 与 executor 把同一份宿主机 ./tasks、./skills 挂到相同容器路径(/workspace/*), -// 所以 core 下发的任务目录 cwd 在 executor 内原样可用。 +// 日志:EXECUTOR_LOG_LEVEL=debug|info|warn|error|none +'use strict'; const http = require('http'); const fs = require('fs'); @@ -46,22 +40,41 @@ const path = require('path'); const crypto = require('crypto'); const { spawn } = require('child_process'); +// ---------- 配置 ---------- const PORT = parseInt(process.env.PORT, 10) || 9000; const TOKEN = process.env.EXECUTOR_TOKEN || ''; -const ROOTS = (process.env.EXECUTOR_ROOTS || '/workspace').split(',').map(s => s.trim()).filter(Boolean).map(p => path.resolve(p)); -const DEFAULT_CWD = process.env.EXECUTOR_CWD || path.join(ROOTS[0], 'tasks'); -// 任务根 realpath:/exec 一律拒绝 cwd 恰好等于它(见 handleExec)。拒绝后「任务根下的命令必进隔离 wrapper」成为硬不变式。 -const REAL_TASK_ROOT = (() => { try { return fs.realpathSync(DEFAULT_CWD); } catch (_) { return null; } })(); -// server.js 所在目录(镜像 WORKDIR /app):隔离 wrapper 用 tmpfs 盖住,不让 AI 读 executor 源码。 -const APP_DIR = __dirname; + +const ROOTS = (process.env.EXECUTOR_ROOTS || '/workspace') + .split(',').map(s => s.trim()).filter(Boolean).map(p => path.resolve(p)); + +// 隔离基路径:宿主机 tasks 在本容器内的真实挂载点。wrapper 用空 tmpfs 遮盖它的父目录来隐藏。 +const ISOLATION_BASE = path.resolve(process.env.EXECUTOR_ISOLATION_BASE || '/mnt/host-tasks'); +// 虚拟任务根:AI 看到的 tasks 路径,仅在子 ns 中由 wrapper 构造。 +const DEFAULT_CWD = path.resolve(process.env.EXECUTOR_CWD || path.join(ROOTS[0], 'tasks')); +// 每个会话私有的空工作区根(不给任何真实数据)。必须与 DEFAULT_CWD 平级,不能在其之下。 +const SCRATCH_ROOT = path.resolve(process.env.EXECUTOR_SCRATCH_ROOT || path.join(ROOTS[0], 'scratch')); +// 技能目录:期望由 compose 以 :ro 挂载。 +const SKILLS_DIR = path.resolve(process.env.EXECUTOR_SKILLS_DIR || path.join(ROOTS[0], 'skills')); + +// server.js 所在目录(镜像 WORKDIR /app):用 tmpfs 盖住,不让 AI 读 executor 源码。 +const APP_DIR = path.resolve(__dirname); + const MAX_TIMEOUT = parseInt(process.env.EXECUTOR_MAX_TIMEOUT_MS, 10) || 30 * 60 * 1000; const DEFAULT_MAX_OUT = parseInt(process.env.EXECUTOR_MAX_OUTPUT_CHARS, 10) || 200000; const PING_MS = 15000; -const BODY_LIMIT = 1024 * 1024; // /exec 请求体上限 1MB +const BODY_LIMIT = 1024 * 1024; -const runs = new Map(); // id -> { child, killedBy, started_at, cwd } +const runs = new Map(); // id -> { child, killedBy, started_at, cwd, timer } -// ---------- 分级日志(格式与 core 的 log.js 对齐: [] [executor] )---------- +// ---------- 小工具 ---------- +function isUnder(p, root) { return p === root || p.startsWith(root + path.sep); } +function shq(s) { return "'" + String(s).replace(/'/g, "'\\''") + "'"; } +function brief(s, n) { + s = String(s); n = n || 2000; + return s.length > n ? s.slice(0, n) + '…(+' + (s.length - n) + ')' : s; +} + +// ---------- 分级日志 ---------- const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 }; function parseLevel(l) { const s = String(l || 'info').trim().toLowerCase(); @@ -91,64 +104,357 @@ const log = { error() { emit(console.error, 'error', arguments); }, }; -// debug 交互日志的文本截断:保留可读性,超长只留头部并标注丢弃量。 -function brief(s, n) { - s = String(s); - n = n || 2000; - return s.length > n ? s.slice(0, n) + '…(+' + (s.length - n) + ')' : s; +// 目录是否为“存在且为空”(允许作为安全的 tmpfs 挂载点) +function emptyDirState(p) { + let st = null; + try { st = fs.statSync(p); } catch (_) { return 'missing'; } + if (!st.isDirectory()) return 'not_dir'; + let ents = []; + try { ents = fs.readdirSync(p); } catch (_) { return 'unreadable'; } + return ents.length === 0 ? 'empty' : 'nonempty'; } -// 单引号安全包裹:内部单引号按 '\'' 规则转义,给 sh -c 拼命令串用。 -function shq(s) { return "'" + String(s).replace(/'/g, "'\\''") + "'"; } +// ---------- 启动自检 ---------- +function selfCheck() { + const problems = []; + const warns = []; -// per-task 挂载隔离 wrapper:返回一个 sh -c 脚本,shell 启动时跑(与 unshare --mount --pid --fork 配合): -// 0) 重挂 proc 到新 pid ns(封掉 nsenter /proc/1/ns/mnt 逃逸),还原 /proc/sys 只读与 mask 遮蔽 -// 1) 把 cwd 预先 bind 到 /tmp 下的 anchor(避开后面被覆盖的任务根) -// 2) 在新 mount ns 里把任务根覆盖为 tmpfs(其他会话从此不可见);同法盖住 APP_DIR(源码遮蔽) -// 3) 在 tmpfs 下重建当前会话目录名,把 anchor bind 回原路径上 -// 4) 拆掉 anchor,切到 cwd,exec 用户命令(此时已是新 pid ns 的 PID 1) -// cwd 不在任务根下时返回 null(不隔离;主要适用于 skill 入口直接跑在 /workspace/skills/ 的场景)。 -// cwd 恰为任务根本身已在 handleExec 边界拒绝,首条分支仅作兜底。 -function isolatedCommand(command, cwd) { - if (cwd === DEFAULT_CWD || !cwd.startsWith(DEFAULT_CWD + path.sep)) return null; - // 会话根 = 任务根下的第一层子目录(task-YYYYMMDD-NNN);cwd 可能是其下任意深子目录(terminal 的 cd)。 - // 隔离时整个会话根 bind 回去,相对子路径自然保留,cd 回原 cwd 不会断。 - const rel = path.relative(DEFAULT_CWD, cwd); - const sessionName = rel.split(path.sep)[0]; - const sessionRoot = path.join(DEFAULT_CWD, sessionName); - // 遮蔽 executor 自身代码目录(镜像 WORKDIR,容器内 /app):tmpfs 盖住,AI 命令读不到 server.js。 - // 任务根/cwd 与 WORKDIR 相互嵌套时(宿主机开发态,smoke 即如此)跳过,避免把任务树一起盖掉。 - const hideWorkdir = !DEFAULT_CWD.startsWith(APP_DIR + path.sep) && !APP_DIR.startsWith(DEFAULT_CWD + path.sep) && !cwd.startsWith(APP_DIR + path.sep); - return [ - 'set -e', - // pid/proc 侧:重挂 proc 绑定本 pid ns(flags 对齐 docker),/proc/1 自此即命令自身,无宿主 ns 句柄可指。 - // 新 proc 是可写的,若不还原会顶掉 docker 防护:/proc/sys 可写→kernel.core_pattern 宿主 root 逃逸; - // 新 mount 盖住旧 /proc 后 maskPaths(kcore/keys)失效;sysrq-trigger 虽非 docker 遮蔽,但可写 proc 下 - // root+SYS_ADMIN 可 echo b 直接重启宿主机,一并遮蔽。mount 失败由 set -e 断令,fail-closed。 - 'mount -t proc -o nosuid,noexec,nodev proc /proc', - 'mount --bind /dev/null /proc/kcore', - 'mount --bind /dev/null /proc/keys', - 'mount --bind /dev/null /proc/sysrq-trigger', - 'mount --bind /proc/sys /proc/sys', - 'mount -o remount,bind,ro /proc/sys', - ...(hideWorkdir ? [ - 'mount -t tmpfs tmpfs ' + shq(APP_DIR), - // 防止 umount /app:bind mount 到自己,制造"子挂载"使内核引用计数 > 0 - 'mount --bind ' + shq(APP_DIR) + ' ' + shq(APP_DIR), - ] : []), - 'anchor=$(mktemp -d /tmp/.exanchor.XXXXXXXXXX)', - 'mount --bind ' + shq(sessionRoot) + ' "$anchor"', - 'mount -t tmpfs tmpfs ' + shq(DEFAULT_CWD), - 'mkdir ' + shq(sessionRoot), - 'mount --bind "$anchor" ' + shq(sessionRoot), - 'umount "$anchor"', - 'rmdir "$anchor"', - 'cd ' + shq(cwd), - 'exec /bin/sh -c ' + shq(command), - ].join('\n'); + for (const r of ROOTS) { + if (isUnder(ISOLATION_BASE, r)) { + problems.push('ISOLATION_BASE=' + ISOLATION_BASE + ' 落在 ROOTS(' + r + ') 内,AI 可访问未卸载的基路径'); + } + if (isUnder(r, ISOLATION_BASE)) { + problems.push('ROOTS(' + r + ') 位于 ISOLATION_BASE 之下'); + } + } + + let bs = null; + try { bs = fs.statSync(ISOLATION_BASE); } catch (_) {} + if (!bs || !bs.isDirectory()) { + problems.push('ISOLATION_BASE=' + ISOLATION_BASE + ' 不存在或不是目录 —— compose 的 volumes 没挂到这里?'); + } else if (fs.readdirSync(ISOLATION_BASE).length === 0) { + // v4 事故特征:挂载被 wrapper 误卸后,此处会变成一个空目录且 /proc/mounts 里无条目。 + problems.push('ISOLATION_BASE=' + ISOLATION_BASE + ' 为空 —— 数据卷可能被卸载(检查 /proc/mounts),需重建容器恢复'); + } + + // 确保基路径确实是一个独立挂载点;不是的话说明它只是普通目录,遮盖将无效。 + let mounted = false; + try { + const mt = fs.readFileSync('/proc/mounts', 'utf8').split('\n'); + const esc = ISOLATION_BASE.replace(/ /g, '\\040'); + for (const line of mt) { + const parts = line.split(' '); + if (parts[1] === esc) { mounted = true; break; } + } + } catch (_) {} + if (!mounted && bs && bs.isDirectory()) { + problems.push('ISOLATION_BASE=' + ISOLATION_BASE + ' 不是挂载点 —— 无法确定它是宿主机数据卷'); + } + + // 防“盖到自己头上”:MNTROOT(遮盖目标)不能落在 ROOTS 内,否则会把合法工作区一并封死。 + const MNTROOT = path.parse(ISOLATION_BASE).dir || '/'; + for (const r of ROOTS) { + if (isUnder(r, MNTROOT) || r === MNTROOT) { + problems.push('MNTROOT=' + MNTROOT + ' 包含或等于 ROOTS(' + r + '),遮盖会连带封死合法工作区'); + } + } + + // 虚拟任务根必须是“存在的空目录”:存在才能当 tmpfs 挂载点,为空才不是数据旁路。 + const dcs = emptyDirState(DEFAULT_CWD); + if (dcs === 'missing') { + warns.push('DEFAULT_CWD=' + DEFAULT_CWD + ' 不存在(wrapper 会自动 mkdir,但建议 Dockerfile 预建)'); + } else if (dcs !== 'empty') { + problems.push('DEFAULT_CWD=' + DEFAULT_CWD + ' 在父 ns 中非空/异常(' + dcs + ') —— 请确认没有把 ./tasks 挂到该路径'); + } + + const scs = emptyDirState(SCRATCH_ROOT); + if (scs === 'missing') { + warns.push('SCRATCH_ROOT=' + SCRATCH_ROOT + ' 不存在(wrapper 会自动 mkdir,但建议 Dockerfile 预建)'); + } else if (scs !== 'empty') { + problems.push('SCRATCH_ROOT=' + SCRATCH_ROOT + ' 在父 ns 中非空/异常(' + scs + ')'); + } + + if (isUnder(SCRATCH_ROOT, DEFAULT_CWD)) { + problems.push('SCRATCH_ROOT=' + SCRATCH_ROOT + ' 位于 DEFAULT_CWD 之下,会被 tmpfs 遮盖连带抹掉'); + } + if (isUnder(DEFAULT_CWD, SCRATCH_ROOT)) { + problems.push('DEFAULT_CWD=' + DEFAULT_CWD + ' 位于 SCRATCH_ROOT 之下,两者遮盖顺序冲突'); + } + + let ss = null; + try { ss = fs.statSync(SKILLS_DIR); } catch (_) {} + if (!ss) warns.push('SKILLS_DIR=' + SKILLS_DIR + ' 不存在(若不使用技能可忽略)'); + + if (problems.length) log.error('启动自检失败:\n - ' + problems.join('\n - ')); + else if (warns.length) log.warn('启动自检通过(有提示):\n - ' + warns.join('\n - ')); + else log.info('启动自检通过'); + return problems.length === 0; } -// 常量时间比较,避免通过响应耗时猜 token +// ---------- 隔离脚本生成 ---------- +// 全部为 POSIX sh 兼容语句;任一步失败由显式退出码标注(90-99 = 隔离层故障)。 +// 铁律:本函数内不得出现任何对 ISOLATION_BASE / MNTROOT 的 umount。只允许 mount(遮盖)。 +// 诊断原则:成功路径零输出;只在失败分支里附带最小现场信息(不报 session 名、不报内容)。 +function buildIsolation(command, plan) { + const L = []; + + L.push('set -e'); + + // --- 传播属性:确保本 ns 的挂载变更不向对等组回传(多一重保险)--- + L.push('mount --make-rprivate / 2>/dev/null || true'); + + // (诊断输出改为“只在失败分支里印”,见下方 anchor / mask 等步骤; + // 原因:无条件输出会污染每条命令的 stderr,且 entries 计数会泄露会话规模。) + + // --- proc 加固:只读 + 敏感项顶掉 --- + L.push('mount -t proc -o nosuid,noexec,nodev proc /proc || { echo "[isolate] proc failed" >&2; exit 90; }'); + L.push('for f in kcore keys kmsg sysrq-trigger sched_debug; do if [ -e /proc/$f ]; then mount --bind /dev/null /proc/$f 2>/dev/null || true; fi; done'); + L.push('mount --bind /proc/sys /proc/sys 2>/dev/null || true'); + L.push('mount -o remount,bind,ro /proc/sys 2>/dev/null || true'); + + // --- 遮盖 executor 自身代码目录(与工作区无父子关系时才做)--- + if (!(isUnder(DEFAULT_CWD, APP_DIR) || isUnder(APP_DIR, DEFAULT_CWD))) { + L.push('mount -t tmpfs tmpfs ' + shq(APP_DIR) + ' || { echo "[isolate] hide appdir failed" >&2; exit 91; }'); + } + + // --- 本会话私有 tmpfs:/tmp 与 anchor 目录 --- + L.push('mkdir -p /tmp'); + L.push('mount -t tmpfs -o nosuid,nodev,mode=1777 tmpfs /tmp || { echo "[isolate] /tmp failed" >&2; exit 92; }'); + L.push('RUNDIR=/run/agent-exec'); + L.push('mkdir -p "$RUNDIR"'); + L.push('mount -t tmpfs -o nosuid,nodev,mode=700 tmpfs "$RUNDIR" || { echo "[isolate] rundir failed" >&2; exit 93; }'); + + // --- 数据面 --- + if (plan.mode === 'session') { + // 1) 【必须最先做】把真实 session 目录 bind 到本会话私有 tmpfs($RUNDIR) 上的 anchor。 + // 这一步在任何遮盖发生之前完成,拿到一份不依赖原路径的独立引用。 + L.push('ANCH=$(mktemp -d "$RUNDIR/a.XXXXXXXX")'); + // 失败时才采集现场:base_entries=0 即“数据卷被摘”特征(v4 事故),无需在正常路径上付费。 + L.push('mount --bind ' + shq(plan.realSession) + ' "$ANCH" || { _b=N; if [ -d "' + ISOLATION_BASE + '" ]; then _b=Y; fi; echo "[isolate] anchor failed base=${_b}" >&2; exit 94; }'); + + // 2) 【核心】用空只读 tmpfs 遮盖整个 /mnt(ISOLATION_BASE 的父目录),使基路径及其下 + // 所有 session 对本 ns 不可见。只做 mount,永远不做 umount —— umount 可能传播回 + // 父 ns 并永久摘掉数据卷(v4 事故)。遮盖是本 ns 局部操作,ns 销毁即无痕。 + L.push('MNTROOT=' + shq(path.parse(ISOLATION_BASE).dir || '/')); + L.push('mkdir -p "$MNTROOT"'); + L.push('mount -t tmpfs -o ro,size=0 tmpfs "$MNTROOT" || { echo "[isolate] mask mnt failed" >&2; exit 98; }'); + + // 3) 重建虚拟视图:先盖住任务根,再把 anchor 内容 bind 回本 session 的虚拟路径 + L.push('mkdir -p ' + shq(DEFAULT_CWD)); + L.push('mount -t tmpfs -o nosuid,nodev tmpfs ' + shq(DEFAULT_CWD) + ' || { echo "[isolate] mask tasks failed" >&2; exit 95; }'); + L.push('mkdir -p ' + shq(plan.virtSession)); + // 虚拟 cwd 可能在 session 之下更深处(校验时按“缺失即交给这里建”处理)。 + // 必须先 bind 再建:深层目录建在 tmpfs 遮盖层上会在 rebind 时被本会话数据盖掉; + // 而 mkdir 在已 bind 的 virtSession 下建新子目录只发生在本 ns,不会写穿到宿主盘。 + L.push('mount --bind "$ANCH" ' + shq(plan.virtSession) + ' || { echo "[isolate] rebind failed" >&2; exit 96; }'); + L.push('mkdir -p ' + shq(plan.cwd)); + + // 4) 释放锚点目录项(仅本 ns 私有的 $RUNDIR 内,可安全卸载) + // 数据仍通过 virtSession 的 bind 存活,ns 退出时彻底回收。 + L.push('umount -l "$ANCH" 2>/dev/null || true'); + L.push('rmdir "$ANCH" 2>/dev/null || true'); + } else { + // scratch / plain:不需要任何真实数据,直接遮盖基路径即可 + L.push('MNTROOT=' + shq(path.parse(ISOLATION_BASE).dir || '/')); + L.push('mkdir -p "$MNTROOT"'); + L.push('mount -t tmpfs -o ro,size=0 tmpfs "$MNTROOT" || { echo "[isolate] mask mnt failed" >&2; exit 98; }'); + + if (plan.mode === 'scratch') { + L.push('mkdir -p ' + shq(SCRATCH_ROOT)); + L.push('mount -t tmpfs -o nosuid,nodev tmpfs ' + shq(SCRATCH_ROOT) + ' || { echo "[isolate] scratch failed" >&2; exit 95; }'); + // 同 session 分支:建到遮盖后的 SCRATCH_ROOT 之下,覆盖 plan.cwd 的全部深度 + L.push('mkdir -p ' + shq(plan.cwd)); + } + // plain(典型:只读的 skills):只需上面的 /mnt 遮盖 + } + + // --- 进入目标目录并执行 --- + L.push('cd ' + shq(plan.cwd) + ' || { echo "[isolate] cd failed" >&2; exit 97; }'); + L.push('exec /bin/sh -c ' + shq(command)); + + return L.join('\n'); +} + +// ---------- 运行期健康护栏 ---------- +// v4 事故后加:如果基路径在运行中被(错误地)卸载,所有后续请求都会变成 +// “session 不存在”的静默半死状态。这里连续失败到阈值就打 error,提醒运维。 +let consecutiveSessionMiss = 0; +function noteSessionProbe(ok) { + if (ok) { consecutiveSessionMiss = 0; return; } + consecutiveSessionMiss += 1; + if (consecutiveSessionMiss === 5 || consecutiveSessionMiss % 20 === 0) { + log.error('ISOLATION_BASE=' + ISOLATION_BASE + ' 已连续 ' + consecutiveSessionMiss + + ' 次无法访问 session 目录 —— 数据卷很可能已被卸载。' + + '确认方法: docker exec agent-executor grep host-tasks /proc/mounts;' + + '恢复方法: docker compose up -d --force-recreate agent-executor'); + } +} + +// ---------- cwd 校验与隔离计划 ---------- +function resolveCwd(raw) { + let cwd; + try { cwd = path.resolve(String(raw || '')); } catch (_) { return { ok: false, reason: 'cwd 无法解析' }; } + if (!cwd.startsWith(path.sep)) return { ok: false, reason: 'cwd 必须是绝对路径' }; + + // 1) 白名单 + if (!ROOTS.some(r => isUnder(cwd, r))) return { ok: false, reason: 'not_in_roots' }; + + // 2) 基路径永远不允许(纵深防御,万一 ROOTS 配错) + if (isUnder(cwd, ISOLATION_BASE) || isUnder(ISOLATION_BASE, cwd)) { + return { ok: false, reason: 'isolation_base_forbidden' }; + } + + // 3) 禁止在根本身执行 + if (cwd === DEFAULT_CWD || cwd === SCRATCH_ROOT) return { ok: false, reason: 'cwd 不能是任务根本身' }; + + // 4) 路径段合法性(统一拦截 .. / 空段 / NUL) + // 注意:必须在 resolveCwd 入口处对“原始字符串”检查 —— path.resolve 会提前折叠掉 .., + // 若在归一化之后才查就永远查不到。AI 无法预知 session 名,把 .. 拼进 session 段 + // (如 /../sessB)是唯一途径,在原始串上拦即可封死跨 session 借道。 + { + const rawStr = String(raw || ''); + if (rawStr.indexOf('\0') >= 0) return { ok: false, reason: '非法字符' }; + for (const s of rawStr.split('/')) { + if (s === '..') return { ok: false, reason: '非法路径段' }; + } + } + for (const s of cwd.split(path.sep)) { + if (s === '..') return { ok: false, reason: '非法路径段' }; + } + + // 5) session 路径:虚拟视图在父 ns 不存在属正常,故不做 lstat,改校验其映射的真实路径 + const relFromTasks = path.relative(DEFAULT_CWD, cwd); + const isSessionPath = relFromTasks !== '' && !relFromTasks.startsWith('..' + path.sep) && !path.isAbsolute(relFromTasks) && relFromTasks !== '..'; + + if (isSessionPath) { + const sessionName = relFromTasks.split(path.sep)[0]; + if (!sessionName || sessionName === '.' || sessionName === '..') { + return { ok: false, reason: '非法 session 名' }; + } + const realSession = path.join(ISOLATION_BASE, sessionName); + + let rs; + try { rs = fs.lstatSync(realSession); } catch (_) { + noteSessionProbe(false); + return { ok: false, reason: 'session 不存在' }; + } + noteSessionProbe(true); + if (rs.isSymbolicLink()) return { ok: false, reason: 'session 不得是符号链接' }; + if (!rs.isDirectory()) return { ok: false, reason: 'session 不是目录' }; + + // session 之下必须逐级是真实目录(不得文件/符号链接);缺失的深层路径按存在处理, + // 交给 wrapper 在子 ns 内 mkdir -p —— 它只会建在本会话 bind 里,落不到别的 session。 + if (relFromTasks.split(path.sep).length > 1) { + let dirChk = cwd; + for (let guard = 0; guard < 32 && dirChk !== DEFAULT_CWD; guard++) { + let ds = null; + try { ds = fs.lstatSync(dirChk); } catch (_) { /* ENOENT: 继续向上找第一个存在的祖先 */ } + if (ds) { + if (ds.isSymbolicLink()) return { ok: false, reason: 'cwd 路径链中存在符号链接' }; + if (!ds.isDirectory()) return { ok: false, reason: 'cwd 不是目录' }; + break; + } + const up = path.dirname(dirChk); + if (up === dirChk) break; + dirChk = up; + } + } + + let realFull; + try { realFull = fs.realpathSync(realSession); } catch (_) { return { ok: false, reason: 'realpath 失败' }; } + if (!isUnder(realFull, ISOLATION_BASE)) return { ok: false, reason: 'realpath 越出基路径' }; + + // 5.1) session 子路径逃逸校验(修复 link_etc 漏洞): + // 上面只校验了 session 名本身,AI 可以在 session 内 ln -s /etc link,再把 cwd + // 指到 /link —— wrapper 的 cd 在父 ns 视图解析符号链接,直接落到 /etc。 + // 这里对 session 之下的每一级做 lstat 拒符号链接 + realpath 确认未离开本 session。 + const relInside = path.relative(path.join(DEFAULT_CWD, sessionName), cwd); + if (relInside !== '') { + // 从真实 session 根逐段下钻;curReal 始终是当前已验证前缀的真实路径。 + // 某级不存在时:符号链接不可能藏在其中,后续各级必然也不存在(ENOENT), + // 直接交给 wrapper 在子 ns 里 mkdir -p(只落在本会话 bind 内)。 + let curReal = realFull; + const segs = relInside.split(path.sep); + for (let i = 0; i < segs.length; i++) { + const seg = segs[i]; + if (!seg || seg === '.' || seg === '..') return { ok: false, reason: '非法路径段' }; + const probe = path.join(curReal, seg); + let ss; + try { ss = fs.lstatSync(probe); } catch (_) { break; } // 不存在 → 停止校验,交 wrapper 创建 + if (ss.isSymbolicLink()) return { ok: false, reason: 'session 子路径不得含符号链接' }; + if (!ss.isDirectory()) return { ok: false, reason: 'cwd 不是目录' }; + let rr; + try { rr = fs.realpathSync(probe); } catch (_) { return { ok: false, reason: 'realpath 失败' }; } + if (!isUnder(rr, realFull)) return { ok: false, reason: 'realpath 越出 session 边界' }; + curReal = rr; + } + } + + return { + ok: true, cwd, + plan: { + mode: 'session', sessionName, cwd, realSession: realFull, + virtSession: path.join(DEFAULT_CWD, sessionName), + }, + }; + } + + // 6) 以下路径在父 ns 中真实存在,可做完整校验。 + // 深层缺失目录(典型:scratch/<新会话>/子路径)逐级向上找到第一个存在的祖先校验; + // 缺失的尾部由 wrapper 在子 ns 内 mkdir -p(scratch 根已被私有 tmpfs 遮盖,不会落盘)。 + let st; + let exist = cwd; + for (let guard = 0; guard < 32; guard++) { + try { st = fs.lstatSync(exist); break; } catch (_) {} + const up = path.dirname(exist); + if (up === exist) return { ok: false, reason: 'cwd 不存在' }; + exist = up; + } + if (!st) return { ok: false, reason: 'cwd 不存在' }; + if (st.isSymbolicLink()) return { ok: false, reason: 'cwd 不得是符号链接' }; + if (!st.isDirectory()) return { ok: false, reason: 'cwd 不是目录' }; + + // 父链软链检查(从实际存在的最深点往上) + let cur = exist; + for (let guard = 0; guard < 32; guard++) { + let s = null; + try { s = fs.lstatSync(cur); } catch (_) { break; } + if (s && s.isSymbolicLink()) return { ok: false, reason: 'cwd 路径链中存在符号链接' }; + const up = path.dirname(cur); + if (up === cur) break; + cur = up; + } + + try { + const real = fs.realpathSync(exist); // 用实际存在的最深点;缺失尾部由 wrapper 补建 + if (!ROOTS.some(r => isUnder(real, r))) return { ok: false, reason: 'realpath 越界' }; + if (isUnder(real, ISOLATION_BASE)) return { ok: false, reason: 'realpath 命中隔离基路径' }; + } catch (_) { + return { ok: false, reason: 'realpath 失败' }; + } + + // 7) skills 必须确实只读(compose 用 :ro 保证,这里二次确认,避免误挂成 rw) + if (isUnder(cwd, SKILLS_DIR)) { + try { + fs.accessSync(cwd, fs.constants.W_OK); + return { ok: false, reason: 'skills 目录应为只读' }; + } catch (e) { + if (e.code !== 'EROFS' && e.code !== 'EACCES' && e.code !== 'EPERM') throw e; + } + } + + // 8) scratch:私有 tmpfs,不给任何真实数据 + if (isUnder(cwd, SCRATCH_ROOT)) { + const seg = path.relative(SCRATCH_ROOT, cwd).split(path.sep)[0]; + if (!seg || seg === '.' || seg === '..') return { ok: false, reason: '非法 scratch 名' }; + return { ok: true, cwd, plan: { mode: 'scratch', cwd, scratchDir: path.join(SCRATCH_ROOT, seg) } }; + } + + // 9) 其余(如 /workspace/skills/)→ 只跑公共加固 + return { ok: true, cwd, plan: { mode: 'plain', cwd } }; +} + +// ---------- HTTP ---------- function tokenOk(req) { if (!TOKEN) return true; const auth = String(req.headers.authorization || ''); @@ -160,9 +466,8 @@ function tokenOk(req) { function send(res, status, obj) { log.debug('resp', status, brief(JSON.stringify(obj))); - const body = JSON.stringify(obj); res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); - res.end(body); + res.end(JSON.stringify(obj)); } function readJsonBody(req) { @@ -173,35 +478,22 @@ function readJsonBody(req) { if (size > BODY_LIMIT) { reject(new Error('请求体超过 ' + BODY_LIMIT + ' 字节')); req.destroy(); return; } chunks.push(c); }); - req.on('end', () => { try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } catch (e) { reject(new Error('body 不是合法 JSON:' + e.message)); } }); + req.on('end', () => { + try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } + catch (e) { reject(new Error('body 不是合法 JSON:' + e.message)); } + }); req.on('error', reject); }); } -// cwd 白名单校验:解析为绝对路径后必须位于某个 root 的 realpath 之下(含 root 本身)。 -function checkCwd(raw) { - let cwd; - try { cwd = path.resolve(raw); } catch (_) { return null; } - let real; - try { real = fs.realpathSync(cwd); } catch (_) { return null; } // 不存在直接拒绝 - for (const root of ROOTS) { - let realRoot; - try { realRoot = fs.realpathSync(root); } catch (_) { continue; } - if (real === realRoot || real.startsWith(realRoot + path.sep)) return real; - } - return null; -} - function killGroup(entry) { const child = entry.child; - // detached 启动后 child 是组长:对 -pid 发信号可连子进程的子孙一起杀掉 try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) { /* 已退出 */ } } } function sseWrite(res, obj) { log.debug('sse →', brief(JSON.stringify(obj))); - // 客户端断开后 res 已死:实测 Node 20 对 destroyed 的 write 静默丢弃,但不依赖该行为,写前显式拦。 if (res.writableEnded || res.destroyed) return; res.write('data: ' + JSON.stringify(obj) + '\n\n'); } @@ -214,11 +506,12 @@ async function handleExec(req, res) { const command = String(args.command || ''); if (!command.trim()) return send(res, 400, { error: 'command 必填' }); - const rawCwd = args.cwd ? String(args.cwd) : DEFAULT_CWD; // 缺省落任务根 → 下面边界拒绝,等效必填 - const cwd = checkCwd(rawCwd); - if (!cwd) return send(res, 400, { error: 'cwd 不存在或不在白名单目录内:' + rawCwd + '(允许:' + ROOTS.join(', ') + ')' }); - if (REAL_TASK_ROOT && cwd === REAL_TASK_ROOT) { - return send(res, 400, { error: 'cwd 不能是任务根本身(全部会话目录的父目录,在其下执行会暴露所有会话):请在具体会话子目录内执行:' + rawCwd }); + const rawCwd = args.cwd ? String(args.cwd) : DEFAULT_CWD; + + const rc = resolveCwd(rawCwd); + if (!rc.ok) { + log.warn('reject', req.socket.remoteAddress, 'cwd=' + brief(rawCwd, 200), 'reason=' + rc.reason); + return send(res, 400, { error: 'cwd 非法或不在白名单目录内' }); // 不回吐 ROOTS,避免侦察 } let timeout = parseInt(args.timeout_ms, 10); @@ -229,52 +522,65 @@ async function handleExec(req, res) { if (!isFinite(maxChars) || maxChars <= 0) maxChars = DEFAULT_MAX_OUT; maxChars = Math.min(maxChars, DEFAULT_MAX_OUT); - const env = Object.assign({}, process.env); - if (args.env && typeof args.env === 'object') { - for (const [k, v] of Object.entries(args.env)) env[String(k)] = String(v); + // 环境变量白名单 + const env = {}; + for (const key of ['PATH', 'HOME', 'LANG', 'LC_ALL', 'TZ', 'PYTHONUNBUFFERED', + 'PYTHONDONTWRITEBYTECODE', 'PYTHONPYCACHEPREFIX', 'MPLBACKEND']) { + if (process.env[key]) env[key] = process.env[key]; } - // 剥掉鉴权 token(合并后再删,防 args.env 重注):AI 命令拿到 token 即可从容器内回环 POST /exec, - // 以任意(他人会话)cwd 起命令,绕过 per-task 隔离。server 侧比对用的是 TOKEN 常量,不受影响。 - delete env.EXECUTOR_TOKEN; + if (args.env && typeof args.env === 'object') { + for (const [k, v] of Object.entries(args.env)) { + const K = String(k); + if (/^(EXECUTOR_.*|.*TOKEN|.*SECRET|.*PASSWORD|.*KEY)$/i.test(K)) continue; + if (/^(LD_PRELOAD|LD_LIBRARY_PATH|NODE_OPTIONS|NODE_REPL_EXTERNAL_MODULE|PYTHONSTARTUP|GIT_CONFIG_GLOBAL|GIT_CONFIG_SYSTEM|BASH_ENV|ENV|PROMPT_COMMAND|GLOBIGNORE)$/.test(K)) continue; + env[K] = String(v); + } + } + if (!env.PATH) env.PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'; + env.HOME = '/tmp'; // 指向会话私有 tmpfs,不污染镜像层 + env.TMPDIR = '/tmp'; + env.PYTHONDONTWRITEBYTECODE = '1'; + env.PYTHONPYCACHEPREFIX = '/tmp/pycache'; + const script = buildIsolation(command, rc.plan); const id = crypto.randomUUID(); + let child; try { - // 任务根下的命令走 unshare(2) + mount(2):新 mount ns 里用 tmpfs 盖住 /workspace/tasks 只留当前会话目录; - // 新 pid ns(--pid --fork)+ wrapper 重挂 proc,封掉借 /proc/1/ns/mnt nsenter 回原始 ns 的逃逸路径(详见 isolatedCommand)。 - // cwd 在任务根外(如 skill 入口跑在技能目录)时直接 spawn。 - const isolation = isolatedCommand(command, cwd); - if (isolation) { - child = spawn('unshare', ['--mount', '--pid', '--fork', '/bin/sh', '-c', isolation], { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] }); - } else { - child = spawn('/bin/sh', ['-c', command], { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] }); - } + // spawn 的 cwd 用父 ns 下确实存在的 ROOTS[0];真正的目标目录由 wrapper 内部 cd 完成 + //(session 的虚拟视图只存在于子 ns)。--propagation private 防止 bind 反向传播回宿主 ns。 + child = spawn('unshare', ['--mount', '--pid', '--fork', '--propagation', 'private', '/bin/sh', '-c', script], + { cwd: ROOTS[0], env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] }); } catch (e) { - return send(res, 500, { error: 'spawn 失败:' + e.message }); + log.error('spawn 失败', e.message); + return send(res, 500, { error: '执行环境启动失败' }); } - const entry = { child, killedBy: null, started_at: Date.now(), cwd, timer: null }; + const entry = { child, killedBy: null, started_at: Date.now(), cwd: rc.cwd, timer: null }; runs.set(id, entry); - log.info('start', id, 'pid=' + child.pid, 'cwd=' + cwd, 'timeout=' + timeout + 'ms', JSON.stringify(command).slice(0, 200)); + log.info('start', id, 'pid=' + child.pid, 'cwd=' + rc.cwd, 'mode=' + rc.plan.mode, 'timeout=' + timeout + 'ms'); res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no', // nginx 前置时对 SSE 关缓冲(配合 core 的 proxy_buffering off 习惯) + 'X-Accel-Buffering': 'no', }); const ping = setInterval(() => { if (!res.writableEnded && !res.destroyed) res.write(': ping\n\n'); }, PING_MS); - // 先下发 start 事件:core 靠这里的 id 调 DELETE /exec/:id 取消 - sseWrite(res, { type: 'start', id, pid: child.pid, cwd }); + sseWrite(res, { type: 'start', id, pid: child.pid, cwd: rc.cwd }); - // 输出计数:超限后停止下发(truncated),但仍要持续消费流,防子进程因管道满阻塞。 const out = { stdout: 0, stderr: 0, truncated: false }; function streamChunk(kind, chunk) { const key = kind === 'out' ? 'stdout' : 'stderr'; const text = chunk.toString('utf8'); const remain = maxChars - out[key]; if (remain <= 0) { out.truncated = true; return; } - if (text.length > remain) { out.truncated = true; sseWrite(res, { type: kind, chunk: text.slice(0, remain) }); out[key] = maxChars; return; } + if (text.length > remain) { + out.truncated = true; + sseWrite(res, { type: kind, chunk: text.slice(0, remain) }); + out[key] = maxChars; + return; + } out[key] += text.length; sseWrite(res, { type: kind, chunk: text }); } @@ -283,7 +589,6 @@ async function handleExec(req, res) { entry.timer = setTimeout(() => { entry.killedBy = 'timeout'; killGroup(entry); }, timeout); - // core 断开连接(取消/重启):连带杀掉进程,防孤儿。 res.on('close', () => { if (runs.has(id)) { entry.killedBy = entry.killedBy || 'disconnected'; killGroup(entry); } }); @@ -291,9 +596,7 @@ async function handleExec(req, res) { function finish(code) { if (!runs.has(id)) return; clearTimeout(entry.timer); clearInterval(ping); runs.delete(id); - // 清理与日志先行:客户端已断开(destroyed,writableEnded 恒 false)也要留 exit 痕迹; - // 之后不再碰 res:不对已死/已 end 的响应 write(sseWrite 内有同款守卫兜底)也不重复 end()。 - log.info('exit ', id, 'code=' + code, 'killed_by=' + entry.killedBy, 'out=' + out.stdout + 'B err=' + out.stderr + 'B'); + log.info('exit ', id, 'code=' + code, 'killed_by=' + entry.killedBy); if (res.writableEnded || res.destroyed) return; sseWrite(res, { type: 'exit', code, signal: child.signalCode, killed_by: entry.killedBy, @@ -301,13 +604,18 @@ async function handleExec(req, res) { }); res.end(); } - child.on('error', err => { entry.killedBy = entry.killedBy || 'spawn_error'; log.error('spawn error', id, err.message); streamChunk('err', Buffer.from('spawn 失败:' + err.message + '\n')); finish(-1); }); - child.on('close', (code) => finish(entry.killedBy ? -1 : (code === null ? -1 : code))); + child.on('error', err => { + entry.killedBy = entry.killedBy || 'spawn_error'; + log.error('spawn error', id, err.message); + streamChunk('err', Buffer.from('执行环境启动失败\n')); + finish(-1); + }); + child.on('close', code => finish(entry.killedBy ? -1 : (code === null ? -1 : code))); } function handleKill(req, res, id) { const entry = runs.get(id); - if (!entry) return send(res, 404, { error: '没有该执行任务(可能已结束)' }); + if (!entry) return send(res, 404, { error: '没有该执行任务' }); entry.killedBy = 'cancelled'; killGroup(entry); send(res, 200, { ok: true, id }); @@ -318,10 +626,11 @@ const server = http.createServer(async (req, res) => { const url = new URL(req.url, 'http://x'); const seg = url.pathname.split('/').filter(Boolean); - if (url.pathname === '/health') return send(res, 200, { ok: true, time: Date.now(), running: Array.from(runs.entries()).map(([id, e]) => ({ id, pid: e.child.pid, cwd: e.cwd, started_at: e.started_at })) }); + if (url.pathname === '/health') return send(res, 200, { ok: true, time: Date.now() }); + if (!tokenOk(req)) { - log.warn('auth', '拒绝(token 缺失或错误)', req.method, url.pathname); - return send(res, 401, { error: '缺少或错误的 Authorization: Bearer token' }); + log.warn('auth', '拒绝', req.method, url.pathname); + return send(res, 401, { error: '鉴权失败' }); } try { @@ -329,19 +638,24 @@ const server = http.createServer(async (req, res) => { if (req.method === 'DELETE' && seg.length === 2 && seg[0] === 'exec') return handleKill(req, res, seg[1]); } catch (e) { log.error('处理异常:', e.message); - if (!res.headersSent) send(res, 500, { error: e.message }); else res.end(); + if (!res.headersSent) send(res, 500, { error: '内部错误' }); else res.end(); return; } - send(res, 404, { error: '未知路由 ' + req.method + ' ' + url.pathname }); + send(res, 404, { error: '未知路由' }); }); server.listen(PORT, () => { - log.info('listening on ' + PORT + ' roots=' + ROOTS.join(', ') + ' default_cwd=' + DEFAULT_CWD + ' auth=' + (TOKEN ? 'token' : 'off') + ' log_level=' + (process.env.EXECUTOR_LOG_LEVEL || 'info')); + log.info('listening on ' + PORT + + ' roots=' + ROOTS.join(', ') + + ' default_cwd=' + DEFAULT_CWD + + ' isolation_base=' + ISOLATION_BASE + + ' scratch=' + SCRATCH_ROOT + + ' auth=' + (TOKEN ? 'on' : 'off')); + selfCheck(); }); -// 退出前杀掉所有在跑的进程组,防容器停止后遗留 function shutdown(sig) { - log.info('收到 ' + sig + ',停止服务(杀掉 ' + runs.size + ' 个运行中任务)'); + log.info('收到 ' + sig + ',停止服务'); for (const entry of runs.values()) { entry.killedBy = 'shutdown'; killGroup(entry); } server.close(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref();