@mnaimfaizy/agent-kit 1.0.0-alpha.12 → 1.0.0-beta.10
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.
- package/README.md +14 -6
- package/bin/agent-kit.mjs +3 -1
- package/package.json +1 -1
- package/src/callers.mjs +73 -10
- package/src/checks/kit-owned-trees.mjs +47 -4
- package/src/checks/result.mjs +8 -2
- package/src/checks/review-response.mjs +205 -0
- package/src/checks/rulesets.mjs +7 -2
- package/src/checks/scan-recipe.mjs +56 -0
- package/src/checks/secrets-and-variables.mjs +65 -15
- package/src/cli.mjs +306 -19
- package/src/deep-scan/agent.mjs +410 -0
- package/src/deep-scan/claude-code.mjs +25 -0
- package/src/deep-scan/credential.mjs +215 -0
- package/src/deep-scan/docker-driver.mjs +696 -0
- package/src/deep-scan/egress.mjs +150 -0
- package/src/deep-scan/lifecycle.mjs +703 -0
- package/src/deep-scan/limits.mjs +126 -0
- package/src/deep-scan/model-proxy.mjs +378 -0
- package/src/deep-scan/preflight.mjs +78 -0
- package/src/deep-scan/recipe.mjs +447 -0
- package/src/deep-scan/relay-script.mjs +98 -0
- package/src/deep-scan/relay.mjs +130 -0
- package/src/deep-scan/runtime.mjs +181 -0
- package/src/deep-scan/sbx-driver.mjs +501 -0
- package/src/deep-scan/steps.mjs +47 -0
- package/src/deep-scan/tar.mjs +84 -0
- package/src/deep-scan/verify.mjs +272 -0
- package/src/deep-scan.mjs +474 -0
- package/src/doctor.mjs +57 -16
- package/src/exec.mjs +225 -23
- package/src/init.mjs +653 -0
- package/src/kit-owned-paths.mjs +5 -3
- package/src/kit-tag.mjs +175 -28
- package/src/local-tree.mjs +142 -27
- package/src/local-writes.mjs +278 -0
- package/src/prompt.mjs +42 -0
- package/src/safe-paths.mjs +68 -0
- package/src/tags.mjs +15 -5
- package/src/templates.mjs +137 -0
- package/src/upgrade.mjs +288 -0
- package/src/workflow-call.mjs +3 -5
- package/src/yaml-subset.mjs +134 -24
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Sandbox runtime selection for the Deep scan launcher (#368, ADR 0018).
|
|
2
|
+
// The rule: the target never shares a kernel with the host OS or with the
|
|
3
|
+
// maintainer's other environments. The launcher chooses the runtime itself,
|
|
4
|
+
// from checks made on the host (the runtimes' own CLIs and Docker's runtime
|
|
5
|
+
// registry), never from a check inside the sandbox, which the target could
|
|
6
|
+
// fake. Preference: Docker Sandboxes, then Kata or Firecracker (Linux), then
|
|
7
|
+
// gVisor (Linux), the last two on Docker Engine 28.0 or later, whose
|
|
8
|
+
// isolated gateway mode leaves the host no address on a sandbox network
|
|
9
|
+
// (#404). A Mac uses Docker Sandboxes: Docker Desktop for macOS has no way
|
|
10
|
+
// to keep a container from the host's services. Everything else is refused,
|
|
11
|
+
// and there is no override. Every probe here only reads: nothing is started.
|
|
12
|
+
|
|
13
|
+
import { firstLine } from "../exec.mjs";
|
|
14
|
+
import { CLI_VERSION } from "../tags.mjs";
|
|
15
|
+
|
|
16
|
+
export const RUNTIMES_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs/security-audit.md#sandbox-runtimes`;
|
|
17
|
+
|
|
18
|
+
/** The lines every runtime refusal ends with: what is accepted, and the CI path. */
|
|
19
|
+
export const ACCEPTED_LINES = Object.freeze([
|
|
20
|
+
"Accepted runtimes: Docker Sandboxes (sbx); Kata Containers or Firecracker on Linux; gVisor (runsc) on Linux; the last two on Docker Engine 28.0 or later.",
|
|
21
|
+
"There is no override: on a host without one of them, use the CI path.",
|
|
22
|
+
"CI path: the deep-scan reusable workflow runs the scan in a gVisor container on an ephemeral GitHub-hosted runner.",
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
const PLATFORMS = { linux: "Linux", darwin: "macOS", win32: "Windows" };
|
|
26
|
+
|
|
27
|
+
/** The oldest Docker Engine deep-scan runs Kata, Firecracker or gVisor on. */
|
|
28
|
+
export const MIN_DOCKER_ENGINE = Object.freeze({ major: 28, minor: 0 });
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @typedef {{ id: "sbx" | "kata" | "firecracker" | "gvisor",
|
|
32
|
+
* name: string, dockerRuntime?: string }} Runtime
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Choose the sandbox runtime from the host, or refuse.
|
|
37
|
+
* @param {{ runner: import("../exec.mjs").Runner, platform: string }} opts
|
|
38
|
+
* @returns {{ runtime: Runtime } | { refused: string[] }}
|
|
39
|
+
*/
|
|
40
|
+
export function selectRuntime({ runner, platform }) {
|
|
41
|
+
const host = PLATFORMS[platform] ?? platform;
|
|
42
|
+
const succeeds = (cmd, args) => runner(cmd, args).status === 0;
|
|
43
|
+
|
|
44
|
+
if (succeeds("sbx", ["version"])) {
|
|
45
|
+
return { runtime: { id: "sbx", name: "Docker Sandboxes (sbx)" } };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const info = dockerInfo(runner);
|
|
49
|
+
// A Mac's one accepted runtime is Docker Sandboxes: say so in every refusal.
|
|
50
|
+
const mac =
|
|
51
|
+
platform === "darwin"
|
|
52
|
+
? [
|
|
53
|
+
"On macOS, deep-scan runs on Docker Sandboxes (sbx), whose per-sandbox policy lets the sandbox reach the model proxy's port alone: install it. Docker Desktop for macOS has no way to keep a container from your machine's other services.",
|
|
54
|
+
]
|
|
55
|
+
: [];
|
|
56
|
+
const refuse = (...lines) => ({ refused: [...lines, ...mac, ...ACCEPTED_LINES] });
|
|
57
|
+
|
|
58
|
+
if (platform === "linux" && info.ok) {
|
|
59
|
+
const viaDocker = (id, label, pattern, cli) => {
|
|
60
|
+
const name = registered(info.runtimes, pattern, id === "kata" ? FIRECRACKER : null);
|
|
61
|
+
if (name === null || !succeeds(cli, ["--version"])) return null;
|
|
62
|
+
return {
|
|
63
|
+
runtime: { id, name: `${label}, as the Docker runtime "${name}"`, dockerRuntime: name },
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
const chosen =
|
|
67
|
+
viaDocker("kata", "Kata Containers", KATA, "kata-runtime") ??
|
|
68
|
+
viaDocker("firecracker", "Firecracker", FIRECRACKER, "firecracker") ??
|
|
69
|
+
viaDocker("gvisor", "gVisor (runsc)", RUNSC, "runsc");
|
|
70
|
+
if (chosen) {
|
|
71
|
+
const old = engineTooOld(info.version);
|
|
72
|
+
if (old === null) return chosen;
|
|
73
|
+
return refuse(
|
|
74
|
+
old === "unknown"
|
|
75
|
+
? `Docker Engine's version is unknown (docker info shows ${JSON.stringify(info.version)}), and deep-scan runs ${chosen.runtime.name} only on ${MIN} or later: from ${MIN} a sandbox network can leave the host no address on it.`
|
|
76
|
+
: `Docker Engine ${info.version} is older than ${MIN}, the oldest deep-scan runs ${chosen.runtime.name} on: from ${MIN} a sandbox network can leave the host no address on it.`,
|
|
77
|
+
`Upgrade Docker Engine to ${MIN} or later, or use Docker Sandboxes (sbx).`,
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const install =
|
|
81
|
+
"Install one of: gVisor (runsc), Kata Containers or Firecracker, each registered as a Docker runtime, or Docker Sandboxes (sbx).";
|
|
82
|
+
if (info.os === "Docker Desktop") {
|
|
83
|
+
return refuse(
|
|
84
|
+
"Docker (Docker Desktop) on Linux is not an accepted sandbox runtime: its one VM is shared by every container.",
|
|
85
|
+
install,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
return refuse(
|
|
89
|
+
"Plain Docker on Linux shares the host's kernel with the target, so it is not an accepted sandbox runtime.",
|
|
90
|
+
install,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (
|
|
95
|
+
platform === "win32" &&
|
|
96
|
+
info.ok &&
|
|
97
|
+
info.os === "Docker Desktop" &&
|
|
98
|
+
/wsl2?\b|microsoft/i.test(info.kernel)
|
|
99
|
+
) {
|
|
100
|
+
return refuse(
|
|
101
|
+
"Docker Desktop on Windows with the WSL 2 backend is not an accepted sandbox runtime.",
|
|
102
|
+
"Its VM shares one Linux kernel and network namespace with your other WSL distros, so the target would share a kernel with them and could reach their network.",
|
|
103
|
+
"Install Docker Sandboxes (sbx), which gives each sandbox its own microVM.",
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (info.ok) {
|
|
108
|
+
return refuse(
|
|
109
|
+
`Docker (${info.os || "unknown"}) on ${host} is not an accepted sandbox runtime.`,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
return refuse(
|
|
113
|
+
`No accepted sandbox runtime found on this ${host} host.`,
|
|
114
|
+
...(info.error ? [`docker info failed: ${info.error}`] : []),
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const MIN = `${MIN_DOCKER_ENGINE.major}.${MIN_DOCKER_ENGINE.minor}`;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Null when Docker Engine `version` (`docker info`'s ServerVersion, such as
|
|
122
|
+
* "28.5.1" or "29.0.0-rc.1") is at least the minimum, "old" when it is
|
|
123
|
+
* older, "unknown" when it cannot be read.
|
|
124
|
+
*/
|
|
125
|
+
function engineTooOld(version) {
|
|
126
|
+
const m = /^(\d+)\.(\d+)(?:\D|$)/.exec(version);
|
|
127
|
+
if (!m) return "unknown";
|
|
128
|
+
const [major, minor] = [Number(m[1]), Number(m[2])];
|
|
129
|
+
const { major: needMajor, minor: needMinor } = MIN_DOCKER_ENGINE;
|
|
130
|
+
return major > needMajor || (major === needMajor && minor >= needMinor) ? null : "old";
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Kata with the Firecracker hypervisor (`kata-fc`) often shares Kata's shim
|
|
134
|
+
// path, so a runtime whose name says Firecracker is never counted as Kata.
|
|
135
|
+
const FIRECRACKER = /firecracker|kata-fc/i;
|
|
136
|
+
const KATA = /kata/i;
|
|
137
|
+
const RUNSC = /runsc/i;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The first Docker runtime whose name or path matches `pattern`, by name, or
|
|
141
|
+
* null. A runtime whose name matches `exclude` is skipped.
|
|
142
|
+
*/
|
|
143
|
+
function registered(runtimes, pattern, exclude = null) {
|
|
144
|
+
for (const [name, spec] of Object.entries(runtimes)) {
|
|
145
|
+
if (exclude?.test(name)) continue;
|
|
146
|
+
const path = spec && typeof spec === "object" && typeof spec.path === "string" ? spec.path : "";
|
|
147
|
+
if (pattern.test(name) || pattern.test(path)) return name;
|
|
148
|
+
}
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* What the host's Docker Engine says about itself: its OS, kernel and
|
|
154
|
+
* registered runtimes. Not installed, failing and unreadable are all "not ok".
|
|
155
|
+
*/
|
|
156
|
+
function dockerInfo(runner) {
|
|
157
|
+
const r = runner("docker", ["info", "--format", "{{json .}}"]);
|
|
158
|
+
if (r.status === null) return { ok: false, error: null };
|
|
159
|
+
if (r.status !== 0) return { ok: false, error: firstLine(r.stderr) || `exit ${r.status}` };
|
|
160
|
+
let info;
|
|
161
|
+
try {
|
|
162
|
+
info = JSON.parse(r.stdout);
|
|
163
|
+
} catch {
|
|
164
|
+
return { ok: false, error: "its output is not JSON" };
|
|
165
|
+
}
|
|
166
|
+
if (!info || typeof info !== "object") return { ok: false, error: "its output is not an object" };
|
|
167
|
+
const text = (v) => (typeof v === "string" ? v : "");
|
|
168
|
+
// Some Docker versions exit 0 when the daemon is down, and say so here.
|
|
169
|
+
const serverErrors = Array.isArray(info.ServerErrors) ? info.ServerErrors.map(text) : [];
|
|
170
|
+
if (serverErrors.some(Boolean)) {
|
|
171
|
+
return { ok: false, error: firstLine(serverErrors.filter(Boolean).join("\n")) };
|
|
172
|
+
}
|
|
173
|
+
const runtimes = info.Runtimes && typeof info.Runtimes === "object" ? info.Runtimes : {};
|
|
174
|
+
return {
|
|
175
|
+
ok: true,
|
|
176
|
+
os: text(info.OperatingSystem),
|
|
177
|
+
kernel: text(info.KernelVersion),
|
|
178
|
+
version: text(info.ServerVersion),
|
|
179
|
+
runtimes,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
// The sandbox driver for Docker Sandboxes (`sbx`, #369): one microVM per
|
|
2
|
+
// sandbox. Built only on the commands of sbx v0.54.0's own help, as the
|
|
3
|
+
// Chief of Staff captured it (run evidence sbx-help.txt; the line numbers
|
|
4
|
+
// below are that file's). The human chose this design (option 1):
|
|
5
|
+
//
|
|
6
|
+
// - The human's global sbx network policy must be deny-all. Per-sandbox rules
|
|
7
|
+
// only add to it, and a deny always wins over an allow (help 641-643, 676),
|
|
8
|
+
// so on any other global policy setup could reach more than `registries`.
|
|
9
|
+
// It is read with `sbx policy ls --json` (811-828) and never changed: the
|
|
10
|
+
// launcher never runs `sbx policy init` or `sbx policy reset`.
|
|
11
|
+
// - The sandbox is mountless: `sbx create` with no PATH (81-82, 103-104), the
|
|
12
|
+
// `shell` agent (86), and a template (`-t`, 173) that is not the recipe's
|
|
13
|
+
// image as it is. sbx v0.54.0 writes /home/agent/AGENTS.md as a sandbox
|
|
14
|
+
// starts, and a plain image has no /home/agent, so `-t <plain image>` never
|
|
15
|
+
// starts (#375's diagnosis, run evidence d375-sbx-diag.txt). The human chose
|
|
16
|
+
// (#375, option 1): Docker on the host pulls the recipe's image and layers
|
|
17
|
+
// on it the Docker driver's pinned Claude Code and what Docker's docs
|
|
18
|
+
// require of a template image (TEMPLATE_LAYER: a non-root `agent`, uid
|
|
19
|
+
// 1000, home /home/agent, as its USER; curl, git, CA certificates and
|
|
20
|
+
// bash, checked); `docker save` writes it to a private folder, `sbx template load`
|
|
21
|
+
// loads it, and `sbx create --pull never -t <it>` uses it. Teardown removes
|
|
22
|
+
// the template and the layered image. Only the pull and that fixed layer run
|
|
23
|
+
// on the host's Docker (Docker Desktop, the WSL 2 boundary a scan refuses),
|
|
24
|
+
// never a Consumer's own build steps, so a `dockerfile` recipe is refused.
|
|
25
|
+
// - Setup egress: `sbx policy allow network --sandbox` for each registry
|
|
26
|
+
// (986-987), removed with `sbx policy rm network --sandbox --resource` for
|
|
27
|
+
// the cut (1148, 1179-1180); `sbx policy ls <sandbox> --json` (812, 822)
|
|
28
|
+
// then shows, from the host, that no network allow is left.
|
|
29
|
+
// - Files move with `sbx cp`, whose host side is a path, not stdin (377-408):
|
|
30
|
+
// tars are written to a private host folder and unpacked inside; the
|
|
31
|
+
// report is copied into a private host folder and checked there.
|
|
32
|
+
// - The model route (#370): the key-injecting model proxy listens on the
|
|
33
|
+
// host's 127.0.0.1, which the sandbox calls as host.docker.internal:<its
|
|
34
|
+
// port>, and one per-sandbox rule allows only that, which sbx's policy
|
|
35
|
+
// names localhost:<its port>. No per-sandbox deny "**" is added: a
|
|
36
|
+
// deny beats every allow (676), so it would block the proxy too, and the
|
|
37
|
+
// global deny-all already decides everything else.
|
|
38
|
+
// - Teardown: `sbx rm --force` (449-457, 480).
|
|
39
|
+
// Every call passes `--no-input` (180), so sbx never waits on a prompt.
|
|
40
|
+
|
|
41
|
+
import { lstatSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
42
|
+
import { tmpdir } from "node:os";
|
|
43
|
+
import { join } from "node:path";
|
|
44
|
+
import { firstLine } from "../exec.mjs";
|
|
45
|
+
import { AUTO_UPDATER_OFF, layerDockerfile } from "./claude-code.mjs";
|
|
46
|
+
import { LABEL } from "./docker-driver.mjs";
|
|
47
|
+
import { allowlistOf } from "./egress.mjs";
|
|
48
|
+
import { ENDS_HERE, must, StepFailed } from "./steps.mjs";
|
|
49
|
+
|
|
50
|
+
const UNINITIALIZED = /global network policy has not been initialized/i;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Why the global sbx network policy is not deny-all, as refusal lines, or
|
|
54
|
+
* null when it is. From `sbx policy ls --json`: deny-all is the active global
|
|
55
|
+
* `default-deny-all` network rule denying "**", with no active global network
|
|
56
|
+
* allow rule beside it.
|
|
57
|
+
* @param {import("../exec.mjs").StartResult} r
|
|
58
|
+
* @returns {string[] | null}
|
|
59
|
+
*/
|
|
60
|
+
export function globalPolicyProblem(r) {
|
|
61
|
+
const text = `${r.stdout.toString("utf8")}\n${r.stderr}`;
|
|
62
|
+
const init =
|
|
63
|
+
"Run `sbx policy init deny-all` yourself (deep-scan never changes your sbx policy), then run deep-scan again.";
|
|
64
|
+
if (r.status !== 0) {
|
|
65
|
+
if (UNINITIALIZED.test(text)) {
|
|
66
|
+
return [
|
|
67
|
+
"REFUSED Docker Sandboxes' global network policy has not been initialized; deep-scan needs it to be deny-all.",
|
|
68
|
+
init,
|
|
69
|
+
];
|
|
70
|
+
}
|
|
71
|
+
return [
|
|
72
|
+
`REFUSED Could not read the Docker Sandboxes network policy: ${firstLine(r.stderr) || `exit ${r.status}`}`,
|
|
73
|
+
];
|
|
74
|
+
}
|
|
75
|
+
const rules = rulesOf(r);
|
|
76
|
+
if (rules === null) {
|
|
77
|
+
return [
|
|
78
|
+
"REFUSED Could not read the Docker Sandboxes network policy: `sbx policy ls --json` did not give a rules list.",
|
|
79
|
+
];
|
|
80
|
+
}
|
|
81
|
+
const network = rules.filter(
|
|
82
|
+
(rule) =>
|
|
83
|
+
rule.resource_type === "network" && rule.scope === "global" && rule.status === "active",
|
|
84
|
+
);
|
|
85
|
+
const denyAll = network.some(
|
|
86
|
+
(rule) =>
|
|
87
|
+
rule.id === "default-deny-all" &&
|
|
88
|
+
rule.decision === "deny" &&
|
|
89
|
+
Array.isArray(rule.resources) &&
|
|
90
|
+
rule.resources.includes("**"),
|
|
91
|
+
);
|
|
92
|
+
const allows = network.filter((rule) => rule.decision === "allow");
|
|
93
|
+
if (denyAll && allows.length === 0) return null;
|
|
94
|
+
return [
|
|
95
|
+
"REFUSED Docker Sandboxes' global network policy is not deny-all, so a sandbox's setup could reach more than the recipe's registries.",
|
|
96
|
+
...(allows.length
|
|
97
|
+
? [
|
|
98
|
+
`Global allow rules: ${allows.map((a) => String(a.id ?? a.name ?? "(no id)")).join(", ")}.`,
|
|
99
|
+
]
|
|
100
|
+
: []),
|
|
101
|
+
"deep-scan needs a deny-all global policy and never changes it itself: change it with `sbx policy`, for example `sbx policy init deny-all` on a fresh policy, then run deep-scan again.",
|
|
102
|
+
];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The rules list of `sbx policy ls --json`, or null. */
|
|
106
|
+
function rulesOf(r) {
|
|
107
|
+
try {
|
|
108
|
+
const parsed = JSON.parse(r.stdout.toString("utf8"));
|
|
109
|
+
return parsed && Array.isArray(parsed.rules)
|
|
110
|
+
? parsed.rules.filter((x) => x && typeof x === "object")
|
|
111
|
+
: null;
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Each registry as the sbx network resources that allow it: host:port. */
|
|
118
|
+
export function sbxResources(registries) {
|
|
119
|
+
const out = [];
|
|
120
|
+
for (const [host, ports] of allowlistOf(registries)) {
|
|
121
|
+
for (const port of ports)
|
|
122
|
+
out.push(host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`);
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* @param {{ id: string, call: import("./docker-driver.mjs").Call }} opts
|
|
129
|
+
* @returns {import("./lifecycle.mjs").Driver}
|
|
130
|
+
*/
|
|
131
|
+
export function sbxDriver({ id, call }) {
|
|
132
|
+
const name = `agent-kit-deep-${id}`;
|
|
133
|
+
/** The layered image, and the sbx template loaded from it. */
|
|
134
|
+
const template = `${name}:sbx`;
|
|
135
|
+
const sbx = (args, opts) => call("sbx", ["--no-input", ...args], opts);
|
|
136
|
+
const docker = (args, opts) => call("docker", args, opts);
|
|
137
|
+
let created = false;
|
|
138
|
+
let imageBuilt = false; // asked for, so removed whether or not it finished
|
|
139
|
+
let templateLoaded = false;
|
|
140
|
+
/** The loaded template's image id: removing it removes every tag sbx gave it. */
|
|
141
|
+
let templateId = null;
|
|
142
|
+
/** The per-sandbox allow rules in place, as their resource lists. */
|
|
143
|
+
const allowed = [];
|
|
144
|
+
let host = null; // a private host folder for the files sbx cp moves
|
|
145
|
+
let copies = 0;
|
|
146
|
+
let modelRoute = null; // the one allow rule the scan may have
|
|
147
|
+
let modelProxy = null;
|
|
148
|
+
|
|
149
|
+
const hostDir = () => (host ??= mkdtempSync(join(tmpdir(), "agent-kit-deep-scan-sbx-")));
|
|
150
|
+
|
|
151
|
+
const allow = async (resources, what) => {
|
|
152
|
+
const list = resources.join(",");
|
|
153
|
+
allowed.push(list);
|
|
154
|
+
must(await sbx(["policy", "allow", "network", "--sandbox", name, list]), what);
|
|
155
|
+
};
|
|
156
|
+
const disallow = async (list, what) => {
|
|
157
|
+
must(
|
|
158
|
+
await sbx(["policy", "rm", "network", "--sandbox", name, "--resource", list, "--force"]),
|
|
159
|
+
what,
|
|
160
|
+
);
|
|
161
|
+
allowed.splice(allowed.indexOf(list), 1);
|
|
162
|
+
};
|
|
163
|
+
const exec = (script, { env = [], workdir = "/workspace", user } = {}) =>
|
|
164
|
+
sbx([
|
|
165
|
+
"exec",
|
|
166
|
+
...(user ? ["-u", user] : []),
|
|
167
|
+
...env.flatMap((v) => ["-e", v]),
|
|
168
|
+
...(workdir ? ["-w", workdir] : []),
|
|
169
|
+
name,
|
|
170
|
+
"sh",
|
|
171
|
+
"-c",
|
|
172
|
+
script,
|
|
173
|
+
]);
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
container: name,
|
|
177
|
+
|
|
178
|
+
async prepare(steps, { out }) {
|
|
179
|
+
if (steps.dockerfile !== undefined) {
|
|
180
|
+
throw new StepFailed([
|
|
181
|
+
`REFUSED The recipe builds ${steps.dockerfile}, and on Docker Sandboxes its build steps would run on this machine's Docker (Docker Desktop's WSL 2 VM on Windows), outside the sandbox.`,
|
|
182
|
+
"On Docker Sandboxes, name a base image with `image:` instead (one with Node.js and npm), or run on another accepted runtime.",
|
|
183
|
+
]);
|
|
184
|
+
}
|
|
185
|
+
const problem = globalPolicyProblem(await sbx(["policy", "ls", "--json"]));
|
|
186
|
+
if (problem) throw new StepFailed(problem);
|
|
187
|
+
out("Network policy: Docker Sandboxes' global policy is deny-all (checked read-only).");
|
|
188
|
+
out(
|
|
189
|
+
`Image: layering the pinned Claude Code on ${steps.image} with Docker on this machine, auto-updater off, as the sandbox's template.`,
|
|
190
|
+
);
|
|
191
|
+
const pulled = await docker(["pull", steps.image]);
|
|
192
|
+
if (pulled.status === null) {
|
|
193
|
+
throw new StepFailed([
|
|
194
|
+
"FAILED Docker Sandboxes' template is built with Docker on this machine, and docker could not run: " +
|
|
195
|
+
(firstLine(pulled.stderr) || "not found"),
|
|
196
|
+
"Install Docker Desktop (it only builds the template here; the scan runs in the sbx microVM), then run deep-scan again.",
|
|
197
|
+
ENDS_HERE,
|
|
198
|
+
]);
|
|
199
|
+
}
|
|
200
|
+
must(pulled, `pulling ${steps.image}`, { showOutput: true });
|
|
201
|
+
imageBuilt = true;
|
|
202
|
+
must(
|
|
203
|
+
await docker(["build", "--label", `${LABEL}=${id}`, "--tag", template, "-"], {
|
|
204
|
+
stdin: `${layerDockerfile(steps.image)}${TEMPLATE_LAYER}`,
|
|
205
|
+
}),
|
|
206
|
+
`layering Claude Code on ${steps.image}`,
|
|
207
|
+
{ showOutput: true },
|
|
208
|
+
);
|
|
209
|
+
// A private host file, by a name relative to its folder, so a Windows
|
|
210
|
+
// drive letter is never read as anything else; gone once it is loaded.
|
|
211
|
+
const tar = "template.tar";
|
|
212
|
+
try {
|
|
213
|
+
must(
|
|
214
|
+
await docker(["save", "--output", tar, template], { cwd: hostDir() }),
|
|
215
|
+
"saving the layered image",
|
|
216
|
+
);
|
|
217
|
+
must(
|
|
218
|
+
await sbx(["template", "load", tar], { cwd: hostDir() }),
|
|
219
|
+
"loading the layered image into Docker Sandboxes",
|
|
220
|
+
{ showOutput: true },
|
|
221
|
+
);
|
|
222
|
+
templateLoaded = true;
|
|
223
|
+
templateId = idOf(
|
|
224
|
+
await sbx(["template", "ls", "--json"]),
|
|
225
|
+
`docker.io/library/${template.split(":")[0]}`,
|
|
226
|
+
"sbx",
|
|
227
|
+
);
|
|
228
|
+
} finally {
|
|
229
|
+
rmSync(join(hostDir(), tar), { force: true });
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
async start() {
|
|
234
|
+
created = true;
|
|
235
|
+
must(
|
|
236
|
+
await sbx([
|
|
237
|
+
"create",
|
|
238
|
+
"--name",
|
|
239
|
+
name,
|
|
240
|
+
"--no-progress",
|
|
241
|
+
"--pull",
|
|
242
|
+
"never",
|
|
243
|
+
"-t",
|
|
244
|
+
template,
|
|
245
|
+
"-e",
|
|
246
|
+
AUTO_UPDATER_OFF,
|
|
247
|
+
"shell",
|
|
248
|
+
]),
|
|
249
|
+
"creating the sandbox",
|
|
250
|
+
{ showOutput: true },
|
|
251
|
+
);
|
|
252
|
+
},
|
|
253
|
+
|
|
254
|
+
async copyIn(tar, what) {
|
|
255
|
+
const file = `in-${copies++}.tar`;
|
|
256
|
+
writeFileSync(join(hostDir(), file), tar, { mode: 0o600 });
|
|
257
|
+
const inside = `/tmp/agent-kit-${file}`;
|
|
258
|
+
try {
|
|
259
|
+
// Relative to the private folder, so a Windows drive letter is never
|
|
260
|
+
// read as a sandbox name.
|
|
261
|
+
must(await sbx(["cp", file, `${name}:${inside}`], { cwd: hostDir() }), what);
|
|
262
|
+
} finally {
|
|
263
|
+
rmSync(join(hostDir(), file), { force: true });
|
|
264
|
+
}
|
|
265
|
+
must(
|
|
266
|
+
await exec(
|
|
267
|
+
// Unpacked as root; then the sandbox's own user may write there.
|
|
268
|
+
`tar -xf ${inside} -C / && rm -f ${inside} && { chmod -R a+rwX /workspace /agent-kit 2>/dev/null || true; }`,
|
|
269
|
+
{ user: "root", workdir: null },
|
|
270
|
+
),
|
|
271
|
+
`${what} (unpacking it)`,
|
|
272
|
+
{ showOutput: true },
|
|
273
|
+
);
|
|
274
|
+
},
|
|
275
|
+
|
|
276
|
+
/** Claude Code is in the template already: nothing to install. */
|
|
277
|
+
async installAgent() {},
|
|
278
|
+
|
|
279
|
+
async openSetupEgress(registries) {
|
|
280
|
+
const resources = sbxResources(registries);
|
|
281
|
+
if (!resources.length) return { env: [], note: "no registries, so no network" };
|
|
282
|
+
await allow(resources, "allowing the recipe's registries for setup");
|
|
283
|
+
return {
|
|
284
|
+
env: [],
|
|
285
|
+
note: `egress limited to ${registries.join(", ")}, by a per-sandbox sbx policy on a deny-all global policy`,
|
|
286
|
+
};
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
refused: () => [],
|
|
290
|
+
|
|
291
|
+
exec,
|
|
292
|
+
|
|
293
|
+
async cutEgress() {
|
|
294
|
+
for (const list of [...allowed]) await disallow(list, "cutting the network");
|
|
295
|
+
},
|
|
296
|
+
|
|
297
|
+
async egressLeft() {
|
|
298
|
+
const r = must(
|
|
299
|
+
await sbx(["policy", "ls", name, "--json"]),
|
|
300
|
+
"checking that the network is cut",
|
|
301
|
+
);
|
|
302
|
+
const rules = rulesOf(r);
|
|
303
|
+
if (rules === null) return "sbx policy ls shows no readable rules";
|
|
304
|
+
const open = rules.filter(
|
|
305
|
+
(rule) =>
|
|
306
|
+
rule.resource_type === "network" &&
|
|
307
|
+
rule.decision === "allow" &&
|
|
308
|
+
rule.status === "active" &&
|
|
309
|
+
!(
|
|
310
|
+
modelRoute &&
|
|
311
|
+
Array.isArray(rule.resources) &&
|
|
312
|
+
rule.resources.length > 0 &&
|
|
313
|
+
rule.resources.every((r) => r === modelRoute)
|
|
314
|
+
),
|
|
315
|
+
);
|
|
316
|
+
if (open.length) {
|
|
317
|
+
return `sbx policy ls still allows ${open.map((o) => (Array.isArray(o.resources) ? o.resources.join(",") : String(o.id))).join("; ")}`;
|
|
318
|
+
}
|
|
319
|
+
const denied = rules.some(
|
|
320
|
+
(rule) =>
|
|
321
|
+
rule.id === "default-deny-all" &&
|
|
322
|
+
rule.resource_type === "network" &&
|
|
323
|
+
rule.decision === "deny" &&
|
|
324
|
+
rule.status === "active",
|
|
325
|
+
);
|
|
326
|
+
return denied ? null : "sbx policy ls no longer shows the deny-all rule";
|
|
327
|
+
},
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Allow only the model proxy on the host. The sandbox calls it as
|
|
331
|
+
* host.docker.internal:<port>, which sbx v0.54.0's policy checks as
|
|
332
|
+
* localhost:<port> (#375's diagnosis), so the rule names that.
|
|
333
|
+
*/
|
|
334
|
+
async openModelRoute(startProxy) {
|
|
335
|
+
const bind = "127.0.0.1";
|
|
336
|
+
try {
|
|
337
|
+
modelProxy = await startProxy(bind);
|
|
338
|
+
} catch (e) {
|
|
339
|
+
throw new StepFailed([
|
|
340
|
+
`FAILED starting the model proxy on ${bind}: ${e.message}`,
|
|
341
|
+
ENDS_HERE,
|
|
342
|
+
]);
|
|
343
|
+
}
|
|
344
|
+
modelRoute = `localhost:${modelProxy.port}`;
|
|
345
|
+
await allow([modelRoute], "allowing the model proxy, and nothing else, for the scan");
|
|
346
|
+
return {
|
|
347
|
+
url: `http://host.docker.internal:${modelProxy.port}`,
|
|
348
|
+
note: `host.docker.internal:${modelProxy.port} from the sandbox, a per-sandbox sbx policy allowing only ${modelRoute}`,
|
|
349
|
+
};
|
|
350
|
+
},
|
|
351
|
+
|
|
352
|
+
async copyOut(path, { maxBytes }) {
|
|
353
|
+
// `sbx cp` writes whatever is there to the host before the checks
|
|
354
|
+
// below can look, so check type and size in the sandbox first: a
|
|
355
|
+
// filter against filling the host's disk, not the check itself.
|
|
356
|
+
if (!/^[\w./-]+$/.test(path)) throw new Error(`copyOut: unsafe path ${path}`);
|
|
357
|
+
const pre = await exec(
|
|
358
|
+
`p=${path}; if [ -e "$p" ] || [ -L "$p" ]; then { [ -f "$p" ] && [ ! -L "$p" ]; } || exit 4; [ "$(wc -c < "$p")" -le ${maxBytes} ] || exit 5; fi`,
|
|
359
|
+
{ workdir: "" },
|
|
360
|
+
);
|
|
361
|
+
if (pre.status === 4) return { error: "it is not a regular file (checked in the sandbox)" };
|
|
362
|
+
if (pre.status === 5) {
|
|
363
|
+
return {
|
|
364
|
+
error: `it is larger than ${maxBytes / 1024 / 1024} MiB (checked in the sandbox)`,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
const into = mkdtempSync(join(hostDir(), "out-"));
|
|
368
|
+
const r = await sbx(["cp", `${name}:${path}`, "."], { cwd: into });
|
|
369
|
+
if (r.status !== 0) return { missing: r };
|
|
370
|
+
const entries = readdirSync(into);
|
|
371
|
+
if (entries.length !== 1)
|
|
372
|
+
return { error: `the copy holds ${entries.length} entries, not one file` };
|
|
373
|
+
const file = join(into, entries[0]);
|
|
374
|
+
const stat = lstatSync(file);
|
|
375
|
+
if (!stat.isFile()) return { error: `${entries[0]} is not a regular file` };
|
|
376
|
+
if (stat.size > maxBytes) return { error: `it is larger than ${maxBytes / 1024 / 1024} MiB` };
|
|
377
|
+
return { name: entries[0], data: readFileSync(file) };
|
|
378
|
+
},
|
|
379
|
+
|
|
380
|
+
async close() {
|
|
381
|
+
if (modelProxy) {
|
|
382
|
+
const p = modelProxy;
|
|
383
|
+
modelProxy = null;
|
|
384
|
+
await p.close();
|
|
385
|
+
}
|
|
386
|
+
},
|
|
387
|
+
|
|
388
|
+
teardown() {
|
|
389
|
+
return [
|
|
390
|
+
...(created ? sandboxTeardown() : []),
|
|
391
|
+
...(templateLoaded
|
|
392
|
+
? [
|
|
393
|
+
{
|
|
394
|
+
what: `template ${template}`,
|
|
395
|
+
cmd: "sbx",
|
|
396
|
+
// By id when sbx listed it: a create gives the template a
|
|
397
|
+
// second, assembled tag, which removing the tag alone leaves.
|
|
398
|
+
args: ["--no-input", "template", "rm", "--force", templateId ?? template],
|
|
399
|
+
},
|
|
400
|
+
]
|
|
401
|
+
: []),
|
|
402
|
+
...(imageBuilt
|
|
403
|
+
? [
|
|
404
|
+
{
|
|
405
|
+
what: `image ${template}`,
|
|
406
|
+
cmd: "docker",
|
|
407
|
+
args: ["image", "rm", "--force", template],
|
|
408
|
+
},
|
|
409
|
+
]
|
|
410
|
+
: []),
|
|
411
|
+
];
|
|
412
|
+
},
|
|
413
|
+
|
|
414
|
+
/** Remove the private host folder the copies went through. */
|
|
415
|
+
cleanup() {
|
|
416
|
+
if (host) rmSync(host, { recursive: true, force: true });
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
function sandboxTeardown() {
|
|
421
|
+
return [
|
|
422
|
+
...allowed.map((list) => ({
|
|
423
|
+
what: `the sbx policy rule for ${list}`,
|
|
424
|
+
cmd: "sbx",
|
|
425
|
+
args: [
|
|
426
|
+
"--no-input",
|
|
427
|
+
"policy",
|
|
428
|
+
"rm",
|
|
429
|
+
"network",
|
|
430
|
+
"--sandbox",
|
|
431
|
+
name,
|
|
432
|
+
"--resource",
|
|
433
|
+
list,
|
|
434
|
+
"--force",
|
|
435
|
+
],
|
|
436
|
+
})),
|
|
437
|
+
{ what: `sandbox ${name}`, cmd: "sbx", args: ["--no-input", "rm", "--force", name] },
|
|
438
|
+
];
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* A template's image id (hex, no `sha256:`) from `sbx template ls --json`,
|
|
444
|
+
* or null when it is not listed or the list cannot be read.
|
|
445
|
+
* @param {import("../exec.mjs").StartResult} r
|
|
446
|
+
* @param {string} repository
|
|
447
|
+
* @param {string} tag
|
|
448
|
+
*/
|
|
449
|
+
function idOf(r, repository, tag) {
|
|
450
|
+
if (r.status !== 0) return null;
|
|
451
|
+
try {
|
|
452
|
+
const list = JSON.parse(r.stdout.toString("utf8"));
|
|
453
|
+
const entry = Array.isArray(list)
|
|
454
|
+
? list.find((t) => t && t.repository === repository && t.tag === tag)
|
|
455
|
+
: undefined;
|
|
456
|
+
const id = typeof entry?.id === "string" ? entry.id.replace(/^sha256:/, "") : "";
|
|
457
|
+
return /^[0-9a-f]{64}$/.test(id) ? id : null;
|
|
458
|
+
} catch {
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* The layer that makes an image a Docker Sandboxes template, as Docker's
|
|
465
|
+
* docs require of one (docs.docker.com/ai/sandboxes/customize/author/
|
|
466
|
+
* base-images/): curl, git, CA certificates, /bin/sh and /bin/bash, and a
|
|
467
|
+
* non-root `agent` account, uid 1000 with home /home/agent, set as the
|
|
468
|
+
* image's USER. sbx writes /home/agent/AGENTS.md as a sandbox starts, so
|
|
469
|
+
* without that home no sandbox starts at all.
|
|
470
|
+
*
|
|
471
|
+
* The tools are checked, never installed: an install would reach the base
|
|
472
|
+
* image's package mirror from the host, which no recipe field names. An
|
|
473
|
+
* existing uid 1000 account (`node`, in the Node.js images) is renamed to
|
|
474
|
+
* `agent`, its home moved, rather than given a second name for one uid.
|
|
475
|
+
* It runs as root, after the Claude Code layer, and ends on USER agent.
|
|
476
|
+
*/
|
|
477
|
+
const TEMPLATE_LAYER = [
|
|
478
|
+
"USER root",
|
|
479
|
+
"RUN set -eu; \\",
|
|
480
|
+
" missing=''; \\",
|
|
481
|
+
' for tool in curl git bash sh; do command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"; done; \\',
|
|
482
|
+
' [ -s /etc/ssl/certs/ca-certificates.crt ] || [ -s /etc/pki/tls/certs/ca-bundle.crt ] || missing="$missing ca-certificates"; \\',
|
|
483
|
+
' if [ -n "$missing" ]; then \\',
|
|
484
|
+
' echo "agent-kit deep-scan: the recipe\'s image lacks$missing, which a Docker Sandboxes template needs (curl, git, CA certificates, sh and bash). Name an image that has them." >&2; exit 1; \\',
|
|
485
|
+
" fi; \\",
|
|
486
|
+
" command -v useradd >/dev/null 2>&1 && command -v usermod >/dev/null 2>&1 || { \\",
|
|
487
|
+
' echo "agent-kit deep-scan: the recipe\'s image has no useradd and usermod, to make the agent account a Docker Sandboxes template needs." >&2; exit 1; }; \\',
|
|
488
|
+
' existing="$(getent passwd 1000 | cut -d: -f1)"; \\',
|
|
489
|
+
' if [ "$existing" = agent ]; then :; \\',
|
|
490
|
+
' elif [ -n "$existing" ]; then \\',
|
|
491
|
+
' usermod -l agent -d /home/agent -m "$existing"; \\',
|
|
492
|
+
' group="$(getent group 1000 | cut -d: -f1)"; \\',
|
|
493
|
+
' if [ -n "$group" ] && [ "$group" != agent ]; then groupmod -n agent "$group"; fi; \\',
|
|
494
|
+
" else \\",
|
|
495
|
+
" getent group 1000 >/dev/null || groupadd -g 1000 agent; \\",
|
|
496
|
+
" useradd -u 1000 -g 1000 -m -d /home/agent -s /bin/bash agent; \\",
|
|
497
|
+
" fi; \\",
|
|
498
|
+
" mkdir -p /home/agent; chown 1000:1000 /home/agent",
|
|
499
|
+
"USER agent",
|
|
500
|
+
"",
|
|
501
|
+
].join("\n");
|