barebox 0.2.0 → 0.3.0

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/src/launcher.js CHANGED
@@ -1,20 +1,79 @@
1
1
  // Launcher: one sandboxed agent (bwrap walls + socat front-door bridge).
2
2
  // Port of poc/m0/launch.sh, minus the throwaway red-team hooks: secure
3
- // defaults are baked in, not switchable. No overlay (M4).
3
+ // defaults are baked in, not switchable. The project bind is read-only unless
4
+ // `overlay:true` mounts the M4 tracing paper over it (see overlay.js).
4
5
  import { spawn } from 'node:child_process';
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
6
- import { join, relative, isAbsolute } from 'node:path';
7
- import { socketPathForAgent, assertAgentName, realPathOf } from './proxy.js';
6
+ import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
+ import { join, relative, dirname } from 'node:path';
8
+ import { assertAgentName, isInside, realPathOf, runtimePaths } from './runtime.js';
9
+ import { assertOverlaySupport, setupOverlay } from './overlay.js';
8
10
 
9
- // Locked drawers: masked with an empty tmpfs wherever they exist.
11
+ // Locked drawers (relative to $HOME): masked wherever they exist — a folder
12
+ // with an empty tmpfs, a file with /dev/null (bwrap cannot mount a tmpfs on
13
+ // a file; `--dev-bind`, because `--ro-bind` makes the mount nodev and the
14
+ // read fails EACCES instead of reading empty). The real kind on disk picks the
15
+ // mask.
16
+ // Deliberately NOT here: the agent's own model credentials (`~/.claude`,
17
+ // `~/.claude.json`, `~/.config/anthropic`, ...). A sandboxed coding agent
18
+ // needs them to run at all; moving keys out of the agent's reach is M5
19
+ // ("keys the agent never holds"), not a mask.
10
20
  const LOCKED_PATHS = [
21
+ // keys, password stores, keyrings
11
22
  '.ssh',
12
23
  'secrets',
24
+ '.gnupg',
25
+ '.password-store',
26
+ '.local/share/keyrings',
27
+ // browser profiles (cookies, saved passwords)
13
28
  '.mozilla',
14
29
  '.config/chromium',
15
- '.gnupg',
30
+ '.config/google-chrome',
31
+ '.config/BraveSoftware',
32
+ // cloud, cluster and container credentials
33
+ '.aws',
34
+ '.azure',
35
+ '.config/gcloud',
36
+ '.kube',
37
+ '.docker',
38
+ // forge and password-manager CLIs
39
+ '.config/gh',
40
+ '.config/op',
41
+ // token files
42
+ '.netrc',
43
+ '.npmrc',
44
+ '.pypirc',
45
+ '.git-credentials',
46
+ '.cargo/credentials.toml',
16
47
  ];
17
48
 
49
+ /**
50
+ * The bwrap args that mask one locked path, or none when it does not exist.
51
+ * A symlinked drawer (dotfile managers) is masked at its real target, which
52
+ * is where bwrap lands a mount anyway, so the content is shut at both
53
+ * spellings; a target outside `$HOME` and the project is not bound into the
54
+ * sandbox at all, so there is nothing to mask.
55
+ *
56
+ * @param {string} abs the locked path under `$HOME`
57
+ * @param {string} home `$HOME`
58
+ * @param {string} proj project dir
59
+ * @returns {string[]} `--tmpfs <dir>` or `--dev-bind /dev/null <file>`, or `[]`
60
+ */
61
+ function lockMask(abs, home, proj) {
62
+ let target = abs;
63
+ let st;
64
+ try {
65
+ st = lstatSync(abs);
66
+ if (st.isSymbolicLink()) {
67
+ target = realPathOf(abs);
68
+ if (!isInside(home, target) && !isInside(proj, target)) return [];
69
+ st = statSync(target);
70
+ }
71
+ } catch {
72
+ return []; // absent, or a dangling link: nothing readable to mask
73
+ }
74
+ return st.isDirectory() ? ['--tmpfs', target] : ['--dev-bind', '/dev/null', target];
75
+ }
76
+
18
77
  // System bundle locations the combined CA file is built from (first hit wins).
19
78
  const SYSTEM_BUNDLES = [
20
79
  '/etc/ssl/certs/ca-certificates.crt', // Debian/Ubuntu
@@ -37,13 +96,16 @@ const CA_ENV_VARS = ['SSL_CERT_FILE', 'NODE_EXTRA_CA_CERTS', 'REQUESTS_CA_BUNDLE
37
96
  * @returns {string} path of the combined bundle inside `runtime`
38
97
  */
39
98
  export function buildCaBundle(runtime, caFile) {
99
+ const out = join(runtime, 'ca-bundle.pem');
100
+ // Once per runtime: the CA doesn't change during a runtime's life, so a
101
+ // present bundle is reused (20 agents launching at once build it once).
102
+ if (existsSync(out)) return out;
40
103
  const ca = readFileSync(caFile, 'utf8');
41
104
  if (!ca.includes('BEGIN CERTIFICATE')) throw new Error(`buildCaBundle: no cert in ${caFile}`);
42
105
  let sys = '';
43
106
  for (const p of SYSTEM_BUNDLES) {
44
107
  if (existsSync(p)) { sys = readFileSync(p, 'utf8'); break; }
45
108
  }
46
- const out = join(runtime, 'ca-bundle.pem');
47
109
  mkdirSync(runtime, { recursive: true });
48
110
  writeFileSync(out, `${sys}${sys.endsWith('\n') || !sys ? '' : '\n'}${ca}`);
49
111
  return out;
@@ -53,7 +115,12 @@ export function buildCaBundle(runtime, caFile) {
53
115
  * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`,
54
116
  * its project and home read-only, the locked drawers masked, no network of
55
117
  * its own, and a single front door: anything sent to `localhost:<proxyPort>`
56
- * is carried out through this agent's socket to the proxy.
118
+ * is carried out through this agent's socket to the proxy. The agent starts
119
+ * in the project dir (`--chdir proj`), so relative paths resolve there no
120
+ * matter where the caller runs from. The agent always runs in a new session
121
+ * (`--new-session`), detached from the caller's terminal, so it cannot inject
122
+ * keystrokes via TIOCSTI on kernels with `dev.tty.legacy_tiocsti=1`. Its stdin
123
+ * is never the terminal (`stdio: ignore`), so detaching costs nothing.
57
124
  *
58
125
  * @param {object} opts
59
126
  * @param {string} opts.runtime where the runtime tree lives (`socks/` is created inside)
@@ -64,26 +131,44 @@ export function buildCaBundle(runtime, caFile) {
64
131
  * @param {object} [opts.extraEnv] extra environment entries for the inside
65
132
  * @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
66
133
  * @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
134
+ * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; diff/commit/rollback address it as `runtimePaths(runtime).overlay(agent)`
135
+ * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
67
136
  * @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
68
- * @when Reach for this to HARNESS-ONLY start one sandboxed agent run: it creates the sandbox the agent lives in. It does not decide anything; combine with the proxy for the front door and the gate (M3) for policy.
69
- * @fails Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, or when `runtime` IS `HOME` or the project dir (its sockets could not be hidden from the agent). The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.
137
+ * @when Reach for this to HARNESS-ONLY start one sandboxed agent run: it creates the sandbox the agent lives in. It does not decide anything; combine with the proxy for the front door and the gate (M3) for policy. Pass overlay:true for a writable tracing-paper run (M4). The agent starts in the project dir.
138
+ * @fails Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on a non-integer `proxyPort`, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, when `runtime` IS `HOME` or the project dir (its sockets could not be hidden from the agent), or with overlay on when the runtime sits inside the project or uncommitted changes linger. The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.
70
139
  * @example
71
140
  * import { launch } from "barebox";
72
141
  * const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
73
142
  * await new Promise((r) => child.on("close", r)); // child.exitCode === 0
74
143
  */
75
144
  export function launch({ runtime, agent, proj, command, proxyPort = 3128,
76
- extraEnv = {}, socket = null, caFile = null }) {
145
+ extraEnv = {}, socket = null, caFile = null, overlay = false, overlayIgnore }) {
77
146
  for (const [k, v] of Object.entries({ runtime, agent, proj })) {
78
147
  if (typeof v !== 'string' || !v) throw new Error(`launch: ${k} must be a non-empty string`);
79
148
  }
80
149
  if (!Array.isArray(command) || !command.length) throw new Error('launch: command must be a non-empty argv array');
150
+ // Pasted into the sandbox's start-up script: anything but an integer port is shell injection.
151
+ if (!Number.isInteger(proxyPort) || proxyPort < 1 || proxyPort > 65535) {
152
+ throw new Error(`launch: proxyPort must be an integer from 1 to 65535, got ${JSON.stringify(proxyPort)}`);
153
+ }
81
154
  assertAgentName(agent);
82
155
  // The socket IS the identity: both sides must name the same path.
83
- const expected = socketPathForAgent(runtime, agent);
156
+ const expected = runtimePaths(runtime).socket(agent);
84
157
  const sock = socket ?? expected;
85
158
  if (sock !== expected) throw new Error(`launch: socket ${sock} disagrees with ${expected}`);
86
- mkdirSync(join(runtime, 'socks'), { recursive: true });
159
+ mkdirSync(dirname(expected), { recursive: true });
160
+ /** @type {{upper: string, work: string} | null} */
161
+ let ov = null;
162
+ if (overlay) {
163
+ assertOverlaySupport();
164
+ // The upper/work dirs live under the runtime: a runtime inside the
165
+ // project would put them inside their own lower, which overlayfs
166
+ // forbids — so that layout throws here, before anything is snapshotted.
167
+ if (isInside(proj, runtime)) {
168
+ throw new Error('launch: runtime must not be inside the project dir when overlay is on (the upper would sit inside its own lower)');
169
+ }
170
+ ov = setupOverlay({ runtime, agent, proj, ignore: overlayIgnore });
171
+ }
87
172
  const home = process.env.HOME || '/root';
88
173
  const args = [
89
174
  '--unshare-pid', '--unshare-uts', '--unshare-ipc', '--unshare-net',
@@ -92,52 +177,63 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
92
177
  '--ro-bind', '/usr', '/usr',
93
178
  '--symlink', 'usr/lib64', '/lib64',
94
179
  '--ro-bind', '/etc', '/etc',
95
- '--ro-bind', proj, proj,
180
+ // $HOME first, the project second: a project under $HOME would otherwise
181
+ // vanish under the home bind (bwrap mounts cover what is below them —
182
+ // the later mount wins where they overlap). The project mount (overlay
183
+ // or read-only) therefore lands on top of the read-only home.
96
184
  '--ro-bind', home, home,
185
+ // Tracing paper (M4): lower = real project, upper = this run's sheet.
186
+ // Without it the project stays a read-only bind and writes fail.
187
+ ...(ov
188
+ ? ['--overlay-src', proj, '--overlay', ov.upper, ov.work, proj]
189
+ : ['--ro-bind', proj, proj]),
190
+ '--chdir', proj,
191
+ // Always detach from our controlling terminal: otherwise the agent could
192
+ // open /dev/tty and TIOCSTI keystrokes into it (e.g. into `sbx approve`)
193
+ // on kernels with dev.tty.legacy_tiocsti=1. The agent's stdin is never
194
+ // the terminal (spawned with stdin ignored), so nothing interactive is lost.
195
+ '--new-session',
97
196
  ];
98
- for (const p of LOCKED_PATHS) {
99
- if (existsSync(`${home}/${p}`)) args.push('--tmpfs', `${home}/${p}`);
100
- }
101
- // The runtime tree holds the control socket (approve/deny) and every
102
- // agent's socket (identity). A read-only bind does NOT stop connect(2)
103
- // to a unix socket, so wherever the runtime would show through the home
104
- // or project binds, mask it with an empty tmpfs. (The agent's own socket
105
- // is bound from the host side to /run/sbx/agent.sock, so masking the
106
- // sandbox-side runtime path does not close the front door.)
197
+ // Locked drawers AFTER the project mount: the tmpfs mask must land on top,
198
+ // or a project that contains one of these paths (a project that IS $HOME,
199
+ // or holds its own `.ssh`) would leak the real drawer through the overlay.
200
+ for (const p of LOCKED_PATHS) args.push(...lockMask(`${home}/${p}`, home, proj));
201
+ // The runtime tree holds the file-checkpoint dirs (`asks/`, `answers/`
202
+ // — the approve/deny capability) and every agent's socket (identity). A
203
+ // read-only bind does NOT stop connect(2) to a unix socket, so wherever
204
+ // the runtime would show through the home or project binds, mask it with
205
+ // an empty tmpfs. The mask lands on the runtime dir itself, so `asks/`
206
+ // and `answers/` underneath are covered too: an agent cannot read its ask
207
+ // file, and a forged answer file would land on the mask (or fail where
208
+ // the runtime is outside home/proj and hence not bound in at all), never
209
+ // on the host tree the proxy polls. (The agent's own socket is bound from
210
+ // the host side to /run/sbx/agent.sock, so masking the sandbox-side
211
+ // runtime path does not close the front door.) These masks stay after the
212
+ // project and locked mounts: where paths overlap, the later mount wins.
107
213
  {
108
- // Lexical on purpose: bwrap sees these same spellings, so the mask
109
- // lands on the path the sandbox actually shows. (`resolve` would
110
- // follow symlinks and can name a path the sandbox never displays.)
111
- const rt = join(runtime);
214
+ // bwrap sees these same spellings, so the mask lands on the path the
215
+ // sandbox actually shows. The sandbox shows the REAL tree (symlinks
216
+ // resolved), so a runtime passed as a symlink from outside $HOME/proj
217
+ // can still land inside it and stay visible through the ro-binds — the
218
+ // mask below covers that spelling too.
112
219
  const hm = join(home);
113
220
  const pr = join(proj);
114
- if (rt === hm || rt === pr) {
115
- throw new Error(`launch: runtime must not be ${rt === hm ? 'HOME' : 'the project dir'} itself (its sockets cannot be hidden there)`);
116
- }
117
- const inside = (base) => {
118
- const rel = relative(base, rt);
119
- return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
120
- };
121
- if (inside(hm) || inside(pr)) args.push('--tmpfs', rt);
122
- // Real-tree mask as well: the sandbox shows the REAL tree (symlinks
123
- // resolved), so a runtime passed as a symlink from outside $HOME/proj
124
- // can still land inside it and stay visible through the ro-binds. The
125
- // lexical mask above covers the spelling bwrap is given; this one covers
126
- // the sandbox-visible spelling join(home, relative(realHome, realRt))
127
- // (likewise proj). Both masks are cheap; keep both.
128
- const realRt = realPathOf(rt);
221
+ const realRt = realPathOf(join(runtime));
129
222
  const realHm = realPathOf(hm);
130
223
  const realPr = realPathOf(pr);
224
+ // One real-path comparison: a lexically-equal spelling resolves to the
225
+ // same real path, so it is subsumed here.
131
226
  if (realRt === realHm || realRt === realPr) {
132
227
  throw new Error(`launch: runtime must not be ${realRt === realHm ? 'HOME' : 'the project dir'} itself (its sockets cannot be hidden there)`);
133
228
  }
134
- const realInside = (realBase, baseSpelling) => {
135
- const rel = relative(realBase, realRt);
136
- if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null;
137
- return join(baseSpelling, rel);
138
- };
139
- for (const m of [realInside(realHm, hm), realInside(realPr, pr)]) {
140
- if (m && !args.includes(m)) args.push('--tmpfs', m);
229
+ // Mask the sandbox-visible spelling join(home, relative(realHome, realRt))
230
+ // (likewise proj): where nothing is a symlink this IS the lexical path,
231
+ // so no separate lexical mask is needed.
232
+ for (const [realBase, baseSpelling] of [[realHm, hm], [realPr, pr]]) {
233
+ if (realRt !== realBase && isInside(realBase, realRt)) {
234
+ const m = join(baseSpelling, relative(realBase, realRt));
235
+ if (!args.includes(m)) args.push('--tmpfs', m);
236
+ }
141
237
  }
142
238
  }
143
239
  args.push(
@@ -168,6 +264,9 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
168
264
  `socat TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
169
265
  `ok=; for i in $(seq 1 50); do (echo > /dev/tcp/127.0.0.1/${door}) 2>/dev/null && { ok=1; break; }; sleep 0.1; done; ` +
170
266
  '[ -n "$ok" ] || exit 99; exec "$@"';
171
- return spawn('bwrap', [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
267
+ const child = spawn('bwrap', [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
172
268
  { stdio: ['ignore', 'pipe', 'pipe'] });
269
+ // No `.overlay` on the child: the tracing paper's address is one call,
270
+ // `runtimePaths(runtime).overlay(agent)`, so there is nothing to keep in sync.
271
+ return child;
173
272
  }
@@ -0,0 +1,49 @@
1
+ // overlay-walk.js — merged-view walker entry for bwrap mounts (see overlay.js).
2
+ //
3
+ // Runs INSIDE the overlay mount as `<node> <this file> <merged>
4
+ // <ignore-json> <manifest-file> <stage-dir-or-empty> <upper-paths-or-empty>`
5
+ // (`<node>` is the node running barebox now): `src/` is bound read-only at
6
+ // its own path, so this imports the one walker (`walkLocal`) instead of
7
+ // duplicating it. Prints nothing on stdout: the manifest (an array of
8
+ // `[rel, entry]` pairs) goes to `<manifest-file>` inside a folder bound
9
+ // read-write at `/sbx-out`, so trees of any size travel without an output
10
+ // cap. The upper-paths file (also in `/sbx-out`) lists the upper's relative
11
+ // paths: only those get full entries (hashes, link targets) and staging —
12
+ // every other merged path is the lower entry unchanged (opaque folders and
13
+ // copy-up both land the path in the upper), so the host fills it from the
14
+ // lower without a second hash. With a stage dir, only listed files/symlinks
15
+ // are copied under it — the host commit then renames them into the project,
16
+ // never copying. Exotic kinds (fifos, sockets, devices) and non-UTF-8 names
17
+ // are refused loudly by `walkLocal`, never mangled: the mount exits nonzero
18
+ // instead.
19
+ import { copyFileSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs';
20
+ import { join, dirname } from 'node:path';
21
+ import { walkLocal } from './overlay.js';
22
+
23
+ const [, , mergedDir, ignoreJson, manifestFile, stageArg, upperPathsArg] = process.argv;
24
+ if (!mergedDir || !ignoreJson || !manifestFile) {
25
+ console.error('usage: overlay-walk.js <merged-dir> <ignore-json> <manifest-file> [stage-dir] [upper-paths-file]');
26
+ process.exit(2);
27
+ }
28
+ /** @type {string[]} */
29
+ const ignore = JSON.parse(ignoreJson);
30
+ const stageDir = stageArg || null;
31
+ /** @type {Set<string>|null} */
32
+ const upperPaths = upperPathsArg
33
+ ? new Set(/** @type {string[]} */ (JSON.parse(readFileSync(upperPathsArg, 'utf8'))))
34
+ : null;
35
+
36
+ const manifest = walkLocal(mergedDir, new Set(ignore), upperPaths);
37
+
38
+ if (stageDir) {
39
+ for (const [rel, e] of manifest) {
40
+ if (e.type !== 'f' && e.type !== 'l') continue;
41
+ if (upperPaths && !upperPaths.has(rel)) continue;
42
+ const dst = join(stageDir, rel);
43
+ mkdirSync(dirname(dst), { recursive: true });
44
+ if (e.type === 'f') copyFileSync(join(mergedDir, rel), dst);
45
+ else symlinkSync(/** @type {string} */ (e.target), dst);
46
+ }
47
+ }
48
+
49
+ writeFileSync(manifestFile, JSON.stringify([...manifest]));