feat(captures): discover installed protocol and field definitions (#2496)
* feat(captures): discover installed protocol and field definitions * test(captures): isolate the direct glossary oracle profile * test(captures): accept padded kernel limit reports * fix(captures): detach every retained glossary column * fix(captures): describe every field discovery CLI option * fix(captures): retain discovery operation across cleanup retries --------- Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { packetFieldsCatalogSchema } from "../../../src/domain/captures/packetFields.js";
|
||||
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
|
||||
import { it, expect, onTestFinished } from "vitest";
|
||||
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
|
||||
@@ -20,14 +21,15 @@ const fixture = async (mode = "ok", failCleanup = false) => {
|
||||
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'); }
|
||||
if (process.argv.includes('--version')) { console.log(${JSON.stringify(mode)} === 'bad-version' ? 'TShark (Wireshark) 3.0.0' : '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)} === 'overflow') process.stdout.write('x'.repeat((process.argv.includes('-G') ? 33 : 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 (process.argv.includes('-G')) { console.log('P\\tUniversal Serial Bus\\tusb\\nF\\tVendor ID\\tusb.idVendor\\tFT_UINT16\\tusb\\tBASE_HEX\\t0x0\\t\\nF\\tOther Vendor\\tusb.idVendor\\tFT_UINT32\\tusb\\tBASE_HEX\\t0x0\\tSecond registration\\nP\\tInternet Protocol\\tip\\nF\\tAddress\\tip.addr\\tFT_IPv4\\tip\\t\\t0x0\\tSource or destination'); console.error('glossary warning'); }
|
||||
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'); }
|
||||
`,
|
||||
);
|
||||
@@ -301,6 +303,9 @@ it("retains a completed observation when cancellation arrives at the service bou
|
||||
const execution = await f.service.provider.inspect(input);
|
||||
if (!execution.ok) throw execution.error;
|
||||
const service = new PacketCaptureService({
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
f.controller.abort();
|
||||
return execution;
|
||||
@@ -465,3 +470,158 @@ it("rejects oversized selector lists and UTF-8 argv expansion before provider wo
|
||||
}
|
||||
expect(f.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it("discovers installed protocols and field definitions without a capture", async () => {
|
||||
const f = await fixture();
|
||||
for (const [input, expected] of [
|
||||
[
|
||||
{ query: "USB" },
|
||||
{
|
||||
records: [{ abbreviation: "usb", kind: "protocol", field_type: null }],
|
||||
output_window: { examined: 2, matching: 1, returned: 1 },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ kind: "fields", protocol: "usb", limit: 1 },
|
||||
{
|
||||
records: [
|
||||
{
|
||||
abbreviation: "usb.idVendor",
|
||||
field_type: "FT_UINT16",
|
||||
source_line: 2,
|
||||
},
|
||||
],
|
||||
output_window: {
|
||||
examined: 3,
|
||||
matching: 2,
|
||||
returned: 1,
|
||||
has_more: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{ kind: "fields", protocol: "usb", offset: 1, limit: null },
|
||||
{
|
||||
records: [
|
||||
{
|
||||
abbreviation: "usb.idVendor",
|
||||
field_type: "FT_UINT32",
|
||||
source_line: 3,
|
||||
},
|
||||
],
|
||||
output_window: { matching: 2, returned: 1, has_more: false },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ kind: "fields", query: "destination" },
|
||||
{
|
||||
records: [
|
||||
{
|
||||
abbreviation: "ip.addr",
|
||||
description: "Source or destination",
|
||||
display_base: "",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
{ query: "no-such-protocol" },
|
||||
{ records: [], output_window: { matching: 0, returned: 0 } },
|
||||
],
|
||||
] as const) {
|
||||
const result = await f.service.inspectFields(input);
|
||||
if (!result.ok) throw result.error;
|
||||
const report = packetFieldsCatalogSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
expect(report).toMatchObject(expected);
|
||||
expect(report.tool.arguments).toEqual(["-G", "fields"]);
|
||||
expect(report.tool.version_diagnostics).toBe("version warning\n");
|
||||
expect(report.diagnostics).toBe("glossary warning\n");
|
||||
expect(report.limits.output_bytes).toBe(32 * 1024 * 1024);
|
||||
}
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("shares discovery admission with inspection and refuses work after shutdown", async () => {
|
||||
const f = await fixture("gated");
|
||||
const active = f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
await f.acquired;
|
||||
const busy = await f.service.inspectFields({});
|
||||
f.release();
|
||||
if (!(await active).ok) throw new Error("Inspection failed");
|
||||
expect(busy).toMatchObject({
|
||||
ok: false,
|
||||
error: { operation: "inspect_packet_fields", resource: "capacity" },
|
||||
});
|
||||
await f.service.close();
|
||||
expect(await f.service.inspectFields({})).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
operation: "inspect_packet_fields",
|
||||
_tag: "AnalysisCancelledError",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
"bad-version",
|
||||
"nonzero",
|
||||
"overflow",
|
||||
"wait",
|
||||
"oversized-tool",
|
||||
"invalid-json",
|
||||
])("retains field discovery failure facts: %s", async (mode) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspectFields(
|
||||
{},
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected failure");
|
||||
expect(result.error).toMatchObject({ operation: "inspect_packet_fields" });
|
||||
if (mode === "bad-version")
|
||||
expect(result.error.capturedOutput).toMatchObject({
|
||||
stdout: "TShark (Wireshark) 3.0.0\n",
|
||||
stderr: "version warning\n",
|
||||
});
|
||||
if (mode === "invalid-json")
|
||||
expect(result.error.capturedOutput?.stdout).toBe("not json\n");
|
||||
if (mode === "overflow")
|
||||
expect(result.error).toMatchObject({
|
||||
resource: "memory",
|
||||
reportedLimits: { output_bytes: 32 * 1024 * 1024 },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains completed discovery on late cancellation and cleanup failure", async () => {
|
||||
for (const mode of ["post-run-abort", "cleanup"]) {
|
||||
const f = await fixture(mode, mode === "cleanup");
|
||||
const result = await f.service.inspectFields(
|
||||
{ query: "usb" },
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
partialObservation: {
|
||||
operation: "inspect_packet_fields",
|
||||
normalized_result: { records: [{ abbreviation: "usb" }] },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (mode === "cleanup") {
|
||||
await f.service.inspectFields({});
|
||||
await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
expect(f.calls()).toBe(2);
|
||||
for (let attempt = 0; attempt < 2; attempt++)
|
||||
await expect(f.service.close()).rejects.toMatchObject({
|
||||
operation: "inspect_packet_fields",
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
}
|
||||
f.allowCleanup();
|
||||
await f.service.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { inspectPacketFieldsInputSchema } from "../../../src/domain/captures/packetFields.js";
|
||||
import { parseFieldDiscovery } from "../../../src/captures/parseFieldDiscovery.js";
|
||||
|
||||
it("keeps duplicate registrations and source ordinals instead of overwriting abbreviations", () => {
|
||||
const text =
|
||||
"P\tUSB\tusb\r\nF\tVendor\tusb.idVendor\tFT_UINT16\tusb\tBASE_HEX\t0x0\t\r\nF\tVendor\tusb.idVendor\tFT_UINT32\tusb\tBASE_HEX\t0x0\t";
|
||||
const result = parseFieldDiscovery(
|
||||
text,
|
||||
inspectPacketFieldsInputSchema.parse({
|
||||
kind: "fields",
|
||||
query: "idVendor",
|
||||
offset: 1,
|
||||
}),
|
||||
);
|
||||
expect(result.records).toMatchObject([
|
||||
{
|
||||
source_line: 3,
|
||||
abbreviation: "usb.idVendor",
|
||||
field_type: "FT_UINT32",
|
||||
description: "",
|
||||
},
|
||||
]);
|
||||
expect(result.output_window).toEqual({
|
||||
examined: 2,
|
||||
matching: 2,
|
||||
returned: 1,
|
||||
has_more: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects damaged records even outside the selected page", () => {
|
||||
for (const text of [
|
||||
"",
|
||||
"P\tmissing",
|
||||
"F\tname\tabbr",
|
||||
"P\tname\t",
|
||||
"P\tUSB\tusb\nBAD",
|
||||
])
|
||||
expect(() =>
|
||||
parseFieldDiscovery(
|
||||
text,
|
||||
inspectPacketFieldsInputSchema.parse({ limit: 1 }),
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("bounds explicit full-result expansion while allowing a page from the same large glossary", () => {
|
||||
const text = "P\t" + "Long name ".repeat(30) + "\tabbr\n";
|
||||
const glossary = text.repeat(6000);
|
||||
expect(() =>
|
||||
parseFieldDiscovery(
|
||||
glossary,
|
||||
inspectPacketFieldsInputSchema.parse({ limit: null }),
|
||||
),
|
||||
).toThrow("representation budget");
|
||||
const result = parseFieldDiscovery(
|
||||
glossary,
|
||||
inspectPacketFieldsInputSchema.parse({ offset: 5999, limit: 1 }),
|
||||
);
|
||||
expect(result.output_window).toEqual({
|
||||
examined: 6000,
|
||||
matching: 6000,
|
||||
returned: 1,
|
||||
has_more: false,
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,9 @@ it.each([false, true])(
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
@@ -87,6 +90,9 @@ it("rejects an oversized selector budget before the CLI invokes its service", as
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
@@ -125,6 +131,9 @@ it("rejects conflicting output options before the CLI invokes its service", asyn
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
|
||||
@@ -8,42 +8,53 @@ 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"),
|
||||
it.each(["inspect_packet_capture", "inspect_packet_fields"])(
|
||||
"advertises valid target-free schemas and missing-tool diagnostics: %s",
|
||||
async (name) => {
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const tool = (await harness.client.listTools()).tools.find(
|
||||
(tool) => tool.name === name,
|
||||
);
|
||||
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 =
|
||||
name === "inspect_packet_fields"
|
||||
? { query: "usb" }
|
||||
: {
|
||||
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();
|
||||
});
|
||||
});
|
||||
await harness.client.ping();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["cancelled", "cleanup"])(
|
||||
"retains completed Evidence after %s failure",
|
||||
@@ -78,6 +89,9 @@ it.each(["cancelled", "cleanup"])(
|
||||
},
|
||||
);
|
||||
const packetCapture = new PacketCaptureService({
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => err(failure),
|
||||
close: async () => {},
|
||||
});
|
||||
@@ -120,6 +134,9 @@ it.each(["cancelled", "cleanup"])(
|
||||
it("rejects oversized selector expansion through the MCP boundary before invoking the provider", async () => {
|
||||
let calls = 0;
|
||||
const packetCapture = new PacketCaptureService({
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
calls++;
|
||||
return err(new AnalysisCancelledError("inspect_packet_capture"));
|
||||
|
||||
Reference in New Issue
Block a user