@namzu/sandbox 16.0.0 → 17.0.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 +238 -0
- package/README.md +164 -0
- package/dist/backends/aci-standby-pool/index.d.ts +22 -4
- package/dist/backends/aci-standby-pool/index.d.ts.map +1 -1
- package/dist/backends/aci-standby-pool/index.js +31 -7
- package/dist/backends/aci-standby-pool/index.js.map +1 -1
- package/dist/backends/docker/index.d.ts +243 -24
- package/dist/backends/docker/index.d.ts.map +1 -1
- package/dist/backends/docker/index.js +717 -108
- package/dist/backends/docker/index.js.map +1 -1
- package/dist/backends/firecracker/transport.d.ts +156 -1
- package/dist/backends/firecracker/transport.d.ts.map +1 -1
- package/dist/backends/firecracker/transport.js +223 -29
- package/dist/backends/firecracker/transport.js.map +1 -1
- package/dist/backends/http-worker-client.d.ts +64 -2
- package/dist/backends/http-worker-client.d.ts.map +1 -1
- package/dist/backends/http-worker-client.js +78 -7
- package/dist/backends/http-worker-client.js.map +1 -1
- package/dist/backends/kubernetes/transport.d.ts +7 -0
- package/dist/backends/kubernetes/transport.d.ts.map +1 -1
- package/dist/backends/kubernetes/transport.js.map +1 -1
- package/dist/egress/proxy.d.ts +47 -2
- package/dist/egress/proxy.d.ts.map +1 -1
- package/dist/egress/proxy.js +31 -7
- package/dist/egress/proxy.js.map +1 -1
- package/dist/index.d.ts +67 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/backends/aci-standby-pool/index.ts +37 -7
- package/src/backends/docker/index.ts +909 -126
- package/src/backends/firecracker/transport.ts +387 -36
- package/src/backends/http-worker-client.ts +89 -5
- package/src/backends/kubernetes/transport.ts +7 -0
- package/src/egress/proxy.ts +65 -8
- package/src/index.ts +89 -0
|
@@ -14,17 +14,37 @@
|
|
|
14
14
|
* Trust model:
|
|
15
15
|
* - Container is the trust boundary; everything inside is treated
|
|
16
16
|
* as untrusted code.
|
|
17
|
-
* -
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
17
|
+
* - Every call to the worker's control API carries the per-instance
|
|
18
|
+
* `NAMZU_SANDBOX_TOKEN` this backend mints at create time and
|
|
19
|
+
* injects into the container's environment; a worker the host did
|
|
20
|
+
* not create must be provisioned with its own. The worker requires
|
|
21
|
+
* it on every route but `/healthz`, and refuses to start at all if
|
|
22
|
+
* it has none and is bound to anything routable.
|
|
23
|
+
* - Outbound network from the worker is restricted by the network
|
|
24
|
+
* it is attached to (see {@link DockerBackendConfig.network}) and,
|
|
25
|
+
* for a host allowlist, by an egress proxy running as a sibling
|
|
26
|
+
* container on that same network — the only way its traffic reaches
|
|
27
|
+
* the internet, because the network is `--internal` and has no route
|
|
28
|
+
* off it. The proxy is a container on that subnet like any other, so
|
|
29
|
+
* it is not the sandbox's only reachable destination. The proxy
|
|
30
|
+
* environment the sandbox is given directs traffic; the topology is
|
|
31
|
+
* what confines it. See {@link assertNetworkCarriesThePolicy} and
|
|
32
|
+
* #398.
|
|
33
|
+
*
|
|
34
|
+
* The credential above is what a previous version of this docblock
|
|
35
|
+
* claimed network placement alone provided. It said the worker "only
|
|
36
|
+
* listens on loopback inside its own netns", which is false — the worker
|
|
37
|
+
* binds every interface by default and has to, because a published
|
|
38
|
+
* container port forwards to the container's interface address rather
|
|
39
|
+
* than to its loopback, so a loopback-bound worker is unreachable through
|
|
40
|
+
* the port this backend publishes. The boundary was the network the
|
|
41
|
+
* container is attached to, and wanted a credential behind it.
|
|
22
42
|
*/
|
|
23
43
|
import { spawn } from 'node:child_process';
|
|
44
|
+
import { randomBytes } from 'node:crypto';
|
|
24
45
|
import { SANDBOX_DEFAULT_OUTPUTS_PATH, SANDBOX_DEFAULT_SCRATCH_PATH, SANDBOX_DEFAULT_SKILLS_PARENT, SANDBOX_DEFAULT_TOOL_RESULTS_PATH, SANDBOX_DEFAULT_TRANSCRIPTS_PATH, SANDBOX_DEFAULT_UPLOADS_PATH, generateSandboxId, walkFilesViaExec, withHint, } from '@namzu/sdk';
|
|
25
|
-
import { EgressProxy } from '../../egress/index.js';
|
|
26
46
|
import { ContainerSandboxLayoutValidationError, } from '../../index.js';
|
|
27
|
-
import { HttpWorkerClient } from '../http-worker-client.js';
|
|
47
|
+
import { HttpWorkerClient, WORKER_UNAUTHORIZED_HINT, workerAuthorization, } from '../http-worker-client.js';
|
|
28
48
|
import { OperationDeadline, OperationDeadlineExpired, probeHttpHealth, resolveReadinessOptions, runFailureCleanup, } from '../readiness.js';
|
|
29
49
|
import { RemoteCancellationUnknownError, RemoteProtocolError, } from '../remote-execution-controller.js';
|
|
30
50
|
const DEFAULT_DOCKER_BINARY = 'docker';
|
|
@@ -72,6 +92,14 @@ export function buildDockerBackend(config) {
|
|
|
72
92
|
* just the way out. It now keeps the configured network, and
|
|
73
93
|
* {@link assertNetworkCarriesThePolicy} is what makes that network a
|
|
74
94
|
* boundary.
|
|
95
|
+
*
|
|
96
|
+
* Every policy that returns the configured network depends on that same
|
|
97
|
+
* assertion, which is why the two live side by side: this function says which
|
|
98
|
+
* network the container joins, and that one refuses the network if it cannot
|
|
99
|
+
* do what the policy asks of it (#398). An allowlist used to answer the
|
|
100
|
+
* configured network and get a proxy environment variable pointed at a
|
|
101
|
+
* host-side listener — enforcement by convention, which an uncooperative
|
|
102
|
+
* process simply ignores.
|
|
75
103
|
*/
|
|
76
104
|
export function resolveNetwork(configured, egress, hasProxy = false) {
|
|
77
105
|
if (!egress)
|
|
@@ -88,7 +116,7 @@ export function resolveNetwork(configured, egress, hasProxy = false) {
|
|
|
88
116
|
// reporting that it had been restricted.
|
|
89
117
|
if (hasProxy)
|
|
90
118
|
return configured;
|
|
91
|
-
throw new Error(`The docker sandbox backend cannot enforce an egress policy of kind '${egress.kind}' without an egress proxy: it has nothing to filter hosts through.
|
|
119
|
+
throw new Error(`The docker sandbox backend cannot enforce an egress policy of kind '${egress.kind}' without an egress proxy: it has nothing to filter hosts through. Name the image it should run the proxy as (egressProxyImage — see packages/sandbox/egress-proxy/Dockerfile), or use 'deny-all' / 'allow-all'. Refusing rather than silently granting full network access.`);
|
|
92
120
|
}
|
|
93
121
|
}
|
|
94
122
|
/**
|
|
@@ -125,9 +153,9 @@ export function isInternalNetwork(inspectedInternalFlag) {
|
|
|
125
153
|
/**
|
|
126
154
|
* Refuse a container whose network cannot do what was asked of it.
|
|
127
155
|
*
|
|
128
|
-
*
|
|
129
|
-
* unstated — which is how the backend came to ship a default
|
|
130
|
-
* that could not create a sandbox at all:
|
|
156
|
+
* Three requirements meet on the same object here, and the first two were
|
|
157
|
+
* previously unstated — which is how the backend came to ship a default
|
|
158
|
+
* configuration that could not create a sandbox at all:
|
|
131
159
|
*
|
|
132
160
|
* - **A published host port needs a route out.** Docker binds the port by
|
|
133
161
|
* NAT to the container's address, so a container with no address gets no
|
|
@@ -143,12 +171,31 @@ export function isInternalNetwork(inspectedInternalFlag) {
|
|
|
143
171
|
* nothing. `deny-all` pointed at the default bridge would be full egress
|
|
144
172
|
* under a policy object claiming none — the "accepted and silently
|
|
145
173
|
* ignored" failure the rest of this file exists to refuse.
|
|
174
|
+
* - **A host allowlist needs one too, for the same reason and with one
|
|
175
|
+
* addition.** Until #398 the allowlist tier answered the configured
|
|
176
|
+
* network and pointed the sandbox at a proxy running on the host's
|
|
177
|
+
* loopback, and the only thing making traffic go through it was
|
|
178
|
+
* `HTTP_PROXY`. That is a request, not a boundary: anything inside the
|
|
179
|
+
* container that opens a socket directly reaches the network with the
|
|
180
|
+
* allowlist unconsulted, and untrusted code is the caller least likely to
|
|
181
|
+
* honour a convention. With the proxy as a sibling container on an
|
|
182
|
+
* `--internal` network, the only way the sandbox's traffic reaches the
|
|
183
|
+
* internet is that container, and it cannot change that because
|
|
184
|
+
* `--cap-drop=ALL` took `NET_ADMIN` away (see {@link HARDENING_ARGS}). The
|
|
185
|
+
* environment variables stay and now DIRECT traffic rather than permit it.
|
|
186
|
+
* On a network that is not internal there is no such route to remove, and
|
|
187
|
+
* the policy is back to being advisory — which is what this refuses.
|
|
146
188
|
*
|
|
147
|
-
*
|
|
148
|
-
* impossible rather than merely unsupported: no arrangement of docker
|
|
189
|
+
* The first two are exact opposites, so `deny-all` over a published host port
|
|
190
|
+
* is impossible rather than merely unsupported: no arrangement of docker
|
|
149
191
|
* networking both denies all egress and lets the host reach the worker over
|
|
150
|
-
* TCP. Closing that needs the control channel moved off TCP — see #398 —
|
|
151
|
-
*
|
|
192
|
+
* TCP. Closing that needs the control channel moved off TCP — see #398 — and
|
|
193
|
+
* is not a flag this function could accept. The same opposition now reaches
|
|
194
|
+
* an allowlist policy, which is new: an allowlist on an internal network must
|
|
195
|
+
* be reached by container name, so a host that used a published port with a
|
|
196
|
+
* host allowlist has to move that consumer onto the internal network. That is
|
|
197
|
+
* a consequence of the boundary existing at all and not a gap in this
|
|
198
|
+
* function; the refusal below names the mode to move to.
|
|
152
199
|
*/
|
|
153
200
|
export function assertNetworkCarriesThePolicy(network, reachability, egress, inspectedInternalFlag) {
|
|
154
201
|
const internal = isInternalNetwork(inspectedInternalFlag);
|
|
@@ -158,26 +205,154 @@ export function assertNetworkCarriesThePolicy(network, reachability, egress, ins
|
|
|
158
205
|
if (egress?.kind === 'deny-all' && !internal) {
|
|
159
206
|
throw new Error(`The docker sandbox backend was asked for an egress policy of 'deny-all' on network '${network}', but that network is not internal, so the container can still reach the world. Create it with 'docker network create --internal ${network}' — an internal bridge denies egress in the kernel, rather than through an environment variable a workload may decline to read, while sibling containers still reach the worker by name. Refusing rather than reporting a boundary that is not there.`);
|
|
160
207
|
}
|
|
208
|
+
if (needsEgressProxy(egress) && !internal) {
|
|
209
|
+
throw new Error(`The docker sandbox backend was asked for an egress policy of kind '${egress?.kind}' on network '${network}', but that network is not internal, so nothing stops the container from reaching the world directly and the allowlist would only be a proxy environment variable a workload may decline to read. Create the network with 'docker network create --internal ${network}': the sandbox then reaches the internet only through the egress proxy container, which is the boundary — and set hostReachability: 'container-network' to reach the worker by name on it, since a published host port needs a route out this network does not have. Refusing rather than reporting a boundary that is not there.`);
|
|
210
|
+
}
|
|
161
211
|
}
|
|
162
212
|
/**
|
|
163
|
-
*
|
|
213
|
+
* Build the proxy container's configuration.
|
|
164
214
|
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
215
|
+
* `allowedHosts` is already resolved here rather than passed as a policy, and
|
|
216
|
+
* that is the one behavioural difference this change carries into the
|
|
217
|
+
* boundary: the in-process proxy called the host's resolver per request, and
|
|
218
|
+
* the container cannot. A `resolver` policy that rotates is honoured at
|
|
219
|
+
* `create()` and again at every `setNetworkPolicy()` — the container has no
|
|
220
|
+
* channel back to the host's resolver, and a channel the container CAN reach
|
|
221
|
+
* is one the sandbox can reach too, which would let the sandbox ask for its
|
|
222
|
+
* own allowlist to be widened. See `docs/sdk/sandbox-egress.md`.
|
|
170
223
|
*/
|
|
171
|
-
export function
|
|
224
|
+
export function egressProxyContainerConfig(config, allowedHosts, port) {
|
|
172
225
|
return {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
// on a live sandbox.
|
|
176
|
-
allowedHosts: () => resolveAllowedHosts(policy),
|
|
226
|
+
port,
|
|
227
|
+
allowedHosts,
|
|
177
228
|
credentials: config.brokeredCredentials ?? [],
|
|
178
229
|
...(config.allowInwardFor ? { allowInwardFor: config.allowInwardFor } : {}),
|
|
230
|
+
selfNames: [PROXY_HOST_ALIAS],
|
|
179
231
|
};
|
|
180
232
|
}
|
|
233
|
+
/**
|
|
234
|
+
* `--label key=value` flags, validated before they reach the daemon.
|
|
235
|
+
*
|
|
236
|
+
* An empty key or one containing `=` would silently produce a malformed label
|
|
237
|
+
* that a downstream `docker ps --filter label=…` could not match, so misuse
|
|
238
|
+
* surfaces during construction rather than as a container that mysteriously
|
|
239
|
+
* has no labels.
|
|
240
|
+
*/
|
|
241
|
+
function renderLabelArgs(labels) {
|
|
242
|
+
const args = [];
|
|
243
|
+
if (!labels)
|
|
244
|
+
return args;
|
|
245
|
+
for (const [key, value] of Object.entries(labels)) {
|
|
246
|
+
if (!key || key.includes('=')) {
|
|
247
|
+
throw new Error(`docker label key ${JSON.stringify(key)} is invalid (empty or contains '=')`);
|
|
248
|
+
}
|
|
249
|
+
args.push('--label', `${key}=${value}`);
|
|
250
|
+
}
|
|
251
|
+
return args;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Name the proxy container reads its configuration from.
|
|
255
|
+
*
|
|
256
|
+
* The NAME travels in the argv and the VALUE travels in the `docker` CLI
|
|
257
|
+
* child's environment, which is why this is one constant used by both ends of
|
|
258
|
+
* that pair rather than a literal written twice.
|
|
259
|
+
*/
|
|
260
|
+
const EGRESS_PROXY_CONFIG_ENV = 'NAMZU_EGRESS_PROXY_CONFIG';
|
|
261
|
+
/**
|
|
262
|
+
* The `docker run` argv for the egress proxy container, as a value.
|
|
263
|
+
*
|
|
264
|
+
* Extracted for the reason every other argv in this file is: nothing
|
|
265
|
+
* downstream of it can run without a docker daemon, so a flag that never
|
|
266
|
+
* reached it — or a `--network` that named the wrong side of a dual-homed
|
|
267
|
+
* container — could only be caught by an operator in production, where the
|
|
268
|
+
* symptom is a sandbox that reaches nothing.
|
|
269
|
+
*
|
|
270
|
+
* The two networks are the whole topology and they are two calls:
|
|
271
|
+
* `docker run --network <upstream>` gives the container a default route, and
|
|
272
|
+
* {@link renderEgressProxyAttachArgs}'s `docker network connect` adds the
|
|
273
|
+
* internal network afterwards. The order is load-bearing. Attached to the
|
|
274
|
+
* internal network FIRST it would come up with no default route and no way to
|
|
275
|
+
* acquire one, and the proxy would be a boundary in front of nothing.
|
|
276
|
+
*
|
|
277
|
+
* The hardening baseline is the sandbox's, minus the parts that describe a
|
|
278
|
+
* filesystem. `--cap-drop=ALL`, `--no-new-privileges` and `--ipc private` are
|
|
279
|
+
* applied exactly as {@link HARDENING_ARGS} defines them, because this
|
|
280
|
+
* container sits between untrusted code and the internet and is the last one in
|
|
281
|
+
* the deployment that should be holding a capability. `--read-only` is the
|
|
282
|
+
* sandbox's too, with one tmpfs: the proxy writes nothing, and the tmpfs is
|
|
283
|
+
* there so that a Node process which one day wants a temp file fails at a
|
|
284
|
+
* filesystem boundary rather than at a mysterious `EROFS`.
|
|
285
|
+
*
|
|
286
|
+
* The image is last, so nothing after it is read as a flag — the same rule the
|
|
287
|
+
* sandbox argv follows, and here it also means the image's own `CMD` starts the
|
|
288
|
+
* proxy rather than this argv naming an entrypoint.
|
|
289
|
+
*/
|
|
290
|
+
export function renderEgressProxyRunArgs(input) {
|
|
291
|
+
const { config, containerName, upstreamNetwork, internalNetwork } = input;
|
|
292
|
+
if (!config.egressProxyImage) {
|
|
293
|
+
throw new Error('renderEgressProxyRunArgs was called without config.egressProxyImage; the docker backend cannot start an egress proxy container it has no image for. resolveNetwork refuses an allowlist policy in this state, so reaching here means the refusal was bypassed.');
|
|
294
|
+
}
|
|
295
|
+
if (upstreamNetwork === 'none') {
|
|
296
|
+
throw new Error(`egressProxyUpstreamNetwork is 'none', which would give the proxy container no interface and no route: it would come up unable to reach anything, and the only way the sandbox's traffic reaches the internet would be a boundary that cannot reach it itself. Name a bridge, or drop the field to take the 'bridge' default.`);
|
|
297
|
+
}
|
|
298
|
+
if (upstreamNetwork === internalNetwork) {
|
|
299
|
+
throw new Error(`egressProxyUpstreamNetwork names '${upstreamNetwork}', which is the same network the sandbox is on — the internal one. A container whose primary network is internal comes up with no default route and never acquires one, so the proxy would start with no way to reach the internet: the boundary would be a container that can only talk to the sandbox. Name a different network for egressProxyUpstreamNetwork, or drop the field to take the 'bridge' default.`);
|
|
300
|
+
}
|
|
301
|
+
return [
|
|
302
|
+
'run',
|
|
303
|
+
'--detach',
|
|
304
|
+
'--rm',
|
|
305
|
+
'--name',
|
|
306
|
+
containerName,
|
|
307
|
+
// The name the sandbox dials, and the name the proxy's own loop guard
|
|
308
|
+
// has to recognise as itself. Set as the container's hostname so the
|
|
309
|
+
// entrypoint can read it back with `os.hostname()` instead of holding a
|
|
310
|
+
// second copy of the constant.
|
|
311
|
+
'--hostname',
|
|
312
|
+
PROXY_HOST_ALIAS,
|
|
313
|
+
'--network',
|
|
314
|
+
upstreamNetwork,
|
|
315
|
+
...HARDENING_ARGS,
|
|
316
|
+
'--read-only',
|
|
317
|
+
'--tmpfs',
|
|
318
|
+
`/tmp:${TMPFS_MOUNT_OPTIONS}`,
|
|
319
|
+
...renderLabelArgs(config.labels),
|
|
320
|
+
// The NAME only: docker takes the value from the environment of the
|
|
321
|
+
// `docker` CLI process it names, which the caller sets (see
|
|
322
|
+
// `startEgressProxyContainer`). The value is the whole policy —
|
|
323
|
+
// including brokered credential values — and an argv is a worse place
|
|
324
|
+
// for it than an environment on every platform that has a process
|
|
325
|
+
// table: `/proc/<pid>/cmdline` is world-readable on Linux, so putting
|
|
326
|
+
// it here published it to every local user on the docker host for as
|
|
327
|
+
// long as the client ran, where the child's own environment is readable
|
|
328
|
+
// only by the user that owns the process. It is still readable by
|
|
329
|
+
// anything with access to the daemon, through `docker inspect`, and
|
|
330
|
+
// `docs/sdk/sandbox-egress.md` says so.
|
|
331
|
+
'--env',
|
|
332
|
+
EGRESS_PROXY_CONFIG_ENV,
|
|
333
|
+
config.egressProxyImage,
|
|
334
|
+
];
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* The `docker network connect` argv that makes the proxy dual-homed.
|
|
338
|
+
*
|
|
339
|
+
* `--alias` is what puts `namzu-egress` in the internal network's DNS, which
|
|
340
|
+
* is the name {@link buildDockerRunArgs} hands the sandbox in its proxy
|
|
341
|
+
* environment. The alias rather than the container name because the alias is
|
|
342
|
+
* the constant: a container named `namzu-egress-<sandbox-id>` would otherwise
|
|
343
|
+
* make the sandbox's `HTTP_PROXY` value depend on a generated id, and the two
|
|
344
|
+
* would have to be kept in step by hand.
|
|
345
|
+
*/
|
|
346
|
+
export function renderEgressProxyAttachArgs(input) {
|
|
347
|
+
return [
|
|
348
|
+
'network',
|
|
349
|
+
'connect',
|
|
350
|
+
'--alias',
|
|
351
|
+
PROXY_HOST_ALIAS,
|
|
352
|
+
input.internalNetwork,
|
|
353
|
+
input.containerName,
|
|
354
|
+
];
|
|
355
|
+
}
|
|
181
356
|
/**
|
|
182
357
|
* Confinement flags applied to every container.
|
|
183
358
|
*
|
|
@@ -291,8 +466,32 @@ const HARDENING_ARGS = [
|
|
|
291
466
|
'--ipc',
|
|
292
467
|
'private',
|
|
293
468
|
];
|
|
294
|
-
/**
|
|
469
|
+
/**
|
|
470
|
+
* Name the sandbox reaches the egress proxy by.
|
|
471
|
+
*
|
|
472
|
+
* This used to be a `--add-host namzu-egress:host-gateway` entry, because the
|
|
473
|
+
* proxy ran on the host's loopback and `host-gateway` is docker's portable
|
|
474
|
+
* name for the host from inside a container. It is now the proxy's own
|
|
475
|
+
* container name and network alias on the internal network, which needs no
|
|
476
|
+
* alias file at all: docker's embedded DNS resolves a container's aliases for
|
|
477
|
+
* every container on the same user-defined network. The constant survives the
|
|
478
|
+
* mechanism because what the sandbox is told has not changed — only what makes
|
|
479
|
+
* the name resolve, and whether anything else can be reached.
|
|
480
|
+
*/
|
|
295
481
|
const PROXY_HOST_ALIAS = 'namzu-egress';
|
|
482
|
+
/**
|
|
483
|
+
* Port the egress proxy listens on inside its own container.
|
|
484
|
+
*
|
|
485
|
+
* A fixed port rather than one the host reads back, because there is no host
|
|
486
|
+
* port involved: the sandbox dials the proxy container directly on the network
|
|
487
|
+
* they share. The old arrangement had to read a published port back out of
|
|
488
|
+
* `docker inspect`, with the race and the failure mode that came with it.
|
|
489
|
+
*/
|
|
490
|
+
const EGRESS_PROXY_PORT_INSIDE_CONTAINER = 2025;
|
|
491
|
+
/** Name of the sibling container the egress proxy runs in, for one sandbox. */
|
|
492
|
+
function egressProxyContainerName(sandboxId) {
|
|
493
|
+
return `${PROXY_HOST_ALIAS}-${sandboxId}`;
|
|
494
|
+
}
|
|
296
495
|
/**
|
|
297
496
|
* Mount options for every scratch mount this backend creates.
|
|
298
497
|
*
|
|
@@ -567,7 +766,7 @@ export function renderHardeningArgs(config) {
|
|
|
567
766
|
* The complete `docker run` argv, as a value.
|
|
568
767
|
*
|
|
569
768
|
* Extracted for the same reason {@link resolveNetwork} and
|
|
570
|
-
* {@link
|
|
769
|
+
* {@link egressProxyContainerConfig} were: everything downstream of it needs a running
|
|
571
770
|
* Docker daemon, so a confinement flag that never reached the argv — or one
|
|
572
771
|
* that reached it in an order that cancels another — could only be caught by an
|
|
573
772
|
* operator noticing its effect missing in production. Spawning a fake `docker`
|
|
@@ -599,20 +798,7 @@ export function buildDockerRunArgs(input) {
|
|
|
599
798
|
if (config.runAsUser) {
|
|
600
799
|
args.push('--user', config.runAsUser);
|
|
601
800
|
}
|
|
602
|
-
|
|
603
|
-
// a key containing `=` would silently produce a malformed
|
|
604
|
-
// label that downstream `docker ps --filter label=…` queries
|
|
605
|
-
// could not match reliably. Throw before the spawn so misuse
|
|
606
|
-
// surfaces during construction, not as a mysterious "container
|
|
607
|
-
// has no labels" later.
|
|
608
|
-
if (config.labels) {
|
|
609
|
-
for (const [key, value] of Object.entries(config.labels)) {
|
|
610
|
-
if (!key || key.includes('=')) {
|
|
611
|
-
throw new Error(`docker label key ${JSON.stringify(key)} is invalid (empty or contains '=')`);
|
|
612
|
-
}
|
|
613
|
-
args.push('--label', `${key}=${value}`);
|
|
614
|
-
}
|
|
615
|
-
}
|
|
801
|
+
args.push(...renderLabelArgs(config.labels));
|
|
616
802
|
args.push(...renderLayoutMountArgs(layout));
|
|
617
803
|
// Forward only the workspace root so the worker's lexical
|
|
618
804
|
// resolver agrees with the bind target. The full layout used
|
|
@@ -622,15 +808,27 @@ export function buildDockerRunArgs(input) {
|
|
|
622
808
|
// write it to a bind path the worker reads at startup —
|
|
623
809
|
// avoids env-size limits, keeps the wire shape minimal.
|
|
624
810
|
if (egressProxyPort !== undefined) {
|
|
625
|
-
// `host-gateway
|
|
626
|
-
//
|
|
627
|
-
//
|
|
628
|
-
//
|
|
629
|
-
|
|
811
|
+
// No `--add-host`, and no `host-gateway`. The proxy is a container on
|
|
812
|
+
// this container's own internal network and `PROXY_HOST_ALIAS` is its
|
|
813
|
+
// network alias there (see {@link renderEgressProxyAttachArgs}), which
|
|
814
|
+
// docker's embedded DNS resolves with no alias file involved. The alias
|
|
815
|
+
// entry this replaced pointed at the host's loopback, where the proxy
|
|
816
|
+
// used to run — and a name resolving to a host that is not on this
|
|
817
|
+
// network is exactly the route this change removes.
|
|
630
818
|
const proxyUrl = `http://${PROXY_HOST_ALIAS}:${egressProxyPort}`;
|
|
631
|
-
// Both spellings: tooling is split between them, and a workload
|
|
632
|
-
//
|
|
633
|
-
//
|
|
819
|
+
// Both spellings: tooling is split between them, and a workload that
|
|
820
|
+
// reads only the one that is missing loses the redirection.
|
|
821
|
+
//
|
|
822
|
+
// **These are convenience, not the boundary, and that is the point of
|
|
823
|
+
// the arrangement.** A tool that honours them sends its requests to the
|
|
824
|
+
// proxy; a tool that ignores them — a Go or Rust binary that does not
|
|
825
|
+
// read proxy env, `curl --noproxy '*'`, a raw socket — has nowhere to
|
|
826
|
+
// send anything. This container is on an `--internal` network with no
|
|
827
|
+
// default route, and the only host on it is the proxy, so the
|
|
828
|
+
// uncooperative path fails with `Network unreachable` rather than
|
|
829
|
+
// bypassing the allowlist. What makes that true is
|
|
830
|
+
// {@link assertNetworkCarriesThePolicy} refusing a network that is not
|
|
831
|
+
// internal, not this block of environment.
|
|
634
832
|
for (const key of ['HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy']) {
|
|
635
833
|
args.push('--env', `${key}=${proxyUrl}`);
|
|
636
834
|
}
|
|
@@ -679,6 +877,24 @@ export function buildDockerRunArgs(input) {
|
|
|
679
877
|
for (const [key, value] of Object.entries(options.env ?? {})) {
|
|
680
878
|
args.push('--env', `${key}=${value}`);
|
|
681
879
|
}
|
|
880
|
+
// The worker's credential, rendered VALUELESS and last among the `--env`
|
|
881
|
+
// flags.
|
|
882
|
+
//
|
|
883
|
+
// Valueless, because `docker run --env NAME` reads the value out of the
|
|
884
|
+
// docker CLI's own environment — which `runOnce` is handed — and an argv
|
|
885
|
+
// is the wrong place for a secret: `ps` shows it to every user on the
|
|
886
|
+
// host for as long as the CLI lives, and a non-zero run puts the whole
|
|
887
|
+
// argv into the error this backend throws. The CLI environment is
|
|
888
|
+
// readable only by the same user and root, and the message is redacted
|
|
889
|
+
// besides.
|
|
890
|
+
//
|
|
891
|
+
// Last, because docker applies repeated `--env` flags in order and the
|
|
892
|
+
// last one wins: a host that separately sets `NAMZU_SANDBOX_TOKEN` in
|
|
893
|
+
// `options.env` — a copied example, an inherited environment — must not
|
|
894
|
+
// be able to displace the value its own client is sending, which would
|
|
895
|
+
// produce a container that rejects every call and reads as a broken
|
|
896
|
+
// worker rather than as a duplicated setting.
|
|
897
|
+
args.push('--env', 'NAMZU_SANDBOX_TOKEN');
|
|
682
898
|
args.push(config.image);
|
|
683
899
|
return args;
|
|
684
900
|
}
|
|
@@ -687,41 +903,53 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
687
903
|
const resolvedLayout = config.layout;
|
|
688
904
|
const id = generateSandboxId();
|
|
689
905
|
const docker = config.dockerBinary ?? DEFAULT_DOCKER_BINARY;
|
|
690
|
-
// The
|
|
691
|
-
//
|
|
692
|
-
//
|
|
693
|
-
//
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
906
|
+
// The worker's per-instance credential, minted HERE — per `create()`, not
|
|
907
|
+
// per process and never per image. Three properties are the point, and
|
|
908
|
+
// each one rules out a cheaper shape:
|
|
909
|
+
//
|
|
910
|
+
// - Per instance. A token baked into the image is shared by every
|
|
911
|
+
// container ever built from it and readable by anything that can pull
|
|
912
|
+
// it, which is a worse artifact than a documented absence: it looks
|
|
913
|
+
// like a credential while separating nobody.
|
|
914
|
+
// - Not in an argv, and not in any message. It rides in the docker CLI
|
|
915
|
+
// child's environment, which `runOnce` is handed, and the CLI resolves
|
|
916
|
+
// it there for the valueless `--env NAMZU_SANDBOX_TOKEN`; a non-zero
|
|
917
|
+
// `docker run` renders its argv with every `--env` value redacted. So
|
|
918
|
+
// `ps` on the host does not show it and the error this backend throws
|
|
919
|
+
// does not carry it — neither of which was true when the value was
|
|
920
|
+
// rendered into the argv.
|
|
921
|
+
// - Where it IS visible, said plainly: the container's own config, so
|
|
922
|
+
// `docker inspect <name>` shows it for the container's life, to anyone
|
|
923
|
+
// who can already talk to the daemon — the same authority that can
|
|
924
|
+
// `docker exec` into the sandbox. And the worker's own `/proc` inside
|
|
925
|
+
// the container, to a workload that shares its uid. Both are why it is
|
|
926
|
+
// per-instance and dies with the container rather than being shared or
|
|
927
|
+
// long-lived.
|
|
928
|
+
// - Dead with the container. Nothing revokes it, because the only process
|
|
929
|
+
// that would accept it is removed with the sandbox, and the container's
|
|
930
|
+
// config that still holds it is removed with it.
|
|
931
|
+
//
|
|
932
|
+
// 32 bytes rather than a uuid: this is a secret, not an identifier, and
|
|
933
|
+
// base64url keeps it one argv-free environment value on every platform.
|
|
934
|
+
const workerToken = randomBytes(32).toString('base64url');
|
|
706
935
|
const hostReachability = config.hostReachability ?? 'host-port';
|
|
707
|
-
|
|
936
|
+
// Whether a proxy CONTAINER will run, which is what `resolveNetwork` turns
|
|
937
|
+
// on: an allowlist policy needs the image to run one as, and without it
|
|
938
|
+
// there is no boundary to hand traffic to. The refusal lives in
|
|
939
|
+
// `resolveNetwork` so that every caller of it gets the same answer, and it
|
|
940
|
+
// fires before anything is started.
|
|
941
|
+
const proxyPlanned = needsEgressProxy(options.egress) && config.egressProxyImage !== undefined;
|
|
942
|
+
const network = resolveNetwork(config.network ?? 'none', options.egress, proxyPlanned);
|
|
708
943
|
// Whether this network can carry the reachability mode and the policy is
|
|
709
944
|
// a fact about the network, so it is checked against the daemon rather
|
|
710
|
-
// than inferred from its name. Before
|
|
945
|
+
// than inferred from its name. Before anything starts on purpose: a
|
|
711
946
|
// refusal here is a wiring mistake and must not arrive dressed as a
|
|
712
947
|
// container that failed to come up, which is exactly how it used to
|
|
713
948
|
// arrive.
|
|
714
|
-
|
|
715
|
-
assertNetworkCarriesThePolicy(network, hostReachability, options.egress, await inspectNetworkInternalFlag(docker, network, options.signal));
|
|
716
|
-
}
|
|
717
|
-
catch (err) {
|
|
718
|
-
// The allowlist kinds start a proxy above, and this is outside the
|
|
719
|
-
// try/catch that owns teardown — so without this the refusal would
|
|
720
|
-
// leave a listening server on loopback stamping real credentials.
|
|
721
|
-
await egressProxy?.close().catch(() => undefined);
|
|
722
|
-
throw err;
|
|
723
|
-
}
|
|
949
|
+
assertNetworkCarriesThePolicy(network, hostReachability, options.egress, await inspectNetworkInternalFlag(docker, network, options.signal));
|
|
724
950
|
const containerName = `namzu-sandbox-${id}`;
|
|
951
|
+
/** The proxy container's name, once it is being started. */
|
|
952
|
+
let egressProxyContainer;
|
|
725
953
|
// All bind sources come from the consumer-supplied layout. The
|
|
726
954
|
// backend never allocates host directories and never removes them
|
|
727
955
|
// — that pre-existing single-mount mkdtemp path was the source of
|
|
@@ -735,20 +963,31 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
735
963
|
// reconciliation; an external daemon that commits after this delete still
|
|
736
964
|
// needs its ordinary label/name reaper.
|
|
737
965
|
const removeContainer = runOnceQuiet(docker, ['rm', '-f', containerName], signal);
|
|
738
|
-
// The proxy starts BEFORE the
|
|
739
|
-
// in `destroy()`, which a create that never returned can
|
|
740
|
-
// reach. So every failure between the two — a daemon that is
|
|
741
|
-
// port that could not be read, a worker that missed its
|
|
742
|
-
// deadline,
|
|
743
|
-
//
|
|
744
|
-
//
|
|
745
|
-
//
|
|
746
|
-
//
|
|
747
|
-
//
|
|
748
|
-
//
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
966
|
+
// The proxy container starts BEFORE the sandbox and its only other
|
|
967
|
+
// teardown is in `destroy()`, which a create that never returned can
|
|
968
|
+
// never reach. So every failure between the two — a daemon that is
|
|
969
|
+
// down, a port that could not be read, a worker that missed its
|
|
970
|
+
// readiness deadline, an abort — would leave a container holding real
|
|
971
|
+
// credentials and a live route to the internet, and a retry loop left
|
|
972
|
+
// one per attempt. That is the invariant this file states where the
|
|
973
|
+
// proxy is started: it must not outlive the thing it was filtering
|
|
974
|
+
// for. Start both arms before awaiting either: a stuck runtime must
|
|
975
|
+
// not keep the credential-bearing one alive.
|
|
976
|
+
//
|
|
977
|
+
// The proxy arm is the reconciler rather than a `runOnceQuiet` on this
|
|
978
|
+
// signal, and the difference is the grace this function's caller runs
|
|
979
|
+
// under: `runFailureCleanup` spends ONE SECOND on both arms together,
|
|
980
|
+
// so a daemon that is slow to answer rather than down would have its
|
|
981
|
+
// `docker rm -f` killed at that boundary — the credential-bearing
|
|
982
|
+
// container outliving the sandbox by exactly the failure this exists to
|
|
983
|
+
// prevent. The reconciler carries its own deadline, is not reachable by
|
|
984
|
+
// any abort, and is not waited on by the caller's grace either: it
|
|
985
|
+
// finishes whether or not this function is still listening.
|
|
986
|
+
const removeProxy = egressProxyContainer === undefined
|
|
987
|
+
? Promise.resolve()
|
|
988
|
+
: removeEgressProxyContainer(docker, egressProxyContainer);
|
|
989
|
+
egressProxyContainer = undefined;
|
|
990
|
+
await Promise.all([removeContainer, removeProxy]);
|
|
752
991
|
}
|
|
753
992
|
let hostPort;
|
|
754
993
|
let baseUrl;
|
|
@@ -756,15 +995,51 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
756
995
|
// always available — the worker uses it as its workspace root.
|
|
757
996
|
const rootDir = resolvedLayout.outputs.containerPath;
|
|
758
997
|
try {
|
|
998
|
+
// The boundary a host allowlist is actually enforced at, as a sibling
|
|
999
|
+
// container on this container's network (#398). Started before the
|
|
1000
|
+
// sandbox so its alias is in the network's DNS by the time the sandbox's
|
|
1001
|
+
// proxy environment resolves it, and removed with the sandbox — a proxy
|
|
1002
|
+
// holding real credentials must not outlive the thing it was filtering
|
|
1003
|
+
// for, and on this topology a leftover one is also a live route to the
|
|
1004
|
+
// internet for anything that can reach that network.
|
|
1005
|
+
//
|
|
1006
|
+
// Inside this `try` on purpose, which the first cut of this change got
|
|
1007
|
+
// wrong. This block has three suspension points — the resolver, the
|
|
1008
|
+
// proxy's `docker run`, and an explicit `throwIfAborted()` — and an
|
|
1009
|
+
// abort at any of them leaves a container holding real credentials with
|
|
1010
|
+
// nothing that will ever remove it: `destroy()` is unreachable, because
|
|
1011
|
+
// `create()` never returned a handle. Outside the `try` the abort
|
|
1012
|
+
// rethrew past `cleanupOnFailure`; inside it, every path that does not
|
|
1013
|
+
// return a `Sandbox` goes through that cleanup, which removes the proxy
|
|
1014
|
+
// by name on a deadline of its own. The abort that arrives here has to
|
|
1015
|
+
// be raised by a call inside the block — the sandbox's own `docker run`
|
|
1016
|
+
// does that itself — so an abort before this point reaches the same
|
|
1017
|
+
// place by the same route.
|
|
1018
|
+
if (proxyPlanned && options.egress) {
|
|
1019
|
+
egressProxyContainer = egressProxyContainerName(id);
|
|
1020
|
+
// Resolved once, here, rather than per request — see
|
|
1021
|
+
// `egressProxyContainerConfig` for what that costs and why it is paid.
|
|
1022
|
+
const allowedHosts = await resolveAllowedHosts(options.egress);
|
|
1023
|
+
options.signal?.throwIfAborted();
|
|
1024
|
+
await startEgressProxyContainer({
|
|
1025
|
+
docker,
|
|
1026
|
+
config,
|
|
1027
|
+
containerName: egressProxyContainer,
|
|
1028
|
+
internalNetwork: network,
|
|
1029
|
+
allowedHosts,
|
|
1030
|
+
signal: options.signal,
|
|
1031
|
+
});
|
|
1032
|
+
options.signal?.throwIfAborted();
|
|
1033
|
+
}
|
|
759
1034
|
const args = buildDockerRunArgs({
|
|
760
1035
|
config,
|
|
761
1036
|
options,
|
|
762
1037
|
containerName,
|
|
763
1038
|
network,
|
|
764
1039
|
hostReachability,
|
|
765
|
-
...(
|
|
1040
|
+
...(egressProxyContainer ? { egressProxyPort: EGRESS_PROXY_PORT_INSIDE_CONTAINER } : {}),
|
|
766
1041
|
});
|
|
767
|
-
await runOnce(docker, args, options.signal);
|
|
1042
|
+
await runOnce(docker, args, options.signal, { NAMZU_SANDBOX_TOKEN: workerToken });
|
|
768
1043
|
if (hostReachability === 'host-port') {
|
|
769
1044
|
hostPort = await readMappedPort(docker, containerName, options.signal);
|
|
770
1045
|
baseUrl = `http://127.0.0.1:${hostPort}`;
|
|
@@ -787,7 +1062,7 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
787
1062
|
let retirementPromise;
|
|
788
1063
|
let teardownPromise;
|
|
789
1064
|
let teardownComplete = false;
|
|
790
|
-
const workerClient = new HttpWorkerClient(baseUrl);
|
|
1065
|
+
const workerClient = new HttpWorkerClient(baseUrl, workerToken);
|
|
791
1066
|
const assertActive = () => {
|
|
792
1067
|
if (lifecycle !== 'active') {
|
|
793
1068
|
throw new Error(`Sandbox ${id} is ${lifecycle}; no new worker operation can be admitted`);
|
|
@@ -808,11 +1083,18 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
808
1083
|
teardownError = error;
|
|
809
1084
|
}
|
|
810
1085
|
finally {
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
1086
|
+
// The proxy goes with the sandbox, for the reason it is
|
|
1087
|
+
// started before it: a container holding real credentials must
|
|
1088
|
+
// not outlive the thing it was filtering for, and on this
|
|
1089
|
+
// topology leaving it running would also leave a live route to
|
|
1090
|
+
// the internet on a network the sandbox was confined to.
|
|
1091
|
+
if (egressProxyContainer !== undefined) {
|
|
1092
|
+
try {
|
|
1093
|
+
await runOnce(docker, ['rm', '-f', egressProxyContainer], signal);
|
|
1094
|
+
}
|
|
1095
|
+
catch (error) {
|
|
1096
|
+
teardownError ??= error;
|
|
1097
|
+
}
|
|
816
1098
|
}
|
|
817
1099
|
}
|
|
818
1100
|
if (teardownError !== undefined)
|
|
@@ -891,10 +1173,77 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
891
1173
|
// here and doing nothing would leave the caller believing the
|
|
892
1174
|
// sandbox had been confined when it had not. Same rule the
|
|
893
1175
|
// egress-kind refusal above follows.
|
|
894
|
-
if (
|
|
895
|
-
throw withHint(new Error('This sandbox cannot change its network policy: it was created without an egress proxy, so its network was fixed at creation and there is nothing to narrow. Refusing rather than accepting a policy that would not be applied.'), 'Construct the provider with an egress proxy to make the policy mutable, or create a second sandbox under the narrower policy.');
|
|
1176
|
+
if (egressProxyContainer === undefined) {
|
|
1177
|
+
throw withHint(new Error('This sandbox cannot change its network policy: it was created without an egress proxy, so its network was fixed at creation and there is nothing to narrow. Refusing rather than accepting a policy that would not be applied.'), 'Construct the provider with an egress proxy (and an egressProxyImage to run it as) to make the policy mutable, or create a second sandbox under the narrower policy.');
|
|
1178
|
+
}
|
|
1179
|
+
// The policy lives in the proxy container's environment, which is
|
|
1180
|
+
// written when the container starts and cannot be rewritten from
|
|
1181
|
+
// outside. So a live policy change REPLACES the container: the
|
|
1182
|
+
// allowlist the caller asked for is the allowlist the next
|
|
1183
|
+
// connection meets, and the connections open at that instant fail
|
|
1184
|
+
// closed. That is a real difference from the in-process proxy this
|
|
1185
|
+
// used to be — it swapped the allowlist in place, with no window in
|
|
1186
|
+
// which the proxy was absent — and it is the honest trade for a
|
|
1187
|
+
// boundary the sandbox cannot route around. See
|
|
1188
|
+
// `docs/sdk/sandbox-egress.md`.
|
|
1189
|
+
//
|
|
1190
|
+
// The name is read out of the closure once, here, rather than at
|
|
1191
|
+
// each use below: `cleanupOnFailure` clears it, and a swap that
|
|
1192
|
+
// raced a failing create would otherwise call `assertActive()` and
|
|
1193
|
+
// then name `undefined` in the removal.
|
|
1194
|
+
const proxyContainer = egressProxyContainer;
|
|
1195
|
+
try {
|
|
1196
|
+
await restartEgressProxyContainer({
|
|
1197
|
+
docker,
|
|
1198
|
+
config,
|
|
1199
|
+
containerName: proxyContainer,
|
|
1200
|
+
internalNetwork: network,
|
|
1201
|
+
allowedHosts: policy.allowedHosts,
|
|
1202
|
+
});
|
|
1203
|
+
// A teardown that landed while the replacement was starting
|
|
1204
|
+
// leaves a container nothing else will ever remove: `destroy()`
|
|
1205
|
+
// is running or has run, `egressProxyContainer` is only removed
|
|
1206
|
+
// from `teardownSandbox` and `cleanupOnFailure`, and the
|
|
1207
|
+
// `assertActive()` above ran BEFORE the first `await` — before
|
|
1208
|
+
// the swap suspended inside `restartEgressProxyContainer`, which
|
|
1209
|
+
// is exactly when a teardown lands. So the swap fails here
|
|
1210
|
+
// rather than reporting a policy change on a sandbox that no
|
|
1211
|
+
// longer exists.
|
|
1212
|
+
assertActive();
|
|
1213
|
+
}
|
|
1214
|
+
finally {
|
|
1215
|
+
// ... and the replacement is removed even so, because the check
|
|
1216
|
+
// above cannot be where the guarantee lives. It sits AFTER the
|
|
1217
|
+
// container comes into existence, and that ordering is what
|
|
1218
|
+
// makes it airtight rather than merely narrower than the check
|
|
1219
|
+
// at entry. A generation counter read before the `docker run`
|
|
1220
|
+
// has the opposite shape: it can only refuse a start it already
|
|
1221
|
+
// knows about, and a teardown that begins between that refusal
|
|
1222
|
+
// being evaluated and the daemon committing the container is in
|
|
1223
|
+
// no check's view — the container exists and nothing has looked
|
|
1224
|
+
// since. Here the two orderings partition the space instead. A
|
|
1225
|
+
// teardown that began before this point has already set
|
|
1226
|
+
// `lifecycle`, synchronously (`teardownSandbox` and `retire()`
|
|
1227
|
+
// both do, before their first `await`), so this removal runs. A
|
|
1228
|
+
// teardown that begins after it issues its own `rm -f` for this
|
|
1229
|
+
// same name — `teardownSandbox` reads `egressProxyContainer`,
|
|
1230
|
+
// which is this container — against a container that, at this
|
|
1231
|
+
// point, exists. Whichever of the two runs second finds the
|
|
1232
|
+
// container and removes it, and both are idempotent.
|
|
1233
|
+
//
|
|
1234
|
+
// A signal-less remover, and not `runOnce` on some signal, for
|
|
1235
|
+
// the reason `removeEgressProxyContainer` exists: the teardown
|
|
1236
|
+
// this is racing may be one whose own signal was already
|
|
1237
|
+
// aborted, and it removes nothing at all in that case (the whole
|
|
1238
|
+
// container set is left, which is what `Sandbox.destroy`
|
|
1239
|
+
// promises to settle promptly over). That is the caller's
|
|
1240
|
+
// contract and not something to defeat — but a proxy container
|
|
1241
|
+
// holding brokered credentials and a live route to the internet
|
|
1242
|
+
// is not something to leave with it either.
|
|
1243
|
+
if (lifecycle !== 'active') {
|
|
1244
|
+
await removeEgressProxyContainer(docker, proxyContainer);
|
|
1245
|
+
}
|
|
896
1246
|
}
|
|
897
|
-
egressProxy.setAllowedHosts(async () => policy.allowedHosts);
|
|
898
1247
|
},
|
|
899
1248
|
async writeFile(path, content) {
|
|
900
1249
|
assertActive();
|
|
@@ -903,7 +1252,10 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
903
1252
|
try {
|
|
904
1253
|
res = await fetch(`${baseUrl}/write-file`, {
|
|
905
1254
|
method: 'POST',
|
|
906
|
-
headers: {
|
|
1255
|
+
headers: {
|
|
1256
|
+
'content-type': 'application/json',
|
|
1257
|
+
...workerAuthorization(workerToken),
|
|
1258
|
+
},
|
|
907
1259
|
body: JSON.stringify({
|
|
908
1260
|
path,
|
|
909
1261
|
content: buf.toString('base64'),
|
|
@@ -920,6 +1272,9 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
920
1272
|
: 'unknown';
|
|
921
1273
|
throw new Error(`namzu-sandbox /write-file fetch failed (baseUrl=${baseUrl}, path=${path}): ${err instanceof Error ? err.message : String(err)} — cause: ${causeMsg}`, { cause: err });
|
|
922
1274
|
}
|
|
1275
|
+
if (res.status === 401) {
|
|
1276
|
+
throw withHint(new Error(`write-file failed: HTTP 401 ${await res.text()}`), WORKER_UNAUTHORIZED_HINT);
|
|
1277
|
+
}
|
|
923
1278
|
if (!res.ok) {
|
|
924
1279
|
throw new Error(`write-file failed: HTTP ${res.status} ${await res.text()}`);
|
|
925
1280
|
}
|
|
@@ -945,10 +1300,16 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
945
1300
|
}
|
|
946
1301
|
const res = await fetch(`${baseUrl}/read-file`, {
|
|
947
1302
|
method: 'POST',
|
|
948
|
-
headers: {
|
|
1303
|
+
headers: {
|
|
1304
|
+
'content-type': 'application/json',
|
|
1305
|
+
...workerAuthorization(workerToken),
|
|
1306
|
+
},
|
|
949
1307
|
body: JSON.stringify({ path, encoding: 'base64' }),
|
|
950
1308
|
signal: options?.signal,
|
|
951
1309
|
});
|
|
1310
|
+
if (res.status === 401) {
|
|
1311
|
+
throw withHint(new Error(`read-file failed: HTTP 401 ${await res.text()}`), WORKER_UNAUTHORIZED_HINT);
|
|
1312
|
+
}
|
|
952
1313
|
if (!res.ok) {
|
|
953
1314
|
throw new Error(`read-file failed: HTTP ${res.status} ${await res.text()}`);
|
|
954
1315
|
}
|
|
@@ -992,6 +1353,164 @@ async function spawnDockerSandbox(config, options, readiness) {
|
|
|
992
1353
|
},
|
|
993
1354
|
};
|
|
994
1355
|
}
|
|
1356
|
+
/** The proxy's upstream network when the host named none. See the field. */
|
|
1357
|
+
const DEFAULT_EGRESS_PROXY_UPSTREAM_NETWORK = 'bridge';
|
|
1358
|
+
/**
|
|
1359
|
+
* How long a reconciliation remove of the proxy container may take.
|
|
1360
|
+
*
|
|
1361
|
+
* The same order as `retire()`'s own deadline, and for the same reason: this
|
|
1362
|
+
* bounds a call to a daemon that may never answer. It is a deadline of its own
|
|
1363
|
+
* rather than the caller's, because the caller is usually an aborted operation
|
|
1364
|
+
* — see {@link removeEgressProxyContainer}.
|
|
1365
|
+
*/
|
|
1366
|
+
const EGRESS_PROXY_REMOVE_TIMEOUT_MS = 5_000;
|
|
1367
|
+
/**
|
|
1368
|
+
* Remove the proxy container, on a path that is already failing.
|
|
1369
|
+
*
|
|
1370
|
+
* Three properties, each of which the first cut of this change got wrong, and
|
|
1371
|
+
* each of which is why this is a function rather than a `runOnceQuiet` call at
|
|
1372
|
+
* three sites:
|
|
1373
|
+
*
|
|
1374
|
+
* - **It never takes the caller's signal.** A reconciliation remove handed an
|
|
1375
|
+
* already-aborted signal does not reach the daemon at all: `runOnce` and
|
|
1376
|
+
* `runOnceQuiet` install an abort listener that kills the child the moment
|
|
1377
|
+
* they see one, so `docker rm -f` dies before it is spawned and the
|
|
1378
|
+
* container survives — in exactly the case this exists to handle, an
|
|
1379
|
+
* operation that was aborted midway through starting it.
|
|
1380
|
+
* - **It is bounded anyway.** A fresh deadline of its own, so a daemon that
|
|
1381
|
+
* never answers cannot hang the failure path that is cleaning up after it.
|
|
1382
|
+
* - **It does not throw.** Whatever went wrong to bring the caller here is the
|
|
1383
|
+
* thing the caller needs to hear; a failure to remove is reported by the
|
|
1384
|
+
* container's own name in `docker ps` and by the label reaper this file
|
|
1385
|
+
* documents, not by replacing that error with a worse one.
|
|
1386
|
+
*/
|
|
1387
|
+
async function removeEgressProxyContainer(docker, containerName) {
|
|
1388
|
+
const deadline = new OperationDeadline(EGRESS_PROXY_REMOVE_TIMEOUT_MS, `egress proxy container ${containerName} removal`);
|
|
1389
|
+
try {
|
|
1390
|
+
await deadline.run((signal) => runOnceQuiet(docker, ['rm', '-f', containerName], signal));
|
|
1391
|
+
}
|
|
1392
|
+
catch {
|
|
1393
|
+
// Deliberately swallowed. See the third property above.
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Start the proxy container: run it, join it to the internal network, prove it
|
|
1398
|
+
* is up.
|
|
1399
|
+
*
|
|
1400
|
+
* Three steps and not one, in this order, for reasons that are all about the
|
|
1401
|
+
* topology rather than about docker's ergonomics. `docker run --network
|
|
1402
|
+
* <upstream>` gives the proxy its default route — the leg that reaches the
|
|
1403
|
+
* internet. `docker network connect --alias` adds the internal leg the sandbox
|
|
1404
|
+
* dials it on, and it has to be second: a container created on an internal
|
|
1405
|
+
* network first comes up with no default route and never gets one, which is a
|
|
1406
|
+
* proxy that can reach nothing. The readiness check is third because the first
|
|
1407
|
+
* two are `docker run` exiting 0, and `docker run --detach` exits 0 for a
|
|
1408
|
+
* container whose entrypoint is about to fail — an image without the compiled
|
|
1409
|
+
* module in it, or a config the entrypoint refused. Those failures arrive as a
|
|
1410
|
+
* sandbox whose every outbound request fails, which reads as the policy
|
|
1411
|
+
* working.
|
|
1412
|
+
*
|
|
1413
|
+
* A failure after the container exists removes it before rethrowing. Leaving
|
|
1414
|
+
* it would leave a container holding real credentials and a live route to the
|
|
1415
|
+
* internet with no sandbox it belongs to. This is not the only remover on that
|
|
1416
|
+
* path: the block that starts this container sits INSIDE the `try` that owns
|
|
1417
|
+
* `cleanupOnFailure`, and the name it is started under is in
|
|
1418
|
+
* `egressProxyContainer` from before the call, so the caller's cleanup removes
|
|
1419
|
+
* the same name again. The first cut of this change had the block outside that
|
|
1420
|
+
* `try` and this sentence said the caller's own cleanup could not see the
|
|
1421
|
+
* container; the two were wrong together, and the leak was real.
|
|
1422
|
+
*/
|
|
1423
|
+
async function startEgressProxyContainer(input) {
|
|
1424
|
+
const { docker, config, containerName, internalNetwork, allowedHosts, signal } = input;
|
|
1425
|
+
const argvInput = {
|
|
1426
|
+
config,
|
|
1427
|
+
containerName,
|
|
1428
|
+
upstreamNetwork: config.egressProxyUpstreamNetwork ?? DEFAULT_EGRESS_PROXY_UPSTREAM_NETWORK,
|
|
1429
|
+
internalNetwork,
|
|
1430
|
+
};
|
|
1431
|
+
// The policy, on its way to the container's environment by way of the
|
|
1432
|
+
// `docker` CLI's own. See `renderEgressProxyRunArgs` for why it does not
|
|
1433
|
+
// travel in the argv.
|
|
1434
|
+
const proxyEnvironment = {
|
|
1435
|
+
[EGRESS_PROXY_CONFIG_ENV]: JSON.stringify(egressProxyContainerConfig(config, allowedHosts, EGRESS_PROXY_PORT_INSIDE_CONTAINER)),
|
|
1436
|
+
};
|
|
1437
|
+
try {
|
|
1438
|
+
await runOnce(docker, renderEgressProxyRunArgs(argvInput), signal, proxyEnvironment);
|
|
1439
|
+
}
|
|
1440
|
+
catch (error) {
|
|
1441
|
+
// The container may exist even though this call did not return
|
|
1442
|
+
// successfully: `docker run --detach` is a CLI process talking to a
|
|
1443
|
+
// daemon, and the daemon can commit the container while the client is
|
|
1444
|
+
// killed, times out, or fails to report the id back. Remove by name
|
|
1445
|
+
// before rethrowing, which is what the docblock above promised in the
|
|
1446
|
+
// first cut of this change and did not do.
|
|
1447
|
+
await removeEgressProxyContainer(docker, containerName);
|
|
1448
|
+
// An abort is not a failure to start, and the caller that aborted is
|
|
1449
|
+
// entitled to hear its own reason back — the same rule every other
|
|
1450
|
+
// catch in this file follows. Without this an acquisition timeout would
|
|
1451
|
+
// arrive dressed as an image-install problem, which is the diagnosis
|
|
1452
|
+
// shape this file refuses everywhere else.
|
|
1453
|
+
signal?.throwIfAborted();
|
|
1454
|
+
throw withHint(new Error(`Could not start the egress proxy container '${containerName}' from image '${config.egressProxyImage}': ${error instanceof Error ? error.message : String(error)}`), 'Build that image with `docker build -f packages/sandbox/egress-proxy/Dockerfile -t <tag> packages/sandbox` (after `pnpm --filter @namzu/sandbox build`), and name the tag in egressProxyImage. The sandbox is deliberately not started when the only way its traffic reaches the internet is missing.');
|
|
1455
|
+
}
|
|
1456
|
+
try {
|
|
1457
|
+
await runOnce(docker, renderEgressProxyAttachArgs(argvInput), signal);
|
|
1458
|
+
await assertEgressProxyContainerIsRunning(docker, containerName, signal);
|
|
1459
|
+
}
|
|
1460
|
+
catch (error) {
|
|
1461
|
+
await removeEgressProxyContainer(docker, containerName);
|
|
1462
|
+
throw error;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
/**
|
|
1466
|
+
* Replace the proxy container, for `setNetworkPolicy`.
|
|
1467
|
+
*
|
|
1468
|
+
* The policy the container enforces is in its environment, which is written
|
|
1469
|
+
* when it starts and is not writable from outside, so a live policy change is
|
|
1470
|
+
* a new container. The window between the two is one in which the sandbox has
|
|
1471
|
+
* no route out at all — the old proxy is gone and the new one is not up yet —
|
|
1472
|
+
* which fails CLOSED. That is the property worth naming: the alternative
|
|
1473
|
+
* ordering (start the second, then remove the first) has no such window, but
|
|
1474
|
+
* two containers cannot hold the same name or the same network alias, so it
|
|
1475
|
+
* would need a second name the sandbox's `HTTP_PROXY` does not know.
|
|
1476
|
+
*/
|
|
1477
|
+
async function restartEgressProxyContainer(input) {
|
|
1478
|
+
await removeEgressProxyContainer(input.docker, input.containerName);
|
|
1479
|
+
try {
|
|
1480
|
+
await startEgressProxyContainer(input);
|
|
1481
|
+
}
|
|
1482
|
+
catch (error) {
|
|
1483
|
+
// The hint names both states rather than assuming the safe one. The
|
|
1484
|
+
// removal above swallows its own failure, so "the old container is
|
|
1485
|
+
// gone" is not something this function knows: if the daemon never
|
|
1486
|
+
// answered the remove, the previous container is still up and still
|
|
1487
|
+
// enforcing the policy the caller just replaced — which would be a
|
|
1488
|
+
// worse thing to misreport than a sandbox with no route out.
|
|
1489
|
+
throw withHint(error instanceof Error ? error : new Error(String(error)), "Check `docker ps` for this sandbox's proxy container before relying on the new policy: the replacement did not come up, so this sandbox either has no route out at all (every request fails closed) or still has the previous container enforcing the policy you just replaced. Retry, or destroy the sandbox and create it under the policy you want.");
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Whether the daemon says the proxy container is still up.
|
|
1494
|
+
*
|
|
1495
|
+
* Read the same way {@link inspectNetworkInternalFlag} reads the network's
|
|
1496
|
+
* `Internal` flag, and for the same reason: an unreadable answer is not
|
|
1497
|
+
* evidence. A container that has already exited is gone (`--rm` removed it),
|
|
1498
|
+
* so the failure arrives as a failed `docker inspect` rather than as a
|
|
1499
|
+
* `false`, and both have to land on the same refusal.
|
|
1500
|
+
*/
|
|
1501
|
+
async function assertEgressProxyContainerIsRunning(docker, containerName, signal) {
|
|
1502
|
+
let running = '';
|
|
1503
|
+
try {
|
|
1504
|
+
running = await runOnce(docker, ['inspect', '--format', '{{.State.Running}}', containerName], signal);
|
|
1505
|
+
}
|
|
1506
|
+
catch {
|
|
1507
|
+
signal?.throwIfAborted();
|
|
1508
|
+
running = '';
|
|
1509
|
+
}
|
|
1510
|
+
if (running.trim() === 'true')
|
|
1511
|
+
return;
|
|
1512
|
+
throw withHint(new Error(`The egress proxy container '${containerName}' is not running after being started, so this sandbox has no boundary to reach and no other route out.`), 'Almost always the image: it either lacks the compiled module (build the package before the image — `pnpm --filter @namzu/sandbox build`) or the entrypoint refused its configuration. `docker logs <container>` has the line the entrypoint wrote; the container is started with --rm, so an already-exited one is gone and its output with it.');
|
|
1513
|
+
}
|
|
995
1514
|
/**
|
|
996
1515
|
* Ask Docker which host port it bound to the worker port. Used
|
|
997
1516
|
* instead of the pre-reserve-then-publish pattern (which had a
|
|
@@ -1086,10 +1605,100 @@ async function waitForWorkerReady(baseUrl, timeoutMs, pollMs, signal) {
|
|
|
1086
1605
|
// which is what a reader needs.
|
|
1087
1606
|
throw withHint(new Error(`namzu-sandbox worker did not become ready within ${timeoutMs}ms: ${lastError instanceof Error ? lastError.message : String(lastError)}`), 'Check that the container runtime is running and that the sandbox worker image is built and reachable. A cold image pull can also exceed this window — raise the readiness timeout before assuming the worker is broken.');
|
|
1088
1607
|
}
|
|
1089
|
-
|
|
1608
|
+
/**
|
|
1609
|
+
* The argv as it may appear in an error message: the KEYS of every env
|
|
1610
|
+
* entry, with the values replaced.
|
|
1611
|
+
*
|
|
1612
|
+
* A rendered argv is the last place a secret should survive. A non-zero
|
|
1613
|
+
* `docker run` is a routine outcome — a missing image, a name conflict, a
|
|
1614
|
+
* daemon hiccup, ENOSPC — and its message goes wherever the sandbox
|
|
1615
|
+
* package's errors go: a log line, a telemetry batch, a CI transcript, a
|
|
1616
|
+
* pasted bug report. The env flags carry the worker's credential and every
|
|
1617
|
+
* value the host put in `options.env` (an API key, a broker token), and
|
|
1618
|
+
* none of them are needed to explain an exit code. The keys are kept
|
|
1619
|
+
* because they are what distinguishes "the image could not be pulled" from
|
|
1620
|
+
* "the environment was rejected".
|
|
1621
|
+
*
|
|
1622
|
+
* EVERY SPELLING docker accepts for that flag, not the one this backend
|
|
1623
|
+
* happens to emit today. `-e` IS `--env`, separated or `=`-attached, and
|
|
1624
|
+
* this function used to compare each element to the literal `'--env'`: the
|
|
1625
|
+
* long separated form this builder writes was redacted and `-e K=V`,
|
|
1626
|
+
* `--env=K=V` and `-e=K=V` were printed in full. A future caller writing
|
|
1627
|
+
* any of the three would have put a credential in a log line behind a
|
|
1628
|
+
* docblock that promised it would not. The covered forms are `--env K=V`,
|
|
1629
|
+
* `--env=K=V`, `-e K=V`, `-e=K=V` and the attached short form `-eK=V`; the
|
|
1630
|
+
* one shape it does not read is a value attached to an `-e` bundled into a
|
|
1631
|
+
* group of other short flags (`-iteK=V`), which no caller here writes and
|
|
1632
|
+
* which no rule short of matching `-e` anywhere inside an option could
|
|
1633
|
+
* catch. A valueless entry in any form (`--env K`) is passed through: it
|
|
1634
|
+
* resolves from the CLI's own environment and carries no value to redact.
|
|
1635
|
+
*
|
|
1636
|
+
* That redacts the workspace paths the layout is rendered from as well,
|
|
1637
|
+
* which are not secrets. They are also not what an exit code is about, and
|
|
1638
|
+
* a rule with exceptions is a rule that leaks the first time someone's
|
|
1639
|
+
* credential does not look like one.
|
|
1640
|
+
*/
|
|
1641
|
+
export function redactDockerArgv(args) {
|
|
1642
|
+
const rendered = [...args];
|
|
1643
|
+
/** `K=V` → `K=<redacted>`, keeping the key; a valueless entry is left alone. */
|
|
1644
|
+
const redactEntry = (entry) => {
|
|
1645
|
+
const separator = entry.indexOf('=');
|
|
1646
|
+
return separator > 0 ? `${entry.slice(0, separator)}=<redacted>` : entry;
|
|
1647
|
+
};
|
|
1648
|
+
for (let index = 0; index < rendered.length; index += 1) {
|
|
1649
|
+
const arg = rendered[index];
|
|
1650
|
+
if (arg === '--env' || arg === '-e') {
|
|
1651
|
+
const entry = rendered[index + 1];
|
|
1652
|
+
if (entry !== undefined)
|
|
1653
|
+
rendered[index + 1] = redactEntry(entry);
|
|
1654
|
+
index += 1;
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
// Attached, where the option's value is the rest of the same element:
|
|
1658
|
+
// the `=` forms, and the short form with no separator (`-eK=V`).
|
|
1659
|
+
const prefix = arg.startsWith('--env=')
|
|
1660
|
+
? '--env='
|
|
1661
|
+
: arg.startsWith('-e=')
|
|
1662
|
+
? '-e='
|
|
1663
|
+
: arg.startsWith('-e') && arg.length > 2
|
|
1664
|
+
? '-e'
|
|
1665
|
+
: undefined;
|
|
1666
|
+
if (prefix !== undefined)
|
|
1667
|
+
rendered[index] = prefix + redactEntry(arg.slice(prefix.length));
|
|
1668
|
+
}
|
|
1669
|
+
return rendered;
|
|
1670
|
+
}
|
|
1671
|
+
/**
|
|
1672
|
+
* Run a docker subcommand to completion.
|
|
1673
|
+
*
|
|
1674
|
+
* `extraEnv` is added to the child's environment rather than the parent's, and
|
|
1675
|
+
* it is how a value reaches a container without entering the argv this file
|
|
1676
|
+
* builds. Two callers use it, for the same reason:
|
|
1677
|
+
*
|
|
1678
|
+
* - The sandbox's own `docker run`, which hands over the worker's
|
|
1679
|
+
* per-instance credential for the valueless `--env NAMZU_SANDBOX_TOKEN` its
|
|
1680
|
+
* argv carries (minted in `spawnDockerSandbox`).
|
|
1681
|
+
* - The egress proxy's `docker run`, which names its configuration variable
|
|
1682
|
+
* in the argv and hands the value over here. See
|
|
1683
|
+
* `renderEgressProxyRunArgs`.
|
|
1684
|
+
*
|
|
1685
|
+
* Anything a process is told through the environment is visible to `ps`'s
|
|
1686
|
+
* neighbour, `/proc/<pid>/environ`, only to the user that owns it — while an
|
|
1687
|
+
* argv is world-readable on Linux.
|
|
1688
|
+
*/
|
|
1689
|
+
function runOnce(binary, args, signal, extraEnv) {
|
|
1090
1690
|
return new Promise((resolve, reject) => {
|
|
1091
1691
|
signal?.throwIfAborted();
|
|
1092
|
-
const child = spawn(binary, args, {
|
|
1692
|
+
const child = spawn(binary, args, {
|
|
1693
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1694
|
+
// The one channel a value can ride in without entering the argv
|
|
1695
|
+
// this process builds: `ps` shows an argv to every user on the
|
|
1696
|
+
// host, and `/proc/<pid>/environ` is readable only by the same
|
|
1697
|
+
// user and root. `docker run --env NAME` (no `=`) reads the value
|
|
1698
|
+
// out of the CLI's own environment, which is why the credential
|
|
1699
|
+
// is passed this way and rendered valueless in the argv.
|
|
1700
|
+
...(extraEnv ? { env: { ...process.env, ...extraEnv } } : {}),
|
|
1701
|
+
});
|
|
1093
1702
|
let stdout = '';
|
|
1094
1703
|
let stderr = '';
|
|
1095
1704
|
let settled = false;
|
|
@@ -1121,7 +1730,7 @@ function runOnce(binary, args, signal) {
|
|
|
1121
1730
|
if (code === 0)
|
|
1122
1731
|
finish(undefined, stdout.trim());
|
|
1123
1732
|
else
|
|
1124
|
-
finish(new Error(`${binary} ${args.join(' ')} exited ${code}: ${stderr.trim()}`));
|
|
1733
|
+
finish(new Error(`${binary} ${redactDockerArgv(args).join(' ')} exited ${code}: ${stderr.trim()}`));
|
|
1125
1734
|
});
|
|
1126
1735
|
if (signal?.aborted)
|
|
1127
1736
|
abort();
|