@capybara-hq/testing 0.1.0-rc.20 → 0.1.0-rc.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/kernel-helpers.d.ts +8 -0
- package/dist/kernel-helpers.js +29 -0
- package/dist/model-conformance.d.ts +6 -10
- package/dist/model-conformance.js +5 -13
- package/dist/sandbox-permission-conformance.d.ts +60 -0
- package/dist/sandbox-permission-conformance.js +486 -0
- package/package.json +6 -6
package/dist/index.d.ts
CHANGED
|
@@ -20,8 +20,9 @@ export { defaultFakeOpenApiSpec, type FakeOpenApiRequest, type FakeOpenApiServer
|
|
|
20
20
|
export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
|
|
21
21
|
export { type FakeTelegramBot, type FakeTelegramCall, type FakeTelegramFailure, type FakeTelegramMessage, type FakeTelegramOptions, type FakeTelegramServer, findTelegramButton, startFakeTelegram, type TgChat, type TgUser, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
|
|
22
22
|
export { FAKE_EXTENSIONS, type FakeExtensionName, fakeExtensionDir, fakeExtensionEntry, type PackedFixture, packFixture, } from "./fixtures.js";
|
|
23
|
-
export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, type KernelApp, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, type TestKernel, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
|
|
23
|
+
export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, enableModelProviders, eventsOf, joinOrg, type KernelApp, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, type TestKernel, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
|
|
24
24
|
export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
|
|
25
25
|
export { type ConformanceTarget, checkDeclaredParameters, describeModelProviderConformance, MEDIA_SAMPLES, thinkingReplayParams, } from "./model-conformance.js";
|
|
26
26
|
export { type NativeFixtureEntry, runSandboxNativeConformance, type SandboxNativeFixture, } from "./sandbox-native-conformance.js";
|
|
27
|
+
export { runSandboxPermissionConformance, type SandboxPermissionEndpoint, type SandboxPermissionFixture, type SandboxPermissionGrant, } from "./sandbox-permission-conformance.js";
|
|
27
28
|
export { openSse, type SseClient, type SseMessage } from "./sse.js";
|
package/dist/index.js
CHANGED
|
@@ -20,8 +20,9 @@ export { defaultFakeOpenApiSpec, startFakeOpenApiServer, } from "./fake-openapi-
|
|
|
20
20
|
export { findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
|
|
21
21
|
export { findTelegramButton, startFakeTelegram, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
|
|
22
22
|
export { FAKE_EXTENSIONS, fakeExtensionDir, fakeExtensionEntry, packFixture, } from "./fixtures.js";
|
|
23
|
-
export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
|
|
23
|
+
export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, enableModelProviders, eventsOf, joinOrg, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
|
|
24
24
|
export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
|
|
25
25
|
export { checkDeclaredParameters, describeModelProviderConformance, MEDIA_SAMPLES, thinkingReplayParams, } from "./model-conformance.js";
|
|
26
26
|
export { runSandboxNativeConformance, } from "./sandbox-native-conformance.js";
|
|
27
|
+
export { runSandboxPermissionConformance, } from "./sandbox-permission-conformance.js";
|
|
27
28
|
export { openSse } from "./sse.js";
|
package/dist/kernel-helpers.d.ts
CHANGED
|
@@ -87,6 +87,14 @@ export declare function createLocalAccount(db: KernelSchemaDb, login: string, di
|
|
|
87
87
|
export declare function login(k: Pick<TestKernel, "http">, name: string, password?: string): Promise<KernelRequest>;
|
|
88
88
|
/** Creates an org as `req`'s user (who becomes its owner); returns its id. */
|
|
89
89
|
export declare function createOrg(req: KernelRequest, name?: string): Promise<string>;
|
|
90
|
+
/**
|
|
91
|
+
* Switches on in `orgId`, through the org's extension switch (`PUT
|
|
92
|
+
* /api/v1/orgs/:orgId/extensions/:name`; `req` is an org admin), every model provider the kernel
|
|
93
|
+
* loaded that is not on there yet, and returns their names. A model provider is on only in the
|
|
94
|
+
* orgs that enabled it (like every other extension), so a test that saves or runs an agent in a
|
|
95
|
+
* new org calls this first; `only` limits it to those providers.
|
|
96
|
+
*/
|
|
97
|
+
export declare function enableModelProviders(req: KernelRequest, orgId: string, only?: readonly string[]): Promise<string[]>;
|
|
90
98
|
/**
|
|
91
99
|
* A new account joins the org through an invitation (created by `owner`, accepted with `login`
|
|
92
100
|
* and {@link TEST_PASSWORD}); returns the account id and its signed-in request function.
|
package/dist/kernel-helpers.js
CHANGED
|
@@ -157,6 +157,35 @@ export async function createOrg(req, name = "Acme") {
|
|
|
157
157
|
expectStatus(res, 201, "create org");
|
|
158
158
|
return res.json().org.id;
|
|
159
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Switches on in `orgId`, through the org's extension switch (`PUT
|
|
162
|
+
* /api/v1/orgs/:orgId/extensions/:name`; `req` is an org admin), every model provider the kernel
|
|
163
|
+
* loaded that is not on there yet, and returns their names. A model provider is on only in the
|
|
164
|
+
* orgs that enabled it (like every other extension), so a test that saves or runs an agent in a
|
|
165
|
+
* new org calls this first; `only` limits it to those providers.
|
|
166
|
+
*/
|
|
167
|
+
export async function enableModelProviders(req, orgId, only) {
|
|
168
|
+
const list = await req({ method: "GET", url: `/api/v1/orgs/${orgId}/extensions` });
|
|
169
|
+
expectStatus(list, 200, "list the org's extensions");
|
|
170
|
+
const { extensions } = list.json();
|
|
171
|
+
const enabled = [];
|
|
172
|
+
for (const e of extensions) {
|
|
173
|
+
if (e.enabled || !e.available)
|
|
174
|
+
continue;
|
|
175
|
+
if (!e.provides.some((p) => p.startsWith("model-provider@")))
|
|
176
|
+
continue;
|
|
177
|
+
if (only !== undefined && !only.includes(e.plugin))
|
|
178
|
+
continue;
|
|
179
|
+
const on = await req({
|
|
180
|
+
method: "PUT",
|
|
181
|
+
url: `/api/v1/orgs/${orgId}/extensions/${encodeURIComponent(e.plugin)}`,
|
|
182
|
+
payload: { enabled: true },
|
|
183
|
+
});
|
|
184
|
+
expectStatus(on, 200, `enable ${e.plugin}`);
|
|
185
|
+
enabled.push(e.plugin);
|
|
186
|
+
}
|
|
187
|
+
return enabled;
|
|
188
|
+
}
|
|
160
189
|
/**
|
|
161
190
|
* A new account joins the org through an invitation (created by `owner`, accepted with `login`
|
|
162
191
|
* and {@link TEST_PASSWORD}); returns the account id and its signed-in request function.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ModelInfo, type ModelParameter, type ModelProvider, type
|
|
1
|
+
import { type ModelInfo, type ModelParameter, type ModelProvider, type ParamValue } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
interface TargetCommon {
|
|
3
3
|
model: string;
|
|
4
4
|
expect: {
|
|
@@ -15,17 +15,13 @@ interface TargetCommon {
|
|
|
15
15
|
teardown(): Promise<void>;
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
18
|
+
* The provider under test (`model-provider@2`) and its plugin name (checks the key prefix of
|
|
19
|
+
* vendor-specific parameters).
|
|
20
20
|
*/
|
|
21
|
-
export type ConformanceTarget = TargetCommon &
|
|
22
|
-
contract?: 1;
|
|
23
|
-
provider: ModelProviderV1;
|
|
24
|
-
} | {
|
|
25
|
-
contract: 2;
|
|
21
|
+
export type ConformanceTarget = TargetCommon & {
|
|
26
22
|
plugin: string;
|
|
27
23
|
provider: ModelProvider;
|
|
28
|
-
}
|
|
24
|
+
};
|
|
29
25
|
/**
|
|
30
26
|
* `@2` 参数声明检查:每个模型的 `parameters` 须通过 `assertValidDeclarations`,
|
|
31
27
|
* 每个声明的默认值须通过 `validateParams`。返回问题列表(形如 `<模型 id>: <原因>`),无问题为空。
|
|
@@ -61,6 +57,6 @@ export declare const MEDIA_SAMPLES: {
|
|
|
61
57
|
readonly word: "MANGO";
|
|
62
58
|
};
|
|
63
59
|
};
|
|
64
|
-
/** model-provider
|
|
60
|
+
/** The model-provider conformance suite (`@2`): every provider plugin should pass it. */
|
|
65
61
|
export declare function describeModelProviderConformance(name: string, setup: () => Promise<ConformanceTarget>): void;
|
|
66
62
|
export {};
|
|
@@ -3,9 +3,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
|
3
3
|
import { pdfBase64, redPngBase64 } from "./media-samples.js";
|
|
4
4
|
function streamOf(t, req, signal) {
|
|
5
5
|
const { params, ...rest } = req;
|
|
6
|
-
|
|
7
|
-
return t.provider.stream({ ...rest, params: params ?? {} }, { signal });
|
|
8
|
-
return t.provider.stream(rest, { signal });
|
|
6
|
+
return t.provider.stream({ ...rest, params: params ?? {} }, { signal });
|
|
9
7
|
}
|
|
10
8
|
/**
|
|
11
9
|
* `@2` 参数声明检查:每个模型的 `parameters` 须通过 `assertValidDeclarations`,
|
|
@@ -81,7 +79,7 @@ export const MEDIA_SAMPLES = {
|
|
|
81
79
|
},
|
|
82
80
|
};
|
|
83
81
|
const textOf = (content) => content.map((b) => (b.type === "text" ? b.text : "")).join("");
|
|
84
|
-
/** model-provider
|
|
82
|
+
/** The model-provider conformance suite (`@2`): every provider plugin should pass it. */
|
|
85
83
|
export function describeModelProviderConformance(name, setup) {
|
|
86
84
|
describe(`model-provider conformance: ${name}`, () => {
|
|
87
85
|
let t;
|
|
@@ -145,16 +143,12 @@ export function describeModelProviderConformance(name, setup) {
|
|
|
145
143
|
}));
|
|
146
144
|
expect(second.done.content.some((b) => b.type === "text")).toBe(true);
|
|
147
145
|
});
|
|
148
|
-
/**
|
|
146
|
+
/** The thinking case's parameters, see {@link thinkingReplayParams}. */
|
|
149
147
|
const thinkingOver = async () => {
|
|
150
|
-
if (t.contract !== 2)
|
|
151
|
-
return { effort: "high" };
|
|
152
148
|
const info = (await t.provider.listModels()).find((m) => m.id === t.model);
|
|
153
149
|
return { params: thinkingReplayParams(info?.parameters ?? []) };
|
|
154
150
|
};
|
|
155
|
-
it("declares valid parameters", async (
|
|
156
|
-
if (t.contract !== 2)
|
|
157
|
-
return ctx.skip();
|
|
151
|
+
it("declares valid parameters", async () => {
|
|
158
152
|
expect(checkDeclaredParameters(t.plugin, await t.provider.listModels())).toEqual([]);
|
|
159
153
|
});
|
|
160
154
|
it("thinking replay", async (ctx) => {
|
|
@@ -211,10 +205,8 @@ export function describeModelProviderConformance(name, setup) {
|
|
|
211
205
|
}));
|
|
212
206
|
expect(done.content.length).toBeGreaterThan(0);
|
|
213
207
|
});
|
|
214
|
-
/**
|
|
208
|
+
/** The model's declared capabilities (null when it is not listed). */
|
|
215
209
|
const caps = async () => {
|
|
216
|
-
if (t.contract !== 2)
|
|
217
|
-
return null;
|
|
218
210
|
const info = (await t.provider.listModels()).find((m) => m.id === t.model);
|
|
219
211
|
return info?.capabilities ?? null;
|
|
220
212
|
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type PermissionProfile, type SandboxFileScope, type SandboxNetworkScope, type SandboxOperation, type SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { NativeFixtureEntry } from "./sandbox-native-conformance.js";
|
|
3
|
+
/** A controlled endpoint whose receipts the fixture counts out of band (never via the device). */
|
|
4
|
+
export interface SandboxPermissionEndpoint {
|
|
5
|
+
/** A numeric address the device can reach directly. */
|
|
6
|
+
readonly host: string;
|
|
7
|
+
readonly port: number;
|
|
8
|
+
/** Accepted connections so far, observed by the endpoint itself. */
|
|
9
|
+
receipts(): Promise<number>;
|
|
10
|
+
}
|
|
11
|
+
/** The scope one fresh operation receives; the fixture adds the IDs and revisions. */
|
|
12
|
+
export interface SandboxPermissionGrant {
|
|
13
|
+
readonly profile: PermissionProfile;
|
|
14
|
+
readonly filesystem: SandboxFileScope;
|
|
15
|
+
readonly network: SandboxNetworkScope;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The actual provider under test, on one shared device. All paths are absolute device paths on one
|
|
19
|
+
* shared filesystem; `root` and `sibling` are empty directories owned by the device user. The
|
|
20
|
+
* device must provide `/bin/sh`, `python3`, `node` and `curl`. Inspection is trusted, out of band
|
|
21
|
+
* and read-only; it never runs through a restricted operation and never grants anything.
|
|
22
|
+
*/
|
|
23
|
+
export interface SandboxPermissionFixture {
|
|
24
|
+
/** The project root granted (writable) to restricted operations. */
|
|
25
|
+
readonly root: string;
|
|
26
|
+
/** A directory outside every restricted grant, on the same filesystem. */
|
|
27
|
+
readonly sibling: string;
|
|
28
|
+
/** Existing files the device user may write ordinarily but no restricted grant covers. */
|
|
29
|
+
readonly protectedPaths: readonly string[];
|
|
30
|
+
/** `granted` is reachable by allowlisting its host; `ungranted` never is. */
|
|
31
|
+
readonly endpoints: {
|
|
32
|
+
readonly granted: SandboxPermissionEndpoint;
|
|
33
|
+
readonly ungranted: readonly SandboxPermissionEndpoint[];
|
|
34
|
+
};
|
|
35
|
+
/** The provider's own runtime report; the harness never infers support from a fixture. */
|
|
36
|
+
support(): Promise<SandboxPermissionSupport>;
|
|
37
|
+
/** A fresh operation (new operation ID) for the grant, through the provider's factory. */
|
|
38
|
+
operation(grant: SandboxPermissionGrant): Promise<SandboxOperation>;
|
|
39
|
+
/** Trusted setup under root or sibling; preserves entries from earlier calls. */
|
|
40
|
+
seed(entries: readonly NativeFixtureEntry[]): Promise<void>;
|
|
41
|
+
inspect: {
|
|
42
|
+
readFile(path: string): Promise<Uint8Array | null>;
|
|
43
|
+
/** Permission bits (`st_mode & 0o7777`), or null when missing. */
|
|
44
|
+
mode(path: string): Promise<number | null>;
|
|
45
|
+
/** The subset of `pids` still running on the device. */
|
|
46
|
+
alive(pids: readonly number[]): Promise<number[]>;
|
|
47
|
+
};
|
|
48
|
+
/** Removes fixture-owned resources, including after an assertion failure. */
|
|
49
|
+
dispose(): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Proves an actual provider's permission boundary on one shared device: positive controls, sibling,
|
|
53
|
+
* symlink, protected-path and network denials, Full controls without restricted filters, both
|
|
54
|
+
* overlap orders, component/root swaps and mutable syscall pointers during access, exact
|
|
55
|
+
* cancellation and fresh narrowed scopes. Restricted network none/allowlist may bind and listen on
|
|
56
|
+
* loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
|
|
57
|
+
* every network kind, environment included; metadata reads outside the roots are not covered. A provider that reports restricted unsupported must
|
|
58
|
+
* refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
|
|
59
|
+
*/
|
|
60
|
+
export declare function runSandboxPermissionConformance(fixture: SandboxPermissionFixture): Promise<void>;
|
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { posix } from "node:path";
|
|
4
|
+
import { isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
|
|
5
|
+
const text = (data) => (data === null ? null : Buffer.from(data).toString());
|
|
6
|
+
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
7
|
+
/** A Python program in which one thread rewrites a syscall's pointer argument mid-call. */
|
|
8
|
+
const FLIP_PROGRAM = String.raw `
|
|
9
|
+
import ctypes, socket, struct, sys, threading
|
|
10
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
11
|
+
mode, rounds = sys.argv[1], int(sys.argv[2])
|
|
12
|
+
stop = threading.Event()
|
|
13
|
+
def flipper(buffer, good, bad):
|
|
14
|
+
while not stop.is_set():
|
|
15
|
+
ctypes.memmove(buffer, bad, len(bad))
|
|
16
|
+
ctypes.memmove(buffer, good, len(good))
|
|
17
|
+
ok = 0
|
|
18
|
+
if mode == "connect":
|
|
19
|
+
def sockaddr(host, port):
|
|
20
|
+
return struct.pack("HH4s8x", socket.AF_INET, socket.htons(port), socket.inet_aton(host))
|
|
21
|
+
good = sockaddr(sys.argv[3], int(sys.argv[4]))
|
|
22
|
+
bad = sockaddr(sys.argv[5], int(sys.argv[6]))
|
|
23
|
+
buffer = ctypes.create_string_buffer(good, len(good))
|
|
24
|
+
thread = threading.Thread(target=flipper, args=(buffer, good, bad))
|
|
25
|
+
thread.start()
|
|
26
|
+
for _ in range(rounds):
|
|
27
|
+
fd = libc.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
|
|
28
|
+
if fd >= 0 and libc.connect(fd, buffer, len(good)) == 0:
|
|
29
|
+
ok += 1
|
|
30
|
+
if fd >= 0:
|
|
31
|
+
libc.close(fd)
|
|
32
|
+
else:
|
|
33
|
+
good, bad = sys.argv[3].encode() + b"\0", sys.argv[4].encode() + b"\0"
|
|
34
|
+
size = max(len(good), len(bad))
|
|
35
|
+
good, bad = good.ljust(size, b"\0"), bad.ljust(size, b"\0")
|
|
36
|
+
buffer = ctypes.create_string_buffer(good, size)
|
|
37
|
+
thread = threading.Thread(target=flipper, args=(buffer, good, bad))
|
|
38
|
+
thread.start()
|
|
39
|
+
for index in range(rounds):
|
|
40
|
+
if libc.chmod(buffer, 0o640 if index % 2 else 0o600) == 0:
|
|
41
|
+
ok += 1
|
|
42
|
+
stop.set()
|
|
43
|
+
thread.join()
|
|
44
|
+
print("ok=%d" % ok)
|
|
45
|
+
`;
|
|
46
|
+
/** Binds and listens on each address; restricted none/allowlist must allow loopback only. */
|
|
47
|
+
const BIND_PROGRAM = `
|
|
48
|
+
import socket
|
|
49
|
+
out = []
|
|
50
|
+
for family, host in ((socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1"),
|
|
51
|
+
(socket.AF_INET, "0.0.0.0"), (socket.AF_INET6, "::")):
|
|
52
|
+
s = socket.socket(family, socket.SOCK_STREAM)
|
|
53
|
+
try:
|
|
54
|
+
s.bind((host, 0))
|
|
55
|
+
s.listen(1)
|
|
56
|
+
out.append(host + "=ok")
|
|
57
|
+
except OSError:
|
|
58
|
+
out.append(host + "=denied")
|
|
59
|
+
s.close()
|
|
60
|
+
# Dissolving an association (connect AF_UNSPEC) must not turn listen() into a bind to any address.
|
|
61
|
+
import ctypes
|
|
62
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
63
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
64
|
+
libc.connect(s.fileno(), ctypes.create_string_buffer(16), 16)
|
|
65
|
+
try:
|
|
66
|
+
s.listen(1)
|
|
67
|
+
out.append("unspec=" + s.getsockname()[0])
|
|
68
|
+
except OSError:
|
|
69
|
+
out.append("unspec=denied")
|
|
70
|
+
print(" ".join(out))
|
|
71
|
+
`;
|
|
72
|
+
/** A Full-access UNIX service (stream, seqpacket, datagram) counting every client it sees. */
|
|
73
|
+
const UNIX_SERVER = `
|
|
74
|
+
import os, socket, sys, threading
|
|
75
|
+
path, counter = sys.argv[1], sys.argv[2]
|
|
76
|
+
lock = threading.Lock()
|
|
77
|
+
count = [0]
|
|
78
|
+
def seen():
|
|
79
|
+
with lock:
|
|
80
|
+
count[0] += 1
|
|
81
|
+
with open(counter + ".tmp", "w") as handle:
|
|
82
|
+
handle.write(str(count[0]))
|
|
83
|
+
os.replace(counter + ".tmp", counter)
|
|
84
|
+
def serve(kind, suffix):
|
|
85
|
+
s = socket.socket(socket.AF_UNIX, kind)
|
|
86
|
+
s.bind(path + suffix)
|
|
87
|
+
if kind == socket.SOCK_DGRAM:
|
|
88
|
+
while True:
|
|
89
|
+
s.recv(100)
|
|
90
|
+
seen()
|
|
91
|
+
s.listen(16)
|
|
92
|
+
while True:
|
|
93
|
+
s.accept()[0].close()
|
|
94
|
+
seen()
|
|
95
|
+
threads = [threading.Thread(target=serve, args=a, daemon=True)
|
|
96
|
+
for a in ((socket.SOCK_STREAM, ""), (socket.SOCK_SEQPACKET, ".seq"), (socket.SOCK_DGRAM, ".dgram"))]
|
|
97
|
+
for thread in threads:
|
|
98
|
+
thread.start()
|
|
99
|
+
with open(counter + ".tmp", "w") as handle:
|
|
100
|
+
handle.write("0")
|
|
101
|
+
while not all(os.path.exists(path + suffix) for suffix in ("", ".seq", ".dgram")):
|
|
102
|
+
pass
|
|
103
|
+
os.replace(counter + ".tmp", counter)
|
|
104
|
+
threading.Event().wait()
|
|
105
|
+
`;
|
|
106
|
+
/** Tries every way to reach the outside UNIX service; prints ok/denied per attempt. */
|
|
107
|
+
const UNIX_CLIENT = `
|
|
108
|
+
import socket, sys
|
|
109
|
+
path, link = sys.argv[1], sys.argv[2]
|
|
110
|
+
def attempt(name, action):
|
|
111
|
+
try:
|
|
112
|
+
action()
|
|
113
|
+
return name + "=ok"
|
|
114
|
+
except OSError:
|
|
115
|
+
return name + "=denied"
|
|
116
|
+
def connect(kind, target):
|
|
117
|
+
socket.socket(socket.AF_UNIX, kind).connect(target)
|
|
118
|
+
def send(kind):
|
|
119
|
+
socket.socket(socket.AF_UNIX, kind).sendto(b"x", path + ".dgram")
|
|
120
|
+
def pair(kind):
|
|
121
|
+
# An explicit address on a socketpair datagram socket is honoured by the kernel.
|
|
122
|
+
first, _ = socket.socketpair(socket.AF_UNIX, kind)
|
|
123
|
+
first.sendto(b"x", path + ".dgram")
|
|
124
|
+
print(" ".join([
|
|
125
|
+
attempt("stream", lambda: connect(socket.SOCK_STREAM, path)),
|
|
126
|
+
attempt("seqpacket", lambda: connect(socket.SOCK_SEQPACKET, path + ".seq")),
|
|
127
|
+
attempt("dgram", lambda: send(socket.SOCK_DGRAM)),
|
|
128
|
+
attempt("raw", lambda: send(socket.SOCK_RAW)),
|
|
129
|
+
attempt("link", lambda: connect(socket.SOCK_STREAM, link)),
|
|
130
|
+
attempt("pair-dgram", lambda: pair(socket.SOCK_DGRAM)),
|
|
131
|
+
attempt("pair-raw", lambda: pair(socket.SOCK_RAW)),
|
|
132
|
+
]))
|
|
133
|
+
`;
|
|
134
|
+
/** A UNIX stream server and client inside the root talk to each other. */
|
|
135
|
+
const UNIX_ROUNDTRIP = `
|
|
136
|
+
import socket, sys
|
|
137
|
+
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
138
|
+
server.bind(sys.argv[1])
|
|
139
|
+
server.listen(1)
|
|
140
|
+
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
141
|
+
client.connect(sys.argv[1])
|
|
142
|
+
peer = server.accept()[0]
|
|
143
|
+
client.sendall(b"ping")
|
|
144
|
+
print("roundtrip=ok" if peer.recv(4) == b"ping" else "roundtrip=bad")
|
|
145
|
+
`;
|
|
146
|
+
/** Atomically exchanges a directory with a symlink to an outside path until a stop file exists. */
|
|
147
|
+
const SWAP_PROGRAM = `
|
|
148
|
+
import ctypes, os, sys
|
|
149
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
150
|
+
base, outside, stop = sys.argv[1], sys.argv[2], sys.argv[3]
|
|
151
|
+
os.makedirs(base + "/dir")
|
|
152
|
+
os.symlink(outside, base + "/link")
|
|
153
|
+
open(base + "/swapping", "w").close()
|
|
154
|
+
swaps = 0
|
|
155
|
+
while not os.path.exists(stop):
|
|
156
|
+
if libc.renameat2(-100, (base + "/dir").encode(), -100, (base + "/link").encode(), 2) == 0:
|
|
157
|
+
swaps += 1
|
|
158
|
+
print("swaps=%d" % swaps)
|
|
159
|
+
`;
|
|
160
|
+
/**
|
|
161
|
+
* Proves an actual provider's permission boundary on one shared device: positive controls, sibling,
|
|
162
|
+
* symlink, protected-path and network denials, Full controls without restricted filters, both
|
|
163
|
+
* overlap orders, component/root swaps and mutable syscall pointers during access, exact
|
|
164
|
+
* cancellation and fresh narrowed scopes. Restricted network none/allowlist may bind and listen on
|
|
165
|
+
* loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
|
|
166
|
+
* every network kind, environment included; metadata reads outside the roots are not covered. A provider that reports restricted unsupported must
|
|
167
|
+
* refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
|
|
168
|
+
*/
|
|
169
|
+
export async function runSandboxPermissionConformance(fixture) {
|
|
170
|
+
const { root, sibling } = fixture;
|
|
171
|
+
const at = (base, name) => posix.join(base, name);
|
|
172
|
+
const secret = `sibling-secret-${randomUUID()}`;
|
|
173
|
+
const scoped = (writeRoots) => ({
|
|
174
|
+
kind: "scoped",
|
|
175
|
+
readRoots: [],
|
|
176
|
+
writeRoots,
|
|
177
|
+
});
|
|
178
|
+
const restricted = (network = { kind: "none" }, writeRoots = [root]) => ({
|
|
179
|
+
profile: "approve-for-me",
|
|
180
|
+
filesystem: scoped(writeRoots),
|
|
181
|
+
network,
|
|
182
|
+
});
|
|
183
|
+
const full = {
|
|
184
|
+
profile: "full-access",
|
|
185
|
+
filesystem: { kind: "device" },
|
|
186
|
+
network: { kind: "environment" },
|
|
187
|
+
};
|
|
188
|
+
const { granted, ungranted } = fixture.endpoints;
|
|
189
|
+
const allowlisted = { kind: "allowlist", hosts: [granted.host] };
|
|
190
|
+
const exec = async (grant, command, signal = new AbortController().signal, timeoutMs = 120_000) => (await fixture.operation(grant)).exec({
|
|
191
|
+
command,
|
|
192
|
+
cwd: root,
|
|
193
|
+
timeoutMs,
|
|
194
|
+
maxOutputBytes: 1 << 20,
|
|
195
|
+
signal,
|
|
196
|
+
});
|
|
197
|
+
const native = async (grant) => {
|
|
198
|
+
const operation = await fixture.operation(grant);
|
|
199
|
+
assert(operation.list && operation.scan, "Permission conformance requires list and scan");
|
|
200
|
+
return operation;
|
|
201
|
+
};
|
|
202
|
+
const signal = new AbortController().signal;
|
|
203
|
+
const denied = async (promise, what) => {
|
|
204
|
+
await assert.rejects(promise, (error) => isSandboxScopeDeniedError(error), what);
|
|
205
|
+
};
|
|
206
|
+
const waitFor = async (path) => {
|
|
207
|
+
while ((await fixture.inspect.readFile(path)) === null) {
|
|
208
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
const receipts = async () => Promise.all([granted, ...ungranted].map((endpoint) => endpoint.receipts()));
|
|
212
|
+
const connect = (endpoint) => `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(endpoint.host)}, ${endpoint.port}), 10).close()`)}`;
|
|
213
|
+
try {
|
|
214
|
+
const support = await fixture.support();
|
|
215
|
+
if (support.restricted === null) {
|
|
216
|
+
// Fail closed: no restricted operation may run, and nothing falls back to Full access.
|
|
217
|
+
await assert.rejects((async () => (await fixture.operation(restricted())).exec({
|
|
218
|
+
command: "true",
|
|
219
|
+
cwd: root,
|
|
220
|
+
timeoutMs: 10_000,
|
|
221
|
+
maxOutputBytes: 1024,
|
|
222
|
+
signal,
|
|
223
|
+
}))(), (error) => isSandboxPermissionUnsupportedError(error), "an unsupported runtime must refuse restricted operations");
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
assert.deepEqual(support.restricted, { filesystem: true, network: true, native: true, concurrentScopes: true }, "restricted support requires all four claims together");
|
|
227
|
+
await fixture.seed([
|
|
228
|
+
{ path: at(sibling, "secret"), kind: "file", data: new TextEncoder().encode(secret) },
|
|
229
|
+
{ path: at(root, "inroot.txt"), kind: "file", data: new TextEncoder().encode("inroot") },
|
|
230
|
+
{ path: at(root, "escape"), kind: "symlink", target: at(sibling, "secret") },
|
|
231
|
+
{ path: at(root, "linked"), kind: "symlink", target: sibling },
|
|
232
|
+
]);
|
|
233
|
+
const siblingMode = await fixture.inspect.mode(at(sibling, "secret"));
|
|
234
|
+
const siblingIntact = async (label) => {
|
|
235
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "secret"))), secret, label);
|
|
236
|
+
assert.equal(await fixture.inspect.mode(at(sibling, "secret")), siblingMode, label);
|
|
237
|
+
};
|
|
238
|
+
// Positive controls: ordinary shell, Python, Node and native work inside the root.
|
|
239
|
+
const shell = await exec(restricted(), "cat inroot.txt && printf shell > shell.txt && mkdir -p d/e && printf x > d/e/f && " +
|
|
240
|
+
"chmod 755 d/e/f && touch -d 2001-01-01 d/e/f && ln -s shell.txt alias && cat alias");
|
|
241
|
+
assert.equal(shell.exitCode, 0, `restricted shell work must succeed: ${shell.stderr}`);
|
|
242
|
+
assert.equal(shell.stdout, "inrootshell");
|
|
243
|
+
assert.equal(await fixture.inspect.mode(at(root, "d/e/f")), 0o755, "chmod inside the root");
|
|
244
|
+
const python = await exec(restricted(), `python3 -c ${quote("import pathlib; p = pathlib.Path('py.txt'); p.write_text('py'); print(p.read_text())")}`);
|
|
245
|
+
assert.equal(python.exitCode, 0, `restricted Python work must succeed: ${python.stderr}`);
|
|
246
|
+
assert.equal(python.stdout.trim(), "py");
|
|
247
|
+
const node = await exec(restricted(), `node -e ${quote("const fs = require('fs'); fs.writeFileSync('node.txt', 'node'); console.log(fs.readFileSync('node.txt', 'utf8'))")}`);
|
|
248
|
+
assert.equal(node.exitCode, 0, `restricted Node work must succeed: ${node.stderr}`);
|
|
249
|
+
assert.equal(node.stdout.trim(), "node");
|
|
250
|
+
const bytes = new Uint8Array([0, 1, 2, 255]);
|
|
251
|
+
await (await native(restricted())).writeFile(at(root, "native/n.bin"), bytes, signal);
|
|
252
|
+
assert.deepEqual(await (await native(restricted())).readFile(at(root, "native/n.bin"), {
|
|
253
|
+
maxBytes: 10,
|
|
254
|
+
signal,
|
|
255
|
+
}), { data: bytes, truncated: false });
|
|
256
|
+
assert.deepEqual(await (await native(restricted())).stat(at(root, "native/n.bin"), signal), {
|
|
257
|
+
size: 4,
|
|
258
|
+
isDir: false,
|
|
259
|
+
});
|
|
260
|
+
assert.deepEqual(await (await native(restricted())).list(at(root, "native"), {
|
|
261
|
+
limit: 10,
|
|
262
|
+
signal,
|
|
263
|
+
}), { entries: [{ name: "n.bin", isDir: false }], truncated: false });
|
|
264
|
+
// Negative controls: sibling, symlink escapes and protected paths stay out of reach.
|
|
265
|
+
const reads = await exec(restricted(), `cat ${quote(at(sibling, "secret"))}; cat escape; cat linked/secret; true`);
|
|
266
|
+
assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
|
|
267
|
+
await exec(restricted(), `printf pwn > ${quote(at(sibling, "w1"))}; printf pwn > linked/w2; printf pwn > escape; ` +
|
|
268
|
+
`chmod 777 ${quote(at(sibling, "secret"))}; chmod 777 escape; ` +
|
|
269
|
+
`touch -d 2001-01-01 ${quote(at(sibling, "secret"))}; true`);
|
|
270
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "w1")), null, "sibling write");
|
|
271
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "w2")), null, "symlinked dir write");
|
|
272
|
+
await siblingIntact("restricted writes and chmod must not change the sibling");
|
|
273
|
+
for (const path of fixture.protectedPaths) {
|
|
274
|
+
const before = text(await fixture.inspect.readFile(path));
|
|
275
|
+
await exec(restricted(), `printf pwn >> ${quote(path)}; true`);
|
|
276
|
+
assert.equal(text(await fixture.inspect.readFile(path)), before, `protected ${path}`);
|
|
277
|
+
}
|
|
278
|
+
await denied((await native(restricted())).readFile(at(sibling, "secret"), { maxBytes: 100, signal }), "native sibling read");
|
|
279
|
+
await denied((await native(restricted())).readFile(at(root, "escape"), { maxBytes: 100, signal }), "native symlink escape read");
|
|
280
|
+
await denied((await native(restricted())).writeFile(at(sibling, "n1"), bytes, signal), "native sibling write");
|
|
281
|
+
await denied((await native(restricted())).writeFile(at(root, "linked/n2"), bytes, signal), "native write through a directory symlink");
|
|
282
|
+
await denied((await native(restricted())).stat(at(sibling, "secret"), signal), "stat");
|
|
283
|
+
await denied((await native(restricted())).list(sibling, { limit: 5, signal }), "list");
|
|
284
|
+
await siblingIntact("native denials must leave the sibling unchanged");
|
|
285
|
+
// Network: only the granted endpoint, and only while allowlisted.
|
|
286
|
+
const base = await receipts();
|
|
287
|
+
for (const command of [
|
|
288
|
+
connect(granted),
|
|
289
|
+
`curl -fsS -m 10 -o /dev/null http://${granted.host}:${granted.port}/`,
|
|
290
|
+
`node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.host)}).on("connect", function () { this.end() })`)}`,
|
|
291
|
+
]) {
|
|
292
|
+
const result = await exec(restricted(allowlisted), command);
|
|
293
|
+
assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
|
|
294
|
+
}
|
|
295
|
+
for (const endpoint of ungranted) {
|
|
296
|
+
const result = await exec(restricted(allowlisted), connect(endpoint));
|
|
297
|
+
assert.notEqual(result.exitCode, 0, `ungranted ${endpoint.host}:${endpoint.port}`);
|
|
298
|
+
}
|
|
299
|
+
const none = await exec(restricted(), connect(granted));
|
|
300
|
+
assert.notEqual(none.exitCode, 0, "network none must refuse even the granted endpoint");
|
|
301
|
+
const after = await receipts();
|
|
302
|
+
assert.equal(after[0], (base[0] ?? 0) + 3, "granted endpoint receipts");
|
|
303
|
+
assert.deepEqual(after.slice(1), base.slice(1), "ungranted endpoints must see no connection");
|
|
304
|
+
// Restricted network none/allowlist may listen on loopback only.
|
|
305
|
+
for (const network of [{ kind: "none" }, allowlisted]) {
|
|
306
|
+
const binds = await exec(restricted(network), `python3 -c ${quote(BIND_PROGRAM)}`);
|
|
307
|
+
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}`);
|
|
308
|
+
}
|
|
309
|
+
// Pathname UNIX sockets: a service outside the roots is unreachable under every network kind
|
|
310
|
+
// (including environment, which lifts only the network filter); one inside the root works.
|
|
311
|
+
if (support.fullAccess) {
|
|
312
|
+
const server = new AbortController();
|
|
313
|
+
const outside = exec(full, `python3 -c ${quote(UNIX_SERVER)} ${quote(at(sibling, "srv.sock"))} ${quote(at(sibling, "srv.count"))}`, server.signal);
|
|
314
|
+
await waitFor(at(sibling, "srv.count"));
|
|
315
|
+
await fixture.seed([
|
|
316
|
+
{ path: at(root, "srv-link.sock"), kind: "symlink", target: at(sibling, "srv.sock") },
|
|
317
|
+
]);
|
|
318
|
+
for (const network of [
|
|
319
|
+
{ kind: "none" },
|
|
320
|
+
allowlisted,
|
|
321
|
+
{ kind: "environment" },
|
|
322
|
+
]) {
|
|
323
|
+
const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
|
|
324
|
+
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}`);
|
|
325
|
+
const inside = await exec(restricted(network), `python3 -c ${quote(UNIX_ROUNDTRIP)} ${quote(at(root, `own-${network.kind}.sock`))}`);
|
|
326
|
+
assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
|
|
327
|
+
}
|
|
328
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "srv.count"))), "0", "the outside UNIX service must see no client");
|
|
329
|
+
// The same client under Full access reaches the service seven times: the probe is real.
|
|
330
|
+
const control = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
|
|
331
|
+
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}`);
|
|
332
|
+
while (text(await fixture.inspect.readFile(at(sibling, "srv.count"))) !== "7") {
|
|
333
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
334
|
+
}
|
|
335
|
+
server.abort();
|
|
336
|
+
await outside;
|
|
337
|
+
}
|
|
338
|
+
// Full access controls on the same device: no restricted filters apply.
|
|
339
|
+
if (support.fullAccess) {
|
|
340
|
+
const control = await exec(full, `cat ${quote(at(sibling, "secret"))} && printf full > ${quote(at(sibling, "full"))} && ${connect(ungranted[0] ?? granted)}`);
|
|
341
|
+
assert.equal(control.exitCode, 0, `Full access control must succeed: ${control.stderr}`);
|
|
342
|
+
assert(control.stdout.includes(secret), "Full access reads the sibling");
|
|
343
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "full"))), "full");
|
|
344
|
+
assert.equal((await receipts())[1], (after[1] ?? 0) + 1, "Full reaches an ungranted endpoint");
|
|
345
|
+
}
|
|
346
|
+
// Both overlap orders: a live Full operation never widens a restricted one, and vice versa.
|
|
347
|
+
if (support.fullAccess) {
|
|
348
|
+
const first = exec(restricted(), `printf r > ready-a; until [ -e barrier-a ]; do sleep 0.01; done; ` +
|
|
349
|
+
`printf pwn > ${quote(at(sibling, "overlap-a"))}; cat ${quote(at(sibling, "secret"))}; true`);
|
|
350
|
+
await waitFor(at(root, "ready-a"));
|
|
351
|
+
await exec(full, `printf full > ${quote(at(sibling, "full-a"))} && touch barrier-a`);
|
|
352
|
+
assert(!(await first).stdout.includes(secret), "restricted after a live Full operation");
|
|
353
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-a")), null);
|
|
354
|
+
const fullFirst = exec(full, `printf r > ready-b; until [ -e barrier-b ]; do sleep 0.01; done; ` +
|
|
355
|
+
`printf full > ${quote(at(sibling, "full-b"))}`);
|
|
356
|
+
await waitFor(at(root, "ready-b"));
|
|
357
|
+
const second = await exec(restricted(), `printf pwn > ${quote(at(sibling, "overlap-b"))}; cat ${quote(at(sibling, "secret"))}; touch barrier-b`);
|
|
358
|
+
assert(!second.stdout.includes(secret), "restricted while a Full operation is live");
|
|
359
|
+
assert.equal((await fullFirst).exitCode, 0);
|
|
360
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-b")), null);
|
|
361
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "full-b"))), "full");
|
|
362
|
+
}
|
|
363
|
+
// Component swaps during native and shell access never escape.
|
|
364
|
+
if (support.fullAccess) {
|
|
365
|
+
const race = at(root, "race");
|
|
366
|
+
const swapper = exec(full, `python3 -c ${quote(SWAP_PROGRAM)} ${quote(race)} ${quote(sibling)} ${quote(at(root, "race-stop"))}`);
|
|
367
|
+
await waitFor(at(race, "swapping"));
|
|
368
|
+
for (let index = 0; index < 30; index++) {
|
|
369
|
+
const op = await native(restricted());
|
|
370
|
+
try {
|
|
371
|
+
await op.writeFile(at(race, `dir/n-${index}`), bytes, signal);
|
|
372
|
+
}
|
|
373
|
+
catch { }
|
|
374
|
+
const read = await (await native(restricted()))
|
|
375
|
+
.readFile(at(race, "dir/secret"), { maxBytes: 200, signal })
|
|
376
|
+
.catch(() => null);
|
|
377
|
+
assert.notEqual(read && text(read.data), secret, "native read escaped during a swap");
|
|
378
|
+
}
|
|
379
|
+
const shellRace = await exec(restricted(), `i=0; while [ $i -lt 400 ]; do printf pwn > race/dir/x-$i; cat race/dir/secret; ` +
|
|
380
|
+
`chmod 777 race/dir/secret; i=$((i+1)); done 2>/dev/null; true`);
|
|
381
|
+
assert(!shellRace.stdout.includes(secret), "shell read escaped during a swap");
|
|
382
|
+
await exec(full, "touch race-stop");
|
|
383
|
+
assert.equal((await swapper).exitCode, 0);
|
|
384
|
+
for (let index = 0; index < 400; index++) {
|
|
385
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, `x-${index}`)), null);
|
|
386
|
+
if (index < 30)
|
|
387
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, `n-${index}`)), null);
|
|
388
|
+
}
|
|
389
|
+
await siblingIntact("component swaps must not reach the sibling");
|
|
390
|
+
// A swap of the root path itself during a live operation, then a fresh operation.
|
|
391
|
+
const moved = `${root}.moved-${randomUUID()}`;
|
|
392
|
+
const live = exec(restricted(), `printf r > ready-root; until [ -e ${quote(at(moved, "barrier-root"))} ]; do sleep 0.01; done; ` +
|
|
393
|
+
`printf pwn > ${quote(at(root, "after-swap"))}; cat ${quote(at(root, "secret"))}; printf ok > in-place; true`);
|
|
394
|
+
await waitFor(at(root, "ready-root"));
|
|
395
|
+
await exec(full, `mv ${quote(root)} ${quote(moved)} && ln -s ${quote(sibling)} ${quote(root)} && touch ${quote(at(moved, "barrier-root"))}`);
|
|
396
|
+
const swapped = await live;
|
|
397
|
+
assert(!swapped.stdout.includes(secret), "a live operation must not follow a root swap");
|
|
398
|
+
assert.equal(text(await fixture.inspect.readFile(at(moved, "in-place"))), "ok");
|
|
399
|
+
await denied((async () => (await native(restricted())).writeFile(at(root, "fresh"), bytes, signal))(), "a fresh native operation must reject a swapped root");
|
|
400
|
+
const fresh = await (await fixture.operation(restricted()))
|
|
401
|
+
.exec({
|
|
402
|
+
command: "printf pwn > fresh-exec",
|
|
403
|
+
cwd: root,
|
|
404
|
+
timeoutMs: 30_000,
|
|
405
|
+
maxOutputBytes: 1024,
|
|
406
|
+
signal,
|
|
407
|
+
})
|
|
408
|
+
.catch((error) => error);
|
|
409
|
+
assert(isSandboxScopeDeniedError(fresh) || fresh.exitCode !== 0, "a fresh exec must not run in a swapped root");
|
|
410
|
+
await exec(full, `rm ${quote(root)} && mv ${quote(moved)} ${quote(root)}`);
|
|
411
|
+
for (const name of ["after-swap", "fresh", "fresh-exec"]) {
|
|
412
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, name)), null, `root swap ${name}`);
|
|
413
|
+
}
|
|
414
|
+
await siblingIntact("root swaps must not reach the sibling");
|
|
415
|
+
}
|
|
416
|
+
// A mutable syscall pointer: another thread rewrites the address/path during the check.
|
|
417
|
+
const target = ungranted[0];
|
|
418
|
+
if (target) {
|
|
419
|
+
const before = await receipts();
|
|
420
|
+
const flip = await exec(restricted(allowlisted), `python3 -c ${quote(FLIP_PROGRAM)} connect 1500 ${granted.host} ${granted.port} ${target.host} ${target.port}`);
|
|
421
|
+
assert.equal(flip.exitCode, 0, `pointer race program must run: ${flip.stderr}`);
|
|
422
|
+
const flipped = await receipts();
|
|
423
|
+
assert.deepEqual(flipped.slice(1), before.slice(1), "a flipped sockaddr must not escape");
|
|
424
|
+
assert((flipped[0] ?? 0) > (before[0] ?? 0), "the race must also reach the granted endpoint");
|
|
425
|
+
const chmods = await exec(restricted(), `python3 -c ${quote(FLIP_PROGRAM)} chmod 3000 ${quote(at(root, "inroot.txt"))} ${quote(at(sibling, "secret"))}`);
|
|
426
|
+
assert.equal(chmods.exitCode, 0, `chmod race program must run: ${chmods.stderr}`);
|
|
427
|
+
assert.notEqual(chmods.stdout.trim(), "ok=0", "in-root chmods must succeed");
|
|
428
|
+
await siblingIntact("a flipped path must not chmod the sibling");
|
|
429
|
+
}
|
|
430
|
+
// Exact cancellation: detached descendants end; a sibling operation keeps running.
|
|
431
|
+
const keepAlive = exec(restricted(), `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
|
|
432
|
+
await waitFor(at(root, "ready-keep"));
|
|
433
|
+
const abort = new AbortController();
|
|
434
|
+
const cancelled = exec(restricted(), `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
|
|
435
|
+
`setsid sleep 1002 > /dev/null 2>&1 & ` +
|
|
436
|
+
`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)")} & ` +
|
|
437
|
+
`until [ -e p3 ]; do sleep 0.01; done; printf r > ready-cancel; sleep 1004`, abort.signal);
|
|
438
|
+
await waitFor(at(root, "ready-cancel"));
|
|
439
|
+
const pids = await Promise.all(["p1", "p2", "p3"].map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
|
|
440
|
+
assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
|
|
441
|
+
abort.abort();
|
|
442
|
+
const stopped = await cancelled;
|
|
443
|
+
assert.equal(stopped.exitCode, null, "a cancelled operation has no exit code");
|
|
444
|
+
assert.deepEqual(await fixture.inspect.alive(pids), [], "cancellation ends every descendant");
|
|
445
|
+
await exec(restricted(), "touch release-keep");
|
|
446
|
+
assert.equal((await keepAlive).exitCode, 0, "the sibling operation survives the cancel");
|
|
447
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "kept"))), "done");
|
|
448
|
+
// Timeout ends the whole owned tree as well.
|
|
449
|
+
const timed = await exec(restricted(), `(sleep 1005 & echo $! > p4); sleep 1006`, signal, 1000);
|
|
450
|
+
assert.equal(timed.timedOut, true, "a restricted timeout is reported");
|
|
451
|
+
const p4 = Number(text(await fixture.inspect.readFile(at(root, "p4"))));
|
|
452
|
+
assert.deepEqual(await fixture.inspect.alive([p4]), [], "timeout ends background children");
|
|
453
|
+
// A fresh narrowed scope (after revocation) is enforced on the very next operation, while an
|
|
454
|
+
// operation that started with the broader grant keeps it.
|
|
455
|
+
await fixture.seed([{ path: at(root, "narrow/keep"), kind: "directory" }]);
|
|
456
|
+
const narrowed = restricted({ kind: "none" }, [at(root, "narrow/keep")]);
|
|
457
|
+
const broad = exec(restricted(), `printf r > ready-broad; until [ -e narrow/keep/release-broad ]; do sleep 0.01; done; ` +
|
|
458
|
+
`printf broad > broad.txt`);
|
|
459
|
+
await waitFor(at(root, "ready-broad"));
|
|
460
|
+
const overlapping = await (await fixture.operation(narrowed)).exec({
|
|
461
|
+
command: `printf pwn > ${quote(at(root, "overlapping.txt"))}; touch release-broad; true`,
|
|
462
|
+
cwd: at(root, "narrow/keep"),
|
|
463
|
+
timeoutMs: 30_000,
|
|
464
|
+
maxOutputBytes: 1024,
|
|
465
|
+
signal,
|
|
466
|
+
});
|
|
467
|
+
assert.equal(overlapping.exitCode, 0);
|
|
468
|
+
assert.equal((await broad).exitCode, 0, "the broader live grant is retained");
|
|
469
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "broad.txt"))), "broad");
|
|
470
|
+
assert.equal(await fixture.inspect.readFile(at(root, "overlapping.txt")), null, "a concurrent narrower scope stays narrow");
|
|
471
|
+
const narrow = await (await fixture.operation(narrowed)).exec({
|
|
472
|
+
command: `printf ok > keep.txt; printf pwn > ${quote(at(root, "revoked.txt"))}; true`,
|
|
473
|
+
cwd: at(root, "narrow/keep"),
|
|
474
|
+
timeoutMs: 30_000,
|
|
475
|
+
maxOutputBytes: 1024,
|
|
476
|
+
signal,
|
|
477
|
+
});
|
|
478
|
+
assert.equal(narrow.exitCode, 0);
|
|
479
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "narrow/keep/keep.txt"))), "ok");
|
|
480
|
+
assert.equal(await fixture.inspect.readFile(at(root, "revoked.txt")), null, "revoked root");
|
|
481
|
+
await denied((await native(narrowed)).writeFile(at(root, "revoked-native"), bytes, signal), "native write after narrowing");
|
|
482
|
+
}
|
|
483
|
+
finally {
|
|
484
|
+
await fixture.dispose();
|
|
485
|
+
}
|
|
486
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capybara-hq/testing",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.21",
|
|
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.
|
|
50
|
+
"@capybara-hq/kernel": "^0.1.0-rc.37"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/pg": "^8.23.1",
|
|
54
54
|
"@types/ws": "^8.18.2",
|
|
55
|
-
"@capybara-hq/plugin-
|
|
56
|
-
"@capybara-hq/plugin-
|
|
55
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.27",
|
|
56
|
+
"@capybara-hq/plugin-client": "^0.1.0-rc.5"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
59
|
"vitest": "^5.0.5",
|
|
60
|
-
"@capybara-hq/plugin-
|
|
61
|
-
"@capybara-hq/plugin-
|
|
60
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.27",
|
|
61
|
+
"@capybara-hq/plugin-tools": "^0.1.0-rc.16"
|
|
62
62
|
},
|
|
63
63
|
"peerDependenciesMeta": {
|
|
64
64
|
"@capybara-hq/plugin-tools": {
|