barebox 0.4.0 → 0.6.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/CHANGELOG.md +79 -0
- package/README.md +37 -23
- package/barebox.context.md +196 -13
- package/package.json +7 -2
- package/primitives.json +10 -1
- package/src/cardscan.js +96 -0
- package/src/cli.js +29 -4
- package/src/config.js +147 -0
- package/src/holds.js +76 -48
- package/src/index.js +1 -0
- package/src/labels.js +94 -0
- package/src/launcher.js +52 -7
- package/src/policy.js +141 -0
- package/src/proxy.js +599 -161
- package/src/run.js +40 -71
- package/src/runtime.js +7 -2
- package/src/secrets.js +113 -0
- package/src/wall.js +12 -6
- package/types/cardscan.d.ts +17 -0
- package/types/cli.d.ts +1 -1
- package/types/config.d.ts +59 -0
- package/types/holds.d.ts +25 -46
- package/types/index.d.ts +1 -0
- package/types/labels.d.ts +27 -0
- package/types/launcher.d.ts +10 -2
- package/types/policy.d.ts +64 -0
- package/types/proxy.d.ts +87 -33
- package/types/run.d.ts +61 -11
- package/types/runtime.d.ts +3 -1
- package/types/secrets.d.ts +63 -0
- package/types/wall.d.ts +4 -2
package/src/launcher.js
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
// defaults are baked in, not switchable. The project bind is read-only unless
|
|
4
4
|
// `overlay:true` mounts the M4 tracing paper over it (see overlay.js).
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
-
import { join, relative, dirname } from 'node:path';
|
|
6
|
+
import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { join, relative, dirname, delimiter } from 'node:path';
|
|
8
8
|
import { assertAgentName, isInside, realPathOf, runtimePaths } from './runtime.js';
|
|
9
9
|
import { assertOverlaySupport, setupOverlay } from './overlay.js';
|
|
10
|
+
import { configPath } from './config.js';
|
|
10
11
|
|
|
11
12
|
// Locked drawers (relative to $HOME): masked wherever they exist — a folder
|
|
12
13
|
// with an empty tmpfs, a file with /dev/null (bwrap cannot mount a tmpfs on
|
|
@@ -53,12 +54,14 @@ const LOCKED_PATHS = [
|
|
|
53
54
|
* spellings; a target outside `$HOME` and the project is not bound into the
|
|
54
55
|
* sandbox at all, so there is nothing to mask.
|
|
55
56
|
*
|
|
56
|
-
* @param {string} abs the locked path under `$HOME`
|
|
57
|
+
* @param {string} abs the locked path (under `$HOME` or the project to matter)
|
|
57
58
|
* @param {string} home `$HOME`
|
|
58
59
|
* @param {string} proj project dir
|
|
59
60
|
* @returns {string[]} `--tmpfs <dir>` or `--dev-bind /dev/null <file>`, or `[]`
|
|
60
61
|
*/
|
|
61
62
|
function lockMask(abs, home, proj) {
|
|
63
|
+
// Neither under $HOME nor the project: not bound into the sandbox at all.
|
|
64
|
+
if (!isInside(home, abs) && !isInside(proj, abs)) return [];
|
|
62
65
|
let target = abs;
|
|
63
66
|
let st;
|
|
64
67
|
try {
|
|
@@ -85,6 +88,26 @@ const SYSTEM_BUNDLES = [
|
|
|
85
88
|
const CA_ENV_VARS = ['SSL_CERT_FILE', 'NODE_EXTRA_CA_CERTS', 'REQUESTS_CA_BUNDLE',
|
|
86
89
|
'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO'];
|
|
87
90
|
|
|
91
|
+
// Host variables that reach the inside without being asked for (M5). Nothing
|
|
92
|
+
// else does: the sandbox gets a short list, not the host environment.
|
|
93
|
+
const PASS_DEFAULT = /^(TERM|COLORTERM|LANG|LANGUAGE|LC_[A-Z_]+|TZ|USER|LOGNAME|SHELL|EDITOR|PAGER)$/;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Where `bwrap` is, looked up on THIS process's PATH. The spawn below runs
|
|
97
|
+
* with a clean environment (its PATH is fixed), so node could not find a
|
|
98
|
+
* `bwrap` that the caller's PATH puts first (the fake one the tests use).
|
|
99
|
+
*
|
|
100
|
+
* @returns {string} the first executable `bwrap` on PATH, else the bare name (spawn then fails ENOENT as before)
|
|
101
|
+
*/
|
|
102
|
+
function bwrapBin() {
|
|
103
|
+
for (const d of (process.env.PATH ?? '').split(delimiter)) {
|
|
104
|
+
if (!d) continue;
|
|
105
|
+
const p = join(d, 'bwrap');
|
|
106
|
+
try { accessSync(p, constants.X_OK); return p; } catch {}
|
|
107
|
+
}
|
|
108
|
+
return 'bwrap';
|
|
109
|
+
}
|
|
110
|
+
|
|
88
111
|
/**
|
|
89
112
|
* Build the CA bundle the sandbox trusts: system roots plus the barebox CA,
|
|
90
113
|
* so public hosts verify as usual and the proxy's minted certs verify too.
|
|
@@ -128,9 +151,11 @@ export function buildCaBundle(runtime, caFile) {
|
|
|
128
151
|
* @param {string} opts.proj project directory, bound read-only
|
|
129
152
|
* @param {string[]} opts.command argv to run inside, for example `["python3", "agent.py"]`
|
|
130
153
|
* @param {number} [opts.proxyPort] front-door port inside the sandbox (default 3128)
|
|
131
|
-
* @param {object} [opts.extraEnv] extra environment entries for the inside
|
|
154
|
+
* @param {object} [opts.extraEnv] extra environment entries for the inside, set last (they win)
|
|
155
|
+
* @param {{ pass?: string[], set?: Record<string, string>, placeholders?: Record<string, string> }} [opts.env] the inside's environment (M5). The host environment never reaches it except: a short default list (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`, `TZ`, `USER`, `LOGNAME`, `SHELL`, `EDITOR`, `PAGER`), the host variables named in `pass`, the values in `set`, and one placeholder per secret under its own name (`placeholders`, name to value). Set in that order, then `extraEnv`.
|
|
132
156
|
* @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
|
|
133
157
|
* @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
|
|
158
|
+
* @param {string[]} [opts.maskDirs] extra folders hidden from the agent exactly like barebox's config dir (the `labels` folders: the agent must not read or rewrite a letter)
|
|
134
159
|
* @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
160
|
* @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
|
|
136
161
|
* @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
|
|
@@ -142,7 +167,7 @@ export function buildCaBundle(runtime, caFile) {
|
|
|
142
167
|
* await new Promise((r) => child.on("close", r)); // child.exitCode === 0
|
|
143
168
|
*/
|
|
144
169
|
export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
145
|
-
extraEnv = {}, socket = null, caFile = null, overlay = false, overlayIgnore }) {
|
|
170
|
+
extraEnv = {}, env = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [] }) {
|
|
146
171
|
for (const [k, v] of Object.entries({ runtime, agent, proj })) {
|
|
147
172
|
if (typeof v !== 'string' || !v) throw new Error(`launch: ${k} must be a non-empty string`);
|
|
148
173
|
}
|
|
@@ -198,6 +223,11 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
198
223
|
// or a project that contains one of these paths (a project that IS $HOME,
|
|
199
224
|
// or holds its own `.ssh`) would leak the real drawer through the overlay.
|
|
200
225
|
for (const p of LOCKED_PATHS) args.push(...lockMask(`${home}/${p}`, home, proj));
|
|
226
|
+
// barebox's own config: settings the agent must neither read nor edit.
|
|
227
|
+
// Masked wherever it resolves (XDG_CONFIG_HOME may move it).
|
|
228
|
+
args.push(...lockMask(dirname(configPath(process.env)), home, proj));
|
|
229
|
+
// The label folders (the letters live there) get the same mask.
|
|
230
|
+
for (const d of maskDirs) args.push(...lockMask(d, home, proj));
|
|
201
231
|
// The runtime tree holds the file-checkpoint dirs (`asks/`, `answers/`
|
|
202
232
|
// — the approve/deny capability) and every agent's socket (identity). A
|
|
203
233
|
// read-only bind does NOT stop connect(2) to a unix socket, so wherever
|
|
@@ -254,18 +284,33 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
254
284
|
'--setenv', 'HTTPS_PROXY', `http://127.0.0.1:${proxyPort}`,
|
|
255
285
|
'--setenv', 'http_proxy', `http://127.0.0.1:${proxyPort}`,
|
|
256
286
|
'--setenv', 'https_proxy', `http://127.0.0.1:${proxyPort}`,
|
|
287
|
+
// Node's built-in fetch ignores the proxy variables unless this is set.
|
|
288
|
+
'--setenv', 'NODE_USE_ENV_PROXY', '1',
|
|
257
289
|
);
|
|
258
290
|
if (caBundle) {
|
|
259
291
|
for (const v of CA_ENV_VARS) args.push('--setenv', v, '/run/sbx/ca-bundle.pem');
|
|
260
292
|
}
|
|
293
|
+
// M5: the host environment never enters. The default list and `env.pass` are read from this
|
|
294
|
+
// process; then `env.set`, one placeholder per secret, and `extraEnv` (last wins).
|
|
295
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
296
|
+
if (v !== undefined && PASS_DEFAULT.test(k)) args.push('--setenv', k, v);
|
|
297
|
+
}
|
|
298
|
+
for (const k of env.pass ?? []) {
|
|
299
|
+
const v = process.env[k];
|
|
300
|
+
if (v !== undefined) args.push('--setenv', k, v);
|
|
301
|
+
}
|
|
302
|
+
for (const [k, v] of Object.entries(env.set ?? {})) args.push('--setenv', k, String(v));
|
|
303
|
+
for (const [k, v] of Object.entries(env.placeholders ?? {})) args.push('--setenv', k, String(v));
|
|
261
304
|
for (const [k, v] of Object.entries(extraEnv)) args.push('--setenv', k, String(v));
|
|
262
305
|
const door = String(proxyPort);
|
|
263
306
|
const inner = 'ip link set lo up 2>/dev/null; ' +
|
|
264
307
|
`socat TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
|
|
265
308
|
`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; ` +
|
|
266
309
|
'[ -n "$ok" ] || exit 99; exec "$@"';
|
|
267
|
-
const child = spawn(
|
|
268
|
-
|
|
310
|
+
const child = spawn(bwrapBin(), [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
|
|
311
|
+
// A clean spawn environment: bwrap's own pid-1 process keeps the environment it was started
|
|
312
|
+
// with (it is `/proc/1/environ` inside), so the host's must not be it.
|
|
313
|
+
{ stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin' } });
|
|
269
314
|
// No `.overlay` on the child: the tracing paper's address is one call,
|
|
270
315
|
// `runtimePaths(runtime).overlay(agent)`, so there is nothing to keep in sync.
|
|
271
316
|
return child;
|
package/src/policy.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// policy.js — the one owner of what each mode lets through.
|
|
2
|
+
//
|
|
3
|
+
// Every request becomes one bareguard action and one `gate.check()`. The
|
|
4
|
+
// mode only chooses the agent's letters and which unheld letters ask:
|
|
5
|
+
// ask -> holds "r--", asks for w and x
|
|
6
|
+
// auto -> holds "rw-", asks for x
|
|
7
|
+
// trust -> holds "rwx", asks for nothing
|
|
8
|
+
// A request is one tool: `<vendor>.<operationId>` when a label file documents
|
|
9
|
+
// it (letters come from the gate file), `<host>.POST <path>` for a known model
|
|
10
|
+
// endpoint (`r`), else `http.<METHOD>`: GET and HEAD are `r`; POST, PUT, PATCH
|
|
11
|
+
// and DELETE are `x`. A tool that is not listed is denied (`rwx.unlisted`) in
|
|
12
|
+
// every mode. The card/payment floor
|
|
13
|
+
// is `flags`: it asks in every mode, trust included.
|
|
14
|
+
import { Gate } from 'bareguard';
|
|
15
|
+
import { matcherFrom } from 'rwxmap/match';
|
|
16
|
+
|
|
17
|
+
/** The mode names, in the order the CLI and config list them. */
|
|
18
|
+
export const MODES = ['ask', 'auto', 'trust'];
|
|
19
|
+
|
|
20
|
+
const MODE_RULES = {
|
|
21
|
+
ask: { letters: 'r--', askUnheld: ['w', 'x'] },
|
|
22
|
+
auto: { letters: 'rw-', askUnheld: ['x'] },
|
|
23
|
+
trust: { letters: 'rwx', askUnheld: [] },
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// One map for every gate (the grant comes from each gate's letters, never
|
|
27
|
+
// from the action).
|
|
28
|
+
const TOOLS = {
|
|
29
|
+
'http.GET': 'r',
|
|
30
|
+
'http.HEAD': 'r',
|
|
31
|
+
'http.POST': 'x',
|
|
32
|
+
'http.PUT': 'x',
|
|
33
|
+
'http.PATCH': 'x',
|
|
34
|
+
'http.DELETE': 'x',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Model-call endpoints per host (`host[:port]`); each is `POST` and reads (`r`). */
|
|
38
|
+
const MODEL_PATHS = {
|
|
39
|
+
'api.anthropic.com': ['/v1/messages', '/v1/messages/count_tokens'],
|
|
40
|
+
'api.openai.com': ['/v1/chat/completions', '/v1/responses', '/v1/embeddings'],
|
|
41
|
+
};
|
|
42
|
+
const LOCAL_LLM_PATHS = ['/api/chat', '/api/generate', '/api/embed',
|
|
43
|
+
'/v1/chat/completions', '/v1/completions'];
|
|
44
|
+
|
|
45
|
+
/** The matcher used when no label files are loaded: every request is request-only. */
|
|
46
|
+
export const emptyMatcher = matcherFrom([]);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The one tools table of a runtime: the `http.*` tools, the model endpoints
|
|
50
|
+
* (`r`) and the label tools. Model keys come from `matcher.match()` itself so
|
|
51
|
+
* there is no second key builder.
|
|
52
|
+
*
|
|
53
|
+
* @param {Record<string, any>} [labelTools] the label files' gate-file tools (`{ key: { letter, marker } }`)
|
|
54
|
+
* @param {string[]} [localLlm] `host:port` pairs of local model servers
|
|
55
|
+
* @returns {Record<string, any>} tool name to letter
|
|
56
|
+
*/
|
|
57
|
+
export function buildTools(labelTools = {}, localLlm = []) {
|
|
58
|
+
/** @type {Record<string, any>} */
|
|
59
|
+
const models = {};
|
|
60
|
+
const add = (scheme, host, paths) => {
|
|
61
|
+
for (const p of paths) models[emptyMatcher.match('POST', `${scheme}://${host}${p}`).key] = 'r';
|
|
62
|
+
};
|
|
63
|
+
for (const [host, paths] of Object.entries(MODEL_PATHS)) add('https', host, paths);
|
|
64
|
+
for (const hp of localLlm) add('http', hp, LOCAL_LLM_PATHS);
|
|
65
|
+
return { ...TOOLS, ...models, ...labelTools };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The tool name for one request. A spec key (a label file documents it) is
|
|
70
|
+
* used as is, even if the gate file lacks it (then the gate denies it:
|
|
71
|
+
* fail closed). A request-only key is used only when it is a known model
|
|
72
|
+
* endpoint; everything else is `http.<METHOD>`. Never the matcher's letter.
|
|
73
|
+
*
|
|
74
|
+
* @param {{ match: (method: string, url: string) => { key: string, source: string } }} matcher
|
|
75
|
+
* @param {Record<string, any>} tools the runtime's tools table
|
|
76
|
+
* @param {string} method HTTP method
|
|
77
|
+
* @param {string} url full request URL
|
|
78
|
+
* @returns {string} the tool name
|
|
79
|
+
*/
|
|
80
|
+
export function toolFor(matcher, tools, method, url) {
|
|
81
|
+
try {
|
|
82
|
+
const r = matcher.match(method, url);
|
|
83
|
+
if (r.source === 'spec' || Object.hasOwn(tools, r.key)) return r.key;
|
|
84
|
+
} catch { /* not an http(s) URL: fall through */ }
|
|
85
|
+
return `http.${method}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @type {Record<string, Record<string, 'ask' | 'deny'>>} */
|
|
89
|
+
const FLAGS = { cardLike: { true: 'ask' }, paymentPath: { true: 'ask' } };
|
|
90
|
+
|
|
91
|
+
/** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
|
|
92
|
+
const PAYMENT_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* True when the URL's path names a payment destination (the floor's
|
|
96
|
+
* URL-visible half). An unparsable URL is not one.
|
|
97
|
+
*
|
|
98
|
+
* @param {string} url full request URL
|
|
99
|
+
* @returns {boolean} whether the path contains a payment fragment
|
|
100
|
+
*/
|
|
101
|
+
export function paymentPath(url) {
|
|
102
|
+
let pathname;
|
|
103
|
+
try {
|
|
104
|
+
pathname = new URL(url).pathname.toLowerCase();
|
|
105
|
+
} catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
return PAYMENT_PATHS.some((p) => pathname.includes(p));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Build and initialise one agent's gate.
|
|
113
|
+
*
|
|
114
|
+
* @param {object} opts
|
|
115
|
+
* @param {string} opts.agent agent name (the gate's rwx agent)
|
|
116
|
+
* @param {string} opts.mode `ask` | `auto` | `trust`
|
|
117
|
+
* @param {string} opts.auditPath bareguard audit file (shared by every gate of a runtime)
|
|
118
|
+
* @param {Record<string, any>} [opts.tools] the runtime's tools table (default: the `http.*` tools)
|
|
119
|
+
* @param {(event: any) => Promise<{ decision: 'allow' | 'deny', reason?: string }>} opts.humanChannel resolves every ask
|
|
120
|
+
* @returns {Promise<Gate>} an initialised gate
|
|
121
|
+
*/
|
|
122
|
+
export async function gateFor({ agent, mode, auditPath, humanChannel, tools = TOOLS }) {
|
|
123
|
+
if (!MODES.includes(mode)) {
|
|
124
|
+
throw new Error(`policy: mode must be ${MODES.join('|')}, got ${JSON.stringify(mode)}`);
|
|
125
|
+
}
|
|
126
|
+
const { letters, askUnheld } = MODE_RULES[mode];
|
|
127
|
+
const gate = new Gate({
|
|
128
|
+
audit: { path: auditPath },
|
|
129
|
+
// Explicit letters and an empty sharedFile ('' is falsy: no file, and bareguard's
|
|
130
|
+
// `??` stops there) keep the host's BAREGUARD_RWX_LETTERS / BAREGUARD_BUDGET_FILE out.
|
|
131
|
+
rwx: { agent, letters, tools, askUnheld },
|
|
132
|
+
budget: { sharedFile: '' },
|
|
133
|
+
// The mode letters plus the card/payment floor are the whole policy; bareguard's
|
|
134
|
+
// default word patterns scan the URL and method and would fire before rwx.
|
|
135
|
+
content: { askPatterns: [], denyPatterns: [] },
|
|
136
|
+
flags: FLAGS,
|
|
137
|
+
humanChannel,
|
|
138
|
+
});
|
|
139
|
+
await gate.init();
|
|
140
|
+
return gate;
|
|
141
|
+
}
|