build: verify resolved module boundaries (#862)

This commit is contained in:
N0zoM1z0
2026-10-07 13:02:28 +08:00
committed by GitHub
parent 3b92a2bced
commit 3427593daf
10 changed files with 365 additions and 141 deletions
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { listBrowserTargetsInputSchema } from "../../../src/domain/browserObservation.js";
import { browserCaptureComparisonInputSchema } from "../../../src/domain/browserCaptureComparison.js";
import { compareWebScreenshotsInputSchema } from "../../../src/domain/webScreenshot.js";
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import {
compareWebCaptureEvidence,
compareWebScreenshotEvidence,
listBrowserTargets,
} from "../../../src/application/BrowserObservationService.js";
describe("browser observation service prerequisites", () => {
it("reports a missing provider without requiring a permission grant", async () => {
const endpoint = "http://127.0.0.1:9222";
const origin = "http://[::1]:3000";
const result = await listBrowserTargets(
undefined,
listBrowserTargetsInputSchema.parse({
cdp_endpoint: endpoint,
allowed_origins: [origin],
}),
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
},
});
});
it("compares supplied scenarios and PNG artifacts without a CDP endpoint", async () => {
const browser = new CdpBrowserProvider();
const captures = await compareWebCaptureEvidence(
browser,
browserCaptureComparisonInputSchema.parse(
example("compare_web_captures"),
),
);
const screenshots = await compareWebScreenshotEvidence(
browser,
compareWebScreenshotsInputSchema.parse(
example("compare_web_screenshots"),
),
);
for (const result of [captures, screenshots]) {
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.parameters).not.toHaveProperty("cdp_endpoint");
}
});
});
const example = (name: string) => {
const input = BROWSER_TOOL_CONTRACTS.find((tool) => tool.name === name)
?.examples[0]?.input;
if (input === undefined) throw new Error(`Missing example for ${name}`);
return input;
};
@@ -0,0 +1,264 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import {
compareManagedMembers,
managedMemberComparisonResultSchema,
} from "../../../../src/domain/managedMemberComparison.js";
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
} from "../../../../src/dotnet/ManagedPe.fixture.js";
describe("managed member comparison", () => {
it("remaps renamed methods by exact CIL/signature without using names", () => {
const leftBytes = buildManagedPeFixture();
const rightBytes = buildManagedPeFixture({
mvid: Buffer.from("00112233445566778899aabbccddeefe", "hex"),
typeName: "A",
typeNamespace: "X",
methodName: "b",
fieldName: "c",
});
const left = inspect(leftBytes, "/tmp/left.dll");
const right = inspect(rightBytes, "/tmp/right.dll");
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
);
expect(result.algorithm.name_matching).toBe("exact-signature-fallback");
expect(result.left.mvid).toBe("00112233-4455-6677-8899-aabbccddeeff");
expect(result.right.mvid).toBe("33221100-5544-7766-8899-aabbccddeefe");
expect(result.matching.exact_il_signature).toBe(1);
expect(result.methods).toEqual([
expect.objectContaining({
status: "unchanged",
left: expect.objectContaining({ token: "0x06000001", name: "Main" }),
right: expect.objectContaining({ token: "0x06000001", name: "b" }),
match: expect.objectContaining({
status: "matched",
basis: "exact-il-signature",
confidence: "exact",
}),
dimensions: [],
}),
]);
expect(result.limitations).toContain(
"Methods pair by exact CIL/signature, then declared type, name, and signature, then structural shape; names alone are never a matching basis.",
);
expect(
managedMemberComparisonResultSchema.safeParse({
...result,
limitations: Array.from({ length: 101 }, () => "x".repeat(4_097)),
}).success,
).toBe(true);
});
it("compares changed CIL after pairing by exact signature", () => {
const leftBytes = buildManagedPeFixture();
const rightBytes = buildManagedPeFixture({
ilBody: Buffer.from([
0x32, 0x02, 0x7b, 0x02, 0x00, 0x00, 0x04, 0x28, 0x02, 0x00, 0x00, 0x0a,
0x2a,
]),
});
const left = inspect(leftBytes, "/tmp/left.dll");
const right = inspect(rightBytes, "/tmp/right.dll");
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
);
expect(result.matching.exact_il_signature).toBe(0);
expect(result.matching.exact_signature).toBe(1);
expect(result.methods[0]).toMatchObject({
status: "changed",
match: { status: "matched", basis: "exact-signature" },
dimensions: ["cil"],
});
});
it("rejects member states that disagree with their observed sides or match", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
);
const method = result.methods[0];
expect(method).toBeDefined();
if (method === undefined) return;
expect(
managedMemberComparisonResultSchema.safeParse({
...result,
methods: [{ ...method, status: "unchanged", right: null }],
}).success,
).toBe(false);
expect(
managedMemberComparisonResultSchema.safeParse({
...result,
methods: [
{
...method,
match: {
...method.match,
basis: "none",
confidence: "unknown",
},
},
],
}).success,
).toBe(false);
});
});
describe("managed member comparison uncertainty", () => {
it("does not infer a structural method match from undecoded signature fields", () => {
const left = inspect(
buildManagedPeFixture({ methodSignature: Buffer.from([0xff]) }),
"/tmp/unknown-left.dll",
);
const right = inspect(
buildManagedPeFixture({ methodSignature: Buffer.from([0xfe]) }),
"/tmp/unknown-right.dll",
);
expect(left.result.methods[0]?.signature.parse_status).not.toBe("decoded");
expect(right.result.methods[0]?.signature.parse_status).not.toBe("decoded");
const result = compareManagedMembers(
{
evidenceId: left.evidenceId,
result: {
...left.result,
coverage: { ...left.result.coverage, state: "partial" },
},
},
{
evidenceId: right.evidenceId,
result: {
...right.result,
coverage: { ...right.result.coverage, state: "partial" },
},
},
);
expect(result.matching.structural_method_shape).toBe(0);
expect(result.methods).toHaveLength(2);
expect(
result.methods.every(
({ status, match }) =>
status === "unknown" && match.status === "unmatched",
),
).toBe(true);
});
it("keeps unmatched members unknown when opposite metadata is incomplete", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-partial.dll");
const right = inspect(buildManagedPeFixture(), "/tmp/right-partial.dll");
const leftPartial = {
...left.result,
fields: [],
coverage: { ...left.result.coverage, state: "partial" as const },
};
const rightPartial = {
...right.result,
methods: [],
coverage: { ...right.result.coverage, state: "partial" as const },
};
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: leftPartial },
{ evidenceId: right.evidenceId, result: rightPartial },
);
expect(result.summary).toMatchObject({
added: 0,
removed: 0,
unknown: 2,
});
expect(result.methods[0]).toMatchObject({
status: "unknown",
left: { token: "0x06000001" },
right: null,
limitations: [
expect.stringContaining("unknown-within-incomplete-metadata"),
],
});
expect(result.fields[0]).toMatchObject({
status: "unknown",
left: null,
right: { token: "0x04000001" },
limitations: [
expect.stringContaining("unknown-within-incomplete-metadata"),
],
});
expect(result.coverage).toEqual({
status: "partial",
left_status: "partial",
right_status: "partial",
});
});
it("does not guess ambiguous field signature matches", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
const leftField = left.result.fields[0];
expect(leftField).toBeDefined();
if (leftField === undefined) return;
const duplicatedLeft = {
...left.result,
fields: [
leftField,
{
...leftField,
token: "0x04000002",
name: "other",
},
],
};
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
const rightField = right.result.fields[0];
expect(rightField).toBeDefined();
if (rightField === undefined) return;
const duplicatedRight = {
...right.result,
fields: [
rightField,
{
...rightField,
token: "0x04000002",
name: "renamed",
},
],
};
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: duplicatedLeft },
{ evidenceId: right.evidenceId, result: duplicatedRight },
);
expect(result.matching.ambiguous).toBe(1);
expect(result.fields).toEqual([
expect.objectContaining({
status: "unknown",
match: expect.objectContaining({
status: "ambiguous",
basis: "field-signature",
candidate_left_tokens: ["0x04000001", "0x04000002"],
candidate_right_tokens: ["0x04000001", "0x04000002"],
}),
}),
]);
});
});
const inspect = (bytes: Buffer, path: string) => {
const target = managedPeFixtureTarget(bytes, path);
const result = inspectManagedMembersBytes(bytes, target);
return {
result,
evidenceId: `ev_${hash(Buffer.from(path))}`,
};
};
const hash = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
@@ -0,0 +1,124 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { compareManagedMembers } from "../../../../src/domain/managedMemberComparison.js";
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
} from "../../../../src/dotnet/ManagedPe.fixture.js";
const inspect = (bytes: Buffer, path: string) => {
const target = managedPeFixtureTarget(bytes, path);
const result = inspectManagedMembersBytes(bytes, target);
return { result, evidenceId: `ev_${hash(Buffer.from(path))}` };
};
const hash = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
describe("managed member partial body comparison", () => {
it("keeps unavailable body facets unknown while retaining an observed signature change", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-body-partial.dll");
const right = inspect(
buildManagedPeFixture(),
"/tmp/right-body-partial.dll",
);
const leftMethod = left.result.methods[0];
const rightMethod = right.result.methods[0];
expect(leftMethod).toBeDefined();
expect(rightMethod).toBeDefined();
if (leftMethod === undefined || rightMethod === undefined) return;
const leftResult = {
...left.result,
methods: [
{
...leftMethod,
body: {
...leftMethod.body,
status: "partial" as const,
normalized_il_sha256: null,
},
},
],
};
const rightResult = {
...right.result,
methods: [
{
...rightMethod,
body: {
...rightMethod.body,
status: "partial" as const,
normalized_il_sha256: null,
opcode_counts: { nop: 1 },
},
},
],
};
const partial = compareManagedMembers(
{ evidenceId: left.evidenceId, result: leftResult },
{ evidenceId: right.evidenceId, result: rightResult },
);
expect(partial.methods[0]).toMatchObject({
status: "unknown",
dimensions: ["body-coverage"],
});
const rightSignatureChanged = {
...right.result,
methods: [
{
...rightMethod,
signature: {
...rightMethod.signature,
raw_sha256: "f".repeat(64),
},
},
],
};
const signatureChanged = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{
evidenceId: right.evidenceId,
result: rightSignatureChanged,
},
);
expect(signatureChanged.methods[0]).toMatchObject({
status: "changed",
dimensions: ["signature"],
});
const bothAbsent = compareManagedMembers(
{
evidenceId: left.evidenceId,
result: {
...left.result,
methods: [
{
...leftMethod,
body: { ...leftMethod.body, status: "absent" as const },
},
],
},
},
{
evidenceId: right.evidenceId,
result: {
...right.result,
methods: [
{
...rightMethod,
body: { ...rightMethod.body, status: "absent" as const },
},
],
},
},
);
expect(bothAbsent.methods[0]).toMatchObject({
status: "unchanged",
dimensions: [],
});
});
});
+160 -4
View File
@@ -1,10 +1,16 @@
import { spawnSync } from "node:child_process";
import { copyFile, mkdir, writeFile } from "node:fs/promises";
import { execFile, spawnSync } from "node:child_process";
import { copyFile, mkdir, rename, writeFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { inspectModuleBoundaries } from "../../scripts/lib/module-boundaries.mjs";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const verifier = resolve("scripts/verify-module-boundaries.mjs");
describe("incremental module import boundaries", () => {
it.each([
["src/domain/probe.ts", "../application/Workflow.js", false],
@@ -32,16 +38,166 @@ describe("incremental module import boundaries", () => {
["src/composition/probe.ts", "../ghidra/Provider.js", true],
["src/composition/probe.ts", "../android/JadxProvider.js", true],
["src/composition/probe.ts", "../firmware/FirmwareProvider.js", true],
["src/domain/android/probe.ts", "./types.js", true],
["src/domain/javascript/probe.ts", "./types.js", true],
["src/domain/firmware/probe.ts", "../android/types.js", true],
["src/domain/android/probe.ts", "../../android/JadxProvider.js", false],
["src/application/android/probe.ts", "../../domain/android/types.js", true],
[
"src/application/android/probe.ts",
"../../android/JadxProvider.js",
false,
],
["src/application/runtime.ts", "../android/JadxProvider.js", true],
[
"src/application/android/runtime.ts",
"../../android/JadxProvider.js",
false,
],
[
"src/application/probe.test.ts",
"../browser/CdpBrowserProvider.js",
false,
],
["src/domain/probe.test.ts", "../dotnet/ManagedMemberInspector.js", false],
["src/server/probe.ts", "../composition/android.js", true],
["src/application/probe.ts", "../browser/CdpCaptureValues.js", true],
])("checks %s importing %s", async (file, dependency, allowed) => {
const temporary = await createTestTempDirectory("rea-module-boundary-");
const config = join(temporary, ".oxlintrc.json");
await copyFile(resolve(".oxlintrc.json"), config);
const fixture = join(temporary, file);
await mkdir(dirname(fixture), { recursive: true });
await writeFile(
fixture,
`import { value } from ${JSON.stringify(dependency)}; export { value };\n`,
);
const result = spawnSync(process.execPath, [verifier, file], {
cwd: temporary,
encoding: "utf8",
});
if (result.error !== undefined) throw result.error;
expect(result.status).toBe(allowed ? 0 : 1);
if (!allowed) expect(result.stderr).toContain("resolves to src/");
});
});
describe("module import syntax and source discovery", () => {
it.each([
'import { value } from "../android/Provider.js";',
'import type { Value } from "../android/Provider.js";',
'export { value } from "../android/Provider.js";',
'export * from "../android/Provider.js";',
'type Value = import("../android/Provider.js").Value;',
'const loaded = import("../android/Provider.js");',
"const loaded = import(`../android/Provider.js`);",
'import provider = require("../android/Provider.js");',
'import { value } from "../domain/../android/Provider.js";',
'const loaded = import("../%61ndroid/Provider.js?view=one#fragment");',
])("checks the resolved owner in %s", (source) => {
expect(
inspectModuleBoundaries("src/domain/probe.ts", source, process.cwd()),
).toEqual([
expect.objectContaining({
target: "src/android/Provider.js",
boundary: "pure-layer",
}),
]);
});
it("ignores imports mentioned in comments and analyst fixture strings", () => {
expect(
inspectModuleBoundaries(
"src/domain/probe.ts",
'// import("../android/Provider.js");\nconst text = \'import("../android/Provider.js")\';',
process.cwd(),
),
).toEqual([]);
});
it.each(["absolute", "file-url"])("resolves %s source imports", (kind) => {
const target = resolve("src/android/Provider.js");
const specifier = kind === "file-url" ? pathToFileURL(target).href : target;
expect(
inspectModuleBoundaries(
"src/domain/probe.ts",
`export * from ${JSON.stringify(specifier)};`,
process.cwd(),
),
).toEqual([
expect.objectContaining({
target: "src/android/Provider.js",
boundary: "pure-layer",
}),
]);
});
it("rejects unsupported selected arguments instead of checking zero files", () => {
const result = spawnSync(process.execPath, [verifier, "--unknown"], {
encoding: "utf8",
});
if (result.error !== undefined) throw result.error;
expect(result.status).toBe(1);
expect(result.stderr).toContain("Expected an exact TypeScript source file");
});
it("reports malformed source with the selected file and parsing reason", async () => {
const temporary = await createTestTempDirectory("rea-module-syntax-");
await mkdir(join(temporary, "src", "domain"), { recursive: true });
await writeFile(join(temporary, "src/domain/probe.ts"), "import {");
const result = spawnSync(
process.execPath,
[verifier, "src/domain/probe.ts"],
{
cwd: temporary,
encoding: "utf8",
},
);
if (result.error !== undefined) throw result.error;
expect(result.status).toBe(1);
expect(result.stderr).toContain("Could not inspect src/domain/probe.ts");
expect(result.stderr).toContain("Unexpected token");
});
it("checks untracked source files and ignores cached paths removed during a move", async () => {
const temporary = await createTestTempDirectory("rea-module-discovery-");
await mkdir(join(temporary, "src", "domain"), { recursive: true });
await writeFile(join(temporary, "src/domain/old.ts"), "export const x=1;");
await execute("git", ["init", "--quiet"], { cwd: temporary });
await execute("git", ["add", "--", "src"], { cwd: temporary });
await rename(
join(temporary, "src/domain/old.ts"),
join(temporary, "src/domain/new.ts"),
);
await writeFile(
join(temporary, "src/domain/probe.ts"),
'export * from "../android/Provider.js";',
);
const result = spawnSync(process.execPath, [verifier], {
cwd: temporary,
encoding: "utf8",
});
if (result.error !== undefined) throw result.error;
expect(result.status).toBe(1);
expect(result.stderr).toContain("src/domain/probe.ts:1: pure-layer");
expect(result.stderr).not.toContain("old.ts");
});
});
describe("test lane import boundaries", () => {
it.each([
["src/application/probe.test.ts", "../server/createServer.js", false],
["tests/composition/probe.test.ts", "node:child_process", false],
["tests/composition/probe.test.ts", "node:net", false],
["tests/composition/probe.test.ts", "playwright", false],
["tests/composition/probe.test.ts", "../../src/domain/result.js", true],
])("checks %s importing %s", async (file, dependency, allowed) => {
const temporary = await createTestTempDirectory("rea-test-lane-");
const config = join(temporary, ".oxlintrc.json");
await copyFile(resolve(".oxlintrc.json"), config);
await mkdir(dirname(join(temporary, file)), { recursive: true });
await writeFile(
join(temporary, file),
`import { value } from ${JSON.stringify(dependency)}; export { value };\n`,
);
const result = spawnSync(
process.execPath,
[