fix(artifacts): preserve integrity evidence across workflows and integrate main

This commit is contained in:
morluto
2026-10-08 23:16:16 +08:00
781 changed files with 55034 additions and 14106 deletions
+51
View File
@@ -108,6 +108,57 @@ describe("browser CLI parity", () => {
alignment: { status: "aligned", aligned_steps: 2 },
},
});
const intentionalPolicy = await runCli(
[
"compare-web-captures",
JSON.stringify(scenarioCapture),
JSON.stringify(scenarioCapture),
"--normalization-json",
JSON.stringify({
rules: [
{
rule_id: "domain",
artifacts: ["url"],
match: "app.example.test",
replacement: "normalized.test",
},
],
}),
"--json",
],
process.env,
);
expect(intentionalPolicy).toMatchObject({
normalized_result: {
normalization: { rules: [{ rule_id: "domain" }] },
},
});
const malformedPolicy = await runCli(
[
"compare-web-captures",
JSON.stringify(scenarioCapture),
JSON.stringify(scenarioCapture),
"--normalization-json",
"{invalid-policy",
"--json",
],
process.env,
);
expect(malformedPolicy).toMatchObject({
error: "Browser observation failed",
code: "invalid_request",
details: {
operation: "compare_web_captures",
issues: [
{
path: ["normalization"],
reason: "invalid_format",
expected: "JSON",
},
],
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
@@ -0,0 +1,113 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { afterEach, expect, it } from "vitest";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "../../fixtures/fakeCdpBrowser.js";
const execute = promisify(execFile);
const browsers: FakeCdpBrowser[] = [];
afterEach(async () => {
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
});
it("reports missing JSON shapes only when body shapes are selected", async () => {
const browser = await startFakeCdpBrowser({
malformedRedirectResponse: true,
redirectResponseEnvelope: null,
});
browsers.push(browser);
const commonArgs = [
"inspect-web-page",
browser.endpoint,
"allowed-page",
"--allowed-origins",
browser.allowedOrigin,
"--observation-ms",
"0",
];
const selected = normalizedResult(
await runCli([...commonArgs, "--include-json-body-shapes", "--json"]),
);
expect(selected).toMatchObject({
network: {
requests: [
{
body_shapes: {
status: "partial",
request: expect.any(Object),
response: null,
},
},
],
},
completeness: {
unavailable_sections: expect.arrayContaining([
"network_requests",
"json_body_shapes",
]),
excluded: expect.arrayContaining([
{
section: "json_body_shapes",
reason: "invalid_protocol_value",
count: expect.any(Number),
},
]),
},
});
const defaulted = normalizedResult(await runCli([...commonArgs, "--json"]));
expect(defaulted).toMatchObject({
network: {
requests: [
{
body_shapes: {
status: "not_approved",
request: null,
response: null,
},
},
],
},
});
expect(defaulted.completeness).toMatchObject({
unavailable_sections: expect.not.arrayContaining(["json_body_shapes"]),
});
});
const runCli = async (arguments_: readonly string[]): Promise<unknown> => {
try {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: process.cwd(),
env: process.env,
maxBuffer: 16 * 1_024 * 1_024,
},
);
return JSON.parse(stdout);
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"stdout" in cause &&
typeof cause.stdout === "string"
)
return JSON.parse(cause.stdout);
throw cause;
}
};
const normalizedResult = (value: unknown): Record<string, unknown> => {
if (!isRecord(value) || !isRecord(value.normalized_result))
throw new TypeError("Missing CLI normalized result");
return value.normalized_result;
};
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
+69 -3
View File
@@ -57,7 +57,9 @@ describe("CLI output argument and sanitization boundary", () => {
validateCliOutputArguments(["providers", "--token-count", "--json"]),
).toEqual({ ok: true });
});
});
describe("CLI output valued-flag parsing", () => {
workspaceCliTest(
"preserves complete JSON errors when native builtin flags follow unusual arguments",
async ({ cli }) => {
@@ -92,6 +94,70 @@ describe("CLI output argument and sanitization boundary", () => {
CLI_INTEGRATION_TIMEOUT_MS,
);
workspaceCliTest(
"does not treat empty or equals-style output values as active builtins",
async ({ cli }) => {
for (const arguments_ of [
["capabilities", "--json", "--format", ""],
["capabilities", "--json", "--filter-output", ""],
["capabilities", "--json", "--token-limit", ""],
["capabilities", "--json", "--token-limit=5"],
]) {
const result = await cli.run({ arguments: arguments_ });
expect(result.exitCode).toBe(1);
expect(result.json).toBeDefined();
expect(result.stdout).not.toContain("[truncated:");
expect(JSON.stringify(result.json)).not.toContain(
"UNSUPPORTED_OUTPUT_COMBINATION",
);
}
const validTokenWindow = await cli.run({
arguments: ["capabilities", "--json", "--token-limit", "5"],
});
expect(validTokenWindow.exitCode).toBe(1);
expect(validTokenWindow.json).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
});
const emptyFormatWithTokenWindow = await cli.run({
arguments: [
"capabilities",
"--json",
"--format",
"",
"--token-limit",
"5",
],
});
expect(emptyFormatWithTokenWindow.exitCode).toBe(1);
expect(emptyFormatWithTokenWindow.stdout).not.toContain("[truncated:");
expect(emptyFormatWithTokenWindow.json).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
});
for (const arguments_ of [
["capabilities", "--json", "--token-limit", "not-a-number"],
[
"capabilities",
"--format",
"unsupported-format",
"--json",
"--token-limit",
"5",
],
]) {
const result = await cli.run({ arguments: arguments_ });
expect(result.exitCode).toBe(1);
expect(result.stdout).not.toContain("UNSUPPORTED_OUTPUT_COMBINATION");
expect(result.stdout).not.toContain("[truncated:");
}
},
CLI_INTEGRATION_TIMEOUT_MS,
);
});
describe("CLI output argument and sanitization boundary", () => {
it("preserves normal output and sanitizes text and JSON validation errors", () => {
expect(sanitizeCliOutput("result: ok\n")).toBe("result: ok\n");
expect(sanitizeCliOutput("result: VALIDATION_ERROR\n")).toBe(
@@ -179,7 +245,7 @@ describe("compiled CLI output boundary", () => {
expect(result).toMatchObject({
exitCode: 0,
stdout: "{}\n",
stderr: "",
stderr: expect.stringContaining('"rea_progress":'),
json: {},
});
const nested = await cli.run({
@@ -194,7 +260,7 @@ describe("compiled CLI output boundary", () => {
});
expect(nested).toMatchObject({
exitCode: 0,
stderr: "",
stderr: expect.stringContaining('"rea_progress":'),
json: { normalized_result: {} },
});
const selected = await cli.run({
@@ -209,7 +275,7 @@ describe("compiled CLI output boundary", () => {
});
expect(selected).toMatchObject({
exitCode: 0,
stderr: "",
stderr: expect.stringContaining('"rea_progress":'),
json: {
normalized_result: {
summary: expect.objectContaining({ browser_windows: 0 }),
+5
View File
@@ -11,6 +11,7 @@ describe("executable dispatcher", () => {
async ({ processes, workspace }) => {
const scripts = await workspace.mkdir("scripts");
await workspace.mkdir("dist");
await workspace.mkdir("dist/cli");
await Promise.all([
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
workspace.write(
@@ -29,6 +30,10 @@ describe("executable dispatcher", () => {
"dist/cliOutput.js",
"export const sanitizeCliOutput = (output) => output; export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => ''; export const renderEmptyFilteredCliOutput = () => undefined;\n",
),
workspace.write(
"dist/cli/streamedJsonOutput.js",
"export const createStreamedCliJsonOutput = () => undefined;\n",
),
workspace.write(
"dist/mcpDoctor.js",
'export const runProductionMcpDoctorCli = (args) => Promise.resolve({ output: JSON.stringify({ adapter: "mcp-doctor", args }), exitCode: 0 });\n',
@@ -0,0 +1,244 @@
import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { describe, expect } from "vitest";
import {
FILE_TYPE,
LC,
dylibCommand,
machoImage,
rpathCommand,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const ENVIRONMENT = { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" };
const writeFiles = async (
root: string,
files: Readonly<Record<string, string | Uint8Array>>,
): Promise<void> => {
for (const [path, content] of Object.entries(files)) {
await mkdir(dirname(join(root, path)), { recursive: true });
await writeFile(join(root, path), content);
}
};
const fixtureApp = async (): Promise<string> => {
const app = join(
await createTestTempDirectory("rea-dylib-cli-"),
"Fixture.app",
);
await writeFiles(app, {
"Contents/Info.plist":
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
"Contents/MacOS/App": machoImage({
commands: [
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
dylibCommand(LC.LOAD_WEAK_DYLIB, "@rpath/libgone.dylib"),
],
}),
"Contents/Frameworks/libcore.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [dylibCommand(LC.ID_DYLIB, "@rpath/libcore.dylib")],
}),
"Contents/Helpers/tool": machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libnone.dylib")],
}),
});
return app;
};
const withBrokenHelper = async (app: string): Promise<void> => {
const broken = machoImage({ commands: [rpathCommand("x")] });
// cmdsize 0 makes the command table unreadable.
new DataView(broken.buffer).setUint32(32 + 4, 0, true);
await writeFiles(app, { "Contents/Helpers/broken": broken });
};
describe("trace-dylib-resolution CLI", () => {
cliTest("traces every executable root of an app bundle", async ({ cli }) => {
const app = await fixtureApp();
const result = await cli.run({
arguments: ["trace-dylib-resolution", app, "--json"],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
(result.json as { normalized_result: unknown }).normalized_result,
);
expect(trace.root_path).toBe(app);
expect(trace.roots.map(({ image }) => image)).toEqual([
"Contents/Helpers/tool",
"Contents/MacOS/App",
]);
expect(
trace.edges.map(({ loader, install_name: name, resolution }) => [
loader,
name,
resolution.status,
resolution.image,
]),
).toEqual([
[
"Contents/Helpers/tool",
"@loader_path/libnone.dylib",
"unresolved",
null,
],
[
"Contents/MacOS/App",
"@rpath/libcore.dylib",
"resolved",
"Contents/Frameworks/libcore.dylib",
],
["Contents/MacOS/App", "@rpath/libgone.dylib", "unresolved", null],
]);
expect(trace.findings.map(({ kind }) => kind)).toEqual([
"required-load-unresolved",
"weak-load-unresolved",
]);
expect(
trace.images.every(({ sha256 }) => /^[0-9a-f]{64}$/u.test(sha256)),
).toBe(true);
});
cliTest(
"narrows roots and architecture, and rejects escaping roots",
async ({ cli }) => {
const app = await fixtureApp();
const narrowed = await cli.run({
arguments: [
"trace-dylib-resolution",
app,
"--root",
"Contents/MacOS/App",
"--architecture",
"arm64",
"--json",
],
environment: ENVIRONMENT,
});
expect(narrowed.exitCode).toBe(0);
expect(
(narrowed.json as { normalized_result: { roots: unknown } })
.normalized_result.roots,
).toEqual([{ image: "Contents/MacOS/App", architecture: "arm64" }]);
// A root below a symlinked directory that points outside the bundle.
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
for (const root of [
"../outside",
"Contents/Info.plist",
"Contents/Linked/Tool",
]) {
const rejected = await cli.run({
arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
environment: ENVIRONMENT,
});
expect(rejected.exitCode).toBe(1);
expect(rejected.json).toMatchObject({ error: "Analysis failed" });
}
},
);
cliTest(
"resolves a standalone Mach-O against its own directory",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-dylib-standalone-");
await writeFiles(directory, {
tool: machoImage({
commands: [
dylibCommand(LC.LOAD_DYLIB, "@loader_path/lib/libhelper.dylib"),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/../escape.dylib"),
],
}),
"lib/libhelper.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
"unrelated.txt": "not traversed",
});
const result = await cli.run({
arguments: [
"trace-dylib-resolution",
join(directory, "tool"),
"--json",
],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
(result.json as { normalized_result: unknown }).normalized_result,
);
expect(trace.roots).toEqual([{ image: "tool", architecture: "arm64" }]);
expect(trace.edges.map(({ resolution }) => resolution)).toEqual([
{ status: "resolved", image: "lib/libhelper.dylib" },
{ status: "undetermined", image: null },
]);
},
);
cliTest(
"reports unparsed Mach-O files found while enumerating roots",
async ({ cli }) => {
const app = await fixtureApp();
await withBrokenHelper(app);
const result = await cli.run({
arguments: ["trace-dylib-resolution", app, "--json"],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
(result.json as { normalized_result: unknown }).normalized_result,
);
expect(trace.coverage).toMatchObject({
status: "partial",
unparsed_images: ["Contents/Helpers/broken"],
});
},
);
});
describe.skipIf(process.getuid?.() === 0)(
"trace-dylib-resolution permissions",
() => {
cliTest(
"reports an unreadable dependency as a permission failure",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-dylib-denied-");
await writeFiles(directory, {
tool: machoImage({
commands: [
dylibCommand(LC.LOAD_DYLIB, "@loader_path/libsecret.dylib"),
],
}),
"libsecret.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
});
await chmod(join(directory, "libsecret.dylib"), 0o000);
try {
const result = await cli.run({
arguments: [
"trace-dylib-resolution",
join(directory, "tool"),
"--json",
],
environment: ENVIRONMENT,
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
details: {
reason: "unavailable",
detail: expect.stringContaining(
"Permission denied (EACCES) reading libsecret.dylib",
),
},
});
} finally {
await chmod(join(directory, "libsecret.dylib"), 0o644);
}
},
);
},
);
@@ -0,0 +1,158 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackageWithOptions } from "@electron/asar";
import { Filter } from "incur";
import { expect } from "vitest";
import { z } from "zod";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const filter = "evidence_id,normalized_result.graph.nodes[0:1].node_id";
for (const command of ["analyze-javascript-application", "analyze"]) {
for (const format of ["json", "jsonl"]) {
for (const fullOutput of [false, true]) {
for (const filtered of [false, true]) {
cliTest(
`${command} preserves ${format}, full output ${String(fullOutput)}, filtering ${String(filtered)}`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-output-");
await writeFile(join(root, "main.js"), "fetch('');\n");
const direct = await analyzeJavaScriptApplication({
input_path: root,
});
if (!direct.ok) throw direct.error;
const output = await cli.run({
arguments: [
command,
root,
"--format",
format,
...(fullOutput ? ["--full-output"] : []),
...(filtered ? ["--filter-output", filter] : []),
],
});
expect(output.exitCode).toBe(0);
let data: unknown = output.json;
if (fullOutput) {
const envelope = z
.object({
ok: z.literal(true),
data: z.unknown(),
meta: z.object({
command: z.literal(command),
duration: z.string().regex(/^\d+ms$/u),
}),
})
.parse(output.json);
data = envelope.data;
}
expect(data).toEqual(
filtered
? Filter.apply(direct.value, Filter.parse(filter))
: direct.value,
);
},
);
}
}
}
}
cliTest(
"preserves a complete empty filtered JSON document",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-empty-filter-");
await writeFile(join(root, "main.js"), "export const value = 1;\n");
const output = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--json",
"--filter-output",
"absent.field",
],
});
expect(output.exitCode).toBe(0);
expect(output.json).toEqual({});
},
);
cliTest(
"preserves a typed failed analysis in the JSON result",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-failure-");
const output = await cli.run({
arguments: [
"analyze-javascript-application",
join(root, "absent"),
"--json",
],
});
expect(output.json).toMatchObject({
code: "artifact_operation_failed",
details: { reason: "io" },
});
},
);
cliTest(
"preserves JSON omission for inherited filter methods",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-inherited-filter-");
await writeFile(join(root, "main.js"), "export const value = 1;\n");
const output = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--json",
"--filter-output",
"toString",
],
});
expect(output.exitCode).toBe(0);
expect(output.json).toEqual({});
},
);
for (const command of ["analyze", "analyze-javascript-application"]) {
cliTest(
`${command} forwards the integrity policy while preserving JSON output`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-cli-integrity-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "main.js"), "require('./addon.node');\n");
await writeFile(join(source, "addon.node"), "original");
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await writeFile(join(`${archive}.unpacked`, "addon.node"), "changed");
const strict = await cli.run({ arguments: [command, archive, "--json"] });
expect(strict.json).toMatchObject({
code: "artifact_integrity_mismatch",
});
const recorded = await cli.run({
arguments: [
command,
archive,
"--integrity-policy",
"record-and-continue",
"--json",
],
});
expect(recorded.exitCode).toBe(0);
expect(recorded.json).toMatchObject({
parameters: { integrity_policy: "record-and-continue" },
normalized_result: {
integrity_contradictions: [
{ logical_path: "addon.node", trust: "observed-untrusted" },
],
graph: { coverage: { status: "partial" } },
},
});
},
);
}
@@ -0,0 +1,72 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const progressLine = z.object({
rea_progress: z.object({
phase: z.string(),
completed: z.number(),
total: z.number().nullable(),
message: z.string(),
sequence: z.number(),
terminal: z.boolean().optional(),
}),
});
for (const command of ["analyze-javascript-application", "analyze"]) {
cliTest(
`${command} reports real analysis phases on stderr and preserves stdout Evidence`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-cli-progress-");
await writeFile(join(root, "main.js"), "fetch('');\n");
const direct = await analyzeJavaScriptApplication({ input_path: root });
if (!direct.ok) throw direct.error;
const output = await cli.run({ arguments: [command, root, "--json"] });
expect(output.exitCode).toBe(0);
expect(parseEvidence(output.json).evidence_id).toBe(
direct.value.evidence_id,
);
const updates = output.stderr
.trim()
.split("\n")
.map((line) => progressLine.parse(JSON.parse(line)).rea_progress);
expect(updates[0]?.completed).toBe(0);
expect(
updates.some(({ phase }) => phase === "parse_javascript_sources"),
).toBe(true);
expect(updates.at(-1)).toMatchObject({ completed: 1, terminal: true });
expect(
updates.slice(0, -1).every(({ terminal }) => terminal !== true),
).toBe(true);
},
);
}
cliTest(
"keeps a failed analysis distinct from a completed result",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-cli-progress-failure-");
const output = await cli.run({
arguments: [
"analyze-javascript-application",
join(root, "absent"),
"--json",
],
});
expect(output.json).toMatchObject({ code: "artifact_operation_failed" });
const updates = output.stderr
.trim()
.split("\n")
.map((line) => progressLine.parse(JSON.parse(line)).rea_progress);
expect(updates[0]?.completed).toBe(0);
expect(updates.every(({ terminal }) => terminal !== true)).toBe(true);
},
);
+250 -40
View File
@@ -1,9 +1,8 @@
import { writeFile } from "node:fs/promises";
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -30,46 +29,63 @@ const JSON_COMMANDS = [
describe("compiled CLI JSON input failure status", () => {
for (const [command, operation] of JSON_COMMANDS)
for (const kind of ["inline", "file", "missing"] as const)
cliTest(
`${command} rejects malformed or unreadable ${kind} input before dispatch`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-status-");
const input = kind === "inline" ? "{" : join(root, "input.json");
if (kind === "file") await writeFile(input, "{");
const parsed = await parseCliJsonInput(input, operation);
if (parsed.ok)
throw new Error("Expected JSON input to fail before dispatch");
cliTest(
`${command} rejects malformed inline input before dispatch`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-status-");
const input = "{";
const result = await cli.run({
arguments: [command, input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
const result = await cli.run({
arguments: [command, input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: { operation },
});
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(1);
},
);
expect(result.stdout).toBe(
`${JSON.stringify(parsed.error, null, 2)}\n`,
);
expect(result.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
...(kind === "missing" ? {} : { details: { operation } }),
...(kind === "inline"
? {}
: {
input_path: input,
input_reason:
kind === "file" ? "invalid-json" : "read-failed",
}),
});
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(1);
},
);
for (const kind of ["file", "missing"] as const)
cliTest(
`preserves ${kind} JSON input diagnostics through a real command`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-status-");
const input = join(root, "input.json");
if (kind === "file") await writeFile(input, "{");
const result = await cli.run({
arguments: ["compare-javascript-export-shapes", input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
input_path: input,
input_reason: kind === "file" ? "invalid-json" : "read-failed",
...(kind === "file"
? { details: { operation: "compare-javascript-export-shapes" } }
: {}),
});
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(1);
},
);
});
describe("compiled CLI JSON input diagnostic preservation", () => {
for (const [format, flags] of [
["JSON", ["--json"]],
["JSONL", ["--format", "jsonl"]],
@@ -113,7 +129,7 @@ describe("compiled CLI JSON input failure status", () => {
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
expect(JSON.parse(result.stdout.trim())).toMatchObject({
code: "invalid_request",
input_path: "",
input_reason: "read-failed",
@@ -121,6 +137,125 @@ describe("compiled CLI JSON input failure status", () => {
expect(result.exitCode).toBe(1);
},
);
cliTest(
"classifies an overlong malformed inline value before dispatch",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-overlong-");
const input = `[${"x".repeat(3_000)}`;
const result = await cli.run({
arguments: ["compare-javascript-export-shapes", input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
operation: "compare-javascript-export-shapes",
issues: [{ path: [], reason: "invalid_format", expected: "JSON" }],
},
});
expect(result.json).not.toHaveProperty("input_path");
expect(result.stdout).not.toContain("read-failed");
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(1);
},
);
cliTest(
"preserves explicit overlong JSON path diagnostics",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-overlong-path-");
const input = `[${"x".repeat(3_000)}.json`;
const result = await cli.run({
arguments: ["compare-javascript-export-shapes", input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
input_path: input,
input_reason: "read-failed",
});
expect(result.exitCode).toBe(1);
},
);
});
describe("compiled CLI JSON path ambiguity", () => {
cliTest(
"classifies malformed inline JSON when a path prefix is a regular file",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-not-dir-");
await writeFile(join(root, "[prefix"), "regular file");
const input = "[prefix/rest";
const result = await cli.run({
arguments: ["capture-browser-scenario", input, "--json"],
cwd: root,
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
operation: "capture_browser_scenario",
issues: [{ path: [], reason: "invalid_format", expected: "JSON" }],
},
});
expect(result.json).not.toHaveProperty("input_path");
expect(result.stdout).not.toContain("read-failed");
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(1);
},
);
cliTest.runIf(process.platform !== "win32" && process.getuid?.() !== 0)(
"preserves permission errors for malformed path-like JSON input",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-denied-");
const denied = join(root, "[locked");
const input = "[locked/rest";
await mkdir(denied);
await chmod(denied, 0);
try {
await expect(readFile(join(root, input))).rejects.toMatchObject({
code: "EACCES",
});
const result = await cli.run({
arguments: ["capture-browser-scenario", input, "--json"],
cwd: root,
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
input_path: input,
input_reason: "read-failed",
});
expect(result.exitCode).toBe(1);
} finally {
await chmod(denied, 0o700);
}
},
);
});
describe("compiled JSON parser and logger success seam", () => {
@@ -159,3 +294,78 @@ describe("compiled JSON parser and logger success seam", () => {
},
);
});
describe("compiled CLI parser with relative brace and bracket paths", () => {
for (const filename of ["[input].json", "{capture}.json"])
cliTest(
`reads the selected relative file ${filename}`,
async ({ processes }) => {
const root = await createTestTempDirectory("rea-cli-json-path-");
const value = { selected: filename };
await writeFile(join(root, filename), JSON.stringify(value));
const moduleUrl = new URL(
"../../../dist/cliJsonInput.js",
import.meta.url,
).href;
const result = await processes.run(
process.execPath,
[
"--input-type=module",
"-e",
`import { parseCliJsonInput } from ${JSON.stringify(moduleUrl)};
console.log(JSON.stringify(await parseCliJsonInput(process.argv[1], "test-input")));`,
filename,
],
{
cwd: root,
env: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
},
);
expect(result.stdout).toBe(`${JSON.stringify({ ok: true, value })}\n`);
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(0);
},
);
for (const filename of ["[missing].json", "{missing}.json"])
cliTest(
`keeps missing relative path diagnostics for ${filename}`,
async ({ processes }) => {
const root = await createTestTempDirectory("rea-cli-json-missing-");
const moduleUrl = new URL(
"../../../dist/cliJsonInput.js",
import.meta.url,
).href;
const result = await processes.run(
process.execPath,
[
"--input-type=module",
"-e",
`import { parseCliJsonInput } from ${JSON.stringify(moduleUrl)};
console.log(JSON.stringify(await parseCliJsonInput(process.argv[1], "test-input")));`,
filename,
],
{
cwd: root,
env: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
},
);
expect(JSON.parse(result.stdout.trim())).toMatchObject({
ok: false,
error: { input_path: filename, input_reason: "read-failed" },
});
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(0);
},
);
});
+170
View File
@@ -0,0 +1,170 @@
import { Writable } from "node:stream";
import { describe, expect, it } from "vitest";
import { writeJsonOutput } from "../../../src/cli/jsonOutput.js";
import { createStreamedCliJsonOutput } from "../../../src/cli/streamedJsonOutput.js";
const collect = async (
value: unknown,
format: "json" | "jsonl" = "json",
): Promise<string> => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: unknown, _encoding, callback) {
if (!Buffer.isBuffer(chunk)) {
callback(new TypeError("Expected a UTF-8 output buffer"));
return;
}
chunks.push(chunk);
callback();
},
});
await writeJsonOutput(value, destination, format);
return Buffer.concat(chunks).toString("utf8");
};
describe("incremental CLI JSON", () => {
it.each([
null,
true,
-0,
1e-7,
"",
{ empty: [], object: {}, nested: [{ value: null }] },
{ 'quoted"key': '\u0000\b\t\n\f\r\\"', unicode: "雪𝟠\ud800\udfff" },
{ text: `${"x".repeat(8191)}𝟠${"y".repeat(8191)}\ud800` },
])("matches native JSON encoding for %j", async (value) => {
expect(await collect(value)).toBe(`${JSON.stringify(value, null, 2)}\n`);
});
it("preserves shared objects without interpreting them as cycles", async () => {
const shared = { value: "shared" };
const value = { copies: [shared, shared] };
expect(await collect(value)).toBe(`${JSON.stringify(value, null, 2)}\n`);
});
it("writes compact JSONL records and preserves an empty record set", async () => {
const value = [{ text: "first\nrecord" }, { text: "雪𝟠" }];
expect(await collect(value, "jsonl")).toBe(
`${value.map((item) => JSON.stringify(item)).join("\n")}\n`,
);
expect(await collect([], "jsonl")).toBe("");
});
it("bounds escaped leaf writes and waits for a slow destination", async () => {
const leaf = `\u0000雪𝟠`.repeat(32 * 1024);
const chunks: Buffer[] = [];
let largestChunk = 0;
const destination = new Writable({
highWaterMark: 1,
write(chunk: unknown, _encoding, callback) {
if (!Buffer.isBuffer(chunk)) {
callback(new TypeError("Expected UTF-8 bytes"));
return;
}
largestChunk = Math.max(largestChunk, chunk.length);
setTimeout(() => {
chunks.push(chunk);
callback();
}, 1);
},
});
await writeJsonOutput({ leaf }, destination);
expect(largestChunk).toBeLessThan(Buffer.byteLength(leaf));
const actual = Buffer.concat(chunks).toString("utf8");
const expected = `${JSON.stringify({ leaf }, null, 2)}\n`;
expect(actual.length).toBe(expected.length);
expect(actual === expected).toBe(true);
expect(destination.writableEnded).toBe(false);
});
it("waits for the final write even when it fits the destination buffer", async () => {
let completed = false;
const destination = new Writable({
write(_chunk, _encoding, callback) {
setTimeout(() => {
completed = true;
callback();
}, 5);
},
});
await writeJsonOutput({ result: "small" }, destination);
expect(completed).toBe(true);
});
it.each([false, true])(
"propagates a failed destination (deferred: %s)",
async (deferred) => {
const cause = new Error("Fixture destination failed");
const destination = new Writable({
write(_chunk, _encoding, callback) {
if (deferred) setTimeout(() => callback(cause), 5);
else callback(cause);
},
});
await expect(
writeJsonOutput({ result: "small" }, destination),
).rejects.toBe(cause);
},
);
it("leaves a reusable destination open without adding error listeners", async () => {
const destination = new Writable({
write(_chunk, _encoding, callback) {
callback();
},
});
const listeners = destination.listenerCount("error");
await writeJsonOutput({ result: "first" }, destination);
await writeJsonOutput({ result: "second" }, destination);
expect(destination.listenerCount("error")).toBe(listeners);
expect(destination.writableEnded).toBe(false);
});
it("rejects a cycle at the serialization boundary", async () => {
const cycle: Record<string, unknown> = {};
cycle.self = cycle;
await expect(collect(cycle)).rejects.toThrow("circular reference");
});
it.each([undefined, Number.NaN, Number.POSITIVE_INFINITY, 1n, new Date(0)])(
"rejects non-JSON input %s",
async (value) => {
await expect(collect(value)).rejects.toThrow("ordinary JSON");
},
);
});
describe("streamed CLI result surface", () => {
it.each([
[],
["--format", "md"],
["--json", "--token-count"],
["--json", "--token-limit", "5"],
["--json", "--format", "invalid"],
])("delegates unsupported output controls %j", (...arguments_) => {
expect(createStreamedCliJsonOutput(arguments_, new Writable())).toBe(
undefined,
);
});
it("keeps ownership after a failed write so no second document is emitted", async () => {
const cause = new Error("Fixture destination failed");
const destination = new Writable({
write(_chunk, _encoding, callback) {
callback(cause);
},
});
const output = createStreamedCliJsonOutput(["--json"], destination);
if (output === undefined) throw new Error("Missing JSON output surface");
await expect(
output.write(
{ result: "small" },
{ command: "fixture", duration: "1ms", format: "json" },
),
).rejects.toBe(cause);
expect(output.handled).toBe(true);
expect(output.failed).toBe(true);
});
});
@@ -0,0 +1,74 @@
import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
import type { TestCli } from "../../support/cli/cliFixture.js";
const runCapture = async (cli: TestCli, steps: string | undefined) => {
const arguments_ = [
"capture-native-ui-scenario",
"/provider-must-not-be-invoked",
"--pid",
"1",
"--window-id",
"1",
];
if (steps !== undefined) arguments_.push("--steps", steps);
arguments_.push("--json");
return cli.run({
arguments: arguments_,
environment: { REA_LOG_LEVEL: "silent" },
});
};
describe("native UI scenario CLI input", () => {
cliTest(
"rejects omitted steps under the shared scenario contract",
async ({ cli }) => {
const result = await runCapture(cli, undefined);
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_native_ui_scenario",
issues: [{ path: ["steps"], reason: "missing_argument" }],
},
});
},
);
cliTest("rejects malformed JSON as invalid input", async ({ cli }) => {
const result = await runCapture(cli, "[");
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_native_ui_scenario",
issues: [
{
path: ["steps"],
reason: "invalid_format",
expected: "JSON",
},
],
},
});
});
cliTest(
"requires at least one schema-valid scenario step",
async ({ cli }) => {
const result = await runCapture(cli, "[]");
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_native_ui_scenario",
issues: [{ path: ["steps"], reason: "out_of_range", minimum: 1 }],
},
});
},
);
});
+132 -5
View File
@@ -13,9 +13,10 @@ import {
captureProcessScenarioFile,
compareProcessEvidenceFiles,
projectProcessCliError,
} from "../../../src/application/ProcessCli.js";
} from "../../../src/application/process/ProcessCli.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
import { PROCESS_PROVIDER } from "../../../src/application/process/ProcessEvidence.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
const roots: string[] = [];
const execFileAsync = promisify(execFile);
@@ -120,8 +121,17 @@ describe("process CLI errors", () => {
const root = await fixture();
const malformed = join(root, "malformed.json");
const invalid = join(root, "invalid.json");
const invalidUtf8 = join(root, "invalid-utf8.json");
await writeFile(malformed, "not-json");
await writeFile(invalid, "{}");
await writeFile(
invalidUtf8,
Buffer.concat([
Buffer.from('{"executable":"'),
Buffer.from([0xff]),
Buffer.from('"}'),
]),
);
expect(
await captureProcessScenarioFile(join(root, "missing.json")),
@@ -137,6 +147,12 @@ describe("process CLI errors", () => {
message:
"Process input file is not valid JSON. Repair the file, then try again.",
});
expect(await captureProcessScenarioFile(invalidUtf8)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process input file is not valid JSON. Repair the file, then try again.",
});
expect(await captureProcessScenarioFile(invalid)).toEqual({
error: "Process command failed",
code: "invalid_request",
@@ -153,6 +169,66 @@ describe("process CLI errors", () => {
});
});
it("rejects NUL arguments before process launch", async () => {
const root = await fixture();
const scenario = join(root, "nul-argument.json");
await writeFile(
scenario,
JSON.stringify({ executable: process.execPath, arguments: ["\0"] }),
);
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
error: "Process command failed",
code: "invalid_request",
category: "invalid_input",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["arguments", 0],
reason: "invalid_format",
expected: "regex",
message:
"Values passed to operating-system APIs cannot contain NUL",
},
],
},
});
});
});
describe("process CLI environment key diagnostics", () => {
it("reports the reserved process environment key constraint", async () => {
const root = await fixture();
const scenario = join(root, "reserved-environment.json");
await writeFile(
scenario,
JSON.stringify({
executable: process.execPath,
environment: { REA_PROCESS_RUN_ID: "caller-value" },
}),
);
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
error: "Process command failed",
code: "invalid_request",
category: "invalid_input",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["environment", "REA_PROCESS_RUN_ID"],
reason: "invalid_format",
expected: "regex",
message: "REA_PROCESS_RUN_ID is reserved by the process adapter",
},
],
},
});
});
});
describe("process CLI evidence validation", () => {
it("captures the minimal executable-and-arguments scenario", async () => {
const root = await fixture();
const scenario = join(root, "scenario.json");
@@ -217,11 +293,62 @@ describe("process CLI errors", () => {
const malformed = join(root, "malformed-evidence.json");
await writeFile(malformed, "{}");
expect(await compareProcessEvidenceFiles(malformed, malformed)).toEqual({
expect(
await compareProcessEvidenceFiles(malformed, malformed),
).toMatchObject({
error: "Process command failed",
category: "invalid_input",
message:
"Capture evidence is malformed. Create new capture evidence, then try again.",
code: "invalid_request",
details: {
operation: "compare_process_captures",
issues: expect.arrayContaining([
expect.objectContaining({
path: ["parameters"],
reason: "missing_argument",
}),
]),
},
});
});
});
it(
"reports the JSON depth constraint through the compiled comparison CLI",
async () => {
const root = await fixture();
const left = join(root, "left.json");
const right = join(root, "right.json");
const input = INVESTIGATION_EXAMPLES.compare_process_captures.input;
await writeFile(left, JSON.stringify(input.left));
await writeFile(right, JSON.stringify(input.right));
const cli = fileURLToPath(
new URL("../../../scripts/rea.mjs", import.meta.url),
);
const cliArguments = [
cli,
"compare-process-captures",
left,
right,
"--json",
];
const baseline = await execFileAsync(process.execPath, cliArguments);
expect(JSON.parse(baseline.stdout)).toMatchObject({
operation: "compare_process_captures",
});
const nested = '{"nested":'.repeat(10_000) + "1" + "}".repeat(10_000);
await writeFile(
left,
JSON.stringify({
...input.left,
parameters: { attack: "depth-placeholder" },
}).replace('"depth-placeholder"', nested),
);
await expect(
execFileAsync(process.execPath, cliArguments),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("maximum nesting depth"),
});
},
CLI_INTEGRATION_TIMEOUT_MS,
);
+20 -3
View File
@@ -1,3 +1,5 @@
import { EVMOLE_PROVIDER_IDENTITY } from "../../../src/evm/EvmoleRelease.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/PwntoolsRelease.js";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -19,6 +21,10 @@ import {
MANAGED_WORKFLOW_PROVIDER,
} from "../../../src/application/InvestigationProviders.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../../../src/browser/CdpBrowserProvider.js";
import {
HAR_CAPTURE_PROVIDER_IDENTITY,
MITMPROXY_CAPTURE_PROVIDER_IDENTITY,
} from "../../../src/browser/history/CaptureRelease.js";
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "../../../src/browser/CdpElectronProvider.js";
import { PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightElectronActiveProvider.js";
import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
@@ -89,7 +95,7 @@ describe("canonical product catalog", () => {
);
});
it("matches every source-derived checked-in product fact", async () => {
it("matches every source-derived build-generated product fact", async () => {
const catalog = await createProductCatalog(root);
expect(catalog.tools.total).toBe(TOOL_CONTRACTS.length);
expect(
@@ -106,9 +112,13 @@ describe("canonical product catalog", () => {
BINWALK_PROVIDER_IDENTITY,
UNBLOB_PROVIDER_IDENTITY,
WAKARU_PROVIDER_IDENTITY,
HAR_CAPTURE_PROVIDER_IDENTITY,
MITMPROXY_CAPTURE_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_IDENTITY,
IDA_PROVIDER_IDENTITY,
NATIVE_MACOS_PROVIDER_IDENTITY,
PWNTOOLS_PROVIDER_IDENTITY,
EVMOLE_PROVIDER_IDENTITY,
ARTIFACT_GRAPH_PROVIDER,
ANDROID_APPLICATION_PROVIDER,
APPLE_APPLICATION_PROVIDER,
@@ -185,14 +195,19 @@ describe("canonical product catalog", () => {
"project_managed_application_graph",
"verify_managed_native_boundaries",
]);
// Runtime schema commitments must not fan out into checked-in documentation.
// Provider commitments cover the facts actually present in this projection.
expect(Object.keys(catalog.runtime_catalog.digests)).toEqual([
"providers_sha256",
]);
expect(catalog.runtime_catalog.digests.providers_sha256).toBe(
providerCatalogDigest(catalog.providers),
);
expect(
JSON.parse(await readFile("docs/product-catalog.json", "utf8")),
JSON.parse(await readFile("docs/public/product-catalog.json", "utf8")),
).toEqual(catalog);
expect(await serializeProductCatalog(catalog)).toBe(
await readFile("docs/product-catalog.json", "utf8"),
await readFile("docs/public/product-catalog.json", "utf8"),
);
await expect(
assertDocumentationFacts(root, catalog),
@@ -286,6 +301,8 @@ describe("canonical product catalog drift", () => {
true,
);
expect(issues.some((issue) => issue.includes("Future Client"))).toBe(true);
expect(issues).toContain("docs/installation.md: missing Future Client");
expect(issues).not.toContain("README.md: missing Future Client");
});
it("changes the provider projection digest when provider facts drift", async () => {
@@ -0,0 +1,64 @@
import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
describe("scenario CLI schema diagnostics", () => {
cliTest("reports browser scenario schema paths", async ({ cli }) => {
const result = await cli.run({
arguments: ["capture-browser-scenario", "{}", "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_browser_scenario",
issues: expect.arrayContaining([
{
path: ["browser"],
reason: "missing_argument",
expected: "object",
},
{
path: ["start_url"],
reason: "missing_argument",
expected: "object",
},
{
path: ["actions"],
reason: "missing_argument",
expected: "array",
},
]),
},
});
});
cliTest("reports Electron scenario schema paths", async ({ cli }) => {
const result = await cli.run({
arguments: ["capture-electron-scenario", "{}", "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_electron_scenario",
issues: expect.arrayContaining([
{
path: ["executable_path"],
reason: "missing_argument",
expected: "string",
},
{
path: ["application_path"],
reason: "missing_argument",
expected: "string",
},
]),
},
});
});
});