Skip to content

Commit 4d8bfab

Browse files
authored
fix(gateway): preserve cloud node ownership (#128780)
Keep durable cloud node bindings out of ordinary device placement until enrollment retirement is proven, and fail closed when worker ownership inventory cannot be read.\n\nRefs #128769
1 parent 28ee832 commit 4d8bfab

3 files changed

Lines changed: 259 additions & 92 deletions

File tree

Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
import { ErrorCodes } from "../../../packages/gateway-protocol/src/index.js";
3+
import { listNodePairing } from "../../infra/device-pairing-node.js";
4+
import { listDevicePairing } from "../../infra/device-pairing.js";
5+
import {
6+
collectNodeRunnerIssuesByNodeId,
7+
collectNodeWorkerBundleStatusByNodeId,
8+
collectNodeWorkerCapacityByNodeId,
9+
isNodeRunnerSessionHost,
10+
} from "../node-registry-private.js";
11+
import type {
12+
WorkerEnvironmentServiceContract,
13+
WorkerEnvironmentServiceRecord,
14+
} from "../worker-environments/service-contract.js";
15+
import { environmentsHandlers } from "./environments.js";
16+
17+
vi.mock("../../infra/device-pairing.js", () => ({
18+
listDevicePairing: vi.fn(),
19+
resolveNodePairingState: vi.fn(),
20+
}));
21+
22+
vi.mock("../../infra/device-pairing-node.js", () => ({
23+
listNodePairing: vi.fn(),
24+
}));
25+
26+
vi.mock("../node-registry-private.js", () => ({
27+
collectNodeRunnerIssuesByNodeId: vi.fn(() => new Map()),
28+
collectNodeWorkerBundleStatusByNodeId: vi.fn(() => new Map()),
29+
collectNodeWorkerCapacityByNodeId: vi.fn(() => new Map()),
30+
isNodeRunnerSessionHost: vi.fn(() => false),
31+
}));
32+
33+
type TestWorkerService = Pick<WorkerEnvironmentServiceContract, "get" | "list">;
34+
35+
const CONNECTED_NODE = {
36+
nodeId: "node-live",
37+
connId: "conn-live",
38+
displayName: "Live Node",
39+
platform: "linux",
40+
caps: [],
41+
commands: ["system.run"],
42+
connectedAtMs: 123,
43+
};
44+
45+
function workerRecord(
46+
overrides: Partial<WorkerEnvironmentServiceRecord> = {},
47+
): WorkerEnvironmentServiceRecord {
48+
return {
49+
environmentId: "worker-1",
50+
providerId: "static-ssh",
51+
leaseId: "lease-1",
52+
sharedHost: false,
53+
state: "ready",
54+
ownerEpoch: 1,
55+
createdAtMs: 1_000,
56+
idleSinceAtMs: null,
57+
attachedSessionIds: [],
58+
desktopAvailable: false,
59+
desktopApps: [],
60+
tunnelStatus: "stopped",
61+
...overrides,
62+
};
63+
}
64+
65+
function workerService(overrides: Partial<TestWorkerService> = {}): TestWorkerService {
66+
return {
67+
list: vi.fn(() => []),
68+
get: vi.fn(() => undefined),
69+
...overrides,
70+
};
71+
}
72+
73+
async function callEnvironmentMethod(
74+
method: "environments.list" | "environments.status",
75+
params: unknown,
76+
service: TestWorkerService,
77+
) {
78+
const respond = vi.fn();
79+
await environmentsHandlers[method]?.({
80+
params: params as Record<string, unknown>,
81+
respond,
82+
context: {
83+
logGateway: { warn: vi.fn() },
84+
nodeRegistry: {
85+
listConnectedForPairingStates: () => [CONNECTED_NODE],
86+
},
87+
workerEnvironmentService: service,
88+
getRuntimeConfig: () => ({}),
89+
},
90+
} as never);
91+
const call = respond.mock.calls.at(0);
92+
if (!call) {
93+
throw new Error("expected environments handler to respond");
94+
}
95+
return call;
96+
}
97+
98+
beforeEach(() => {
99+
vi.mocked(isNodeRunnerSessionHost).mockReturnValue(false);
100+
vi.mocked(collectNodeRunnerIssuesByNodeId).mockReturnValue(new Map());
101+
vi.mocked(collectNodeWorkerCapacityByNodeId).mockReturnValue(new Map());
102+
vi.mocked(collectNodeWorkerBundleStatusByNodeId).mockReturnValue(new Map());
103+
vi.mocked(listDevicePairing).mockResolvedValue({ paired: [] } as never);
104+
vi.mocked(listNodePairing).mockResolvedValue({ paired: [] } as never);
105+
});
106+
107+
afterEach(() => vi.restoreAllMocks());
108+
109+
describe("environment node ownership", () => {
110+
it.each([
111+
{
112+
name: "requested worker without a node binding",
113+
state: "requested",
114+
status: "starting",
115+
visible: true,
116+
providerId: "static-ssh",
117+
nodeDeviceId: undefined,
118+
},
119+
{
120+
name: "ready cloud worker",
121+
state: "ready",
122+
status: "available",
123+
visible: false,
124+
providerId: "static-ssh",
125+
nodeDeviceId: "node-live",
126+
},
127+
{
128+
name: "draining cloud worker",
129+
state: "draining",
130+
status: "stopping",
131+
visible: false,
132+
providerId: "static-ssh",
133+
nodeDeviceId: "node-live",
134+
},
135+
{
136+
name: "destroyed cloud worker",
137+
state: "destroyed",
138+
status: "unavailable",
139+
visible: true,
140+
providerId: "static-ssh",
141+
nodeDeviceId: "node-live",
142+
},
143+
{
144+
name: "failed cloud worker retaining its node binding",
145+
state: "failed",
146+
status: "error",
147+
visible: false,
148+
providerId: "static-ssh",
149+
nodeDeviceId: "node-live",
150+
},
151+
{
152+
name: "failed cloud worker after enrollment retirement",
153+
state: "failed",
154+
status: "error",
155+
visible: true,
156+
providerId: "static-ssh",
157+
nodeDeviceId: undefined,
158+
},
159+
{
160+
name: "orphaned cloud worker",
161+
state: "orphaned",
162+
status: "error",
163+
visible: false,
164+
providerId: "static-ssh",
165+
nodeDeviceId: "node-live",
166+
},
167+
{
168+
name: "paired-device provider worker",
169+
state: "ready",
170+
status: "available",
171+
visible: true,
172+
providerId: "device",
173+
nodeDeviceId: "node-live",
174+
},
175+
] as const)("projects $name without losing pairing ownership", async (scenario) => {
176+
const error =
177+
scenario.state === "orphaned" ? "provider no longer recognizes the lease" : undefined;
178+
const service = workerService({
179+
list: vi.fn(() => [
180+
workerRecord({
181+
state: scenario.state,
182+
providerId: scenario.providerId,
183+
nodeDeviceId: scenario.nodeDeviceId,
184+
...(error ? { error } : {}),
185+
}),
186+
]),
187+
});
188+
189+
const [ok, payload] = await callEnvironmentMethod("environments.list", {}, service);
190+
const environments = (payload as { environments: Array<Record<string, unknown>> }).environments;
191+
192+
expect(ok).toBe(true);
193+
expect(environments.some((entry) => entry.id === "node:node-live")).toBe(scenario.visible);
194+
expect(environments.find((entry) => entry.id === "worker-1")).toMatchObject({
195+
type: "worker",
196+
status: scenario.status,
197+
worker: {
198+
providerId: scenario.providerId,
199+
state: scenario.state,
200+
...(error ? { error } : {}),
201+
},
202+
});
203+
});
204+
205+
it("fails closed and redacts worker inventory read failures", async () => {
206+
const secret = "private SecretRef and database path";
207+
const listFailure = workerService({
208+
list: vi.fn(() => {
209+
throw new Error(secret);
210+
}),
211+
});
212+
const statusFailure = workerService({
213+
get: vi.fn(() => {
214+
throw new Error(secret);
215+
}),
216+
});
217+
218+
const listResult = await callEnvironmentMethod("environments.list", {}, listFailure);
219+
const nodeStatusResult = await callEnvironmentMethod(
220+
"environments.status",
221+
{ environmentId: "node:node-live" },
222+
listFailure,
223+
);
224+
const workerStatusResult = await callEnvironmentMethod(
225+
"environments.status",
226+
{ environmentId: "worker-missing" },
227+
statusFailure,
228+
);
229+
230+
const inventoryFailure = {
231+
code: ErrorCodes.UNAVAILABLE,
232+
message: "Error: environment inventory unavailable",
233+
};
234+
expect(listResult).toEqual([false, undefined, inventoryFailure]);
235+
expect(nodeStatusResult).toEqual([false, undefined, inventoryFailure]);
236+
expect(workerStatusResult[2]).toEqual({
237+
code: ErrorCodes.UNAVAILABLE,
238+
message: "environment status unavailable",
239+
});
240+
expect(JSON.stringify([listResult, nodeStatusResult, workerStatusResult])).not.toContain(
241+
secret,
242+
);
243+
});
244+
});

‎src/gateway/server-methods/environments.test.ts‎

Lines changed: 8 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import {
1313
collectNodeWorkerCapacityByNodeId,
1414
isNodeRunnerSessionHost,
1515
} from "../node-registry-private.js";
16-
import type { WorkerEnvironmentServiceRecord } from "../worker-environments/service-contract.js";
16+
import type {
17+
WorkerEnvironmentServiceContract,
18+
WorkerEnvironmentServiceRecord,
19+
} from "../worker-environments/service-contract.js";
1720
import type { WorkerEnvironmentRecord } from "../worker-environments/store.js";
1821
import { environmentsHandlers, summarizeWorkerEnvironment } from "./environments.js";
1922

@@ -35,36 +38,9 @@ vi.mock("../node-registry-private.js", () => ({
3538

3639
const NOW = 10_000;
3740

38-
type TestWorkerRecord = WorkerEnvironmentRecord &
39-
Pick<
40-
WorkerEnvironmentServiceRecord,
41-
"desktopAvailable" | "desktopApps" | "tunnelStatus" | "error"
42-
>;
43-
44-
type TestWorkerService = {
45-
list: () => TestWorkerRecord[];
46-
get: (environmentId: string) => TestWorkerRecord | undefined;
47-
supportsExecutionMode: (profileId: string, mode: "worker-turn" | "remote-exec") => boolean;
48-
listMachineOptions: (
49-
profileId: string,
50-
) => Promise<
51-
Array<{ id: string; label: string; description?: string; default?: boolean }> | undefined
52-
>;
53-
create: (profileId: string, idempotencyKey: string) => Promise<TestWorkerRecord>;
54-
destroy: (environmentId: string) => Promise<TestWorkerRecord>;
55-
destroyUnattached: (environmentId: string) => Promise<TestWorkerRecord>;
56-
observeDesktop: (request: { environmentId: string; control: boolean }) => Promise<{
57-
transport: "rfb";
58-
wsPath: string;
59-
expiresAtMs: number;
60-
control: boolean;
61-
vncPassword?: string;
62-
}>;
63-
launchDesktopApp: (request: {
64-
environmentId: string;
65-
app: "browser" | "terminal";
66-
}) => Promise<{ app: "browser" | "terminal"; status: "ready" }>;
67-
};
41+
type TestWorkerRecord = WorkerEnvironmentRecord & WorkerEnvironmentServiceRecord;
42+
43+
type TestWorkerService = Omit<WorkerEnvironmentServiceContract, "startTunnel" | "stopTunnel">;
6844

6945
function mockContext(
7046
workerEnvironmentService?: TestWorkerService,
@@ -494,6 +470,7 @@ describe("environment gateway methods", () => {
494470
expect(worker).not.toHaveProperty("sshEndpoint");
495471
expect(worker?.worker).not.toHaveProperty("sshEndpoint");
496472
expect(worker?.worker).not.toHaveProperty("keyRef");
473+
expect(service.list).toHaveBeenCalledOnce();
497474
});
498475

499476
it("adds known provider capabilities to configured profile summaries", async () => {
@@ -551,17 +528,6 @@ describe("environment gateway methods", () => {
551528
).not.toHaveProperty("executionMode");
552529
});
553530

554-
it.each([
555-
["requested", "starting"],
556-
["ready", "available"],
557-
["draining", "stopping"],
558-
["destroyed", "unavailable"],
559-
["failed", "error"],
560-
["orphaned", "error"],
561-
] as const)("maps worker state %s to %s", (state, status) => {
562-
expect(summarizeWorkerEnvironment(workerRecord({ state }), NOW).status).toBe(status);
563-
});
564-
565531
it("projects trust from recorded worker isolation without guessing unknown leases", () => {
566532
expect(summarizeWorkerEnvironment(workerRecord({ sharedHost: true }), NOW).trust).toBe(
567533
"persistent",
@@ -655,49 +621,6 @@ describe("environment gateway methods", () => {
655621
});
656622
});
657623

658-
it("preserves gateway listing and hides durable-store details when worker reads fail", async () => {
659-
const secret = "private SecretRef and database path";
660-
const listFailure = workerService({
661-
list: vi.fn(() => {
662-
throw new Error(secret);
663-
}),
664-
});
665-
const statusFailure = workerService({
666-
get: vi.fn(() => {
667-
throw new Error(secret);
668-
}),
669-
});
670-
671-
const listResult = await callEnvironmentMethod(
672-
"environments.list",
673-
{},
674-
{
675-
service: listFailure,
676-
},
677-
);
678-
const statusResult = await callEnvironmentMethod(
679-
"environments.status",
680-
{ environmentId: "worker-missing" },
681-
{ service: statusFailure },
682-
);
683-
684-
expect(listResult[0]).toBe(true);
685-
const listed = (listResult[1] as { environments: Array<{ id: string; type: string }> })
686-
.environments;
687-
// Gateway/node inventory survives a damaged worker store; worker rows are omitted.
688-
expect(listed.map((entry) => entry.id)).toEqual([
689-
"gateway",
690-
"node:node-live",
691-
"node:node-offline",
692-
]);
693-
expect(listed.every((entry) => entry.type !== "worker")).toBe(true);
694-
expect(statusResult[2]).toEqual({
695-
code: ErrorCodes.UNAVAILABLE,
696-
message: "environment status unavailable",
697-
});
698-
expect(JSON.stringify([listResult, statusResult])).not.toContain(secret);
699-
});
700-
701624
it("keeps worker creation unavailable until a provider profile is configured", async () => {
702625
const [ok, , error] = await callEnvironmentMethod("environments.create", {
703626
profileId: "development",

0 commit comments

Comments
 (0)