Skip to content

Commit 9b91c55

Browse files
freeqaz-openaiLocal Verification
andauthored
Split OpenShell startup tests into typed cases (#5676)
* Type OpenShell startup wiring and network admission cases * Type native Sandbox launch and recovery cases * test: type-check OpenShell startup case modules * test: check managed MCP admission with a typed install * Use the OpenShell credential catalog in admitted command tests * test: preserve managed MCP registration boundary --------- Co-authored-by: Local Verification <verification@localhost>
1 parent 3912754 commit 9b91c55

11 files changed

Lines changed: 675 additions & 522 deletions
Lines changed: 248 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,248 @@
1+
import assert from "node:assert/strict";
2+
import { createHash } from "node:crypto";
3+
import type { TestContext } from "node:test";
4+
import {
5+
OpenShellGateway,
6+
openShellProviderName,
7+
} from "../../apps/controller/src/backends/openshell.ts";
8+
import { OpenShellCredentialGatewayDriver } from "../../apps/controller/src/drivers/credential-gateway/openshell.ts";
9+
import type {
10+
KubernetesComputeDriver,
11+
KubernetesComputeDriverOptions,
12+
} from "../../apps/controller/src/drivers/compute/kubernetes/index.ts";
13+
import type { OpenShellSandboxCreateRequest } from "../../apps/controller/src/drivers/sandbox/openshell-gateway-client.ts";
14+
import { asRecord } from "../../packages/utils/src/index.ts";
15+
import type {
16+
AgentRevision,
17+
ComputeRevisionContext,
18+
CredentialGatewayDriver,
19+
CredentialSource,
20+
CredentialSourceLoginMode,
21+
} from "../../packages/contracts/src/index.ts";
22+
import {
23+
WORKSPACE_DEFAULTS,
24+
WORKSPACE_DEFAULTS_ID,
25+
} from "../../packages/contracts/src/workspace-defaults.mjs";
26+
import { inspectOpenShellCodexCommand } from "../fixtures/openshell-codex-command.ts";
27+
import {
28+
captureOpenShellHarness,
29+
providerEndpointFixture,
30+
tlsPinnedWorkspaceSetupCode,
31+
} from "../fixtures/kubernetes-provider-endpoint.mjs";
32+
import { admitRevisionHarness as admitRevisionHarnessFixture } from "../helpers/kubernetes-routed-scenarios.mjs";
33+
import { buildSandboxInstallation } from "./sandbox-driver-installation-fixture.ts";
34+
35+
const admitRevisionHarness: (driver: KubernetesComputeDriver, revision: AgentRevision) => void =
36+
admitRevisionHarnessFixture;
37+
38+
type HarnessCapture = Omit<ReturnType<typeof captureOpenShellHarness>, "request"> & {
39+
readonly request: unknown;
40+
};
41+
42+
type Mutable<T> = { -readonly [Key in keyof T]: T[Key] };
43+
44+
type CommandFixtureRevision = Mutable<Omit<AgentRevision, "compute">> & {
45+
compute: Mutable<AgentRevision["compute"]>;
46+
};
47+
48+
function capturedRequest(value: unknown): Pick<OpenShellSandboxCreateRequest, "name" | "spec"> {
49+
const request = asRecord(value);
50+
assert.ok(request);
51+
assert.ok(typeof request.name === "string");
52+
const spec = asRecord(request.spec);
53+
assert.ok(spec);
54+
return { name: request.name, spec };
55+
}
56+
57+
function commandArguments(value: unknown): string[] {
58+
assert.ok(Array.isArray(value));
59+
const args: unknown[] = value;
60+
assert.ok(args.every((arg): arg is string => typeof arg === "string"));
61+
return args;
62+
}
63+
64+
// The command budget applies after Compute adds the workspace verifier and
65+
// OpenShell adds links, setup wait and any account bootstrap to CreateSandbox.
66+
export async function verifyAdmittedComputeCommands(t: TestContext): Promise<void> {
67+
const installation = buildSandboxInstallation();
68+
const [backend] = installation.backend;
69+
assert.ok(backend);
70+
const gateway = installation.drivers.credential_gateway;
71+
const catalogDriver = new OpenShellCredentialGatewayDriver(gateway.configuration, {
72+
id: gateway.id,
73+
backend: {
74+
id: backend.id,
75+
// OpenShell advertises Codex OAuth only when its Backend provides credential refresh.
76+
drivers: { ...backend.drivers, credential_refresh: "openshell-refresh" },
77+
client: new OpenShellGateway(backend.configuration),
78+
},
79+
});
80+
const catalog = await catalogDriver.listSourceTypes({ signal: t.signal });
81+
const cases: ReadonlyArray<{
82+
loginMode: Extract<CredentialSourceLoginMode, "codex_pat" | "chatgptAuthTokens">;
83+
hasSetup: boolean;
84+
admitted: boolean;
85+
}> = [
86+
{ loginMode: "codex_pat", hasSetup: true, admitted: true },
87+
{ loginMode: "codex_pat", hasSetup: false, admitted: true },
88+
{ loginMode: "codex_pat", hasSetup: true, admitted: false },
89+
{ loginMode: "codex_pat", hasSetup: false, admitted: false },
90+
{ loginMode: "chatgptAuthTokens", hasSetup: true, admitted: true },
91+
];
92+
for (const { loginMode, hasSetup, admitted } of cases) {
93+
await t.test(`${loginMode}, setup ${hasSetup}, new admission ${admitted}`, async (t) => {
94+
const options: NonNullable<Parameters<typeof providerEndpointFixture>[0]> & {
95+
servicePrincipalCredentials: KubernetesComputeDriverOptions["servicePrincipalCredentials"];
96+
revisionOverrides: Pick<AgentRevision, "id" | "agentId" | "servicePrincipalId">;
97+
} = {
98+
servicePrincipalCredentials: { mode: "disabled" },
99+
revisionOverrides: {
100+
id: "rev_2c9250cd-6aa2-4493-a73e-2422ec6c1537",
101+
agentId: "agt_9bee809d-62ec-4d41-b68d-25ead74b3a4d",
102+
servicePrincipalId: "spn_02aa5adc-0b5c-417d-b8d4-1a1de5157809",
103+
},
104+
};
105+
const fixture = providerEndpointFixture(options);
106+
const { driver: compute, sandbox } = fixture;
107+
const revision: CommandFixtureRevision = fixture.revision;
108+
const capture: HarnessCapture = captureOpenShellHarness(fixture, sandbox);
109+
const source: CredentialSource = {
110+
id: "cs_324fc26c-59b3-43e0-b057-53fce26a2f19",
111+
namespaceId: revision.namespaceId,
112+
type: loginMode === "codex_pat" ? "codex-pat" : "codex-oauth",
113+
name: "fixture source",
114+
config: {},
115+
secrets: {},
116+
ownerCapability: "credential_gateway",
117+
driverId: catalogDriver.id,
118+
state: "ready",
119+
createdAt: revision.createdAt,
120+
};
121+
const sourceType = catalog.find((entry) => entry.type === source.type);
122+
assert.ok(sourceType);
123+
const ref = openShellProviderName(source.id);
124+
revision.harnessAuth = {
125+
method: "credential_source",
126+
sourceId: source.id,
127+
sourceType: source.type,
128+
credentialGatewayId: source.driverId,
129+
loginMode,
130+
};
131+
const credentialGateway: Pick<
132+
CredentialGatewayDriver,
133+
"id" | "capability" | "implementation" | "listSourceTypes" | "attachForRevision"
134+
> = {
135+
id: source.driverId,
136+
capability: "credential_gateway",
137+
implementation: "openshell",
138+
listSourceTypes: async () => [sourceType],
139+
attachForRevision: async () => [
140+
{
141+
sourceId: source.id,
142+
ref,
143+
...(loginMode === "chatgptAuthTokens" && {
144+
externalChatgptAuth: {
145+
accessTokenPlaceholder: `openshell:resolve:env:s${"1".repeat(64)}_CODEX_ACCESS_TOKEN`,
146+
accountId: "fixture-account",
147+
planType: "business",
148+
},
149+
}),
150+
},
151+
],
152+
};
153+
assert.ok(Object.hasOwn(compute, "credentialGatewayDriver"));
154+
Object.assign(compute, { credentialGatewayDriver: credentialGateway });
155+
revision.configuration = capture.openshell.configureAgent(
156+
revision.configuration,
157+
revision.harness,
158+
);
159+
admitRevisionHarness(compute, revision);
160+
if (!admitted) {
161+
// Pre-upgrade PAT revisions did not save a Compute admission.
162+
delete revision.compute.admission;
163+
}
164+
const workspaceSetup = {
165+
id: "workspace-setup-1f8d6823-aa87-4cba-ae3e-62352e892d12",
166+
namespaceId: revision.namespaceId,
167+
agentId: revision.agentId,
168+
defaultsId: WORKSPACE_DEFAULTS_ID,
169+
completed: false,
170+
files: { ...WORKSPACE_DEFAULTS, "AGENTS.md": "Private initial Agent instructions\n" },
171+
};
172+
const context: Pick<ComputeRevisionContext, "harnessAuth" | "workspaceSetup"> = {
173+
harnessAuth: { ...revision.harnessAuth, source },
174+
...(hasSetup && { workspaceSetup }),
175+
};
176+
const enrollment = compute["nodeEnrollment"];
177+
assert.ok(enrollment);
178+
const createSetup = enrollment.createSetup;
179+
enrollment.createSetup = async (url: string, nodeUrl: string, signal: AbortSignal) => {
180+
const setup = await createSetup(url, nodeUrl, signal);
181+
return { ...setup, setupCode: tlsPinnedWorkspaceSetupCode(nodeUrl, setup.expiresAtMs) };
182+
};
183+
184+
await fixture.prepare(undefined, context);
185+
fixture.setGatewayServing();
186+
// Let the real Compute enrollment write the Agent-owned Secret.
187+
const provision = (input = context) =>
188+
assert.rejects(fixture.prepare(undefined, input), (error) => error === capture.provisioned);
189+
await provision();
190+
const { name, spec } = capturedRequest(capture.request);
191+
const command = commandArguments(spec.command);
192+
const { loader, supervisor, codex } = inspectOpenShellCodexCommand(t, command, {
193+
compact: admitted && (hasSetup || loginMode === "codex_pat"),
194+
current: admitted,
195+
});
196+
if (!admitted) {
197+
// Stock 0.1.6 Compute and OpenShell at 4d68b3b7 render these exact commands.
198+
// Revisions with initial setup embed that release's workspace verifier.
199+
assert.equal(
200+
createHash("sha256").update(JSON.stringify(command)).digest("hex"),
201+
hasSetup
202+
? "b491545115bb907a872b0fe34b56cfc850dd684cd495ec280bb86e4a3f1cf3bc"
203+
: "a0d8025d10aeb7dbf26ca8271ad2cecb0eacb3ef1cd0bfafbf22ce251d9bd1fa",
204+
);
205+
}
206+
const startup = loader + supervisor;
207+
assert.equal(startup.includes(".oce-workspace-setup.json"), hasSetup);
208+
if (hasSetup) {
209+
assert.match(supervisor, new RegExp(workspaceSetup.id));
210+
assert.doesNotMatch(supervisor, /Private initial Agent instructions/);
211+
}
212+
assert.equal(
213+
codex.includes("unsupported_l7_protocol"),
214+
admitted && loginMode === "codex_pat",
215+
);
216+
const environment = asRecord(spec.environment);
217+
assert.ok(environment);
218+
assert.equal(environment.CODEX_LOGIN_MODE, loginMode);
219+
assert.equal(
220+
environment.OCE_CODEX_CREDENTIAL_SOURCE,
221+
loginMode === "codex_pat" ? "1" : undefined,
222+
);
223+
assert.equal(
224+
startup.includes("OCE_CODEX_CHATGPT_ACCOUNT"),
225+
loginMode === "chatgptAuthTokens",
226+
);
227+
228+
if (!admitted && hasSetup) {
229+
// Completing setup keeps the legacy Sandbox adoptable, while even one
230+
// byte of command drift in its stored spec must be refused.
231+
await provision({
232+
...context,
233+
workspaceSetup: { ...workspaceSetup, files: {}, completed: true },
234+
});
235+
const stored = capture.gateway.sandboxes.get(name);
236+
assert.ok(stored?.spec);
237+
const storedCommand = commandArguments(stored.spec.command);
238+
const loaderArgument = storedCommand[7];
239+
assert.equal(typeof loaderArgument, "string");
240+
storedCommand[7] = loaderArgument + " ";
241+
await assert.rejects(
242+
fixture.prepare(undefined, context),
243+
/without exact AgentRevision ownership and content/,
244+
);
245+
}
246+
});
247+
}
248+
}

‎tests/integration/sandbox-driver-gateway-replay-cases.ts‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@ export async function prepareGatewayReplayFixture({
6969
prepareProvision,
7070
harnessService,
7171
storedSandbox,
72-
replayState,
7372
}: {
7473
openShellDriver: (gatewayClient: ReplayGateway) => OpenShellSandboxDriver;
7574
prepareProvision: (driver: OpenShellSandboxDriver) => Provision;
@@ -82,8 +81,14 @@ export async function prepareGatewayReplayFixture({
8281
request: OpenShellSandboxCreateRequest,
8382
fields: Pick<OpenShellSandboxResponse, "id">,
8483
) => OpenShellSandboxResponse;
85-
replayState: ReplayState;
8684
}) {
85+
const replayState: ReplayState = {
86+
handlerError: undefined,
87+
refuseEverything: undefined,
88+
onRefusal: undefined,
89+
holdHandler: undefined,
90+
reachedHold: undefined,
91+
};
8792
const gatewayClient: ReplayGateway = workspaceGatewayClient();
8893
const sandboxes = new Map<string, OpenShellSandboxResponse>();
8994
const admissions = new Map<string, { payload: string; sandboxId?: string }>();
@@ -154,7 +159,47 @@ export async function prepareGatewayReplayFixture({
154159
return seen;
155160
};
156161
const id0 = "00000000-0000-4000-8000-000000000004";
157-
return { gatewayClient, sandboxes, provision, trace, id0 };
162+
return { gatewayClient, sandboxes, provision, trace, id0, replayState };
163+
}
164+
165+
export async function verifyFreshRequestAfterRefusal({
166+
sandboxes,
167+
provision,
168+
trace,
169+
id0,
170+
replayState,
171+
}: Awaited<ReturnType<typeof prepareGatewayReplayFixture>>) {
172+
// A create that errors server-side leaves its request_id unresolved.
173+
replayState.handlerError = new Error("provider 'model' not found");
174+
await assert.rejects(provision(), /provider 'model' not found/);
175+
assert.deepEqual(trace(), ["getSandbox", `createSandbox:${id0}`]);
176+
177+
// The next pass sees the refusal and no Sandbox, then creates with the next request_id.
178+
const first = await provision();
179+
const [, refusedCreate, , freshCreate] = trace();
180+
assert.equal(refusedCreate, `createSandbox:${id0}`);
181+
assert.ok(freshCreate);
182+
const id1 = freshCreate.slice("createSandbox:".length);
183+
assert.match(id1, /^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
184+
assert.notEqual(id1, id0);
185+
assert.equal(sandboxes.size, 1);
186+
187+
// Each failing pass spends at most one new request_id.
188+
sandboxes.clear();
189+
replayState.handlerError = new Error("compute driver unavailable");
190+
await assert.rejects(provision(), /compute driver unavailable/);
191+
const failed = trace();
192+
assert.deepEqual(failed.slice(0, 4), [
193+
"getSandbox",
194+
`createSandbox:${id0}`,
195+
"getSandbox",
196+
`createSandbox:${id1}`,
197+
]);
198+
assert.equal(failed.length, 6);
199+
const failedCreate = failed[5];
200+
assert.ok(failedCreate);
201+
const id2 = failedCreate.slice("createSandbox:".length);
202+
return { first, id1, id2 };
158203
}
159204

160205
export async function verifyConcurrentReplayAndExhaustion({
Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,32 @@
11
import assert from "node:assert/strict";
2-
import type {
2+
import { managedMcpInstalls } from "../../apps/controller/src/drivers/plugin/managed-catalog.ts";
3+
import {
4+
assertNoManagedMcpRouteOverlap,
35
managedMcpNetwork,
46
managedMcpProviderEndpoint,
57
} from "../../apps/controller/src/drivers/sandbox/openshell-managed-mcp-policy.ts";
68

7-
type ManagedMcpInstall = Parameters<typeof managedMcpProviderEndpoint>[0];
8-
9-
export function assertManagedMcpProjection({
10-
endpoint,
11-
install,
12-
provider,
13-
network,
14-
}: {
15-
endpoint: ManagedMcpInstall["endpoint"];
16-
install: ManagedMcpInstall;
17-
provider: ReturnType<typeof managedMcpProviderEndpoint>;
18-
network: ReturnType<typeof managedMcpNetwork>;
19-
}): void {
9+
export function verifyManagedMcpProjection(): void {
10+
const bundled = managedMcpInstalls.find(({ id }) => id === "occ-plugin:slack@1.0.0");
11+
assert.ok(bundled);
12+
const endpoint = { host: "mcp.tools.example", port: 8443, path: "/api/mcp" };
13+
const install = {
14+
...bundled,
15+
runtimeName: "inventory",
16+
endpoint,
17+
url: `https://${endpoint.host}:${endpoint.port}${endpoint.path}`,
18+
mcpVersions: ["2025-11-25"],
19+
};
20+
const provider = managedMcpProviderEndpoint(install);
21+
const network = managedMcpNetwork(install, ["read_inventory"]);
2022
assert.deepEqual(provider, {
2123
...endpoint,
2224
protocol: "mcp",
2325
mcp: { strict_tool_names: true, versions: ["2025-11-25"] },
2426
rules: [{ allow: { method: "ping" } }],
2527
});
2628
assert.equal(network.name, "oce-inventory-mcp");
27-
assert.deepEqual(network.binaries, [{ path: install.binaryPath }]);
29+
assert.deepEqual(network.binaries, [{ path: "/usr/local/bin/node" }]);
2830
assert.deepEqual(network.endpoints, [
2931
{
3032
host: endpoint.host,
@@ -42,4 +44,21 @@ export function assertManagedMcpProjection({
4244
],
4345
},
4446
]);
47+
assert.doesNotThrow(() =>
48+
assertNoManagedMcpRouteOverlap(overlappingPolicy(network, 443), install, [network.name]),
49+
);
50+
assert.throws(
51+
() =>
52+
assertNoManagedMcpRouteOverlap(overlappingPolicy(network, endpoint.port), install, [
53+
network.name,
54+
]),
55+
/overlaps the credentialed managed MCP endpoint/,
56+
);
57+
}
58+
59+
function overlappingPolicy(network: ReturnType<typeof managedMcpNetwork>, port: number) {
60+
return {
61+
[network.name]: network,
62+
other: { endpoints: [{ host: "*.tools.example", ports: [port] }] },
63+
};
4564
}

0 commit comments

Comments
 (0)