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

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.
@@ -52,6 +52,14 @@ export interface SandboxPermissionFixture {
52
52
  * Either way the device needs no name resolution of its own for endpoint names.
53
53
  */
54
54
  readonly access: "direct" | "proxy";
55
+ /**
56
+ * "unavailable" where the fixture cannot make the allowlisted name lead to `granted` without
57
+ * changing the host (macOS: no hosts-file entry, and the runtime's proxy refuses a name that
58
+ * resolves to loopback, by design). The by-name positives are then skipped and `granted`
59
+ * must see no connection at all; every negative still runs. The positive allowlist reach is
60
+ * then the provider's own test's evidence (state it next to the fixture). Default "available".
61
+ */
62
+ readonly namedReach?: "available" | "unavailable";
55
63
  };
56
64
  /**
57
65
  * Set to "refused" when the provider refuses a restricted filesystem with the `environment`
@@ -60,6 +68,31 @@ export interface SandboxPermissionFixture {
60
68
  * otherwise probe a restricted operation on the environment network. Default: "supported".
61
69
  */
62
70
  readonly restrictedEnvironment?: "supported" | "refused";
71
+ /**
72
+ * How restricted commands meet the mandatory write denies in other spellings of a protected
73
+ * name. "nfkc" (default): every spelling whose NFKC case fold is protected is refused, as the
74
+ * shared SDK policy compares names. "filesystem": the runtime enforces paths as the filesystem
75
+ * resolves them (macOS Seatbelt on case-insensitive APFS: ASCII case and the Unicode case folds
76
+ * APFS applies, such as the Kelvin sign for `k`, reach the protected file and are refused, while
77
+ * compatibility forms such as fullwidth letters are distinct files there); the harness then
78
+ * proves that a fullwidth spelling created a distinct file and never the protected one.
79
+ */
80
+ readonly foldedNames?: "nfkc" | "filesystem";
81
+ /**
82
+ * Whether restricted none/allowlist operations may listen on loopback. "allowed" (default):
83
+ * loopback only, every wildcard address refused, and a UNIX socket inside the root works.
84
+ * "refused": the runtime refuses every listener, loopback and UNIX sockets inside the root
85
+ * included (the macOS worker runs its runtime with local binding off).
86
+ */
87
+ readonly restrictedLoopbackListen?: "allowed" | "refused";
88
+ /**
89
+ * Whether cancellation must also end a descendant that left the command's process group
90
+ * (fork + setpgid). "ended" (default): it must, as Linux PID namespaces and cgroups provide.
91
+ * "not-promised": the runtime ends the owned process group and what stays in it, and does not
92
+ * promise to rediscover a regrouped descendant (macOS, permission operation contract "Explicit
93
+ * background supervision"); the harness then leaves that case out.
94
+ */
95
+ readonly regroupedDescendants?: "ended" | "not-promised";
63
96
  /** The provider's own runtime report; the harness never infers support from a fixture. */
64
97
  support(): Promise<SandboxPermissionSupport>;
65
98
  /** A fresh operation (new operation ID) for the grant, through the provider's factory. */
@@ -18,6 +18,9 @@ def flipper(buffer, good, bad):
18
18
  ok = 0
19
19
  if mode == "connect":
20
20
  def sockaddr(host, port):
21
+ if sys.platform == "darwin":
22
+ # BSD sockaddr_in: a length byte, then a one-byte family
23
+ return struct.pack("BBH4s8x", 16, socket.AF_INET, socket.htons(port), socket.inet_aton(host))
21
24
  return struct.pack("HH4s8x", socket.AF_INET, socket.htons(port), socket.inet_aton(host))
22
25
  if sys.argv[3] == "proxy":
23
26
  # The allowed target is the operation's own HTTP proxy, taken from its environment.
@@ -78,7 +81,8 @@ print(" ".join(out))
78
81
  `;
79
82
  /** A Full-access UNIX service (stream, seqpacket, datagram) counting every client it sees. */
80
83
  const UNIX_SERVER = `
81
- import os, socket, sys, threading
84
+ import errno, os, socket, sys, threading
85
+ UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
82
86
  path, counter = sys.argv[1], sys.argv[2]
83
87
  lock = threading.Lock()
84
88
  count = [0]
@@ -89,7 +93,14 @@ def seen():
89
93
  handle.write(str(count[0]))
90
94
  os.replace(counter + ".tmp", counter)
91
95
  def serve(kind, suffix):
92
- s = socket.socket(socket.AF_UNIX, kind)
96
+ try:
97
+ s = socket.socket(socket.AF_UNIX, kind)
98
+ except OSError as error:
99
+ if error.errno not in UNSUPPORTED:
100
+ raise
101
+ # this OS has no such UNIX socket type (macOS: SOCK_SEQPACKET): mark it and stop
102
+ open(path + suffix, "w").close()
103
+ return
93
104
  s.bind(path + suffix)
94
105
  if kind == socket.SOCK_DGRAM:
95
106
  while True:
@@ -112,22 +123,41 @@ threading.Event().wait()
112
123
  `;
113
124
  /** Tries every way to reach the outside UNIX service; prints ok/denied per attempt. */
114
125
  const UNIX_CLIENT = `
115
- import socket, sys
126
+ import errno, socket, sys
127
+ UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
116
128
  path, link = sys.argv[1], sys.argv[2]
129
+ class Unsupported(Exception):
130
+ pass
131
+ def make(create):
132
+ # the OS has no such UNIX socket type at all (macOS: SOCK_SEQPACKET, SOCK_RAW)
133
+ try:
134
+ return create()
135
+ except OSError as error:
136
+ if error.errno in UNSUPPORTED:
137
+ raise Unsupported()
138
+ raise
117
139
  def attempt(name, action):
118
140
  try:
119
141
  action()
120
142
  return name + "=ok"
143
+ except Unsupported:
144
+ return name + "=unsupported"
121
145
  except OSError:
122
146
  return name + "=denied"
123
147
  def connect(kind, target):
124
- socket.socket(socket.AF_UNIX, kind).connect(target)
148
+ make(lambda: socket.socket(socket.AF_UNIX, kind)).connect(target)
125
149
  def send(kind):
126
- socket.socket(socket.AF_UNIX, kind).sendto(b"x", path + ".dgram")
150
+ make(lambda: socket.socket(socket.AF_UNIX, kind)).sendto(b"x", path + ".dgram")
127
151
  def pair(kind):
128
152
  # An explicit address on a socketpair datagram socket is honoured by the kernel.
129
- first, _ = socket.socketpair(socket.AF_UNIX, kind)
130
- first.sendto(b"x", path + ".dgram")
153
+ first, _ = make(lambda: socket.socketpair(socket.AF_UNIX, kind))
154
+ try:
155
+ first.sendto(b"x", path + ".dgram")
156
+ except OSError as error:
157
+ # the OS ignores no explicit address on a connected socket (macOS): no such vector there
158
+ if error.errno == errno.EISCONN:
159
+ raise Unsupported()
160
+ raise
131
161
  print(" ".join([
132
162
  attempt("stream", lambda: connect(socket.SOCK_STREAM, path)),
133
163
  attempt("seqpacket", lambda: connect(socket.SOCK_SEQPACKET, path + ".seq")),
@@ -159,8 +189,12 @@ os.makedirs(base + "/dir")
159
189
  os.symlink(outside, base + "/link")
160
190
  open(base + "/swapping", "w").close()
161
191
  swaps = 0
192
+ def exchange(a, b):
193
+ if sys.platform == "darwin":
194
+ return libc.renamex_np(a, b, 2) # RENAME_SWAP
195
+ return libc.renameat2(-100, a, -100, b, 2) # RENAME_EXCHANGE
162
196
  while not os.path.exists(stop):
163
- if libc.renameat2(-100, (base + "/dir").encode(), -100, (base + "/link").encode(), 2) == 0:
197
+ if exchange((base + "/dir").encode(), (base + "/link").encode()) == 0:
164
198
  swaps += 1
165
199
  print("swaps=%d" % swaps)
166
200
  `;
@@ -310,7 +344,7 @@ export async function runSandboxPermissionConformance(fixture) {
310
344
  };
311
345
  // Positive controls: ordinary shell, Python, Node and native work inside the root.
312
346
  const shell = await exec(restricted(), "cat inroot.txt && printf shell > shell.txt && mkdir -p d/e && printf x > d/e/f && " +
313
- "chmod 755 d/e/f && touch -d 2001-01-01 d/e/f && ln -s shell.txt alias && cat alias");
347
+ "chmod 755 d/e/f && touch -t 200101010000 d/e/f && ln -s shell.txt alias && cat alias");
314
348
  assert.equal(shell.exitCode, 0, `restricted shell work must succeed: ${shell.stderr}`);
315
349
  assert.equal(shell.stdout, "inrootshell");
316
350
  assert.equal(await fixture.inspect.mode(at(root, "d/e/f")), 0o755, "chmod inside the root");
@@ -448,10 +482,14 @@ export async function runSandboxPermissionConformance(fixture) {
448
482
  ".envrc",
449
483
  ".npmrc",
450
484
  "deep/.npmrc",
451
- ".BASHRC",
452
- ".envrc",
485
+ ...(fixture.foldedNames === "filesystem" ? [".bashrc"] : [".BASHRC", ".envrc"]),
453
486
  ])
454
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}`);
492
+ }
455
493
  await denied((await native(restricted())).writeFile(at(root, "repo/.git/modules/sub/config"), bytes, signal), "native write of a submodule's config");
456
494
  await denied((await native(restricted())).writeFile(at(root, "bare2/HEAD"), bytes, signal), "native write of a bare-repository HEAD");
457
495
  // No repository can be forged inside git's own allowlisted subtrees, and hook managers
@@ -505,7 +543,7 @@ export async function runSandboxPermissionConformance(fixture) {
505
543
  assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
506
544
  await exec(restricted(), `printf pwn > ${quote(at(sibling, "w1"))}; printf pwn > linked/w2; printf pwn > escape; ` +
507
545
  `chmod 777 ${quote(at(sibling, "secret"))}; chmod 777 escape; ` +
508
- `touch -d 2001-01-01 ${quote(at(sibling, "secret"))}; true`);
546
+ `touch -t 200101010000 ${quote(at(sibling, "secret"))}; true`);
509
547
  assert.equal(await fixture.inspect.readFile(at(sibling, "w1")), null, "sibling write");
510
548
  assert.equal(await fixture.inspect.readFile(at(sibling, "w2")), null, "symlinked dir write");
511
549
  await siblingIntact("restricted writes and chmod must not change the sibling");
@@ -523,13 +561,16 @@ export async function runSandboxPermissionConformance(fixture) {
523
561
  await siblingIntact("native denials must leave the sibling unchanged");
524
562
  // Network: only the granted endpoint, and only while allowlisted.
525
563
  const base = await receipts();
526
- const positives = proxied
527
- ? [byName(granted), urlopen(granted)]
528
- : [
529
- connect(granted),
530
- `curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
531
- `node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
532
- ];
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
+ ];
533
574
  for (const command of positives) {
534
575
  const result = await exec(restricted(allowlisted), command);
535
576
  assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
@@ -557,7 +598,9 @@ export async function runSandboxPermissionConformance(fixture) {
557
598
  // Restricted network none/allowlist may listen on loopback only.
558
599
  for (const network of [{ kind: "none" }, allowlisted]) {
559
600
  const binds = await exec(restricted(network), `python3 -c ${quote(BIND_PROGRAM)}`);
560
- assert.equal(binds.stdout.trim(), "127.0.0.1=ok ::1=ok 0.0.0.0=denied ::=denied unspec=denied", `restricted ${network.kind} binds loopback only: ${binds.stderr}`);
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}`);
561
604
  }
562
605
  // Pathname UNIX sockets: a service outside the roots is unreachable under every network kind
563
606
  // (including environment, which lifts only the network filter); one inside the root works.
@@ -573,23 +616,51 @@ export async function runSandboxPermissionConformance(fixture) {
573
616
  await denied(exec(restricted({ kind: "environment" }), `printf ran > ${quote(at(root, "env-ran"))}`), "a restricted environment-network operation must be refused by policy");
574
617
  assert.equal(await fixture.inspect.readFile(at(root, "env-ran")), null);
575
618
  }
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(" ");
576
633
  for (const network of [
577
634
  { kind: "none" },
578
635
  allowlisted,
579
636
  ...(fixture.restrictedEnvironment === "refused" ? [] : [{ kind: "environment" }]),
580
637
  ]) {
581
638
  const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
582
- assert.equal(probe.stdout.trim(), "stream=denied seqpacket=denied dgram=denied raw=denied link=denied pair-dgram=denied pair-raw=denied", `restricted ${network.kind} must not reach a UNIX service outside the roots: ${probe.stderr}`);
639
+ assert.equal(
640
+ // a type the OS lacks may also be refused before the OS says so: both reach nothing
641
+ probe.stdout
642
+ .trim()
643
+ .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}`);
583
649
  const inside = await exec(restricted(network), `python3 -c ${quote(UNIX_ROUNDTRIP)} ${quote(at(root, `own-${network.kind}.sock`))}`);
584
- assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
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}`);
585
655
  }
586
656
  assert.equal(text(await fixture.inspect.readFile(at(sibling, "srv.count"))), "0", "the outside UNIX service must see no client");
587
657
  // The same client under Full access reaches the service seven times: the probe is real.
588
658
  const control = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
589
- assert.equal(control.stdout.trim(), "stream=ok seqpacket=ok dgram=ok raw=ok link=ok pair-dgram=ok pair-raw=ok", `Full UNIX control: ${control.stderr}`);
659
+ assert.equal(control.stdout.trim(), expectWhen(true), `Full UNIX control: ${control.stderr}`);
660
+ const reached = String(kinds.filter(([, state]) => state !== "unsupported").length);
590
661
  await waitForFile(async (path) => {
591
662
  const data = await fixture.inspect.readFile(path);
592
- return text(data) === "7" ? data : null;
663
+ return text(data) === reached ? data : null;
593
664
  }, at(sibling, "srv.count"), outside);
594
665
  server.abort();
595
666
  await outside;
@@ -654,7 +725,9 @@ export async function runSandboxPermissionConformance(fixture) {
654
725
  await exec(full, `mv ${quote(root)} ${quote(moved)} && ln -s ${quote(sibling)} ${quote(root)} && touch ${quote(at(moved, "barrier-root"))}`);
655
726
  const swapped = await live;
656
727
  assert(!swapped.stdout.includes(secret), "a live operation must not follow a root swap");
657
- assert.equal(text(await fixture.inspect.readFile(at(moved, "in-place"))), "ok");
728
+ // an inode-pinned runtime (Landlock) keeps writing in the moved root; a path-based one
729
+ // (Seatbelt) refuses the moved path: either way nothing follows the swap
730
+ assert([null, "ok"].includes(text(await fixture.inspect.readFile(at(moved, "in-place")))), "a live operation writes in place or nowhere");
658
731
  await denied((async () => (await native(restricted())).writeFile(at(root, "fresh"), bytes, signal))(), "a fresh native operation must reject a swapped root");
659
732
  const fresh = await (await fixture.operation(restricted()))
660
733
  .exec({
@@ -720,12 +793,16 @@ export async function runSandboxPermissionConformance(fixture) {
720
793
  const keepAlive = exec(restricted(), `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
721
794
  await waitFor(at(root, "ready-keep"), keepAlive);
722
795
  const abort = new AbortController();
796
+ const regrouped = fixture.regroupedDescendants !== "not-promised";
723
797
  const cancelled = exec(restricted(), `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
724
798
  `setsid sleep 1002 > /dev/null 2>&1 & ` +
725
- `python3 -c ${quote("import os, time\nif os.fork() == 0:\n os.setpgid(0, 0)\n open('p3.tmp', 'w').write(str(os.getpid()))\n os.rename('p3.tmp', 'p3')\n time.sleep(1003)")} & ` +
726
- `until [ -e p3 ]; do sleep 0.01; done; printf r > ready-cancel; sleep 1004`, abort.signal);
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);
727
804
  await waitFor(at(root, "ready-cancel"), cancelled);
728
- const pids = await Promise.all(["p1", "p2", "p3"].map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
805
+ const pids = await Promise.all((regrouped ? ["p1", "p2", "p3"] : ["p1", "p2"]).map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
729
806
  assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
730
807
  abort.abort();
731
808
  const stopped = await cancelled;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.27",
3
+ "version": "0.1.0-rc.28",
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,17 +47,17 @@
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.48"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.50"
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.6",
56
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.34"
56
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.36"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.34",
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.36",
61
61
  "@capybara-hq/plugin-tools": "^0.1.0-rc.17"
62
62
  },
63
63
  "peerDependenciesMeta": {