@capybara-hq/testing 0.1.0-rc.27 → 0.1.0-rc.29

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.
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { isIP, isIPv4 } from "node:net";
4
4
  import { posix } from "node:path";
5
- import { isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, validateAllowHost, } from "@capybara-hq/plugin-sdk";
5
+ import { classifyAddress, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, isSandboxScopeValidationError, OPEN_PUBLIC_DENIED_CLASSES, SANDBOX_RESERVED_NAME_PREFIX, validateAllowHost, } from "@capybara-hq/plugin-sdk";
6
6
  const text = (data) => (data === null ? null : Buffer.from(data).toString());
7
7
  const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
8
8
  /** A Python program in which one thread rewrites a syscall's pointer argument mid-call. */
@@ -18,6 +18,9 @@ def flipper(buffer, good, bad):
18
18
  ok = 0
19
19
  if mode == "connect":
20
20
  def sockaddr(host, port):
21
+ if sys.platform == "darwin":
22
+ # BSD sockaddr_in: a length byte, then a one-byte family
23
+ return struct.pack("BBH4s8x", 16, socket.AF_INET, socket.htons(port), socket.inet_aton(host))
21
24
  return struct.pack("HH4s8x", socket.AF_INET, socket.htons(port), socket.inet_aton(host))
22
25
  if sys.argv[3] == "proxy":
23
26
  # The allowed target is the operation's own HTTP proxy, taken from its environment.
@@ -78,7 +81,8 @@ print(" ".join(out))
78
81
  `;
79
82
  /** A Full-access UNIX service (stream, seqpacket, datagram) counting every client it sees. */
80
83
  const UNIX_SERVER = `
81
- import os, socket, sys, threading
84
+ import errno, os, socket, sys, threading
85
+ UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
82
86
  path, counter = sys.argv[1], sys.argv[2]
83
87
  lock = threading.Lock()
84
88
  count = [0]
@@ -89,7 +93,14 @@ def seen():
89
93
  handle.write(str(count[0]))
90
94
  os.replace(counter + ".tmp", counter)
91
95
  def serve(kind, suffix):
92
- s = socket.socket(socket.AF_UNIX, kind)
96
+ try:
97
+ s = socket.socket(socket.AF_UNIX, kind)
98
+ except OSError as error:
99
+ if error.errno not in UNSUPPORTED:
100
+ raise
101
+ # this OS has no such UNIX socket type (macOS: SOCK_SEQPACKET): mark it and stop
102
+ open(path + suffix, "w").close()
103
+ return
93
104
  s.bind(path + suffix)
94
105
  if kind == socket.SOCK_DGRAM:
95
106
  while True:
@@ -112,22 +123,41 @@ threading.Event().wait()
112
123
  `;
113
124
  /** Tries every way to reach the outside UNIX service; prints ok/denied per attempt. */
114
125
  const UNIX_CLIENT = `
115
- import socket, sys
126
+ import errno, socket, sys
127
+ UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
116
128
  path, link = sys.argv[1], sys.argv[2]
129
+ class Unsupported(Exception):
130
+ pass
131
+ def make(create):
132
+ # the OS has no such UNIX socket type at all (macOS: SOCK_SEQPACKET, SOCK_RAW)
133
+ try:
134
+ return create()
135
+ except OSError as error:
136
+ if error.errno in UNSUPPORTED:
137
+ raise Unsupported()
138
+ raise
117
139
  def attempt(name, action):
118
140
  try:
119
141
  action()
120
142
  return name + "=ok"
143
+ except Unsupported:
144
+ return name + "=unsupported"
121
145
  except OSError:
122
146
  return name + "=denied"
123
147
  def connect(kind, target):
124
- socket.socket(socket.AF_UNIX, kind).connect(target)
148
+ make(lambda: socket.socket(socket.AF_UNIX, kind)).connect(target)
125
149
  def send(kind):
126
- socket.socket(socket.AF_UNIX, kind).sendto(b"x", path + ".dgram")
150
+ make(lambda: socket.socket(socket.AF_UNIX, kind)).sendto(b"x", path + ".dgram")
127
151
  def pair(kind):
128
152
  # An explicit address on a socketpair datagram socket is honoured by the kernel.
129
- first, _ = socket.socketpair(socket.AF_UNIX, kind)
130
- first.sendto(b"x", path + ".dgram")
153
+ first, _ = make(lambda: socket.socketpair(socket.AF_UNIX, kind))
154
+ try:
155
+ first.sendto(b"x", path + ".dgram")
156
+ except OSError as error:
157
+ # the OS ignores no explicit address on a connected socket (macOS): no such vector there
158
+ if error.errno == errno.EISCONN:
159
+ raise Unsupported()
160
+ raise
131
161
  print(" ".join([
132
162
  attempt("stream", lambda: connect(socket.SOCK_STREAM, path)),
133
163
  attempt("seqpacket", lambda: connect(socket.SOCK_SEQPACKET, path + ".seq")),
@@ -138,6 +168,30 @@ print(" ".join([
138
168
  attempt("pair-raw", lambda: pair(socket.SOCK_RAW)),
139
169
  ]))
140
170
  `;
171
+ /**
172
+ * Connects to a UNIX service another process made inside the root (stream, and seqpacket where the
173
+ * OS has it), by the relative path and by `argv[2]` (absolute); prints ok/denied/unsupported.
174
+ */
175
+ const FOREIGN_UNIX_CLIENT = `
176
+ import errno, socket, sys
177
+ UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
178
+ out = []
179
+ for name, kind, suffix in (("stream", socket.SOCK_STREAM, ""), ("seqpacket", socket.SOCK_SEQPACKET, ".seq")):
180
+ for spelling, path in (("", sys.argv[1]), ("-absolute", sys.argv[2])):
181
+ try:
182
+ s = socket.socket(socket.AF_UNIX, kind)
183
+ except OSError as error:
184
+ out.append(name + spelling + ("=unsupported" if error.errno in UNSUPPORTED else "=denied"))
185
+ continue
186
+ try:
187
+ s.settimeout(10)
188
+ s.connect(path + suffix)
189
+ out.append(name + spelling + "=ok")
190
+ except OSError:
191
+ out.append(name + spelling + "=denied")
192
+ s.close()
193
+ print("foreign-unix-client " + " ".join(out))
194
+ `;
141
195
  /** A UNIX stream server and client inside the root talk to each other. */
142
196
  const UNIX_ROUNDTRIP = `
143
197
  import socket, sys
@@ -159,8 +213,12 @@ os.makedirs(base + "/dir")
159
213
  os.symlink(outside, base + "/link")
160
214
  open(base + "/swapping", "w").close()
161
215
  swaps = 0
216
+ def exchange(a, b):
217
+ if sys.platform == "darwin":
218
+ return libc.renamex_np(a, b, 2) # RENAME_SWAP
219
+ return libc.renameat2(-100, a, -100, b, 2) # RENAME_EXCHANGE
162
220
  while not os.path.exists(stop):
163
- if libc.renameat2(-100, (base + "/dir").encode(), -100, (base + "/link").encode(), 2) == 0:
221
+ if exchange((base + "/dir").encode(), (base + "/link").encode()) == 0:
164
222
  swaps += 1
165
223
  print("swaps=%d" % swaps)
166
224
  `;
@@ -213,24 +271,110 @@ print(json.dumps({"uid": os.getuid(), "who": identity(target), "control": contro
213
271
  "target": probe(target)}))
214
272
  `;
215
273
  /**
216
- * Proves an actual provider's permission boundary on one shared device: positive controls, sibling,
217
- * symlink, protected-path and network denials, Full controls without restricted filters, both
218
- * overlap orders, component/root swaps and mutable syscall pointers during access, exact
219
- * cancellation, a supervisor closed to same-uid outsiders (when the fixture can run one) and fresh
220
- * narrowed scopes. Restricted network none/allowlist may bind and listen on
221
- * loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
222
- * every network kind, environment included. A provider that reports restricted unsupported must
274
+ * Listens on loopback and connects to its own listener (refused: no sandboxed client reaches a
275
+ * loopback listener, its own included), then tries to join a reuseport group (refused).
276
+ */
277
+ const OWN_LOOPBACK = `
278
+ import json, socket
279
+ out = {}
280
+ for family, host in ((socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1")):
281
+ server = socket.socket(family, socket.SOCK_STREAM)
282
+ server.bind((host, 0))
283
+ server.listen(4)
284
+ client = socket.socket(family, socket.SOCK_STREAM)
285
+ client.settimeout(5)
286
+ try:
287
+ client.connect((host, server.getsockname()[1]))
288
+ out["own " + host] = "ok"
289
+ except OSError:
290
+ out["own " + host] = "denied"
291
+ s = socket.socket()
292
+ try:
293
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
294
+ out["reuseport"] = "ok"
295
+ except OSError:
296
+ out["reuseport"] = "denied"
297
+ print(json.dumps(out, sort_keys=True))
298
+ `;
299
+ /** Listens on loopback, publishes its port and prints what the first client sends. */
300
+ const LOOPBACK_SERVICE = `
301
+ import os, socket, sys
302
+ server = socket.socket()
303
+ server.bind(("127.0.0.1", 0))
304
+ server.listen(1)
305
+ server.settimeout(60)
306
+ with open(sys.argv[1] + ".tmp", "w") as handle:
307
+ handle.write(str(server.getsockname()[1]))
308
+ os.rename(sys.argv[1] + ".tmp", sys.argv[1])
309
+ peer = server.accept()[0]
310
+ peer.settimeout(10)
311
+ print(peer.recv(16).decode())
312
+ `;
313
+ const CHECK_PART = {
314
+ "outside-switch": "processes",
315
+ environment: "filesystem",
316
+ "reserved-names": "filesystem",
317
+ "link-chain": "filesystem",
318
+ "closed-granted": "network",
319
+ loopback: "network",
320
+ "open-network": "network",
321
+ "foreign-unix": "network",
322
+ };
323
+ /** The innocent-looking planted name a denylist would let through (see `deviceEnvironment`). */
324
+ const SECRET_LOOKING = /SECRET|TOKEN|KEY|PASS|CREDENTIAL|^CAPYBARA_/i;
325
+ /** The minimal environment's fixed names (see `deviceEnvironment`). */
326
+ const MINIMAL_ENVIRONMENT = new Set([
327
+ "PATH",
328
+ "LANG",
329
+ "HOME",
330
+ "TMPDIR",
331
+ "TMP",
332
+ "TEMP",
333
+ "PWD",
334
+ "OLDPWD",
335
+ "SHLVL",
336
+ "_",
337
+ ]);
338
+ /**
339
+ * Proves an actual provider's permission boundary on one shared device (approval-only profiles
340
+ * design). The sandbox is the device's and the same under every profile: a profile only chooses
341
+ * who approves a crossing, so every profile's ordinary call is sandboxed, and only the escalated
342
+ * pair (the device filesystem with the environment network, legal only together) runs outside it,
343
+ * and only with outside-sandbox support while the owner allows it.
344
+ *
345
+ * An operation-boundary provider (a local device) is proved with positive controls; sibling,
346
+ * symlink, protected-path, mandatory-deny, reserved-name, protected-link-chain and network
347
+ * denials; every profile sandboxed with the minimal environment; the open network (closed classes
348
+ * refused by resolved address, rebinding and fake-IP names included) and the allowlist (closed
349
+ * classes refused even for granted names); loopback listeners (Linux: loopback only, no sandboxed
350
+ * connect to any, its own included, no `SO_REUSEPORT`; macOS: none at all); escalated-pair
351
+ * controls outside the sandbox; both overlap orders; component/root swaps and mutable syscall
352
+ * pointers during access; exact cancellation; a supervisor closed to same-uid outsiders (when the
353
+ * fixture can run one) and fresh narrowed scopes. Pathname UNIX services outside the roots stay
354
+ * unreachable under every sandbox network, and so does one another process made inside a write
355
+ * root (only the operation's own sockets are reachable). A provider that reports restricted unsupported must
223
356
  * refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
224
357
  *
358
+ * An instance-boundary provider (a cloud device: the container or microVM is the sandbox) is
359
+ * proved with every profile running alike in the instance (its whole filesystem the scope),
360
+ * nothing outside it, the outer network (open or allowlist) for every operation, and exact
361
+ * cancellation.
362
+ *
225
363
  * Not covered, by design (known limitations, not passes): metadata reads outside the roots (stat,
226
364
  * readlink, xattrs, statfs), and the world-readable `/proc/<pid>` entries of other processes of the
227
365
  * same uid, such as `cmdline`, `stat` and `status`. A restricted operation can therefore read the
228
- * command line of a concurrent Full command on the device: Landlock cannot scope `/proc` to the
366
+ * command line of a concurrent escalated command on the device: Landlock cannot scope `/proc` to the
229
367
  * operation's own process tree (see the Linux launcher's known limitations). Providers keep secrets
230
368
  * out of command lines; ptrace-guarded entries (`environ`, `mem`, `maps`, `fd`) stay closed.
231
369
  */
232
- export async function runSandboxPermissionConformance(fixture) {
370
+ export async function runSandboxPermissionConformance(fixture, options = {}) {
233
371
  const { root, sibling } = fixture;
372
+ const unavailable = [];
373
+ const report = () => ({ unavailable: [...unavailable] });
374
+ const part = (name) => options.parts === undefined || options.parts.includes(name);
375
+ /** The parts' other checks run only in a run that does not pick single checks. */
376
+ const whole = (name) => options.checks === undefined && part(name);
377
+ const want = (check) => options.checks === undefined ? part(CHECK_PART[check]) : options.checks.includes(check);
234
378
  const at = (base, name) => posix.join(base, name);
235
379
  const secret = `sibling-secret-${randomUUID()}`;
236
380
  const scoped = (writeRoots) => ({
@@ -243,11 +387,21 @@ export async function runSandboxPermissionConformance(fixture) {
243
387
  filesystem: scoped(writeRoots),
244
388
  network,
245
389
  });
246
- const full = {
247
- profile: "full-access",
390
+ /**
391
+ * The escalated pair: one call run outside the sandbox (the device filesystem with the
392
+ * environment network). Only an outside-sandbox grant makes it legal, under any profile; the
393
+ * profile names who approved it, nothing more.
394
+ */
395
+ const escalated = {
396
+ profile: "request-approval",
248
397
  filesystem: { kind: "device" },
249
398
  network: { kind: "environment" },
250
399
  };
400
+ const PROFILES = [
401
+ "request-approval",
402
+ "approve-for-me",
403
+ "full-access",
404
+ ];
251
405
  const { granted, ungranted, access } = fixture.endpoints;
252
406
  const proxied = access === "proxy";
253
407
  const allowlisted = { kind: "allowlist", hosts: [granted.name] };
@@ -272,8 +426,285 @@ export async function runSandboxPermissionConformance(fixture) {
272
426
  const connect = (endpoint) => `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(endpoint.address)}, ${endpoint.port}), 10).close()`)}`;
273
427
  /** An HTTP request by name; curl and Python use the environment's proxy when there is one. */
274
428
  const byName = (endpoint) => `curl -fsS -m 10 -o /dev/null http://${endpoint.name}:${endpoint.port}/`;
429
+ const url = (target) => `http://${isIP(target.host) === 6 ? `[${target.host}]` : target.host}:${target.port}/`;
430
+ /**
431
+ * Asks for each target by URL in one sandboxed command and returns the HTTP status per label
432
+ * ("000": no answer at all). `viaProxy`: every request goes to the environment's proxy (curl
433
+ * `--noproxy ''`, overriding a `NO_PROXY` list); otherwise curl follows the environment as an
434
+ * ordinary client does (a `NO_PROXY` entry connects directly, which the sandbox must refuse).
435
+ */
436
+ const probeTargets = async (grant, targets, viaProxy) => {
437
+ if (targets.length === 0)
438
+ return {};
439
+ const noProxy = viaProxy ? "--noproxy '' " : "";
440
+ const result = await exec(grant, targets
441
+ .map((target) => `printf '%s %s\\n' ${quote(target.label)} "$(curl -sS -m 10 ${noProxy}-o /dev/null -w '%{http_code}' ${quote(url(target))} 2>/dev/null)"`)
442
+ .join("; "));
443
+ assert.equal(result.exitCode, 0, `the target probe must run: ${result.stderr}`);
444
+ return Object.fromEntries(result.stdout
445
+ .trim()
446
+ .split("\n")
447
+ .map((line) => line.split(" ")));
448
+ };
449
+ const counts = async (targets) => Promise.all(targets.map(async (target) => (target.receipts ? target.receipts() : 0)));
450
+ const reached = (status) => status !== undefined && /^[23]\d\d$/.test(status);
451
+ /**
452
+ * Every closed target is refused (a proxied provider answers its own 403 before any dial) and
453
+ * none sees a connection; every reachable target answers and, where counted, sees one.
454
+ */
455
+ const proveTargets = async (grant, reachable, closed, what) => {
456
+ const before = await counts([...reachable, ...closed]);
457
+ // as an ordinary client: closed targets stay unreached whatever NO_PROXY says
458
+ const plain = await probeTargets(grant, closed, false);
459
+ for (const target of closed)
460
+ assert(!reached(plain[target.label]), `${what}: ${target.label} (${url(target)}) must not be reached: ${JSON.stringify(plain)}`);
461
+ const statuses = await probeTargets(grant, [...reachable, ...closed], proxied);
462
+ const after = await counts([...reachable, ...closed]);
463
+ reachable.forEach((target, index) => {
464
+ assert(reached(statuses[target.label]), `${what}: ${target.label} (${url(target)}) must be reached: ${JSON.stringify(statuses)}`);
465
+ if (target.receipts)
466
+ assert((after[index] ?? 0) > (before[index] ?? 0), `${what}: ${target.label} must see the connection`);
467
+ });
468
+ closed.forEach((target, offset) => {
469
+ const index = reachable.length + offset;
470
+ const status = statuses[target.label];
471
+ assert(proxied ? status === "403" : !reached(status), `${what}: ${target.label} (${url(target)}) must be refused${proxied ? " by the proxy (403)" : ""}: ${JSON.stringify(statuses)}`);
472
+ assert.equal(after[index], before[index], `${what}: ${target.label} must see no connection`);
473
+ });
474
+ };
475
+ /** The names of the planted device variables a command under `grant` can see, and its names. */
476
+ const environmentOf = async (grant) => {
477
+ const planted = fixture.deviceEnvironment?.variables ?? {};
478
+ const result = await exec(grant, "env");
479
+ assert.equal(result.exitCode, 0, `env must run: ${result.stderr}`);
480
+ const names = result.stdout
481
+ .split("\n")
482
+ .filter((line) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(line))
483
+ .map((line) => line.slice(0, line.indexOf("=")));
484
+ return {
485
+ leaked: Object.entries(planted)
486
+ .filter(([, value]) => result.stdout.includes(value))
487
+ .map(([name]) => name),
488
+ names,
489
+ };
490
+ };
491
+ const leakedVariables = async (grant) => (await environmentOf(grant)).leaked;
492
+ /**
493
+ * A sandboxed command under `grant` sees no planted value and, on an operation boundary, only
494
+ * the minimal environment's names (a denylist would pass the first, never the second).
495
+ */
496
+ const proveMinimalEnvironment = async (grant, minimalNames) => {
497
+ const environment = fixture.deviceEnvironment;
498
+ if (!environment)
499
+ return;
500
+ const { leaked, names } = await environmentOf(grant);
501
+ assert.deepEqual(leaked, [], `${grant.profile}: no device variable reaches a sandboxed command`);
502
+ if (!minimalNames)
503
+ return;
504
+ const allowed = new Set([...MINIMAL_ENVIRONMENT, ...(environment.allowed ?? [])]);
505
+ const extra = names.filter((name) => !allowed.has(name) && !/proxy/i.test(name));
506
+ assert.deepEqual(extra, [], `${grant.profile}: a sandboxed command gets the minimal environment only (PATH, LANG, HOME, ` +
507
+ "TMPDIR/TMP/TEMP, the proxy variables, the stated tool homes), never a filtered copy of " +
508
+ "the device's");
509
+ };
510
+ /** The closed-class names behind allowlist grants, or none (reported unavailable). */
511
+ const closedGrantedTargets = () => {
512
+ const closed = fixture.endpoints.closedGranted;
513
+ if (closed === undefined)
514
+ return [];
515
+ if ("unavailable" in closed)
516
+ return [];
517
+ return closed;
518
+ };
519
+ const namedReachAvailable = () => {
520
+ const reach = fixture.endpoints.namedReach;
521
+ if (reach === undefined || reach === "available")
522
+ return true;
523
+ unavailable.push({ item: "allowlist positive by name", reason: reach.unavailable });
524
+ return false;
525
+ };
526
+ /** The escalated pair is refused before anything runs (typed), and leaves no trace. */
527
+ const escalationRefused = async (what) => {
528
+ const marker = `escalated-${randomUUID()}`;
529
+ await assert.rejects(exec(escalated, `printf ran > ${quote(at(root, marker))}`), (error) => isSandboxScopeDeniedError(error) ||
530
+ isSandboxPermissionUnsupportedError(error) ||
531
+ isSandboxScopeValidationError(error), what);
532
+ assert.equal(await fixture.inspect.readFile(at(root, marker)), null, `${what}: nothing ran`);
533
+ };
534
+ /** A sandboxed filesystem with the environment network is refused as invalid (typed). */
535
+ const environmentPairRefused = async (writeRoots) => {
536
+ const marker = `env-ran-${randomUUID()}`;
537
+ await assert.rejects(exec({
538
+ profile: "full-access",
539
+ filesystem: scoped(writeRoots),
540
+ network: { kind: "environment" },
541
+ }, `printf ran > ${quote(at(root, marker))}`), (error) => isSandboxScopeValidationError(error) || isSandboxScopeDeniedError(error), "the environment network without the device filesystem must be refused before it runs " +
542
+ "(only the escalated pair carries it)");
543
+ assert.equal(await fixture.inspect.readFile(at(root, marker)), null, "nothing ran");
544
+ };
545
+ /** The open network under every profile (approval-only profiles design, "Open network"). */
546
+ const proveOpenNetwork = async (writeRoots) => {
547
+ const open = fixture.openNetwork;
548
+ assert(open, "a provider reporting network.openPublic needs the openNetwork fixture");
549
+ assert(open.closed.length > 0, "the open network needs closed targets");
550
+ // the closed targets cover every closed class (by their literal host or served address)
551
+ const covered = new Set(open.closed
552
+ .map((target) => target.address ?? target.host)
553
+ .filter((host) => isIP(host) !== 0)
554
+ .map((host) => classifyAddress(host)));
555
+ const missing = OPEN_PUBLIC_DENIED_CLASSES.filter((cls) => !covered.has(cls));
556
+ assert.deepEqual(missing, [], "the open network's closed targets cover every closed class");
557
+ const reachable = "unavailable" in open.reachable ? [] : open.reachable;
558
+ if ("unavailable" in open.reachable)
559
+ unavailable.push({
560
+ item: "open network: public targets",
561
+ reason: open.reachable.unavailable,
562
+ });
563
+ const fake = open.fakeIp && !("unavailable" in open.fakeIp) ? open.fakeIp : undefined;
564
+ if (open.fakeIp === undefined)
565
+ unavailable.push({ item: "open network: fake-IP names", reason: "no fakeIp fixture" });
566
+ else if ("unavailable" in open.fakeIp)
567
+ unavailable.push({ item: "open network: fake-IP names", reason: open.fakeIp.unavailable });
568
+ assert(reachable.length + (fake?.reachable.length ?? 0) > 0 || open.allowNoPositive === true, "the open network needs a reachable public target (set allowNoPositive only for an offline run)");
569
+ for (const profile of PROFILES) {
570
+ const grant = {
571
+ profile,
572
+ filesystem: scoped(writeRoots),
573
+ network: { kind: "open-public" },
574
+ };
575
+ await proveTargets(grant, [...reachable, ...(fake?.reachable ?? [])], [...open.closed, ...(fake?.closed ?? [])], `open network (${profile})`);
576
+ if (proxied)
577
+ // only the proxy dials: a raw connect to a public address bypasses it and is refused
578
+ for (const target of reachable.filter((t) => t.address !== undefined)) {
579
+ const raw = await exec(grant, `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(target.address)}, ${target.port}), 10).close()`)}`);
580
+ assert.notEqual(raw.exitCode, 0, `open network (${profile}): raw ${target.label}`);
581
+ }
582
+ }
583
+ };
275
584
  const urlopen = (endpoint) => `python3 -c ${quote(`import urllib.request; urllib.request.urlopen("http://${endpoint.name}:${endpoint.port}/", timeout=10).read()`)}`;
585
+ /** Exact cancellation and timeouts of operations under `grant` (whose roots cover `root`). */
586
+ const proveCancellation = async (grant) => {
587
+ // Exact cancellation: detached descendants end; a sibling operation keeps running.
588
+ const keepAlive = exec(grant, `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
589
+ await waitFor(at(root, "ready-keep"), keepAlive);
590
+ const abort = new AbortController();
591
+ const regrouped = fixture.regroupedDescendants !== "not-promised";
592
+ const cancelled = exec(grant, `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
593
+ `setsid sleep 1002 > /dev/null 2>&1 & ` +
594
+ (regrouped
595
+ ? `python3 -c ${quote("import os, time\nif os.fork() == 0:\n os.setpgid(0, 0)\n open('p3.tmp', 'w').write(str(os.getpid()))\n os.rename('p3.tmp', 'p3')\n time.sleep(1003)")} & ` +
596
+ `until [ -e p3 ]; do sleep 0.01; done; `
597
+ : "") +
598
+ `printf r > ready-cancel; sleep 1004`, abort.signal);
599
+ await waitFor(at(root, "ready-cancel"), cancelled);
600
+ const pids = await Promise.all((regrouped ? ["p1", "p2", "p3"] : ["p1", "p2"]).map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
601
+ assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
602
+ abort.abort();
603
+ const stopped = await cancelled;
604
+ assert.equal(stopped.exitCode, null, "a cancelled operation has no exit code");
605
+ assert.deepEqual(await fixture.inspect.alive(pids), [], "cancellation ends every descendant");
606
+ await exec(grant, "touch release-keep");
607
+ assert.equal((await keepAlive).exitCode, 0, "the sibling operation survives the cancel");
608
+ assert.equal(text(await fixture.inspect.readFile(at(root, "kept"))), "done");
609
+ // Timeout ends the whole owned tree as well.
610
+ const timed = await exec(grant, `(sleep 1005 & echo $! > p4); sleep 1006`, signal, 1000);
611
+ assert.equal(timed.timedOut, true, "a restricted timeout is reported");
612
+ const p4 = Number(text(await fixture.inspect.readFile(at(root, "p4"))));
613
+ assert.deepEqual(await fixture.inspect.alive([p4]), [], "timeout ends background children");
614
+ };
615
+ /**
616
+ * An instance-boundary provider (a cloud device): the container or microVM is the sandbox, its
617
+ * whole filesystem the scope, its outer network the sandbox network. Every profile runs there
618
+ * alike, nothing runs outside it, and the outer network holds for every operation.
619
+ */
620
+ const proveInstanceBoundary = async (support) => {
621
+ assert.equal(support.restricted, null, "an instance boundary has no per-operation restriction");
622
+ assert.equal(support.outsideSandbox, false, "an instance boundary has nothing outside");
623
+ assert.equal(support.network.perOperationHosts, false, "an instance's outer network covers every operation: no per-operation hosts");
624
+ const network = fixture.instanceNetwork;
625
+ assert(network, "an instance-boundary fixture names its outer network (instanceNetwork)");
626
+ const closedGranted = fixture.endpoints.closedGranted;
627
+ assert(Array.isArray(closedGranted) &&
628
+ closedGranted.some((target) => target.address !== undefined && classifyAddress(target.address) === "metadata"), "an instance boundary needs closedGranted with a name served at a cloud metadata address");
629
+ const whole = ["/"];
630
+ const instanceGrant = (profile, kind = network === "open" ? "open-public" : "allowlist") => ({
631
+ profile,
632
+ filesystem: scoped(whole),
633
+ network: kind === "allowlist"
634
+ ? {
635
+ kind: "allowlist",
636
+ hosts: [granted.name, ...closedGrantedTargets().map((t) => t.host)],
637
+ }
638
+ : { kind },
639
+ });
640
+ await fixture.seed([
641
+ { path: at(sibling, "secret"), kind: "file", data: new TextEncoder().encode(secret) },
642
+ ]);
643
+ // nothing runs outside the instance, and the environment network comes only with it
644
+ await escalationRefused("an instance boundary must refuse the escalated pair");
645
+ await environmentPairRefused(whole);
646
+ // every profile runs alike inside: the whole instance is the scope, root and sibling included
647
+ const bytes = new Uint8Array([7, 8, 9]);
648
+ for (const profile of PROFILES) {
649
+ const shell = await exec(instanceGrant(profile), `printf ${profile} > ${quote(at(root, `${profile}.txt`))} && cat ${quote(at(sibling, "secret"))}`);
650
+ assert.equal(shell.exitCode, 0, `${profile} runs in the instance: ${shell.stderr}`);
651
+ assert.equal(shell.stdout, secret, `${profile} reads anywhere in the instance`);
652
+ assert.equal(text(await fixture.inspect.readFile(at(root, `${profile}.txt`))), profile);
653
+ await (await native(instanceGrant(profile))).writeFile(at(sibling, `${profile}.bin`), bytes, signal);
654
+ assert.deepEqual(await (await native(instanceGrant(profile))).readFile(at(sibling, `${profile}.bin`), {
655
+ maxBytes: 10,
656
+ signal,
657
+ }), { data: bytes, truncated: false });
658
+ if (fixture.deviceEnvironment)
659
+ assert.deepEqual(await leakedVariables(instanceGrant(profile)), [], `${profile}: no provider variable reaches a command`);
660
+ }
661
+ // the outer network holds for every operation and profile
662
+ if (network === "open") {
663
+ assert(support.network.openPublic, "an open outer network must be reported as openPublic");
664
+ await proveOpenNetwork(whole);
665
+ }
666
+ else {
667
+ assert(support.network.allowlist, "an allowlist outer network must be reported as allowlist");
668
+ assert(ungranted.length > 0, "an allowlist outer network needs an ungranted endpoint");
669
+ const named = namedReachAvailable();
670
+ for (const profile of PROFILES) {
671
+ const before = await receipts();
672
+ const grant = instanceGrant(profile);
673
+ let positives = 0;
674
+ if (named) {
675
+ const result = await exec(grant, byName(granted));
676
+ assert.equal(result.exitCode, 0, `${profile}: the allowlisted name: ${result.stderr}`);
677
+ positives++;
678
+ }
679
+ for (const endpoint of ungranted)
680
+ for (const command of [connect(endpoint), byName(endpoint)]) {
681
+ const result = await exec(grant, command);
682
+ assert.notEqual(result.exitCode, 0, `${profile}: ungranted ${endpoint.name}: ${command}`);
683
+ }
684
+ // a scope that names an ungranted host widens nothing: the instance's list holds for
685
+ // every operation (no per-operation hosts)
686
+ const asked = {
687
+ ...grant,
688
+ network: {
689
+ kind: "allowlist",
690
+ hosts: [granted.name, ...ungranted.map((endpoint) => endpoint.name)],
691
+ },
692
+ };
693
+ for (const endpoint of ungranted) {
694
+ const result = await exec(asked, byName(endpoint));
695
+ assert.notEqual(result.exitCode, 0, `${profile}: an ungranted name in the scope's hosts must still be refused: ${endpoint.name}`);
696
+ }
697
+ await proveTargets(grant, [], closedGrantedTargets(), `${profile} allowlist`);
698
+ const after = await receipts();
699
+ assert.equal(after[0], (before[0] ?? 0) + positives, `${profile}: granted receipts`);
700
+ assert.deepEqual(after.slice(1), before.slice(1), `${profile}: ungranted see nothing`);
701
+ }
702
+ }
703
+ await proveCancellation(instanceGrant("full-access"));
704
+ };
276
705
  try {
706
+ assert(options.parts === undefined || options.parts.length > 0, "parts must not be empty");
707
+ assert(options.checks === undefined || options.checks.length > 0, "checks must not be empty");
277
708
  for (const [label, endpoint] of [
278
709
  ["granted", granted],
279
710
  ...ungranted.map((endpoint) => ["ungranted", endpoint]),
@@ -285,8 +716,13 @@ export async function runSandboxPermissionConformance(fixture) {
285
716
  assert(isIPv4(granted.address), "the granted endpoint address must be IPv4 (race program)");
286
717
  assert(ungranted.every((endpoint) => endpoint.name !== granted.name), "ungranted endpoints need names other than the granted one");
287
718
  const support = await fixture.support();
719
+ assert.equal(support.version, 2, "permission support must be version 2");
720
+ if (support.boundary === "instance") {
721
+ await proveInstanceBoundary(support);
722
+ return report();
723
+ }
288
724
  if (support.restricted === null) {
289
- // Fail closed: no restricted operation may run, and nothing falls back to Full access.
725
+ // Fail closed: no restricted operation may run, and nothing falls back to the escalated pair.
290
726
  await assert.rejects((async () => (await fixture.operation(restricted())).exec({
291
727
  command: "true",
292
728
  cwd: root,
@@ -294,9 +730,26 @@ export async function runSandboxPermissionConformance(fixture) {
294
730
  maxOutputBytes: 1024,
295
731
  signal,
296
732
  }))(), (error) => isSandboxPermissionUnsupportedError(error), "an unsupported runtime must refuse restricted operations");
297
- return;
733
+ return report();
298
734
  }
299
735
  assert.deepEqual(support.restricted, { filesystem: true, network: true, native: true, concurrentScopes: true }, "restricted support requires all four claims together");
736
+ // the approval-only inputs a provider with restricted support must give the harness
737
+ const planted = fixture.deviceEnvironment?.variables ?? {};
738
+ assert(Object.keys(planted).some((name) => SECRET_LOOKING.test(name)) &&
739
+ Object.keys(planted).some((name) => !SECRET_LOOKING.test(name)), "deviceEnvironment must plant a secret-looking and an innocent-looking variable");
740
+ assert(fixture.endpoints.closedGranted !== undefined, "closedGranted is required (or { unavailable } with the reason)");
741
+ if (Array.isArray(fixture.endpoints.closedGranted))
742
+ assert(fixture.endpoints.closedGranted.length > 0, "closedGranted must not be empty");
743
+ else
744
+ unavailable.push({
745
+ item: "allowlisted names in closed classes",
746
+ reason: fixture.endpoints.closedGranted.unavailable,
747
+ });
748
+ if (support.outsideSandbox)
749
+ assert(fixture.withoutOutsideSandbox, "withoutOutsideSandbox is required with outside-sandbox support");
750
+ assert(fixture.home, "home is required (or { unavailable } with the reason)");
751
+ if ("unavailable" in fixture.home)
752
+ unavailable.push({ item: "protected link chains", reason: fixture.home.unavailable });
300
753
  await fixture.seed([
301
754
  { path: at(sibling, "secret"), kind: "file", data: new TextEncoder().encode(secret) },
302
755
  { path: at(root, "inroot.txt"), kind: "file", data: new TextEncoder().encode("inroot") },
@@ -310,7 +763,7 @@ export async function runSandboxPermissionConformance(fixture) {
310
763
  };
311
764
  // Positive controls: ordinary shell, Python, Node and native work inside the root.
312
765
  const shell = await exec(restricted(), "cat inroot.txt && printf shell > shell.txt && mkdir -p d/e && printf x > d/e/f && " +
313
- "chmod 755 d/e/f && touch -d 2001-01-01 d/e/f && ln -s shell.txt alias && cat alias");
766
+ "chmod 755 d/e/f && touch -t 200101010000 d/e/f && ln -s shell.txt alias && cat alias");
314
767
  assert.equal(shell.exitCode, 0, `restricted shell work must succeed: ${shell.stderr}`);
315
768
  assert.equal(shell.stdout, "inrootshell");
316
769
  assert.equal(await fixture.inspect.mode(at(root, "d/e/f")), 0o755, "chmod inside the root");
@@ -334,161 +787,253 @@ export async function runSandboxPermissionConformance(fixture) {
334
787
  limit: 10,
335
788
  signal,
336
789
  }), { entries: [{ name: "n.bin", isDir: false }], truncated: false });
337
- // Mandatory write denies inside a granted root (the macOS set, shared through the SDK): git
338
- // configuration and hooks (a later unsandboxed `git` there would run them), shell startup
339
- // files and editor/agent configuration. Direct writes, creation, renames, hard and symbolic
340
- // links, and the same paths in a repository the command creates itself all stay refused.
341
- await fixture.seed([
342
- { path: at(root, "repo/.git/config"), kind: "file", data: new TextEncoder().encode("cfg") },
343
- {
344
- path: at(root, "repo/.git/hooks/pre-commit.sample"),
345
- kind: "file",
346
- data: new TextEncoder().encode("s"),
347
- },
348
- { path: at(root, "repo/.git/HEAD"), kind: "file", data: new TextEncoder().encode("ref: x") },
349
- ]);
350
- const evil = '[core]\n\tfsmonitor = "touch escaped; false"\n';
351
- const denies = await exec(restricted(), [
352
- `cd repo`,
353
- `printf ${quote(evil)} > .git/config`,
354
- `printf x >> .git/config`,
355
- `mkdir -p .git/hooks; printf '#!/bin/sh' > .git/hooks/pre-commit`,
356
- `chmod 755 .git/hooks/pre-commit.sample`,
357
- `printf x > staged-config; mv staged-config .git/config`,
358
- `printf x > staged-hook; ln staged-hook .git/hooks/post-checkout`,
359
- `ln -s ../staged-hook .git/hooks/pre-push`,
360
- `ln -s .git/config cfg-link; printf x > cfg-link`,
361
- `mkdir moved; printf x > moved/config; mkdir -p sub; mv moved sub/.git`,
362
- `mkdir -p ../ptr && printf 'gitdir: /tmp' > ../ptr/.git`,
363
- `cd ..; git init -q nested 2>/dev/null; mkdir -p nested/.git/hooks; printf x > nested/.git/hooks/pre-commit; printf x > nested/.git/config`,
364
- `printf x > .bashrc; printf x > .zshrc; printf x > .profile; printf x > .gitconfig; printf x > .gitmodules; printf x > .mcp.json`,
365
- `mkdir -p .vscode && printf x > .vscode/settings.json; mkdir -p .idea && printf x > .idea/x`,
366
- `mkdir -p .claude/commands .claude/agents; printf x > .claude/commands/c.md; printf x > .claude/agents/a.md`,
367
- `mkdir -p deep/er; printf x > deep/er/.bash_profile`,
368
- `printf ok > allowed.txt`,
369
- `true`,
370
- ].join("; "));
371
- assert.equal(denies.exitCode, 0, `the mandatory-deny probe must run: ${denies.stderr}`);
372
- assert.equal(text(await fixture.inspect.readFile(at(root, "allowed.txt"))), "ok", "ordinary writes");
373
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", ".git/config");
374
- assert.equal((await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-commit.sample"))) !== 0o755, true, "hook mode");
375
- for (const path of [
376
- "repo/.git/hooks/pre-commit",
377
- "repo/.git/hooks/post-checkout",
378
- "repo/.git/hooks/pre-push",
379
- "repo/sub/.git/config",
380
- "ptr/.git",
381
- "nested/.git/hooks/pre-commit",
382
- "nested/.git/config",
383
- ".bashrc",
384
- ".zshrc",
385
- ".profile",
386
- ".gitconfig",
387
- ".gitmodules",
388
- ".mcp.json",
389
- ".vscode/settings.json",
390
- ".idea/x",
391
- ".claude/commands/c.md",
392
- ".claude/agents/a.md",
393
- "deep/er/.bash_profile",
394
- ])
395
- assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
396
- assert.equal(await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-push")), null, "a symbolic link into the hooks is refused too");
397
- await denied((await native(restricted())).writeFile(at(root, "repo/.git/config"), bytes, signal), "native write of .git/config");
398
- await denied((await native(restricted())).writeFile(at(root, "repo/.git/hooks/post-merge"), bytes, signal), "native write of a git hook");
399
- await denied((await native(restricted())).writeFile(at(root, ".vscode/tasks.json"), bytes, signal), "native write of editor configuration");
400
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg");
401
- // Inside a .git directory only git's ordinary internals are writable: the gitdirs of
402
- // submodules and worktrees keep their configuration, hooks and pointers too. A bare-repository
403
- // lookalike (a HEAD file outside .git) and moving .git away are refused as well, and the
404
- // matching folds case and Unicode compatibility forms.
405
- await fixture.seed([
406
- {
407
- path: at(root, "repo/.git/modules/sub/config"),
408
- kind: "file",
409
- data: new TextEncoder().encode("cfg"),
410
- },
411
- { path: at(root, "repo/.git/modules/sub/hooks"), kind: "directory" },
412
- { path: at(root, "repo/.git/modules/sub/objects"), kind: "directory" },
413
- {
414
- path: at(root, "repo/.git/worktrees/wt/commondir"),
415
- kind: "file",
416
- data: new TextEncoder().encode("../.."),
417
- },
418
- ]);
419
- const internals = await exec(restricted(), [
420
- "cd repo",
421
- "printf x >> .git/modules/sub/config",
422
- "printf x > .git/modules/sub/hooks/pre-commit",
423
- "printf x > .git/worktrees/wt/commondir",
424
- "printf x > .git/worktrees/wt/config.worktree",
425
- "printf x > .git/worktrees/wt/gitdir",
426
- "printf x > .git/info-attributes-probe; mkdir -p .git/info; printf x > .git/info/attributes",
427
- "printf x > .git/modules/sub/objects/ok-object",
428
- "mkdir -p ../bare/objects ../bare/refs; printf 'ref: refs/heads/main' > ../bare/HEAD; printf x > ../bare/config",
429
- "mv .git ../moved-git; printf x >> ../moved-git/config",
430
- "cd ..",
431
- "printf x > .envrc; printf x > .npmrc; mkdir -p deep; printf x > deep/.npmrc",
432
- "printf x > .BASHRC; printf x > .envrc",
433
- "true",
434
- ].join("; "));
435
- assert.equal(internals.exitCode, 0, `the git-internals probe must run: ${internals.stderr}`);
436
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/config"))), "cfg", "submodule config");
437
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/worktrees/wt/commondir"))), "../..", "worktree commondir");
438
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/objects/ok-object"))), "x", "submodule objects stay writable");
439
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", "moving .git away");
440
- for (const path of [
441
- "repo/.git/modules/sub/hooks/pre-commit",
442
- "repo/.git/worktrees/wt/config.worktree",
443
- "repo/.git/worktrees/wt/gitdir",
444
- "repo/.git/info-attributes-probe",
445
- "repo/.git/info/attributes",
446
- "bare/HEAD",
447
- "moved-git/config",
448
- ".envrc",
449
- ".npmrc",
450
- "deep/.npmrc",
451
- ".BASHRC",
452
- ".envrc",
453
- ])
454
- assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
455
- await denied((await native(restricted())).writeFile(at(root, "repo/.git/modules/sub/config"), bytes, signal), "native write of a submodule's config");
456
- await denied((await native(restricted())).writeFile(at(root, "bare2/HEAD"), bytes, signal), "native write of a bare-repository HEAD");
457
- // No repository can be forged inside git's own allowlisted subtrees, and hook managers
458
- // files stay out of reach.
459
- const forged = await exec(restricted(), [
460
- "cd repo/.git",
461
- "mkdir -p objects/zz/.git/objects objects/zz/.git/refs",
462
- "printf 'ref: refs/heads/main' > objects/zz/.git/HEAD",
463
- "printf x > objects/zz/.git/config",
464
- "mkdir -p objects/yy/objects objects/yy/refs; printf 'ref: refs/heads/main' > objects/yy/HEAD",
465
- "mkdir -p logs/objects; printf ../.. > logs/commondir",
466
- "mkdir -p refs/remotes/o/objects",
467
- "cd ../..",
468
- "mkdir -p .husky .lefthook .githooks .config",
469
- "printf x > .husky/pre-commit; printf x > .pre-commit-config.yaml; printf x > lefthook.yml",
470
- "printf x > .lefthook/x; printf x > .githooks/pre-commit; printf x > .config/lefthook.yml",
471
- "true",
472
- ].join("; "));
473
- assert.equal(forged.exitCode, 0, `the forged-repository probe must run: ${forged.stderr}`);
474
- for (const path of [
475
- "repo/.git/objects/zz/.git/HEAD",
476
- "repo/.git/objects/zz/.git/config",
477
- "repo/.git/objects/yy/HEAD",
478
- "repo/.git/logs/objects",
479
- "repo/.git/logs/commondir",
480
- "repo/.git/refs/remotes/o/objects",
481
- ".husky/pre-commit",
482
- ".pre-commit-config.yaml",
483
- "lefthook.yml",
484
- ".lefthook/x",
485
- ".githooks/pre-commit",
486
- ".config/lefthook.yml",
487
- ])
488
- assert.equal(await fixture.inspect.mode(at(root, path)), null, `mandatory deny: ${path}`);
489
- if (support.fullAccess) {
790
+ // The scope contract: the environment network comes only with the device filesystem (the
791
+ // escalated pair), which runs only with outside-sandbox support and while the owner allows it.
792
+ await environmentPairRefused([root]);
793
+ if (!support.outsideSandbox)
794
+ await escalationRefused("without outside-sandbox support the escalated pair is refused");
795
+ else if (want("outside-switch") && fixture.withoutOutsideSandbox) {
796
+ const restore = await fixture.withoutOutsideSandbox();
797
+ try {
798
+ await escalationRefused("the escalated pair while the owner's outside-sandbox setting is off");
799
+ }
800
+ finally {
801
+ await restore();
802
+ }
803
+ const control = await exec(escalated, `printf ran > ${quote(at(root, "escalated-ran"))}`);
804
+ assert.equal(control.exitCode, 0, `the escalated pair runs again: ${control.stderr}`);
805
+ assert.equal(text(await fixture.inspect.readFile(at(root, "escalated-ran"))), "ran");
806
+ }
807
+ if (whole("filesystem")) {
808
+ // Mandatory write denies inside a granted root (the macOS set, shared through the SDK): git
809
+ // configuration and hooks (a later unsandboxed `git` there would run them), shell startup
810
+ // files and editor/agent configuration. Direct writes, creation, renames, hard and symbolic
811
+ // links, and the same paths in a repository the command creates itself all stay refused.
812
+ await fixture.seed([
813
+ { path: at(root, "repo/.git/config"), kind: "file", data: new TextEncoder().encode("cfg") },
814
+ {
815
+ path: at(root, "repo/.git/hooks/pre-commit.sample"),
816
+ kind: "file",
817
+ data: new TextEncoder().encode("s"),
818
+ },
819
+ {
820
+ path: at(root, "repo/.git/HEAD"),
821
+ kind: "file",
822
+ data: new TextEncoder().encode("ref: x"),
823
+ },
824
+ ]);
825
+ const evil = '[core]\n\tfsmonitor = "touch escaped; false"\n';
826
+ const denies = await exec(restricted(), [
827
+ `cd repo`,
828
+ `printf ${quote(evil)} > .git/config`,
829
+ `printf x >> .git/config`,
830
+ `mkdir -p .git/hooks; printf '#!/bin/sh' > .git/hooks/pre-commit`,
831
+ `chmod 755 .git/hooks/pre-commit.sample`,
832
+ `printf x > staged-config; mv staged-config .git/config`,
833
+ `printf x > staged-hook; ln staged-hook .git/hooks/post-checkout`,
834
+ `ln -s ../staged-hook .git/hooks/pre-push`,
835
+ `ln -s .git/config cfg-link; printf x > cfg-link`,
836
+ `mkdir moved; printf x > moved/config; mkdir -p sub; mv moved sub/.git`,
837
+ `mkdir -p ../ptr && printf 'gitdir: /tmp' > ../ptr/.git`,
838
+ `cd ..; git init -q nested 2>/dev/null; mkdir -p nested/.git/hooks; printf x > nested/.git/hooks/pre-commit; printf x > nested/.git/config`,
839
+ `printf x > .bashrc; printf x > .zshrc; printf x > .profile; printf x > .gitconfig; printf x > .gitmodules; printf x > .mcp.json`,
840
+ `mkdir -p .vscode && printf x > .vscode/settings.json; mkdir -p .idea && printf x > .idea/x`,
841
+ `mkdir -p .claude/commands .claude/agents; printf x > .claude/commands/c.md; printf x > .claude/agents/a.md`,
842
+ `mkdir -p deep/er; printf x > deep/er/.bash_profile`,
843
+ `printf ok > allowed.txt`,
844
+ `true`,
845
+ ].join("; "));
846
+ assert.equal(denies.exitCode, 0, `the mandatory-deny probe must run: ${denies.stderr}`);
847
+ assert.equal(text(await fixture.inspect.readFile(at(root, "allowed.txt"))), "ok", "ordinary writes");
848
+ assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", ".git/config");
849
+ assert.equal((await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-commit.sample"))) !== 0o755, true, "hook mode");
850
+ for (const path of [
851
+ "repo/.git/hooks/pre-commit",
852
+ "repo/.git/hooks/post-checkout",
853
+ "repo/.git/hooks/pre-push",
854
+ "repo/sub/.git/config",
855
+ "ptr/.git",
856
+ "nested/.git/hooks/pre-commit",
857
+ "nested/.git/config",
858
+ ".bashrc",
859
+ ".zshrc",
860
+ ".profile",
861
+ ".gitconfig",
862
+ ".gitmodules",
863
+ ".mcp.json",
864
+ ".vscode/settings.json",
865
+ ".idea/x",
866
+ ".claude/commands/c.md",
867
+ ".claude/agents/a.md",
868
+ "deep/er/.bash_profile",
869
+ ])
870
+ assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
871
+ assert.equal(await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-push")), null, "a symbolic link into the hooks is refused too");
872
+ await denied((await native(restricted())).writeFile(at(root, "repo/.git/config"), bytes, signal), "native write of .git/config");
873
+ await denied((await native(restricted())).writeFile(at(root, "repo/.git/hooks/post-merge"), bytes, signal), "native write of a git hook");
874
+ await denied((await native(restricted())).writeFile(at(root, ".vscode/tasks.json"), bytes, signal), "native write of editor configuration");
875
+ assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg");
876
+ // Inside a .git directory only git's ordinary internals are writable: the gitdirs of
877
+ // submodules and worktrees keep their configuration, hooks and pointers too. A bare-repository
878
+ // lookalike (a HEAD file outside .git) and moving .git away are refused as well, and the
879
+ // matching folds case and Unicode compatibility forms.
880
+ await fixture.seed([
881
+ {
882
+ path: at(root, "repo/.git/modules/sub/config"),
883
+ kind: "file",
884
+ data: new TextEncoder().encode("cfg"),
885
+ },
886
+ { path: at(root, "repo/.git/modules/sub/hooks"), kind: "directory" },
887
+ { path: at(root, "repo/.git/modules/sub/objects"), kind: "directory" },
888
+ {
889
+ path: at(root, "repo/.git/worktrees/wt/commondir"),
890
+ kind: "file",
891
+ data: new TextEncoder().encode("../.."),
892
+ },
893
+ ]);
894
+ const internals = await exec(restricted(), [
895
+ "cd repo",
896
+ "printf x >> .git/modules/sub/config",
897
+ "printf x > .git/modules/sub/hooks/pre-commit",
898
+ "printf x > .git/worktrees/wt/commondir",
899
+ "printf x > .git/worktrees/wt/config.worktree",
900
+ "printf x > .git/worktrees/wt/gitdir",
901
+ "printf x > .git/info-attributes-probe; mkdir -p .git/info; printf x > .git/info/attributes",
902
+ "printf x > .git/modules/sub/objects/ok-object",
903
+ "mkdir -p ../bare/objects ../bare/refs; printf 'ref: refs/heads/main' > ../bare/HEAD; printf x > ../bare/config",
904
+ "mv .git ../moved-git; printf x >> ../moved-git/config",
905
+ "cd ..",
906
+ "printf x > .envrc; printf x > .npmrc; mkdir -p deep; printf x > deep/.npmrc",
907
+ "printf x > .BASHRC; printf x > .envrc",
908
+ "true",
909
+ ].join("; "));
910
+ assert.equal(internals.exitCode, 0, `the git-internals probe must run: ${internals.stderr}`);
911
+ assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/config"))), "cfg", "submodule config");
912
+ assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/worktrees/wt/commondir"))), "../..", "worktree commondir");
913
+ assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/objects/ok-object"))), "x", "submodule objects stay writable");
914
+ assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", "moving .git away");
915
+ for (const path of [
916
+ "repo/.git/modules/sub/hooks/pre-commit",
917
+ "repo/.git/worktrees/wt/config.worktree",
918
+ "repo/.git/worktrees/wt/gitdir",
919
+ "repo/.git/info-attributes-probe",
920
+ "repo/.git/info/attributes",
921
+ "bare/HEAD",
922
+ "moved-git/config",
923
+ ".envrc",
924
+ ".npmrc",
925
+ "deep/.npmrc",
926
+ ...(fixture.foldedNames === "filesystem" ? [".bashrc"] : [".BASHRC", ".envrc"]),
927
+ ])
928
+ assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
929
+ if (fixture.foldedNames === "filesystem") {
930
+ // fullwidth spellings are their own files on such a filesystem, never the protected ones
931
+ for (const path of [".BASHRC", ".envrc"])
932
+ assert.equal(text(await fixture.inspect.readFile(at(root, path))), "x", `distinct ${path}`);
933
+ }
934
+ await denied((await native(restricted())).writeFile(at(root, "repo/.git/modules/sub/config"), bytes, signal), "native write of a submodule's config");
935
+ await denied((await native(restricted())).writeFile(at(root, "bare2/HEAD"), bytes, signal), "native write of a bare-repository HEAD");
936
+ // No repository can be forged inside git's own allowlisted subtrees, and hook managers
937
+ // files stay out of reach.
938
+ const forged = await exec(restricted(), [
939
+ "cd repo/.git",
940
+ "mkdir -p objects/zz/.git/objects objects/zz/.git/refs",
941
+ "printf 'ref: refs/heads/main' > objects/zz/.git/HEAD",
942
+ "printf x > objects/zz/.git/config",
943
+ "mkdir -p objects/yy/objects objects/yy/refs; printf 'ref: refs/heads/main' > objects/yy/HEAD",
944
+ "mkdir -p logs/objects; printf ../.. > logs/commondir",
945
+ "mkdir -p refs/remotes/o/objects",
946
+ "cd ../..",
947
+ "mkdir -p .husky .lefthook .githooks .config",
948
+ "printf x > .husky/pre-commit; printf x > .pre-commit-config.yaml; printf x > lefthook.yml",
949
+ "printf x > .lefthook/x; printf x > .githooks/pre-commit; printf x > .config/lefthook.yml",
950
+ "true",
951
+ ].join("; "));
952
+ assert.equal(forged.exitCode, 0, `the forged-repository probe must run: ${forged.stderr}`);
953
+ for (const path of [
954
+ "repo/.git/objects/zz/.git/HEAD",
955
+ "repo/.git/objects/zz/.git/config",
956
+ "repo/.git/objects/yy/HEAD",
957
+ "repo/.git/logs/objects",
958
+ "repo/.git/logs/commondir",
959
+ "repo/.git/refs/remotes/o/objects",
960
+ ".husky/pre-commit",
961
+ ".pre-commit-config.yaml",
962
+ "lefthook.yml",
963
+ ".lefthook/x",
964
+ ".githooks/pre-commit",
965
+ ".config/lefthook.yml",
966
+ ])
967
+ assert.equal(await fixture.inspect.mode(at(root, path)), null, `mandatory deny: ${path}`);
968
+ }
969
+ if (want("reserved-names")) {
970
+ // The reserved staging prefix (the Linux broker's staging and quarantine names) is denied to
971
+ // every sandboxed write, at any depth and in any case; a name merely containing it is not.
972
+ const reserved = SANDBOX_RESERVED_NAME_PREFIX;
973
+ const upper = reserved.toUpperCase();
974
+ const staging = await exec(restricted(), [
975
+ `mkdir ${reserved}a`,
976
+ `printf x > ${reserved}b`,
977
+ `mkdir -p deep/${upper}c`,
978
+ `printf x > deep/${upper}d`,
979
+ "mkdir -p plain-dir",
980
+ `mv plain-dir ${reserved}e`,
981
+ `printf ok > not${reserved}f`,
982
+ "true",
983
+ ].join("; "));
984
+ assert.equal(staging.exitCode, 0, `the reserved-name probe must run: ${staging.stderr}`);
985
+ for (const path of [
986
+ `${reserved}a`,
987
+ `${reserved}b`,
988
+ `deep/${upper}c`,
989
+ `deep/${upper}d`,
990
+ `${reserved}e`,
991
+ ])
992
+ assert.equal(await fixture.inspect.mode(at(root, path)), null, `reserved name: ${path}`);
993
+ assert.notEqual(await fixture.inspect.mode(at(root, "plain-dir")), null, "the move was refused");
994
+ assert.equal(text(await fixture.inspect.readFile(at(root, `not${reserved}f`))), "ok");
995
+ await denied((await native(restricted())).writeFile(at(root, `${reserved}n`), bytes, signal), "native write of a reserved name");
996
+ }
997
+ // A protected home location linked into the granted root (a dotfile manager's chain): every
998
+ // link on the chain and the target are denied, and no hop can be retargeted or moved away.
999
+ if (want("link-chain") && fixture.home && "path" in fixture.home) {
1000
+ const home = fixture.home;
1001
+ const chain = at(root, "dotfiles");
1002
+ await fixture.seed([
1003
+ { path: at(chain, "v1/zprofile"), kind: "file", data: new TextEncoder().encode("rc1") },
1004
+ { path: at(chain, "v2/zprofile"), kind: "file", data: new TextEncoder().encode("rc2") },
1005
+ { path: at(chain, "current"), kind: "symlink", target: "v1" },
1006
+ {
1007
+ path: at(home.path, ".zprofile"),
1008
+ kind: "symlink",
1009
+ target: at(chain, "current/zprofile"),
1010
+ },
1011
+ ]);
1012
+ try {
1013
+ const hops = await exec(restricted(), [
1014
+ "cd dotfiles",
1015
+ "(printf x >> v1/zprofile) 2>/dev/null && echo wrote-target",
1016
+ "(printf x > current/zprofile) 2>/dev/null && echo wrote-through",
1017
+ "ln -sfn v2 current 2>/dev/null && echo retargeted",
1018
+ "mv current c2 2>/dev/null && echo moved-link",
1019
+ "rm current 2>/dev/null && echo removed-link",
1020
+ "mv v1 gone 2>/dev/null && echo moved-target",
1021
+ "cd .. && mv dotfiles gone 2>/dev/null && echo moved-ancestor",
1022
+ "true",
1023
+ ].join("; "));
1024
+ assert.equal(hops.exitCode, 0, `the link-chain probe must run: ${hops.stderr}`);
1025
+ assert.equal(hops.stdout.trim(), "", `no hop of a protected chain is writable: ${hops.stdout}`);
1026
+ assert.equal(text(await fixture.inspect.readFile(at(chain, "current/zprofile"))), "rc1");
1027
+ assert.equal(text(await fixture.inspect.readFile(at(chain, "v2/zprofile"))), "rc2");
1028
+ await denied((await native(restricted())).writeFile(at(chain, "v1/zprofile"), bytes, signal), "native write of a protected chain's target");
1029
+ }
1030
+ finally {
1031
+ await home.remove(at(home.path, ".zprofile"));
1032
+ }
1033
+ }
1034
+ if (whole("filesystem") && support.outsideSandbox) {
490
1035
  // ordinary git work in a restricted repository keeps working under these rules
491
- await exec(full, `cd ${quote(root)} && git init -q work && git -C work -c user.name=t -c user.email=t@t commit -q --allow-empty -m init`);
1036
+ await exec(escalated, `cd ${quote(root)} && git init -q work && git -C work -c user.name=t -c user.email=t@t commit -q --allow-empty -m init`);
492
1037
  const git = await exec(restricted(), "cd work && printf a > f && git add f && git -c user.name=t -c user.email=t@t commit -qm m && " +
493
1038
  "git checkout -qb topic && git status --short && git log --oneline | wc -l");
494
1039
  assert.equal(git.exitCode, 0, `ordinary restricted git work: ${git.stderr}`);
@@ -500,129 +1045,269 @@ export async function runSandboxPermissionConformance(fixture) {
500
1045
  "g pack-refs --all && g gc -q && git stash list | wc -l");
501
1046
  assert.equal(housekeeping.exitCode, 0, `restricted stash, pack-refs and gc: ${housekeeping.stderr}`);
502
1047
  }
503
- // Negative controls: sibling, symlink escapes and protected paths stay out of reach.
504
- const reads = await exec(restricted(), `cat ${quote(at(sibling, "secret"))}; cat escape; cat linked/secret; true`);
505
- assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
506
- await exec(restricted(), `printf pwn > ${quote(at(sibling, "w1"))}; printf pwn > linked/w2; printf pwn > escape; ` +
507
- `chmod 777 ${quote(at(sibling, "secret"))}; chmod 777 escape; ` +
508
- `touch -d 2001-01-01 ${quote(at(sibling, "secret"))}; true`);
509
- assert.equal(await fixture.inspect.readFile(at(sibling, "w1")), null, "sibling write");
510
- assert.equal(await fixture.inspect.readFile(at(sibling, "w2")), null, "symlinked dir write");
511
- await siblingIntact("restricted writes and chmod must not change the sibling");
512
- for (const path of fixture.protectedPaths) {
513
- const before = text(await fixture.inspect.readFile(path));
514
- await exec(restricted(), `printf pwn >> ${quote(path)}; true`);
515
- assert.equal(text(await fixture.inspect.readFile(path)), before, `protected ${path}`);
516
- }
517
- await denied((await native(restricted())).readFile(at(sibling, "secret"), { maxBytes: 100, signal }), "native sibling read");
518
- await denied((await native(restricted())).readFile(at(root, "escape"), { maxBytes: 100, signal }), "native symlink escape read");
519
- await denied((await native(restricted())).writeFile(at(sibling, "n1"), bytes, signal), "native sibling write");
520
- await denied((await native(restricted())).writeFile(at(root, "linked/n2"), bytes, signal), "native write through a directory symlink");
521
- await denied((await native(restricted())).stat(at(sibling, "secret"), signal), "stat");
522
- await denied((await native(restricted())).list(sibling, { limit: 5, signal }), "list");
523
- await siblingIntact("native denials must leave the sibling unchanged");
524
- // Network: only the granted endpoint, and only while allowlisted.
525
- const base = await receipts();
526
- const positives = proxied
527
- ? [byName(granted), urlopen(granted)]
528
- : [
529
- connect(granted),
530
- `curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
531
- `node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
532
- ];
533
- for (const command of positives) {
534
- const result = await exec(restricted(allowlisted), command);
535
- assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
536
- }
537
- for (const endpoint of ungranted) {
538
- // Raw connects to an ungranted address fail; through a proxy, so does a request by name.
539
- for (const command of proxied ? [connect(endpoint), byName(endpoint)] : [connect(endpoint)]) {
540
- const result = await exec(restricted(allowlisted), command);
541
- assert.notEqual(result.exitCode, 0, `ungranted ${endpoint.name}: ${command}`);
1048
+ if (whole("filesystem")) {
1049
+ // Negative controls: sibling, symlink escapes and protected paths stay out of reach.
1050
+ const reads = await exec(restricted(), `cat ${quote(at(sibling, "secret"))}; cat escape; cat linked/secret; true`);
1051
+ assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
1052
+ await exec(restricted(), `printf pwn > ${quote(at(sibling, "w1"))}; printf pwn > linked/w2; printf pwn > escape; ` +
1053
+ `chmod 777 ${quote(at(sibling, "secret"))}; chmod 777 escape; ` +
1054
+ `touch -t 200101010000 ${quote(at(sibling, "secret"))}; true`);
1055
+ assert.equal(await fixture.inspect.readFile(at(sibling, "w1")), null, "sibling write");
1056
+ assert.equal(await fixture.inspect.readFile(at(sibling, "w2")), null, "symlinked dir write");
1057
+ await siblingIntact("restricted writes and chmod must not change the sibling");
1058
+ for (const path of fixture.protectedPaths) {
1059
+ const before = text(await fixture.inspect.readFile(path));
1060
+ await exec(restricted(), `printf pwn >> ${quote(path)}; true`);
1061
+ assert.equal(text(await fixture.inspect.readFile(path)), before, `protected ${path}`);
1062
+ }
1063
+ await denied((await native(restricted())).readFile(at(sibling, "secret"), { maxBytes: 100, signal }), "native sibling read");
1064
+ await denied((await native(restricted())).readFile(at(root, "escape"), { maxBytes: 100, signal }), "native symlink escape read");
1065
+ await denied((await native(restricted())).writeFile(at(sibling, "n1"), bytes, signal), "native sibling write");
1066
+ await denied((await native(restricted())).writeFile(at(root, "linked/n2"), bytes, signal), "native write through a directory symlink");
1067
+ await denied((await native(restricted())).stat(at(sibling, "secret"), signal), "stat");
1068
+ await denied((await native(restricted())).list(sibling, { limit: 5, signal }), "list");
1069
+ await siblingIntact("native denials must leave the sibling unchanged");
1070
+ // Every profile is sandboxed: Full access only skips the approvals, never the sandbox. Under
1071
+ // each profile a call keeps the scope, the fixed denies, the network and the minimal
1072
+ // environment (no device variable reaches it).
1073
+ {
1074
+ const before = await receipts();
1075
+ for (const profile of PROFILES) {
1076
+ const grant = {
1077
+ profile,
1078
+ filesystem: scoped([root]),
1079
+ network: { kind: "none" },
1080
+ };
1081
+ const probe = await exec(grant, [
1082
+ `cat ${quote(at(sibling, "secret"))}`,
1083
+ `printf pwn > ${quote(at(sibling, `profile-${profile}`))}`,
1084
+ ...fixture.protectedPaths.map((path) => `printf pwn >> ${quote(path)}`),
1085
+ connect(ungranted[0] ?? granted),
1086
+ `printf ok > ${quote(`in-root-${profile}`)}`,
1087
+ "true",
1088
+ ].join("; "));
1089
+ assert.equal(probe.exitCode, 0, `${profile}: the probe must run: ${probe.stderr}`);
1090
+ assert(!probe.stdout.includes(secret), `${profile}: the sibling stays out of reach`);
1091
+ assert.equal(await fixture.inspect.readFile(at(sibling, `profile-${profile}`)), null);
1092
+ assert.equal(text(await fixture.inspect.readFile(at(root, `in-root-${profile}`))), "ok");
1093
+ await denied((await native(grant)).readFile(at(sibling, "secret"), { maxBytes: 100, signal }), `${profile}: native sibling read`);
1094
+ }
1095
+ for (const path of fixture.protectedPaths)
1096
+ assert(!text(await fixture.inspect.readFile(path))?.includes("pwn"), `protected ${path} under every profile`);
1097
+ assert.deepEqual(await receipts(), before, "no profile reaches an endpoint on network none");
1098
+ await siblingIntact("every profile leaves the sibling unchanged");
542
1099
  }
543
1100
  }
544
- if (proxied) {
545
- // allowlisted traffic goes through the proxy: a raw connect to the granted address bypasses
546
- // it and must be refused as well
547
- const raw = await exec(restricted(allowlisted), connect(granted));
548
- assert.notEqual(raw.exitCode, 0, `a proxied provider must refuse a raw connect: ${granted.name}`);
549
- }
550
- for (const command of [connect(granted), byName(granted)]) {
551
- const none = await exec(restricted(), command);
552
- assert.notEqual(none.exitCode, 0, `network none must refuse even the granted endpoint: ${command}`);
553
- }
554
- const after = await receipts();
555
- assert.equal(after[0], (base[0] ?? 0) + positives.length, "granted endpoint receipts");
556
- assert.deepEqual(after.slice(1), base.slice(1), "ungranted endpoints must see no connection");
557
- // Restricted network none/allowlist may listen on loopback only.
558
- for (const network of [{ kind: "none" }, allowlisted]) {
559
- const binds = await exec(restricted(network), `python3 -c ${quote(BIND_PROGRAM)}`);
560
- assert.equal(binds.stdout.trim(), "127.0.0.1=ok ::1=ok 0.0.0.0=denied ::=denied unspec=denied", `restricted ${network.kind} binds loopback only: ${binds.stderr}`);
1101
+ // The minimal environment under every profile: no planted value and no name beyond the
1102
+ // minimal set; the planted values are real (an escalated call sees them).
1103
+ if (want("environment")) {
1104
+ for (const profile of PROFILES)
1105
+ await proveMinimalEnvironment({ profile, filesystem: scoped([root]), network: { kind: "none" } }, true);
1106
+ if (fixture.deviceEnvironment?.escalatedControl && support.outsideSandbox) {
1107
+ // the planted values are real: an escalated call (outside the sandbox) sees them, except
1108
+ // the device's own CAPYBARA_ variables
1109
+ const seen = await leakedVariables(escalated);
1110
+ const planted = Object.keys(fixture.deviceEnvironment.variables);
1111
+ assert.deepEqual(seen.sort(), planted.filter((name) => !/^CAPYBARA_/.test(name)).sort(), "an escalated call gets the device environment minus every CAPYBARA_ variable");
1112
+ }
561
1113
  }
562
- // Pathname UNIX sockets: a service outside the roots is unreachable under every network kind
563
- // (including environment, which lifts only the network filter); one inside the root works.
564
- if (support.fullAccess) {
565
- const server = new AbortController();
566
- const outside = exec(full, `python3 -c ${quote(UNIX_SERVER)} ${quote(at(sibling, "srv.sock"))} ${quote(at(sibling, "srv.count"))}`, server.signal);
567
- await waitFor(at(sibling, "srv.count"), outside);
568
- await fixture.seed([
569
- { path: at(root, "srv-link.sock"), kind: "symlink", target: at(sibling, "srv.sock") },
570
- ]);
571
- if (fixture.restrictedEnvironment === "refused") {
572
- // the policy refusal is the result: a typed scope denial before anything runs
573
- await denied(exec(restricted({ kind: "environment" }), `printf ran > ${quote(at(root, "env-ran"))}`), "a restricted environment-network operation must be refused by policy");
574
- assert.equal(await fixture.inspect.readFile(at(root, "env-ran")), null);
1114
+ {
1115
+ if (whole("network")) {
1116
+ // Network: only the granted endpoint, and only while allowlisted.
1117
+ const base = await receipts();
1118
+ const namedReach = namedReachAvailable();
1119
+ const positives = !namedReach
1120
+ ? []
1121
+ : proxied
1122
+ ? [byName(granted), urlopen(granted)]
1123
+ : [
1124
+ connect(granted),
1125
+ `curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
1126
+ `node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
1127
+ ];
1128
+ for (const command of positives) {
1129
+ const result = await exec(restricted(allowlisted), command);
1130
+ assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
1131
+ }
1132
+ for (const endpoint of ungranted) {
1133
+ // Raw connects to an ungranted address fail; through a proxy, so does a request by name.
1134
+ for (const command of proxied
1135
+ ? [connect(endpoint), byName(endpoint)]
1136
+ : [connect(endpoint)]) {
1137
+ const result = await exec(restricted(allowlisted), command);
1138
+ assert.notEqual(result.exitCode, 0, `ungranted ${endpoint.name}: ${command}`);
1139
+ }
1140
+ }
1141
+ if (proxied) {
1142
+ // allowlisted traffic goes through the proxy: a raw connect to the granted address bypasses
1143
+ // it and must be refused as well
1144
+ const raw = await exec(restricted(allowlisted), connect(granted));
1145
+ assert.notEqual(raw.exitCode, 0, `a proxied provider must refuse a raw connect: ${granted.name}`);
1146
+ }
1147
+ for (const command of [connect(granted), byName(granted)]) {
1148
+ const none = await exec(restricted(), command);
1149
+ assert.notEqual(none.exitCode, 0, `network none must refuse even the granted endpoint: ${command}`);
1150
+ }
1151
+ const after = await receipts();
1152
+ assert.equal(after[0], (base[0] ?? 0) + positives.length, "granted endpoint receipts");
1153
+ assert.deepEqual(after.slice(1), base.slice(1), "ungranted endpoints must see no connection");
1154
+ }
1155
+ // An allowlist grant never reaches a closed address class, not even for a granted name.
1156
+ const closedGranted = closedGrantedTargets();
1157
+ if (want("closed-granted") && closedGranted.length > 0) {
1158
+ const before = await receipts();
1159
+ await proveTargets(restricted({
1160
+ kind: "allowlist",
1161
+ hosts: [granted.name, ...closedGranted.map((t) => t.host)],
1162
+ }), [], closedGranted, "allowlisted names resolving into a closed class");
1163
+ assert.deepEqual(await receipts(), before, "no endpoint sees a closed-class grant");
575
1164
  }
576
- for (const network of [
577
- { kind: "none" },
578
- allowlisted,
579
- ...(fixture.restrictedEnvironment === "refused" ? [] : [{ kind: "environment" }]),
580
- ]) {
581
- const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
582
- assert.equal(probe.stdout.trim(), "stream=denied seqpacket=denied dgram=denied raw=denied link=denied pair-dgram=denied pair-raw=denied", `restricted ${network.kind} must not reach a UNIX service outside the roots: ${probe.stderr}`);
583
- const inside = await exec(restricted(network), `python3 -c ${quote(UNIX_ROUNDTRIP)} ${quote(at(root, `own-${network.kind}.sock`))}`);
584
- assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
1165
+ if (want("loopback")) {
1166
+ // Restricted network none/allowlist may listen on loopback only.
1167
+ for (const network of [{ kind: "none" }, allowlisted]) {
1168
+ const binds = await exec(restricted(network), `python3 -c ${quote(BIND_PROGRAM)}`);
1169
+ assert.equal(binds.stdout.trim(), fixture.restrictedLoopbackListen === "refused"
1170
+ ? "127.0.0.1=denied ::1=denied 0.0.0.0=denied ::=denied unspec=denied"
1171
+ : "127.0.0.1=ok ::1=ok 0.0.0.0=denied ::=denied unspec=denied", `restricted ${network.kind} binds loopback only: ${binds.stderr}`);
1172
+ }
1173
+ if (fixture.restrictedLoopbackListen !== "refused") {
1174
+ // No sandboxed client connects to a loopback listener, its own included (a listener cannot
1175
+ // be told from another process's at the address dialled), and no reuseport group is joined.
1176
+ for (const network of [{ kind: "none" }, allowlisted]) {
1177
+ const own = await exec(restricted(network), `python3 -c ${quote(OWN_LOOPBACK)}`);
1178
+ assert.equal(own.exitCode, 0, `the own-loopback probe must run: ${own.stderr}`);
1179
+ assert.deepEqual(JSON.parse(own.stdout), { "own 127.0.0.1": "denied", "own ::1": "denied", reuseport: "denied" }, `restricted ${network.kind}: no loopback connect, no SO_REUSEPORT`);
1180
+ }
1181
+ if (support.outsideSandbox) {
1182
+ // a client outside the sandbox (an escalated call) reaches the command's listener
1183
+ const portFile = at(root, "loopback-port");
1184
+ const service = exec(restricted(), `python3 -c ${quote(LOOPBACK_SERVICE)} ${quote(portFile)}`);
1185
+ await waitFor(portFile, service);
1186
+ const port = Number(text(await fixture.inspect.readFile(portFile)));
1187
+ const client = await exec(escalated, `python3 -c ${quote(`import socket\ns = socket.create_connection(("127.0.0.1", ${port}), 10)\ns.sendall(b"from-outside")\ns.close()`)}`);
1188
+ assert.equal(client.exitCode, 0, `the outside client must connect: ${client.stderr}`);
1189
+ const served = await service;
1190
+ assert.equal(served.stdout.trim(), "from-outside", `the listener serves it: ${served.stderr}`);
1191
+ }
1192
+ }
1193
+ }
1194
+ if (want("open-network") && support.network.openPublic)
1195
+ await proveOpenNetwork([root]);
1196
+ // A UNIX socket another process made inside a write root (a user D-Bus, a rootless
1197
+ // docker.sock, ssh-agent or tmux in a granted directory) is code execution outside the
1198
+ // sandbox: no sandboxed command connects to it, under any sandbox network. An escalated call
1199
+ // stands in for that process; the same client there proves the probe is real.
1200
+ if (want("foreign-unix") && support.outsideSandbox) {
1201
+ const server = new AbortController();
1202
+ const outside = exec(escalated, `python3 -c ${quote(UNIX_SERVER)} foreign.sock foreign.count`, server.signal);
1203
+ try {
1204
+ await waitFor(at(root, "foreign.count"), outside);
1205
+ const client = `python3 -c ${quote(FOREIGN_UNIX_CLIENT)} foreign.sock ${quote(at(root, "foreign.sock"))}`;
1206
+ for (const network of [{ kind: "none" }, allowlisted]) {
1207
+ const probe = await exec(restricted(network), client);
1208
+ const reached = probe.stdout
1209
+ .trim()
1210
+ .split(" ")
1211
+ .slice(1)
1212
+ .filter((entry) => entry.endsWith("=ok"));
1213
+ assert.equal(probe.stdout.trim().startsWith("foreign-unix-client stream=") && reached.length === 0, true, `restricted ${network.kind} must not connect to a socket another process made in the root: ${probe.stdout} ${probe.stderr}`);
1214
+ }
1215
+ assert.equal(text(await fixture.inspect.readFile(at(root, "foreign.count"))), "0", "the foreign UNIX service in the root must see no sandboxed client");
1216
+ const control = await exec(escalated, client);
1217
+ assert.match(control.stdout, /^foreign-unix-client stream=ok /, `the escalated control reaches the foreign UNIX service: ${control.stderr}`);
1218
+ }
1219
+ finally {
1220
+ server.abort();
1221
+ await outside.catch(() => undefined);
1222
+ }
1223
+ }
1224
+ // Pathname UNIX sockets: a service outside the roots (run by an escalated call) is unreachable
1225
+ // under every sandbox network; one inside the root works.
1226
+ if (whole("network") && support.outsideSandbox) {
1227
+ const server = new AbortController();
1228
+ const outside = exec(escalated, `python3 -c ${quote(UNIX_SERVER)} ${quote(at(sibling, "srv.sock"))} ${quote(at(sibling, "srv.count"))}`, server.signal);
1229
+ await waitFor(at(sibling, "srv.count"), outside);
1230
+ await fixture.seed([
1231
+ { path: at(root, "srv-link.sock"), kind: "symlink", target: at(sibling, "srv.sock") },
1232
+ ]);
1233
+ // The OS's own UNIX socket types, probed outside every restriction (unsupported types are
1234
+ // reported as such by an escalated call and expected the same in restricted operations)
1235
+ const types = await exec(escalated, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "missing.sock"))} missing-link.sock`);
1236
+ const kinds = types.stdout
1237
+ .trim()
1238
+ .split(" ")
1239
+ .map((entry) => entry.split("="));
1240
+ for (const name of ["stream", "dgram", "link"])
1241
+ assert.notEqual(kinds.find(([kind]) => kind === name)?.[1], "unsupported", `UNIX ${name} sockets are required: ${types.stdout} ${types.stderr}`);
1242
+ const expectWhen = (reachable) => kinds
1243
+ .map(([kind, state]) => state === "unsupported"
1244
+ ? `${kind}=unsupported`
1245
+ : `${kind}=${reachable ? "ok" : "denied"}`)
1246
+ .join(" ");
1247
+ for (const network of [{ kind: "none" }, allowlisted]) {
1248
+ const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
1249
+ assert.equal(
1250
+ // a type the OS lacks may also be refused before the OS says so: both reach nothing
1251
+ probe.stdout
1252
+ .trim()
1253
+ .split(" ")
1254
+ .map((entry) => entry.endsWith("=denied") &&
1255
+ kinds.some(([kind, state]) => `${kind}=denied` === entry && state === "unsupported")
1256
+ ? entry.replace("=denied", "=unsupported")
1257
+ : entry)
1258
+ .join(" "), expectWhen(false), `restricted ${network.kind} must not reach a UNIX service outside the roots: ${probe.stderr}`);
1259
+ const inside = await exec(restricted(network), `python3 -c ${quote(UNIX_ROUNDTRIP)} ${quote(at(root, `own-${network.kind}.sock`))}`);
1260
+ if (fixture.restrictedLoopbackListen === "refused")
1261
+ // no listener at all: binding a UNIX socket fails before any roundtrip
1262
+ assert.notEqual(inside.stdout.trim(), "roundtrip=ok", "no restricted UNIX listener");
1263
+ else
1264
+ assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
1265
+ }
1266
+ assert.equal(text(await fixture.inspect.readFile(at(sibling, "srv.count"))), "0", "the outside UNIX service must see no client");
1267
+ // The same client in an escalated call reaches the service seven times: the probe is real.
1268
+ const control = await exec(escalated, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
1269
+ assert.equal(control.stdout.trim(), expectWhen(true), `escalated UNIX control: ${control.stderr}`);
1270
+ const reached = String(kinds.filter(([, state]) => state !== "unsupported").length);
1271
+ await waitForFile(async (path) => {
1272
+ const data = await fixture.inspect.readFile(path);
1273
+ return text(data) === reached ? data : null;
1274
+ }, at(sibling, "srv.count"), outside);
1275
+ server.abort();
1276
+ await outside;
585
1277
  }
586
- assert.equal(text(await fixture.inspect.readFile(at(sibling, "srv.count"))), "0", "the outside UNIX service must see no client");
587
- // The same client under Full access reaches the service seven times: the probe is real.
588
- const control = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
589
- assert.equal(control.stdout.trim(), "stream=ok seqpacket=ok dgram=ok raw=ok link=ok pair-dgram=ok pair-raw=ok", `Full UNIX control: ${control.stderr}`);
590
- await waitForFile(async (path) => {
591
- const data = await fixture.inspect.readFile(path);
592
- return text(data) === "7" ? data : null;
593
- }, at(sibling, "srv.count"), outside);
594
- server.abort();
595
- await outside;
596
1278
  }
597
- // Full access controls on the same device: no restricted filters apply.
598
- if (support.fullAccess) {
599
- const control = await exec(full, `cat ${quote(at(sibling, "secret"))} && printf full > ${quote(at(sibling, "full"))} && ${connect(ungranted[0] ?? granted)}`);
600
- assert.equal(control.exitCode, 0, `Full access control must succeed: ${control.stderr}`);
601
- assert(control.stdout.includes(secret), "Full access reads the sibling");
1279
+ if (!whole("processes"))
1280
+ return report();
1281
+ // Escalated-pair controls on the same device: outside the sandbox no restricted filter applies.
1282
+ if (support.outsideSandbox) {
1283
+ const before = await receipts();
1284
+ const control = await exec(escalated, `cat ${quote(at(sibling, "secret"))} && printf full > ${quote(at(sibling, "full"))} && ${connect(ungranted[0] ?? granted)}`);
1285
+ assert.equal(control.exitCode, 0, `the escalated control must succeed: ${control.stderr}`);
1286
+ assert(control.stdout.includes(secret), "the escalated call reads the sibling");
602
1287
  assert.equal(text(await fixture.inspect.readFile(at(sibling, "full"))), "full");
603
- assert.equal((await receipts())[1], (after[1] ?? 0) + 1, "Full reaches an ungranted endpoint");
1288
+ assert.equal((await receipts())[1], (before[1] ?? 0) + 1, "the escalated call reaches an ungranted endpoint");
604
1289
  }
605
- // Both overlap orders: a live Full operation never widens a restricted one, and vice versa.
606
- if (support.fullAccess) {
1290
+ // Both overlap orders: a live escalated call never widens a restricted one, and vice versa.
1291
+ if (support.outsideSandbox) {
607
1292
  const first = exec(restricted(), `printf r > ready-a; until [ -e barrier-a ]; do sleep 0.01; done; ` +
608
1293
  `printf pwn > ${quote(at(sibling, "overlap-a"))}; cat ${quote(at(sibling, "secret"))}; true`);
609
1294
  await waitFor(at(root, "ready-a"), first);
610
- await exec(full, `printf full > ${quote(at(sibling, "full-a"))} && touch barrier-a`);
611
- assert(!(await first).stdout.includes(secret), "restricted after a live Full operation");
1295
+ await exec(escalated, `printf full > ${quote(at(sibling, "full-a"))} && touch barrier-a`);
1296
+ assert(!(await first).stdout.includes(secret), "restricted after a live escalated call");
612
1297
  assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-a")), null);
613
- const fullFirst = exec(full, `printf r > ready-b; until [ -e barrier-b ]; do sleep 0.01; done; ` +
1298
+ const fullFirst = exec(escalated, `printf r > ready-b; until [ -e barrier-b ]; do sleep 0.01; done; ` +
614
1299
  `printf full > ${quote(at(sibling, "full-b"))}`);
615
1300
  await waitFor(at(root, "ready-b"), fullFirst);
616
1301
  const second = await exec(restricted(), `printf pwn > ${quote(at(sibling, "overlap-b"))}; cat ${quote(at(sibling, "secret"))}; touch barrier-b`);
617
- assert(!second.stdout.includes(secret), "restricted while a Full operation is live");
1302
+ assert(!second.stdout.includes(secret), "restricted while an escalated call is live");
618
1303
  assert.equal((await fullFirst).exitCode, 0);
619
1304
  assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-b")), null);
620
1305
  assert.equal(text(await fixture.inspect.readFile(at(sibling, "full-b"))), "full");
621
1306
  }
622
1307
  // Component swaps during native and shell access never escape.
623
- if (support.fullAccess) {
1308
+ if (support.outsideSandbox) {
624
1309
  const race = at(root, "race");
625
- const swapper = exec(full, `python3 -c ${quote(SWAP_PROGRAM)} ${quote(race)} ${quote(sibling)} ${quote(at(root, "race-stop"))}`);
1310
+ const swapper = exec(escalated, `python3 -c ${quote(SWAP_PROGRAM)} ${quote(race)} ${quote(sibling)} ${quote(at(root, "race-stop"))}`);
626
1311
  await waitFor(at(race, "swapping"), swapper);
627
1312
  for (let index = 0; index < 30; index++) {
628
1313
  const op = await native(restricted());
@@ -638,7 +1323,7 @@ export async function runSandboxPermissionConformance(fixture) {
638
1323
  const shellRace = await exec(restricted(), `i=0; while [ $i -lt 400 ]; do printf pwn > race/dir/x-$i; cat race/dir/secret; ` +
639
1324
  `chmod 777 race/dir/secret; i=$((i+1)); done 2>/dev/null; true`);
640
1325
  assert(!shellRace.stdout.includes(secret), "shell read escaped during a swap");
641
- await exec(full, "touch race-stop");
1326
+ await exec(escalated, "touch race-stop");
642
1327
  assert.equal((await swapper).exitCode, 0);
643
1328
  for (let index = 0; index < 400; index++) {
644
1329
  assert.equal(await fixture.inspect.readFile(at(sibling, `x-${index}`)), null);
@@ -651,10 +1336,12 @@ export async function runSandboxPermissionConformance(fixture) {
651
1336
  const live = exec(restricted(), `printf r > ready-root; until [ -e ${quote(at(moved, "barrier-root"))} ]; do sleep 0.01; done; ` +
652
1337
  `printf pwn > ${quote(at(root, "after-swap"))}; cat ${quote(at(root, "secret"))}; printf ok > in-place; true`);
653
1338
  await waitFor(at(root, "ready-root"), live);
654
- await exec(full, `mv ${quote(root)} ${quote(moved)} && ln -s ${quote(sibling)} ${quote(root)} && touch ${quote(at(moved, "barrier-root"))}`);
1339
+ await exec(escalated, `mv ${quote(root)} ${quote(moved)} && ln -s ${quote(sibling)} ${quote(root)} && touch ${quote(at(moved, "barrier-root"))}`);
655
1340
  const swapped = await live;
656
1341
  assert(!swapped.stdout.includes(secret), "a live operation must not follow a root swap");
657
- assert.equal(text(await fixture.inspect.readFile(at(moved, "in-place"))), "ok");
1342
+ // an inode-pinned runtime (Landlock) keeps writing in the moved root; a path-based one
1343
+ // (Seatbelt) refuses the moved path: either way nothing follows the swap
1344
+ assert([null, "ok"].includes(text(await fixture.inspect.readFile(at(moved, "in-place")))), "a live operation writes in place or nowhere");
658
1345
  await denied((async () => (await native(restricted())).writeFile(at(root, "fresh"), bytes, signal))(), "a fresh native operation must reject a swapped root");
659
1346
  const fresh = await (await fixture.operation(restricted()))
660
1347
  .exec({
@@ -666,7 +1353,7 @@ export async function runSandboxPermissionConformance(fixture) {
666
1353
  })
667
1354
  .catch((error) => error);
668
1355
  assert(isSandboxScopeDeniedError(fresh) || fresh.exitCode !== 0, "a fresh exec must not run in a swapped root");
669
- await exec(full, `rm ${quote(root)} && mv ${quote(moved)} ${quote(root)}`);
1356
+ await exec(escalated, `rm ${quote(root)} && mv ${quote(moved)} ${quote(root)}`);
670
1357
  for (const name of ["after-swap", "fresh", "fresh-exec"]) {
671
1358
  assert.equal(await fixture.inspect.readFile(at(sibling, name)), null, `root swap ${name}`);
672
1359
  }
@@ -716,29 +1403,7 @@ export async function runSandboxPermissionConformance(fixture) {
716
1403
  assert.equal(control?.environ, "ALLOWED", `the probe must read a same-uid control: ${probed}`);
717
1404
  assert.deepEqual(target, { mem: "EACCES", environ: "EACCES", attach: "EPERM" }, `a same-uid outsider must not ptrace or read the supervisor ${supervisor}: ${probed}`);
718
1405
  }
719
- // Exact cancellation: detached descendants end; a sibling operation keeps running.
720
- const keepAlive = exec(restricted(), `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
721
- await waitFor(at(root, "ready-keep"), keepAlive);
722
- const abort = new AbortController();
723
- const cancelled = exec(restricted(), `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
724
- `setsid sleep 1002 > /dev/null 2>&1 & ` +
725
- `python3 -c ${quote("import os, time\nif os.fork() == 0:\n os.setpgid(0, 0)\n open('p3.tmp', 'w').write(str(os.getpid()))\n os.rename('p3.tmp', 'p3')\n time.sleep(1003)")} & ` +
726
- `until [ -e p3 ]; do sleep 0.01; done; printf r > ready-cancel; sleep 1004`, abort.signal);
727
- await waitFor(at(root, "ready-cancel"), cancelled);
728
- const pids = await Promise.all(["p1", "p2", "p3"].map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
729
- assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
730
- abort.abort();
731
- const stopped = await cancelled;
732
- assert.equal(stopped.exitCode, null, "a cancelled operation has no exit code");
733
- assert.deepEqual(await fixture.inspect.alive(pids), [], "cancellation ends every descendant");
734
- await exec(restricted(), "touch release-keep");
735
- assert.equal((await keepAlive).exitCode, 0, "the sibling operation survives the cancel");
736
- assert.equal(text(await fixture.inspect.readFile(at(root, "kept"))), "done");
737
- // Timeout ends the whole owned tree as well.
738
- const timed = await exec(restricted(), `(sleep 1005 & echo $! > p4); sleep 1006`, signal, 1000);
739
- assert.equal(timed.timedOut, true, "a restricted timeout is reported");
740
- const p4 = Number(text(await fixture.inspect.readFile(at(root, "p4"))));
741
- assert.deepEqual(await fixture.inspect.alive([p4]), [], "timeout ends background children");
1406
+ await proveCancellation(restricted());
742
1407
  // A fresh narrowed scope (after revocation) is enforced on the very next operation, while an
743
1408
  // operation that started with the broader grant keeps it.
744
1409
  await fixture.seed([{ path: at(root, "narrow/keep"), kind: "directory" }]);
@@ -768,6 +1433,7 @@ export async function runSandboxPermissionConformance(fixture) {
768
1433
  assert.equal(text(await fixture.inspect.readFile(at(root, "narrow/keep/keep.txt"))), "ok");
769
1434
  assert.equal(await fixture.inspect.readFile(at(root, "revoked.txt")), null, "revoked root");
770
1435
  await denied((await native(narrowed)).writeFile(at(root, "revoked-native"), bytes, signal), "native write after narrowing");
1436
+ return report();
771
1437
  }
772
1438
  finally {
773
1439
  await fixture.dispose();