@buildanagent/harness 0.1.0-alpha.28 → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +152 -5
  2. package/dist/context/file-spill.d.ts +11 -1
  3. package/dist/context/file-spill.js +23 -8
  4. package/dist/context/file-spill.js.map +1 -1
  5. package/dist/context/spill.d.ts +5 -1
  6. package/dist/context/spill.js +6 -2
  7. package/dist/context/spill.js.map +1 -1
  8. package/dist/credentials/addresses.d.ts +11 -0
  9. package/dist/credentials/addresses.js +41 -2
  10. package/dist/credentials/addresses.js.map +1 -1
  11. package/dist/credentials/allowlist.d.ts +22 -2
  12. package/dist/credentials/allowlist.js +74 -17
  13. package/dist/credentials/allowlist.js.map +1 -1
  14. package/dist/credentials/egress-policy.d.ts +69 -0
  15. package/dist/credentials/egress-policy.js +170 -0
  16. package/dist/credentials/egress-policy.js.map +1 -0
  17. package/dist/credentials/egress-proxy.d.ts +13 -1
  18. package/dist/credentials/egress-proxy.js +179 -11
  19. package/dist/credentials/egress-proxy.js.map +1 -1
  20. package/dist/credentials/git-route.d.ts +68 -0
  21. package/dist/credentials/git-route.js +288 -0
  22. package/dist/credentials/git-route.js.map +1 -0
  23. package/dist/credentials/index.d.ts +5 -1
  24. package/dist/credentials/index.js +5 -1
  25. package/dist/credentials/index.js.map +1 -1
  26. package/dist/credentials/scrub.d.ts +7 -0
  27. package/dist/credentials/scrub.js +22 -0
  28. package/dist/credentials/scrub.js.map +1 -1
  29. package/dist/errors.d.ts +14 -7
  30. package/dist/errors.js +13 -6
  31. package/dist/errors.js.map +1 -1
  32. package/dist/sandbox/base.d.ts +11 -1
  33. package/dist/sandbox/base.js +14 -0
  34. package/dist/sandbox/base.js.map +1 -1
  35. package/dist/sandbox/docker/index.d.ts +8 -2
  36. package/dist/sandbox/docker/index.js +63 -14
  37. package/dist/sandbox/docker/index.js.map +1 -1
  38. package/dist/sandbox/errors.d.ts +30 -2
  39. package/dist/sandbox/errors.js +36 -1
  40. package/dist/sandbox/errors.js.map +1 -1
  41. package/dist/sandbox/escalation-table.d.ts +38 -0
  42. package/dist/sandbox/escalation-table.js +95 -0
  43. package/dist/sandbox/escalation-table.js.map +1 -0
  44. package/dist/sandbox/escalation.d.ts +191 -0
  45. package/dist/sandbox/escalation.js +370 -0
  46. package/dist/sandbox/escalation.js.map +1 -0
  47. package/dist/sandbox/host-files.d.ts +2 -0
  48. package/dist/sandbox/host-files.js +10 -0
  49. package/dist/sandbox/host-files.js.map +1 -1
  50. package/dist/sandbox/index.d.ts +9 -4
  51. package/dist/sandbox/index.js +8 -3
  52. package/dist/sandbox/index.js.map +1 -1
  53. package/dist/sandbox/policy.d.ts +49 -0
  54. package/dist/sandbox/policy.js +149 -0
  55. package/dist/sandbox/policy.js.map +1 -0
  56. package/dist/sandbox/process.js +1 -1
  57. package/dist/sandbox/process.js.map +1 -1
  58. package/dist/sandbox/srt/index.d.ts +5 -2
  59. package/dist/sandbox/srt/index.js +27 -8
  60. package/dist/sandbox/srt/index.js.map +1 -1
  61. package/dist/sandbox/srt/settings.d.ts +17 -5
  62. package/dist/sandbox/srt/settings.js +53 -0
  63. package/dist/sandbox/srt/settings.js.map +1 -1
  64. package/dist/sandbox/types.d.ts +41 -4
  65. package/dist/sandbox/types.js.map +1 -1
  66. package/dist/sandbox/widen.d.ts +10 -0
  67. package/dist/sandbox/widen.js +150 -0
  68. package/dist/sandbox/widen.js.map +1 -0
  69. package/dist/session/approvals.d.ts +30 -1
  70. package/dist/session/approvals.js +12 -4
  71. package/dist/session/approvals.js.map +1 -1
  72. package/dist/session/code-call.d.ts +15 -1
  73. package/dist/session/code-call.js +2 -1
  74. package/dist/session/code-call.js.map +1 -1
  75. package/dist/session/escalation-log.d.ts +65 -0
  76. package/dist/session/escalation-log.js +84 -0
  77. package/dist/session/escalation-log.js.map +1 -0
  78. package/dist/session/rebuild.js +12 -3
  79. package/dist/session/rebuild.js.map +1 -1
  80. package/dist/testing/fake-sandbox.d.ts +21 -3
  81. package/dist/testing/fake-sandbox.js +157 -8
  82. package/dist/testing/fake-sandbox.js.map +1 -1
  83. package/dist/testing/sandbox-conformance.js +108 -1
  84. package/dist/testing/sandbox-conformance.js.map +1 -1
  85. package/dist/tools/builtins/bash.d.ts +9 -0
  86. package/dist/tools/builtins/bash.js +75 -0
  87. package/dist/tools/builtins/bash.js.map +1 -0
  88. package/dist/tools/builtins/builtins.d.ts +38 -0
  89. package/dist/tools/builtins/builtins.js +48 -0
  90. package/dist/tools/builtins/builtins.js.map +1 -0
  91. package/dist/tools/builtins/descriptions.d.ts +69 -0
  92. package/dist/tools/builtins/descriptions.js +94 -0
  93. package/dist/tools/builtins/descriptions.js.map +1 -0
  94. package/dist/tools/builtins/fetch.d.ts +12 -0
  95. package/dist/tools/builtins/fetch.js +157 -0
  96. package/dist/tools/builtins/fetch.js.map +1 -0
  97. package/dist/tools/builtins/files.d.ts +27 -0
  98. package/dist/tools/builtins/files.js +274 -0
  99. package/dist/tools/builtins/files.js.map +1 -0
  100. package/dist/tools/builtins/paths.d.ts +30 -0
  101. package/dist/tools/builtins/paths.js +62 -0
  102. package/dist/tools/builtins/paths.js.map +1 -0
  103. package/dist/tools/builtins/results.d.ts +15 -0
  104. package/dist/tools/builtins/results.js +31 -0
  105. package/dist/tools/builtins/results.js.map +1 -0
  106. package/dist/tools/builtins/search.d.ts +18 -0
  107. package/dist/tools/builtins/search.js +217 -0
  108. package/dist/tools/builtins/search.js.map +1 -0
  109. package/dist/tools/index.d.ts +6 -2
  110. package/dist/tools/index.js +5 -2
  111. package/dist/tools/index.js.map +1 -1
  112. package/llms.txt +52 -0
  113. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAkDH,4FAA4F;AAC5F,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACnB,IAAI,GAAW,cAAc,CAAC;IACvC,IAAI,CAAmB;IAEhC,YAAY,IAAsB,EAAE,OAAe,EAAE,OAAsB;QACzE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9D,CAAC;CACF;AAED,iFAAiF;AACjF,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,aAAa,CAAC,KAAK,IAAI,CAAC;AACnH,CAAC","sourcesContent":["/**\n * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Two\n * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError` and\n * `SandboxDeniedError`, both in `./sandbox`.\n */\n\n/** Why a `HarnessError` was thrown. */\nexport type HarnessErrorCode =\n | \"sandbox_unavailable\"\n | \"sandbox_denied\"\n | \"sandbox_disposed\"\n | \"sandbox_not_found\"\n | \"sandbox_io_failed\"\n | \"egress_denied\"\n | \"invalid_egress_options\"\n | \"unsafe_sandbox_not_acknowledged\"\n | \"invalid_sandbox_options\"\n | \"invalid_spawn_env\"\n | \"duplicate_tool\"\n | \"invalid_tool_registration\"\n | \"invalid_permission_config\"\n | \"invalid_lock_options\"\n | \"session_locked\"\n | \"session_read_only\"\n | \"entry_not_found\"\n | \"unsupported_format\"\n | \"invalid_turn_options\"\n | \"invalid_context_options\"\n | \"invalid_dispatcher_options\"\n | \"invalid_transport_options\"\n | \"spill_unavailable\"\n | \"invalid_extension\"\n | \"extension_hash_mismatch\"\n | \"approval_not_pending\"\n | \"approval_unavailable\"\n | \"sticky_refused\"\n | \"approval_reuse_refused\"\n | \"approver_is_requester\"\n | \"approval_refused\"\n | \"invalid_code_call\"\n | \"invalid_key_store\"\n | \"key_store_read_only\"\n | \"session_conflict\"\n | \"entry_too_large\"\n | \"invalid_session_entry\"\n | \"invalid_session_key\"\n | \"invalid_retention\"\n | \"session_corrupt\"\n | \"invalid_completion_config\"\n | \"invalid_mcp_config\"\n | \"mcp_connect_failed\"\n | \"mcp_tool_list_refused\"\n | \"mcp_call_failed\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst HARNESS_ERROR = Symbol.for(\"buildanagent.harness.HarnessError\");\n\n/**\n * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.\n * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file\n * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.\n * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is\n * neither a missing file nor a denial. `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:\n * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:\n * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry\n * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration\n * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.\n * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).\n * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:\n * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.\n * `entry_not_found`: an entry id is in no file of the session. `unsupported_format`: a session file's format can't be\n * read or migrated, its header names none, or the store can't read it as written. `invalid_turn_options`: a turn's\n * options can't be used, such as a tool allowlist that names a tool the registry lacks, or a hook that changed the\n * model inside a turn.\n * `invalid_context_options`: a context policy's setting can't be used, such as a write cap with no spill store or a mask\n * step of zero. `invalid_dispatcher_options`: a dispatcher's setting can't be used, such as a queue size of zero.\n * `invalid_transport_options`: a transport's setting can't be used, such as a write timeout of zero.\n * `spill_unavailable`: a spill store can't write, such as the file store on a runtime without Node's file\n * system. `invalid_extension`: an extension has no name or version, two share a name, or a project extension's module does not export one. `extension_hash_mismatch`: a project extension's files hash differently from the lock file, or the lock file does not list it. `approval_not_pending`: a resolution names a request that is not waiting.\n * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky\n * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids\n * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code\n * call's signed request failed its check when it was resolved, so nothing ran and nothing was written.\n * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a\n * tool the registry lacks or a compensation that names no call that ran. `invalid_key_store`: a key\n * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store\n * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did\n * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).\n * `invalid_session_entry`: an entry is not valid or is out of place, such as a first entry that is not a header.\n * `invalid_session_key`: a user or session id the store can't use. `invalid_retention`: a retention period that is not a\n * positive number, or an action other than `archive` and `purge`. `session_corrupt`: a log file has a bad line before\n * its last line. `invalid_completion_config`: `.agents/harness.json` is not JSON, or its `completionChecks` is not a list\n * of commands. `invalid_mcp_config`: an MCP server's configuration can't be used, such as a name outside the allowed\n * characters or two servers with one name. `mcp_connect_failed`: an MCP server did not start, did not finish the\n * handshake in time, or closed before it did (`McpError`). `mcp_tool_list_refused`: an MCP server listed tools the\n * harness refuses, such as two with one name, so none of its tools was registered (`McpError`). `mcp_call_failed`: an\n * MCP tool call ended without a result, because the server closed, timed out, asked for input or answered with an\n * error (`McpError`).\n */\nexport class HarnessError extends Error {\n override readonly name: string = \"HarnessError\";\n readonly code: HarnessErrorCode;\n\n constructor(code: HarnessErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, HARNESS_ERROR, { value: true });\n }\n}\n\n/** True for a `HarnessError`, including one from another copy of the package. */\nexport function isHarnessError(error: unknown): error is HarnessError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[HARNESS_ERROR] === true;\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAsDH,4FAA4F;AAC5F,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACnB,IAAI,GAAW,cAAc,CAAC;IACvC,IAAI,CAAmB;IAEhC,YAAY,IAAsB,EAAE,OAAe,EAAE,OAAsB;QACzE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9D,CAAC;CACF;AAED,iFAAiF;AACjF,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,aAAa,CAAC,KAAK,IAAI,CAAC;AACnH,CAAC","sourcesContent":["/**\n * `HarnessError`: the harness's error for programmer errors and for a sandbox that can't do what it was asked. Four\n * subclasses keep their own names for the cases callers catch by class: `SandboxUnavailableError`,\n * `SandboxDeniedError`, `SandboxPolicyMismatchError` and `SandboxUnsupportedError`, all in `./sandbox`.\n */\n\n/** Why a `HarnessError` was thrown. */\nexport type HarnessErrorCode =\n | \"sandbox_unavailable\"\n | \"sandbox_denied\"\n | \"sandbox_disposed\"\n | \"sandbox_not_found\"\n | \"sandbox_io_failed\"\n | \"sandbox_policy_mismatch\"\n | \"sandbox_unsupported\"\n | \"egress_denied\"\n | \"invalid_egress_options\"\n | \"unsafe_sandbox_not_acknowledged\"\n | \"invalid_sandbox_options\"\n | \"invalid_spawn_env\"\n | \"duplicate_tool\"\n | \"invalid_tool_registration\"\n | \"invalid_tool_options\"\n | \"invalid_permission_config\"\n | \"invalid_lock_options\"\n | \"session_locked\"\n | \"session_read_only\"\n | \"entry_not_found\"\n | \"unsupported_format\"\n | \"invalid_turn_options\"\n | \"invalid_context_options\"\n | \"invalid_dispatcher_options\"\n | \"invalid_transport_options\"\n | \"spill_unavailable\"\n | \"invalid_extension\"\n | \"extension_hash_mismatch\"\n | \"approval_not_pending\"\n | \"approval_unavailable\"\n | \"sticky_refused\"\n | \"approval_reuse_refused\"\n | \"approver_is_requester\"\n | \"approval_refused\"\n | \"invalid_code_call\"\n | \"invalid_escalation\"\n | \"invalid_key_store\"\n | \"key_store_read_only\"\n | \"session_conflict\"\n | \"entry_too_large\"\n | \"invalid_session_entry\"\n | \"invalid_session_key\"\n | \"invalid_retention\"\n | \"session_corrupt\"\n | \"invalid_completion_config\"\n | \"invalid_mcp_config\"\n | \"mcp_connect_failed\"\n | \"mcp_tool_list_refused\"\n | \"mcp_call_failed\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst HARNESS_ERROR = Symbol.for(\"buildanagent.harness.HarnessError\");\n\n/**\n * Thrown for a mistake in how the harness is called, and for a sandbox that is unavailable or refuses a file operation.\n * `sandbox_unavailable`: a backend can't start (`SandboxUnavailableError`). `sandbox_denied`: the policy refused a file\n * read or write (`SandboxDeniedError`). `sandbox_disposed`: the sandbox was disposed before the call.\n * `sandbox_not_found`: a file to read doesn't exist. `sandbox_io_failed`: a file call failed for a reason that is\n * neither a missing file nor a denial. `sandbox_policy_mismatch`: the policy a backend read back after it provisioned or\n * resumed a sandbox differs from the one requested (`SandboxPolicyMismatchError`). `sandbox_unsupported`: a sandbox was\n * asked to resume, snapshot or pause on a backend that lacks the capability (`SandboxUnsupportedError`).\n * `unsafe_sandbox_not_acknowledged`: `noneSandbox()` was called without `unsafe:\n * true`. `invalid_sandbox_options`: a sandbox option, manifest or command is unusable. `invalid_spawn_env`:\n * `spawnEnv()` was given a name or value that can't be part of a clean environment. `duplicate_tool`: a tool registry\n * already holds a tool or alias by that name (`DuplicateToolError`). `invalid_tool_registration`: a tool registration\n * or a registry option is unusable, such as a name that breaks the canonical rule or an unknown source.\n * `invalid_tool_options`: the built-in tools were given a workspace root or a policy root that is not an absolute path.\n * `invalid_permission_config`: an allow rule makes the host callback unreachable (`PermissionConfigError`).\n * `invalid_lock_options`: a file lock was given a lease, renewal interval or host name it can't use. `session_locked`:\n * another writer holds the session. `session_read_only`: a session opened without a lock was asked to write.\n * `entry_not_found`: an entry id is in no file of the session. `unsupported_format`: a session file's format can't be\n * read or migrated, its header names none, or the store can't read it as written. `invalid_turn_options`: a turn's\n * options can't be used, such as a tool allowlist that names a tool the registry lacks, or a hook that changed the\n * model inside a turn.\n * `invalid_context_options`: a context policy's setting can't be used, such as a write cap with no spill store or a mask\n * step of zero. `invalid_dispatcher_options`: a dispatcher's setting can't be used, such as a queue size of zero.\n * `invalid_transport_options`: a transport's setting can't be used, such as a write timeout of zero.\n * `spill_unavailable`: a spill store can't write, such as the file store on a runtime without Node's file\n * system. `invalid_extension`: an extension has no name or version, two share a name, or a project extension's module does not export one. `extension_hash_mismatch`: a project extension's files hash differently from the lock file, or the lock file does not list it. `approval_not_pending`: a resolution names a request that is not waiting.\n * `approval_unavailable`: the harness has no signer, so no approval can be checked. `sticky_refused`: a sticky\n * allowance would cover an interpreter prefix or a secret. `approval_reuse_refused`: the tool's `approvalReuse` forbids\n * a sticky or grouped answer. `approver_is_requester`: the approver is the one who asked. `approval_refused`: a code\n * call's or a sandbox escalation's signed request failed its check when it was resolved, or a classifier tried to\n * approve an escalation, so nothing ran and nothing was written.\n * `invalid_code_call`: `Harness.invokeTool()` or a code call's resolution was given something it can't run, such as a\n * tool the registry lacks or a compensation that names no call that ran. `invalid_escalation`: `escalation()` or one\n * of its calls was given something it can't use, such as a granular policy with no rules, or an edge the escalation\n * table does not list. `invalid_key_store`: a key\n * file or key secret is unreadable or malformed, or a key file is readable by others. `key_store_read_only`: a key store\n * with no `rotate()` or `prune()` was asked to rotate or prune. `session_conflict`: an append found the log in a state it did\n * not expect (`ConflictError`). `entry_too_large`: an entry is over the store's size bound (`EntryTooLargeError`).\n * `invalid_session_entry`: an entry is not valid or is out of place, such as a first entry that is not a header.\n * `invalid_session_key`: a user or session id the store can't use. `invalid_retention`: a retention period that is not a\n * positive number, or an action other than `archive` and `purge`. `session_corrupt`: a log file has a bad line before\n * its last line. `invalid_completion_config`: `.agents/harness.json` is not JSON, or its `completionChecks` is not a list\n * of commands. `invalid_mcp_config`: an MCP server's configuration can't be used, such as a name outside the allowed\n * characters or two servers with one name. `mcp_connect_failed`: an MCP server did not start, did not finish the\n * handshake in time, or closed before it did (`McpError`). `mcp_tool_list_refused`: an MCP server listed tools the\n * harness refuses, such as two with one name, so none of its tools was registered (`McpError`). `mcp_call_failed`: an\n * MCP tool call ended without a result, because the server closed, timed out, asked for input or answered with an\n * error (`McpError`).\n */\nexport class HarnessError extends Error {\n override readonly name: string = \"HarnessError\";\n readonly code: HarnessErrorCode;\n\n constructor(code: HarnessErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, HARNESS_ERROR, { value: true });\n }\n}\n\n/** True for a `HarnessError`, including one from another copy of the package. */\nexport function isHarnessError(error: unknown): error is HarnessError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[HARNESS_ERROR] === true;\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { type HostFiles } from "./host-files.js";
2
+ import { APPLY_STOPS } from "./policy.js";
2
3
  import { type NodeModules } from "./process.js";
3
- import type { ExecOptions, ExecResult, Sandbox } from "./types.js";
4
+ import type { ExecOptions, ExecResult, Sandbox, SandboxClient, SandboxPolicy, SandboxStop } from "./types.js";
4
5
  /** The state a backend's sandbox is built on. */
5
6
  export interface BackendBase {
6
7
  readonly modules: NodeModules;
@@ -12,6 +13,7 @@ export interface BackendBase {
12
13
  export declare abstract class BackendSandbox implements Sandbox {
13
14
  private disposed;
14
15
  private disposing;
16
+ private applied;
15
17
  private readonly base;
16
18
  protected constructor(base: BackendBase);
17
19
  /** Throws `sandbox_disposed` once `dispose()` has been called. */
@@ -26,6 +28,14 @@ export declare abstract class BackendSandbox implements Sandbox {
26
28
  readonly cwd: string;
27
29
  } | ExecResult>;
28
30
  abstract exec(command: readonly string[], options: ExecOptions): Promise<ExecResult>;
31
+ /** Reads back the policy this sandbox applies, from what the backend wrote or will pass to each command. */
32
+ abstract readBack(): Promise<SandboxPolicy>;
33
+ /** The stops the applied policy delivers, set by `confirm()` when the sandbox is provisioned. */
34
+ get stops(): readonly SandboxStop[];
35
+ /** Reads the policy back and checks it against `requested`, or disposes the sandbox and throws on a difference. */
36
+ confirm(client: SandboxClient, requested: SandboxPolicy): Promise<void>;
37
+ /** Sets the stops a resumed sandbox's confirmed policy delivers, for `resumeSandbox()`. */
38
+ [APPLY_STOPS](stops: readonly SandboxStop[]): void;
29
39
  readFile(path: string): Promise<Uint8Array>;
30
40
  writeFile(path: string, data: Uint8Array): Promise<void>;
31
41
  /** Stops what is running and cleans up. Every call gets the first call's promise, so a second caller waits too. */
@@ -4,11 +4,13 @@
4
4
  */
5
5
  import { HarnessError } from "../errors.js";
6
6
  import { workingDirectory } from "./host-files.js";
7
+ import { APPLY_STOPS, confirmPolicy } from "./policy.js";
7
8
  import { checkCommand, checkOptions } from "./process.js";
8
9
  /** A sandbox that checks a command the same way, reads and writes files in the host, and disposes once. */
9
10
  export class BackendSandbox {
10
11
  disposed = false;
11
12
  disposing;
13
+ applied = [];
12
14
  base;
13
15
  constructor(base) {
14
16
  this.base = base;
@@ -40,6 +42,18 @@ export class BackendSandbox {
40
42
  }
41
43
  return located;
42
44
  }
45
+ /** The stops the applied policy delivers, set by `confirm()` when the sandbox is provisioned. */
46
+ get stops() {
47
+ return this.applied;
48
+ }
49
+ /** Reads the policy back and checks it against `requested`, or disposes the sandbox and throws on a difference. */
50
+ async confirm(client, requested) {
51
+ this.applied = await confirmPolicy(client, this, requested);
52
+ }
53
+ /** Sets the stops a resumed sandbox's confirmed policy delivers, for `resumeSandbox()`. */
54
+ [APPLY_STOPS](stops) {
55
+ this.applied = stops;
56
+ }
43
57
  async readFile(path) {
44
58
  this.live();
45
59
  return this.base.files.readFile(path);
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/sandbox/base.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAkB,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,YAAY,EAAoB,MAAM,cAAc,CAAC;AAW5E,2GAA2G;AAC3G,MAAM,OAAgB,cAAc;IAC1B,QAAQ,GAAG,KAAK,CAAC;IACjB,SAAS,CAA4B;IAC5B,IAAI,CAAc;IAEnC,YAAsB,IAAiB;QACrC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,kEAAkE;IACxD,IAAI;QACZ,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,YAAY,CAAC,kBAAkB,EAAE,0BAA0B,CAAC,CAAC;IAC5F,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,OAAO,CACrB,OAA0B,EAC1B,OAAoB;QAEpB,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,YAAY,CAAC,OAAO,CAAC,CAAC;QACtB,YAAY,CAAC,OAAO,CAAC,CAAC;QACtB,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,MAAM,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACnF,IAAI,QAAQ,IAAI,OAAO;YAAE,OAAO,OAAO,CAAC;QACxC,2EAA2E;QAC3E,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;QAChC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAC9B,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,sBAAsB,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACrF,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAID,KAAK,CAAC,QAAQ,CAAC,IAAY;QACzB,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,IAAY,EAAE,IAAgB;QAC5C,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC/C,CAAC;IAED,mHAAmH;IACnH,OAAO;QACL,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;YACrB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QACnC,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;CAIF","sourcesContent":["/**\n * What the Node-only backends that mount a workspace share: the checks before a command runs, the file calls, and a\n * `dispose()` that every caller waits on. A backend extends it and adds how it starts a command and what it cleans up.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { type HostFiles, workingDirectory } from \"./host-files.js\";\nimport { checkCommand, checkOptions, type NodeModules } from \"./process.js\";\nimport type { ExecOptions, ExecResult, Sandbox } from \"./types.js\";\n\n/** The state a backend's sandbox is built on. */\nexport interface BackendBase {\n readonly modules: NodeModules;\n /** The workspace's real root. */\n readonly root: string;\n readonly files: HostFiles;\n}\n\n/** A sandbox that checks a command the same way, reads and writes files in the host, and disposes once. */\nexport abstract class BackendSandbox implements Sandbox {\n private disposed = false;\n private disposing: Promise<void> | undefined;\n private readonly base: BackendBase;\n\n protected constructor(base: BackendBase) {\n this.base = base;\n }\n\n /** Throws `sandbox_disposed` once `dispose()` has been called. */\n protected live(): void {\n if (this.disposed) throw new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\");\n }\n\n /**\n * Checks a command and its options, and finds its working directory. It returns the real working directory to run in,\n * or the result that settles the call without running anything: a denial for a directory outside the workspace, and\n * exit code 127 for a first word with `=`, which `env` would read as an assignment, as `none` answers a program it\n * can't find.\n */\n protected async prepare(\n command: readonly string[],\n options: ExecOptions,\n ): Promise<{ readonly cwd: string } | ExecResult> {\n this.live();\n checkCommand(command);\n checkOptions(options);\n options.signal.throwIfAborted();\n const located = await workingDirectory(this.base.modules, this.base.root, options);\n if (\"denied\" in located) return located;\n // The sandbox or the signal may have changed while the folder was checked.\n this.live();\n options.signal.throwIfAborted();\n if (command[0]?.includes(\"=\")) {\n return { exitCode: 127, stdout: \"\", stderr: `command not found: ${command[0]}\\n` };\n }\n return located;\n }\n\n abstract exec(command: readonly string[], options: ExecOptions): Promise<ExecResult>;\n\n async readFile(path: string): Promise<Uint8Array> {\n this.live();\n return this.base.files.readFile(path);\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n this.live();\n return this.base.files.writeFile(path, data);\n }\n\n /** Stops what is running and cleans up. Every call gets the first call's promise, so a second caller waits too. */\n dispose(): Promise<void> {\n if (this.disposing === undefined) {\n this.disposed = true;\n this.disposing = this.shutDown();\n }\n return this.disposing;\n }\n\n /** Ends the commands still running and removes what the sandbox made. It runs once. */\n protected abstract shutDown(): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/sandbox/base.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAkB,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAoB,MAAM,cAAc,CAAC;AAW5E,2GAA2G;AAC3G,MAAM,OAAgB,cAAc;IAC1B,QAAQ,GAAG,KAAK,CAAC;IACjB,SAAS,CAA4B;IACrC,OAAO,GAA2B,EAAE,CAAC;IAC5B,IAAI,CAAc;IAEnC,YAAsB,IAAiB;QACrC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,kEAAkE;IACxD,IAAI;QACZ,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,YAAY,CAAC,kBAAkB,EAAE,0BAA0B,CAAC,CAAC;IAC5F,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,OAAO,CACrB,OAA0B,EAC1B,OAAoB;QAEpB,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,YAAY,CAAC,OAAO,CAAC,CAAC;QACtB,YAAY,CAAC,OAAO,CAAC,CAAC;QACtB,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,MAAM,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACnF,IAAI,QAAQ,IAAI,OAAO;YAAE,OAAO,OAAO,CAAC;QACxC,2EAA2E;QA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nC,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;CAIF","sourcesContent":["/**\n * What the Node-only backends that mount a workspace share: the checks before a command runs, the file calls, and a\n * `dispose()` that every caller waits on. A backend extends it and adds how it starts a command and what it cleans up.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { type HostFiles, workingDirectory } from \"./host-files.js\";\nimport { APPLY_STOPS, confirmPolicy } from \"./policy.js\";\nimport { checkCommand, checkOptions, type NodeModules } from \"./process.js\";\nimport type { ExecOptions, ExecResult, Sandbox, SandboxClient, SandboxPolicy, SandboxStop } from \"./types.js\";\n\n/** The state a backend's sandbox is built on. */\nexport interface BackendBase {\n readonly modules: NodeModules;\n /** The workspace's real root. */\n readonly root: string;\n readonly files: HostFiles;\n}\n\n/** A sandbox that checks a command the same way, reads and writes files in the host, and disposes once. */\nexport abstract class BackendSandbox implements Sandbox {\n private disposed = false;\n private disposing: Promise<void> | undefined;\n private applied: readonly SandboxStop[] = [];\n private readonly base: BackendBase;\n\n protected constructor(base: BackendBase) {\n this.base = base;\n }\n\n /** Throws `sandbox_disposed` once `dispose()` has been called. */\n protected live(): void {\n if (this.disposed) throw new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\");\n }\n\n /**\n * Checks a command and its options, and finds its working directory. It returns the real working directory to run in,\n * or the result that settles the call without running anything: a denial for a directory outside the workspace, and\n * exit code 127 for a first word with `=`, which `env` would read as an assignment, as `none` answers a program it\n * can't find.\n */\n protected async prepare(\n command: readonly string[],\n options: ExecOptions,\n ): Promise<{ readonly cwd: string } | ExecResult> {\n this.live();\n checkCommand(command);\n checkOptions(options);\n options.signal.throwIfAborted();\n const located = await workingDirectory(this.base.modules, this.base.root, options);\n if (\"denied\" in located) return located;\n // The sandbox or the signal may have changed while the folder was checked.\n this.live();\n options.signal.throwIfAborted();\n if (command[0]?.includes(\"=\")) {\n return { exitCode: 127, stdout: \"\", stderr: `command not found: ${command[0]}\\n` };\n }\n return located;\n }\n\n abstract exec(command: readonly string[], options: ExecOptions): Promise<ExecResult>;\n\n /** Reads back the policy this sandbox applies, from what the backend wrote or will pass to each command. */\n abstract readBack(): Promise<SandboxPolicy>;\n\n /** The stops the applied policy delivers, set by `confirm()` when the sandbox is provisioned. */\n get stops(): readonly SandboxStop[] {\n return this.applied;\n }\n\n /** Reads the policy back and checks it against `requested`, or disposes the sandbox and throws on a difference. */\n async confirm(client: SandboxClient, requested: SandboxPolicy): Promise<void> {\n this.applied = await confirmPolicy(client, this, requested);\n }\n\n /** Sets the stops a resumed sandbox's confirmed policy delivers, for `resumeSandbox()`. */\n [APPLY_STOPS](stops: readonly SandboxStop[]): void {\n this.applied = stops;\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n this.live();\n return this.base.files.readFile(path);\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n this.live();\n return this.base.files.writeFile(path, data);\n }\n\n /** Stops what is running and cleans up. Every call gets the first call's promise, so a second caller waits too. */\n dispose(): Promise<void> {\n if (this.disposing === undefined) {\n this.disposed = true;\n this.disposing = this.shutDown();\n }\n return this.disposing;\n }\n\n /** Ends the commands still running and removes what the sandbox made. It runs once. */\n protected abstract shutDown(): Promise<void>;\n}\n"]}
@@ -19,7 +19,11 @@ export interface DockerSandboxOptions {
19
19
  readonly extraReadRoots?: readonly string[];
20
20
  /** Folders that stay read-only inside a write root, such as the session's own log folder. */
21
21
  readonly denyWrite?: readonly string[];
22
- /** A Unix socket on the host that a command may use to reach the hosts its policy allows, mounted at `DOCKER_PROXY_SOCKET_PATH`. */
22
+ /**
23
+ * A Unix socket on the host that a command may use to reach the hosts its policy allows, mounted at
24
+ * `DOCKER_PROXY_SOCKET_PATH`. The proxy on it enforces the allowlist, so start `startEgressProxy()` there with the
25
+ * policy's hosts, such as from `compileEgressPolicy()`; the read-back trusts it to.
26
+ */
23
27
  readonly proxySocket?: string;
24
28
  }
25
29
  /** Where a command finds the proxy socket, when the caller mounts one. */
@@ -30,6 +34,8 @@ export declare const DOCKER_PROXY_SOCKET_PATH = "/run/harness/proxy.sock";
30
34
  * client runs with a clean environment: a `PATH`, a private empty `HOME` and `DOCKER_HOST` when one is set, and never
31
35
  * the parent's environment. The policy's roots, `extraReadRoots`, `denyWrite` and `proxySocket` must be absolute, and
32
36
  * the workspace must lie inside a root. A command whose first word contains `=` resolves with exit code 127, as under
33
- * `none`.
37
+ * `none`. Before it returns, `provision()` reads back the policy its mounts and flags apply and throws
38
+ * `SandboxPolicyMismatchError` on a difference. Without `proxySocket` the container reaches no host, so a policy whose
39
+ * `network.allow` names one is refused. The backend lists no capability: it can't resume, snapshot or pause.
34
40
  */
35
41
  export declare function dockerSandbox(options: DockerSandboxOptions): SandboxClient;
@@ -12,7 +12,7 @@
12
12
  import { HarnessError } from "../../errors.js";
13
13
  import { BackendSandbox } from "../base.js";
14
14
  import { SandboxUnavailableError } from "../errors.js";
15
- import { absolutePath, checkPaths, existing, findOnPath, HostFiles, inside, isProtectedPath, PROTECTED_TOP_LEVEL, realOrSelf, workspaceRoot, } from "../host-files.js";
15
+ import { absolutePath, checkPaths, existing, findOnPath, HostFiles, inside, isProtectedPath, PROTECTED_TOP_LEVEL, realOrSelf, spellings, workspaceRoot, } from "../host-files.js";
16
16
  import { nodeModules, ProcessRunner } from "../process.js";
17
17
  /** Where a command finds the proxy socket, when the caller mounts one. */
18
18
  export const DOCKER_PROXY_SOCKET_PATH = "/run/harness/proxy.sock";
@@ -124,8 +124,8 @@ class DockerSandbox extends BackendSandbox {
124
124
  const created = this.client(this.runArguments(name, located.cwd, command, options.env), CREATE_TIMEOUT_MS);
125
125
  this.track(created);
126
126
  const made = await this.untilStopped(name, created, options);
127
- if ("timedOut" in made)
128
- return made.timedOut;
127
+ if ("expired" in made)
128
+ return made.expired;
129
129
  if (made.exitCode !== 0) {
130
130
  await this.removeContainer(name);
131
131
  return { exitCode: made.exitCode, stdout: "", stderr: made.stderr };
@@ -181,7 +181,7 @@ class DockerSandbox extends BackendSandbox {
181
181
  options.signal.addEventListener("abort", onAbort, { once: true });
182
182
  if (options.timeoutMs !== undefined) {
183
183
  const note = `timed out after ${options.timeoutMs} ms\n`;
184
- timer = setTimeout(() => finish(() => resolve({ timedOut: { exitCode: 124, stdout: "", stderr: note } }), true), options.timeoutMs);
184
+ timer = setTimeout(() => finish(() => resolve({ expired: { exitCode: 124, stdout: "", stderr: note, timedOut: true } }), true), options.timeoutMs);
185
185
  }
186
186
  created.then((result) => finish(() => resolve(result), false), (error) => finish(() => reject(error), false));
187
187
  });
@@ -206,6 +206,43 @@ class DockerSandbox extends BackendSandbox {
206
206
  await new Promise((resolve) => setTimeout(resolve, SWEEP_PAUSE_MS));
207
207
  }
208
208
  }
209
+ /**
210
+ * The policy the mounts and flags apply, which are what every command's container is created with. The network is
211
+ * closed unless the caller mounted a proxy socket, and then the proxy on it enforces the requested allowlist. A
212
+ * read-only mount the request doesn't explain reads back as a read root it didn't ask for.
213
+ *
214
+ * One narrowing is not caught: a write root that the caller's `denyWrite` names exactly is mounted read-only but still
215
+ * reads back as a write root, because the read-back takes the caller's own `denyWrite` as part of the request. So
216
+ * `provision()` accepts it, and nothing in that root is writable inside the container.
217
+ */
218
+ async readBack() {
219
+ this.live();
220
+ const { mounts, names, flags } = this.state;
221
+ const own = mounts.filter((mount) => mount.to !== DOCKER_PROXY_SOCKET_PATH);
222
+ // A write root that the caller's own denyWrite made read-only is still the root the request asked for.
223
+ const granted = (mount) => !mount.readOnly || (names.implicit.has(mount.from) && names.write.has(mount.from));
224
+ const writable = own.filter(granted).map((mount) => mount.from);
225
+ const inWritable = (path) => writable.some((root) => inside(this.state.modules, root, path));
226
+ const readable = (real) => names.missing.has(real) || inWritable(real) || own.some((m) => m.from === real);
227
+ const unexplained = own
228
+ .filter((mount) => mount.readOnly && !names.readReal.includes(mount.from))
229
+ .map((mount) => mount.from)
230
+ .filter((from) => !names.implicit.has(from) && !inWritable(from));
231
+ const closed = flags.join(" ").includes("--network none");
232
+ const proxied = mounts.length !== own.length;
233
+ return {
234
+ readRoots: [
235
+ ...names.requested.readRoots.filter((_, index) => readable(names.readReal[index] ?? "")),
236
+ ...unexplained,
237
+ ],
238
+ writeRoots: writable.flatMap((path) => names.write.get(path) ?? [path]),
239
+ network: !closed
240
+ ? { allow: ["*"], deny: [] }
241
+ : proxied
242
+ ? names.requested.network
243
+ : { allow: [], deny: names.requested.network.deny },
244
+ };
245
+ }
209
246
  async shutDown() {
210
247
  await this.runner.stopAll();
211
248
  await Promise.allSettled([...this.pending]);
@@ -281,19 +318,27 @@ async function planMounts(modules, policy, options) {
281
318
  const denied = denyWrite.filter(underWrite);
282
319
  const protectedPaths = writeRoots.flatMap((root) => PROTECTED_TOP_LEVEL.map((name) => modules.path.join(root, name)));
283
320
  const readOnlyRoots = [...readRoots, ...extra].filter((path) => !underWrite(path));
321
+ // One look at which read roots exist feeds both the mounts and the names, so a folder made in between can't make them
322
+ // disagree.
323
+ const present = await existing(modules, readOnlyRoots);
284
324
  const base = [
285
325
  ...writeRoots.map((from) => ({ from, to: from, readOnly: false })),
286
- ...(await existing(modules, readOnlyRoots)).map((from) => ({ from, to: from, readOnly: true })),
326
+ ...present.map((from) => ({ from, to: from, readOnly: true })),
287
327
  ];
288
- const guarded = [...denied, ...(await existing(modules, protectedPaths))].map((from) => ({
289
- from,
290
- to: from,
291
- readOnly: true,
292
- }));
328
+ const protectedPresent = await existing(modules, protectedPaths);
329
+ const guarded = [...denied, ...protectedPresent].map((from) => ({ from, to: from, readOnly: true }));
330
+ const names = {
331
+ requested: policy,
332
+ readReal: readRoots,
333
+ write: spellings(writeRoots, policy.writeRoots),
334
+ missing: new Set(readOnlyRoots.filter((path) => !present.includes(path))),
335
+ implicit: new Set([...extra, ...denied, ...protectedPresent]),
336
+ };
293
337
  return {
294
338
  base: onePerDestination(base),
295
339
  mounts: onePerDestination([...base, ...guarded]),
296
340
  roots: { read: readRoots, write: writeRoots, denyWrite: denied },
341
+ names,
297
342
  };
298
343
  }
299
344
  /** The `docker run` flags that lock a container down, and limit what it may use. */
@@ -348,11 +393,13 @@ const firstLine = (text) => text.trim().split("\n")[0] ?? "no output";
348
393
  * client runs with a clean environment: a `PATH`, a private empty `HOME` and `DOCKER_HOST` when one is set, and never
349
394
  * the parent's environment. The policy's roots, `extraReadRoots`, `denyWrite` and `proxySocket` must be absolute, and
350
395
  * the workspace must lie inside a root. A command whose first word contains `=` resolves with exit code 127, as under
351
- * `none`.
396
+ * `none`. Before it returns, `provision()` reads back the policy its mounts and flags apply and throws
397
+ * `SandboxPolicyMismatchError` on a difference. Without `proxySocket` the container reaches no host, so a policy whose
398
+ * `network.allow` names one is refused. The backend lists no capability: it can't resume, snapshot or pause.
352
399
  */
353
400
  export function dockerSandbox(options) {
354
401
  checkOptionValues(options);
355
- return {
402
+ const client = {
356
403
  tier: "container",
357
404
  stops: ["mistakes", "exfiltration"],
358
405
  async provision(manifest, policy) {
@@ -368,8 +415,7 @@ export function dockerSandbox(options) {
368
415
  checkPaths(modules, options.denyWrite ?? [], "a denyWrite folder");
369
416
  const folder = await modules.fs.mkdtemp(modules.path.join(modules.os.tmpdir(), "harness-docker-"));
370
417
  try {
371
- const sandbox = await startSandbox({ modules, docker, hostPath, root, folder, manifest, policy, options });
372
- return sandbox;
418
+ return await startSandbox({ modules, docker, hostPath, root, folder, manifest, policy, options, client });
373
419
  }
374
420
  catch (error) {
375
421
  await modules.fs.rm(folder, { recursive: true, force: true });
@@ -377,6 +423,7 @@ export function dockerSandbox(options) {
377
423
  }
378
424
  },
379
425
  };
426
+ return client;
380
427
  }
381
428
  async function startSandbox(input) {
382
429
  const { modules, options } = input;
@@ -416,8 +463,10 @@ async function startSandbox(input) {
416
463
  clientEnv,
417
464
  folder: input.folder,
418
465
  label: `harness.sandbox=harness-${modules.path.basename(input.folder).slice("harness-docker-".length)}`,
466
+ names: plan.names,
419
467
  });
420
468
  await probe(sandbox, options.image);
469
+ await sandbox.confirm(input.client, input.policy);
421
470
  for (const folder of plan.roots.denyWrite)
422
471
  await modules.fs.mkdir(folder, { recursive: true });
423
472
  const encoder = new TextEncoder();
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/sandbox/docker/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EACL,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,SAAS,EACT,MAAM,EACN,eAAe,EACf,mBAAmB,EACnB,UAAU,EACV,aAAa,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAoB,WAAW,EAAsB,aAAa,EAAE,MAAM,eAAe,CAAC;AA2BjG,0EAA0E;AAC1E,MAAM,CAAC,MAAM,wBAAwB,GAAG,yBAAyB,CAAC;AAElE,MAAM,QAAQ,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAW,CAAC;AACtE,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,mEAAmE;AACnE,MAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,yFAAyF;AACzF,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAClC,2HAA2H;AAC3H,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,uEAAuE;AACvE,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,kFAAkF;AAClF,MAAM,aAAa,GAAG,0BAA0B,CAAC;AACjD,oGAAoG;AACpG,MAAM,SAAS,GAAG,cAAc,CAAC;AA0BjC,MAAM,UAAU,GAAG,CAAC,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AC,QAAQ,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,WAAW,CAAC,aAAa,KAAK,sEAAsE,CAAC,CAAC;IAC9G,CAAC;AACH,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/sandbox/docker`: the container-tier backend. Each command runs in its own locked-down\n * container: all capabilities dropped, a read-only root file system, no network, no new privileges, and limits on\n * processes, CPUs and memory. Only the policy's write roots are writable, and only the policy's roots are mounted. It\n * claims `mistakes` and `exfiltration`, never a `hostile_process`: the kernel is shared with the host. Only Linux and a\n * rootful daemon are tested. A backend that can't start throws `SandboxUnavailableError` and runs nothing. It is\n * Node-only.\n *\n * The container has no network, so a command reaches a host only through a proxy socket the caller mounts. The file calls\n * run in the host on the mounted folders, checked by their real path.\n */\nimport { HarnessError } from \"../../errors.js\";\nimport { BackendSandbox } from \"../base.js\";\nimport { SandboxUnavailableError } from \"../errors.js\";\nimport {\n absolutePath,\n checkPaths,\n existing,\n findOnPath,\n HostFiles,\n inside,\n isProtectedPath,\n PROTECTED_TOP_LEVEL,\n realOrSelf,\n workspaceRoot,\n} from \"../host-files.js\";\nimport { type NodeModules, nodeModules, type ProcessResult, ProcessRunner } from \"../process.js\";\nimport type { ExecOptions, ExecResult, Sandbox, SandboxClient, SandboxPolicy, WorkspaceManifest } from \"../types.js\";\n\n/** The options of `dockerSandbox()`. */\nexport interface DockerSandboxOptions {\n /** The image to run, which must already be on the Docker host: `provision()` never pulls. Pin it by digest. */\n readonly image: string;\n /** CPUs a command may use. Defaults to 1. */\n readonly cpus?: number;\n /** Megabytes of memory a command may use, with no swap. Defaults to 1024. */\n readonly memoryMb?: number;\n /** Processes a command may start. Defaults to 256. */\n readonly pidsLimit?: number;\n /** The `docker` executable. Without it the backend finds `docker` on the absolute folders of the host's `PATH`. */\n readonly binary?: string;\n /** The Docker daemon's address. Without it the backend passes the host's `DOCKER_HOST` when it is set. */\n readonly dockerHost?: string;\n /** The user and group a command runs as, as `uid:gid`. Defaults to this process's, so its files stay yours. */\n readonly user?: string;\n /** Folders to read besides the policy's roots, mounted read-only. */\n readonly extraReadRoots?: readonly string[];\n /** Folders that stay read-only inside a write root, such as the session's own log folder. */\n readonly denyWrite?: readonly string[];\n /** A Unix socket on the host that a command may use to reach the hosts its policy allows, mounted at `DOCKER_PROXY_SOCKET_PATH`. */\n readonly proxySocket?: string;\n}\n\n/** Where a command finds the proxy socket, when the caller mounts one. */\nexport const DOCKER_PROXY_SOCKET_PATH = \"/run/harness/proxy.sock\";\n\nconst DEFAULTS = { cpus: 1, memoryMb: 1024, pidsLimit: 256 } as const;\nconst DAEMON_TIMEOUT_MS = 20_000;\n// The longest one call that kills or removes a container may take.\nconst CALL_TIMEOUT_MS = 5000;\n// Creating a container copies the image on some storage drivers, which can take a while.\nconst CREATE_TIMEOUT_MS = 120_000;\n// How long a stopped `docker run` client has to leave on its own, which lets it cancel a container that isn't started yet.\nconst GRACE_MS = 3000;\nconst KILL_ATTEMPTS = 5;\nconst KILL_RETRY_MS = 100;\nconst SWEEP_QUIET_PASSES = 2;\n// The longest the sweep at the end waits for the last container to go.\nconst SWEEP_MAX_MS = 20_000;\nconst SWEEP_PAUSE_MS = 200;\n// A variable name that `env` can set, which is every name a process can be given.\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n// A path in a `--mount` value can't hold a comma or a quote, which that syntax reads as separators.\nconst MOUNTABLE = /^[^,\"\\n\\r]+$/;\n\n/** One bind mount: the real host path, mounted at the same path inside, or at `to`. */\ninterface Mount {\n readonly from: string;\n readonly to: string;\n readonly readOnly: boolean;\n}\n\n/** Everything a provisioned sandbox holds. */\ninterface DockerState {\n readonly modules: NodeModules;\n readonly docker: string;\n readonly image: string;\n readonly root: string;\n readonly files: HostFiles;\n readonly mounts: readonly Mount[];\n readonly flags: readonly string[];\n /** The environment the `docker` client runs with: where to find its programs, and a private empty `HOME`. */\n readonly clientEnv: Readonly<Record<string, string>>;\n /** A private folder that holds the client's `HOME`, removed on dispose. */\n readonly folder: string;\n /** Marks this sandbox's containers, so `dispose()` can find any that a stopped client left behind. */\n readonly label: string;\n}\n\nconst mountFlags = (mount: Mount): string[] => [\n \"--mount\",\n `type=bind,src=${mount.from},dst=${mount.to}${mount.readOnly ? \",readonly\" : \"\"}`,\n];\n\nclass DockerSandbox extends BackendSandbox {\n private started = 0;\n // Whether a creation was left to finish in the background, which a sweep at the end has to catch.\n private abandoned = false;\n // The containers being created, which `dispose()` waits for before it sweeps.\n private readonly pending = new Set<Promise<unknown>>();\n private readonly runner: ProcessRunner;\n // Runs the calls that manage containers, which `dispose()` must not cut short: a `create` that is stopped half way\n // leaves a container behind.\n private readonly manager: ProcessRunner;\n private readonly state: DockerState;\n\n constructor(state: DockerState) {\n super(state);\n this.state = state;\n this.runner = new ProcessRunner(state.modules);\n this.manager = new ProcessRunner(state.modules);\n }\n\n /** Runs the `docker` client with `args` and waits for it, for the calls that manage containers. */\n async client(args: readonly string[], timeoutMs: number) {\n return this.manager.run(\n {\n program: this.state.docker,\n args,\n cwd: this.state.root,\n env: this.state.clientEnv,\n missingProgram: \"reject\",\n },\n { env: {}, signal: new AbortController().signal, timeoutMs },\n );\n }\n\n /** The `docker run` arguments for one command in a container called `name`. */\n private runArguments(name: string, cwd: string, command: readonly string[], env: Readonly<Record<string, string>>) {\n const assignments: string[] = [];\n for (const [variable, value] of Object.entries(env)) {\n if (!VARIABLE_NAME.test(variable)) {\n throw new HarnessError(\"invalid_sandbox_options\", `${JSON.stringify(variable)} is not a variable name`);\n }\n assignments.push(`${variable}=${value}`);\n }\n const { state } = this;\n // `env -i` clears the image's own variables, so the command holds exactly the ones it was given.\n return [\n \"create\",\n \"--rm\",\n \"--name\",\n name,\n \"--label\",\n state.label,\n ...state.flags,\n ...state.mounts.flatMap(mountFlags),\n \"--workdir\",\n cwd,\n \"--entrypoint\",\n \"env\",\n state.image,\n \"-i\",\n // Ends `env`'s options, so a first word that starts with `-` is a program name.\n \"--\",\n ...assignments,\n ...command,\n ];\n }\n\n /** Removes the container if it exists, which is all a container that never started needs. */\n private async removeContainer(name: string): Promise<void> {\n await this.client([\"rm\", \"--force\", name], CALL_TIMEOUT_MS).catch(() => undefined);\n }\n\n /** Kills the container, trying again while the daemon is still creating it, and removes what is left. */\n private async killContainer(name: string): Promise<void> {\n for (let attempt = 0; attempt < KILL_ATTEMPTS; attempt += 1) {\n const result = await this.client([\"kill\", name], CALL_TIMEOUT_MS).catch(() => undefined);\n if (result?.exitCode === 0) break;\n await new Promise((resolve) => setTimeout(resolve, KILL_RETRY_MS));\n }\n await this.removeContainer(name);\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n const prepared = await this.prepare(command, options);\n if (!(\"cwd\" in prepared)) return prepared;\n const located = prepared;\n const { root } = this.state;\n this.started += 1;\n const name = `${this.state.label.split(\"=\")[1]}-${this.started}`;\n const started = Date.now();\n // The container is created first and started after, so a stop never leaves a client half way through creating one.\n const created = this.client(this.runArguments(name, located.cwd, command, options.env), CREATE_TIMEOUT_MS);\n this.track(created);\n const made = await this.untilStopped(name, created, options);\n if (\"timedOut\" in made) return made.timedOut;\n if (made.exitCode !== 0) {\n await this.removeContainer(name);\n return { exitCode: made.exitCode, stdout: \"\", stderr: made.stderr };\n }\n try {\n this.live();\n options.signal.throwIfAborted();\n } catch (error) {\n await this.killContainer(name);\n throw error;\n }\n const remaining =\n options.timeoutMs === undefined ? {} : { timeoutMs: Math.max(1, options.timeoutMs - (Date.now() - started)) };\n const { stdoutBytes: _bytes, ...result } = await this.runner.run(\n {\n program: this.state.docker,\n args: [\"start\", \"--attach\", name],\n cwd: root,\n env: this.state.clientEnv,\n missingProgram: \"reject\",\n onStop: () => this.killContainer(name),\n graceMs: GRACE_MS,\n },\n { ...options, ...remaining },\n );\n return result;\n }\n\n /** Keeps `work` in the set that `dispose()` waits for, until it settles. */\n private track(work: Promise<unknown>): void {\n const tracked = work.then(\n () => undefined,\n () => undefined,\n );\n this.pending.add(tracked);\n void tracked.then(() => this.pending.delete(tracked));\n }\n\n /**\n * Waits for a container to be created, but settles the call when the caller's signal aborts or its timeout passes. The\n * creation can't be cut short without leaving a container behind, so it carries on in the background, and the container\n * is removed when it ends.\n */\n private untilStopped(\n name: string,\n created: Promise<ProcessResult>,\n options: ExecOptions,\n ): Promise<ProcessResult | { readonly timedOut: ExecResult }> {\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const finish = (settle: () => void, discard: boolean) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", onAbort);\n if (discard) {\n this.abandoned = true;\n this.track(created.then(() => this.killContainer(name)));\n }\n settle();\n };\n const onAbort = () => finish(() => reject(options.signal.reason), true);\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n if (options.timeoutMs !== undefined) {\n const note = `timed out after ${options.timeoutMs} ms\\n`;\n timer = setTimeout(\n () => finish(() => resolve({ timedOut: { exitCode: 124, stdout: \"\", stderr: note } }), true),\n options.timeoutMs,\n );\n }\n created.then(\n (result) => finish(() => resolve(result), false),\n (error: unknown) => finish(() => reject(error), false),\n );\n });\n }\n\n /**\n * Removes every container of this sandbox until none is left. A client stopped while the daemon was creating its\n * container can leave one behind, and a removal can take a while on a slow storage driver, so it waits for the last to go.\n * With no creation left in the background, an empty first pass ends it.\n */\n private async sweep(): Promise<void> {\n const deadline = Date.now() + SWEEP_MAX_MS;\n let quiet = 0;\n for (;;) {\n const left = await this.client(\n [\"ps\", \"--all\", \"--quiet\", \"--filter\", `label=${this.state.label}`],\n DAEMON_TIMEOUT_MS,\n )\n .then((result) => result.stdout.split(\"\\n\").filter((id) => id !== \"\"))\n .catch(() => []);\n quiet = left.length === 0 ? quiet + 1 : 0;\n if (left.length > 0) await this.client([\"rm\", \"--force\", ...left], DAEMON_TIMEOUT_MS).catch(() => undefined);\n if ((left.length === 0 && (!this.abandoned || quiet >= SWEEP_QUIET_PASSES)) || Date.now() > deadline) return;\n await new Promise((resolve) => setTimeout(resolve, SWEEP_PAUSE_MS));\n }\n }\n\n protected async shutDown(): Promise<void> {\n await this.runner.stopAll();\n await Promise.allSettled([...this.pending]);\n await this.sweep();\n await this.state.modules.fs.rm(this.state.folder, { recursive: true, force: true });\n }\n}\n\n/** Throws unless `image` is a name `docker run` takes as an image and not as an option. */\nfunction checkOptionValues(options: DockerSandboxOptions): void {\n const { image, cpus, memoryMb, pidsLimit, user } = options;\n if (typeof image !== \"string\" || image === \"\" || /\\s/.test(image) || image.startsWith(\"-\")) {\n throw new HarnessError(\n \"invalid_sandbox_options\",\n \"dockerSandbox needs an image name, such as one pinned by digest\",\n );\n }\n const bad = (what: string) => new HarnessError(\"invalid_sandbox_options\", `${what} is not usable`);\n if (cpus !== undefined && !(Number.isFinite(cpus) && cpus > 0)) throw bad(\"cpus\");\n if (memoryMb !== undefined && !(Number.isInteger(memoryMb) && memoryMb >= 6)) throw bad(\"memoryMb\");\n if (pidsLimit !== undefined && !(Number.isInteger(pidsLimit) && pidsLimit >= 1)) throw bad(\"pidsLimit\");\n if (user !== undefined && !/^[0-9]+(:[0-9]+)?$/.test(user)) throw bad(\"user\");\n}\n\n/** The sockets a Docker client may use: the default ones, and the one `dockerHost` names when it is a Unix socket. */\nfunction daemonSockets(dockerHost: string | undefined): string[] {\n const named = dockerHost?.startsWith(\"unix://\") ? [dockerHost.slice(\"unix://\".length)] : [];\n return [\"/var/run/docker.sock\", \"/run/docker.sock\", ...named];\n}\n\n/** Throws unless every source is mountable, and none is `/` or holds a Docker daemon socket, which would hand over the host. */\nasync function checkSources(modules: NodeModules, sources: readonly string[], dockerHost: string | undefined) {\n for (const from of sources) {\n if (!MOUNTABLE.test(from)) {\n throw new HarnessError(\"invalid_sandbox_options\", `a mounted folder can't have a comma or quote: ${from}`);\n }\n if (from === \"/\") throw new HarnessError(\"invalid_sandbox_options\", \"a mounted folder can't resolve to /\");\n }\n for (const socket of daemonSockets(dockerHost)) {\n const real = await modules.fs.realpath(socket).catch(() => undefined);\n if (real !== undefined && sources.some((from) => inside(modules, from, real))) {\n throw new HarnessError(\"invalid_sandbox_options\", `a mounted folder would hold the Docker socket ${socket}`);\n }\n }\n}\n\n/** One mount for each destination, read-only when any of the mounts for it is. */\nfunction onePerDestination(mounts: readonly Mount[]): Mount[] {\n const byDestination = new Map<string, Mount>();\n for (const mount of mounts) {\n const earlier = byDestination.get(mount.to);\n byDestination.set(\n mount.to,\n earlier === undefined ? mount : { ...mount, readOnly: earlier.readOnly || mount.readOnly },\n );\n }\n return [...byDestination.values()];\n}\n\n/**\n * The real mounts for a policy: write roots writable, read roots and extras read-only, and read-only again on top the\n * `denyWrite` folders inside a write root (made after the checks, so a later write can't find them writable) and the\n * protected files that exist. A `denyWrite` path outside every write root is not mounted: nothing there is writable.\n */\nasync function planMounts(modules: NodeModules, policy: SandboxPolicy, options: DockerSandboxOptions) {\n const real = (paths: readonly string[]) => Promise.all(paths.map((path) => realOrSelf(modules, path)));\n const [readRoots, writeRoots, extra, denyWrite] = await Promise.all([\n real(policy.readRoots),\n real(policy.writeRoots),\n real(options.extraReadRoots ?? []),\n real(options.denyWrite ?? []),\n ]);\n for (const root of writeRoots) {\n if (!(await modules.fs.stat(root).catch(() => undefined))?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", `a write root must be an existing folder: ${root}`);\n }\n }\n const underWrite = (path: string) => writeRoots.some((root) => inside(modules, root, path));\n const denied = denyWrite.filter(underWrite);\n const protectedPaths = writeRoots.flatMap((root) => PROTECTED_TOP_LEVEL.map((name) => modules.path.join(root, name)));\n const readOnlyRoots = [...readRoots, ...extra].filter((path) => !underWrite(path));\n const base: Mount[] = [\n ...writeRoots.map((from) => ({ from, to: from, readOnly: false })),\n ...(await existing(modules, readOnlyRoots)).map((from) => ({ from, to: from, readOnly: true })),\n ];\n const guarded = [...denied, ...(await existing(modules, protectedPaths))].map((from) => ({\n from,\n to: from,\n readOnly: true,\n }));\n return {\n base: onePerDestination(base),\n mounts: onePerDestination([...base, ...guarded]),\n roots: { read: readRoots, write: writeRoots, denyWrite: denied },\n };\n}\n\n/** The `docker run` flags that lock a container down, and limit what it may use. */\nfunction lockdownFlags(options: DockerSandboxOptions, user: string): string[] {\n const memory = `${options.memoryMb ?? DEFAULTS.memoryMb}m`;\n return [\n \"--pull\",\n \"never\",\n \"--network\",\n \"none\",\n \"--read-only\",\n \"--cap-drop\",\n \"ALL\",\n \"--security-opt\",\n \"no-new-privileges\",\n \"--ipc\",\n \"none\",\n \"--pids-limit\",\n String(options.pidsLimit ?? DEFAULTS.pidsLimit),\n \"--cpus\",\n String(options.cpus ?? DEFAULTS.cpus),\n \"--memory\",\n memory,\n \"--memory-swap\",\n memory,\n \"--user\",\n user,\n // The only writable place that isn't a mounted write root: memory-backed, so it is gone with the container.\n \"--tmpfs\",\n \"/tmp:rw,nosuid,size=64m\",\n ];\n}\n\n/** The `docker` executable, or a `SandboxUnavailableError` when there is none. */\nasync function dockerProgram(modules: NodeModules, options: DockerSandboxOptions, hostPath: string): Promise<string> {\n if (options.binary !== undefined) {\n const program = modules.path.resolve(options.binary);\n await modules.fs.access(program, modules.fs.constants.X_OK).catch((error: unknown) => {\n throw new SandboxUnavailableError(\"docker\", `${options.binary} is not an executable file`, { cause: error });\n });\n return program;\n }\n const found = await findOnPath(modules, hostPath, \"docker\");\n if (found === undefined) throw new SandboxUnavailableError(\"docker\", \"docker is not on the PATH\");\n return found;\n}\n\n/** The first line of what a client printed, for the message of a failure. */\nconst firstLine = (text: string): string => text.trim().split(\"\\n\")[0] ?? \"no output\";\n\n/**\n * Builds the Docker backend. `provision()` checks the platform, the `docker` client, the daemon and that the image is on\n * the host, so a host that can't run the container throws `SandboxUnavailableError` and runs nothing. The `docker`\n * client runs with a clean environment: a `PATH`, a private empty `HOME` and `DOCKER_HOST` when one is set, and never\n * the parent's environment. The policy's roots, `extraReadRoots`, `denyWrite` and `proxySocket` must be absolute, and\n * the workspace must lie inside a root. A command whose first word contains `=` resolves with exit code 127, as under\n * `none`.\n */\nexport function dockerSandbox(options: DockerSandboxOptions): SandboxClient {\n checkOptionValues(options);\n return {\n tier: \"container\",\n stops: [\"mistakes\", \"exfiltration\"],\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox> {\n const modules = nodeModules(\"docker\");\n if (process.platform !== \"linux\") {\n throw new SandboxUnavailableError(\n \"docker\",\n `only Linux is supported, because it is the only platform this backend is tested on, and this is ${process.platform}`,\n );\n }\n const hostPath = absolutePath(modules, process.env.PATH);\n const docker = await dockerProgram(modules, options, hostPath);\n const root = await workspaceRoot(modules, manifest.root);\n checkPaths(modules, [...policy.readRoots, ...policy.writeRoots], \"a sandbox root\");\n checkPaths(modules, options.extraReadRoots ?? [], \"an extra read root\");\n checkPaths(modules, options.denyWrite ?? [], \"a denyWrite folder\");\n const folder = await modules.fs.mkdtemp(modules.path.join(modules.os.tmpdir(), \"harness-docker-\"));\n try {\n const sandbox = await startSandbox({ modules, docker, hostPath, root, folder, manifest, policy, options });\n return sandbox;\n } catch (error) {\n await modules.fs.rm(folder, { recursive: true, force: true });\n throw error;\n }\n },\n };\n}\n\ninterface StartInput {\n readonly modules: NodeModules;\n readonly docker: string;\n readonly hostPath: string;\n readonly root: string;\n readonly folder: string;\n readonly manifest: WorkspaceManifest;\n readonly policy: SandboxPolicy;\n readonly options: DockerSandboxOptions;\n}\n\nasync function startSandbox(input: StartInput): Promise<DockerSandbox> {\n const { modules, options } = input;\n await modules.fs.chmod(input.folder, 0o700);\n const home = modules.path.join(input.folder, \"home\");\n await modules.fs.mkdir(home, { mode: 0o700 });\n const dockerHost = options.dockerHost ?? process.env.DOCKER_HOST;\n const clientEnv = {\n PATH: input.hostPath,\n HOME: home,\n ...(dockerHost === undefined ? {} : { DOCKER_HOST: dockerHost }),\n };\n const plan = await planMounts(modules, input.policy, options);\n await checkSources(\n modules,\n plan.mounts.map((mount) => mount.from),\n dockerHost,\n );\n if (!plan.base.some((mount) => inside(modules, mount.from, input.root))) {\n throw new HarnessError(\"invalid_sandbox_options\", \"the workspace root must lie inside a read or write root\");\n }\n const mounts = [...plan.mounts];\n if (options.proxySocket !== undefined) {\n checkPaths(modules, [options.proxySocket], \"the proxy socket\");\n const stats = await modules.fs.stat(options.proxySocket).catch(() => undefined);\n if (!stats?.isSocket()) throw new HarnessError(\"invalid_sandbox_options\", \"proxySocket must be a Unix socket\");\n const from = await modules.fs.realpath(options.proxySocket);\n await checkSources(modules, [from], dockerHost);\n mounts.push({ from, to: DOCKER_PROXY_SOCKET_PATH, readOnly: false });\n }\n const user = options.user ?? `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`;\n const sandbox = new DockerSandbox({\n modules,\n docker: input.docker,\n image: options.image,\n root: input.root,\n files: new HostFiles(modules, input.root, plan.roots, isProtectedPath),\n mounts,\n flags: lockdownFlags(options, user),\n clientEnv,\n folder: input.folder,\n label: `harness.sandbox=harness-${modules.path.basename(input.folder).slice(\"harness-docker-\".length)}`,\n });\n await probe(sandbox, options.image);\n for (const folder of plan.roots.denyWrite) await modules.fs.mkdir(folder, { recursive: true });\n const encoder = new TextEncoder();\n for (const [path, data] of Object.entries(input.manifest.files ?? {})) {\n await sandbox.writeFile(path, typeof data === \"string\" ? encoder.encode(data) : data);\n }\n return sandbox;\n}\n\n/** Asks the daemon for its version and for the image, and throws `SandboxUnavailableError` when either fails. */\nasync function probe(sandbox: DockerSandbox, image: string): Promise<void> {\n const unavailable = (reason: string, cause?: unknown) => new SandboxUnavailableError(\"docker\", reason, { cause });\n const version = await sandbox\n .client([\"version\", \"--format\", \"{{.Server.Version}}\"], DAEMON_TIMEOUT_MS)\n .catch((error: unknown) => {\n throw unavailable(\"the docker client could not be started\", error);\n });\n if (version.exitCode !== 0) throw unavailable(`the daemon did not answer: ${firstLine(version.stderr)}`);\n const found = await sandbox\n .client([\"image\", \"inspect\", \"--format\", \"{{.Id}}\", image], DAEMON_TIMEOUT_MS)\n .catch((error: unknown) => {\n throw unavailable(\"the docker client could not be started\", error);\n });\n if (found.exitCode !== 0) {\n throw unavailable(`the image ${image} is not on the Docker host, and provision never pulls: pull it first`);\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/sandbox/docker/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EACL,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,SAAS,EACT,MAAM,EACN,eAAe,EACf,mBAAmB,EACnB,UAAU,EACV,SAAS,EACT,aAAa,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAoB,WAAW,EAAsB,aAAa,EAAE,MAAM,eAAe,CAAC;AA+BjG,0EAA0E;AAC1E,MAAM,CAAC,MAAM,wBAAwB,GAAG,yBAAyB,CAAC;AAElE,MAAM,QAAQ,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAW,CAAC;AACtE,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,mEAAmE;AACnE,MAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,yFAAyF;AACzF,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAClC,2HAA2H;AAC3H,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,uEAAuE;AACvE,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,kFAAkF;AAClF,MAAM,aAAa,GAAG,0BAA0B,CAAC;AACjD,oGAAoG;AACpG,MAAM,SAAS,GAAG,cAAc,CAAC;AAyCjC,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M,CAAC,CAAC,SAAS,EAAE,UAAU,EAAE,qBAAqB,CAAC,EAAE,iBAAiB,CAAC;SACzE,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,MAAM,WAAW,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;IACrE,CAAC,CAAC,CAAC;IACL,IAAI,OAAO,CAAC,QAAQ,KAAK,CAAC;QAAE,MAAM,WAAW,CAAC,8BAA8B,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IACzG,MAAM,KAAK,GAAG,MAAM,OAAO;SACxB,MAAM,CAAC,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,KAAK,CAAC,EAAE,iBAAiB,CAAC;SAC7E,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,MAAM,WAAW,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;IACrE,CAAC,CAAC,CAAC;IACL,IAAI,KAAK,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,WAAW,CAAC,aAAa,KAAK,sEAAsE,CAAC,CAAC;IAC9G,CAAC;AACH,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/sandbox/docker`: the container-tier backend. Each command runs in its own locked-down\n * container: all capabilities dropped, a read-only root file system, no network, no new privileges, and limits on\n * processes, CPUs and memory. Only the policy's write roots are writable, and only the policy's roots are mounted. It\n * claims `mistakes` and `exfiltration`, never a `hostile_process`: the kernel is shared with the host. Only Linux and a\n * rootful daemon are tested. A backend that can't start throws `SandboxUnavailableError` and runs nothing. It is\n * Node-only.\n *\n * The container has no network, so a command reaches a host only through a proxy socket the caller mounts. The file calls\n * run in the host on the mounted folders, checked by their real path.\n */\nimport { HarnessError } from \"../../errors.js\";\nimport { BackendSandbox } from \"../base.js\";\nimport { SandboxUnavailableError } from \"../errors.js\";\nimport {\n absolutePath,\n checkPaths,\n existing,\n findOnPath,\n HostFiles,\n inside,\n isProtectedPath,\n PROTECTED_TOP_LEVEL,\n realOrSelf,\n spellings,\n workspaceRoot,\n} from \"../host-files.js\";\nimport { type NodeModules, nodeModules, type ProcessResult, ProcessRunner } from \"../process.js\";\nimport type { ExecOptions, ExecResult, Sandbox, SandboxClient, SandboxPolicy, WorkspaceManifest } from \"../types.js\";\n\n/** The options of `dockerSandbox()`. */\nexport interface DockerSandboxOptions {\n /** The image to run, which must already be on the Docker host: `provision()` never pulls. Pin it by digest. */\n readonly image: string;\n /** CPUs a command may use. Defaults to 1. */\n readonly cpus?: number;\n /** Megabytes of memory a command may use, with no swap. Defaults to 1024. */\n readonly memoryMb?: number;\n /** Processes a command may start. Defaults to 256. */\n readonly pidsLimit?: number;\n /** The `docker` executable. Without it the backend finds `docker` on the absolute folders of the host's `PATH`. */\n readonly binary?: string;\n /** The Docker daemon's address. Without it the backend passes the host's `DOCKER_HOST` when it is set. */\n readonly dockerHost?: string;\n /** The user and group a command runs as, as `uid:gid`. Defaults to this process's, so its files stay yours. */\n readonly user?: string;\n /** Folders to read besides the policy's roots, mounted read-only. */\n readonly extraReadRoots?: readonly string[];\n /** Folders that stay read-only inside a write root, such as the session's own log folder. */\n readonly denyWrite?: readonly string[];\n /**\n * A Unix socket on the host that a command may use to reach the hosts its policy allows, mounted at\n * `DOCKER_PROXY_SOCKET_PATH`. The proxy on it enforces the allowlist, so start `startEgressProxy()` there with the\n * policy's hosts, such as from `compileEgressPolicy()`; the read-back trusts it to.\n */\n readonly proxySocket?: string;\n}\n\n/** Where a command finds the proxy socket, when the caller mounts one. */\nexport const DOCKER_PROXY_SOCKET_PATH = \"/run/harness/proxy.sock\";\n\nconst DEFAULTS = { cpus: 1, memoryMb: 1024, pidsLimit: 256 } as const;\nconst DAEMON_TIMEOUT_MS = 20_000;\n// The longest one call that kills or removes a container may take.\nconst CALL_TIMEOUT_MS = 5000;\n// Creating a container copies the image on some storage drivers, which can take a while.\nconst CREATE_TIMEOUT_MS = 120_000;\n// How long a stopped `docker run` client has to leave on its own, which lets it cancel a container that isn't started yet.\nconst GRACE_MS = 3000;\nconst KILL_ATTEMPTS = 5;\nconst KILL_RETRY_MS = 100;\nconst SWEEP_QUIET_PASSES = 2;\n// The longest the sweep at the end waits for the last container to go.\nconst SWEEP_MAX_MS = 20_000;\nconst SWEEP_PAUSE_MS = 200;\n// A variable name that `env` can set, which is every name a process can be given.\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n// A path in a `--mount` value can't hold a comma or a quote, which that syntax reads as separators.\nconst MOUNTABLE = /^[^,\"\\n\\r]+$/;\n\n/** One bind mount: the real host path, mounted at the same path inside, or at `to`. */\ninterface Mount {\n readonly from: string;\n readonly to: string;\n readonly readOnly: boolean;\n}\n\n/** Everything a provisioned sandbox holds. */\ninterface DockerState {\n readonly modules: NodeModules;\n readonly docker: string;\n readonly image: string;\n readonly root: string;\n readonly files: HostFiles;\n readonly mounts: readonly Mount[];\n readonly flags: readonly string[];\n /** The environment the `docker` client runs with: where to find its programs, and a private empty `HOME`. */\n readonly clientEnv: Readonly<Record<string, string>>;\n /** A private folder that holds the client's `HOME`, removed on dispose. */\n readonly folder: string;\n /** Marks this sandbox's containers, so `dispose()` can find any that a stopped client left behind. */\n readonly label: string;\n /** What the read-back needs to map the mounts back to the request's spelling. */\n readonly names: DockerPolicyNames;\n}\n\n/** How the mounts map back to the request, for the read-back. */\ninterface DockerPolicyNames {\n readonly requested: SandboxPolicy;\n /** The real path of each requested read root, in the request's order. */\n readonly readReal: readonly string[];\n /** For each real write root, the request's spellings that resolved to it. */\n readonly write: ReadonlyMap<string, readonly string[]>;\n /** Requested read roots that don't exist, which have nothing to mount and nothing to read. */\n readonly missing: ReadonlySet<string>;\n /** Read-only mounts the backend adds itself: the extra read roots, the denyWrite folders and the protected files. */\n readonly implicit: ReadonlySet<string>;\n}\n\nconst mountFlags = (mount: Mount): string[] => [\n \"--mount\",\n `type=bind,src=${mount.from},dst=${mount.to}${mount.readOnly ? \",readonly\" : \"\"}`,\n];\n\nclass DockerSandbox extends BackendSandbox {\n private started = 0;\n // Whether a creation was left to finish in the background, which a sweep at the end has to catch.\n private abandoned = false;\n // The containers being created, which `dispose()` waits for before it sweeps.\n private readonly pending = new Set<Promise<unknown>>();\n private readonly runner: ProcessRunner;\n // Runs the calls that manage containers, which `dispose()` must not cut short: a `create` that is stopped half way\n // leaves a container behind.\n private readonly manager: ProcessRunner;\n private readonly state: DockerState;\n\n constructor(state: DockerState) {\n super(state);\n this.state = state;\n this.runner = new ProcessRunner(state.modules);\n this.manager = new ProcessRunner(state.modules);\n }\n\n /** Runs the `docker` client with `args` and waits for it, for the calls that manage containers. */\n async client(args: readonly string[], timeoutMs: number) {\n return this.manager.run(\n {\n program: this.state.docker,\n args,\n cwd: this.state.root,\n env: this.state.clientEnv,\n missingProgram: \"reject\",\n },\n { env: {}, signal: new AbortController().signal, timeoutMs },\n );\n }\n\n /** The `docker run` arguments for one command in a container called `name`. */\n private runArguments(name: string, cwd: string, command: readonly string[], env: Readonly<Record<string, string>>) {\n const assignments: string[] = [];\n for (const [variable, value] of Object.entries(env)) {\n if (!VARIABLE_NAME.test(variable)) {\n throw new HarnessError(\"invalid_sandbox_options\", `${JSON.stringify(variable)} is not a variable name`);\n }\n assignments.push(`${variable}=${value}`);\n }\n const { state } = this;\n // `env -i` clears the image's own variables, so the command holds exactly the ones it was given.\n return [\n \"create\",\n \"--rm\",\n \"--name\",\n name,\n \"--label\",\n state.label,\n ...state.flags,\n ...state.mounts.flatMap(mountFlags),\n \"--workdir\",\n cwd,\n \"--entrypoint\",\n \"env\",\n state.image,\n \"-i\",\n // Ends `env`'s options, so a first word that starts with `-` is a program name.\n \"--\",\n ...assignments,\n ...command,\n ];\n }\n\n /** Removes the container if it exists, which is all a container that never started needs. */\n private async removeContainer(name: string): Promise<void> {\n await this.client([\"rm\", \"--force\", name], CALL_TIMEOUT_MS).catch(() => undefined);\n }\n\n /** Kills the container, trying again while the daemon is still creating it, and removes what is left. */\n private async killContainer(name: string): Promise<void> {\n for (let attempt = 0; attempt < KILL_ATTEMPTS; attempt += 1) {\n const result = await this.client([\"kill\", name], CALL_TIMEOUT_MS).catch(() => undefined);\n if (result?.exitCode === 0) break;\n await new Promise((resolve) => setTimeout(resolve, KILL_RETRY_MS));\n }\n await this.removeContainer(name);\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n const prepared = await this.prepare(command, options);\n if (!(\"cwd\" in prepared)) return prepared;\n const located = prepared;\n const { root } = this.state;\n this.started += 1;\n const name = `${this.state.label.split(\"=\")[1]}-${this.started}`;\n const started = Date.now();\n // The container is created first and started after, so a stop never leaves a client half way through creating one.\n const created = this.client(this.runArguments(name, located.cwd, command, options.env), CREATE_TIMEOUT_MS);\n this.track(created);\n const made = await this.untilStopped(name, created, options);\n if (\"expired\" in made) return made.expired;\n if (made.exitCode !== 0) {\n await this.removeContainer(name);\n return { exitCode: made.exitCode, stdout: \"\", stderr: made.stderr };\n }\n try {\n this.live();\n options.signal.throwIfAborted();\n } catch (error) {\n await this.killContainer(name);\n throw error;\n }\n const remaining =\n options.timeoutMs === undefined ? {} : { timeoutMs: Math.max(1, options.timeoutMs - (Date.now() - started)) };\n const { stdoutBytes: _bytes, ...result } = await this.runner.run(\n {\n program: this.state.docker,\n args: [\"start\", \"--attach\", name],\n cwd: root,\n env: this.state.clientEnv,\n missingProgram: \"reject\",\n onStop: () => this.killContainer(name),\n graceMs: GRACE_MS,\n },\n { ...options, ...remaining },\n );\n return result;\n }\n\n /** Keeps `work` in the set that `dispose()` waits for, until it settles. */\n private track(work: Promise<unknown>): void {\n const tracked = work.then(\n () => undefined,\n () => undefined,\n );\n this.pending.add(tracked);\n void tracked.then(() => this.pending.delete(tracked));\n }\n\n /**\n * Waits for a container to be created, but settles the call when the caller's signal aborts or its timeout passes. The\n * creation can't be cut short without leaving a container behind, so it carries on in the background, and the container\n * is removed when it ends.\n */\n private untilStopped(\n name: string,\n created: Promise<ProcessResult>,\n options: ExecOptions,\n ): Promise<ProcessResult | { readonly expired: ExecResult }> {\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const finish = (settle: () => void, discard: boolean) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", onAbort);\n if (discard) {\n this.abandoned = true;\n this.track(created.then(() => this.killContainer(name)));\n }\n settle();\n };\n const onAbort = () => finish(() => reject(options.signal.reason), true);\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n if (options.timeoutMs !== undefined) {\n const note = `timed out after ${options.timeoutMs} ms\\n`;\n timer = setTimeout(\n () => finish(() => resolve({ expired: { exitCode: 124, stdout: \"\", stderr: note, timedOut: true } }), true),\n options.timeoutMs,\n );\n }\n created.then(\n (result) => finish(() => resolve(result), false),\n (error: unknown) => finish(() => reject(error), false),\n );\n });\n }\n\n /**\n * Removes every container of this sandbox until none is left. A client stopped while the daemon was creating its\n * container can leave one behind, and a removal can take a while on a slow storage driver, so it waits for the last to go.\n * With no creation left in the background, an empty first pass ends it.\n */\n private async sweep(): Promise<void> {\n const deadline = Date.now() + SWEEP_MAX_MS;\n let quiet = 0;\n for (;;) {\n const left = await this.client(\n [\"ps\", \"--all\", \"--quiet\", \"--filter\", `label=${this.state.label}`],\n DAEMON_TIMEOUT_MS,\n )\n .then((result) => result.stdout.split(\"\\n\").filter((id) => id !== \"\"))\n .catch(() => []);\n quiet = left.length === 0 ? quiet + 1 : 0;\n if (left.length > 0) await this.client([\"rm\", \"--force\", ...left], DAEMON_TIMEOUT_MS).catch(() => undefined);\n if ((left.length === 0 && (!this.abandoned || quiet >= SWEEP_QUIET_PASSES)) || Date.now() > deadline) return;\n await new Promise((resolve) => setTimeout(resolve, SWEEP_PAUSE_MS));\n }\n }\n\n /**\n * The policy the mounts and flags apply, which are what every command's container is created with. The network is\n * closed unless the caller mounted a proxy socket, and then the proxy on it enforces the requested allowlist. A\n * read-only mount the request doesn't explain reads back as a read root it didn't ask for.\n *\n * One narrowing is not caught: a write root that the caller's `denyWrite` names exactly is mounted read-only but still\n * reads back as a write root, because the read-back takes the caller's own `denyWrite` as part of the request. So\n * `provision()` accepts it, and nothing in that root is writable inside the container.\n */\n async readBack(): Promise<SandboxPolicy> {\n this.live();\n const { mounts, names, flags } = this.state;\n const own = mounts.filter((mount) => mount.to !== DOCKER_PROXY_SOCKET_PATH);\n // A write root that the caller's own denyWrite made read-only is still the root the request asked for.\n const granted = (mount: Mount) =>\n !mount.readOnly || (names.implicit.has(mount.from) && names.write.has(mount.from));\n const writable = own.filter(granted).map((mount) => mount.from);\n const inWritable = (path: string) => writable.some((root) => inside(this.state.modules, root, path));\n const readable = (real: string) => names.missing.has(real) || inWritable(real) || own.some((m) => m.from === real);\n const unexplained = own\n .filter((mount) => mount.readOnly && !names.readReal.includes(mount.from))\n .map((mount) => mount.from)\n .filter((from) => !names.implicit.has(from) && !inWritable(from));\n const closed = flags.join(\" \").includes(\"--network none\");\n const proxied = mounts.length !== own.length;\n return {\n readRoots: [\n ...names.requested.readRoots.filter((_, index) => readable(names.readReal[index] ?? \"\")),\n ...unexplained,\n ],\n writeRoots: writable.flatMap((path) => names.write.get(path) ?? [path]),\n network: !closed\n ? { allow: [\"*\"], deny: [] }\n : proxied\n ? names.requested.network\n : { allow: [], deny: names.requested.network.deny },\n };\n }\n\n protected async shutDown(): Promise<void> {\n await this.runner.stopAll();\n await Promise.allSettled([...this.pending]);\n await this.sweep();\n await this.state.modules.fs.rm(this.state.folder, { recursive: true, force: true });\n }\n}\n\n/** Throws unless `image` is a name `docker run` takes as an image and not as an option. */\nfunction checkOptionValues(options: DockerSandboxOptions): void {\n const { image, cpus, memoryMb, pidsLimit, user } = options;\n if (typeof image !== \"string\" || image === \"\" || /\\s/.test(image) || image.startsWith(\"-\")) {\n throw new HarnessError(\n \"invalid_sandbox_options\",\n \"dockerSandbox needs an image name, such as one pinned by digest\",\n );\n }\n const bad = (what: string) => new HarnessError(\"invalid_sandbox_options\", `${what} is not usable`);\n if (cpus !== undefined && !(Number.isFinite(cpus) && cpus > 0)) throw bad(\"cpus\");\n if (memoryMb !== undefined && !(Number.isInteger(memoryMb) && memoryMb >= 6)) throw bad(\"memoryMb\");\n if (pidsLimit !== undefined && !(Number.isInteger(pidsLimit) && pidsLimit >= 1)) throw bad(\"pidsLimit\");\n if (user !== undefined && !/^[0-9]+(:[0-9]+)?$/.test(user)) throw bad(\"user\");\n}\n\n/** The sockets a Docker client may use: the default ones, and the one `dockerHost` names when it is a Unix socket. */\nfunction daemonSockets(dockerHost: string | undefined): string[] {\n const named = dockerHost?.startsWith(\"unix://\") ? [dockerHost.slice(\"unix://\".length)] : [];\n return [\"/var/run/docker.sock\", \"/run/docker.sock\", ...named];\n}\n\n/** Throws unless every source is mountable, and none is `/` or holds a Docker daemon socket, which would hand over the host. */\nasync function checkSources(modules: NodeModules, sources: readonly string[], dockerHost: string | undefined) {\n for (const from of sources) {\n if (!MOUNTABLE.test(from)) {\n throw new HarnessError(\"invalid_sandbox_options\", `a mounted folder can't have a comma or quote: ${from}`);\n }\n if (from === \"/\") throw new HarnessError(\"invalid_sandbox_options\", \"a mounted folder can't resolve to /\");\n }\n for (const socket of daemonSockets(dockerHost)) {\n const real = await modules.fs.realpath(socket).catch(() => undefined);\n if (real !== undefined && sources.some((from) => inside(modules, from, real))) {\n throw new HarnessError(\"invalid_sandbox_options\", `a mounted folder would hold the Docker socket ${socket}`);\n }\n }\n}\n\n/** One mount for each destination, read-only when any of the mounts for it is. */\nfunction onePerDestination(mounts: readonly Mount[]): Mount[] {\n const byDestination = new Map<string, Mount>();\n for (const mount of mounts) {\n const earlier = byDestination.get(mount.to);\n byDestination.set(\n mount.to,\n earlier === undefined ? mount : { ...mount, readOnly: earlier.readOnly || mount.readOnly },\n );\n }\n return [...byDestination.values()];\n}\n\n/**\n * The real mounts for a policy: write roots writable, read roots and extras read-only, and read-only again on top the\n * `denyWrite` folders inside a write root (made after the checks, so a later write can't find them writable) and the\n * protected files that exist. A `denyWrite` path outside every write root is not mounted: nothing there is writable.\n */\nasync function planMounts(modules: NodeModules, policy: SandboxPolicy, options: DockerSandboxOptions) {\n const real = (paths: readonly string[]) => Promise.all(paths.map((path) => realOrSelf(modules, path)));\n const [readRoots, writeRoots, extra, denyWrite] = await Promise.all([\n real(policy.readRoots),\n real(policy.writeRoots),\n real(options.extraReadRoots ?? []),\n real(options.denyWrite ?? []),\n ]);\n for (const root of writeRoots) {\n if (!(await modules.fs.stat(root).catch(() => undefined))?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", `a write root must be an existing folder: ${root}`);\n }\n }\n const underWrite = (path: string) => writeRoots.some((root) => inside(modules, root, path));\n const denied = denyWrite.filter(underWrite);\n const protectedPaths = writeRoots.flatMap((root) => PROTECTED_TOP_LEVEL.map((name) => modules.path.join(root, name)));\n const readOnlyRoots = [...readRoots, ...extra].filter((path) => !underWrite(path));\n // One look at which read roots exist feeds both the mounts and the names, so a folder made in between can't make them\n // disagree.\n const present = await existing(modules, readOnlyRoots);\n const base: Mount[] = [\n ...writeRoots.map((from) => ({ from, to: from, readOnly: false })),\n ...present.map((from) => ({ from, to: from, readOnly: true })),\n ];\n const protectedPresent = await existing(modules, protectedPaths);\n const guarded = [...denied, ...protectedPresent].map((from) => ({ from, to: from, readOnly: true }));\n const names: DockerPolicyNames = {\n requested: policy,\n readReal: readRoots,\n write: spellings(writeRoots, policy.writeRoots),\n missing: new Set(readOnlyRoots.filter((path) => !present.includes(path))),\n implicit: new Set([...extra, ...denied, ...protectedPresent]),\n };\n return {\n base: onePerDestination(base),\n mounts: onePerDestination([...base, ...guarded]),\n roots: { read: readRoots, write: writeRoots, denyWrite: denied },\n names,\n };\n}\n\n/** The `docker run` flags that lock a container down, and limit what it may use. */\nfunction lockdownFlags(options: DockerSandboxOptions, user: string): string[] {\n const memory = `${options.memoryMb ?? DEFAULTS.memoryMb}m`;\n return [\n \"--pull\",\n \"never\",\n \"--network\",\n \"none\",\n \"--read-only\",\n \"--cap-drop\",\n \"ALL\",\n \"--security-opt\",\n \"no-new-privileges\",\n \"--ipc\",\n \"none\",\n \"--pids-limit\",\n String(options.pidsLimit ?? DEFAULTS.pidsLimit),\n \"--cpus\",\n String(options.cpus ?? DEFAULTS.cpus),\n \"--memory\",\n memory,\n \"--memory-swap\",\n memory,\n \"--user\",\n user,\n // The only writable place that isn't a mounted write root: memory-backed, so it is gone with the container.\n \"--tmpfs\",\n \"/tmp:rw,nosuid,size=64m\",\n ];\n}\n\n/** The `docker` executable, or a `SandboxUnavailableError` when there is none. */\nasync function dockerProgram(modules: NodeModules, options: DockerSandboxOptions, hostPath: string): Promise<string> {\n if (options.binary !== undefined) {\n const program = modules.path.resolve(options.binary);\n await modules.fs.access(program, modules.fs.constants.X_OK).catch((error: unknown) => {\n throw new SandboxUnavailableError(\"docker\", `${options.binary} is not an executable file`, { cause: error });\n });\n return program;\n }\n const found = await findOnPath(modules, hostPath, \"docker\");\n if (found === undefined) throw new SandboxUnavailableError(\"docker\", \"docker is not on the PATH\");\n return found;\n}\n\n/** The first line of what a client printed, for the message of a failure. */\nconst firstLine = (text: string): string => text.trim().split(\"\\n\")[0] ?? \"no output\";\n\n/**\n * Builds the Docker backend. `provision()` checks the platform, the `docker` client, the daemon and that the image is on\n * the host, so a host that can't run the container throws `SandboxUnavailableError` and runs nothing. The `docker`\n * client runs with a clean environment: a `PATH`, a private empty `HOME` and `DOCKER_HOST` when one is set, and never\n * the parent's environment. The policy's roots, `extraReadRoots`, `denyWrite` and `proxySocket` must be absolute, and\n * the workspace must lie inside a root. A command whose first word contains `=` resolves with exit code 127, as under\n * `none`. Before it returns, `provision()` reads back the policy its mounts and flags apply and throws\n * `SandboxPolicyMismatchError` on a difference. Without `proxySocket` the container reaches no host, so a policy whose\n * `network.allow` names one is refused. The backend lists no capability: it can't resume, snapshot or pause.\n */\nexport function dockerSandbox(options: DockerSandboxOptions): SandboxClient {\n checkOptionValues(options);\n const client: SandboxClient = {\n tier: \"container\",\n stops: [\"mistakes\", \"exfiltration\"],\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox> {\n const modules = nodeModules(\"docker\");\n if (process.platform !== \"linux\") {\n throw new SandboxUnavailableError(\n \"docker\",\n `only Linux is supported, because it is the only platform this backend is tested on, and this is ${process.platform}`,\n );\n }\n const hostPath = absolutePath(modules, process.env.PATH);\n const docker = await dockerProgram(modules, options, hostPath);\n const root = await workspaceRoot(modules, manifest.root);\n checkPaths(modules, [...policy.readRoots, ...policy.writeRoots], \"a sandbox root\");\n checkPaths(modules, options.extraReadRoots ?? [], \"an extra read root\");\n checkPaths(modules, options.denyWrite ?? [], \"a denyWrite folder\");\n const folder = await modules.fs.mkdtemp(modules.path.join(modules.os.tmpdir(), \"harness-docker-\"));\n try {\n return await startSandbox({ modules, docker, hostPath, root, folder, manifest, policy, options, client });\n } catch (error) {\n await modules.fs.rm(folder, { recursive: true, force: true });\n throw error;\n }\n },\n };\n return client;\n}\n\ninterface StartInput {\n readonly modules: NodeModules;\n readonly docker: string;\n readonly hostPath: string;\n readonly root: string;\n readonly folder: string;\n readonly manifest: WorkspaceManifest;\n readonly policy: SandboxPolicy;\n readonly options: DockerSandboxOptions;\n readonly client: SandboxClient;\n}\n\nasync function startSandbox(input: StartInput): Promise<DockerSandbox> {\n const { modules, options } = input;\n await modules.fs.chmod(input.folder, 0o700);\n const home = modules.path.join(input.folder, \"home\");\n await modules.fs.mkdir(home, { mode: 0o700 });\n const dockerHost = options.dockerHost ?? process.env.DOCKER_HOST;\n const clientEnv = {\n PATH: input.hostPath,\n HOME: home,\n ...(dockerHost === undefined ? {} : { DOCKER_HOST: dockerHost }),\n };\n const plan = await planMounts(modules, input.policy, options);\n await checkSources(\n modules,\n plan.mounts.map((mount) => mount.from),\n dockerHost,\n );\n if (!plan.base.some((mount) => inside(modules, mount.from, input.root))) {\n throw new HarnessError(\"invalid_sandbox_options\", \"the workspace root must lie inside a read or write root\");\n }\n const mounts = [...plan.mounts];\n if (options.proxySocket !== undefined) {\n checkPaths(modules, [options.proxySocket], \"the proxy socket\");\n const stats = await modules.fs.stat(options.proxySocket).catch(() => undefined);\n if (!stats?.isSocket()) throw new HarnessError(\"invalid_sandbox_options\", \"proxySocket must be a Unix socket\");\n const from = await modules.fs.realpath(options.proxySocket);\n await checkSources(modules, [from], dockerHost);\n mounts.push({ from, to: DOCKER_PROXY_SOCKET_PATH, readOnly: false });\n }\n const user = options.user ?? `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`;\n const sandbox = new DockerSandbox({\n modules,\n docker: input.docker,\n image: options.image,\n root: input.root,\n files: new HostFiles(modules, input.root, plan.roots, isProtectedPath),\n mounts,\n flags: lockdownFlags(options, user),\n clientEnv,\n folder: input.folder,\n label: `harness.sandbox=harness-${modules.path.basename(input.folder).slice(\"harness-docker-\".length)}`,\n names: plan.names,\n });\n await probe(sandbox, options.image);\n await sandbox.confirm(input.client, input.policy);\n for (const folder of plan.roots.denyWrite) await modules.fs.mkdir(folder, { recursive: true });\n const encoder = new TextEncoder();\n for (const [path, data] of Object.entries(input.manifest.files ?? {})) {\n await sandbox.writeFile(path, typeof data === \"string\" ? encoder.encode(data) : data);\n }\n return sandbox;\n}\n\n/** Asks the daemon for its version and for the image, and throws `SandboxUnavailableError` when either fails. */\nasync function probe(sandbox: DockerSandbox, image: string): Promise<void> {\n const unavailable = (reason: string, cause?: unknown) => new SandboxUnavailableError(\"docker\", reason, { cause });\n const version = await sandbox\n .client([\"version\", \"--format\", \"{{.Server.Version}}\"], DAEMON_TIMEOUT_MS)\n .catch((error: unknown) => {\n throw unavailable(\"the docker client could not be started\", error);\n });\n if (version.exitCode !== 0) throw unavailable(`the daemon did not answer: ${firstLine(version.stderr)}`);\n const found = await sandbox\n .client([\"image\", \"inspect\", \"--format\", \"{{.Id}}\", image], DAEMON_TIMEOUT_MS)\n .catch((error: unknown) => {\n throw unavailable(\"the docker client could not be started\", error);\n });\n if (found.exitCode !== 0) {\n throw unavailable(`the image ${image} is not on the Docker host, and provision never pulls: pull it first`);\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
- /** The sandbox's two named errors, each a `HarnessError` with its own code and its own fields. */
1
+ /** The sandbox's four named errors, each a `HarnessError` with its own code and its own fields. */
2
2
  import { HarnessError } from "../errors.js";
3
- import type { SandboxDenial } from "./types.js";
3
+ import type { SandboxCapability, SandboxDenial } from "./types.js";
4
4
  /** Thrown by `provision()` when a backend can't start, such as a missing binary. The host must not run unconfined. */
5
5
  export declare class SandboxUnavailableError extends HarnessError {
6
6
  readonly name = "SandboxUnavailableError";
@@ -14,3 +14,31 @@ export declare class SandboxDeniedError extends HarnessError {
14
14
  readonly denial: SandboxDenial;
15
15
  constructor(denial: SandboxDenial);
16
16
  }
17
+ /**
18
+ * Thrown when the policy a backend read back from what it applied differs from the policy it was asked for, after
19
+ * `provision()` or a resume. After `provision()` the sandbox is disposed before the error is thrown, so nothing runs
20
+ * under the wrong policy; after `resumeSandbox()` it is left to the caller, who decides whether to dispose it. `field`
21
+ * names the first field that differs, such as `network.allow`. The message names only the field and, for `stops`, the
22
+ * cause, never a path or host from either policy.
23
+ */
24
+ export declare class SandboxPolicyMismatchError extends HarnessError {
25
+ readonly name = "SandboxPolicyMismatchError";
26
+ /**
27
+ * What differs: `readRoots`, `writeRoots`, `network.allow` or `network.deny` for the first field that differs;
28
+ * `stops` when the applied policy can't deliver a stop the backend claims; `readBack` when a backend that claims a
29
+ * stop has no read-back or its read-back fails; and `settings` when a settings file isn't in the shape its backend
30
+ * writes.
31
+ */
32
+ readonly field: string;
33
+ /** `options.reason` says why a claimed stop isn't delivered, and must not hold a path or host of either policy. */
34
+ constructor(field: string, options?: ErrorOptions & {
35
+ readonly reason?: string;
36
+ });
37
+ }
38
+ /** Thrown by `resumeSandbox()`, `snapshotSandbox()` and `pauseSandbox()` for a capability the backend doesn't list. */
39
+ export declare class SandboxUnsupportedError extends HarnessError {
40
+ readonly name = "SandboxUnsupportedError";
41
+ /** The capability that was asked for. */
42
+ readonly capability: SandboxCapability;
43
+ constructor(capability: SandboxCapability, tier: string);
44
+ }