@capybara-hq/testing 0.1.0-rc.23 → 0.1.0-rc.24

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.
@@ -53,6 +53,13 @@ export interface SandboxPermissionFixture {
53
53
  */
54
54
  readonly access: "direct" | "proxy";
55
55
  };
56
+ /**
57
+ * Set to "refused" when the provider refuses a restricted filesystem with the `environment`
58
+ * network by policy (a local device whose owner ceiling ties the environment network to Full
59
+ * access). The harness then proves that refusal (a scope denial, nothing run) where it would
60
+ * otherwise probe a restricted operation on the environment network. Default: "supported".
61
+ */
62
+ readonly restrictedEnvironment?: "supported" | "refused";
56
63
  /** The provider's own runtime report; the harness never infers support from a fixture. */
57
64
  support(): Promise<SandboxPermissionSupport>;
58
65
  /** A fresh operation (new operation ID) for the grant, through the provider's factory. */
@@ -65,6 +72,15 @@ export interface SandboxPermissionFixture {
65
72
  mode(path: string): Promise<number | null>;
66
73
  /** The subset of `pids` still running on the device. */
67
74
  alive(pids: readonly number[]): Promise<number[]>;
75
+ /**
76
+ * Runs a Python 3 program (`python3 - ...args`, program on stdin) as the device user in a
77
+ * fresh process outside every operation and every restricted domain, standing in for another
78
+ * session's Full-access work, and returns its stdout. When present, the harness proves that
79
+ * such a process can neither ptrace nor read the memory or environment of the process that
80
+ * supervises a restricted command (its parent). Omit it only where no process outside an
81
+ * operation can run as the device user.
82
+ */
83
+ outside?(program: string, args: readonly string[]): Promise<string>;
68
84
  };
69
85
  /** Removes fixture-owned resources, including after an assertion failure. */
70
86
  dispose(): Promise<void>;
@@ -73,7 +89,8 @@ export interface SandboxPermissionFixture {
73
89
  * Proves an actual provider's permission boundary on one shared device: positive controls, sibling,
74
90
  * symlink, protected-path and network denials, Full controls without restricted filters, both
75
91
  * overlap orders, component/root swaps and mutable syscall pointers during access, exact
76
- * cancellation and fresh narrowed scopes. Restricted network none/allowlist may bind and listen on
92
+ * cancellation, a supervisor closed to same-uid outsiders (when the fixture can run one) and fresh
93
+ * narrowed scopes. Restricted network none/allowlist may bind and listen on
77
94
  * loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
78
95
  * every network kind, environment included. A provider that reports restricted unsupported must
79
96
  * refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
@@ -164,11 +164,60 @@ while not os.path.exists(stop):
164
164
  swaps += 1
165
165
  print("swaps=%d" % swaps)
166
166
  `;
167
+ /**
168
+ * Run by a same-uid process outside every operation: tries `PTRACE_ATTACH` and opens `mem` and
169
+ * `environ` of a control child of its own (proving the probe sees real access) and of the target.
170
+ */
171
+ const OUTSIDE_PROBE = `
172
+ import ctypes, errno, json, os, signal, sys, time
173
+ libc = ctypes.CDLL(None, use_errno=True)
174
+ libc.ptrace.restype = ctypes.c_long
175
+ libc.ptrace.argtypes = (ctypes.c_long, ctypes.c_long, ctypes.c_void_p, ctypes.c_void_p)
176
+ PTRACE_ATTACH, PTRACE_DETACH, WALL = 16, 17, 0x40000000
177
+ def name(code):
178
+ return errno.errorcode.get(code, str(code))
179
+ def opened(pid, entry):
180
+ try:
181
+ fd = os.open("/proc/%d/%s" % (pid, entry), os.O_RDONLY)
182
+ except OSError as error:
183
+ return name(error.errno)
184
+ try:
185
+ if entry == "environ":
186
+ os.read(fd, 1)
187
+ finally:
188
+ os.close(fd)
189
+ return "ALLOWED"
190
+ def attach(pid):
191
+ if libc.ptrace(PTRACE_ATTACH, pid, None, None) < 0:
192
+ return name(ctypes.get_errno())
193
+ # Undo at once (the attach stopped the target) so even a failing check leaves it running.
194
+ os.waitpid(pid, WALL)
195
+ libc.ptrace(PTRACE_DETACH, pid, None, None)
196
+ return "ALLOWED"
197
+ def probe(pid):
198
+ return {"mem": opened(pid, "mem"), "environ": opened(pid, "environ"), "attach": attach(pid)}
199
+ child = os.fork()
200
+ if child == 0:
201
+ time.sleep(600)
202
+ os._exit(0)
203
+ control = probe(child)
204
+ os.kill(child, signal.SIGKILL)
205
+ os.waitpid(child, 0)
206
+ target = int(sys.argv[1])
207
+ def identity(pid):
208
+ with open("/proc/%d/status" % pid) as handle:
209
+ uid = [int(line.split()[1]) for line in handle if line.startswith("Uid:")][0]
210
+ with open("/proc/%d/cmdline" % pid, "rb") as handle:
211
+ return {"uid": uid, "cmdline": handle.read().replace(b"\\0", b" ").decode().strip()}
212
+ print(json.dumps({"uid": os.getuid(), "who": identity(target), "control": control,
213
+ "target": probe(target)}))
214
+ `;
167
215
  /**
168
216
  * Proves an actual provider's permission boundary on one shared device: positive controls, sibling,
169
217
  * symlink, protected-path and network denials, Full controls without restricted filters, both
170
218
  * overlap orders, component/root swaps and mutable syscall pointers during access, exact
171
- * cancellation and fresh narrowed scopes. Restricted network none/allowlist may bind and listen on
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
172
221
  * loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
173
222
  * every network kind, environment included. A provider that reports restricted unsupported must
174
223
  * refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
@@ -285,6 +334,172 @@ export async function runSandboxPermissionConformance(fixture) {
285
334
  limit: 10,
286
335
  signal,
287
336
  }), { 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) {
490
+ // 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`);
492
+ 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
+ "git checkout -qb topic && git status --short && git log --oneline | wc -l");
494
+ assert.equal(git.exitCode, 0, `ordinary restricted git work: ${git.stderr}`);
495
+ assert.equal(git.stdout.trim(), "2", "the restricted commit landed");
496
+ // stash, pack-refs and gc write git internals of their own (index.stash.<n>,
497
+ // packed-refs.new, MERGE_AUTOSTASH) that the allowlist keeps writable
498
+ const housekeeping = await exec(restricted(), 'cd work && g() { git -c user.name=t -c user.email=t@t -c gc.auto=0 "$@"; } && ' +
499
+ "printf b >> f && g stash -q && g stash pop -q && g commit -qam s && " +
500
+ "g pack-refs --all && g gc -q && git stash list | wc -l");
501
+ assert.equal(housekeeping.exitCode, 0, `restricted stash, pack-refs and gc: ${housekeeping.stderr}`);
502
+ }
288
503
  // Negative controls: sibling, symlink escapes and protected paths stay out of reach.
289
504
  const reads = await exec(restricted(), `cat ${quote(at(sibling, "secret"))}; cat escape; cat linked/secret; true`);
290
505
  assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
@@ -353,10 +568,15 @@ export async function runSandboxPermissionConformance(fixture) {
353
568
  await fixture.seed([
354
569
  { path: at(root, "srv-link.sock"), kind: "symlink", target: at(sibling, "srv.sock") },
355
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);
575
+ }
356
576
  for (const network of [
357
577
  { kind: "none" },
358
578
  allowlisted,
359
- { kind: "environment" },
579
+ ...(fixture.restrictedEnvironment === "refused" ? [] : [{ kind: "environment" }]),
360
580
  ]) {
361
581
  const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
362
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}`);
@@ -472,6 +692,30 @@ export async function runSandboxPermissionConformance(fixture) {
472
692
  assert.notEqual(chmods.stdout.trim(), "ok=0", "in-root chmods must succeed");
473
693
  await siblingIntact("a flipped path must not chmod the sibling");
474
694
  }
695
+ // The supervisor of a restricted command (its parent) is closed to a same-uid process outside
696
+ // the operation: no ptrace attach, no mem or environ, while the command itself runs normally.
697
+ if (fixture.inspect.outside) {
698
+ const held = exec(restricted(), `echo $PPID > supervisor-pid; printf r > ready-held; ` +
699
+ `until [ -e release-held ]; do sleep 0.01; done; printf ran > held.txt`);
700
+ await waitFor(at(root, "ready-held"), held);
701
+ const supervisor = Number(text(await fixture.inspect.readFile(at(root, "supervisor-pid"))));
702
+ let probed;
703
+ try {
704
+ probed = await fixture.inspect.outside(OUTSIDE_PROBE, [String(supervisor)]);
705
+ }
706
+ finally {
707
+ await exec(restricted(), "touch release-held");
708
+ }
709
+ assert.equal((await held).exitCode, 0, "the supervised command runs normally");
710
+ assert.equal(text(await fixture.inspect.readFile(at(root, "held.txt"))), "ran");
711
+ const { uid, who, control, target } = JSON.parse(probed);
712
+ // Not vacuous: the target is a live process of the outsider's own uid.
713
+ assert.equal(who?.uid, uid, `the supervisor must run as the outsider's uid: ${probed}`);
714
+ assert.notEqual(who?.cmdline ?? "", "", `the supervisor must still be running: ${probed}`);
715
+ assert.equal(control?.mem, "ALLOWED", `the probe must read a same-uid control: ${probed}`);
716
+ assert.equal(control?.environ, "ALLOWED", `the probe must read a same-uid control: ${probed}`);
717
+ assert.deepEqual(target, { mem: "EACCES", environ: "EACCES", attach: "EPERM" }, `a same-uid outsider must not ptrace or read the supervisor ${supervisor}: ${probed}`);
718
+ }
475
719
  // Exact cancellation: detached descendants end; a sibling operation keeps running.
476
720
  const keepAlive = exec(restricted(), `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
477
721
  await waitFor(at(root, "ready-keep"), keepAlive);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.23",
3
+ "version": "0.1.0-rc.24",
4
4
  "description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,18 +47,18 @@
47
47
  "tsx": "^4.23.15",
48
48
  "ws": "^8.22.0",
49
49
  "zod": "^4.6.7",
50
- "@capybara-hq/kernel": "^0.1.0-rc.38"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.42"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
55
  "@capybara-hq/plugin-client": "^0.1.0-rc.5",
56
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.29"
56
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.31"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.29",
61
- "@capybara-hq/plugin-tools": "^0.1.0-rc.16"
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.31",
61
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.17"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "@capybara-hq/plugin-tools": {