test(providers): verify framing through client socket boundaries

This commit is contained in:
morluto
2026-10-08 04:03:23 +08:00
parent f517a5a1d7
commit 1fd1989d34
20 changed files with 226 additions and 607 deletions
+22
View File
@@ -7,6 +7,28 @@ import {
} from "./ManagedPe.fixture.js";
describe("managed member inspection", () => {
it("keeps metadata handles distinct from calls and field accesses", () => {
const il = Buffer.from([
0xd0, 0x01, 0, 0, 0x06, 0x26, 0xd0, 0x01, 0, 0, 0x04, 0x26, 0x28, 0x01, 0,
0, 0x0a, 0x7b, 0x01, 0, 0, 0x04, 0x26, 0x2a,
]);
const bytes = buildManagedPeFixture({
ilBody: Buffer.concat([Buffer.from([(il.length << 2) | 2]), il]),
});
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.methods[0]?.body.anchors.map(({ opcode }) => opcode)).toEqual(
["ldtoken", "ldtoken", "call", "ldfld"],
);
expect(result.call_edges.map(({ opcode }) => opcode)).toEqual(["call"]);
expect(result.field_accesses.map(({ opcode }) => opcode)).toEqual([
"ldfld",
]);
});
it("inspects metadata members, signatures, CIL hashes, call edges, and field anchors", () => {
const bytes = buildManagedPeFixture();
const result = inspectManagedMembersBytes(
-27
View File
@@ -1,27 +0,0 @@
import { expect, it } from "vitest";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
} from "./ManagedPe.fixture.js";
it("retains metadata handles without reporting calls or field accesses", () => {
const il = Buffer.from([
0xd0, 0x01, 0, 0, 0x06, 0x26, 0xd0, 0x01, 0, 0, 0x04, 0x26, 0x28, 0x01, 0,
0, 0x0a, 0x7b, 0x01, 0, 0, 0x04, 0x26, 0x2a,
]);
const bytes = buildManagedPeFixture({
ilBody: Buffer.concat([Buffer.from([(il.length << 2) | 2]), il]),
});
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(
result.methods[0]?.body.anchors.map((anchor) => anchor.opcode),
).toEqual(["ldtoken", "ldtoken", "call", "ldfld"]);
expect(result.call_edges.map((edge) => edge.opcode)).toEqual(["call"]);
expect(result.field_accesses.map((access) => access.opcode)).toEqual([
"ldfld",
]);
});
-17
View File
@@ -299,23 +299,6 @@ describe("Ghidra jump-table mapping contract", () => {
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
}
});
it("keeps jump-table sources separate from case-to-target mappings", () => {
const parsed = parseGhidraFunctionResult(
"analyze_function",
ghidraFunctionDossier(),
);
if (!parsed.ok) throw parsed.error;
const boundary = functionDossierSchema.parse(parsed.value).native_api;
if (boundary?.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
const mapping = boundary.jump_tables[0]?.mappings[0];
expect(mapping).toMatchObject({
case_value: 0,
target_address: "0x401020",
});
expect(mapping).not.toHaveProperty("data_addresses");
});
});
describe("Ghidra function-analysis malformed results", () => {
-56
View File
@@ -1,56 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../config.js";
import { silentLogger } from "../logger.js";
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
import { GhidraProvider } from "./GhidraProvider.js";
describe("Ghidra provider capabilities", () => {
it("publishes admitted operation effects and resists caller mutation", () => {
const config = parseConfig({});
expect(config.ok).toBe(true);
if (!config.ok) return;
const provider = new GhidraProvider(config.value, silentLogger, {
platform: "linux",
architecture: "x64",
readText: () => undefined,
executable: () => false,
probeJava: () => undefined,
});
const capabilities = provider.capabilities();
const published = structuredClone(capabilities);
expect(capabilities.map(({ operation }) => operation).sort()).toEqual(
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].sort(),
);
for (const descriptor of capabilities) {
expect(descriptor).toMatchObject({
available: true,
reason: null,
effects: {
mutatesArtifact: descriptor.operation === "annotate_native_function",
mayShowUi: false,
mayAccessNetwork: false,
changesPermissions: false,
requiresRoot: false,
},
});
}
const baseLimitations = capabilities.find(
(item) => item.operation === "address_name",
)?.limitations;
for (const operation of ["search_procedures", "search_strings"]) {
expect(
capabilities.find((item) => item.operation === operation)?.limitations,
).toEqual(baseLimitations);
}
const first = capabilities[0];
if (first === undefined) throw new Error("Ghidra capabilities are empty");
Reflect.set(capabilities, 0, { ...first, available: false });
Reflect.set(first, "available", false);
Reflect.set(first.effects, "mutatesArtifact", true);
Reflect.set(first.limitations, 0, "forged limitation");
expect(provider.capabilities()).toEqual(published);
});
});
-66
View File
@@ -1,66 +0,0 @@
import { describe, expect, it } from "vitest";
import { GhidraResponseBuffer } from "./GhidraResponseBuffer.js";
describe("Ghidra response buffer", () => {
it("preserves fragmented lines, whitespace and a trailing partial response", () => {
const lines: string[] = [];
const buffer = new GhidraResponseBuffer({
onLine: (line) => lines.push(line),
});
buffer.push(' {"result":"雪');
buffer.push('🦊"}\r');
buffer.push('\n\n {"result":2}\n{"res');
expect(lines).toEqual(['{"result":"雪🦊"}', '{"result":2}']);
buffer.push('ult":3}');
expect(lines).toHaveLength(2);
buffer.push("\n");
expect(lines).toEqual([
'{"result":"雪🦊"}',
'{"result":2}',
'{"result":3}',
]);
});
it("drops both pending fragments and remaining lines when reset during delivery", () => {
const lines: string[] = [];
const buffer = new GhidraResponseBuffer({
onLine: (line) => {
lines.push(line);
buffer.reset();
},
});
buffer.push("discarded partial");
buffer.reset();
buffer.push("first\nsecond\npartial");
buffer.push("discarded");
buffer.reset();
buffer.push("next\n");
expect(lines).toEqual(["first", "next"]);
});
it("accepts a large response arriving in many small socket fragments", () => {
const lines: string[] = [];
const buffer = new GhidraResponseBuffer({
onLine: (line) => lines.push(line),
});
const response = `{"result":"${"x".repeat(8 * 1024 * 1024)}"}`;
for (let offset = 0; offset < response.length; offset += 4096)
buffer.push(response.slice(offset, offset + 4096));
expect(lines).toEqual([]);
buffer.push("\n");
expect(lines).toEqual([response]);
});
it("accepts complete responses larger than the former 64 MiB ceiling", () => {
const lines: string[] = [];
const buffer = new GhidraResponseBuffer({
onLine: (line) => lines.push(line),
});
const response = `{"result":"${"x".repeat(64 * 1024 * 1024 + 1)}"}`;
buffer.push(`${response}\n`);
expect(lines).toEqual([response]);
});
});
+1 -39
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { parseConfig } from "../config.js";
import { silentLogger } from "../logger.js";
import { HopperProvider, HOPPER_OPERATIONS } from "./HopperProvider.js";
import { HopperProvider } from "./HopperProvider.js";
describe("Hopper provider capabilities", () => {
it("declines DOS MZ targets with a provider-specific support reason", () => {
@@ -24,42 +24,4 @@ describe("Hopper provider capabilities", () => {
reason: expect.stringContaining("Ghidra"),
});
});
it("publishes deterministic descriptors and resists caller mutation", () => {
const config = parseConfig({});
expect(config.ok).toBe(true);
if (!config.ok) throw new Error("expected valid configuration");
const provider = new HopperProvider(config.value, silentLogger);
const capabilities = provider.capabilities();
const published = structuredClone(capabilities);
expect(capabilities.map(({ operation }) => operation)).toEqual([
...HOPPER_OPERATIONS,
]);
expect(new Set(capabilities.map(({ operation }) => operation)).size).toBe(
capabilities.length,
);
for (const descriptor of capabilities) {
expect(descriptor.provider).toEqual(provider.identity());
expect(descriptor).toMatchObject({
available: true,
reason: null,
});
}
expect(
capabilities.find(({ operation }) => operation === "list_procedures"),
).toMatchObject({ available: true });
expect(
capabilities.find(({ operation }) => operation === "set_comment"),
).toMatchObject({
effects: { mutatesArtifact: true, mayWriteFilesystem: true },
});
const first = capabilities[0];
if (first === undefined) throw new Error("Hopper capabilities are empty");
Reflect.set(capabilities, 0, { ...first, available: false });
Reflect.set(first, "available", false);
Reflect.set(first.effects, "mutatesArtifact", true);
Reflect.set(first.limitations, 0, "forged limitation");
expect(provider.capabilities()).toEqual(published);
});
});
-99
View File
@@ -1,99 +0,0 @@
import { describe, expect, it } from "vitest";
import { HopperResponseStream } from "./HopperResponseStream.js";
describe("Hopper response stream", () => {
it("preserves fragmented messages and drops partial bytes on reset", () => {
const messages: unknown[] = [];
const stream = new HopperResponseStream({
accept: (message) => {
messages.push(message);
return true;
},
hasQueued: () => false,
nextRequestId: () => 4,
abort: (message) => {
throw new Error(message);
},
});
stream.push("discarded");
stream.reset();
stream.push(' {"id":1,"result":"雪');
stream.push('🦊"}\r');
stream.push('\n\n{"id":2,"result":null}\n{"id":');
stream.push('3,"result":true}');
expect(messages).toEqual([
{ id: 1, result: "雪🦊" },
{ id: 2, result: null },
]);
stream.push("\n");
expect(messages).toEqual([
{ id: 1, result: "雪🦊" },
{ id: 2, result: null },
{ id: 3, result: true },
]);
});
it("stops delivering queued lines when validation aborts and resets the stream", () => {
const messages: unknown[] = [];
const failures: string[] = [];
const stream = new HopperResponseStream({
accept: (message) => {
messages.push(message);
return true;
},
hasQueued: () => false,
nextRequestId: () => 2,
abort: (message) => {
failures.push(message);
stream.reset();
},
});
stream.push('malformed\n{"id":1,"result":true}\n');
expect(messages).toEqual([]);
expect(failures).toHaveLength(1);
stream.push('{"id":1,"result":false}\n');
expect(messages).toEqual([{ id: 1, result: false }]);
});
it("accepts a large response arriving in many small socket fragments", () => {
const messages: unknown[] = [];
const stream = new HopperResponseStream({
accept: (message) => {
messages.push(message);
return true;
},
hasQueued: () => false,
nextRequestId: () => 2,
abort: (message) => {
throw new Error(message);
},
});
const response = `{"id":1,"result":"${"x".repeat(8 * 1024 * 1024)}"}`;
for (let offset = 0; offset < response.length; offset += 4096)
stream.push(response.slice(offset, offset + 4096));
expect(messages).toEqual([]);
stream.push("\n");
expect(messages).toEqual([JSON.parse(response)]);
});
it("accepts complete responses larger than the former 10 MiB ceiling", () => {
const messages: unknown[] = [];
const failures: string[] = [];
const stream = new HopperResponseStream({
accept: (message) => {
messages.push(message);
return true;
},
hasQueued: () => false,
nextRequestId: () => 2,
abort: (message) => failures.push(message),
});
const line = `{"id":1,"result":"${"x".repeat(10 * 1024 * 1024 + 1)}"}`;
stream.push(`${line}\n`);
expect(failures).toEqual([]);
expect(messages).toEqual([JSON.parse(line)]);
});
});
-18
View File
@@ -1,18 +0,0 @@
import { expect, it } from "vitest";
import { IDA_OPERATIONS, idaCapabilities } from "./IdaProviderCapabilities.js";
it("preserves live read-only capabilities when callers attempt to alter declarations", () => {
const original = idaCapabilities("headless", true);
Reflect.set(IDA_OPERATIONS, 0, "set_comment");
Reflect.set(IDA_OPERATIONS, IDA_OPERATIONS.length, "set_address_name");
expect(idaCapabilities("headless", true)).toEqual(original);
expect(original.every(({ cachePolicy }) => cachePolicy === "live")).toBe(
true,
);
expect(original.every(({ effects }) => !effects.mutatesArtifact)).toBe(true);
expect(
original.find(({ operation }) => operation === "procedure_callers"),
).toMatchObject({ available: false });
});
@@ -1,34 +0,0 @@
import { describe, expect, it } from "vitest";
import {
authorizeRuntimeLocation,
inspectorExclusionKey,
} from "./JavaScriptRuntimeScope.js";
describe("runtime location authorization", () => {
it("reports canonical exclusion reasons per denial case", async () => {
expect(await authorizeRuntimeLocation("not a url")).toEqual({
allowed: false,
reason: "unsupported_url",
});
expect(await authorizeRuntimeLocation("ftp://example.test/app.js")).toEqual(
{
allowed: false,
reason: "unsupported_url",
},
);
expect(
await authorizeRuntimeLocation("file:///outside-approved-scope.js"),
).toEqual({ allowed: false, reason: "not_approved" });
});
it("collapses every canonical denial onto the fixed wire bucket", () => {
expect(inspectorExclusionKey("unsupported_url")).toBe(
"unsupported_location",
);
expect(inspectorExclusionKey("not_approved")).toBe("unsupported_location");
expect(inspectorExclusionKey("disallowed_origin")).toBe(
"unsupported_location",
);
});
});
@@ -5,7 +5,6 @@ import { pathToFileURL } from "node:url";
import { afterAll, beforeAll, expect, it } from "vitest";
import { authorizeRuntimeLocation } from "./JavaScriptRuntimeScope.js";
import { finalizeInspectorCapture } from "./V8InspectorCaptureProjection.js";
import type { CaptureState } from "./V8InspectorProvider.js";
@@ -17,6 +16,48 @@ afterAll(async () => {
if (root !== undefined) await rm(root, { recursive: true, force: true });
});
const target = {
id: "target-1",
type: "node",
url: "file:///tmp/target.js",
attached: false,
webSocketUrl: "ws://127.0.0.1:9222/target-1",
location: { kind: "file" as const, file_path: "/tmp/target.js" },
};
const stateFor = (scripts: CaptureState["scripts"]): CaptureState => ({
scripts,
contexts: new Map(),
eventsObserved: scripts.length,
eventsRetained: scripts.length,
eventsDropped: 0,
metadataBytes: 0,
scriptsObserved: scripts.length,
invalidScripts: 0,
truncated: false,
truncationReasons: new Set(),
});
const finalize = (
state: CaptureState,
authorizeLocation?: Parameters<
typeof finalizeInspectorCapture
>[0]["authorizeLocation"],
) =>
finalizeInspectorCapture({
input: {
inspector_endpoint: "http://127.0.0.1:9222",
target_id: target.id,
observation_ms: 100,
},
runtime: {
product: "Node.js/v24.18.0",
protocol_version: "1.3",
v8_version: null,
},
target,
state,
...(authorizeLocation === undefined ? {} : { authorizeLocation }),
});
it("authorizes distinct Inspector locations and preserves stable deduplication", async () => {
const firstPath = join(root, "first.js");
const secondPath = join(root, "second.js");
@@ -26,8 +67,8 @@ it("authorizes distinct Inspector locations and preserves stable deduplication",
]);
const firstUrl = pathToFileURL(firstPath).href;
const secondUrl = pathToFileURL(secondPath).href;
const state: CaptureState = {
scripts: [
const result = await finalize(
stateFor([
{
rawUrl: firstUrl,
executionContextKey: "1",
@@ -56,38 +97,8 @@ it("authorizes distinct Inspector locations and preserves stable deduplication",
length: 0,
isModule: false,
},
],
contexts: new Map(),
eventsObserved: 4,
eventsRetained: 4,
eventsDropped: 0,
metadataBytes: 0,
scriptsObserved: 4,
invalidScripts: 0,
truncated: false,
truncationReasons: new Set(),
};
const result = await finalizeInspectorCapture({
input: {
inspector_endpoint: "http://127.0.0.1:9222",
target_id: "target-1",
observation_ms: 100,
},
runtime: {
product: "Node.js/v24.18.0",
protocol_version: "1.3",
v8_version: null,
},
target: {
id: "target-1",
type: "node",
url: "file:///tmp/target.js",
attached: false,
webSocketUrl: "ws://127.0.0.1:9222/target-1",
location: { kind: "file", file_path: "/tmp/target.js" },
},
state,
});
]),
);
expect(result.scripts.items.map(({ location }) => location)).toEqual(
expect.arrayContaining([
@@ -102,7 +113,7 @@ it("authorizes distinct Inspector locations and preserves stable deduplication",
});
});
it("authorizes every unique script location through a bounded worker pool", async () => {
it("authorizes each unique script location through a bounded worker pool", async () => {
const drafts = Array.from({ length: 200 }, (_, index) => ({
rawUrl: `file:///fixture/script-${String(index)}.js`,
executionContextKey: "1",
@@ -110,64 +121,29 @@ it("authorizes every unique script location through a bounded worker pool", asyn
length: 7,
isModule: false,
}));
const state: CaptureState = {
scripts: [
...drafts,
...drafts.slice(0, 1),
{
rawUrl: "ftp://example.test/unapproved.js",
executionContextKey: null,
cdpHash: null,
length: 0,
isModule: false,
},
],
contexts: new Map(),
eventsObserved: 202,
eventsRetained: 202,
eventsDropped: 0,
metadataBytes: 0,
scriptsObserved: 202,
invalidScripts: 0,
truncated: false,
truncationReasons: new Set(),
};
const state = stateFor([
...drafts,
...drafts.slice(0, 1),
{
rawUrl: "ftp://example.test/unapproved.js",
executionContextKey: null,
cdpHash: null,
length: 0,
isModule: false,
},
]);
const activeUrls = new Set<string>();
const authorizedUrls = new Set<string>();
let maximumActive = 0;
const result = await finalizeInspectorCapture({
input: {
inspector_endpoint: "http://127.0.0.1:9222",
target_id: "target-1",
observation_ms: 100,
},
runtime: {
product: "Node.js/v24.18.0",
protocol_version: "1.3",
v8_version: null,
},
target: {
id: "target-1",
type: "node",
url: "file:///tmp/target.js",
attached: false,
webSocketUrl: "ws://127.0.0.1:9222/target-1",
location: { kind: "file", file_path: "/tmp/target.js" },
},
state,
authorizeLocation: async (rawUrl) => {
activeUrls.add(rawUrl);
authorizedUrls.add(rawUrl);
maximumActive = Math.max(maximumActive, activeUrls.size);
await new Promise((resolve) => setTimeout(resolve, 1));
activeUrls.delete(rawUrl);
return rawUrl.startsWith("ftp:")
? { allowed: false, reason: "unsupported_url" }
: {
allowed: true,
location: { kind: "file", file_path: rawUrl },
};
},
const result = await finalize(state, async (rawUrl) => {
activeUrls.add(rawUrl);
authorizedUrls.add(rawUrl);
maximumActive = Math.max(maximumActive, activeUrls.size);
await new Promise((resolve) => setTimeout(resolve, 1));
activeUrls.delete(rawUrl);
return rawUrl.startsWith("ftp:")
? { allowed: false, reason: "unsupported_url" }
: { allowed: true, location: { kind: "file", file_path: rawUrl } };
});
expect(maximumActive).toBeGreaterThan(1);
@@ -190,20 +166,8 @@ it("waits for active authorization workers to settle before returning a failure"
length: 0,
isModule: false,
}));
const state: CaptureState = {
scripts,
contexts: new Map(),
eventsObserved: scripts.length,
eventsRetained: scripts.length,
eventsDropped: 0,
metadataBytes: 0,
scriptsObserved: scripts.length,
invalidScripts: 0,
truncated: false,
truncationReasons: new Set(),
};
const startedUrls: string[] = [];
const pendingAuthorizations = new Map<
const pending = new Map<
string,
{ readonly resolve: () => void; readonly reject: (error: Error) => void }
>();
@@ -212,47 +176,27 @@ it("waits for active authorization workers to settle before returning a failure"
let maximumActive = 0;
let failureInjected = false;
const finalization = finalizeInspectorCapture({
input: {
inspector_endpoint: "http://127.0.0.1:9222",
target_id: "target-1",
observation_ms: 100,
},
runtime: {
product: "Node.js/v24.18.0",
protocol_version: "1.3",
v8_version: null,
},
target: {
id: "target-1",
type: "node",
url: "file:///tmp/target.js",
attached: false,
webSocketUrl: "ws://127.0.0.1:9222/target-1",
location: { kind: "file", file_path: "/tmp/target.js" },
},
state,
authorizeLocation: async (rawUrl) => {
startedUrls.push(rawUrl);
if (failureInjected)
return { allowed: true, location: { kind: "file", file_path: rawUrl } };
active += 1;
maximumActive = Math.max(maximumActive, active);
return new Promise<Awaited<ReturnType<typeof authorizeRuntimeLocation>>>(
(resolve, reject) => {
pendingAuthorizations.set(rawUrl, {
resolve: () =>
resolve({
allowed: true,
location: { kind: "file", file_path: rawUrl },
}),
reject,
});
},
).finally(() => {
active -= 1;
const finalization = finalize(stateFor(scripts), async (rawUrl) => {
startedUrls.push(rawUrl);
if (failureInjected)
return { allowed: true, location: { kind: "file", file_path: rawUrl } };
active += 1;
maximumActive = Math.max(maximumActive, active);
return new Promise<{
readonly allowed: true;
readonly location: { readonly kind: "file"; readonly file_path: string };
}>((resolve, reject) => {
pending.set(rawUrl, {
resolve: () =>
resolve({
allowed: true,
location: { kind: "file", file_path: rawUrl },
}),
reject,
});
},
}).finally(() => {
active -= 1;
});
});
const initialStarted = new Set(startedUrls);
expect(initialStarted.size).toBeGreaterThan(1);
@@ -261,11 +205,11 @@ it("waits for active authorization workers to settle before returning a failure"
if (failingUrl === undefined)
throw new Error("Expected at least one active authorization");
failureInjected = true;
pendingAuthorizations.get(failingUrl)?.reject(failure);
pending.get(failingUrl)?.reject(failure);
await Promise.resolve();
expect(new Set(startedUrls)).toEqual(initialStarted);
for (const [rawUrl, pending] of pendingAuthorizations)
if (rawUrl !== failingUrl) pending.resolve();
for (const [rawUrl, request] of pending)
if (rawUrl !== failingUrl) request.resolve();
await expect(finalization).rejects.toBe(failure);
expect(new Set(startedUrls)).toEqual(initialStarted);
expect(active).toBe(0);
-1
View File
@@ -62,7 +62,6 @@ describe("native UI screenshot validation", () => {
{ base64: "%%%=" },
{ base64: Buffer.from("not a PNG").toString("base64") },
{ width: 2 },
{ sha256: "0".repeat(64) },
])(
"rejects invalid screenshot field variants from the helper",
async (change) => {
-36
View File
@@ -1,36 +0,0 @@
import { expect, it } from "vitest";
import { parseDemangledSymbols } from "./demangle.js";
it.each(["ordinary name ", "ordinary\t", " "])(
"preserves unchanged final symbol text: %j",
(input) => {
expect(parseDemangledSymbols([input], `${input}\n`)).toEqual([
{ input, output: input, status: "unchanged" },
]);
},
);
it.each(["carriage\r", "\r", "mid\rdle"])(
"keeps carriage returns that belong to the symbol: %j",
(input) => {
expect(parseDemangledSymbols([input], `${input}\n`)).toEqual([
{ input, output: input, status: "unchanged" },
]);
},
);
it("removes only the line terminator and preserves mixed output ordering", () => {
expect(
parseDemangledSymbols(
["$s4main5helloyyF", "plain "],
"main.hello() -> ()\nplain \n",
),
).toEqual([
{
input: "$s4main5helloyyF",
output: "main.hello() -> ()",
status: "demangled",
},
{ input: "plain ", output: "plain ", status: "unchanged" },
]);
});