feat(browser): inspect historical web network captures (#992)
* feat(browser): inspect retained HAR and mitmproxy capture evidence Add independent offline format adapters, inline CLI/MCP evidence, bounded owned decoder processes, and real producer verification. Refs #882 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) * fix(browser): preserve capture boundaries during cancellation and decoding Honor cancellation during owned-command cleanup, retain opaque HAR extension content, and clean verifier resources on every failure path. Refs #882 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) * fix(browser): exclude sensitive capture fields across representations Normalize known native transport URLs for both bytes and strings, including backups. Exclude explicitly sensitive text fields with null so redaction markers cannot reintroduce declared literals. Cover both provider identities in catalog conformance. Refs #882 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) * fix(browser): exclude sensitive capture identities and bound diagnostics * fix(browser): validate excluded HAR subtrees before projection * fix(browser): distinguish capture input limits from decoder failures * fix(browser): preserve decoder failure categories * fix(browser): validate excluded native credential values * test(browser): report capture verifier assertions directly * fix(browser): classify native representation failures precisely * fix(browser): exclude URL userinfo after header whitespace * fix(browser): preserve capture evidence and failure boundaries * fix(browser): exclude sensitive literals from capture limitations * test(browser): check limitation values without JSON syntax * fix(browser): preserve acquisition integrity and exclude selection diagnostics * fix(browser): preserve capture acquisition and declaration boundaries * fix(mcp): project sensitive capture argument validation * fix: preserve capture bytes and prelaunch cancellation * fix(browser): exclude sensitive HAR record ancestry * fix(browser): preserve transport URL and parameter exclusions * fix(browser): preserve numeric redaction and canonical capture provenance * fix(browser): cover derived capture values and ownership preparation deadlines * fix(browser): exclude explicitly sensitive artifact digests * chore: regenerate generated metadata * fix(browser): reject lossy HAR member normalization * test(browser): assert the advertised unsupported-profile outcome * fix(browser): preserve JSON visitor nesting failure locations * fix(browser): exclude explicitly sensitive native source ranges --------- Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Kaoru0822
github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
parent
6e4535c101
commit
2bf3663f65
@@ -0,0 +1,481 @@
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
mkdtemp,
|
||||
rm,
|
||||
truncate,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { HistoricalCaptureDecoder } from "../../../src/browser/history/HistoricalCaptureDecoder.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "../../../src/browser/history/CaptureRelease.js";
|
||||
import {
|
||||
inspectWebNetworkCaptureInputSchema,
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
} from "../../../src/domain/webNetworkCapture.js";
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
|
||||
it.each([true, false])(
|
||||
"binds decoder replies to the complete selected provider identity (matching name: %s)",
|
||||
async (matching) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-capture-identity-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "capture.har");
|
||||
const text = JSON.stringify(historicalHar());
|
||||
await writeFile(path, text);
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
const value = decodeHarCapture(text, []);
|
||||
if (!matching) value.decoder.name = "different adapter";
|
||||
await writeFile(
|
||||
join(runtimePath, "reply.json"),
|
||||
JSON.stringify({ ok: true, value }),
|
||||
);
|
||||
return { command: process.execPath, arguments: ["-e", ""] };
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(matching);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
else expect(result.value.decoder).toEqual(HAR_CAPTURE_PROVIDER_IDENTITY);
|
||||
},
|
||||
);
|
||||
|
||||
it("classifies an oversized selected capture before creating an owned decoder", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-limit-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, "");
|
||||
await truncate(path, WEB_NETWORK_CAPTURE_LIMITS.inputBytes + 1);
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
throw new Error("Oversized input must not launch decoding");
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Oversized input must fail");
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: "out_of_range",
|
||||
expected: {
|
||||
maximum_capture_bytes: WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not misclassify decoder filesystem failures as missing selected input", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-command-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
throw Object.assign(
|
||||
new Error("Configured decoder command file missing"),
|
||||
{ code: "ENOENT" },
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Failed decoder command must fail");
|
||||
expect(result.error._tag).toBe("ProviderAdapterError");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
details: {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
reason: "Configured decoder command file missing",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["missing-capture", "missing-reply", "failed-command"])(
|
||||
"redacts declared paths and diagnostics while preserving the %s failure",
|
||||
async (mode) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-sensitive-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "explicit-private-value.har");
|
||||
if (mode !== "missing-capture")
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => ({
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
"-e",
|
||||
mode === "failed-command"
|
||||
? 'process.stderr.write("explicit-private-value ordinary diagnostic"); process.exit(2)'
|
||||
: "process.exit(0)",
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["explicit-private-value", "REDACTED"],
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Failure required");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
const serialized = JSON.stringify(projected);
|
||||
expect(serialized).not.toContain("explicit-private-value");
|
||||
expect(serialized).not.toContain("REDACTED");
|
||||
expect(result.error._tag).toBe(
|
||||
mode === "missing-capture"
|
||||
? "AnalysisInputError"
|
||||
: mode === "missing-reply"
|
||||
? "AnalysisOutputError"
|
||||
: "ProviderAdapterError",
|
||||
);
|
||||
if (mode === "missing-capture") expect(serialized).toContain("ENOENT");
|
||||
if (mode === "failed-command")
|
||||
expect(serialized).toContain('"exit_code":2');
|
||||
},
|
||||
);
|
||||
|
||||
it("reports an absent owned reply as output failure and removes its private snapshot root", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-decoder-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
let privatePath: string | undefined;
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
privatePath = runtimePath;
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Owned reply is required");
|
||||
expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
expect(result.error.message).toContain("ENOENT");
|
||||
if (privatePath === undefined)
|
||||
throw new Error("Private root was not acquired");
|
||||
await expect(access(privatePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("cancels after snapshot acquisition before launch and removes private input declarations", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-cancel-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
let privatePath: string | undefined;
|
||||
const controller = new AbortController();
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
privatePath = runtimePath;
|
||||
controller.abort();
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(3)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["explicit-private-declaration"],
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Cancelled acquisition must fail");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
if (privatePath === undefined)
|
||||
throw new Error("Private root was not acquired");
|
||||
await expect(access(privatePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ reason: "input-limit", tag: "AnalysisInputError" },
|
||||
{ reason: "resource-limit", tag: "ProviderAdapterError" },
|
||||
{ reason: "decoder", tag: "ProviderAdapterError" },
|
||||
{ reason: "limit", tag: "AnalysisOutputError" },
|
||||
])(
|
||||
"preserves $reason decoder failures through the public error boundary",
|
||||
async ({ reason, tag }) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-reply-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
let privatePath: string | undefined;
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
privatePath = runtimePath;
|
||||
await writeFile(
|
||||
join(runtimePath, "reply.json"),
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
reason,
|
||||
message: "Specific decoder constraint",
|
||||
pointer: "/extension/child",
|
||||
}),
|
||||
);
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Failure required");
|
||||
expect(result.error._tag).toBe(tag);
|
||||
const projected = projectAnalysisError(result.error);
|
||||
if (reason === "input-limit") {
|
||||
expect(projected).toMatchObject({
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path", "/extension/child"],
|
||||
reason: "out_of_range",
|
||||
expected: {
|
||||
maximum_capture_nesting: WEB_NETWORK_CAPTURE_LIMITS.depth,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} else if (tag === "ProviderAdapterError") {
|
||||
expect(projected).toMatchObject({
|
||||
details: {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
reason: "Specific decoder constraint",
|
||||
failure_kind: reason,
|
||||
pointer: "/extension/child",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (privatePath === undefined)
|
||||
throw new Error("Private root was not acquired");
|
||||
await expect(access(privatePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"reports a real filesystem permission denial separately from missing capture input",
|
||||
async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-denied-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "unreadable.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()), { mode: 0o000 });
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
throw new Error("Permission-denied input must not launch decoding");
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
await chmod(path, 0o600);
|
||||
if (result.ok) throw new Error("Permission denial required");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "access_denied",
|
||||
category: "unavailable",
|
||||
retryable: false,
|
||||
details: {
|
||||
operation: "inspect_web_network_capture",
|
||||
path,
|
||||
system_code: "EACCES",
|
||||
},
|
||||
});
|
||||
expect(projectAnalysisError(result.error).remediation.action).toContain(
|
||||
"read access",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["format", "process"])(
|
||||
"preserves the structured %s failure when runtime cleanup fails",
|
||||
async (kind) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-cleanup-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "capture-private.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
if (kind === "format")
|
||||
await writeFile(
|
||||
join(runtimePath, "reply.json"),
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
reason: "format",
|
||||
message: "Malformed retained record",
|
||||
pointer: "/metadata/capture-private",
|
||||
}),
|
||||
);
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
"-e",
|
||||
kind === "format"
|
||||
? "process.exit(0)"
|
||||
: 'process.stderr.write("Specific provider fault"); process.exit(3)',
|
||||
],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
async () => {
|
||||
const runtime = await PrivateRuntimeRoot.create({
|
||||
prefix: "rea-cleanup-proof-",
|
||||
});
|
||||
onTestFinished(() => runtime.close());
|
||||
return {
|
||||
path: runtime.path,
|
||||
close: async () => {
|
||||
throw new Error("Deliberate cleanup denial");
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["capture-private"],
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Cleanup failure required");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
previous_error:
|
||||
kind === "format"
|
||||
? {
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path", "/metadata"],
|
||||
reason: "invalid_format",
|
||||
message: "Malformed retained record",
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
: {
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
exit_code: 3,
|
||||
stderr: "Specific provider fault",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("capture-private");
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,109 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, writeFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
const entrypoint = fileURLToPath(
|
||||
new URL("../../../scripts/rea.mjs", import.meta.url),
|
||||
);
|
||||
const cli = async (
|
||||
path: string,
|
||||
format: string,
|
||||
extra: readonly string[] = [],
|
||||
) => {
|
||||
try {
|
||||
const result = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
entrypoint,
|
||||
"inspect-web-network-capture",
|
||||
path,
|
||||
format,
|
||||
"--json",
|
||||
...extra,
|
||||
],
|
||||
{ env: { ...process.env, REA_MITMDUMP_COMMAND: "" }, timeout: 40_000 },
|
||||
);
|
||||
return { ok: true, stdout: result.stdout };
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"stdout" in cause &&
|
||||
typeof cause.stdout === "string"
|
||||
)
|
||||
return { ok: false, stdout: cause.stdout };
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
|
||||
it("reads actual upstream HAR packages in an owned process and retains selected producer order", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-har-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
fixture.log.entries.push(structuredClone(first));
|
||||
const text = JSON.stringify(fixture);
|
||||
const path = join(root, "capture.har");
|
||||
await writeFile(path, text);
|
||||
const called = await cli(path, "har", ["--record", "1", "--record", "0"]);
|
||||
expect(called.ok, called.stdout).toBe(true);
|
||||
const result = { value: parseEvidence(JSON.parse(called.stdout)) };
|
||||
expect(result.value.subject?.digest).toMatchObject({
|
||||
sha256: createHash("sha256").update(text).digest("hex"),
|
||||
});
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
total_records: 2,
|
||||
records: [{ ordinal: 1 }, { ordinal: 0 }],
|
||||
runtime_attribution: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps malformed JSON separate from absent external mitmproxy capability", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-errors-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "capture.har");
|
||||
await writeFile(path, "{malformed-private-json");
|
||||
const malformed = await cli(path, "har");
|
||||
expect(malformed.ok).toBe(false);
|
||||
expect(JSON.parse(malformed.stdout)).toMatchObject({
|
||||
category: "invalid_input",
|
||||
});
|
||||
expect(malformed.stdout).not.toContain("malformed-private-json");
|
||||
const missing = await cli(path, "mitmproxy");
|
||||
expect(missing.ok).toBe(false);
|
||||
expect(JSON.parse(missing.stdout)).toMatchObject({
|
||||
category: "unsupported_provider",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the actual HAR decoder nesting constraint as a typed selected-input issue", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-depth-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
let extension: unknown = "leaf";
|
||||
for (let depth = 0; depth < 66; depth++) extension = { child: extension };
|
||||
const path = join(root, "deep.har");
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({ ...historicalHar(), _extension: extension }),
|
||||
);
|
||||
const result = await cli(path, "har");
|
||||
expect(result.ok).toBe(false);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path", expect.stringMatching(/^\/_extension\/child/)],
|
||||
reason: "out_of_range",
|
||||
expected: { maximum_capture_nesting: 64 },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,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";
|
||||
@@ -106,6 +110,8 @@ 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,
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
|
||||
it("publishes valid SDK schemas and retains historical inline Evidence with the supplied session", async () => {
|
||||
const service = new WebNetworkCaptureService({
|
||||
inspect: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
artifact: { path: "/capture.har", sha256: "a".repeat(64), bytes: 10 },
|
||||
format: "har",
|
||||
decoder: { id: "test-capture-port", name: "test port", version: "1" },
|
||||
container: {
|
||||
reported: { creator: "fixture" },
|
||||
numeric_literals: [],
|
||||
redactions: [],
|
||||
records_pointer: "/log/entries",
|
||||
},
|
||||
total_records: 0,
|
||||
records: [],
|
||||
runtime_attribution: "unknown",
|
||||
limitations: ["synthetic application port, no real decoder claim"],
|
||||
}),
|
||||
),
|
||||
});
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Binary provider must not start");
|
||||
});
|
||||
const server = createServer(session, session, { webNetworkCapture: service });
|
||||
const client = new Client({
|
||||
name: "historical-capture-contract",
|
||||
version: "1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = (await client.listTools()).tools.find(
|
||||
(tool) => tool.name === "inspect_web_network_capture",
|
||||
);
|
||||
if (advertised?.outputSchema === undefined)
|
||||
throw new Error("Capture inspection must advertise both schemas");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = advertised.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = advertised.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
const args = { capture_path: "/capture.har", format: "har" };
|
||||
expect(ajv.validate(inputSchema, args)).toBe(true);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: args,
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(
|
||||
ajv.validate(outputSchema, response.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
).toBe(true);
|
||||
const parsed = toolContract("inspect_web_network_capture").outputSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
const evidence = parseEvidence(parsed.evidence);
|
||||
expect(parsed.result).toEqual(evidence.normalized_result);
|
||||
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
|
||||
const invalid = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: { ...args, capture_path: "relative.har" },
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
const invalidSensitive = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: { ...args, sensitive_values: ["secret"], mysecret: true },
|
||||
});
|
||||
expect(invalidSensitive.isError).toBe(true);
|
||||
expect(invalidSensitive.structuredContent).toMatchObject({
|
||||
error: { code: "invalid_request", details: { issues: [{ path: [] }] } },
|
||||
});
|
||||
expect(JSON.stringify(invalidSensitive)).not.toContain("secret");
|
||||
expect(ajv.validate(inputSchema, { ...args, mysecret: true })).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
OwnedCommandFailure,
|
||||
runOwnedCommand,
|
||||
} from "../../../src/process/OwnedCommand.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
|
||||
|
||||
const command = (script: string) => ({
|
||||
command: process.execPath,
|
||||
arguments: ["-e", script],
|
||||
runId: `rea-owned-command-test-${randomUUID()}`,
|
||||
});
|
||||
|
||||
it("includes ownership preparation in the command deadline before provider creation", async () => {
|
||||
let prepared = false;
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
command("process.exit(0)"),
|
||||
{
|
||||
timeoutMs: 20,
|
||||
diagnosticBytes: 1024,
|
||||
},
|
||||
{
|
||||
launcher: async (input) => {
|
||||
await delay(80, undefined, { signal: input.signal });
|
||||
prepared = true;
|
||||
throw new Error(
|
||||
"Slow preparation must be aborted before provider creation",
|
||||
);
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({ reason: "timeout", snapshot: null });
|
||||
expect(prepared).toBe(false);
|
||||
});
|
||||
|
||||
it("passes cancellation into native ownership preparation before provider creation", async () => {
|
||||
const controller = new AbortController();
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
command("process.exit(0)"),
|
||||
{ timeoutMs: 2000, diagnosticBytes: 1024 },
|
||||
{
|
||||
signal: controller.signal,
|
||||
launcher: async (input) => {
|
||||
expect(input.signal?.aborted).toBe(false);
|
||||
controller.abort();
|
||||
input.signal?.throwIfAborted();
|
||||
throw new Error("Cancelled preparation must not launch a provider");
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({ reason: "cancelled", snapshot: null });
|
||||
});
|
||||
|
||||
it("bounds retained diagnostics across both streams during a real output burst", async () => {
|
||||
try {
|
||||
await runOwnedCommand(
|
||||
command(
|
||||
'process.stdout.write("a".repeat(256 * 1024)); process.stderr.write("b".repeat(256 * 1024))',
|
||||
),
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
);
|
||||
throw new Error("An oversized producer must fail");
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof OwnedCommandFailure)) throw cause;
|
||||
expect(cause.reason).toBe("output-limit");
|
||||
expect(cause.snapshot).not.toBeNull();
|
||||
expect(
|
||||
(cause.snapshot?.stdout.bytes ?? 0) + (cause.snapshot?.stderr.bytes ?? 0),
|
||||
).toBeLessThanOrEqual(1024);
|
||||
}
|
||||
});
|
||||
|
||||
it("collects a real owned command and verifies its exit before returning diagnostics", async () => {
|
||||
const result = await runOwnedCommand(
|
||||
command('process.stdout.write("observed-output")'),
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
stdout: { text: "observed-output", bytes: 15 },
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels a real acquired process and independently releases it", async () => {
|
||||
const controller = new AbortController();
|
||||
let pid: number | undefined;
|
||||
const result = runOwnedCommand(
|
||||
command(
|
||||
'process.stdout.write("ready\\n"); setInterval(() => undefined, 1000)',
|
||||
),
|
||||
{ timeoutMs: 5_000, diagnosticBytes: 1024 },
|
||||
{
|
||||
signal: controller.signal,
|
||||
launcher: async (input) => {
|
||||
const process = await spawnOwnedProviderProcess(input);
|
||||
pid = process.process.pid;
|
||||
await waitForProviderProcessReady(process.process);
|
||||
setImmediate(() => controller.abort());
|
||||
return process;
|
||||
},
|
||||
},
|
||||
);
|
||||
await expect(result).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
cleanupFailure: null,
|
||||
});
|
||||
if (pid === undefined) throw new Error("Process was not acquired");
|
||||
const acquiredPid = pid;
|
||||
expect(() => process.kill(acquiredPid, 0)).toThrow();
|
||||
});
|
||||
|
||||
it("returns a timeout for a running process after independent cleanup", async () => {
|
||||
await expect(
|
||||
runOwnedCommand(command("setInterval(() => undefined, 1000)"), {
|
||||
timeoutMs: 50,
|
||||
diagnosticBytes: 1024,
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: "timeout", cleanupFailure: null });
|
||||
});
|
||||
|
||||
it("honors cancellation during cleanup after a successful command", async () => {
|
||||
const controller = new AbortController();
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
command("process.exit(0)"),
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
{
|
||||
signal: controller.signal,
|
||||
launcher: async (input) => {
|
||||
const launched = await spawnOwnedProviderProcess(input);
|
||||
return {
|
||||
...launched,
|
||||
cleanup: async () => {
|
||||
const result = await cleanupOwnedProcessGroup(launched.ownership);
|
||||
controller.abort();
|
||||
return result;
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({ reason: "cancelled", cleanupFailure: null });
|
||||
});
|
||||
|
||||
it("rejects oversized diagnostics even when the child exits immediately", async () => {
|
||||
await expect(
|
||||
runOwnedCommand(command('process.stdout.write("x".repeat(2048))'), {
|
||||
timeoutMs: 2_000,
|
||||
diagnosticBytes: 1024,
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: "output-limit", cleanupFailure: null });
|
||||
});
|
||||
|
||||
it("preserves original command failure together with failed cleanup resource identities", async () => {
|
||||
const request = command("process.exit(2)");
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
request,
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
{
|
||||
launcher: async (input) => {
|
||||
const process = await spawnOwnedProviderProcess(input);
|
||||
return {
|
||||
...process,
|
||||
cleanup: async () => ({
|
||||
cleaned: false as const,
|
||||
reason: "synthetic cleanup could not be confirmed",
|
||||
}),
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
reason: "process",
|
||||
cleanupFailure: "synthetic cleanup could not be confirmed",
|
||||
resources: expect.arrayContaining([request.runId]),
|
||||
snapshot: { exitCode: 2 },
|
||||
});
|
||||
});
|
||||
@@ -41,7 +41,6 @@ itWithLinuxCaptureCapability.each([false, true])(
|
||||
idle_timeout_ms: 10_000,
|
||||
});
|
||||
const result = await captureProcessScenario(scenario);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
const capture = result.value;
|
||||
const identity = identitySchema.parse(
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
type ProviderProcessDiagnostic,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
import {
|
||||
spawnProviderProcessFixture,
|
||||
stopProviderProcessFixture,
|
||||
} from "../../fixtures/providerProcess.js";
|
||||
|
||||
it("bounds capture before diagnostic callbacks while draining both output streams", async () => {
|
||||
const child = spawnProviderProcessFixture("burst", 70_000);
|
||||
const diagnostics: ProviderProcessDiagnostic[] = [];
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{ process: child, ownsProcessLifetime: true },
|
||||
{
|
||||
maxDiagnosticBytes: 1024,
|
||||
onDiagnostic: (event) => {
|
||||
const snapshot = supervisor.snapshot();
|
||||
expect(
|
||||
snapshot.stdout.bytes + snapshot.stderr.bytes,
|
||||
).toBeLessThanOrEqual(1024);
|
||||
diagnostics.push(event);
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
expect(await supervisor.waitForOutputClose(2_000)).toBe(true);
|
||||
expect(
|
||||
diagnostics.some((event) => event.type === "output" && event.truncated),
|
||||
).toBe(true);
|
||||
for (const stream of ["stdout", "stderr"])
|
||||
expect(
|
||||
diagnostics
|
||||
.filter((event) => event.type === "output" && event.stream === stream)
|
||||
.at(-1),
|
||||
).toMatchObject({ totalBytes: 70_000 });
|
||||
} finally {
|
||||
await supervisor.stop();
|
||||
await stopProviderProcessFixture(child);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { open, stat, type FileHandle } from "node:fs/promises";
|
||||
import { expect, it } from "vitest";
|
||||
import { observeSelectedExecutable } from "../../../src/process/capture/ProcessCaptureLifecycle.js";
|
||||
|
||||
it("cancels after real metadata IO without creating an already-aborted stream or leaking the file handle", async () => {
|
||||
const controller = new AbortController();
|
||||
let opened: FileHandle | undefined;
|
||||
await expect(
|
||||
observeSelectedExecutable(process.execPath, controller.signal, {
|
||||
async open(path, flags) {
|
||||
opened = await open(path, flags);
|
||||
return opened;
|
||||
},
|
||||
async stat(path) {
|
||||
const metadata = await stat(path, { bigint: true });
|
||||
controller.abort();
|
||||
return metadata;
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: "cancelled" });
|
||||
expect(opened?.fd).toBe(-1);
|
||||
});
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
/** Synthetic HAR 1.2 fixture with producer-declared sizes independent of Unicode content. */
|
||||
export const historicalHar = () => ({
|
||||
log: {
|
||||
version: "1.2",
|
||||
creator: { name: "rea-source-owned-fixture", version: "1" },
|
||||
entries: [
|
||||
{
|
||||
startedDateTime: "2026-10-07T13:00:00.123+08:00",
|
||||
time: 1.25,
|
||||
request: {
|
||||
method: "GET",
|
||||
url: "https://example.test/a?token=ordinary#fragment",
|
||||
httpVersion: "HTTP/2",
|
||||
cookies: [],
|
||||
headers: [],
|
||||
queryString: [],
|
||||
headersSize: -1,
|
||||
bodySize: 0,
|
||||
},
|
||||
response: {
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: "HTTP/2",
|
||||
cookies: [],
|
||||
headers: [],
|
||||
content: { size: 99, mimeType: "text/plain", text: "雪😀\r\n" },
|
||||
redirectURL: "",
|
||||
headersSize: -1,
|
||||
bodySize: 99,
|
||||
},
|
||||
cache: {},
|
||||
timings: { send: 0, wait: 1.25, receive: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user