feat(captures): inspect recorded packets with bounded TShark delivery (#2318)
Inspect selected fields in existing captures through shared CLI/MCP Evidence. Page matching frames without changing dissection or two-pass read coverage; retain failed descriptor/process cleanup ownership and reject excess admission. Verified with real TShark 4.0.17 and 4.2.2, public Wireshark recordings, owned HTTP application traffic, real CLI/MCP workflows and schema checks. Co-authored-by: Olorinm <59321404+Olorinm@users.noreply.github.com> Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
|
||||
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const cleanup = vi.hoisted(() => ({
|
||||
path: "",
|
||||
denied: false,
|
||||
handles: [] as FileHandle[],
|
||||
}));
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...filesystem,
|
||||
open: async (...args: Parameters<typeof filesystem.open>) => {
|
||||
const handle = await filesystem.open(...args);
|
||||
if (args[0] === cleanup.path) {
|
||||
cleanup.handles.push(handle);
|
||||
const close = handle.close.bind(handle);
|
||||
handle.close = async () => {
|
||||
if (cleanup.denied && handle.fd >= 0)
|
||||
throw new Error("Descriptor close deliberately denied");
|
||||
await close();
|
||||
};
|
||||
}
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
it
|
||||
.runIf(process.platform === "linux")
|
||||
.each(["capture", "tool", "limiter", "kernel"])(
|
||||
"retains failed %s descriptors and retries them before further acquisition and shutdown",
|
||||
async (member) => {
|
||||
const directory = await createTestTempDirectory("rea-capture-descriptor-");
|
||||
const path = join(directory, "recording.pcap");
|
||||
const command = join(directory, "tshark.mjs");
|
||||
const limiter = join(directory, "limiter");
|
||||
await writeFile(path, "recording bytes");
|
||||
await writeFile(limiter, "limiter", { mode: 0o700 });
|
||||
await writeFile(
|
||||
command,
|
||||
`if(process.argv.includes('--version'))console.log('TShark (Wireshark) 4.0.17');else console.log('[{"_source":{"layers":{"frame.number":["1"]}}}]');`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
let launches = 0;
|
||||
const provider = new TsharkCaptureProvider(
|
||||
{
|
||||
...process.env,
|
||||
REA_TSHARK_COMMAND: command,
|
||||
REA_TSHARK_PRLIMIT_COMMAND: limiter,
|
||||
},
|
||||
(input) => {
|
||||
launches += 1;
|
||||
return spawnOwnedProviderProcess({
|
||||
...input,
|
||||
command: process.execPath,
|
||||
arguments: [command, ...input.arguments],
|
||||
expectedCommand: process.execPath,
|
||||
});
|
||||
},
|
||||
() => PrivateRuntimeRoot.create({ parent: directory }),
|
||||
);
|
||||
cleanup.path =
|
||||
member === "capture"
|
||||
? path
|
||||
: member === "tool"
|
||||
? command
|
||||
: member === "limiter"
|
||||
? limiter
|
||||
: "/proc/self/limits";
|
||||
cleanup.denied = true;
|
||||
cleanup.handles = [];
|
||||
onTestFinished(async () => {
|
||||
cleanup.denied = false;
|
||||
await provider.close();
|
||||
for (const handle of cleanup.handles) await handle.close();
|
||||
cleanup.path = "";
|
||||
});
|
||||
const service = new PacketCaptureService(provider);
|
||||
const first = await service.inspect({ path, fields: ["frame.number"] });
|
||||
expect(first).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
|
||||
});
|
||||
expect(cleanup.handles).toHaveLength(1);
|
||||
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
|
||||
const launchCount = launches;
|
||||
expect(
|
||||
await service.inspect({ path, fields: ["frame.number"] }),
|
||||
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
|
||||
expect(cleanup.handles).toHaveLength(1);
|
||||
expect(launches).toBe(launchCount);
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
cleanup.denied = false;
|
||||
await provider.close();
|
||||
expect(cleanup.handles[0]?.fd).toBe(-1);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,467 @@
|
||||
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
|
||||
import { it, expect, onTestFinished } from "vitest";
|
||||
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { readStableArtifact } from "../../../src/artifacts/readStableArtifact.js";
|
||||
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
|
||||
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
||||
import { packetCaptureSchema } from "../../../src/domain/captures/packetCapture.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { createDeferred } from "../../fixtures/binarySession.js";
|
||||
|
||||
// A command-boundary simulator: real process ownership/filesystem, not real TShark coverage.
|
||||
const fixture = async (mode = "ok", failCleanup = false) => {
|
||||
const directory = await createTestTempDirectory("rea-capture-test-");
|
||||
const path = join(directory, "recorded bytes.pcap");
|
||||
await writeFile(path, "recording bytes");
|
||||
const script = join(directory, "producer.mjs");
|
||||
await writeFile(
|
||||
script,
|
||||
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
|
||||
if (process.argv.includes('--version')) { console.log('TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
|
||||
else if (${JSON.stringify(mode)} === 'nonzero') { console.error('invalid decoder'); process.exitCode = 1; }
|
||||
else if (${JSON.stringify(mode)} === 'malformed-copy') { chmodSync('capture', 0o600); writeFileSync('capture', 'changed'); }
|
||||
else if (${JSON.stringify(mode)} === 'oversized-copy') { chmodSync('capture', 0o600); truncateSync('capture', 32 * 1024 * 1024 + 1); console.log('[]'); }
|
||||
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat(5 * 1024 * 1024));
|
||||
else if (${JSON.stringify(mode)} === 'wait') { console.log('ready'); setInterval(() => {}, 1000); }
|
||||
else if (${JSON.stringify(mode)} === 'invalid-json') console.log('not json');
|
||||
else if (${JSON.stringify(mode)} === 'many') console.log(JSON.stringify(Array.from({length:90},(_,i)=>({_source:{layers:{"frame.number":[String(i+1)],"ip.addr":["192.0.2.1"]}}}))));
|
||||
else { if(readFileSync('capture', 'utf8') !== 'recording bytes') throw Error('wrong copy'); console.log(JSON.stringify([{_source:{layers:{"frame.number":["1"],"ip.addr":["192.0.2.1","192.0.2.2"]}}}])); console.error('producer warning'); }
|
||||
`,
|
||||
);
|
||||
await chmod(script, 0o700);
|
||||
const configuredCommand =
|
||||
mode === "symlink" ? join(directory, "configured-tool") : script;
|
||||
if (mode === "symlink") await symlink(script, configuredCommand);
|
||||
const controller = new AbortController();
|
||||
let calls = 0;
|
||||
let mayClean = !failCleanup;
|
||||
const acquired = createDeferred<void>();
|
||||
const release = createDeferred<void>();
|
||||
const provider = new TsharkCaptureProvider(
|
||||
{
|
||||
...process.env,
|
||||
REA_TSHARK_COMMAND: configuredCommand,
|
||||
REA_TSHARK_PRLIMIT_COMMAND: configuredCommand,
|
||||
},
|
||||
async (input) => {
|
||||
calls++;
|
||||
if (mode === "file-limit" && !input.arguments.includes("--version")) {
|
||||
const stdout = { text: "", bytes: 0, observedBytes: 0 };
|
||||
const stderr = {
|
||||
text: "before file limit\n",
|
||||
bytes: 18,
|
||||
observedBytes: 18,
|
||||
};
|
||||
throw new OwnedCommandFailure("process", "Synthetic SIGXFSZ snapshot", {
|
||||
stdout,
|
||||
stderr,
|
||||
exitCode: null,
|
||||
signal: "SIGXFSZ",
|
||||
});
|
||||
}
|
||||
const spawned = await spawnOwnedProviderProcess({
|
||||
...input,
|
||||
command: process.execPath,
|
||||
arguments: [script, ...input.arguments],
|
||||
expectedCommand: process.execPath,
|
||||
});
|
||||
if (mode === "wait" && !input.arguments.includes("--version"))
|
||||
spawned.process.stdout?.once("data", () => controller.abort());
|
||||
return spawned;
|
||||
},
|
||||
async () => {
|
||||
if (mode === "workspace-full")
|
||||
throw Object.assign(new Error("No space left on device"), {
|
||||
code: "ENOSPC",
|
||||
});
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
parent: directory,
|
||||
prefix: "decoder-",
|
||||
});
|
||||
if (mode === "gated") {
|
||||
acquired.resolve();
|
||||
await release.promise;
|
||||
}
|
||||
if (mode === "snapshot-write-failure")
|
||||
await writeFile(join(root.path, "capture"), "existing");
|
||||
return {
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (!mayClean) throw new Error("cleanup fixture failure");
|
||||
await root.close();
|
||||
},
|
||||
};
|
||||
},
|
||||
"linux",
|
||||
async (...args) => {
|
||||
if (mode === "oversized-tool" && calls === 2 && args[0] === script) {
|
||||
const { truncate } = await import("node:fs/promises");
|
||||
await truncate(script, 64 * 1024 * 1024 + 1);
|
||||
}
|
||||
if (mode === "post-run-abort" && calls === 2) controller.abort();
|
||||
return readStableArtifact(...args);
|
||||
},
|
||||
async (limits) => ({ ...limits, file_bytes: 1048576 }),
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
release.resolve();
|
||||
mayClean = true;
|
||||
await provider.close();
|
||||
});
|
||||
const service = new PacketCaptureService(provider);
|
||||
return {
|
||||
service,
|
||||
directory,
|
||||
path,
|
||||
controller,
|
||||
calls: () => calls,
|
||||
acquired: acquired.promise,
|
||||
release: () => release.resolve(),
|
||||
allowCleanup: () => {
|
||||
mayClean = true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("refuses new acquisition after provider shutdown", async () => {
|
||||
const f = await fixture();
|
||||
await f.service.close();
|
||||
expect(
|
||||
await f.service.inspect({ path: f.path, fields: ["ip.addr"] }),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(f.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it("pages matching observations without changing dissection scope or frame identities", async () => {
|
||||
const f = await fixture("many");
|
||||
const input = { path: f.path, fields: ["ip.addr"] };
|
||||
for (const [options, first, count] of [
|
||||
[{}, 1, 50],
|
||||
[{ match_offset: 50, match_limit: 30 }, 51, 30],
|
||||
[{ match_limit: null }, 1, 90],
|
||||
[{ match_offset: 100 }, undefined, 0],
|
||||
] as const) {
|
||||
const result = await f.service.inspect({ ...input, ...options });
|
||||
if (!result.ok) throw result.error;
|
||||
const report = packetCaptureSchema.parse(result.value.normalized_result);
|
||||
expect(report.packets).toHaveLength(count);
|
||||
expect(report.packets[0]?.["frame.number"][0]).toBe(
|
||||
first === undefined ? undefined : String(first),
|
||||
);
|
||||
expect(report.output_window.matching_packets).toBe(90);
|
||||
expect(report.output_window.returned_packets).toBe(count);
|
||||
expect(report.read_scope).toBe("to-eof");
|
||||
expect(report.tool.arguments).not.toContain("-c");
|
||||
}
|
||||
});
|
||||
|
||||
it("bounds admission without queuing additional snapshots or delaying cancellation", async () => {
|
||||
const f = await fixture("gated");
|
||||
const input = { path: f.path, fields: ["ip.addr"] };
|
||||
const first = f.service.inspect(input);
|
||||
await f.acquired;
|
||||
const second = f.service.inspect(input);
|
||||
const cancelled = f.service.inspect(input, { signal: AbortSignal.abort() });
|
||||
f.release();
|
||||
expect(await first).toMatchObject({ ok: true });
|
||||
expect(await second).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisResourceConstraintError", resource: "capacity" },
|
||||
});
|
||||
expect(await cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(f.calls()).toBe(2);
|
||||
expect(await f.service.inspect(input)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("inspects an immutable copy, preserves options and warnings, and releases its directory", async () => {
|
||||
const f = await fixture();
|
||||
const result = await f.service.inspect({
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
display_filter: "udp",
|
||||
packet_limit: 10,
|
||||
decode_as: ["udp.port==5555,dns"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const report = packetCaptureSchema.parse(result.value.normalized_result);
|
||||
expect(report.packets).toEqual([
|
||||
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
]);
|
||||
expect(report.diagnostics).toBe("producer warning\n");
|
||||
expect(report.tool.version_diagnostics).toBe("version warning\n");
|
||||
expect(report.read_scope).toBe("up-to-input-packet-limit");
|
||||
expect(report.tool.arguments).toEqual([
|
||||
"-n",
|
||||
"-r",
|
||||
"capture",
|
||||
"-T",
|
||||
"json",
|
||||
"--no-duplicate-keys",
|
||||
"--temp-dir=.",
|
||||
"-2",
|
||||
"-c",
|
||||
"10",
|
||||
"-Y",
|
||||
"udp",
|
||||
"-d",
|
||||
"udp.port==5555,dns",
|
||||
"-e",
|
||||
"frame.number",
|
||||
"-e",
|
||||
"ip.addr",
|
||||
]);
|
||||
expect((await readdir(f.directory)).sort()).toEqual([
|
||||
"producer.mjs",
|
||||
"recorded bytes.pcap",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid-json", "AnalysisOutputError"],
|
||||
["nonzero", "ProviderAdapterError"],
|
||||
["malformed-copy", "AnalysisArtifactChangedError"],
|
||||
["overflow", "AnalysisResourceConstraintError"],
|
||||
["wait", "AnalysisCancelledError"],
|
||||
])(
|
||||
"preserves %s failure and releases the process and snapshot",
|
||||
async (mode, tag) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspect(
|
||||
{ path: f.path, fields: ["ip.addr"] },
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected capture analysis failure");
|
||||
expect(result.error._tag).toBe(tag);
|
||||
expect(result.error.cleanupIncomplete).toBe(false);
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) =>
|
||||
name.startsWith("decoder-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains a completed observation and cleanup ownership for retry", async () => {
|
||||
const f = await fixture("ok", true);
|
||||
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
if (result.ok) throw new Error("Expected cleanup failure");
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
operation: "inspect_packet_capture",
|
||||
});
|
||||
const retry = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
expect(retry.ok).toBe(false);
|
||||
expect(f.calls()).toBe(2);
|
||||
f.allowCleanup();
|
||||
await f.service.close();
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects cancelled and invalid requests before any provider work", async () => {
|
||||
const f = await fixture();
|
||||
for (const input of [
|
||||
{ path: "relative.pcap", fields: ["ip.addr"] },
|
||||
{ path: f.path, fields: ["ip.addr"], interface: "lo0" },
|
||||
]) {
|
||||
const result = await f.service.inspect(input);
|
||||
expect(result.ok).toBe(false);
|
||||
}
|
||||
const result = await f.service.inspect(
|
||||
{ path: f.path, fields: ["ip.addr"] },
|
||||
{ signal: AbortSignal.abort() },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(f.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it("retains a completed observation when cancellation arrives at the service boundary", async () => {
|
||||
const f = await fixture();
|
||||
const input = {
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
display_filter: null,
|
||||
decode_as: [],
|
||||
packet_limit: null,
|
||||
two_pass: true,
|
||||
match_offset: 0,
|
||||
match_limit: 50,
|
||||
};
|
||||
const execution = await f.service.provider.inspect(input);
|
||||
if (!execution.ok) throw execution.error;
|
||||
const service = new PacketCaptureService({
|
||||
inspect: async () => {
|
||||
f.controller.abort();
|
||||
return execution;
|
||||
},
|
||||
close: async () => {},
|
||||
});
|
||||
const result = await service.inspect(input, { signal: f.controller.signal });
|
||||
if (result.ok) throw new Error("Expected late cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
operation: "inspect_packet_capture",
|
||||
normalized_result: {
|
||||
packets: [
|
||||
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["workspace-full", "AnalysisResourceConstraintError"],
|
||||
["snapshot-write-failure", "ProviderAdapterError"],
|
||||
])(
|
||||
"reports %s against the private workspace, not the selected input",
|
||||
async (mode, tag) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspect({
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
});
|
||||
if (result.ok) throw new Error("Expected workspace failure");
|
||||
expect(result.error._tag).toBe(tag);
|
||||
if (result.error._tag === "ProviderAdapterError")
|
||||
expect(result.error).toMatchObject({
|
||||
diagnostics: {
|
||||
stage: "workspace",
|
||||
system_code: "EEXIST",
|
||||
},
|
||||
});
|
||||
if (result.error._tag === "AnalysisResourceConstraintError")
|
||||
expect(result.error).toMatchObject({
|
||||
reportedLimits: {
|
||||
system_code: "ENOSPC",
|
||||
},
|
||||
});
|
||||
expect(f.calls()).toBe(mode === "workspace-full" ? 0 : 1);
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) =>
|
||||
name.startsWith("decoder-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses unsupported hosts before launching or allocating a workspace", async () => {
|
||||
const provider = new TsharkCaptureProvider(
|
||||
{ REA_TSHARK_COMMAND: process.execPath },
|
||||
async () => {
|
||||
throw new Error("Must not launch");
|
||||
},
|
||||
async () => {
|
||||
throw new Error("Must not allocate");
|
||||
},
|
||||
"darwin",
|
||||
);
|
||||
const result = await new PacketCaptureService(provider).inspect({
|
||||
path: "/recording.pcap",
|
||||
fields: ["ip.addr"],
|
||||
});
|
||||
if (result.ok) throw new Error("Expected host refusal");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("Linux"),
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves complete Evidence when aborted during post-run integrity checks", async () => {
|
||||
const f = await fixture("post-run-abort");
|
||||
const result = await f.service.inspect(
|
||||
{ path: f.path, fields: ["ip.addr"] },
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected late cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
normalized_result: {
|
||||
packets: [
|
||||
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
],
|
||||
diagnostics: "producer warning\n",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
|
||||
).toEqual([]);
|
||||
});
|
||||
it("preserves configured symlink paths separately from resolved tool identities", async () => {
|
||||
const f = await fixture("symlink");
|
||||
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
tool: {
|
||||
configured_path: join(f.directory, "configured-tool"),
|
||||
path: join(f.directory, "producer.mjs"),
|
||||
},
|
||||
resource_limiter: {
|
||||
configured_path: join(f.directory, "configured-tool"),
|
||||
path: join(f.directory, "producer.mjs"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["oversized-copy", "oversized-tool"])(
|
||||
"identifies the mutated %s without blaming the admitted source",
|
||||
async (mode) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspect({
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
});
|
||||
if (result.ok) throw new Error("Expected changed artifact");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisArtifactChangedError",
|
||||
path:
|
||||
mode === "oversized-tool"
|
||||
? join(f.directory, "producer.mjs")
|
||||
: expect.stringMatching(/decoder-.*[/\\]capture$/u),
|
||||
});
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) =>
|
||||
name.startsWith("decoder-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
},
|
||||
);
|
||||
it("preserves termination signal and effective file ceiling as a resource failure", async () => {
|
||||
const f = await fixture("file-limit");
|
||||
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
if (result.ok) throw new Error("Expected resource failure");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
resource: "file-size",
|
||||
reportedLimits: { file_bytes: 1048576 },
|
||||
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects oversized selector lists and UTF-8 argv expansion before provider work", async () => {
|
||||
const f = await fixture();
|
||||
for (const selections of [
|
||||
{ fields: Array.from({ length: 1025 }, () => "ip.addr") },
|
||||
{ fields: ["x".repeat(8193)] },
|
||||
{ fields: ["x".repeat(8192)], display_filter: "界".repeat(8192) },
|
||||
{
|
||||
fields: ["ip.addr"],
|
||||
decode_as: Array.from({ length: 1025 }, () => "udp.port==5555,dns"),
|
||||
},
|
||||
]) {
|
||||
const result = await f.service.inspect({ path: f.path, ...selections });
|
||||
if (result.ok) throw new Error("Expected invalid selectors");
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
}
|
||||
expect(f.calls()).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { parsePacketOutput } from "../../../src/captures/parsePacketOutput.js";
|
||||
|
||||
it("preserves repeated field values and missing fields while discarding export index metadata", () => {
|
||||
const output = JSON.stringify([
|
||||
{
|
||||
_index: "packets-2026",
|
||||
_score: null,
|
||||
_source: {
|
||||
layers: {
|
||||
"frame.number": ["2"],
|
||||
"ip.addr": ["192.0.2.1", "192.0.2.2"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ _source: { layers: { "frame.number": ["7"] } } },
|
||||
]);
|
||||
expect(parsePacketOutput(output, ["ip.addr"])).toEqual([
|
||||
{ "frame.number": ["2"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
{ "frame.number": ["7"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(
|
||||
[
|
||||
[{ "ip.addr": ["192.0.2.1"] }],
|
||||
[{ "frame.number": ["1"], "ip.addr": "192.0.2.1" }],
|
||||
[{ "frame.number": ["0"] }],
|
||||
[{ "frame.number": ["1", "2"] }],
|
||||
[{ "frame.number": ["1"], "unselected.field": ["hidden"] }],
|
||||
[{ "frame.number": ["2"] }, { "frame.number": ["2"] }],
|
||||
[{ "frame.number": ["2"] }, { "frame.number": ["1"] }],
|
||||
].map((layers) => [layers]),
|
||||
)("rejects malformed, repeated or reordered producer frames: %j", (layers) => {
|
||||
expect(() =>
|
||||
parsePacketOutput(
|
||||
JSON.stringify(layers.map((value) => ({ _source: { layers: value } }))),
|
||||
["ip.addr"],
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
|
||||
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
// Real kernel-limit verification with a synthetic producer; real TShark has its own verifier.
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"enforces both address-space limits before any producer allocation",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-tshark-limits-");
|
||||
const command = join(directory, "memory-probe");
|
||||
await writeFile(
|
||||
command,
|
||||
`#!/usr/bin/python3
|
||||
import json, resource, sys
|
||||
assert resource.getrlimit(resource.RLIMIT_AS) == (1073741824, 1073741824)
|
||||
assert resource.getrlimit(resource.RLIMIT_FSIZE) == (67108864, 67108864)
|
||||
assert resource.getrlimit(resource.RLIMIT_CORE) == (0, 0)
|
||||
if '--version' in sys.argv:
|
||||
print('TShark (Wireshark) 4.6.9 (resource fixture)')
|
||||
else:
|
||||
try:
|
||||
bytearray(1073741825)
|
||||
except MemoryError:
|
||||
print(json.dumps([{'_source': {'layers': {'frame.number': ['1']}}}]))
|
||||
else:
|
||||
raise RuntimeError('allocation unexpectedly succeeded')
|
||||
`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
const path = join(directory, "recording.pcap");
|
||||
await writeFile(path, "selected fixture");
|
||||
const service = new PacketCaptureService(
|
||||
new TsharkCaptureProvider({
|
||||
...process.env,
|
||||
REA_TSHARK_COMMAND: command,
|
||||
}),
|
||||
);
|
||||
onTestFinished(() => service.close());
|
||||
const result = await service.inspect({ path, fields: ["frame.number"] });
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
packets: [{ "frame.number": ["1"] }],
|
||||
limits: { address_space_bytes: 1073741824 },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"preserves lower inherited file/CPU limits in the real launch",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-tshark-inherited-limits-",
|
||||
);
|
||||
const command = join(directory, "limit-probe");
|
||||
const path = join(directory, "recording.pcap");
|
||||
await writeFile(path, "selected fixture");
|
||||
await writeFile(
|
||||
command,
|
||||
`#!/usr/bin/python3
|
||||
import json, resource, sys
|
||||
assert resource.getrlimit(resource.RLIMIT_FSIZE) == (1048576, 1048576)
|
||||
assert resource.getrlimit(resource.RLIMIT_CPU) == (20, 20)
|
||||
if '--version' in sys.argv:
|
||||
print('TShark (Wireshark) 4.6.9 (resource fixture)')
|
||||
else:
|
||||
print(json.dumps([{'_source': {'layers': {'frame.number': ['1']}}}]))
|
||||
`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
const runner = join(directory, "runner.mjs");
|
||||
const serviceModule = new URL(
|
||||
"../../../dist/application/captures/PacketCaptureService.js",
|
||||
import.meta.url,
|
||||
).href;
|
||||
const providerModule = new URL(
|
||||
"../../../dist/captures/TsharkCaptureProvider.js",
|
||||
import.meta.url,
|
||||
).href;
|
||||
await writeFile(
|
||||
runner,
|
||||
`import { PacketCaptureService } from ${JSON.stringify(serviceModule)};
|
||||
import { TsharkCaptureProvider } from ${JSON.stringify(providerModule)};
|
||||
const service = new PacketCaptureService(new TsharkCaptureProvider({ ...process.env, REA_TSHARK_COMMAND: ${JSON.stringify(command)} }));
|
||||
try {
|
||||
const result = await service.inspect({ path: ${JSON.stringify(path)}, fields: ['frame.number'] });
|
||||
if (!result.ok) throw result.error;
|
||||
console.log(JSON.stringify(result.value.normalized_result.limits));
|
||||
} finally { await service.close(); }
|
||||
`,
|
||||
);
|
||||
const { stdout } = await promisify(execFile)(
|
||||
"/usr/bin/prlimit",
|
||||
[
|
||||
"--fsize=1048576:2097152",
|
||||
"--cpu=20:25",
|
||||
"--",
|
||||
process.execPath,
|
||||
runner,
|
||||
],
|
||||
{ timeout: 30000, maxBuffer: 65536 },
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
file_bytes: 1048576,
|
||||
cpu_seconds: 20,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"reports a real kernel file-limit termination with its effective ceiling",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-tshark-file-limit-");
|
||||
const command = join(directory, "file-probe");
|
||||
const path = join(directory, "recording.pcap");
|
||||
await writeFile(path, "selected fixture");
|
||||
await writeFile(
|
||||
command,
|
||||
`#!/usr/bin/python3
|
||||
import signal, sys
|
||||
if '--version' in sys.argv:
|
||||
print('TShark (Wireshark) 4.6.9 (resource fixture)')
|
||||
else:
|
||||
signal.signal(signal.SIGXFSZ, signal.SIG_DFL)
|
||||
print('before file limit', file=sys.stderr, flush=True)
|
||||
with open('overflow', 'wb', buffering=0) as output:
|
||||
output.write(b'x' * 4096)
|
||||
output.write(b'x')
|
||||
`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
const service = new PacketCaptureService(
|
||||
new TsharkCaptureProvider(
|
||||
{ ...process.env, REA_TSHARK_COMMAND: command },
|
||||
undefined,
|
||||
undefined,
|
||||
process.platform,
|
||||
undefined,
|
||||
async (limits) => ({ ...limits, file_bytes: 4096 }),
|
||||
),
|
||||
);
|
||||
onTestFinished(() => service.close());
|
||||
const result = await service.inspect({ path, fields: ["frame.number"] });
|
||||
if (result.ok) throw new Error("Expected file-limit failure");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
resource: "file-size",
|
||||
reportedLimits: { file_bytes: 4096 },
|
||||
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,157 @@
|
||||
import { Cli } from "incur";
|
||||
import { expect, it } from "vitest";
|
||||
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
|
||||
it.each([false, true])(
|
||||
"awaits cleanup retry and preserves completed output when retry failure is %s",
|
||||
async (failAgain) => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Completed capture fixture", version: "1" },
|
||||
{
|
||||
operation: "inspect_packet_capture",
|
||||
parameters: {},
|
||||
result: { packets: [{ "frame.number": ["1"] }] },
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
const original = new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
["original-workspace"],
|
||||
{ reason: "original cleanup failure" },
|
||||
{ operation: "inspect_packet_capture", partialObservation: evidence },
|
||||
);
|
||||
let closed = false;
|
||||
const cli = Cli.create("capture-cleanup-test", { sync: false });
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspect: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
closed = true;
|
||||
if (failAgain)
|
||||
throw new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
["retry-workspace"],
|
||||
{ reason: "retry failed" },
|
||||
{ operation: "inspect_packet_capture" },
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
expect(closed).toBe(true);
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
partial_observation: evidence,
|
||||
resources: expect.arrayContaining(["original-workspace"]),
|
||||
},
|
||||
});
|
||||
if (failAgain)
|
||||
expect(output).toMatchObject({
|
||||
details: { resources: expect.arrayContaining(["retry-workspace"]) },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
|
||||
const cli = Cli.create("capture-selector-test", { sync: false });
|
||||
let called = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"x".repeat(8192),
|
||||
"--display_filter",
|
||||
"界".repeat(8192),
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain("32 KiB");
|
||||
});
|
||||
|
||||
it("rejects conflicting output options before the CLI invokes its service", async () => {
|
||||
const cli = Cli.create("capture-window-test", { sync: false });
|
||||
let called = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--all_matches",
|
||||
"--match_limit",
|
||||
"20",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain("mutually exclusive");
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
|
||||
it("advertises valid target-free packet capture schemas and actionable missing-tool diagnostics", async () => {
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const tool = (await harness.client.listTools()).tools.find(
|
||||
({ name }) => name === "inspect_packet_capture",
|
||||
);
|
||||
if (tool?.outputSchema === undefined) throw new Error("Capture tool missing");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = tool.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = tool.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
const input = {
|
||||
path:
|
||||
process.platform === "win32" ? "C:\\recording.pcap" : "/recording.pcap",
|
||||
fields: ["ip.addr"],
|
||||
};
|
||||
expect(ajv.validate(inputSchema, input)).toBe(true);
|
||||
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(false);
|
||||
const result = await harness.client.callTool({
|
||||
name: tool.name,
|
||||
arguments: input,
|
||||
});
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
operation: tool.name,
|
||||
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
|
||||
},
|
||||
},
|
||||
});
|
||||
await harness.client.ping();
|
||||
});
|
||||
|
||||
it.each(["cancelled", "cleanup"])(
|
||||
"retains completed Evidence after %s failure",
|
||||
async (kind) => {
|
||||
const input = {
|
||||
path:
|
||||
process.platform === "win32" ? "C:\\recording.pcap" : "/recording.pcap",
|
||||
fields: ["ip.addr"],
|
||||
};
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Completed capture fixture", version: "1" },
|
||||
{
|
||||
operation: "inspect_packet_capture",
|
||||
parameters: input,
|
||||
result: { packets: [{ "frame.number": ["1"] }] },
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
const failure =
|
||||
kind === "cancelled"
|
||||
? new AnalysisCancelledError("inspect_packet_capture", {
|
||||
partialObservation: evidence,
|
||||
})
|
||||
: new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
["private-workspace"],
|
||||
{},
|
||||
{
|
||||
operation: "inspect_packet_capture",
|
||||
partialObservation: evidence,
|
||||
},
|
||||
);
|
||||
const packetCapture = new PacketCaptureService({
|
||||
inspect: async () => err(failure),
|
||||
close: async () => {},
|
||||
});
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { packetCapture },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const response = await harness.client.callTool({
|
||||
name: "inspect_packet_capture",
|
||||
arguments: input,
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response)).toMatchObject({
|
||||
error: {
|
||||
details: {
|
||||
partial_observation: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: evidence.evidence_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const bundle = await harness.client.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(bundle.isError).not.toBe(true);
|
||||
expect(JSON.stringify(bundle.structuredContent)).toContain(
|
||||
evidence.evidence_id,
|
||||
);
|
||||
expect(harness.session.evidenceById(evidence.evidence_id)).toEqual(
|
||||
evidence,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects oversized selector expansion through the MCP boundary before invoking the provider", async () => {
|
||||
let calls = 0;
|
||||
const packetCapture = new PacketCaptureService({
|
||||
inspect: async () => {
|
||||
calls++;
|
||||
return err(new AnalysisCancelledError("inspect_packet_capture"));
|
||||
},
|
||||
close: async () => {},
|
||||
});
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { packetCapture },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const response = await harness.client.callTool({
|
||||
name: "inspect_packet_capture",
|
||||
arguments: {
|
||||
path:
|
||||
process.platform === "win32" ? "C:\\recording.pcap" : "/recording.pcap",
|
||||
fields: ["x".repeat(8192)],
|
||||
display_filter: "界".repeat(8192),
|
||||
},
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(JSON.stringify(response)).toContain("32 KiB");
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
Reference in New Issue
Block a user