@capybara-hq/testing 0.1.0-rc.28 → 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. */
@@ -168,6 +168,30 @@ print(" ".join([
168
168
  attempt("pair-raw", lambda: pair(socket.SOCK_RAW)),
169
169
  ]))
170
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
+ `;
171
195
  /** A UNIX stream server and client inside the root talk to each other. */
172
196
  const UNIX_ROUNDTRIP = `
173
197
  import socket, sys
@@ -247,24 +271,110 @@ print(json.dumps({"uid": os.getuid(), "who": identity(target), "control": contro
247
271
  "target": probe(target)}))
248
272
  `;
249
273
  /**
250
- * Proves an actual provider's permission boundary on one shared device: positive controls, sibling,
251
- * symlink, protected-path and network denials, Full controls without restricted filters, both
252
- * overlap orders, component/root swaps and mutable syscall pointers during access, exact
253
- * cancellation, a supervisor closed to same-uid outsiders (when the fixture can run one) and fresh
254
- * narrowed scopes. Restricted network none/allowlist may bind and listen on
255
- * loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
256
- * 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
257
356
  * refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
258
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
+ *
259
363
  * Not covered, by design (known limitations, not passes): metadata reads outside the roots (stat,
260
364
  * readlink, xattrs, statfs), and the world-readable `/proc/<pid>` entries of other processes of the
261
365
  * same uid, such as `cmdline`, `stat` and `status`. A restricted operation can therefore read the
262
- * 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
263
367
  * operation's own process tree (see the Linux launcher's known limitations). Providers keep secrets
264
368
  * out of command lines; ptrace-guarded entries (`environ`, `mem`, `maps`, `fd`) stay closed.
265
369
  */
266
- export async function runSandboxPermissionConformance(fixture) {
370
+ export async function runSandboxPermissionConformance(fixture, options = {}) {
267
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);
268
378
  const at = (base, name) => posix.join(base, name);
269
379
  const secret = `sibling-secret-${randomUUID()}`;
270
380
  const scoped = (writeRoots) => ({
@@ -277,11 +387,21 @@ export async function runSandboxPermissionConformance(fixture) {
277
387
  filesystem: scoped(writeRoots),
278
388
  network,
279
389
  });
280
- const full = {
281
- 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",
282
397
  filesystem: { kind: "device" },
283
398
  network: { kind: "environment" },
284
399
  };
400
+ const PROFILES = [
401
+ "request-approval",
402
+ "approve-for-me",
403
+ "full-access",
404
+ ];
285
405
  const { granted, ungranted, access } = fixture.endpoints;
286
406
  const proxied = access === "proxy";
287
407
  const allowlisted = { kind: "allowlist", hosts: [granted.name] };
@@ -306,8 +426,285 @@ export async function runSandboxPermissionConformance(fixture) {
306
426
  const connect = (endpoint) => `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(endpoint.address)}, ${endpoint.port}), 10).close()`)}`;
307
427
  /** An HTTP request by name; curl and Python use the environment's proxy when there is one. */
308
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
+ };
309
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
+ };
310
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");
311
708
  for (const [label, endpoint] of [
312
709
  ["granted", granted],
313
710
  ...ungranted.map((endpoint) => ["ungranted", endpoint]),
@@ -319,8 +716,13 @@ export async function runSandboxPermissionConformance(fixture) {
319
716
  assert(isIPv4(granted.address), "the granted endpoint address must be IPv4 (race program)");
320
717
  assert(ungranted.every((endpoint) => endpoint.name !== granted.name), "ungranted endpoints need names other than the granted one");
321
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
+ }
322
724
  if (support.restricted === null) {
323
- // 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.
324
726
  await assert.rejects((async () => (await fixture.operation(restricted())).exec({
325
727
  command: "true",
326
728
  cwd: root,
@@ -328,9 +730,26 @@ export async function runSandboxPermissionConformance(fixture) {
328
730
  maxOutputBytes: 1024,
329
731
  signal,
330
732
  }))(), (error) => isSandboxPermissionUnsupportedError(error), "an unsupported runtime must refuse restricted operations");
331
- return;
733
+ return report();
332
734
  }
333
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 });
334
753
  await fixture.seed([
335
754
  { path: at(sibling, "secret"), kind: "file", data: new TextEncoder().encode(secret) },
336
755
  { path: at(root, "inroot.txt"), kind: "file", data: new TextEncoder().encode("inroot") },
@@ -368,165 +787,253 @@ export async function runSandboxPermissionConformance(fixture) {
368
787
  limit: 10,
369
788
  signal,
370
789
  }), { entries: [{ name: "n.bin", isDir: false }], truncated: false });
371
- // Mandatory write denies inside a granted root (the macOS set, shared through the SDK): git
372
- // configuration and hooks (a later unsandboxed `git` there would run them), shell startup
373
- // files and editor/agent configuration. Direct writes, creation, renames, hard and symbolic
374
- // links, and the same paths in a repository the command creates itself all stay refused.
375
- await fixture.seed([
376
- { path: at(root, "repo/.git/config"), kind: "file", data: new TextEncoder().encode("cfg") },
377
- {
378
- path: at(root, "repo/.git/hooks/pre-commit.sample"),
379
- kind: "file",
380
- data: new TextEncoder().encode("s"),
381
- },
382
- { path: at(root, "repo/.git/HEAD"), kind: "file", data: new TextEncoder().encode("ref: x") },
383
- ]);
384
- const evil = '[core]\n\tfsmonitor = "touch escaped; false"\n';
385
- const denies = await exec(restricted(), [
386
- `cd repo`,
387
- `printf ${quote(evil)} > .git/config`,
388
- `printf x >> .git/config`,
389
- `mkdir -p .git/hooks; printf '#!/bin/sh' > .git/hooks/pre-commit`,
390
- `chmod 755 .git/hooks/pre-commit.sample`,
391
- `printf x > staged-config; mv staged-config .git/config`,
392
- `printf x > staged-hook; ln staged-hook .git/hooks/post-checkout`,
393
- `ln -s ../staged-hook .git/hooks/pre-push`,
394
- `ln -s .git/config cfg-link; printf x > cfg-link`,
395
- `mkdir moved; printf x > moved/config; mkdir -p sub; mv moved sub/.git`,
396
- `mkdir -p ../ptr && printf 'gitdir: /tmp' > ../ptr/.git`,
397
- `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`,
398
- `printf x > .bashrc; printf x > .zshrc; printf x > .profile; printf x > .gitconfig; printf x > .gitmodules; printf x > .mcp.json`,
399
- `mkdir -p .vscode && printf x > .vscode/settings.json; mkdir -p .idea && printf x > .idea/x`,
400
- `mkdir -p .claude/commands .claude/agents; printf x > .claude/commands/c.md; printf x > .claude/agents/a.md`,
401
- `mkdir -p deep/er; printf x > deep/er/.bash_profile`,
402
- `printf ok > allowed.txt`,
403
- `true`,
404
- ].join("; "));
405
- assert.equal(denies.exitCode, 0, `the mandatory-deny probe must run: ${denies.stderr}`);
406
- assert.equal(text(await fixture.inspect.readFile(at(root, "allowed.txt"))), "ok", "ordinary writes");
407
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", ".git/config");
408
- assert.equal((await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-commit.sample"))) !== 0o755, true, "hook mode");
409
- for (const path of [
410
- "repo/.git/hooks/pre-commit",
411
- "repo/.git/hooks/post-checkout",
412
- "repo/.git/hooks/pre-push",
413
- "repo/sub/.git/config",
414
- "ptr/.git",
415
- "nested/.git/hooks/pre-commit",
416
- "nested/.git/config",
417
- ".bashrc",
418
- ".zshrc",
419
- ".profile",
420
- ".gitconfig",
421
- ".gitmodules",
422
- ".mcp.json",
423
- ".vscode/settings.json",
424
- ".idea/x",
425
- ".claude/commands/c.md",
426
- ".claude/agents/a.md",
427
- "deep/er/.bash_profile",
428
- ])
429
- assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
430
- assert.equal(await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-push")), null, "a symbolic link into the hooks is refused too");
431
- await denied((await native(restricted())).writeFile(at(root, "repo/.git/config"), bytes, signal), "native write of .git/config");
432
- await denied((await native(restricted())).writeFile(at(root, "repo/.git/hooks/post-merge"), bytes, signal), "native write of a git hook");
433
- await denied((await native(restricted())).writeFile(at(root, ".vscode/tasks.json"), bytes, signal), "native write of editor configuration");
434
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg");
435
- // Inside a .git directory only git's ordinary internals are writable: the gitdirs of
436
- // submodules and worktrees keep their configuration, hooks and pointers too. A bare-repository
437
- // lookalike (a HEAD file outside .git) and moving .git away are refused as well, and the
438
- // matching folds case and Unicode compatibility forms.
439
- await fixture.seed([
440
- {
441
- path: at(root, "repo/.git/modules/sub/config"),
442
- kind: "file",
443
- data: new TextEncoder().encode("cfg"),
444
- },
445
- { path: at(root, "repo/.git/modules/sub/hooks"), kind: "directory" },
446
- { path: at(root, "repo/.git/modules/sub/objects"), kind: "directory" },
447
- {
448
- path: at(root, "repo/.git/worktrees/wt/commondir"),
449
- kind: "file",
450
- data: new TextEncoder().encode("../.."),
451
- },
452
- ]);
453
- const internals = await exec(restricted(), [
454
- "cd repo",
455
- "printf x >> .git/modules/sub/config",
456
- "printf x > .git/modules/sub/hooks/pre-commit",
457
- "printf x > .git/worktrees/wt/commondir",
458
- "printf x > .git/worktrees/wt/config.worktree",
459
- "printf x > .git/worktrees/wt/gitdir",
460
- "printf x > .git/info-attributes-probe; mkdir -p .git/info; printf x > .git/info/attributes",
461
- "printf x > .git/modules/sub/objects/ok-object",
462
- "mkdir -p ../bare/objects ../bare/refs; printf 'ref: refs/heads/main' > ../bare/HEAD; printf x > ../bare/config",
463
- "mv .git ../moved-git; printf x >> ../moved-git/config",
464
- "cd ..",
465
- "printf x > .envrc; printf x > .npmrc; mkdir -p deep; printf x > deep/.npmrc",
466
- "printf x > .BASHRC; printf x > .envrc",
467
- "true",
468
- ].join("; "));
469
- assert.equal(internals.exitCode, 0, `the git-internals probe must run: ${internals.stderr}`);
470
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/config"))), "cfg", "submodule config");
471
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/worktrees/wt/commondir"))), "../..", "worktree commondir");
472
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/objects/ok-object"))), "x", "submodule objects stay writable");
473
- assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", "moving .git away");
474
- for (const path of [
475
- "repo/.git/modules/sub/hooks/pre-commit",
476
- "repo/.git/worktrees/wt/config.worktree",
477
- "repo/.git/worktrees/wt/gitdir",
478
- "repo/.git/info-attributes-probe",
479
- "repo/.git/info/attributes",
480
- "bare/HEAD",
481
- "moved-git/config",
482
- ".envrc",
483
- ".npmrc",
484
- "deep/.npmrc",
485
- ...(fixture.foldedNames === "filesystem" ? [".bashrc"] : [".BASHRC", ".envrc"]),
486
- ])
487
- assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
488
- if (fixture.foldedNames === "filesystem") {
489
- // fullwidth spellings are their own files on such a filesystem, never the protected ones
490
- for (const path of [".BASHRC", ".envrc"])
491
- assert.equal(text(await fixture.inspect.readFile(at(root, path))), "x", `distinct ${path}`);
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");
492
996
  }
493
- await denied((await native(restricted())).writeFile(at(root, "repo/.git/modules/sub/config"), bytes, signal), "native write of a submodule's config");
494
- await denied((await native(restricted())).writeFile(at(root, "bare2/HEAD"), bytes, signal), "native write of a bare-repository HEAD");
495
- // No repository can be forged inside git's own allowlisted subtrees, and hook managers
496
- // files stay out of reach.
497
- const forged = await exec(restricted(), [
498
- "cd repo/.git",
499
- "mkdir -p objects/zz/.git/objects objects/zz/.git/refs",
500
- "printf 'ref: refs/heads/main' > objects/zz/.git/HEAD",
501
- "printf x > objects/zz/.git/config",
502
- "mkdir -p objects/yy/objects objects/yy/refs; printf 'ref: refs/heads/main' > objects/yy/HEAD",
503
- "mkdir -p logs/objects; printf ../.. > logs/commondir",
504
- "mkdir -p refs/remotes/o/objects",
505
- "cd ../..",
506
- "mkdir -p .husky .lefthook .githooks .config",
507
- "printf x > .husky/pre-commit; printf x > .pre-commit-config.yaml; printf x > lefthook.yml",
508
- "printf x > .lefthook/x; printf x > .githooks/pre-commit; printf x > .config/lefthook.yml",
509
- "true",
510
- ].join("; "));
511
- assert.equal(forged.exitCode, 0, `the forged-repository probe must run: ${forged.stderr}`);
512
- for (const path of [
513
- "repo/.git/objects/zz/.git/HEAD",
514
- "repo/.git/objects/zz/.git/config",
515
- "repo/.git/objects/yy/HEAD",
516
- "repo/.git/logs/objects",
517
- "repo/.git/logs/commondir",
518
- "repo/.git/refs/remotes/o/objects",
519
- ".husky/pre-commit",
520
- ".pre-commit-config.yaml",
521
- "lefthook.yml",
522
- ".lefthook/x",
523
- ".githooks/pre-commit",
524
- ".config/lefthook.yml",
525
- ])
526
- assert.equal(await fixture.inspect.mode(at(root, path)), null, `mandatory deny: ${path}`);
527
- if (support.fullAccess) {
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) {
528
1035
  // ordinary git work in a restricted repository keeps working under these rules
529
- 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`);
530
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 && " +
531
1038
  "git checkout -qb topic && git status --short && git log --oneline | wc -l");
532
1039
  assert.equal(git.exitCode, 0, `ordinary restricted git work: ${git.stderr}`);
@@ -538,162 +1045,269 @@ export async function runSandboxPermissionConformance(fixture) {
538
1045
  "g pack-refs --all && g gc -q && git stash list | wc -l");
539
1046
  assert.equal(housekeeping.exitCode, 0, `restricted stash, pack-refs and gc: ${housekeeping.stderr}`);
540
1047
  }
541
- // Negative controls: sibling, symlink escapes and protected paths stay out of reach.
542
- const reads = await exec(restricted(), `cat ${quote(at(sibling, "secret"))}; cat escape; cat linked/secret; true`);
543
- assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
544
- await exec(restricted(), `printf pwn > ${quote(at(sibling, "w1"))}; printf pwn > linked/w2; printf pwn > escape; ` +
545
- `chmod 777 ${quote(at(sibling, "secret"))}; chmod 777 escape; ` +
546
- `touch -t 200101010000 ${quote(at(sibling, "secret"))}; true`);
547
- assert.equal(await fixture.inspect.readFile(at(sibling, "w1")), null, "sibling write");
548
- assert.equal(await fixture.inspect.readFile(at(sibling, "w2")), null, "symlinked dir write");
549
- await siblingIntact("restricted writes and chmod must not change the sibling");
550
- for (const path of fixture.protectedPaths) {
551
- const before = text(await fixture.inspect.readFile(path));
552
- await exec(restricted(), `printf pwn >> ${quote(path)}; true`);
553
- assert.equal(text(await fixture.inspect.readFile(path)), before, `protected ${path}`);
554
- }
555
- await denied((await native(restricted())).readFile(at(sibling, "secret"), { maxBytes: 100, signal }), "native sibling read");
556
- await denied((await native(restricted())).readFile(at(root, "escape"), { maxBytes: 100, signal }), "native symlink escape read");
557
- await denied((await native(restricted())).writeFile(at(sibling, "n1"), bytes, signal), "native sibling write");
558
- await denied((await native(restricted())).writeFile(at(root, "linked/n2"), bytes, signal), "native write through a directory symlink");
559
- await denied((await native(restricted())).stat(at(sibling, "secret"), signal), "stat");
560
- await denied((await native(restricted())).list(sibling, { limit: 5, signal }), "list");
561
- await siblingIntact("native denials must leave the sibling unchanged");
562
- // Network: only the granted endpoint, and only while allowlisted.
563
- const base = await receipts();
564
- const namedReach = fixture.endpoints.namedReach !== "unavailable";
565
- const positives = !namedReach
566
- ? []
567
- : proxied
568
- ? [byName(granted), urlopen(granted)]
569
- : [
570
- connect(granted),
571
- `curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
572
- `node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
573
- ];
574
- for (const command of positives) {
575
- const result = await exec(restricted(allowlisted), command);
576
- assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
577
- }
578
- for (const endpoint of ungranted) {
579
- // Raw connects to an ungranted address fail; through a proxy, so does a request by name.
580
- for (const command of proxied ? [connect(endpoint), byName(endpoint)] : [connect(endpoint)]) {
581
- const result = await exec(restricted(allowlisted), command);
582
- 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");
583
1099
  }
584
1100
  }
585
- if (proxied) {
586
- // allowlisted traffic goes through the proxy: a raw connect to the granted address bypasses
587
- // it and must be refused as well
588
- const raw = await exec(restricted(allowlisted), connect(granted));
589
- assert.notEqual(raw.exitCode, 0, `a proxied provider must refuse a raw connect: ${granted.name}`);
590
- }
591
- for (const command of [connect(granted), byName(granted)]) {
592
- const none = await exec(restricted(), command);
593
- assert.notEqual(none.exitCode, 0, `network none must refuse even the granted endpoint: ${command}`);
594
- }
595
- const after = await receipts();
596
- assert.equal(after[0], (base[0] ?? 0) + positives.length, "granted endpoint receipts");
597
- assert.deepEqual(after.slice(1), base.slice(1), "ungranted endpoints must see no connection");
598
- // Restricted network none/allowlist may listen on loopback only.
599
- for (const network of [{ kind: "none" }, allowlisted]) {
600
- const binds = await exec(restricted(network), `python3 -c ${quote(BIND_PROGRAM)}`);
601
- assert.equal(binds.stdout.trim(), fixture.restrictedLoopbackListen === "refused"
602
- ? "127.0.0.1=denied ::1=denied 0.0.0.0=denied ::=denied unspec=denied"
603
- : "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
+ }
604
1113
  }
605
- // Pathname UNIX sockets: a service outside the roots is unreachable under every network kind
606
- // (including environment, which lifts only the network filter); one inside the root works.
607
- if (support.fullAccess) {
608
- const server = new AbortController();
609
- const outside = exec(full, `python3 -c ${quote(UNIX_SERVER)} ${quote(at(sibling, "srv.sock"))} ${quote(at(sibling, "srv.count"))}`, server.signal);
610
- await waitFor(at(sibling, "srv.count"), outside);
611
- await fixture.seed([
612
- { path: at(root, "srv-link.sock"), kind: "symlink", target: at(sibling, "srv.sock") },
613
- ]);
614
- if (fixture.restrictedEnvironment === "refused") {
615
- // the policy refusal is the result: a typed scope denial before anything runs
616
- await denied(exec(restricted({ kind: "environment" }), `printf ran > ${quote(at(root, "env-ran"))}`), "a restricted environment-network operation must be refused by policy");
617
- 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");
1164
+ }
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
+ }
618
1223
  }
619
- // The OS's own UNIX socket types, probed outside every restriction (unsupported types are
620
- // reported as such by Full access and expected the same in restricted operations)
621
- const types = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "missing.sock"))} missing-link.sock`);
622
- const kinds = types.stdout
623
- .trim()
624
- .split(" ")
625
- .map((entry) => entry.split("="));
626
- for (const name of ["stream", "dgram", "link"])
627
- assert.notEqual(kinds.find(([kind]) => kind === name)?.[1], "unsupported", `UNIX ${name} sockets are required: ${types.stdout} ${types.stderr}`);
628
- const expectWhen = (reachable) => kinds
629
- .map(([kind, state]) => state === "unsupported"
630
- ? `${kind}=unsupported`
631
- : `${kind}=${reachable ? "ok" : "denied"}`)
632
- .join(" ");
633
- for (const network of [
634
- { kind: "none" },
635
- allowlisted,
636
- ...(fixture.restrictedEnvironment === "refused" ? [] : [{ kind: "environment" }]),
637
- ]) {
638
- const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
639
- assert.equal(
640
- // a type the OS lacks may also be refused before the OS says so: both reach nothing
641
- probe.stdout
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
642
1237
  .trim()
643
1238
  .split(" ")
644
- .map((entry) => entry.endsWith("=denied") &&
645
- kinds.some(([kind, state]) => `${kind}=denied` === entry && state === "unsupported")
646
- ? entry.replace("=denied", "=unsupported")
647
- : entry)
648
- .join(" "), expectWhen(false), `restricted ${network.kind} must not reach a UNIX service outside the roots: ${probe.stderr}`);
649
- const inside = await exec(restricted(network), `python3 -c ${quote(UNIX_ROUNDTRIP)} ${quote(at(root, `own-${network.kind}.sock`))}`);
650
- if (fixture.restrictedLoopbackListen === "refused")
651
- // no listener at all: binding a UNIX socket fails before any roundtrip
652
- assert.notEqual(inside.stdout.trim(), "roundtrip=ok", "no restricted UNIX listener");
653
- else
654
- assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
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;
655
1277
  }
656
- assert.equal(text(await fixture.inspect.readFile(at(sibling, "srv.count"))), "0", "the outside UNIX service must see no client");
657
- // The same client under Full access reaches the service seven times: the probe is real.
658
- const control = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
659
- assert.equal(control.stdout.trim(), expectWhen(true), `Full UNIX control: ${control.stderr}`);
660
- const reached = String(kinds.filter(([, state]) => state !== "unsupported").length);
661
- await waitForFile(async (path) => {
662
- const data = await fixture.inspect.readFile(path);
663
- return text(data) === reached ? data : null;
664
- }, at(sibling, "srv.count"), outside);
665
- server.abort();
666
- await outside;
667
1278
  }
668
- // Full access controls on the same device: no restricted filters apply.
669
- if (support.fullAccess) {
670
- const control = await exec(full, `cat ${quote(at(sibling, "secret"))} && printf full > ${quote(at(sibling, "full"))} && ${connect(ungranted[0] ?? granted)}`);
671
- assert.equal(control.exitCode, 0, `Full access control must succeed: ${control.stderr}`);
672
- 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");
673
1287
  assert.equal(text(await fixture.inspect.readFile(at(sibling, "full"))), "full");
674
- 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");
675
1289
  }
676
- // Both overlap orders: a live Full operation never widens a restricted one, and vice versa.
677
- if (support.fullAccess) {
1290
+ // Both overlap orders: a live escalated call never widens a restricted one, and vice versa.
1291
+ if (support.outsideSandbox) {
678
1292
  const first = exec(restricted(), `printf r > ready-a; until [ -e barrier-a ]; do sleep 0.01; done; ` +
679
1293
  `printf pwn > ${quote(at(sibling, "overlap-a"))}; cat ${quote(at(sibling, "secret"))}; true`);
680
1294
  await waitFor(at(root, "ready-a"), first);
681
- await exec(full, `printf full > ${quote(at(sibling, "full-a"))} && touch barrier-a`);
682
- 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");
683
1297
  assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-a")), null);
684
- 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; ` +
685
1299
  `printf full > ${quote(at(sibling, "full-b"))}`);
686
1300
  await waitFor(at(root, "ready-b"), fullFirst);
687
1301
  const second = await exec(restricted(), `printf pwn > ${quote(at(sibling, "overlap-b"))}; cat ${quote(at(sibling, "secret"))}; touch barrier-b`);
688
- 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");
689
1303
  assert.equal((await fullFirst).exitCode, 0);
690
1304
  assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-b")), null);
691
1305
  assert.equal(text(await fixture.inspect.readFile(at(sibling, "full-b"))), "full");
692
1306
  }
693
1307
  // Component swaps during native and shell access never escape.
694
- if (support.fullAccess) {
1308
+ if (support.outsideSandbox) {
695
1309
  const race = at(root, "race");
696
- 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"))}`);
697
1311
  await waitFor(at(race, "swapping"), swapper);
698
1312
  for (let index = 0; index < 30; index++) {
699
1313
  const op = await native(restricted());
@@ -709,7 +1323,7 @@ export async function runSandboxPermissionConformance(fixture) {
709
1323
  const shellRace = await exec(restricted(), `i=0; while [ $i -lt 400 ]; do printf pwn > race/dir/x-$i; cat race/dir/secret; ` +
710
1324
  `chmod 777 race/dir/secret; i=$((i+1)); done 2>/dev/null; true`);
711
1325
  assert(!shellRace.stdout.includes(secret), "shell read escaped during a swap");
712
- await exec(full, "touch race-stop");
1326
+ await exec(escalated, "touch race-stop");
713
1327
  assert.equal((await swapper).exitCode, 0);
714
1328
  for (let index = 0; index < 400; index++) {
715
1329
  assert.equal(await fixture.inspect.readFile(at(sibling, `x-${index}`)), null);
@@ -722,7 +1336,7 @@ export async function runSandboxPermissionConformance(fixture) {
722
1336
  const live = exec(restricted(), `printf r > ready-root; until [ -e ${quote(at(moved, "barrier-root"))} ]; do sleep 0.01; done; ` +
723
1337
  `printf pwn > ${quote(at(root, "after-swap"))}; cat ${quote(at(root, "secret"))}; printf ok > in-place; true`);
724
1338
  await waitFor(at(root, "ready-root"), live);
725
- 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"))}`);
726
1340
  const swapped = await live;
727
1341
  assert(!swapped.stdout.includes(secret), "a live operation must not follow a root swap");
728
1342
  // an inode-pinned runtime (Landlock) keeps writing in the moved root; a path-based one
@@ -739,7 +1353,7 @@ export async function runSandboxPermissionConformance(fixture) {
739
1353
  })
740
1354
  .catch((error) => error);
741
1355
  assert(isSandboxScopeDeniedError(fresh) || fresh.exitCode !== 0, "a fresh exec must not run in a swapped root");
742
- await exec(full, `rm ${quote(root)} && mv ${quote(moved)} ${quote(root)}`);
1356
+ await exec(escalated, `rm ${quote(root)} && mv ${quote(moved)} ${quote(root)}`);
743
1357
  for (const name of ["after-swap", "fresh", "fresh-exec"]) {
744
1358
  assert.equal(await fixture.inspect.readFile(at(sibling, name)), null, `root swap ${name}`);
745
1359
  }
@@ -789,33 +1403,7 @@ export async function runSandboxPermissionConformance(fixture) {
789
1403
  assert.equal(control?.environ, "ALLOWED", `the probe must read a same-uid control: ${probed}`);
790
1404
  assert.deepEqual(target, { mem: "EACCES", environ: "EACCES", attach: "EPERM" }, `a same-uid outsider must not ptrace or read the supervisor ${supervisor}: ${probed}`);
791
1405
  }
792
- // Exact cancellation: detached descendants end; a sibling operation keeps running.
793
- const keepAlive = exec(restricted(), `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
794
- await waitFor(at(root, "ready-keep"), keepAlive);
795
- const abort = new AbortController();
796
- const regrouped = fixture.regroupedDescendants !== "not-promised";
797
- const cancelled = exec(restricted(), `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
798
- `setsid sleep 1002 > /dev/null 2>&1 & ` +
799
- (regrouped
800
- ? `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)")} & ` +
801
- `until [ -e p3 ]; do sleep 0.01; done; `
802
- : "") +
803
- `printf r > ready-cancel; sleep 1004`, abort.signal);
804
- await waitFor(at(root, "ready-cancel"), cancelled);
805
- const pids = await Promise.all((regrouped ? ["p1", "p2", "p3"] : ["p1", "p2"]).map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
806
- assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
807
- abort.abort();
808
- const stopped = await cancelled;
809
- assert.equal(stopped.exitCode, null, "a cancelled operation has no exit code");
810
- assert.deepEqual(await fixture.inspect.alive(pids), [], "cancellation ends every descendant");
811
- await exec(restricted(), "touch release-keep");
812
- assert.equal((await keepAlive).exitCode, 0, "the sibling operation survives the cancel");
813
- assert.equal(text(await fixture.inspect.readFile(at(root, "kept"))), "done");
814
- // Timeout ends the whole owned tree as well.
815
- const timed = await exec(restricted(), `(sleep 1005 & echo $! > p4); sleep 1006`, signal, 1000);
816
- assert.equal(timed.timedOut, true, "a restricted timeout is reported");
817
- const p4 = Number(text(await fixture.inspect.readFile(at(root, "p4"))));
818
- assert.deepEqual(await fixture.inspect.alive([p4]), [], "timeout ends background children");
1406
+ await proveCancellation(restricted());
819
1407
  // A fresh narrowed scope (after revocation) is enforced on the very next operation, while an
820
1408
  // operation that started with the broader grant keeps it.
821
1409
  await fixture.seed([{ path: at(root, "narrow/keep"), kind: "directory" }]);
@@ -845,6 +1433,7 @@ export async function runSandboxPermissionConformance(fixture) {
845
1433
  assert.equal(text(await fixture.inspect.readFile(at(root, "narrow/keep/keep.txt"))), "ok");
846
1434
  assert.equal(await fixture.inspect.readFile(at(root, "revoked.txt")), null, "revoked root");
847
1435
  await denied((await native(narrowed)).writeFile(at(root, "revoked-native"), bytes, signal), "native write after narrowing");
1436
+ return report();
848
1437
  }
849
1438
  finally {
850
1439
  await fixture.dispose();