security.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /**
  2. * 沙箱安全:vm.createContext 求值单元的隔离契约(docs/execution-engine.md 的"The sandbox")。
  3. * 这些脚本按设计**无法**通过 facade typecheck(直接摸 process/import 等),故绕开编译器,把手写的
  4. * lowered 函数体直接喂 harness——vm 契约本身才是被测对象,这是正当做法。
  5. */
  6. import { createInterface } from "node:readline";
  7. import { PassThrough } from "node:stream";
  8. import vm from "node:vm";
  9. import { describe, expect, it } from "vitest";
  10. import { InMemoryJournalStore, type RunSettlement } from "@zcode/dynamic-workflow";
  11. import { CELL_STREAMS_BOOTSTRAP } from "../src/child-cell-streams.js";
  12. import { childMain } from "../src/child-source.js";
  13. import { runWorkflowScript } from "../src/index.js";
  14. import { AutoDriver } from "./auto-driver.js";
  15. import { TEST_CWD } from "./helpers.js";
  16. /** 直接投喂手写 lowered 体(自由标识符仅 `__host`),返回结算。 */
  17. async function runLowered(lowered: string): Promise<RunSettlement> {
  18. const journal = new InMemoryJournalStore();
  19. const driver = new AutoDriver(journal);
  20. return runWorkflowScript({
  21. cwd: TEST_CWD,
  22. lowered,
  23. caps: { maxConcurrency: 4 },
  24. askSpecs: new Map(),
  25. validate: () => [],
  26. makeDriver: (sink) => {
  27. driver.attach(sink);
  28. return driver;
  29. },
  30. timeoutMs: 15000,
  31. });
  32. }
  33. /** 便捷:跑一个直接 return 表达式的沙箱体,取回 artifact。 */
  34. async function evalInSandbox(expr: string): Promise<unknown> {
  35. const settlement = await runLowered(`return ${expr};`);
  36. expect(settlement.status).toBe("completed");
  37. return (settlement as { status: "completed"; artifact: unknown }).artifact;
  38. }
  39. describe("sandbox security — Node globals are absent", () => {
  40. it("process / fetch / require / globalThis.process are undefined", async () => {
  41. expect(await evalInSandbox('typeof process')).toBe("undefined");
  42. expect(await evalInSandbox('typeof fetch')).toBe("undefined");
  43. expect(await evalInSandbox('typeof require')).toBe("undefined");
  44. expect(await evalInSandbox('typeof globalThis.process')).toBe("undefined");
  45. expect(await evalInSandbox('typeof Buffer')).toBe("undefined");
  46. expect(await evalInSandbox('typeof global')).toBe("undefined");
  47. });
  48. it("ES intrinsics are present (curated globals, not a stripped realm)", async () => {
  49. expect(await evalInSandbox('typeof JSON')).toBe("object");
  50. expect(await evalInSandbox('typeof Promise')).toBe("function");
  51. expect(await evalInSandbox('Array.isArray([1,2])')).toBe(true);
  52. });
  53. });
  54. describe("sandbox security — dynamic import throws", () => {
  55. it("import() rejects with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING", async () => {
  56. const result = await evalInSandbox(
  57. '(await (async () => { try { await import("node:fs"); return "NO-THROW"; } catch (e) { return String(e && (e.code || e.name)); } })())',
  58. );
  59. expect(result).toContain("ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING");
  60. });
  61. });
  62. describe("sandbox security — runtime nondeterminism bans (belt)", () => {
  63. it("Date.now() throws", async () => {
  64. expect(await evalInSandbox('(() => { try { Date.now(); return "NO"; } catch (e) { return e.message; } })()')).toContain(
  65. "Date.now()",
  66. );
  67. });
  68. it("argless new Date() throws; new Date(ms) is allowed", async () => {
  69. expect(await evalInSandbox('(() => { try { new Date(); return "NO"; } catch (e) { return e.message; } })()')).toContain(
  70. "argless new Date()",
  71. );
  72. // 带参构造仍可用(只有不确定性的无参形态被禁)。
  73. expect(await evalInSandbox("new Date(0).getTime()")).toBe(0);
  74. });
  75. it("Math.random() throws", async () => {
  76. expect(
  77. await evalInSandbox('(() => { try { Math.random(); return "NO"; } catch (e) { return e.message; } })()'),
  78. ).toContain("Math.random()");
  79. });
  80. });
  81. describe("sandbox security — eval binds to the same curated globals", () => {
  82. it('eval("process") sees undefined; eval("Date.now()") throws', async () => {
  83. // 动态创建的代码也绑定同一套 curated 全局:证明隔离不是靠静态改写脚本文本。
  84. expect(await evalInSandbox('eval("typeof process")')).toBe("undefined");
  85. expect(await evalInSandbox('(() => { try { eval("Date.now()"); return "NO"; } catch (e) { return "THREW"; } })()')).toBe(
  86. "THREW",
  87. );
  88. });
  89. });
  90. // 跨 realm 逃逸回归(execution-engine.md「The vm cell」的边界规则)。每条都是一条曾经真实可用的
  91. // 逃逸路径:脚本拿到任何一个外层 realm 的函数,`.constructor` 就是外层的 Function,
  92. // `Function("return process")()` 即拿到宿主 process——以当前用户权限执行任意命令,且不经任何审批门。
  93. // 断言一律写成「脚本看不到外层 realm 的 Function」,而不是「process 拿不到」,以免漏掉别的出口。
  94. describe("sandbox security — realm boundary: no outer-realm function reaches the script", () => {
  95. /** 在 cell 内把「这个值是否来自外层 realm」判成字符串;`Function` 是 context 自己的。 */
  96. const FOREIGN = "(v) => (typeof v === 'function' || (typeof v === 'object' && v !== null)) && v.constructor !== undefined && v.constructor.constructor !== Function";
  97. it("the global object does not inherit from the outer realm", async () => {
  98. // 曾经:沙箱对象是外层 realm 的 `{}`,context 全局的属性查找落到外层 Object.prototype 上。
  99. expect(
  100. await evalInSandbox(
  101. '(() => { try { return typeof globalThis.constructor.constructor("return process")(); } catch (e) { return "blocked"; } })()',
  102. ),
  103. ).toBe("blocked");
  104. });
  105. it("the transport functions are not reachable from the script", async () => {
  106. // 曾经:宿主箭头函数 `__send` 原样挂在全局上,`__send.constructor` 即外层 Function。
  107. expect(await evalInSandbox("[typeof globalThis.__send, typeof globalThis.__finish]")).toEqual([
  108. "undefined",
  109. "undefined",
  110. ]);
  111. });
  112. it("no global and no __host member is an outer-realm value", async () => {
  113. const foreign = await evalInSandbox(
  114. `(() => {
  115. const foreign = ${FOREIGN};
  116. const hits = [];
  117. for (const k of Object.getOwnPropertyNames(globalThis)) {
  118. let v; try { v = globalThis[k]; } catch (e) { continue; }
  119. if (foreign(v)) hits.push(k);
  120. }
  121. for (const k of Object.keys(__host)) if (foreign(__host[k])) hits.push("__host." + k);
  122. return hits;
  123. })()`,
  124. );
  125. expect(foreign).toEqual([]);
  126. });
  127. it("a failing transport call throws a context-native error (non-string payload)", async () => {
  128. // 曾经:`${line}` 在宿主函数里对 Symbol 求值,抛出的是外层 realm 的 TypeError。
  129. // __emitLine 是 bootstrap 包在传输外面的 cell 侧函数,脚本能直接调到它。
  130. const result = await evalInSandbox(
  131. `(() => { const foreign = ${FOREIGN}; try { __emitLine(Symbol("x")); return "no-throw"; } catch (e) { return foreign(e) ? "FOREIGN" : "native"; } })()`,
  132. );
  133. expect(result).not.toBe("FOREIGN");
  134. });
  135. it("the outer realm never calls a function the script swapped in", async () => {
  136. // 曾经:外层每次都按 `sandbox.__deliver(line)` 现取现调,`this` 是外层的沙箱对象;脚本换掉
  137. // __deliver 就能拿到它。现在外层在脚本运行前就取走三个入口,之后对全局的改写不起作用。
  138. const result = await evalInSandbox(
  139. `await (async () => {
  140. const foreign = ${FOREIGN};
  141. const seen = [];
  142. globalThis.__deliver = function () { seen.push(foreign(this) ? "FOREIGN-this" : "called"); };
  143. globalThis.__checkStalled = function () { seen.push(foreign(this) ? "FOREIGN-this" : "called"); return false; };
  144. const paths = await __host.worldRead("world-read#1", "glob", ["*"]);
  145. return { paths, seen };
  146. })()`,
  147. );
  148. expect(result).toEqual({ paths: [], seen: [] });
  149. });
  150. it("the outer realm never calls then() on a cell promise", async () => {
  151. // 曾经:外层对 __execute 返回的 promise 调 `.then(hostFn, hostFn)`;脚本先改写
  152. // Promise.prototype.then,就能收到这两个宿主函数。
  153. const result = await evalInSandbox(
  154. `await (async () => {
  155. const foreign = ${FOREIGN};
  156. const origThen = Promise.prototype.then;
  157. let leaked = "none";
  158. Promise.prototype.then = function (a, b) {
  159. if (foreign(a) || foreign(b)) leaked = "host";
  160. return origThen.call(this, a, b);
  161. };
  162. // 外层的 .then 调用(若有)发生在 __execute 同步返回之后、微任务之前。
  163. await null;
  164. await __host.worldRead("world-read#1", "glob", ["*"]);
  165. Promise.prototype.then = origThen;
  166. return leaked;
  167. })()`,
  168. );
  169. expect(result).toBe("none");
  170. });
  171. });
  172. describe("sandbox security — realm boundary: stack overflow at the transport", () => {
  173. it("a stack overflow on entry to the transport throws a context-native error", async () => {
  174. // 曾经:在栈将满时调用宿主函数,栈溢出的 RangeError 生成于外层 realm。
  175. // 这条直接驱动 childMain 而不走真子进程:溢出也可能落在真 stdout 管道流的内部,把流写坏,
  176. // run 于是以 interrupted 告终(脚本只坑了自己,不泄漏任何东西),结果就读不回来了。
  177. // 这里换成最简的 stdout,让探针结果稳定回传。
  178. const lines: string[] = [];
  179. await childMain({
  180. vm,
  181. createInterface,
  182. stdin: new PassThrough(),
  183. stdout: {
  184. write: (chunk: string) => lines.push(chunk),
  185. },
  186. streamsBootstrap: CELL_STREAMS_BOOTSTRAP,
  187. payload: {
  188. run: { id: "run" },
  189. maxOldSpaceSizeMb: 256,
  190. lowered: `
  191. const foreign = (v) => (typeof v === "function" || (typeof v === "object" && v !== null)) && v.constructor !== undefined && v.constructor.constructor !== Function;
  192. // 预先序列化:栈将满时 JSON.stringify 自己就会先溢出,探不到传输入口。
  193. const line = JSON.stringify({ kind: "event", type: "log", message: "probe" });
  194. let probes = 0;
  195. let hits = 0;
  196. let transportThrows = 0;
  197. function dive() {
  198. try { dive(); } catch (e) {
  199. if (foreign(e)) hits++;
  200. if (probes >= 64) return;
  201. probes++;
  202. try { __emitLine(line); } catch (e2) { transportThrows++; if (foreign(e2)) hits++; }
  203. // 重新抛出,让上一帧也探一次:每往回一帧栈余量多一点,总有一次溢出落在传输入口上。
  204. throw e;
  205. }
  206. }
  207. dive();
  208. return { probes, hits, transportThrows };`,
  209. },
  210. });
  211. const complete = JSON.parse(lines.at(-1) ?? "null") as { kind: string; ok: boolean; value: unknown };
  212. expect(complete).toMatchObject({ kind: "complete", ok: true });
  213. const value = complete.value as { probes: number; hits: number; transportThrows: number };
  214. expect(value.probes).toBe(64);
  215. // 至少一次溢出真的落在了传输上,否则这条测试什么也没证明。
  216. expect(value.transportThrows).toBeGreaterThan(0);
  217. expect(value.hits).toBe(0);
  218. });
  219. });