@capybara-hq/testing 0.1.0-rc.21 → 0.1.0-rc.23
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/fixtures.d.ts +2 -2
- package/dist/fixtures.js +2 -2
- package/dist/kernel-helpers.d.ts +2 -1
- package/dist/kernel-helpers.js +4 -1
- package/dist/replica-runner.js +2 -0
- package/dist/sandbox-permission-conformance.d.ts +38 -4
- package/dist/sandbox-permission-conformance.js +114 -35
- package/fixtures/extensions/fake-connector/src/index.ts +41 -21
- package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
- package/package.json +5 -5
package/dist/fixtures.d.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
*
|
|
8
8
|
* | name | provides / covers |
|
|
9
9
|
* |---|---|
|
|
10
|
-
* | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`;
|
|
11
|
-
* | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`;
|
|
10
|
+
* | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`; requests go through `ctx.net.fetch` (test kernels set `net.allowInsecureLoopback`; `testKernelConfig` and `runConfig` do); deployment config `inspectAuth` (`bearer` / `api_key`), `kind` (default `fake`; `mcp` lets clients that know only the official kinds drive it) |
|
|
11
|
+
* | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`; requests go through `ctx.net.fetch`, no deployment config |
|
|
12
12
|
* | `fake-object-store` | `object-store@1` on the `startTestS3()` container (deployment config as `TestS3` gives it; POST-policy presign) |
|
|
13
13
|
* | `fake-tools-ui` | tools `write` and `web-only` (`sources` web and channel_dm; returns its call context), view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
|
|
14
14
|
* | `fake-storage-user` | tools `note` / `read_note` through `ctx.storage` (`permissions.storage`) |
|
package/dist/fixtures.js
CHANGED
|
@@ -10,8 +10,8 @@ import { fileURLToPath } from "node:url";
|
|
|
10
10
|
*
|
|
11
11
|
* | name | provides / covers |
|
|
12
12
|
* |---|---|
|
|
13
|
-
* | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`;
|
|
14
|
-
* | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`;
|
|
13
|
+
* | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`; requests go through `ctx.net.fetch` (test kernels set `net.allowInsecureLoopback`; `testKernelConfig` and `runConfig` do); deployment config `inspectAuth` (`bearer` / `api_key`), `kind` (default `fake`; `mcp` lets clients that know only the official kinds drive it) |
|
|
14
|
+
* | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`; requests go through `ctx.net.fetch`, no deployment config |
|
|
15
15
|
* | `fake-object-store` | `object-store@1` on the `startTestS3()` container (deployment config as `TestS3` gives it; POST-policy presign) |
|
|
16
16
|
* | `fake-tools-ui` | tools `write` and `web-only` (`sources` web and channel_dm; returns its call context), view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
|
|
17
17
|
* | `fake-storage-user` | tools `note` / `read_note` through `ctx.storage` (`permissions.storage`) |
|
package/dist/kernel-helpers.d.ts
CHANGED
|
@@ -12,7 +12,8 @@ export declare const sleep: (ms: number) => Promise<void>;
|
|
|
12
12
|
export declare function waitFor<T>(fn: () => Promise<T | null | undefined | false>, timeoutMs?: number, label?: string, stepMs?: number): Promise<T>;
|
|
13
13
|
/**
|
|
14
14
|
* A kernel config for tests: the given PG / Redis, a fixed master key, an ephemeral HTTP port,
|
|
15
|
-
* auto-approved extension permissions,
|
|
15
|
+
* auto-approved extension permissions, `net.allowInsecureLoopback` (fake servers on loopback),
|
|
16
|
+
* short run-lock timings and the official marketplace off
|
|
16
17
|
* (it is on by default and its address is on the internet). `overrides` are top-level config keys
|
|
17
18
|
* and win; `runtime` is merged into the defaults, and `marketplaces` too, so other marketplace
|
|
18
19
|
* settings keep the official one off unless `marketplaces.official` turns it on.
|
package/dist/kernel-helpers.js
CHANGED
|
@@ -26,7 +26,8 @@ export async function waitFor(fn, timeoutMs = 10_000, label = "condition", stepM
|
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
28
|
* A kernel config for tests: the given PG / Redis, a fixed master key, an ephemeral HTTP port,
|
|
29
|
-
* auto-approved extension permissions,
|
|
29
|
+
* auto-approved extension permissions, `net.allowInsecureLoopback` (fake servers on loopback),
|
|
30
|
+
* short run-lock timings and the official marketplace off
|
|
30
31
|
* (it is on by default and its address is on the internet). `overrides` are top-level config keys
|
|
31
32
|
* and win; `runtime` is merged into the defaults, and `marketplaces` too, so other marketplace
|
|
32
33
|
* settings keep the official one off unless `marketplaces.official` turns it on.
|
|
@@ -44,6 +45,8 @@ export function testKernelConfig(urls, overrides) {
|
|
|
44
45
|
...marketplaces,
|
|
45
46
|
official: { enabled: false, ...marketplaces?.official },
|
|
46
47
|
},
|
|
48
|
+
// Fake servers run on loopback: ctx.net may reach them (a test overrides `net` to assert refusals)
|
|
49
|
+
net: { allowInsecureLoopback: true },
|
|
47
50
|
...rest,
|
|
48
51
|
});
|
|
49
52
|
}
|
package/dist/replica-runner.js
CHANGED
|
@@ -29,6 +29,8 @@ async function startKernel(c) {
|
|
|
29
29
|
extensionPermissions: { autoApprove: true },
|
|
30
30
|
// The official marketplace is on by default and on the internet: tests turn it on explicitly.
|
|
31
31
|
marketplaces: { official: { enabled: false } },
|
|
32
|
+
// Fake servers run on loopback: ctx.net may reach them
|
|
33
|
+
net: { allowInsecureLoopback: true },
|
|
32
34
|
log: { level: "error" },
|
|
33
35
|
};
|
|
34
36
|
const config = KernelConfigSchema.parse(deepMerge(base, c.overrides));
|
|
@@ -2,8 +2,18 @@ import { type PermissionProfile, type SandboxFileScope, type SandboxNetworkScope
|
|
|
2
2
|
import type { NativeFixtureEntry } from "./sandbox-native-conformance.js";
|
|
3
3
|
/** A controlled endpoint whose receipts the fixture counts out of band (never via the device). */
|
|
4
4
|
export interface SandboxPermissionEndpoint {
|
|
5
|
-
/**
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The host name a scope allowlists for this endpoint (it must pass `validateAllowHost`, which
|
|
7
|
+
* refuses IP literals). The provider or fixture maps it to the endpoint; an ungranted endpoint's
|
|
8
|
+
* name is never allowlisted, so a proxy asked for it by name must refuse.
|
|
9
|
+
*/
|
|
10
|
+
readonly name: string;
|
|
11
|
+
/**
|
|
12
|
+
* The endpoint's numeric address (an IP literal) for raw socket clients: the pointer race and
|
|
13
|
+
* the ungranted, network-none and Full controls connect here. The granted endpoint's address and
|
|
14
|
+
* at least one ungranted address are IPv4 (the race program builds IPv4 socket addresses).
|
|
15
|
+
*/
|
|
16
|
+
readonly address: string;
|
|
7
17
|
readonly port: number;
|
|
8
18
|
/** Accepted connections so far, observed by the endpoint itself. */
|
|
9
19
|
receipts(): Promise<number>;
|
|
@@ -27,10 +37,21 @@ export interface SandboxPermissionFixture {
|
|
|
27
37
|
readonly sibling: string;
|
|
28
38
|
/** Existing files the device user may write ordinarily but no restricted grant covers. */
|
|
29
39
|
readonly protectedPaths: readonly string[];
|
|
30
|
-
/** `granted` is reachable by allowlisting its
|
|
40
|
+
/** `granted` is reachable by allowlisting its name; `ungranted` never is. */
|
|
31
41
|
readonly endpoints: {
|
|
32
42
|
readonly granted: SandboxPermissionEndpoint;
|
|
33
43
|
readonly ungranted: readonly SandboxPermissionEndpoint[];
|
|
44
|
+
/**
|
|
45
|
+
* How a restricted allowlist operation reaches `granted`:
|
|
46
|
+
* - `direct`: by connecting to its address (the provider admits the address it maps the
|
|
47
|
+
* allowlisted name to); Python, curl and Node connect straight to it.
|
|
48
|
+
* - `proxy`: only through the HTTP proxy the provider names in the operation's environment
|
|
49
|
+
* (`http_proxy`, the variable curl and Python read for http URLs), which resolves `name`.
|
|
50
|
+
* Positives use curl and Python through that proxy; raw connects to the address are not
|
|
51
|
+
* expected to work, and the pointer race targets the proxy instead.
|
|
52
|
+
* Either way the device needs no name resolution of its own for endpoint names.
|
|
53
|
+
*/
|
|
54
|
+
readonly access: "direct" | "proxy";
|
|
34
55
|
};
|
|
35
56
|
/** The provider's own runtime report; the harness never infers support from a fixture. */
|
|
36
57
|
support(): Promise<SandboxPermissionSupport>;
|
|
@@ -54,7 +75,20 @@ export interface SandboxPermissionFixture {
|
|
|
54
75
|
* overlap orders, component/root swaps and mutable syscall pointers during access, exact
|
|
55
76
|
* cancellation and fresh narrowed scopes. Restricted network none/allowlist may bind and listen on
|
|
56
77
|
* loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
|
|
57
|
-
* every network kind, environment included
|
|
78
|
+
* every network kind, environment included. A provider that reports restricted unsupported must
|
|
58
79
|
* refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
|
|
80
|
+
*
|
|
81
|
+
* Not covered, by design (known limitations, not passes): metadata reads outside the roots (stat,
|
|
82
|
+
* readlink, xattrs, statfs), and the world-readable `/proc/<pid>` entries of other processes of the
|
|
83
|
+
* same uid, such as `cmdline`, `stat` and `status`. A restricted operation can therefore read the
|
|
84
|
+
* command line of a concurrent Full command on the device: Landlock cannot scope `/proc` to the
|
|
85
|
+
* operation's own process tree (see the Linux launcher's known limitations). Providers keep secrets
|
|
86
|
+
* out of command lines; ptrace-guarded entries (`environ`, `mem`, `maps`, `fd`) stay closed.
|
|
59
87
|
*/
|
|
60
88
|
export declare function runSandboxPermissionConformance(fixture: SandboxPermissionFixture): Promise<void>;
|
|
89
|
+
/**
|
|
90
|
+
* Polls a trusted read until `path` exists, racing the operation that should create it: if that
|
|
91
|
+
* operation settles first (refused, failed or exited without the file), this throws at once with
|
|
92
|
+
* the operation's error or exit, after one last read. The operation's rejection is always handled.
|
|
93
|
+
*/
|
|
94
|
+
export declare function waitForFile(read: (path: string) => Promise<Uint8Array | null>, path: string, pending: Promise<unknown>): Promise<void>;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { isIP, isIPv4 } from "node:net";
|
|
3
4
|
import { posix } from "node:path";
|
|
4
|
-
import { isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
|
|
5
|
+
import { isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
5
6
|
const text = (data) => (data === null ? null : Buffer.from(data).toString());
|
|
6
7
|
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
7
8
|
/** A Python program in which one thread rewrites a syscall's pointer argument mid-call. */
|
|
@@ -18,7 +19,13 @@ ok = 0
|
|
|
18
19
|
if mode == "connect":
|
|
19
20
|
def sockaddr(host, port):
|
|
20
21
|
return struct.pack("HH4s8x", socket.AF_INET, socket.htons(port), socket.inet_aton(host))
|
|
21
|
-
|
|
22
|
+
if sys.argv[3] == "proxy":
|
|
23
|
+
# The allowed target is the operation's own HTTP proxy, taken from its environment.
|
|
24
|
+
import os, urllib.parse
|
|
25
|
+
proxy = urllib.parse.urlsplit(os.environ.get("http_proxy") or os.environ["HTTP_PROXY"])
|
|
26
|
+
good = sockaddr(socket.gethostbyname(proxy.hostname), proxy.port)
|
|
27
|
+
else:
|
|
28
|
+
good = sockaddr(sys.argv[3], int(sys.argv[4]))
|
|
22
29
|
bad = sockaddr(sys.argv[5], int(sys.argv[6]))
|
|
23
30
|
buffer = ctypes.create_string_buffer(good, len(good))
|
|
24
31
|
thread = threading.Thread(target=flipper, args=(buffer, good, bad))
|
|
@@ -163,8 +170,15 @@ print("swaps=%d" % swaps)
|
|
|
163
170
|
* overlap orders, component/root swaps and mutable syscall pointers during access, exact
|
|
164
171
|
* cancellation and fresh narrowed scopes. Restricted network none/allowlist may bind and listen on
|
|
165
172
|
* loopback (127.0.0.1, ::1) only. Pathname UNIX services outside the roots stay unreachable under
|
|
166
|
-
* every network kind, environment included
|
|
173
|
+
* every network kind, environment included. A provider that reports restricted unsupported must
|
|
167
174
|
* refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
|
|
175
|
+
*
|
|
176
|
+
* Not covered, by design (known limitations, not passes): metadata reads outside the roots (stat,
|
|
177
|
+
* readlink, xattrs, statfs), and the world-readable `/proc/<pid>` entries of other processes of the
|
|
178
|
+
* same uid, such as `cmdline`, `stat` and `status`. A restricted operation can therefore read the
|
|
179
|
+
* command line of a concurrent Full command on the device: Landlock cannot scope `/proc` to the
|
|
180
|
+
* operation's own process tree (see the Linux launcher's known limitations). Providers keep secrets
|
|
181
|
+
* out of command lines; ptrace-guarded entries (`environ`, `mem`, `maps`, `fd`) stay closed.
|
|
168
182
|
*/
|
|
169
183
|
export async function runSandboxPermissionConformance(fixture) {
|
|
170
184
|
const { root, sibling } = fixture;
|
|
@@ -185,8 +199,9 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
185
199
|
filesystem: { kind: "device" },
|
|
186
200
|
network: { kind: "environment" },
|
|
187
201
|
};
|
|
188
|
-
const { granted, ungranted } = fixture.endpoints;
|
|
189
|
-
const
|
|
202
|
+
const { granted, ungranted, access } = fixture.endpoints;
|
|
203
|
+
const proxied = access === "proxy";
|
|
204
|
+
const allowlisted = { kind: "allowlist", hosts: [granted.name] };
|
|
190
205
|
const exec = async (grant, command, signal = new AbortController().signal, timeoutMs = 120_000) => (await fixture.operation(grant)).exec({
|
|
191
206
|
command,
|
|
192
207
|
cwd: root,
|
|
@@ -203,14 +218,23 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
203
218
|
const denied = async (promise, what) => {
|
|
204
219
|
await assert.rejects(promise, (error) => isSandboxScopeDeniedError(error), what);
|
|
205
220
|
};
|
|
206
|
-
const waitFor =
|
|
207
|
-
while ((await fixture.inspect.readFile(path)) === null) {
|
|
208
|
-
await new Promise((resolve) => setImmediate(resolve));
|
|
209
|
-
}
|
|
210
|
-
};
|
|
221
|
+
const waitFor = (path, pending) => waitForFile(fixture.inspect.readFile, path, pending);
|
|
211
222
|
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.
|
|
223
|
+
const connect = (endpoint) => `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(endpoint.address)}, ${endpoint.port}), 10).close()`)}`;
|
|
224
|
+
/** An HTTP request by name; curl and Python use the environment's proxy when there is one. */
|
|
225
|
+
const byName = (endpoint) => `curl -fsS -m 10 -o /dev/null http://${endpoint.name}:${endpoint.port}/`;
|
|
226
|
+
const urlopen = (endpoint) => `python3 -c ${quote(`import urllib.request; urllib.request.urlopen("http://${endpoint.name}:${endpoint.port}/", timeout=10).read()`)}`;
|
|
213
227
|
try {
|
|
228
|
+
for (const [label, endpoint] of [
|
|
229
|
+
["granted", granted],
|
|
230
|
+
...ungranted.map((endpoint) => ["ungranted", endpoint]),
|
|
231
|
+
]) {
|
|
232
|
+
const problems = validateAllowHost(endpoint.name);
|
|
233
|
+
assert(problems.length === 0, `${label} endpoint name ${endpoint.name} is not a valid allowlist host: ${problems.join("; ")}`);
|
|
234
|
+
assert(isIP(endpoint.address) !== 0, `${label} endpoint address ${endpoint.address} is not a numeric address`);
|
|
235
|
+
}
|
|
236
|
+
assert(isIPv4(granted.address), "the granted endpoint address must be IPv4 (race program)");
|
|
237
|
+
assert(ungranted.every((endpoint) => endpoint.name !== granted.name), "ungranted endpoints need names other than the granted one");
|
|
214
238
|
const support = await fixture.support();
|
|
215
239
|
if (support.restricted === null) {
|
|
216
240
|
// Fail closed: no restricted operation may run, and nothing falls back to Full access.
|
|
@@ -284,22 +308,36 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
284
308
|
await siblingIntact("native denials must leave the sibling unchanged");
|
|
285
309
|
// Network: only the granted endpoint, and only while allowlisted.
|
|
286
310
|
const base = await receipts();
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
311
|
+
const positives = proxied
|
|
312
|
+
? [byName(granted), urlopen(granted)]
|
|
313
|
+
: [
|
|
314
|
+
connect(granted),
|
|
315
|
+
`curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
|
|
316
|
+
`node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
|
|
317
|
+
];
|
|
318
|
+
for (const command of positives) {
|
|
292
319
|
const result = await exec(restricted(allowlisted), command);
|
|
293
320
|
assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
|
|
294
321
|
}
|
|
295
322
|
for (const endpoint of ungranted) {
|
|
296
|
-
|
|
297
|
-
|
|
323
|
+
// Raw connects to an ungranted address fail; through a proxy, so does a request by name.
|
|
324
|
+
for (const command of proxied ? [connect(endpoint), byName(endpoint)] : [connect(endpoint)]) {
|
|
325
|
+
const result = await exec(restricted(allowlisted), command);
|
|
326
|
+
assert.notEqual(result.exitCode, 0, `ungranted ${endpoint.name}: ${command}`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (proxied) {
|
|
330
|
+
// allowlisted traffic goes through the proxy: a raw connect to the granted address bypasses
|
|
331
|
+
// it and must be refused as well
|
|
332
|
+
const raw = await exec(restricted(allowlisted), connect(granted));
|
|
333
|
+
assert.notEqual(raw.exitCode, 0, `a proxied provider must refuse a raw connect: ${granted.name}`);
|
|
334
|
+
}
|
|
335
|
+
for (const command of [connect(granted), byName(granted)]) {
|
|
336
|
+
const none = await exec(restricted(), command);
|
|
337
|
+
assert.notEqual(none.exitCode, 0, `network none must refuse even the granted endpoint: ${command}`);
|
|
298
338
|
}
|
|
299
|
-
const none = await exec(restricted(), connect(granted));
|
|
300
|
-
assert.notEqual(none.exitCode, 0, "network none must refuse even the granted endpoint");
|
|
301
339
|
const after = await receipts();
|
|
302
|
-
assert.equal(after[0], (base[0] ?? 0) +
|
|
340
|
+
assert.equal(after[0], (base[0] ?? 0) + positives.length, "granted endpoint receipts");
|
|
303
341
|
assert.deepEqual(after.slice(1), base.slice(1), "ungranted endpoints must see no connection");
|
|
304
342
|
// Restricted network none/allowlist may listen on loopback only.
|
|
305
343
|
for (const network of [{ kind: "none" }, allowlisted]) {
|
|
@@ -311,7 +349,7 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
311
349
|
if (support.fullAccess) {
|
|
312
350
|
const server = new AbortController();
|
|
313
351
|
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"));
|
|
352
|
+
await waitFor(at(sibling, "srv.count"), outside);
|
|
315
353
|
await fixture.seed([
|
|
316
354
|
{ path: at(root, "srv-link.sock"), kind: "symlink", target: at(sibling, "srv.sock") },
|
|
317
355
|
]);
|
|
@@ -329,9 +367,10 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
329
367
|
// The same client under Full access reaches the service seven times: the probe is real.
|
|
330
368
|
const control = await exec(full, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
|
|
331
369
|
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
|
-
|
|
333
|
-
|
|
334
|
-
|
|
370
|
+
await waitForFile(async (path) => {
|
|
371
|
+
const data = await fixture.inspect.readFile(path);
|
|
372
|
+
return text(data) === "7" ? data : null;
|
|
373
|
+
}, at(sibling, "srv.count"), outside);
|
|
335
374
|
server.abort();
|
|
336
375
|
await outside;
|
|
337
376
|
}
|
|
@@ -347,13 +386,13 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
347
386
|
if (support.fullAccess) {
|
|
348
387
|
const first = exec(restricted(), `printf r > ready-a; until [ -e barrier-a ]; do sleep 0.01; done; ` +
|
|
349
388
|
`printf pwn > ${quote(at(sibling, "overlap-a"))}; cat ${quote(at(sibling, "secret"))}; true`);
|
|
350
|
-
await waitFor(at(root, "ready-a"));
|
|
389
|
+
await waitFor(at(root, "ready-a"), first);
|
|
351
390
|
await exec(full, `printf full > ${quote(at(sibling, "full-a"))} && touch barrier-a`);
|
|
352
391
|
assert(!(await first).stdout.includes(secret), "restricted after a live Full operation");
|
|
353
392
|
assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-a")), null);
|
|
354
393
|
const fullFirst = exec(full, `printf r > ready-b; until [ -e barrier-b ]; do sleep 0.01; done; ` +
|
|
355
394
|
`printf full > ${quote(at(sibling, "full-b"))}`);
|
|
356
|
-
await waitFor(at(root, "ready-b"));
|
|
395
|
+
await waitFor(at(root, "ready-b"), fullFirst);
|
|
357
396
|
const second = await exec(restricted(), `printf pwn > ${quote(at(sibling, "overlap-b"))}; cat ${quote(at(sibling, "secret"))}; touch barrier-b`);
|
|
358
397
|
assert(!second.stdout.includes(secret), "restricted while a Full operation is live");
|
|
359
398
|
assert.equal((await fullFirst).exitCode, 0);
|
|
@@ -364,7 +403,7 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
364
403
|
if (support.fullAccess) {
|
|
365
404
|
const race = at(root, "race");
|
|
366
405
|
const swapper = exec(full, `python3 -c ${quote(SWAP_PROGRAM)} ${quote(race)} ${quote(sibling)} ${quote(at(root, "race-stop"))}`);
|
|
367
|
-
await waitFor(at(race, "swapping"));
|
|
406
|
+
await waitFor(at(race, "swapping"), swapper);
|
|
368
407
|
for (let index = 0; index < 30; index++) {
|
|
369
408
|
const op = await native(restricted());
|
|
370
409
|
try {
|
|
@@ -391,7 +430,7 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
391
430
|
const moved = `${root}.moved-${randomUUID()}`;
|
|
392
431
|
const live = exec(restricted(), `printf r > ready-root; until [ -e ${quote(at(moved, "barrier-root"))} ]; do sleep 0.01; done; ` +
|
|
393
432
|
`printf pwn > ${quote(at(root, "after-swap"))}; cat ${quote(at(root, "secret"))}; printf ok > in-place; true`);
|
|
394
|
-
await waitFor(at(root, "ready-root"));
|
|
433
|
+
await waitFor(at(root, "ready-root"), live);
|
|
395
434
|
await exec(full, `mv ${quote(root)} ${quote(moved)} && ln -s ${quote(sibling)} ${quote(root)} && touch ${quote(at(moved, "barrier-root"))}`);
|
|
396
435
|
const swapped = await live;
|
|
397
436
|
assert(!swapped.stdout.includes(secret), "a live operation must not follow a root swap");
|
|
@@ -414,14 +453,20 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
414
453
|
await siblingIntact("root swaps must not reach the sibling");
|
|
415
454
|
}
|
|
416
455
|
// A mutable syscall pointer: another thread rewrites the address/path during the check.
|
|
417
|
-
|
|
456
|
+
// Direct access flips between the granted and an ungranted address; proxied access between the
|
|
457
|
+
// operation's proxy (from its environment) and an ungranted address.
|
|
458
|
+
const target = ungranted.find((endpoint) => isIPv4(endpoint.address));
|
|
418
459
|
if (target) {
|
|
419
460
|
const before = await receipts();
|
|
420
|
-
const
|
|
461
|
+
const good = proxied ? "proxy -" : `${granted.address} ${granted.port}`;
|
|
462
|
+
const flip = await exec(restricted(allowlisted), `python3 -c ${quote(FLIP_PROGRAM)} connect 1500 ${good} ${target.address} ${target.port}`);
|
|
421
463
|
assert.equal(flip.exitCode, 0, `pointer race program must run: ${flip.stderr}`);
|
|
422
464
|
const flipped = await receipts();
|
|
423
465
|
assert.deepEqual(flipped.slice(1), before.slice(1), "a flipped sockaddr must not escape");
|
|
424
|
-
assert((
|
|
466
|
+
assert.notEqual(flip.stdout.trim(), "ok=0", "the race must also reach the allowed target");
|
|
467
|
+
if (!proxied) {
|
|
468
|
+
assert((flipped[0] ?? 0) > (before[0] ?? 0), "the race must reach the granted endpoint");
|
|
469
|
+
}
|
|
425
470
|
const chmods = await exec(restricted(), `python3 -c ${quote(FLIP_PROGRAM)} chmod 3000 ${quote(at(root, "inroot.txt"))} ${quote(at(sibling, "secret"))}`);
|
|
426
471
|
assert.equal(chmods.exitCode, 0, `chmod race program must run: ${chmods.stderr}`);
|
|
427
472
|
assert.notEqual(chmods.stdout.trim(), "ok=0", "in-root chmods must succeed");
|
|
@@ -429,13 +474,13 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
429
474
|
}
|
|
430
475
|
// Exact cancellation: detached descendants end; a sibling operation keeps running.
|
|
431
476
|
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"));
|
|
477
|
+
await waitFor(at(root, "ready-keep"), keepAlive);
|
|
433
478
|
const abort = new AbortController();
|
|
434
479
|
const cancelled = exec(restricted(), `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
|
|
435
480
|
`setsid sleep 1002 > /dev/null 2>&1 & ` +
|
|
436
481
|
`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
482
|
`until [ -e p3 ]; do sleep 0.01; done; printf r > ready-cancel; sleep 1004`, abort.signal);
|
|
438
|
-
await waitFor(at(root, "ready-cancel"));
|
|
483
|
+
await waitFor(at(root, "ready-cancel"), cancelled);
|
|
439
484
|
const pids = await Promise.all(["p1", "p2", "p3"].map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
|
|
440
485
|
assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
|
|
441
486
|
abort.abort();
|
|
@@ -456,7 +501,7 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
456
501
|
const narrowed = restricted({ kind: "none" }, [at(root, "narrow/keep")]);
|
|
457
502
|
const broad = exec(restricted(), `printf r > ready-broad; until [ -e narrow/keep/release-broad ]; do sleep 0.01; done; ` +
|
|
458
503
|
`printf broad > broad.txt`);
|
|
459
|
-
await waitFor(at(root, "ready-broad"));
|
|
504
|
+
await waitFor(at(root, "ready-broad"), broad);
|
|
460
505
|
const overlapping = await (await fixture.operation(narrowed)).exec({
|
|
461
506
|
command: `printf pwn > ${quote(at(root, "overlapping.txt"))}; touch release-broad; true`,
|
|
462
507
|
cwd: at(root, "narrow/keep"),
|
|
@@ -484,3 +529,37 @@ export async function runSandboxPermissionConformance(fixture) {
|
|
|
484
529
|
await fixture.dispose();
|
|
485
530
|
}
|
|
486
531
|
}
|
|
532
|
+
/**
|
|
533
|
+
* Polls a trusted read until `path` exists, racing the operation that should create it: if that
|
|
534
|
+
* operation settles first (refused, failed or exited without the file), this throws at once with
|
|
535
|
+
* the operation's error or exit, after one last read. The operation's rejection is always handled.
|
|
536
|
+
*/
|
|
537
|
+
export async function waitForFile(read, path, pending) {
|
|
538
|
+
let ended;
|
|
539
|
+
pending.then((value) => {
|
|
540
|
+
ended = { value };
|
|
541
|
+
}, (error) => {
|
|
542
|
+
ended = { error };
|
|
543
|
+
});
|
|
544
|
+
for (;;) {
|
|
545
|
+
if ((await read(path)) !== null)
|
|
546
|
+
return;
|
|
547
|
+
if (ended) {
|
|
548
|
+
// The operation may have written the file just before it ended.
|
|
549
|
+
if ((await read(path)) !== null)
|
|
550
|
+
return;
|
|
551
|
+
if ("error" in ended) {
|
|
552
|
+
const reason = ended.error instanceof Error ? ended.error.message : String(ended.error);
|
|
553
|
+
throw new Error(`operation ended before ${path} existed: ${reason}`, {
|
|
554
|
+
cause: ended.error,
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
const result = ended.value;
|
|
558
|
+
const detail = result && "exitCode" in result
|
|
559
|
+
? `exit ${result.exitCode}${result.timedOut ? " (timed out)" : ""}: ${result.stderr ?? ""}`
|
|
560
|
+
: "it returned";
|
|
561
|
+
throw new Error(`operation ended before ${path} existed: ${detail}`);
|
|
562
|
+
}
|
|
563
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
564
|
+
}
|
|
565
|
+
}
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
type ConnectorSession,
|
|
8
8
|
defineExtension,
|
|
9
9
|
type ElicitationRequest,
|
|
10
|
+
type ExtensionNet,
|
|
10
11
|
type Logger,
|
|
11
12
|
type PromptInfo,
|
|
12
13
|
type ToolContent,
|
|
@@ -33,8 +34,10 @@ import { z } from "zod";
|
|
|
33
34
|
* `kind` names another): a deliberately small MCP client
|
|
34
35
|
* (Streamable HTTP) meant for `startFakeMcpServer` from `@capybara-hq/testing`. It covers the
|
|
35
36
|
* kernel side of the connector contract, not MCP edge cases:
|
|
36
|
-
* - `endpointSchema`: `{ url, headers? }`, https or (
|
|
37
|
-
*
|
|
37
|
+
* - `endpointSchema`: `{ url, headers? }`, https or loopback http (the kernel's `ctx.net` decides
|
|
38
|
+
* what is reachable: test kernels set `net.allowInsecureLoopback`); credential headers are
|
|
39
|
+
* rejected;
|
|
40
|
+
* - every request goes through `ctx.net.fetch` with the session's `orgId`;
|
|
38
41
|
* - `auth()` before every request, one `onUnauthorized()` + retry on 401, redirects not followed;
|
|
39
42
|
* a 5xx answer's body is logged as the warning `fake-connector request failed` (the kernel
|
|
40
43
|
* redacts credentials in extension logs);
|
|
@@ -65,8 +68,6 @@ const CLIENT_INFO = { name: "capybara-fake-connector", version: "0.1.0" };
|
|
|
65
68
|
const REQUEST_TIMEOUT_MS = 3_600_000;
|
|
66
69
|
|
|
67
70
|
const DeploymentConfig = z.object({
|
|
68
|
-
/** Accept http://127.0.0.1 / localhost / [::1] endpoints (on by default: this is a test fake). */
|
|
69
|
-
allowInsecureLoopback: z.boolean().default(true),
|
|
70
71
|
/** The auth hint `inspect` reports behind a 401. */
|
|
71
72
|
inspectAuth: z.enum(["bearer", "api_key"]).default("bearer"),
|
|
72
73
|
/**
|
|
@@ -83,13 +84,14 @@ const DeploymentConfig = z.object({
|
|
|
83
84
|
/** The `_meta` key of a remote tool that names the remote tool serving it (its route). */
|
|
84
85
|
export const FAKE_ROUTE_META = "fake/route";
|
|
85
86
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
87
|
+
/**
|
|
88
|
+
* http or https; whether the target is reachable is `ctx.net`'s call at request time (http only for
|
|
89
|
+
* an org-allowed `http://host:port` origin, or loopback under `net.allowInsecureLoopback`).
|
|
90
|
+
*/
|
|
91
|
+
const urlAllowed = (raw: string): boolean => {
|
|
90
92
|
try {
|
|
91
93
|
const u = new URL(raw);
|
|
92
|
-
return u.protocol === "https:" ||
|
|
94
|
+
return u.protocol === "https:" || u.protocol === "http:";
|
|
93
95
|
} catch {
|
|
94
96
|
return true; // z.url() reports the format error
|
|
95
97
|
}
|
|
@@ -99,11 +101,11 @@ const isCredentialHeader = (name: string): boolean =>
|
|
|
99
101
|
["authorization", "proxy-authorization", "cookie"].includes(name.toLowerCase());
|
|
100
102
|
|
|
101
103
|
/** The endpoint: the server URL and optional non-secret fixed headers. */
|
|
102
|
-
export function fakeEndpointSchema(
|
|
104
|
+
export function fakeEndpointSchema() {
|
|
103
105
|
return z
|
|
104
106
|
.object({
|
|
105
|
-
url: z.url().refine(
|
|
106
|
-
message: "URL must use
|
|
107
|
+
url: z.url().refine(urlAllowed, {
|
|
108
|
+
message: "URL must use http or https",
|
|
107
109
|
}),
|
|
108
110
|
/** Free-form text the connector ignores (large-endpoint tests). */
|
|
109
111
|
notesText: z.string().optional(),
|
|
@@ -174,6 +176,8 @@ async function guarded<T>(work: () => Promise<T>): Promise<T> {
|
|
|
174
176
|
|
|
175
177
|
/** A fetch that injects `auth()` before every request and retries once after `onUnauthorized()`. */
|
|
176
178
|
function authedFetch(
|
|
179
|
+
net: ExtensionNet,
|
|
180
|
+
orgId: string,
|
|
177
181
|
endpoint: Endpoint,
|
|
178
182
|
auth: ConnectorOpenArgs["auth"] | undefined,
|
|
179
183
|
onUnauthorized: ConnectorOpenArgs["onUnauthorized"] | undefined,
|
|
@@ -190,7 +194,11 @@ function authedFetch(
|
|
|
190
194
|
for (const [k, v] of Object.entries(endpoint.headers)) if (!headers.has(k)) headers.set(k, v);
|
|
191
195
|
for (const [k, v] of Object.entries(inj.headers)) headers.set(k, v);
|
|
192
196
|
const s = init?.signal ? AbortSignal.any([init.signal, signal]) : signal;
|
|
193
|
-
return fetch(
|
|
197
|
+
return net.fetch(
|
|
198
|
+
url.toString(),
|
|
199
|
+
{ ...init, headers, signal: s, redirect: "manual" },
|
|
200
|
+
{ orgId },
|
|
201
|
+
);
|
|
194
202
|
};
|
|
195
203
|
const noRedirect = async (r: Response) => {
|
|
196
204
|
if (r.status >= 300 && r.status < 400) {
|
|
@@ -275,11 +283,20 @@ async function connect(
|
|
|
275
283
|
}
|
|
276
284
|
|
|
277
285
|
async function openSession(
|
|
286
|
+
net: ExtensionNet,
|
|
278
287
|
endpoint: Endpoint,
|
|
279
288
|
args: ConnectorOpenArgs,
|
|
280
289
|
log?: Logger,
|
|
281
290
|
): Promise<ConnectorSession> {
|
|
282
|
-
const fetchImpl = authedFetch(
|
|
291
|
+
const fetchImpl = authedFetch(
|
|
292
|
+
net,
|
|
293
|
+
args.orgId,
|
|
294
|
+
endpoint,
|
|
295
|
+
args.auth,
|
|
296
|
+
args.onUnauthorized,
|
|
297
|
+
args.signal,
|
|
298
|
+
log,
|
|
299
|
+
);
|
|
283
300
|
const { client, transport } = await connect(endpoint, fetchImpl, args);
|
|
284
301
|
const opts = (signal: AbortSignal = args.signal) => ({ signal, timeout: REQUEST_TIMEOUT_MS });
|
|
285
302
|
const session: ConnectorSession = {
|
|
@@ -412,12 +429,14 @@ const authHint = (kind: InspectAuth): AuthHint =>
|
|
|
412
429
|
|
|
413
430
|
/** Install preview without credentials: 401 -> the configured auth hint; otherwise the tools as operations. */
|
|
414
431
|
async function inspect(
|
|
432
|
+
net: ExtensionNet,
|
|
433
|
+
orgId: string,
|
|
415
434
|
endpoint: Endpoint,
|
|
416
435
|
signal: AbortSignal,
|
|
417
436
|
hint: InspectAuth,
|
|
418
437
|
): Promise<ConnectorInspection> {
|
|
419
438
|
let unauthorized = false;
|
|
420
|
-
const probe = authedFetch(endpoint, undefined, undefined, signal);
|
|
439
|
+
const probe = authedFetch(net, orgId, endpoint, undefined, undefined, signal);
|
|
421
440
|
const fetchImpl = async (input: string | URL, init?: RequestInit) => {
|
|
422
441
|
const r = await probe(input, init);
|
|
423
442
|
if (r.status === 401) unauthorized = true;
|
|
@@ -447,17 +466,18 @@ async function inspect(
|
|
|
447
466
|
|
|
448
467
|
/** Creates the fake connector (exported for unit tests that call it without a kernel). */
|
|
449
468
|
export function createFakeConnector(
|
|
450
|
-
|
|
469
|
+
net: ExtensionNet,
|
|
451
470
|
inspectAuth: InspectAuth = "bearer",
|
|
452
471
|
kind = "fake",
|
|
453
472
|
log?: Logger,
|
|
454
473
|
): Connector {
|
|
455
|
-
const schema = fakeEndpointSchema(
|
|
474
|
+
const schema = fakeEndpointSchema();
|
|
456
475
|
return {
|
|
457
476
|
kind,
|
|
458
477
|
endpointSchema: schema,
|
|
459
|
-
open: (args) => openSession(schema.parse(args.endpoint), args, log),
|
|
460
|
-
inspect: ({ endpoint, signal }) =>
|
|
478
|
+
open: (args) => openSession(net, schema.parse(args.endpoint), args, log),
|
|
479
|
+
inspect: ({ endpoint, signal, orgId }) =>
|
|
480
|
+
inspect(net, orgId, schema.parse(endpoint), signal, inspectAuth),
|
|
461
481
|
};
|
|
462
482
|
}
|
|
463
483
|
|
|
@@ -468,10 +488,10 @@ export default defineExtension({
|
|
|
468
488
|
provides: [CONNECTOR_EXTENSION_POINT],
|
|
469
489
|
config: { deployment: DeploymentConfig },
|
|
470
490
|
setup(ctx) {
|
|
471
|
-
const {
|
|
491
|
+
const { inspectAuth, kind } = DeploymentConfig.parse(ctx.config ?? {});
|
|
472
492
|
ctx.provide(
|
|
473
493
|
CONNECTOR_EXTENSION_POINT,
|
|
474
|
-
createFakeConnector(
|
|
494
|
+
createFakeConnector(ctx.net, inspectAuth, kind, ctx.log),
|
|
475
495
|
);
|
|
476
496
|
},
|
|
477
497
|
});
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
type ConnectorOpenArgs,
|
|
7
7
|
type ConnectorSession,
|
|
8
8
|
defineExtension,
|
|
9
|
+
type ExtensionNet,
|
|
9
10
|
ToolError,
|
|
10
11
|
type ToolResult,
|
|
11
12
|
type ToolSpec,
|
|
@@ -28,7 +29,9 @@ import { z } from "zod";
|
|
|
28
29
|
* ```
|
|
29
30
|
*
|
|
30
31
|
* - `endpointSchema`: `{ specUrl, baseUrl?, operations? }` (the wizard's OpenAPI endpoint without
|
|
31
|
-
* `specText`),
|
|
32
|
+
* `specText`), http or https (the kernel's `ctx.net` decides at request time what is
|
|
33
|
+
* reachable: http only for an org-allowed `http://host:port` origin, or loopback under
|
|
34
|
+
* `net.allowInsecureLoopback`, which test kernels set);
|
|
32
35
|
* - `inspect`: the document's security schemes as auth hints (`{ scheme, ...value }`) and its
|
|
33
36
|
* operations (`id` = name);
|
|
34
37
|
* - a session lists one tool per operation (all, or the endpoint's `operations`), named by the
|
|
@@ -39,27 +42,20 @@ import { z } from "zod";
|
|
|
39
42
|
* kind `unavailable`.
|
|
40
43
|
*/
|
|
41
44
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
allowInsecureLoopback: z.boolean().default(true),
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
const isLoopbackHttp = (u: URL): boolean =>
|
|
48
|
-
u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname);
|
|
49
|
-
|
|
50
|
-
const urlOk = (raw: string, loopback: boolean): boolean => {
|
|
45
|
+
/** http or https; whether the target is reachable is `ctx.net`'s call at request time. */
|
|
46
|
+
const urlOk = (raw: string): boolean => {
|
|
51
47
|
try {
|
|
52
48
|
const u = new URL(raw);
|
|
53
|
-
return u.protocol === "https:" ||
|
|
49
|
+
return u.protocol === "https:" || u.protocol === "http:";
|
|
54
50
|
} catch {
|
|
55
51
|
return true; // z.url() reports the format error
|
|
56
52
|
}
|
|
57
53
|
};
|
|
58
54
|
|
|
59
55
|
/** The endpoint: the document URL, an optional API base URL and the selected operations. */
|
|
60
|
-
export function fakeOpenApiEndpointSchema(
|
|
61
|
-
const url = z.url().refine(
|
|
62
|
-
message: "URL must use
|
|
56
|
+
export function fakeOpenApiEndpointSchema() {
|
|
57
|
+
const url = z.url().refine(urlOk, {
|
|
58
|
+
message: "URL must use http or https",
|
|
63
59
|
});
|
|
64
60
|
return z
|
|
65
61
|
.object({
|
|
@@ -104,10 +100,15 @@ const UNREACHABLE_TEXT = "Could not reach the connector's server; retry later.";
|
|
|
104
100
|
const AUTH_FAILED_TEXT = "Authentication failed for this connector; ask the user to reconnect it.";
|
|
105
101
|
|
|
106
102
|
/** Reads the operations document (no credentials: like an OpenAPI document, it is public). */
|
|
107
|
-
async function loadDoc(
|
|
103
|
+
async function loadDoc(
|
|
104
|
+
net: ExtensionNet,
|
|
105
|
+
orgId: string,
|
|
106
|
+
endpoint: Endpoint,
|
|
107
|
+
signal: AbortSignal,
|
|
108
|
+
): Promise<Doc> {
|
|
108
109
|
let res: Response;
|
|
109
110
|
try {
|
|
110
|
-
res = await fetch(endpoint.specUrl, { signal, redirect: "manual" });
|
|
111
|
+
res = await net.fetch(endpoint.specUrl, { signal, redirect: "manual" }, { orgId });
|
|
111
112
|
} catch {
|
|
112
113
|
throw new ToolError(UNREACHABLE_TEXT, { kind: "unavailable" });
|
|
113
114
|
}
|
|
@@ -143,8 +144,12 @@ const INPUT_SCHEMA = {
|
|
|
143
144
|
const isObj = (v: unknown): v is Record<string, unknown> =>
|
|
144
145
|
typeof v === "object" && v !== null && !Array.isArray(v);
|
|
145
146
|
|
|
146
|
-
async function openSession(
|
|
147
|
-
|
|
147
|
+
async function openSession(
|
|
148
|
+
net: ExtensionNet,
|
|
149
|
+
endpoint: Endpoint,
|
|
150
|
+
args: ConnectorOpenArgs,
|
|
151
|
+
): Promise<ConnectorSession> {
|
|
152
|
+
const doc = await loadDoc(net, args.orgId, endpoint, args.signal);
|
|
148
153
|
const base = endpoint.baseUrl ?? doc.baseUrl ?? new URL(endpoint.specUrl).origin;
|
|
149
154
|
const ops = selected(doc, endpoint);
|
|
150
155
|
return {
|
|
@@ -178,13 +183,17 @@ async function openSession(endpoint: Endpoint, args: ConnectorOpenArgs): Promise
|
|
|
178
183
|
const headers = new Headers(inj.headers);
|
|
179
184
|
if (body !== undefined) headers.set("content-type", "application/json");
|
|
180
185
|
try {
|
|
181
|
-
return await fetch(
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
186
|
+
return await net.fetch(
|
|
187
|
+
url.toString(),
|
|
188
|
+
{
|
|
189
|
+
method,
|
|
190
|
+
headers,
|
|
191
|
+
...(body !== undefined && { body }),
|
|
192
|
+
signal: AbortSignal.any([signal, args.signal]),
|
|
193
|
+
redirect: "manual",
|
|
194
|
+
},
|
|
195
|
+
{ orgId: args.orgId },
|
|
196
|
+
);
|
|
188
197
|
} catch (e) {
|
|
189
198
|
if (signal.aborted || args.signal.aborted) throw e;
|
|
190
199
|
throw new ToolError(UNREACHABLE_TEXT, { kind: "unavailable" });
|
|
@@ -221,8 +230,13 @@ async function openSession(endpoint: Endpoint, args: ConnectorOpenArgs): Promise
|
|
|
221
230
|
};
|
|
222
231
|
}
|
|
223
232
|
|
|
224
|
-
async function inspect(
|
|
225
|
-
|
|
233
|
+
async function inspect(
|
|
234
|
+
net: ExtensionNet,
|
|
235
|
+
orgId: string,
|
|
236
|
+
endpoint: Endpoint,
|
|
237
|
+
signal: AbortSignal,
|
|
238
|
+
): Promise<ConnectorInspection> {
|
|
239
|
+
const doc = await loadDoc(net, orgId, endpoint, signal);
|
|
226
240
|
return {
|
|
227
241
|
authHints: hintsOf(doc),
|
|
228
242
|
operations: doc.operations.map((o) => ({
|
|
@@ -235,13 +249,13 @@ async function inspect(endpoint: Endpoint, signal: AbortSignal): Promise<Connect
|
|
|
235
249
|
}
|
|
236
250
|
|
|
237
251
|
/** Creates the fake OpenAPI connector (exported for unit tests that call it without a kernel). */
|
|
238
|
-
export function createFakeOpenApiConnector(
|
|
239
|
-
const schema = fakeOpenApiEndpointSchema(
|
|
252
|
+
export function createFakeOpenApiConnector(net: ExtensionNet): Connector {
|
|
253
|
+
const schema = fakeOpenApiEndpointSchema();
|
|
240
254
|
return {
|
|
241
255
|
kind: "openapi",
|
|
242
256
|
endpointSchema: schema,
|
|
243
|
-
open: (args) => openSession(schema.parse(args.endpoint), args),
|
|
244
|
-
inspect: ({ endpoint, signal }) => inspect(schema.parse(endpoint), signal),
|
|
257
|
+
open: (args) => openSession(net, schema.parse(args.endpoint), args),
|
|
258
|
+
inspect: ({ endpoint, signal, orgId }) => inspect(net, orgId, schema.parse(endpoint), signal),
|
|
245
259
|
};
|
|
246
260
|
}
|
|
247
261
|
|
|
@@ -250,9 +264,7 @@ export default defineExtension({
|
|
|
250
264
|
version: "0.1.0",
|
|
251
265
|
sdk: "^0.1.0-rc.0",
|
|
252
266
|
provides: [CONNECTOR_EXTENSION_POINT],
|
|
253
|
-
config: { deployment: DeploymentConfig },
|
|
254
267
|
setup(ctx) {
|
|
255
|
-
|
|
256
|
-
ctx.provide(CONNECTOR_EXTENSION_POINT, createFakeOpenApiConnector(allowInsecureLoopback));
|
|
268
|
+
ctx.provide(CONNECTOR_EXTENSION_POINT, createFakeOpenApiConnector(ctx.net));
|
|
257
269
|
},
|
|
258
270
|
});
|
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.23",
|
|
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.
|
|
50
|
+
"@capybara-hq/kernel": "^0.1.0-rc.38"
|
|
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-client": "^0.1.0-rc.5",
|
|
56
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.29"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
59
|
"vitest": "^5.0.5",
|
|
60
|
-
"@capybara-hq/plugin-sdk": "^0.1.0-rc.
|
|
60
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.29",
|
|
61
61
|
"@capybara-hq/plugin-tools": "^0.1.0-rc.16"
|
|
62
62
|
},
|
|
63
63
|
"peerDependenciesMeta": {
|