security.test.ts 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * 沙箱安全:vm.createContext 求值单元的隔离契约(docs/execution-engine.md 的"The sandbox")。
  3. * 这些脚本按设计**无法**通过 facade typecheck(直接摸 process/import 等),故绕开编译器,把手写的
  4. * lowered 函数体直接喂 harness——vm 契约本身才是被测对象,这是正当做法。
  5. */
  6. import { describe, expect, it } from "vitest";
  7. import { InMemoryJournalStore, type RunSettlement } from "@zcode/dynamic-workflow";
  8. import { runWorkflowScript } from "../src/index.js";
  9. import { AutoDriver } from "./auto-driver.js";
  10. import { TEST_CWD } from "./helpers.js";
  11. /** 直接投喂手写 lowered 体(自由标识符仅 `__host`),返回结算。 */
  12. async function runLowered(lowered: string): Promise<RunSettlement> {
  13. const journal = new InMemoryJournalStore();
  14. const driver = new AutoDriver(journal);
  15. return runWorkflowScript({
  16. cwd: TEST_CWD,
  17. lowered,
  18. caps: { maxConcurrency: 4 },
  19. askSpecs: new Map(),
  20. validate: () => [],
  21. makeDriver: (sink) => {
  22. driver.attach(sink);
  23. return driver;
  24. },
  25. timeoutMs: 15000,
  26. });
  27. }
  28. /** 便捷:跑一个直接 return 表达式的沙箱体,取回 artifact。 */
  29. async function evalInSandbox(expr: string): Promise<unknown> {
  30. const settlement = await runLowered(`return ${expr};`);
  31. expect(settlement.status).toBe("completed");
  32. return (settlement as { status: "completed"; artifact: unknown }).artifact;
  33. }
  34. describe("sandbox security — Node globals are absent", () => {
  35. it("process / fetch / require / globalThis.process are undefined", async () => {
  36. expect(await evalInSandbox('typeof process')).toBe("undefined");
  37. expect(await evalInSandbox('typeof fetch')).toBe("undefined");
  38. expect(await evalInSandbox('typeof require')).toBe("undefined");
  39. expect(await evalInSandbox('typeof globalThis.process')).toBe("undefined");
  40. expect(await evalInSandbox('typeof Buffer')).toBe("undefined");
  41. expect(await evalInSandbox('typeof global')).toBe("undefined");
  42. });
  43. it("ES intrinsics are present (curated globals, not a stripped realm)", async () => {
  44. expect(await evalInSandbox('typeof JSON')).toBe("object");
  45. expect(await evalInSandbox('typeof Promise')).toBe("function");
  46. expect(await evalInSandbox('Array.isArray([1,2])')).toBe(true);
  47. });
  48. });
  49. describe("sandbox security — dynamic import throws", () => {
  50. it("import() rejects with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING", async () => {
  51. const result = await evalInSandbox(
  52. '(await (async () => { try { await import("node:fs"); return "NO-THROW"; } catch (e) { return String(e && (e.code || e.name)); } })())',
  53. );
  54. expect(result).toContain("ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING");
  55. });
  56. });
  57. describe("sandbox security — runtime nondeterminism bans (belt)", () => {
  58. it("Date.now() throws", async () => {
  59. expect(await evalInSandbox('(() => { try { Date.now(); return "NO"; } catch (e) { return e.message; } })()')).toContain(
  60. "Date.now()",
  61. );
  62. });
  63. it("argless new Date() throws; new Date(ms) is allowed", async () => {
  64. expect(await evalInSandbox('(() => { try { new Date(); return "NO"; } catch (e) { return e.message; } })()')).toContain(
  65. "argless new Date()",
  66. );
  67. // 带参构造仍可用(只有不确定性的无参形态被禁)。
  68. expect(await evalInSandbox("new Date(0).getTime()")).toBe(0);
  69. });
  70. it("Math.random() throws", async () => {
  71. expect(
  72. await evalInSandbox('(() => { try { Math.random(); return "NO"; } catch (e) { return e.message; } })()'),
  73. ).toContain("Math.random()");
  74. });
  75. });
  76. describe("sandbox security — eval binds to the same curated globals", () => {
  77. it('eval("process") sees undefined; eval("Date.now()") throws', async () => {
  78. // 动态创建的代码也绑定同一套 curated 全局:证明隔离不是靠静态改写脚本文本。
  79. expect(await evalInSandbox('eval("typeof process")')).toBe("undefined");
  80. expect(await evalInSandbox('(() => { try { eval("Date.now()"); return "NO"; } catch (e) { return "THREW"; } })()')).toBe(
  81. "THREW",
  82. );
  83. });
  84. });