barebox 0.5.0 → 0.7.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 +42 -0
- package/README.md +19 -4
- package/barebox.context.md +81 -8
- package/package.json +2 -2
- package/primitives.json +11 -2
- package/src/cli.js +5 -3
- package/src/config.js +53 -2
- package/src/index.js +1 -0
- package/src/labels.js +6 -0
- package/src/launcher.js +82 -33
- package/src/overlay.js +3 -3
- package/src/policy.js +4 -1
- package/src/proxy.js +76 -8
- package/src/run.js +11 -3
- package/src/runtime.js +22 -0
- package/src/secrets.js +121 -0
- package/types/config.d.ts +20 -2
- package/types/index.d.ts +1 -0
- package/types/labels.d.ts +6 -0
- package/types/launcher.d.ts +11 -3
- package/types/proxy.d.ts +5 -0
- package/types/run.d.ts +30 -2
- package/types/runtime.d.ts +18 -0
- package/types/secrets.d.ts +68 -0
package/src/launcher.js
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
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';
|
|
8
|
-
import { assertAgentName, isInside, realPathOf, runtimePaths } from './runtime.js';
|
|
6
|
+
import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { join, relative, dirname, delimiter } from 'node:path';
|
|
8
|
+
import { assertAgentName, hostNode, isInside, realPathOf, runtimePaths } from './runtime.js';
|
|
9
9
|
import { assertOverlaySupport, setupOverlay } from './overlay.js';
|
|
10
10
|
import { configPath } from './config.js';
|
|
11
11
|
|
|
@@ -47,28 +47,30 @@ const LOCKED_PATHS = [
|
|
|
47
47
|
'.cargo/credentials.toml',
|
|
48
48
|
];
|
|
49
49
|
|
|
50
|
+
const SYSTEM_PATH = ['/usr/bin', '/bin', '/usr/sbin'];
|
|
51
|
+
|
|
50
52
|
/**
|
|
51
53
|
* The bwrap args that mask one locked path, or none when it does not exist.
|
|
52
54
|
* A symlinked drawer (dotfile managers) is masked at its real target, which
|
|
53
55
|
* is where bwrap lands a mount anyway, so the content is shut at both
|
|
54
|
-
* spellings; a target outside
|
|
55
|
-
*
|
|
56
|
+
* spellings; a target outside every bound root is not in the sandbox at all,
|
|
57
|
+
* so there is nothing to mask.
|
|
56
58
|
*
|
|
57
|
-
* @param {string} abs the locked path (under
|
|
58
|
-
* @param {string}
|
|
59
|
-
* @param {string} proj project dir
|
|
59
|
+
* @param {string} abs the locked path (under a bound root to matter)
|
|
60
|
+
* @param {string[]} roots the paths the sandbox binds in: `$HOME`, the project, `/etc`, `/usr` and the Node install
|
|
60
61
|
* @returns {string[]} `--tmpfs <dir>` or `--dev-bind /dev/null <file>`, or `[]`
|
|
61
62
|
*/
|
|
62
|
-
function lockMask(abs,
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
function lockMask(abs, roots) {
|
|
64
|
+
const bound = (p) => roots.some((r) => isInside(r, p));
|
|
65
|
+
// Under no bound root: not in the sandbox at all.
|
|
66
|
+
if (!bound(abs)) return [];
|
|
65
67
|
let target = abs;
|
|
66
68
|
let st;
|
|
67
69
|
try {
|
|
68
70
|
st = lstatSync(abs);
|
|
69
71
|
if (st.isSymbolicLink()) {
|
|
70
72
|
target = realPathOf(abs);
|
|
71
|
-
if (!
|
|
73
|
+
if (!bound(target)) return [];
|
|
72
74
|
st = statSync(target);
|
|
73
75
|
}
|
|
74
76
|
} catch {
|
|
@@ -88,6 +90,26 @@ const SYSTEM_BUNDLES = [
|
|
|
88
90
|
const CA_ENV_VARS = ['SSL_CERT_FILE', 'NODE_EXTRA_CA_CERTS', 'REQUESTS_CA_BUNDLE',
|
|
89
91
|
'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO'];
|
|
90
92
|
|
|
93
|
+
// Host variables that reach the inside without being asked for (M5). Nothing
|
|
94
|
+
// else does: the sandbox gets a short list, not the host environment.
|
|
95
|
+
const PASS_DEFAULT = /^(TERM|COLORTERM|LANG|LANGUAGE|LC_[A-Z_]+|TZ|USER|LOGNAME|SHELL|EDITOR|PAGER)$/;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Where `bwrap` is, looked up on THIS process's PATH. The spawn below runs
|
|
99
|
+
* with a clean environment (its PATH is fixed), so node could not find a
|
|
100
|
+
* `bwrap` that the caller's PATH puts first (the fake one the tests use).
|
|
101
|
+
*
|
|
102
|
+
* @returns {string} the first executable `bwrap` on PATH, else the bare name (spawn then fails ENOENT as before)
|
|
103
|
+
*/
|
|
104
|
+
function bwrapBin() {
|
|
105
|
+
for (const d of (process.env.PATH ?? '').split(delimiter)) {
|
|
106
|
+
if (!d) continue;
|
|
107
|
+
const p = join(d, 'bwrap');
|
|
108
|
+
try { accessSync(p, constants.X_OK); return p; } catch {}
|
|
109
|
+
}
|
|
110
|
+
return 'bwrap';
|
|
111
|
+
}
|
|
112
|
+
|
|
91
113
|
/**
|
|
92
114
|
* Build the CA bundle the sandbox trusts: system roots plus the barebox CA,
|
|
93
115
|
* so public hosts verify as usual and the proxy's minted certs verify too.
|
|
@@ -131,22 +153,24 @@ export function buildCaBundle(runtime, caFile) {
|
|
|
131
153
|
* @param {string} opts.proj project directory, bound read-only
|
|
132
154
|
* @param {string[]} opts.command argv to run inside, for example `["python3", "agent.py"]`
|
|
133
155
|
* @param {number} [opts.proxyPort] front-door port inside the sandbox (default 3128)
|
|
134
|
-
* @param {object} [opts.extraEnv] extra environment entries for the inside
|
|
156
|
+
* @param {object} [opts.extraEnv] extra environment entries for the inside, set last (they win)
|
|
157
|
+
* @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`.
|
|
135
158
|
* @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
|
|
136
159
|
* @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
|
|
160
|
+
* @param {string} [opts.nodeExec] the node executable to run inside (default: this process's `process.execPath`). The install is a `bin/` layout's parent dir (npm and global CLIs live there) or, for any other layout, the exec's own dir. It is bound read-only with the exec's dir first on the inside PATH, unless already visible there (under `/usr`, `$HOME` or the project). Never bound when it is `/`, `$HOME` or above it: then it is not on PATH either (see `hostNode` in `src/runtime.js`). A runtime or project under the install is masked or mounted over it, so the bind never exposes either
|
|
137
161
|
* @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)
|
|
138
162
|
* @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)`
|
|
139
163
|
* @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
|
|
140
164
|
* @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
|
|
141
165
|
* @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.
|
|
142
|
-
* @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
|
|
166
|
+
* @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`, the project dir, `/etc`, `/usr` or the bound Node install 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.
|
|
143
167
|
* @example
|
|
144
168
|
* import { launch } from "barebox";
|
|
145
169
|
* const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
|
|
146
170
|
* await new Promise((r) => child.on("close", r)); // child.exitCode === 0
|
|
147
171
|
*/
|
|
148
172
|
export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
149
|
-
extraEnv = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [] }) {
|
|
173
|
+
extraEnv = {}, env = {}, socket = null, caFile = null, overlay = false, overlayIgnore, maskDirs = [], nodeExec = process.execPath }) {
|
|
150
174
|
for (const [k, v] of Object.entries({ runtime, agent, proj })) {
|
|
151
175
|
if (typeof v !== 'string' || !v) throw new Error(`launch: ${k} must be a non-empty string`);
|
|
152
176
|
}
|
|
@@ -174,6 +198,12 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
174
198
|
ov = setupOverlay({ runtime, agent, proj, ignore: overlayIgnore });
|
|
175
199
|
}
|
|
176
200
|
const home = process.env.HOME || '/root';
|
|
201
|
+
// A Node outside /usr and $HOME (nvm, a CI toolcache) is bound read-only too, so the host's
|
|
202
|
+
// node and its global CLIs run inside.
|
|
203
|
+
const { bin: nodeBin, bind: nodeBind } = hostNode(nodeExec, home, proj);
|
|
204
|
+
// Every path the sandbox binds in from the host: the locked drawers and mask folders are
|
|
205
|
+
// hidden wherever they sit under one of these.
|
|
206
|
+
const roots = [home, proj, '/etc', '/usr', ...(nodeBind ? [nodeBind] : [])];
|
|
177
207
|
const args = [
|
|
178
208
|
'--unshare-pid', '--unshare-uts', '--unshare-ipc', '--unshare-net',
|
|
179
209
|
'--die-with-parent',
|
|
@@ -181,7 +211,11 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
181
211
|
'--ro-bind', '/usr', '/usr',
|
|
182
212
|
'--symlink', 'usr/lib64', '/lib64',
|
|
183
213
|
'--ro-bind', '/etc', '/etc',
|
|
184
|
-
//
|
|
214
|
+
// The Node install first: a project or runtime inside it must win over it.
|
|
215
|
+
// It never holds $HOME and is never inside $HOME, /usr or the project (then
|
|
216
|
+
// it is not bound), so the only overlap is a project or runtime under it.
|
|
217
|
+
...(nodeBind ? ['--ro-bind', nodeBind, nodeBind] : []),
|
|
218
|
+
// $HOME next, the project after: a project under $HOME would otherwise
|
|
185
219
|
// vanish under the home bind (bwrap mounts cover what is below them —
|
|
186
220
|
// the later mount wins where they overlap). The project mount (overlay
|
|
187
221
|
// or read-only) therefore lands on top of the read-only home.
|
|
@@ -201,12 +235,12 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
201
235
|
// Locked drawers AFTER the project mount: the tmpfs mask must land on top,
|
|
202
236
|
// or a project that contains one of these paths (a project that IS $HOME,
|
|
203
237
|
// or holds its own `.ssh`) would leak the real drawer through the overlay.
|
|
204
|
-
for (const p of LOCKED_PATHS) args.push(...lockMask(`${home}/${p}`,
|
|
238
|
+
for (const p of LOCKED_PATHS) args.push(...lockMask(`${home}/${p}`, roots));
|
|
205
239
|
// barebox's own config: settings the agent must neither read nor edit.
|
|
206
240
|
// Masked wherever it resolves (XDG_CONFIG_HOME may move it).
|
|
207
|
-
args.push(...lockMask(dirname(configPath(process.env)),
|
|
241
|
+
args.push(...lockMask(dirname(configPath(process.env)), roots));
|
|
208
242
|
// The label folders (the letters live there) get the same mask.
|
|
209
|
-
for (const d of maskDirs) args.push(...lockMask(d,
|
|
243
|
+
for (const d of maskDirs) args.push(...lockMask(d, roots));
|
|
210
244
|
// The runtime tree holds the file-checkpoint dirs (`asks/`, `answers/`
|
|
211
245
|
// — the approve/deny capability) and every agent's socket (identity). A
|
|
212
246
|
// read-only bind does NOT stop connect(2) to a unix socket, so wherever
|
|
@@ -225,21 +259,21 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
225
259
|
// resolved), so a runtime passed as a symlink from outside $HOME/proj
|
|
226
260
|
// can still land inside it and stay visible through the ro-binds — the
|
|
227
261
|
// mask below covers that spelling too.
|
|
228
|
-
|
|
229
|
-
const
|
|
262
|
+
// Every root the sandbox binds: (real path, the spelling bwrap sees).
|
|
263
|
+
const bases = roots.map((r) => [realPathOf(join(r)), join(r)]);
|
|
230
264
|
const realRt = realPathOf(join(runtime));
|
|
231
|
-
const realHm = realPathOf(hm);
|
|
232
|
-
const realPr = realPathOf(pr);
|
|
233
265
|
// One real-path comparison: a lexically-equal spelling resolves to the
|
|
234
266
|
// same real path, so it is subsumed here.
|
|
235
|
-
|
|
236
|
-
|
|
267
|
+
const same = bases.findIndex(([realBase]) => realRt === realBase);
|
|
268
|
+
if (same >= 0) {
|
|
269
|
+
const what = same === 0 ? 'HOME' : same === 1 ? 'the project dir' : roots[same] === nodeBind ? 'the Node install dir' : roots[same];
|
|
270
|
+
throw new Error(`launch: runtime must not be ${what} itself (its sockets cannot be hidden there)`);
|
|
237
271
|
}
|
|
238
|
-
// Mask the sandbox-visible spelling join(
|
|
239
|
-
//
|
|
240
|
-
//
|
|
241
|
-
for (const [realBase, baseSpelling] of
|
|
242
|
-
if (
|
|
272
|
+
// Mask the sandbox-visible spelling join(root, relative(realRoot, realRt)):
|
|
273
|
+
// where nothing is a symlink this IS the lexical path, so no separate
|
|
274
|
+
// lexical mask is needed.
|
|
275
|
+
for (const [realBase, baseSpelling] of bases) {
|
|
276
|
+
if (isInside(realBase, realRt)) {
|
|
243
277
|
const m = join(baseSpelling, relative(realBase, realRt));
|
|
244
278
|
if (!args.includes(m)) args.push('--tmpfs', m);
|
|
245
279
|
}
|
|
@@ -258,23 +292,38 @@ export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
|
258
292
|
}
|
|
259
293
|
args.push(
|
|
260
294
|
'--setenv', 'HOME', home,
|
|
261
|
-
'--setenv', 'PATH', '
|
|
295
|
+
'--setenv', 'PATH', (!nodeBin || SYSTEM_PATH.includes(nodeBin) ? SYSTEM_PATH : [nodeBin, ...SYSTEM_PATH]).join(':'),
|
|
262
296
|
'--setenv', 'HTTP_PROXY', `http://127.0.0.1:${proxyPort}`,
|
|
263
297
|
'--setenv', 'HTTPS_PROXY', `http://127.0.0.1:${proxyPort}`,
|
|
264
298
|
'--setenv', 'http_proxy', `http://127.0.0.1:${proxyPort}`,
|
|
265
299
|
'--setenv', 'https_proxy', `http://127.0.0.1:${proxyPort}`,
|
|
300
|
+
// Node's built-in fetch ignores the proxy variables unless this is set.
|
|
301
|
+
'--setenv', 'NODE_USE_ENV_PROXY', '1',
|
|
266
302
|
);
|
|
267
303
|
if (caBundle) {
|
|
268
304
|
for (const v of CA_ENV_VARS) args.push('--setenv', v, '/run/sbx/ca-bundle.pem');
|
|
269
305
|
}
|
|
306
|
+
// M5: the host environment never enters. The default list and `env.pass` are read from this
|
|
307
|
+
// process; then `env.set`, one placeholder per secret, and `extraEnv` (last wins).
|
|
308
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
309
|
+
if (v !== undefined && PASS_DEFAULT.test(k)) args.push('--setenv', k, v);
|
|
310
|
+
}
|
|
311
|
+
for (const k of env.pass ?? []) {
|
|
312
|
+
const v = process.env[k];
|
|
313
|
+
if (v !== undefined) args.push('--setenv', k, v);
|
|
314
|
+
}
|
|
315
|
+
for (const [k, v] of Object.entries(env.set ?? {})) args.push('--setenv', k, String(v));
|
|
316
|
+
for (const [k, v] of Object.entries(env.placeholders ?? {})) args.push('--setenv', k, String(v));
|
|
270
317
|
for (const [k, v] of Object.entries(extraEnv)) args.push('--setenv', k, String(v));
|
|
271
318
|
const door = String(proxyPort);
|
|
272
319
|
const inner = 'ip link set lo up 2>/dev/null; ' +
|
|
273
320
|
`socat TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
|
|
274
321
|
`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; ` +
|
|
275
322
|
'[ -n "$ok" ] || exit 99; exec "$@"';
|
|
276
|
-
const child = spawn(
|
|
277
|
-
|
|
323
|
+
const child = spawn(bwrapBin(), [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
|
|
324
|
+
// A clean spawn environment: bwrap's own pid-1 process keeps the environment it was started
|
|
325
|
+
// with (it is `/proc/1/environ` inside), so the host's must not be it.
|
|
326
|
+
{ stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin' } });
|
|
278
327
|
// No `.overlay` on the child: the tracing paper's address is one call,
|
|
279
328
|
// `runtimePaths(runtime).overlay(agent)`, so there is nothing to keep in sync.
|
|
280
329
|
return child;
|
package/src/overlay.js
CHANGED
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
} from 'node:fs';
|
|
19
19
|
import { join, dirname } from 'node:path';
|
|
20
20
|
import { fileURLToPath } from 'node:url';
|
|
21
|
-
import { assertAgentName, runtimeTempDir, runtimePaths, safe } from './runtime.js';
|
|
21
|
+
import { assertAgentName, hostNode, runtimeTempDir, runtimePaths, safe } from './runtime.js';
|
|
22
22
|
|
|
23
23
|
/** One reviewed file change: what the sandbox did at `path`, and whether the project changed underneath it mid-run.
|
|
24
24
|
*
|
|
@@ -468,8 +468,8 @@ function bwrapWalk({ lower, upper, work, ignore, scratch, stageDir = null, upper
|
|
|
468
468
|
// /usr). Its prefix is bound read-only when /usr does not already show it.
|
|
469
469
|
const node = realpathSync(process.execPath);
|
|
470
470
|
const underUsr = node === '/usr' || node.startsWith('/usr/');
|
|
471
|
-
|
|
472
|
-
const nodePrefix =
|
|
471
|
+
// Only the install dir: this trusted walker binds even `/` (see below), so `refused` is ignored.
|
|
472
|
+
const nodePrefix = hostNode(node, process.env.HOME || '/root').dir;
|
|
473
473
|
try {
|
|
474
474
|
// No output cap (stdout carries no data) and no time limit: the walk
|
|
475
475
|
// is finite (`lstat`, never following symlinks), and killing a commit's
|
package/src/policy.js
CHANGED
|
@@ -126,7 +126,10 @@ export async function gateFor({ agent, mode, auditPath, humanChannel, tools = TO
|
|
|
126
126
|
const { letters, askUnheld } = MODE_RULES[mode];
|
|
127
127
|
const gate = new Gate({
|
|
128
128
|
audit: { path: auditPath },
|
|
129
|
-
|
|
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: '' },
|
|
130
133
|
// The mode letters plus the card/payment floor are the whole policy; bareguard's
|
|
131
134
|
// default word patterns scan the URL and method and would fire before rwx.
|
|
132
135
|
content: { askPatterns: [], denyPatterns: [] },
|
package/src/proxy.js
CHANGED
|
@@ -23,6 +23,7 @@ import { ASK_BODY_LIMIT, DEFAULT_HOLD_MAX_BODY, bodyPreview, createHolds } from
|
|
|
23
23
|
import { claimRuntime, ensurePrivateDir, runtimePaths } from './runtime.js';
|
|
24
24
|
import { paymentPath, toolFor, buildTools, emptyMatcher } from './policy.js';
|
|
25
25
|
import { checkUpstream } from './wall.js';
|
|
26
|
+
import { findPlaceholders, urlPlaceholders, applySecrets } from './secrets.js';
|
|
26
27
|
import { Gate } from 'bareguard';
|
|
27
28
|
|
|
28
29
|
const AGENT = Symbol('agent');
|
|
@@ -60,6 +61,7 @@ const HOP_RESP = new Set(['connection', 'keep-alive', 'proxy-authenticate',
|
|
|
60
61
|
* so tests pass this; production never should.
|
|
61
62
|
* @property {(host: string) => Promise<string[] | string | null>} [unsafeTestOnly.resolveUpstream]
|
|
62
63
|
* DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
|
|
64
|
+
* @property {import('./secrets.js').Secret[]} [secrets] the loaded secrets (`loadSecrets`): a request carrying a secret's placeholder in a header gets the real value there only after the gate allowed it and only for a bound host; for any other host it is refused `403 denied: secret.host`. The value never reaches the audit file, an ask or an error body.
|
|
63
65
|
* @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
|
|
64
66
|
* @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing; its result becomes the `meta` of an `annotate` line (default: identity)
|
|
65
67
|
*/
|
|
@@ -123,7 +125,7 @@ export function createProxy(opts) {
|
|
|
123
125
|
const { logFile, runtime, port = null,
|
|
124
126
|
upstreamCa = null, hold = null, gateFor = null, allowLocal = [], labels = null,
|
|
125
127
|
upstreamTimeoutMs = 120000, clientIdleMs = 60000,
|
|
126
|
-
unsafeTestOnly = null,
|
|
128
|
+
unsafeTestOnly = null, secrets = [],
|
|
127
129
|
redact = (e) => e } = opts ?? {};
|
|
128
130
|
const { allowLoopback = false, resolveUpstream = null } = unsafeTestOnly ?? {};
|
|
129
131
|
const gate = {
|
|
@@ -538,6 +540,7 @@ export function createProxy(opts) {
|
|
|
538
540
|
};
|
|
539
541
|
/** @param {string} reason @param {number} [status] */
|
|
540
542
|
const refuse = (reason, status) => {
|
|
543
|
+
if (settled) return; // a late failure must not rewrite the settled deny's status
|
|
541
544
|
if (status) ctx.status = status;
|
|
542
545
|
finish({ decision: 'deny', reason });
|
|
543
546
|
};
|
|
@@ -659,6 +662,44 @@ export function createProxy(opts) {
|
|
|
659
662
|
denyRes(cres, 403, verdict.reason);
|
|
660
663
|
return;
|
|
661
664
|
}
|
|
665
|
+
// The request's one id: the audit lines of its secret swap, its body and
|
|
666
|
+
// its gate decision all carry it.
|
|
667
|
+
const rid = `r${++ridN}`;
|
|
668
|
+
// M5: a placeholder is found before the gate and swapped only after it
|
|
669
|
+
// allows (`withSecrets`), so the real value never sits in `ctx.headers`
|
|
670
|
+
// while the request waits for a decision. A placeholder headed for a host
|
|
671
|
+
// its secret is not bound to is refused in every mode.
|
|
672
|
+
const found = secrets.length ? findPlaceholders(creq.headers, url.hostname, secrets) : [];
|
|
673
|
+
const unbound = found.filter((f) => !f.bound);
|
|
674
|
+
if (unbound.length) {
|
|
675
|
+
for (const f of unbound) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: false });
|
|
676
|
+
try { creq.resume(); } catch {}
|
|
677
|
+
denyRes(cres, 403, 'denied: secret.host');
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
// A real value only ever goes upstream over TLS: forwardInner picks
|
|
681
|
+
// https from this same `url.protocol`, so a cleartext hop is refused here.
|
|
682
|
+
if (found.length && url.protocol !== 'https:') {
|
|
683
|
+
for (const f of found) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: false });
|
|
684
|
+
try { creq.resume(); } catch {}
|
|
685
|
+
denyRes(cres, 403, 'denied: secret.scheme');
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
// Keys are swapped in headers only: a placeholder in the URL is refused,
|
|
689
|
+
// not sent as a literal that the API would answer 401 for no visible reason.
|
|
690
|
+
const inUrl = secrets.length ? urlPlaceholders(url.pathname + url.search, secrets) : [];
|
|
691
|
+
if (inUrl.length) {
|
|
692
|
+
for (const name of inUrl) log({ ev: 'secret', agent, rid, name, host: url.hostname, swapped: false });
|
|
693
|
+
try { creq.resume(); } catch {}
|
|
694
|
+
denyRes(cres, 403, 'denied: secret.url');
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
/** The headers to forward: the real values in, one audit line per swap. @param {Record<string, string | string[] | undefined>} headers */
|
|
698
|
+
const withSecrets = (headers) => {
|
|
699
|
+
if (!found.length) return headers;
|
|
700
|
+
for (const f of found) log({ ev: 'secret', agent, rid, name: f.name, host: url.hostname, swapped: true });
|
|
701
|
+
return applySecrets(headers, url.hostname, secrets);
|
|
702
|
+
};
|
|
662
703
|
const cl = Number(creq.headers['content-length'] ?? 0);
|
|
663
704
|
const hasBody = creq.headers['transfer-encoding'] !== undefined || cl > 0;
|
|
664
705
|
|
|
@@ -672,7 +713,6 @@ export function createProxy(opts) {
|
|
|
672
713
|
// `end` fires once the whole body was read, whichever path read it (also
|
|
673
714
|
// a streamed body past 64 KB), so the values cover all of it. A client
|
|
674
715
|
// that aborts mid-body never reaches `end`: no line, as before.
|
|
675
|
-
const rid = `r${++ridN}`;
|
|
676
716
|
if (hasBody) {
|
|
677
717
|
creq.on('end', () => log({ ev: 'body', agent, rid, bodyBytes: tee.bytes, bodySha256: tee.digest() }));
|
|
678
718
|
}
|
|
@@ -680,7 +720,7 @@ export function createProxy(opts) {
|
|
|
680
720
|
|
|
681
721
|
// No gate: straight through. pipe() resumes the flow.
|
|
682
722
|
if (!gateFor) {
|
|
683
|
-
forward({ agent, method, url: urlStr, headers: { ...creq.headers }, stream: creq, cres });
|
|
723
|
+
forward({ agent, method, url: urlStr, headers: withSecrets({ ...creq.headers }), stream: creq, cres });
|
|
684
724
|
return;
|
|
685
725
|
}
|
|
686
726
|
|
|
@@ -713,7 +753,7 @@ export function createProxy(opts) {
|
|
|
713
753
|
const g = await gateOf(agent);
|
|
714
754
|
const d = await decideAction(g, action);
|
|
715
755
|
if (d.outcome === 'allow') {
|
|
716
|
-
const common = { agent, method, url: urlStr, headers: ctx.headers, cres,
|
|
756
|
+
const common = { agent, method, url: urlStr, headers: withSecrets(ctx.headers), cres,
|
|
717
757
|
...(d.aid ? { rec: { gate: g, action, aid: d.aid } } : {}) };
|
|
718
758
|
if (ctx.heldId) {
|
|
719
759
|
// The file is the exact body; the client's own framing (length or
|
|
@@ -867,6 +907,9 @@ export function createProxy(opts) {
|
|
|
867
907
|
sock.removeListener('data', onData);
|
|
868
908
|
sock.setTimeout(0); // the http.Server owns idle from here
|
|
869
909
|
if (method === 'CONNECT') {
|
|
910
|
+
// Whoever removes the last data listener pauses: a flowing socket with no
|
|
911
|
+
// listener drops what arrives (a hello sent before the 200) and what is pushed back.
|
|
912
|
+
sock.pause();
|
|
870
913
|
handleConnect(sock, target, buf.subarray(i + 4), agent);
|
|
871
914
|
} else {
|
|
872
915
|
// Plain HTTP (absolute- or origin-form): same parser, same handler.
|
|
@@ -893,17 +936,42 @@ export function createProxy(opts) {
|
|
|
893
936
|
denyRaw(sock, 403, verdict.reason);
|
|
894
937
|
return;
|
|
895
938
|
}
|
|
939
|
+
if (closed || sock.destroyed) return;
|
|
940
|
+
try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
|
|
941
|
+
catch { return; }
|
|
942
|
+
// One reader of the first byte: 0x16 is a TLS handshake (decrypt it);
|
|
943
|
+
// anything else is plain HTTP inside the tunnel (Node's fetch tunnels
|
|
944
|
+
// http:// URLs too) and goes to the server as it is, as `admit` does.
|
|
945
|
+
let first = rest;
|
|
946
|
+
if (!first.length) {
|
|
947
|
+
sock.setTimeout(clientIdleMs, () => sock.destroy());
|
|
948
|
+
first = await new Promise((resolve) => {
|
|
949
|
+
const done = (c) => { sock.off('data', done); sock.off('close', gone); sock.pause(); resolve(c); };
|
|
950
|
+
const gone = () => done(Buffer.alloc(0));
|
|
951
|
+
sock.on('data', done);
|
|
952
|
+
sock.on('close', gone);
|
|
953
|
+
sock.resume(); // paused by admit
|
|
954
|
+
});
|
|
955
|
+
sock.setTimeout(0);
|
|
956
|
+
if (!first.length || closed || sock.destroyed) return;
|
|
957
|
+
}
|
|
958
|
+
sock.unshift(first); // paused: admit paused it, and `done` pauses again
|
|
959
|
+
if (first[0] !== 0x16) {
|
|
960
|
+
sock.resume(); // the http server only adds a data listener
|
|
961
|
+
server.emit('connection', sock);
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
// The cert is minted only for a TLS tunnel. The 200 is already sent, so a
|
|
965
|
+
// failure cannot answer 502: it is logged as the deny it would have been.
|
|
896
966
|
let creds;
|
|
897
967
|
try {
|
|
898
968
|
creds = await certFor(certDir, host);
|
|
899
969
|
} catch (e) {
|
|
900
|
-
|
|
970
|
+
log({ ev: 'deny', agent: agentOf(sock), code: 502, note: `no cert for ${host}: ${e.message}` });
|
|
971
|
+
sock.destroy();
|
|
901
972
|
return;
|
|
902
973
|
}
|
|
903
974
|
if (closed || sock.destroyed) return;
|
|
904
|
-
try { sock.write('HTTP/1.1 200 Connection established\r\n\r\n'); }
|
|
905
|
-
catch { return; }
|
|
906
|
-
if (rest.length) sock.unshift(rest);
|
|
907
975
|
const st = new tls.TLSSocket(sock, { isServer: true, key: creds.key, cert: creds.cert });
|
|
908
976
|
st[AGENT] = agent;
|
|
909
977
|
st[SECURE] = true;
|
package/src/run.js
CHANGED
|
@@ -31,6 +31,7 @@ import { createRuntime, runtimePaths } from './runtime.js';
|
|
|
31
31
|
import { launch } from './launcher.js';
|
|
32
32
|
import { diffOverlay } from './overlay.js';
|
|
33
33
|
import { MODES, gateFor } from './policy.js';
|
|
34
|
+
import { loadSecrets } from './secrets.js';
|
|
34
35
|
|
|
35
36
|
/**
|
|
36
37
|
* A collected ask record: the parked ask plus how it was decided.
|
|
@@ -67,6 +68,8 @@ import { MODES, gateFor } from './policy.js';
|
|
|
67
68
|
* @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
|
|
68
69
|
* @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
|
|
69
70
|
* @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
|
|
71
|
+
* @property {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [secrets] keys the agent never holds (M5), the config `secrets` shape: the sandbox gets a random placeholder under each NAME; the proxy swaps in the real value on an allowed request to one of its `hosts` (see `createProxy`). A `fromEnv` variable missing from this process's environment rejects the run, naming the secret
|
|
72
|
+
* @property {{ pass?: string[], set?: Record<string, string> }} [env] the sandbox's environment (M5), the config `env` shape: the host environment never reaches it except a short default list (`TERM`, `LANG`, `LC_*`, `TZ`, ...), the host variables named in `pass` and the values in `set` (see `launch`)
|
|
70
73
|
* @property {boolean} [overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
|
|
71
74
|
* @property {string[]} [overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
|
|
72
75
|
*/
|
|
@@ -89,11 +92,13 @@ import { MODES, gateFor } from './policy.js';
|
|
|
89
92
|
* @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
|
|
90
93
|
* @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
|
|
91
94
|
* @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
|
|
95
|
+
* @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>|null} [opts.secrets] keys the agent never holds (M5), the config `secrets` shape; see {@link RunOptions}
|
|
96
|
+
* @param {{ pass?: string[], set?: Record<string, string> }|null} [opts.env] the sandbox's environment (M5), the config `env` shape; see {@link RunOptions}
|
|
92
97
|
* @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
|
|
93
98
|
* @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
|
|
94
99
|
* @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), and the runtime dir addressing it
|
|
95
100
|
* @when Reach for this to HARNESS-ONLY run one sandboxed agent start-to-finish in a single call: it starts the proxy, sandboxes the command, answers holds, and returns the exit code with the ask and audit trail (plus the overlay diff once M4 exists).
|
|
96
|
-
* @fails Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.
|
|
101
|
+
* @fails Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a `secrets` entry with no value (a `fromEnv` variable missing from this process's environment; the message names the secret, never a value), a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.
|
|
97
102
|
* @example
|
|
98
103
|
* import { run } from "barebox";
|
|
99
104
|
* const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
|
|
@@ -101,7 +106,7 @@ import { MODES, gateFor } from './policy.js';
|
|
|
101
106
|
export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
102
107
|
onEvent = null, runtime = null, agent = 'agent', timeoutMs, heldBodyMaxBytes,
|
|
103
108
|
allowLocal = [], labels = null, unsafeTestOnly = null, stdout = null, stderr = null,
|
|
104
|
-
overlay = false, overlayIgnore }) {
|
|
109
|
+
overlay = false, overlayIgnore, secrets = null, env = null }) {
|
|
105
110
|
if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
|
|
106
111
|
if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
|
|
107
112
|
if (!Array.isArray(command) || !command.length) {
|
|
@@ -114,6 +119,8 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
114
119
|
if (!MODES.includes(mode)) {
|
|
115
120
|
throw new Error(`run: mode must be ${MODES.join('|')}, got ${JSON.stringify(mode)}`);
|
|
116
121
|
}
|
|
122
|
+
// Once per run: the placeholders are fresh per run. A secret without a value throws here, before any runtime dir.
|
|
123
|
+
const loaded = loadSecrets(secrets ?? {});
|
|
117
124
|
// Short temp dir: agent socket paths inherit it and cap at ~108 chars.
|
|
118
125
|
const rt = runtime ?? createRuntime();
|
|
119
126
|
const audit = runtimePaths(rt).audit;
|
|
@@ -136,7 +143,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
136
143
|
: recordEvent;
|
|
137
144
|
|
|
138
145
|
const proxy = createProxy({
|
|
139
|
-
runtime: rt, logFile: audit, allowLocal, unsafeTestOnly,
|
|
146
|
+
runtime: rt, logFile: audit, allowLocal, unsafeTestOnly, secrets: loaded,
|
|
140
147
|
...(labels ? { labels } : {}),
|
|
141
148
|
gateFor: (name, { humanChannel, tools }) => gateFor({ agent: name, mode, auditPath: audit, humanChannel, tools }),
|
|
142
149
|
hold: { onAsk, timeoutMs, maxBody: heldBodyMaxBytes, onEvent: holdOnEvent },
|
|
@@ -161,6 +168,7 @@ export async function run({ proj, command, mode = 'auto', onAsk = null,
|
|
|
161
168
|
runtime: rt, agent, proj, command,
|
|
162
169
|
socket: sock, caFile: proxy.caFile,
|
|
163
170
|
overlay, overlayIgnore, maskDirs: labels?.dirs ?? [],
|
|
171
|
+
env: { ...env, placeholders: Object.fromEntries(loaded.map((s) => [s.name, s.placeholder])) },
|
|
164
172
|
});
|
|
165
173
|
const out = stdout ?? process.stdout;
|
|
166
174
|
const err = stderr ?? process.stderr;
|
package/src/runtime.js
CHANGED
|
@@ -67,6 +67,28 @@ export function isInside(base, p) {
|
|
|
67
67
|
return realP.startsWith(prefix);
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Where the host's node sits and what of it to bind so it runs inside the sandbox. An exec in a
|
|
72
|
+
* `bin/` dir (nvm, fnm, toolcache, distro) has its install one dir up, where npm and the global
|
|
73
|
+
* CLIs live; any other layout is its own dir. Never `/`, `$HOME` or an ancestor of it: binding
|
|
74
|
+
* that would hand the sandbox the whole host or every user's home, so it is `refused` and
|
|
75
|
+
* neither bound nor put on PATH.
|
|
76
|
+
*
|
|
77
|
+
* @param {string} execPath absolute path of the node executable
|
|
78
|
+
* @param {string} home the sandbox $HOME
|
|
79
|
+
* @param {string} [proj] the project dir, already visible inside
|
|
80
|
+
* @returns {{dir: string, bin: string|null, bind: string|null, refused: string|null}} `dir` the install folder; `bin` the PATH entry (null when refused); `bind` the dir to bind read-only (null when refused or already under `/usr`, `$HOME` or the project); `refused` a short reason or null
|
|
81
|
+
*/
|
|
82
|
+
export function hostNode(execPath, home, proj) {
|
|
83
|
+
const bin = path.dirname(execPath);
|
|
84
|
+
const dir = path.basename(bin) === 'bin' ? path.dirname(bin) : bin;
|
|
85
|
+
if (isInside(dir, home)) { // `/` is inside-of-everything: it lands here too
|
|
86
|
+
return { dir, bin: null, bind: null, refused: 'it contains $HOME or is /' };
|
|
87
|
+
}
|
|
88
|
+
const visible = ['/usr', home, ...(proj ? [proj] : [])].some((r) => isInside(r, dir));
|
|
89
|
+
return { dir, bin, bind: visible ? null : dir, refused: null };
|
|
90
|
+
}
|
|
91
|
+
|
|
70
92
|
/**
|
|
71
93
|
* Create a short-lived runtime dir: a short `sbx-` temp dir, keeping unix
|
|
72
94
|
* socket paths under the ~108-char limit.
|
package/src/secrets.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Secrets (M5): keys the agent never holds. The sandbox gets one random
|
|
2
|
+
// placeholder per secret; the proxy, outside it, swaps the real value into a
|
|
3
|
+
// request's headers only after the gate allowed it and only for a bound host.
|
|
4
|
+
// Pure: no I/O, no proxy state. Detect and apply are separate on purpose, so
|
|
5
|
+
// the real value is never in a request's headers while it waits for a decision.
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* One loaded secret.
|
|
10
|
+
*
|
|
11
|
+
* @typedef {object} Secret
|
|
12
|
+
* @property {string} name the variable name the sandbox sees the placeholder under
|
|
13
|
+
* @property {string} value the real value; never leaves the proxy except in an allowed request's header
|
|
14
|
+
* @property {string[]} hosts hostnames (no port) the real value may be sent to
|
|
15
|
+
* @property {string} placeholder `sbx-ph-<16 hex>`, fresh per call
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Request headers as node reads them: lowercase names, string or string[] values. @typedef {Record<string, string | string[] | undefined>} Headers */
|
|
19
|
+
|
|
20
|
+
const BASIC = /^(Basic\s+)([A-Za-z0-9+/=_-]+)$/i;
|
|
21
|
+
|
|
22
|
+
/** @param {string} h @returns {string} */
|
|
23
|
+
const bare = (h) => h.toLowerCase();
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Read the secrets from the config shape and give each a fresh placeholder.
|
|
27
|
+
*
|
|
28
|
+
* @param {Record<string, { fromEnv?: string, value?: string, hosts: string[] }>} [config] the config `secrets` object
|
|
29
|
+
* @param {NodeJS.ProcessEnv} [env] where `fromEnv` is read (default `process.env`)
|
|
30
|
+
* @returns {Secret[]} one entry per secret, new placeholders on every call (so per run)
|
|
31
|
+
* @throws {Error} naming the secret (never a value) when it has no value or no hosts
|
|
32
|
+
*/
|
|
33
|
+
export function loadSecrets(config = {}, env = process.env) {
|
|
34
|
+
return Object.entries(config).map(([name, c]) => {
|
|
35
|
+
const value = c.fromEnv !== undefined ? env[c.fromEnv] : c.value;
|
|
36
|
+
if (typeof value !== 'string' || !value) throw new Error(`secret ${name}: no value`);
|
|
37
|
+
if (!Array.isArray(c.hosts) || !c.hosts.length) throw new Error(`secret ${name}: hosts required`);
|
|
38
|
+
return { name, value, hosts: c.hosts.map(bare), placeholder: `sbx-ph-${crypto.randomBytes(8).toString('hex')}` };
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Does `v` hold the secret's placeholder, plainly or inside `Basic <base64>`?
|
|
44
|
+
* @param {string} v @param {Secret} s @returns {'plain'|'basic'|null}
|
|
45
|
+
*/
|
|
46
|
+
function kindIn(v, s) {
|
|
47
|
+
if (v.includes(s.placeholder)) return 'plain';
|
|
48
|
+
const m = BASIC.exec(v);
|
|
49
|
+
if (m && Buffer.from(m[2], 'base64').toString('latin1').includes(s.placeholder)) return 'basic';
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {string} v one header value @param {Secret} s @returns {string} `v` with the real value in place
|
|
55
|
+
*/
|
|
56
|
+
function swapIn(v, s) {
|
|
57
|
+
const kind = kindIn(v, s);
|
|
58
|
+
if (kind === 'plain') return v.split(s.placeholder).join(s.value);
|
|
59
|
+
if (kind === 'basic') {
|
|
60
|
+
const m = /** @type {RegExpExecArray} */ (BASIC.exec(v));
|
|
61
|
+
const dec = Buffer.from(m[2], 'base64').toString('latin1');
|
|
62
|
+
// latin1 keeps every byte; the value goes in as its UTF-8 bytes.
|
|
63
|
+
const real = Buffer.from(s.value, 'utf8').toString('latin1');
|
|
64
|
+
return m[1] + Buffer.from(dec.split(s.placeholder).join(real), 'latin1').toString('base64');
|
|
65
|
+
}
|
|
66
|
+
return v;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Which secrets' placeholders sit in a request URL (path and query). Keys are swapped in headers only.
|
|
71
|
+
* @param {string} pathAndQuery @param {Secret[]} secrets @returns {string[]} the secrets' names
|
|
72
|
+
*/
|
|
73
|
+
export function urlPlaceholders(pathAndQuery, secrets) {
|
|
74
|
+
return secrets.filter((s) => pathAndQuery.includes(s.placeholder)).map((s) => s.name);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Which placeholders a request carries, and whether each is headed for a host its secret is bound to.
|
|
79
|
+
* Each header value is searched as a substring and, for `Basic <base64>`, decoded.
|
|
80
|
+
*
|
|
81
|
+
* @param {Headers} headers the request headers
|
|
82
|
+
* @param {string} host the request's hostname (no port)
|
|
83
|
+
* @param {Secret[]} secrets from {@link loadSecrets}
|
|
84
|
+
* @returns {{ name: string, header: string, bound: boolean }[]} one entry per (secret, header)
|
|
85
|
+
*/
|
|
86
|
+
export function findPlaceholders(headers, host, secrets) {
|
|
87
|
+
const h = bare(host);
|
|
88
|
+
const found = [];
|
|
89
|
+
for (const [header, v] of Object.entries(headers)) {
|
|
90
|
+
const vals = Array.isArray(v) ? v : [v];
|
|
91
|
+
for (const s of secrets) {
|
|
92
|
+
if (vals.some((x) => typeof x === 'string' && kindIn(x, s))) {
|
|
93
|
+
found.push({ name: s.name, header, bound: s.hosts.includes(h) });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return found;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The headers with every bound placeholder replaced by its real value. A new
|
|
102
|
+
* object; the input (which the agent's request owns) is never changed.
|
|
103
|
+
* Placeholders of a secret not bound to `host` stay as they are.
|
|
104
|
+
*
|
|
105
|
+
* @param {Headers} headers the request headers
|
|
106
|
+
* @param {string} host the request's hostname (no port)
|
|
107
|
+
* @param {Secret[]} secrets from {@link loadSecrets}
|
|
108
|
+
* @returns {Headers} new headers
|
|
109
|
+
*/
|
|
110
|
+
export function applySecrets(headers, host, secrets) {
|
|
111
|
+
const h = bare(host);
|
|
112
|
+
const bound = secrets.filter((s) => s.hosts.includes(h));
|
|
113
|
+
/** @type {Headers} */
|
|
114
|
+
const out = {};
|
|
115
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
116
|
+
/** @param {string} x @returns {string} */
|
|
117
|
+
const one = (x) => bound.reduce((acc, s) => swapIn(acc, s), x);
|
|
118
|
+
out[k] = Array.isArray(v) ? v.map(one) : (typeof v === 'string' ? one(v) : v);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|