@mnaimfaizy/agent-kit 1.0.0-beta.1 → 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 +8 -3
- package/package.json +1 -1
- package/src/callers.mjs +35 -10
- package/src/checks/kit-owned-trees.mjs +45 -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 +163 -8
- 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 +14 -10
- package/src/exec.mjs +222 -33
- package/src/init.mjs +35 -9
- package/src/kit-owned-paths.mjs +5 -3
- package/src/kit-tag.mjs +12 -3
- package/src/local-tree.mjs +69 -4
- package/src/local-writes.mjs +4 -33
- package/src/templates.mjs +12 -8
- package/src/workflow-call.mjs +3 -5
- package/src/yaml-subset.mjs +134 -24
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
// The Scan recipe: where it lives, how it is read, and what a valid one holds.
|
|
2
|
+
//
|
|
3
|
+
// The recipe is read at the trusted ref (the default branch's tip) with git,
|
|
4
|
+
// never from the working tree and never from issue or pull request text, so
|
|
5
|
+
// nothing an outsider writes can change what a Deep scan builds or runs.
|
|
6
|
+
// Validation returns every problem at once, each naming its field.
|
|
7
|
+
|
|
8
|
+
import { CLI_VERSION } from "../tags.mjs";
|
|
9
|
+
import { checkSafePath } from "../safe-paths.mjs";
|
|
10
|
+
import {
|
|
11
|
+
isMapping,
|
|
12
|
+
parseScalar,
|
|
13
|
+
parseYamlSubset,
|
|
14
|
+
stripBom,
|
|
15
|
+
stripComment,
|
|
16
|
+
} from "../yaml-subset.mjs";
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_RECIPE_PATH = ".security/scan-recipe.yml";
|
|
19
|
+
|
|
20
|
+
/** The recipe-format docs, at the tag this CLI was published from. */
|
|
21
|
+
export const RECIPE_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs/security-audit.md#scan-recipe`;
|
|
22
|
+
|
|
23
|
+
/** A recipe larger than this is refused unread: a real one is a page or two. */
|
|
24
|
+
export const MAX_RECIPE_BYTES = 256 * 1024;
|
|
25
|
+
|
|
26
|
+
export const RECIPE_FIELDS = [
|
|
27
|
+
"image",
|
|
28
|
+
"dockerfile",
|
|
29
|
+
"setup",
|
|
30
|
+
"registries",
|
|
31
|
+
"start",
|
|
32
|
+
"ready",
|
|
33
|
+
"seed",
|
|
34
|
+
"entry_points",
|
|
35
|
+
"fixtures",
|
|
36
|
+
"grounding",
|
|
37
|
+
"notes",
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
const ENTRY_KINDS = ["url", "port", "command"];
|
|
41
|
+
|
|
42
|
+
// Keys that would set a limit. Limits come from launcher flags or workflow
|
|
43
|
+
// inputs only, so a merged recipe change can never raise a run's spend.
|
|
44
|
+
const LIMIT_KEY =
|
|
45
|
+
/(?:^|_)(?:limits?|timeouts?|turns|max_turns|tokens?|token_cap|budget|spend|wall_clock|minutes|seconds|duration)(?:$|_)/i;
|
|
46
|
+
const COMPOSE_KEY =
|
|
47
|
+
/^(?:compose|compose_file|docker_compose|services|containers|sidecars|sibling_containers)$/i;
|
|
48
|
+
const SOCKET_KEY = /^(?:docker_socket|socket|docker_host)$/i;
|
|
49
|
+
const COMPOSE_FILE = /(?:^|\/)(?:docker-)?compose\.ya?ml$/i;
|
|
50
|
+
const CONTAINER_COMMAND = /(?:^|[\s;&|(`])(?:docker|docker-compose|podman|nerdctl)(?=\s|$)/m;
|
|
51
|
+
|
|
52
|
+
// Shapes of real credentials. Fixtures and every other field hold fake
|
|
53
|
+
// values only: the recipe is committed, and the sandbox is not a secret store.
|
|
54
|
+
const CREDENTIALS = [
|
|
55
|
+
[/\bgh[pousr]_[A-Za-z0-9]{20,}/, "a GitHub token"],
|
|
56
|
+
[/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token"],
|
|
57
|
+
[/\bsk-ant-[A-Za-z0-9_-]{10,}/, "an Anthropic API key"],
|
|
58
|
+
[/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key"],
|
|
59
|
+
[/\bxox[abposr]-[A-Za-z0-9-]{10,}/, "a Slack token"],
|
|
60
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----/, "a private key"],
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
export class RecipeError extends Error {}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Read the recipe at `ref` (a commit). Returns `{ found: false }` when the
|
|
67
|
+
* ref has no file at `path`, else `{ found: true, text, oid }`. Throws
|
|
68
|
+
* RecipeError when `path` is unsafe, or names a folder, a symbolic link or a
|
|
69
|
+
* submodule, or the file is too large.
|
|
70
|
+
*
|
|
71
|
+
* @param {{ runner: import("../exec.mjs").Runner, root: string, ref: string, path: string }} opts
|
|
72
|
+
*/
|
|
73
|
+
export function readRecipeAtRef({ runner, root, ref, path }) {
|
|
74
|
+
const listed = runner("git", ["-C", root, "ls-tree", "--full-tree", "-z", ref, "--", path]);
|
|
75
|
+
if (listed.status !== 0) {
|
|
76
|
+
throw new RecipeError(`git could not list ${path} at ${ref}: ${listed.stderr.trim()}`);
|
|
77
|
+
}
|
|
78
|
+
const entry = listed.stdout.split("\0").find((e) => e.endsWith(`\t${path}`));
|
|
79
|
+
if (!entry) return { found: false };
|
|
80
|
+
const [mode, type, oid] = entry.slice(0, entry.indexOf("\t")).split(" ");
|
|
81
|
+
if (type !== "blob")
|
|
82
|
+
throw new RecipeError(`${path} is a ${type === "tree" ? "folder" : type}, not a file.`);
|
|
83
|
+
if (mode === "120000")
|
|
84
|
+
throw new RecipeError(`${path} is a symbolic link; commit the recipe itself.`);
|
|
85
|
+
const size = runner("git", ["-C", root, "cat-file", "-s", oid]);
|
|
86
|
+
if (size.status !== 0) throw new RecipeError(`git could not read ${path}: ${size.stderr.trim()}`);
|
|
87
|
+
if (Number(size.stdout.trim()) > MAX_RECIPE_BYTES) {
|
|
88
|
+
throw new RecipeError(`${path} is larger than ${MAX_RECIPE_BYTES / 1024} KiB.`);
|
|
89
|
+
}
|
|
90
|
+
const blob = runner("git", ["-C", root, "cat-file", "blob", oid]);
|
|
91
|
+
if (blob.status !== 0) throw new RecipeError(`git could not read ${path}: ${blob.stderr.trim()}`);
|
|
92
|
+
return { found: true, text: blob.stdout, oid };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Every problem with a recipe's text, each one line naming its field. An
|
|
97
|
+
* empty list means the recipe is valid.
|
|
98
|
+
*
|
|
99
|
+
* @param {string} text
|
|
100
|
+
* @returns {string[]}
|
|
101
|
+
*/
|
|
102
|
+
export function validateRecipe(text) {
|
|
103
|
+
const problems = [];
|
|
104
|
+
const say = (field, problem) => problems.push(`${field}: ${problem}`);
|
|
105
|
+
if (stripBom(text).trim() === "") return ["the recipe is empty."];
|
|
106
|
+
|
|
107
|
+
const lines = lineProblems(text);
|
|
108
|
+
for (const key of lines.twice) say(key, "is given more than once.");
|
|
109
|
+
for (const problem of lines.problems) problems.push(problem);
|
|
110
|
+
// A null-prototype copy: a `__proto__:` key becomes an ordinary key that
|
|
111
|
+
// the field checks see and refuse, never a hidden prototype.
|
|
112
|
+
const recipe = ownCopy(parseYamlSubset(text, { problems }));
|
|
113
|
+
|
|
114
|
+
for (const key of Object.keys(recipe)) {
|
|
115
|
+
const problem = keyProblem(key, RECIPE_FIELDS);
|
|
116
|
+
if (problem) say(key, problem);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// image or dockerfile, exactly one.
|
|
120
|
+
const hasImage = "image" in recipe;
|
|
121
|
+
const hasDockerfile = "dockerfile" in recipe;
|
|
122
|
+
if (!hasImage && !hasDockerfile) {
|
|
123
|
+
say(
|
|
124
|
+
"image or dockerfile",
|
|
125
|
+
"name a base image (image) or a Dockerfile (dockerfile); the recipe has neither.",
|
|
126
|
+
);
|
|
127
|
+
} else if (hasImage && hasDockerfile) {
|
|
128
|
+
say("image and dockerfile", "give one of them, not both.");
|
|
129
|
+
}
|
|
130
|
+
if (hasImage && !isWord(recipe.image)) {
|
|
131
|
+
say("image", "must be one image reference, such as node:22-bookworm.");
|
|
132
|
+
}
|
|
133
|
+
if (hasDockerfile) {
|
|
134
|
+
const file = recipe.dockerfile;
|
|
135
|
+
if (typeof file !== "string" || file === "") {
|
|
136
|
+
say("dockerfile", "must be a path in the repository, such as Dockerfile.");
|
|
137
|
+
} else if (COMPOSE_FILE.test(file)) {
|
|
138
|
+
say("dockerfile", composeProblem());
|
|
139
|
+
} else {
|
|
140
|
+
try {
|
|
141
|
+
checkSafePath(file, "dockerfile");
|
|
142
|
+
} catch (err) {
|
|
143
|
+
say("dockerfile", `${err.message}; give a path relative to the repository root.`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Commands: setup is required, start, ready and seed are optional.
|
|
149
|
+
const commands = {};
|
|
150
|
+
for (const field of ["setup", "start", "ready", "seed"]) {
|
|
151
|
+
if (!(field in recipe)) continue;
|
|
152
|
+
commands[field] = commandList(recipe[field], field, say);
|
|
153
|
+
if ((field === "start" || field === "ready") && commands[field]?.length === 0) {
|
|
154
|
+
say(field, "is empty; leave start and ready out when every entry point is a command.");
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (!("setup" in recipe)) {
|
|
158
|
+
say("setup", "is missing; list the commands that install dependencies (or write setup: []).");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (!("registries" in recipe)) {
|
|
162
|
+
say("registries", "is missing; list the hosts setup may reach (or write registries: []).");
|
|
163
|
+
} else {
|
|
164
|
+
const list = asList(recipe.registries, "registries", say);
|
|
165
|
+
list?.forEach((r, i) => {
|
|
166
|
+
if (!isWord(r)) say(`registries[${i}]`, "must be one host name or URL.");
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Entry points: at least one, each a url, port or command with a note.
|
|
171
|
+
let entries = null;
|
|
172
|
+
if (!("entry_points" in recipe)) {
|
|
173
|
+
say("entry_points", "is missing; list what the scan may probe, each with a note.");
|
|
174
|
+
} else {
|
|
175
|
+
entries = asList(recipe.entry_points, "entry_points", say);
|
|
176
|
+
if (entries && entries.length === 0) {
|
|
177
|
+
say("entry_points", "is empty; list at least one url, port or command to probe.");
|
|
178
|
+
}
|
|
179
|
+
entries?.forEach((entry, i) => entryProblems(entry, `entry_points[${i}]`, say));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// start and ready come as a pair, and are optional only when every entry
|
|
183
|
+
// point is a command (a CLI needs no server).
|
|
184
|
+
const hasStart = "start" in recipe;
|
|
185
|
+
const hasReady = "ready" in recipe;
|
|
186
|
+
if (hasStart && !hasReady) {
|
|
187
|
+
say(
|
|
188
|
+
"start",
|
|
189
|
+
"is given without ready; add ready, the commands that confirm the services are up.",
|
|
190
|
+
);
|
|
191
|
+
} else if (hasReady && !hasStart) {
|
|
192
|
+
say("ready", "is given without start; add start, the commands that start the services.");
|
|
193
|
+
} else if (!hasStart && entries) {
|
|
194
|
+
const i = entries.findIndex((e) => isMapping(e) && !("command" in e));
|
|
195
|
+
if (i >= 0) {
|
|
196
|
+
const kind = ENTRY_KINDS.find((k) => k in entries[i]);
|
|
197
|
+
say(
|
|
198
|
+
"start and ready",
|
|
199
|
+
`are missing, and entry_points[${i}] ${kind ? `is a ${kind}` : "is not a command"}: they may be left out only when every entry point is a command.`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (!("fixtures" in recipe)) {
|
|
205
|
+
say(
|
|
206
|
+
"fixtures",
|
|
207
|
+
"is missing; list the test users and roles, with fake values (or write fixtures: []).",
|
|
208
|
+
);
|
|
209
|
+
} else {
|
|
210
|
+
asList(recipe.fixtures, "fixtures", say)?.forEach((f, i) => {
|
|
211
|
+
if (!isMapping(f)) say(`fixtures[${i}]`, "must be a mapping, such as user: alice.");
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if ("grounding" in recipe) {
|
|
216
|
+
asList(recipe.grounding, "grounding", say)?.forEach((g, i) => {
|
|
217
|
+
if (!isWord(g)) say(`grounding[${i}]`, "must be one URL or repository path.");
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (!("notes" in recipe)) {
|
|
222
|
+
say("notes", "is missing; say what stays static-only (what this scan never exercises).");
|
|
223
|
+
} else if (typeof recipe.notes === "string") {
|
|
224
|
+
if (recipe.notes.trim() === "") say("notes", "is empty; say what stays static-only.");
|
|
225
|
+
} else {
|
|
226
|
+
const list = asList(recipe.notes, "notes", say);
|
|
227
|
+
if (list && list.length === 0) say("notes", "is empty; say what stays static-only.");
|
|
228
|
+
list?.forEach((t, i) => {
|
|
229
|
+
if (typeof t !== "string" || t.trim() === "") say(`notes[${i}]`, "must be a line of text.");
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Anywhere in the recipe: no Docker socket, no real credential.
|
|
234
|
+
let socket = false;
|
|
235
|
+
walkStrings(recipe, "", (where, value) => {
|
|
236
|
+
if (/docker\.sock/i.test(value)) {
|
|
237
|
+
socket = true;
|
|
238
|
+
say(where, socketProblem());
|
|
239
|
+
}
|
|
240
|
+
for (const [pattern, kind] of CREDENTIALS) {
|
|
241
|
+
if (pattern.test(value)) {
|
|
242
|
+
say(where, `looks like ${kind}; the recipe is committed, so it holds fake values only.`);
|
|
243
|
+
break;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
// Even on a line the reader dropped.
|
|
249
|
+
if (!socket && /docker\.sock/i.test(text)) say("(recipe)", socketProblem());
|
|
250
|
+
|
|
251
|
+
for (const [field, list] of Object.entries(commands)) {
|
|
252
|
+
list?.forEach((cmd, i) => {
|
|
253
|
+
if (CONTAINER_COMMAND.test(cmd)) say(`${field}[${i}]`, composeProblem());
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
entries?.forEach((entry, i) => {
|
|
257
|
+
if (
|
|
258
|
+
isMapping(entry) &&
|
|
259
|
+
typeof entry.command === "string" &&
|
|
260
|
+
CONTAINER_COMMAND.test(entry.command)
|
|
261
|
+
) {
|
|
262
|
+
say(`entry_points[${i}].command`, composeProblem());
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
return problems;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function composeProblem() {
|
|
269
|
+
return "no compose file and no sibling containers; start each service as a process with start and ready, inside the one sandbox.";
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function socketProblem() {
|
|
273
|
+
return "names the Docker socket; the sandbox never gets one.";
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Why `key` cannot be in a mapping whose fields are `known`, or null. */
|
|
277
|
+
function keyProblem(key, known) {
|
|
278
|
+
if (known.includes(key)) return null;
|
|
279
|
+
if (LIMIT_KEY.test(key)) {
|
|
280
|
+
return "the recipe holds no limits; set time, turn and token limits with deep-scan's options or the deep-scan workflow's inputs.";
|
|
281
|
+
}
|
|
282
|
+
if (COMPOSE_KEY.test(key)) return composeProblem();
|
|
283
|
+
if (SOCKET_KEY.test(key)) return socketProblem();
|
|
284
|
+
return `is not a Scan recipe field (fields: ${known.join(", ")}).`;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function entryProblems(entry, where, say) {
|
|
288
|
+
if (!isMapping(entry)) {
|
|
289
|
+
say(where, "must be a mapping with one of url, port or command, and a note.");
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
for (const key of Object.keys(entry)) {
|
|
293
|
+
const problem = keyProblem(key, [...ENTRY_KINDS, "note"]);
|
|
294
|
+
if (problem)
|
|
295
|
+
say(`${where}.${key}`, problem.replace("a Scan recipe field", "an entry point field"));
|
|
296
|
+
}
|
|
297
|
+
const kinds = ENTRY_KINDS.filter((k) => k in entry);
|
|
298
|
+
if (kinds.length === 0) say(where, "has none of url, port or command.");
|
|
299
|
+
if (kinds.length > 1) say(where, `gives ${kinds.join(" and ")}; give exactly one.`);
|
|
300
|
+
if ("url" in entry && !/^https?:\/\/\S+$/.test(String(entry.url ?? ""))) {
|
|
301
|
+
say(`${where}.url`, "must be an http:// or https:// URL.");
|
|
302
|
+
}
|
|
303
|
+
if ("port" in entry) {
|
|
304
|
+
const port = Number(entry.port);
|
|
305
|
+
if (!/^[1-9]\d*$/.test(String(entry.port ?? "")) || port > 65535) {
|
|
306
|
+
say(`${where}.port`, "must be a port number from 1 to 65535.");
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if ("command" in entry && (typeof entry.command !== "string" || entry.command.trim() === "")) {
|
|
310
|
+
say(`${where}.command`, "must be a command line.");
|
|
311
|
+
}
|
|
312
|
+
if (!("note" in entry) || typeof entry.note !== "string" || entry.note.trim() === "") {
|
|
313
|
+
say(where, "has no note; give each entry point a one-line note on what it is.");
|
|
314
|
+
} else if (entry.note.trim().includes("\n")) {
|
|
315
|
+
say(`${where}.note`, "must be one line.");
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** A field that holds commands: one command, or a list of them. */
|
|
320
|
+
function commandList(value, field, say) {
|
|
321
|
+
if (typeof value === "string" && value.trim() !== "" && !/^[[{]/.test(value)) return [value];
|
|
322
|
+
const list = asList(value, field, say);
|
|
323
|
+
list?.forEach((cmd, i) => {
|
|
324
|
+
if (typeof cmd !== "string" || cmd.trim() === "")
|
|
325
|
+
say(`${field}[${i}]`, "must be a command line.");
|
|
326
|
+
});
|
|
327
|
+
return list?.filter((c) => typeof c === "string") ?? null;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** `value` as a list, or null after saying why it is not one. */
|
|
331
|
+
function asList(value, field, say) {
|
|
332
|
+
if (Array.isArray(value)) return value;
|
|
333
|
+
if (typeof value === "string" && value.trim() === "[]") return [];
|
|
334
|
+
if (typeof value === "string" && /^[[{]/.test(value.trim())) {
|
|
335
|
+
say(field, "write it as a block list, one `- item` per line (only an empty [] may be inline).");
|
|
336
|
+
} else {
|
|
337
|
+
say(field, "must be a list, one `- item` per line.");
|
|
338
|
+
}
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** One non-empty token with no spaces: an image, a host, a URL or a path. */
|
|
343
|
+
function isWord(value) {
|
|
344
|
+
return typeof value === "string" && /^\S+$/.test(value);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Call `visit(where, value)` for every string in `value`, with its field path. */
|
|
348
|
+
function walkStrings(value, where, visit) {
|
|
349
|
+
if (typeof value === "string") visit(where || "(recipe)", value);
|
|
350
|
+
else if (Array.isArray(value)) value.forEach((v, i) => walkStrings(v, `${where}[${i}]`, visit));
|
|
351
|
+
else if (isMapping(value)) {
|
|
352
|
+
for (const [k, v] of Object.entries(value)) walkStrings(v, where ? `${where}.${k}` : k, visit);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* A copy of the reader's output in which every mapping has a null
|
|
358
|
+
* prototype. The reader assigns keys with `obj[key] = value`, so a
|
|
359
|
+
* `__proto__:` mapping became the object's prototype: it comes back here as
|
|
360
|
+
* an own `__proto__` key.
|
|
361
|
+
*/
|
|
362
|
+
function ownCopy(value) {
|
|
363
|
+
if (Array.isArray(value)) return value.map(ownCopy);
|
|
364
|
+
if (!isMapping(value)) return value;
|
|
365
|
+
const copy = Object.create(null);
|
|
366
|
+
for (const [k, v] of Object.entries(value)) copy[k] = ownCopy(v);
|
|
367
|
+
const proto = Object.getPrototypeOf(value);
|
|
368
|
+
if (proto !== Object.prototype && proto !== null) copy.__proto__ = ownCopy(proto);
|
|
369
|
+
return copy;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const TOP_KEY = /^("[^"]*"|'[^']*'|[^\s#:"'-][^:]*?):(?:\s+(.*))?$/;
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Problems the YAML reader would pass over without a word, found from the
|
|
376
|
+
* top-level lines: a line that is not `key: value`, a line indented under a
|
|
377
|
+
* key that holds a single value (the reader drops it), and a key given twice
|
|
378
|
+
* (the reader keeps the last). Keys are compared unquoted.
|
|
379
|
+
*/
|
|
380
|
+
function lineProblems(text) {
|
|
381
|
+
const problems = [];
|
|
382
|
+
const seen = new Set();
|
|
383
|
+
const twice = new Set();
|
|
384
|
+
let current = null; // { key, single } for the last top-level key
|
|
385
|
+
const all = stripBom(text).replace(/\r\n?/g, "\n").split("\n");
|
|
386
|
+
all.forEach((raw, index) => {
|
|
387
|
+
const line = stripComment(raw).trimEnd();
|
|
388
|
+
if (line.trim() === "") return;
|
|
389
|
+
const n = index + 1;
|
|
390
|
+
if (/^\s/.test(line)) {
|
|
391
|
+
if (current?.single) {
|
|
392
|
+
problems.push(
|
|
393
|
+
`line ${n}: is indented under ${current.key}, which holds a single value; the reader would drop it.`,
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (line === "---" && seen.size === 0) return;
|
|
399
|
+
if (line === "-" || line.startsWith("- ")) {
|
|
400
|
+
// A list at the key's own indent: valid only under a key with no value.
|
|
401
|
+
if (current && !current.single) return;
|
|
402
|
+
problems.push(`line ${n}: is a list item with no key above it to belong to.`);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const m = TOP_KEY.exec(line);
|
|
406
|
+
if (!m) {
|
|
407
|
+
problems.push(`line ${n}: is not a \`key: value\` line; the reader would drop it.`);
|
|
408
|
+
current = null;
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const key = parseScalar(m[1]);
|
|
412
|
+
if (seen.has(key)) twice.add(key);
|
|
413
|
+
seen.add(key);
|
|
414
|
+
const value = (m[2] ?? "").trim();
|
|
415
|
+
current = { key, single: value !== "" && !/^[|>][-+0-9]*$/.test(value) };
|
|
416
|
+
});
|
|
417
|
+
return { problems, twice: [...twice] };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* What the sandbox lifecycle runs and copies from a recipe that
|
|
422
|
+
* `validateRecipe` passed: the image or Dockerfile, each command field as a
|
|
423
|
+
* list, and the registries and grounding lists.
|
|
424
|
+
*
|
|
425
|
+
* @param {string} text
|
|
426
|
+
* @returns {{ image?: string, dockerfile?: string, setup: string[], start: string[],
|
|
427
|
+
* ready: string[], seed: string[], registries: string[], grounding: string[] }}
|
|
428
|
+
*/
|
|
429
|
+
export function recipeSteps(text) {
|
|
430
|
+
const recipe = parseYamlSubset(text);
|
|
431
|
+
const strings = (value) =>
|
|
432
|
+
Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
433
|
+
const commands = (value) =>
|
|
434
|
+
typeof value === "string" && value.trim() !== "" && !/^[[{]/.test(value)
|
|
435
|
+
? [value]
|
|
436
|
+
: strings(value);
|
|
437
|
+
return {
|
|
438
|
+
...(typeof recipe.image === "string" ? { image: recipe.image } : {}),
|
|
439
|
+
...(typeof recipe.dockerfile === "string" ? { dockerfile: recipe.dockerfile } : {}),
|
|
440
|
+
setup: commands(recipe.setup),
|
|
441
|
+
start: commands(recipe.start),
|
|
442
|
+
ready: commands(recipe.ready),
|
|
443
|
+
seed: commands(recipe.seed),
|
|
444
|
+
registries: strings(recipe.registries),
|
|
445
|
+
grounding: strings(recipe.grounding),
|
|
446
|
+
};
|
|
447
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// The relay and the probe of a Deep scan on Docker Engine (#404). This file
|
|
2
|
+
// runs inside a launcher-owned container, never in the launcher: the
|
|
3
|
+
// launcher checks its bytes against its pinned SHA-256 (relay.mjs) and
|
|
4
|
+
// builds them into an image from the official node image, its build context
|
|
5
|
+
// sent on stdin. Node core only.
|
|
6
|
+
//
|
|
7
|
+
// forward <listen-port> <host> <port>
|
|
8
|
+
// Accept TCP on <listen-port>, the one port it listens on, and pipe each
|
|
9
|
+
// connection to <host>:<port>, the host-side proxy. It reads nothing and
|
|
10
|
+
// holds no credential: the bytes pass through as they are.
|
|
11
|
+
//
|
|
12
|
+
// probe [--timeout-ms <ms>] <host> <port> [<host> <port> ...]
|
|
13
|
+
// Try a TCP connection to each target, again and again until one
|
|
14
|
+
// connects or the time is up (a relay just started may not listen yet),
|
|
15
|
+
// and print one JSON object: `self`, the probe's own addresses (a
|
|
16
|
+
// target at one of them would answer from the probe itself), and
|
|
17
|
+
// `results`, for each target, in order, the outcome that reached
|
|
18
|
+
// furthest: "connected", "refused" (a host answered, so a route exists),
|
|
19
|
+
// "error <code>", or "unreachable" (no route, or no answer in time).
|
|
20
|
+
|
|
21
|
+
import { connect, createServer } from "node:net";
|
|
22
|
+
import { networkInterfaces } from "node:os";
|
|
23
|
+
|
|
24
|
+
const [mode, ...rest] = process.argv.slice(2);
|
|
25
|
+
|
|
26
|
+
if (mode === "forward") {
|
|
27
|
+
const [listen, host, port] = rest;
|
|
28
|
+
// Half-close: when one side ends, `pipe` ends the other once what is
|
|
29
|
+
// queued for it is written, so a reply that ends at once arrives whole.
|
|
30
|
+
// Only an error tears both sides down.
|
|
31
|
+
const server = createServer({ allowHalfOpen: true }, (client) => {
|
|
32
|
+
const upstream = connect({ host, port: Number(port), allowHalfOpen: true });
|
|
33
|
+
const fail = () => {
|
|
34
|
+
client.destroy();
|
|
35
|
+
upstream.destroy();
|
|
36
|
+
};
|
|
37
|
+
client.on("error", fail);
|
|
38
|
+
upstream.on("error", fail);
|
|
39
|
+
client.pipe(upstream);
|
|
40
|
+
upstream.pipe(client);
|
|
41
|
+
});
|
|
42
|
+
server.on("error", (e) => {
|
|
43
|
+
process.stderr.write(`relay: ${e.message}\n`);
|
|
44
|
+
process.exit(1);
|
|
45
|
+
});
|
|
46
|
+
server.listen(Number(listen), () => process.stdout.write(`relay: listening on ${listen}\n`));
|
|
47
|
+
process.on("SIGTERM", () => process.exit(0));
|
|
48
|
+
} else if (mode === "probe") {
|
|
49
|
+
let timeoutMs = 3000;
|
|
50
|
+
if (rest[0] === "--timeout-ms") {
|
|
51
|
+
timeoutMs = Number(rest[1]);
|
|
52
|
+
rest.splice(0, 2);
|
|
53
|
+
}
|
|
54
|
+
const targets = [];
|
|
55
|
+
for (let i = 0; i + 1 < rest.length; i += 2) targets.push([rest[i], Number(rest[i + 1])]);
|
|
56
|
+
const UNREACHABLE = new Set(["ENETUNREACH", "EHOSTUNREACH", "ETIMEDOUT"]);
|
|
57
|
+
const attempt = ([host, port], ms) =>
|
|
58
|
+
new Promise((resolve) => {
|
|
59
|
+
const socket = connect({ host, port });
|
|
60
|
+
const done = (result) => {
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
socket.destroy();
|
|
63
|
+
resolve(result);
|
|
64
|
+
};
|
|
65
|
+
const timer = setTimeout(() => done("unreachable"), ms);
|
|
66
|
+
socket.once("connect", () => done("connected"));
|
|
67
|
+
socket.once("error", (e) =>
|
|
68
|
+
done(
|
|
69
|
+
e.code === "ECONNREFUSED"
|
|
70
|
+
? "refused"
|
|
71
|
+
: UNREACHABLE.has(e.code)
|
|
72
|
+
? "unreachable"
|
|
73
|
+
: `error ${e.code}`,
|
|
74
|
+
),
|
|
75
|
+
);
|
|
76
|
+
});
|
|
77
|
+
const deadline = Date.now() + timeoutMs;
|
|
78
|
+
// The outcome that reached furthest wins: one answer from a host is a route.
|
|
79
|
+
const rank = (r) => (r === "connected" ? 3 : r === "refused" ? 2 : r === "unreachable" ? 0 : 1);
|
|
80
|
+
const reach = async (target) => {
|
|
81
|
+
let best = "unreachable";
|
|
82
|
+
for (;;) {
|
|
83
|
+
const result = await attempt(target, Math.max(1, deadline - Date.now()));
|
|
84
|
+
if (rank(result) > rank(best)) best = result;
|
|
85
|
+
if (best === "connected" || Date.now() >= deadline) return best;
|
|
86
|
+
await new Promise((r) => setTimeout(r, Math.min(100, Math.max(1, deadline - Date.now()))));
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const results = await Promise.all(targets.map(reach));
|
|
90
|
+
const self = Object.values(networkInterfaces())
|
|
91
|
+
.flat()
|
|
92
|
+
.filter((i) => i && !i.internal)
|
|
93
|
+
.map((i) => i.address);
|
|
94
|
+
process.stdout.write(`${JSON.stringify({ self, results })}\n`);
|
|
95
|
+
} else {
|
|
96
|
+
process.stderr.write("usage: relay.mjs forward <listen-port> <host> <port> | probe ...\n");
|
|
97
|
+
process.exit(2);
|
|
98
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// The relay and the probe on Docker Engine (#404), from the launcher's side:
|
|
2
|
+
// the pinned image their image is built from, the relay script built into
|
|
3
|
+
// it and checked against its pinned SHA-256, and the reading of a probe's
|
|
4
|
+
// answer.
|
|
5
|
+
//
|
|
6
|
+
// On Docker Engine the sandbox's network is `--internal` with the
|
|
7
|
+
// `isolated` gateway mode (Docker 28.0 and later), so the host has no
|
|
8
|
+
// address on it. The sandbox's one way to a host-side proxy is a relay
|
|
9
|
+
// container on that network and on an ordinary bridge network: it forwards
|
|
10
|
+
// one TCP port to the proxy, on that bridge's gateway, and listens on
|
|
11
|
+
// nothing else. It never holds the model credential: the bytes pass through,
|
|
12
|
+
// and the key is added in the host-side proxy.
|
|
13
|
+
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
import { fileURLToPath } from "node:url";
|
|
17
|
+
import { ENDS_HERE, StepFailed } from "./steps.mjs";
|
|
18
|
+
import { tarOf } from "./tar.mjs";
|
|
19
|
+
|
|
20
|
+
/** The official node image the relay image is built from, pinned by digest. */
|
|
21
|
+
export const RELAY_IMAGE =
|
|
22
|
+
"node:24.22.3-alpine3.24@sha256:116b800c3754b440ee0aa3ed2f20f5bf3d99a554bfd9adeea09ea8017f6e85f5";
|
|
23
|
+
|
|
24
|
+
/** The relay script as it ships, and its pinned SHA-256. */
|
|
25
|
+
export const RELAY_SCRIPT_FILE = fileURLToPath(new URL("./relay-script.mjs", import.meta.url));
|
|
26
|
+
export const RELAY_SCRIPT_SHA256 =
|
|
27
|
+
"4240ef10d2e702c08bdc04f16ebec8e17318655109d66c52ba33dd11d72ac5d5";
|
|
28
|
+
|
|
29
|
+
/** Where the relay and the probe find the script, in the relay image. */
|
|
30
|
+
export const RELAY_SCRIPT_PATH = "/agent-kit/relay.mjs";
|
|
31
|
+
|
|
32
|
+
/** The port the probe tries on the host besides the proxy's: sshd's, often on all interfaces. */
|
|
33
|
+
export const OTHER_HOST_PORT = 22;
|
|
34
|
+
|
|
35
|
+
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
|
|
36
|
+
|
|
37
|
+
const mismatch = (what) =>
|
|
38
|
+
new StepFailed([
|
|
39
|
+
`FAILED the relay script does not match its pinned SHA-256 (${what}); reinstall agent-kit.`,
|
|
40
|
+
ENDS_HERE,
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/** The relay image's Dockerfile: the pinned node image, and the script copied in. */
|
|
44
|
+
export const RELAY_DOCKERFILE = `FROM ${RELAY_IMAGE}\nCOPY relay.mjs ${RELAY_SCRIPT_PATH}\n`;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The relay image's build context, for `docker build -` on stdin: its
|
|
48
|
+
* Dockerfile and the relay script, whose bytes are checked against the
|
|
49
|
+
* pinned SHA-256 first, so what goes into the image is what was checked.
|
|
50
|
+
* No host path is mounted into a container: a daemon with its own private
|
|
51
|
+
* /tmp, such as snap Docker, could not see one.
|
|
52
|
+
* @param {{ source?: string }} [opts]
|
|
53
|
+
* @returns {Buffer}
|
|
54
|
+
*/
|
|
55
|
+
export function relayBuildContext({ source = RELAY_SCRIPT_FILE } = {}) {
|
|
56
|
+
const data = readFileSync(source);
|
|
57
|
+
if (sha256(data) !== RELAY_SCRIPT_SHA256) throw mismatch(source);
|
|
58
|
+
return tarOf([
|
|
59
|
+
{ path: "Dockerfile", data: Buffer.from(RELAY_DOCKERFILE, "utf8") },
|
|
60
|
+
{ path: "relay.mjs", data },
|
|
61
|
+
]);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The `docker run` options a relay or a probe container shares: no
|
|
66
|
+
* capabilities, a read-only root filesystem, no new privileges, an
|
|
67
|
+
* unprivileged user and small limits. The script is in the image.
|
|
68
|
+
*/
|
|
69
|
+
export function relayOptions() {
|
|
70
|
+
return [
|
|
71
|
+
"--read-only",
|
|
72
|
+
"--cap-drop",
|
|
73
|
+
"ALL",
|
|
74
|
+
"--security-opt",
|
|
75
|
+
"no-new-privileges",
|
|
76
|
+
"--user",
|
|
77
|
+
"node",
|
|
78
|
+
"--pids-limit",
|
|
79
|
+
"64",
|
|
80
|
+
"--memory",
|
|
81
|
+
"128m",
|
|
82
|
+
"--entrypoint",
|
|
83
|
+
"node",
|
|
84
|
+
];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @typedef {{ host: string, port: number, want: "connected" | "unreachable", what: string }} ProbeTarget
|
|
89
|
+
* A target a probe tries, what it must give, and what to call it.
|
|
90
|
+
*/
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Why a probe's answer fails the check, or null when it passes: the probe
|
|
94
|
+
* named its own addresses, none of them is a target (a probe dialling
|
|
95
|
+
* itself, at an address Docker reused, would read as a route or as none),
|
|
96
|
+
* and every target gave what it must.
|
|
97
|
+
* @param {string} stdout the probe's output
|
|
98
|
+
* @param {ProbeTarget[]} targets
|
|
99
|
+
*/
|
|
100
|
+
export function probeFailure(stdout, targets) {
|
|
101
|
+
let answer;
|
|
102
|
+
try {
|
|
103
|
+
answer = JSON.parse(stdout.trim());
|
|
104
|
+
} catch {
|
|
105
|
+
answer = null;
|
|
106
|
+
}
|
|
107
|
+
const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
108
|
+
if (
|
|
109
|
+
!answer ||
|
|
110
|
+
typeof answer !== "object" ||
|
|
111
|
+
!strings(answer.self) ||
|
|
112
|
+
!strings(answer.results) ||
|
|
113
|
+
answer.results.length !== targets.length
|
|
114
|
+
) {
|
|
115
|
+
return "the probe's answer is not its own addresses and one result per target";
|
|
116
|
+
}
|
|
117
|
+
const own = targets.find((t) => answer.self.includes(t.host));
|
|
118
|
+
if (own) {
|
|
119
|
+
return `the probe's own address ${own.host} is one of its targets, so it cannot tell a route from itself`;
|
|
120
|
+
}
|
|
121
|
+
for (const [i, t] of targets.entries()) {
|
|
122
|
+
const r = answer.results[i];
|
|
123
|
+
if (r === t.want) continue;
|
|
124
|
+
const at = `${t.host.includes(":") ? `[${t.host}]` : t.host}:${t.port}`;
|
|
125
|
+
return t.want === "connected"
|
|
126
|
+
? `a probe on it could not reach ${t.what} at ${at} (${r})`
|
|
127
|
+
: `a probe on it reached ${t.what} at ${at} (${r})`;
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
}
|