Skip to content

Commit 41dccab

Browse files
authored
fix(worker): reject malformed protocol records (#133123)
* fix(worker): require own protocol record keys * fix(worker): avoid unnecessary protocol assertion * fix(worker): reject inherited optional protocol fields * test(worker): avoid shadowed computer binding
1 parent aace96c commit 41dccab

13 files changed

Lines changed: 234 additions & 78 deletions

‎src/worker/launch-descriptor.test.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,19 @@ describe("worker launch descriptor", () => {
106106
});
107107
});
108108

109+
it("rejects a launch version inherited from the prototype", () => {
110+
const descriptor = launchDescriptor();
111+
const { version, ...ownFields } = descriptor;
112+
const candidate = Object.assign(
113+
Object.create({ version }) as Record<string, unknown>,
114+
ownFields,
115+
);
116+
117+
expect(() => parseWorkerLaunchDescriptor(candidate)).toThrow(
118+
"invalid worker launch descriptor",
119+
);
120+
});
121+
109122
it("accepts the permission context pair only when both fields are present", () => {
110123
const descriptor = launchDescriptor();
111124
const {
@@ -333,15 +346,29 @@ describe("worker launch descriptor", () => {
333346
descriptor.assignment.toolAuthority.allowedToolNames = ["computer"];
334347
descriptor.assignment.prompt = [{ type: "image", data: "AA==", mimeType: "image/png" }];
335348
expect(parseWorkerLaunchDescriptor(descriptor)).toEqual(descriptor);
336-
for (const computer of [
349+
const { computer, ...assignmentFields } = descriptor.assignment;
350+
const inheritedComputerAssignment = Object.assign(
351+
Object.create({ computer }),
352+
assignmentFields,
353+
);
354+
expect(() =>
355+
parseWorkerLaunchDescriptor({
356+
...descriptor,
357+
assignment: inheritedComputerAssignment,
358+
}),
359+
).toThrow("invalid worker launch descriptor");
360+
const { nodeId, ...computerFields } = descriptor.assignment.computer;
361+
const inheritedNodeIdComputer = Object.assign(Object.create({ nodeId }), computerFields);
362+
for (const candidateComputer of [
337363
undefined,
338364
{ ...descriptor.assignment.computer, gatewayUrl: "ws://other" },
339365
{ ...descriptor.assignment.computer, nodeId: "" },
366+
inheritedNodeIdComputer,
340367
]) {
341368
expect(() =>
342369
parseWorkerLaunchDescriptor({
343370
...descriptor,
344-
assignment: { ...descriptor.assignment, computer },
371+
assignment: { ...descriptor.assignment, computer: candidateComputer },
345372
}),
346373
).toThrow("invalid worker launch descriptor");
347374
}

‎src/worker/launch-descriptor.ts‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
ComputerUseCapabilityDescriptorSchema,
3535
type ComputerUseCapabilityDescriptor,
3636
} from "../plugins/computer-use-contract.js";
37+
import { hasExactOwnKeys } from "./protocol-record.js";
3738
import { isWorkerToolName, type WorkerToolAuthority } from "./tool-authority.js";
3839
import { isWorkerTranscriptMessageFrameSafe } from "./transcript-message.js";
3940
import {
@@ -99,13 +100,6 @@ export type WorkerLaunchDescriptor = WorkerLaunchPlan & {
99100
connectionEndpoint: WorkerConnectionEndpoint;
100101
};
101102

102-
function hasExactKeys(value: Record<string, unknown>, required: string[], optional: string[] = []) {
103-
const allowed = new Set([...required, ...optional]);
104-
return (
105-
required.every((key) => key in value) && Object.keys(value).every((key) => allowed.has(key))
106-
);
107-
}
108-
109103
function isIdentifier(value: unknown): value is string {
110104
return (
111105
typeof value === "string" &&
@@ -130,7 +124,7 @@ function isInferenceOptions(value: unknown): value is WorkerInferenceOptions {
130124
function parseToolAuthority(value: unknown): WorkerToolAuthority | undefined {
131125
if (
132126
!isRecord(value) ||
133-
!hasExactKeys(value, ["allowedToolNames"]) ||
127+
!hasExactOwnKeys(value, ["allowedToolNames"]) ||
134128
!Array.isArray(value.allowedToolNames) ||
135129
!value.allowedToolNames.every(isWorkerToolName) ||
136130
new Set(value.allowedToolNames).size !== value.allowedToolNames.length
@@ -143,7 +137,7 @@ function parseToolAuthority(value: unknown): WorkerToolAuthority | undefined {
143137
function parseBrowserLaunchDescriptor(value: unknown): WorkerBrowserLaunchDescriptor | undefined {
144138
if (
145139
!isRecord(value) ||
146-
!hasExactKeys(value, ["cdpUrl", "launcherPath"]) ||
140+
!hasExactOwnKeys(value, ["cdpUrl", "launcherPath"]) ||
147141
typeof value.cdpUrl !== "string" ||
148142
typeof value.launcherPath !== "string" ||
149143
!isAbsoluteHostPath(value.launcherPath)
@@ -181,7 +175,7 @@ function parseBrowserLaunchDescriptor(value: unknown): WorkerBrowserLaunchDescri
181175
function parseAssignment(value: unknown): WorkerLaunchAssignment | undefined {
182176
if (
183177
!isRecord(value) ||
184-
!hasExactKeys(
178+
!hasExactOwnKeys(
185179
value,
186180
[
187181
"agentId",
@@ -257,7 +251,7 @@ function parseAssignment(value: unknown): WorkerLaunchAssignment | undefined {
257251
toolAuthority.allowedToolNames.includes("computer") !== (value.computer !== undefined) ||
258252
(value.computer !== undefined &&
259253
(!isRecord(value.computer) ||
260-
!hasExactKeys(value.computer, ["nodeId", "computerUse"]) ||
254+
!hasExactOwnKeys(value.computer, ["nodeId", "computerUse"]) ||
261255
!isIdentifier(value.computer.nodeId) ||
262256
!Value.Check(ComputerUseCapabilityDescriptorSchema, value.computer.computerUse)))
263257
) {
@@ -271,15 +265,15 @@ function parseAssignment(value: unknown): WorkerLaunchAssignment | undefined {
271265
}
272266
if (
273267
!isRecord(value.transcript) ||
274-
!hasExactKeys(value.transcript, ["baseLeafId", "nextSeq"]) ||
268+
!hasExactOwnKeys(value.transcript, ["baseLeafId", "nextSeq"]) ||
275269
(value.transcript.baseLeafId !== null && !isIdentifier(value.transcript.baseLeafId)) ||
276270
!isSafeSequence(value.transcript.nextSeq, 1)
277271
) {
278272
return undefined;
279273
}
280274
if (
281275
!isRecord(value.liveEvents) ||
282-
!hasExactKeys(value.liveEvents, ["ackedSeq", "nextSeq"]) ||
276+
!hasExactOwnKeys(value.liveEvents, ["ackedSeq", "nextSeq"]) ||
283277
!isSafeSequence(value.liveEvents.ackedSeq, 0) ||
284278
!isSafeSequence(value.liveEvents.nextSeq, 1) ||
285279
value.liveEvents.nextSeq !== value.liveEvents.ackedSeq + 1
@@ -345,7 +339,7 @@ function validateWorkerLaunchPlan(candidate: WorkerLaunchPlan): WorkerLaunchPlan
345339
export function parseWorkerLaunchPlan(value: unknown): WorkerLaunchPlan {
346340
if (
347341
!isRecord(value) ||
348-
!hasExactKeys(value, ["version", "admission", "assignment"]) ||
342+
!hasExactOwnKeys(value, ["version", "admission", "assignment"]) ||
349343
value.version !== LAUNCH_VERSION
350344
) {
351345
throw new Error("invalid worker launch descriptor");
@@ -376,7 +370,7 @@ export function completeWorkerLaunchDescriptor(
376370
export function parseWorkerLaunchDescriptor(value: unknown): WorkerLaunchDescriptor {
377371
if (
378372
!isRecord(value) ||
379-
!hasExactKeys(value, ["version", "connectionEndpoint", "admission", "assignment"])
373+
!hasExactOwnKeys(value, ["version", "connectionEndpoint", "admission", "assignment"])
380374
) {
381375
throw new Error("invalid worker launch descriptor");
382376
}

‎src/worker/node-desktop-protocol.ts‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from "node:path";
22
import { isRecord } from "@openclaw/normalization-core/record-coerce";
33
import type { WorkerDesktopApp } from "../plugins/capability-provider.types.js";
44
import { NODE_DESKTOP_ATTACH_PATH } from "../shared/node-desktop-stream.js";
5+
import { hasExactOwnKeys } from "./protocol-record.js";
56

67
const REQUEST_MAX_BYTES = 16 * 1024;
78
const PATH_MAX_BYTES = 4 * 1024;
@@ -25,18 +26,6 @@ function parseJson(raw?: string | null): unknown {
2526
}
2627
}
2728

28-
function hasExactKeys(
29-
value: Record<string, unknown>,
30-
required: readonly string[],
31-
optional: readonly string[] = [],
32-
): boolean {
33-
const allowed = new Set([...required, ...optional]);
34-
return (
35-
required.every((key) => Object.hasOwn(value, key)) &&
36-
Object.keys(value).every((key) => allowed.has(key))
37-
);
38-
}
39-
4029
function isValidPort(value: unknown): value is number {
4130
return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= 65_535;
4231
}
@@ -59,7 +48,7 @@ export function parseNodeWorkerDesktopStreamInput(
5948
const value = parseJson(raw);
6049
if (
6150
!isRecord(value) ||
62-
!hasExactKeys(value, ["ticket", "attachPath", "port"], ["passwordFilePath"])
51+
!hasExactOwnKeys(value, ["ticket", "attachPath", "port"], ["passwordFilePath"])
6352
) {
6453
throw new Error("INVALID_REQUEST: invalid node worker desktop stream request");
6554
}
@@ -92,12 +81,12 @@ export function parseNodeWorkerDesktopLaunchInput(raw?: string | null): WorkerDe
9281
}
9382
const executablePath = requireAbsolutePath(value.executablePath, "executablePath");
9483
if (value.id === "terminal") {
95-
if (!hasExactKeys(value, ["id", "executablePath"])) {
84+
if (!hasExactOwnKeys(value, ["id", "executablePath"])) {
9685
throw new Error("INVALID_REQUEST: invalid node worker terminal descriptor");
9786
}
9887
return { id: "terminal", executablePath };
9988
}
100-
if (!hasExactKeys(value, ["id", "executablePath", "cdpPort"]) || !isValidPort(value.cdpPort)) {
89+
if (!hasExactOwnKeys(value, ["id", "executablePath", "cdpPort"]) || !isValidPort(value.cdpPort)) {
10190
throw new Error("INVALID_REQUEST: invalid node worker browser descriptor");
10291
}
10392
return { id: "browser", executablePath, cdpPort: value.cdpPort };

‎src/worker/node-supervisor-protocol.ts‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
22
import { stableStringify } from "@openclaw/normalization-core";
33
import { isRecord } from "@openclaw/normalization-core/record-coerce";
44
import { parseWorkerLaunchPlan, type WorkerLaunchPlan } from "./launch-descriptor.js";
5+
import { hasExactOwnKeys } from "./protocol-record.js";
56

67
const IDENTIFIER_MAX_CHARS = 256;
78
const GATEWAY_NAMESPACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
@@ -61,12 +62,6 @@ export type NodeWorkerConnectionFailureMessage = {
6162
cause: string | null;
6263
};
6364

64-
function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
65-
return (
66-
Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key))
67-
);
68-
}
69-
7065
function isIdentifier(value: unknown): value is string {
7166
return (
7267
typeof value === "string" &&
@@ -129,7 +124,7 @@ export function parseNodeWorkerLaunchInput(raw?: string | null): NodeWorkerLaunc
129124
export function validateNodeWorkerLaunchInput(value: unknown): NodeWorkerLaunchInput {
130125
if (
131126
!isRecord(value) ||
132-
!hasExactKeys(value, [
127+
!hasExactOwnKeys(value, [
133128
"environmentSession",
134129
"launchId",
135130
"gatewayNamespace",
@@ -178,7 +173,7 @@ export function validateNodeWorkerLaunchInput(value: unknown): NodeWorkerLaunchI
178173

179174
export function parseNodeWorkerLookupInput(raw?: string | null): { launchId: string } {
180175
const value = decodeRequest(raw);
181-
if (!isRecord(value) || !hasExactKeys(value, ["launchId"])) {
176+
if (!isRecord(value) || !hasExactOwnKeys(value, ["launchId"])) {
182177
throw new Error("INVALID_REQUEST: invalid node worker lookup request");
183178
}
184179
return { launchId: requireIdentifier(value.launchId, "launchId") };
@@ -191,7 +186,7 @@ export function parseNodeWorkerCancelInput(raw?: string | null): NodeWorkerSuper
191186
const value = decodeRequest(raw);
192187
if (
193188
!isRecord(value) ||
194-
!hasExactKeys(value, [
189+
!hasExactOwnKeys(value, [
195190
"launchId",
196191
"planHash",
197192
"environmentId",
@@ -229,7 +224,7 @@ export function parseNodeWorkerEnvironmentStopInput(
229224
const value = decodeRequest(raw);
230225
if (
231226
!isRecord(value) ||
232-
!hasExactKeys(value, ["gatewayNamespace", "environmentId", "sessionId", "ownerEpoch"])
227+
!hasExactOwnKeys(value, ["gatewayNamespace", "environmentId", "sessionId", "ownerEpoch"])
233228
) {
234229
throw new Error("INVALID_REQUEST: invalid node worker environment stop request");
235230
}
@@ -325,7 +320,7 @@ export function parseNodeWorkerConnectionFailureMessage(
325320
): NodeWorkerConnectionFailureMessage | null {
326321
if (
327322
!isRecord(value) ||
328-
!hasExactKeys(value, ["type", "cause"]) ||
323+
!hasExactOwnKeys(value, ["type", "cause"]) ||
329324
value.type !== NODE_WORKER_CONNECTION_FAILURE_MESSAGE_TYPE ||
330325
(value.cause !== null &&
331326
(typeof value.cause !== "string" ||
@@ -351,18 +346,18 @@ export function parseNodeWorkerSupervisorReceipt(
351346
return null;
352347
}
353348
if (value.state === "pending" || value.state === "running") {
354-
return hasExactKeys(value, [...RECEIPT_IDENTITY_KEYS, "state"])
349+
return hasExactOwnKeys(value, [...RECEIPT_IDENTITY_KEYS, "state"])
355350
? { ...identity, state: value.state }
356351
: null;
357352
}
358353
if (value.state === "completed") {
359-
return hasExactKeys(value, [...RECEIPT_IDENTITY_KEYS, "state", "resultJson"]) &&
354+
return hasExactOwnKeys(value, [...RECEIPT_IDENTITY_KEYS, "state", "resultJson"]) &&
360355
isBoundedResultJson(value.resultJson)
361356
? { ...identity, state: value.state, resultJson: value.resultJson }
362357
: null;
363358
}
364359
if (value.state === "failed" || value.state === "interrupted" || value.state === "cancelled") {
365-
return hasExactKeys(value, [...RECEIPT_IDENTITY_KEYS, "state", "errorText"]) &&
360+
return hasExactOwnKeys(value, [...RECEIPT_IDENTITY_KEYS, "state", "errorText"]) &&
366361
isBoundedErrorText(value.errorText)
367362
? { ...identity, state: value.state, errorText: value.errorText }
368363
: null;

‎src/worker/node-workspace-protocol.ts‎

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from "node:path";
22
import { isRecord } from "@openclaw/normalization-core/record-coerce";
33
import type { SpawnResult } from "../process/exec.js";
44
import type { NodeWorkerWorkspaceTransferInput } from "./node-workspace-transfer-protocol.js";
5+
import { hasExactOwnKeys } from "./protocol-record.js";
56

67
const IDENTIFIER_MAX_CHARS = 256;
78
const GATEWAY_NAMESPACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
@@ -34,14 +35,6 @@ export type NodeWorkerWorkspaceExecInput = {
3435

3536
export type NodeWorkerWorkspaceExecResult = SpawnResult & { workspaceDir: string };
3637

37-
function hasExactKeys(value: Record<string, unknown>, required: string[], optional: string[] = []) {
38-
const allowed = new Set([...required, ...optional]);
39-
return (
40-
required.every((key) => Object.hasOwn(value, key)) &&
41-
Object.keys(value).every((key) => allowed.has(key))
42-
);
43-
}
44-
4538
function parseJson(raw?: string | null): unknown {
4639
if (!raw || Buffer.byteLength(raw, "utf8") > REQUEST_MAX_BYTES) {
4740
throw new Error("INVALID_REQUEST: invalid node worker workspace request");
@@ -72,7 +65,7 @@ export function parseNodeWorkerWorkspaceExecInput(
7265
const value = parseJson(raw);
7366
if (
7467
!isRecord(value) ||
75-
!hasExactKeys(
68+
!hasExactOwnKeys(
7669
value,
7770
["gatewayNamespace", "environmentId", "sessionId", "generation", "argv"],
7871
["input", "timeoutMs", "resetWorkspace", "transfer", "seed"],
@@ -139,11 +132,11 @@ export function parseNodeWorkerWorkspaceExecInput(
139132
throw new Error("INVALID_REQUEST: workspace seed key must be a SHA-256 hex digest");
140133
}
141134
const { action, key, maxAgeMs } = value.seed;
142-
if (action === "apply" && hasExactKeys(value.seed, ["action", "key"])) {
135+
if (action === "apply" && hasExactOwnKeys(value.seed, ["action", "key"])) {
143136
seed = { action, key };
144137
} else if (
145138
action === "store" &&
146-
hasExactKeys(value.seed, ["action", "key", "maxAgeMs"]) &&
139+
hasExactOwnKeys(value.seed, ["action", "key", "maxAgeMs"]) &&
147140
typeof maxAgeMs === "number" &&
148141
Number.isSafeInteger(maxAgeMs) &&
149142
maxAgeMs >= 0
@@ -170,11 +163,15 @@ export function parseNodeWorkerWorkspaceExecInput(
170163
token.length > 1_024 ||
171164
token.includes("\0") ||
172165
(direction === "download"
173-
? !hasExactKeys(value.transfer, ["direction", "token", "manifestRef"], ["attachments"]) ||
166+
? !hasExactOwnKeys(
167+
value.transfer,
168+
["direction", "token", "manifestRef"],
169+
["attachments"],
170+
) ||
174171
!validRef(manifestRef) ||
175172
(value.transfer.attachments !== undefined && value.transfer.attachments !== true)
176173
: direction === "upload"
177-
? !hasExactKeys(value.transfer, ["direction", "token", "baseManifestRef"]) ||
174+
? !hasExactOwnKeys(value.transfer, ["direction", "token", "baseManifestRef"]) ||
178175
!validRef(baseManifestRef)
179176
: true)
180177
) {
@@ -217,7 +214,7 @@ export function parseNodeWorkerWorkspaceExecResult(
217214
): NodeWorkerWorkspaceExecResult | null {
218215
if (
219216
!isRecord(value) ||
220-
!hasExactKeys(
217+
!hasExactOwnKeys(
221218
value,
222219
["workspaceDir", "stdout", "stderr", "code", "signal", "killed", "termination"],
223220
[

‎src/worker/protocol-record.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export function hasExactOwnKeys(
2+
value: object,
3+
required: readonly string[],
4+
optional: readonly string[] = [],
5+
): boolean {
6+
const allowed = new Set([...required, ...optional]);
7+
return (
8+
required.every((key) => Object.hasOwn(value, key)) &&
9+
optional.every((key) => Object.hasOwn(value, key) || !Reflect.has(value, key)) &&
10+
Object.keys(value).every((key) => allowed.has(key))
11+
);
12+
}

0 commit comments

Comments
 (0)