Compare commits

..
Author SHA1 Message Date
morluto 78d4e2a1ba fix(captures): validate packet read scope before paging 2026-11-10 21:27:00 -05:00
8 changed files with 56 additions and 87 deletions

No files matched your search

@@ -175,27 +175,6 @@ describe("ESP flash layout inventory", () => {
});
});
it("inventories a zero-byte partition without reporting missing bytes", async () => {
const dump = espFlashDump({
bootloader: { at: 0, bytes: BOOTLOADER },
table: partitionTable([
...TWO_OTA_PARTITIONS,
{ label: "empty", type: 1, subtype: 0x82, offset: 0xa000, size: 0 },
]),
});
const snapshot = await scanCanonicalArtifactInventory(await writeDump(dump));
expect(snapshot.coverage.status).toBe("complete");
expect(
snapshot.occurrences.find(
({ logical_path }) => logical_path === "partitions/empty.bin",
),
).toMatchObject({
declared_size: 0,
limitations: ["partitions/empty.bin declares zero bytes."],
format_metadata: { flash_address: 0xa000, size: 0 },
});
});
describe("ESP flash layout coverage and selection", () => {
it("keeps usable partitions beside a truncated and a missing one", async () => {
const cut = DUMP.subarray(0, 0x2_8000);
+7 -9
View File
@@ -272,17 +272,15 @@ const regionEntry = (
declaredIntegrity: null,
unpacked: false,
limitations:
region.availability === "empty"
? [`${region.path} declares zero bytes.`]
: region.availability === "missing"
region.available === 0
? [
`${region.path} lies outside the dump: the file holds none of its ${String(region.length)} bytes.`,
]
: region.available < region.length
? [
`${region.path} lies outside the dump: the file holds none of its ${String(region.length)} bytes.`,
`${region.path} is truncated: the dump holds ${String(region.available)} of its ${String(region.length)} bytes.`,
]
: region.availability === "truncated"
? [
`${region.path} is truncated: the dump holds ${String(region.available)} of its ${String(region.length)} bytes.`,
]
: [],
: [],
adapterKey: `esp-flash-image:${region.path}`,
...(region.partition === undefined
? {}
+4 -1
View File
@@ -369,7 +369,10 @@ export class TsharkCaptureProvider implements PacketCapturePort {
resourcePath = "path" in input ? input.path : command;
// TShark resolves `-e` aliases before emitting canonical field names;
// the command arguments, not output names, own field selection.
const matchingPackets = parsePacketOutput(output.stdout.text);
const matchingPackets = parsePacketOutput(
output.stdout.text,
input.packet_limit,
);
const start = Math.min(input.match_offset, matchingPackets.length);
const end =
input.match_limit === null
+6 -1
View File
@@ -6,7 +6,7 @@ import { packetFieldsSchema } from "../domain/captures/packetCapture.js";
const producerSchema = z.array(
z.object({ _source: z.object({ layers: packetFieldsSchema }) }),
);
export const parsePacketOutput = (text: string) => {
export const parsePacketOutput = (text: string, packetLimit: number | null) => {
const decoded: unknown = JSON.parse(text);
const packets = producerSchema
.parse(decoded)
@@ -19,6 +19,11 @@ export const parsePacketOutput = (text: string) => {
"inspect_packet_capture",
"TShark returned unordered frames.",
);
if (packetLimit !== null && frame > BigInt(packetLimit))
throw new AnalysisOutputError(
"inspect_packet_capture",
"TShark returned a frame beyond the selected input packet limit.",
);
previous = frame;
}
return packets;
+4 -20
View File
@@ -38,8 +38,6 @@ export interface EspFlashRegion {
readonly fileOffset: number;
/** Bytes of the region the file holds, from `fileOffset`. */
readonly available: number;
/** An empty declaration has no bytes to be missing from the dump. */
readonly availability: "empty" | "missing" | "truncated" | "complete";
readonly partition: EspPartition | undefined;
}
@@ -119,21 +117,12 @@ const partitionPaths = (
const region = (
input: EspFlashPlanInput,
fields: Omit<EspFlashRegion, "fileOffset" | "available" | "availability">,
fields: Omit<EspFlashRegion, "fileOffset" | "available">,
): EspFlashRegion => {
const fileOffset = fields.flashAddress - input.origin.value;
const start = Math.max(0, fileOffset);
const end = Math.min(input.fileSize, fileOffset + fields.length);
const available = Math.max(0, end - start);
const availability =
fields.length === 0
? "empty"
: available === 0
? "missing"
: available < fields.length
? "truncated"
: "complete";
return { ...fields, fileOffset, available, availability };
return { ...fields, fileOffset, available: Math.max(0, end - start) };
};
const rangeText = (address: number, length: number): string =>
@@ -222,15 +211,11 @@ export const planEspFlashLayout = (input: EspFlashPlanInput): EspFlashPlan => {
limitations.push(
`Partition ${name} at ${offsetText(part.offset)} begins before the dump's first byte at flash ${offsetText(input.origin.value)}; it is not read.`,
);
else if (placed.availability === "empty")
limitations.push(
`Partition ${name} at ${offsetText(part.offset)} declares zero bytes.`,
);
else if (placed.availability === "missing")
else if (placed.available === 0)
limitations.push(
`Partition ${name} at ${rangeText(part.offset, part.size)} lies outside the dump, which ends at flash ${offsetText(input.origin.value + input.fileSize)}.`,
);
else if (placed.availability === "truncated")
else if (placed.available < part.size)
limitations.push(
`Partition ${name} at ${rangeText(part.offset, part.size)} is truncated: the dump holds ${String(placed.available)} of its ${String(part.size)} bytes.`,
);
@@ -283,7 +268,6 @@ const overlaps = (regions: readonly EspFlashRegion[]): string[] => {
// The region reaching furthest so far, so a long one shows every overlap.
let furthest: EspFlashRegion | undefined;
for (const current of ordered) {
if (current.availability === "empty") continue;
if (
furthest !== undefined &&
current.flashAddress < regionEnd(furthest) &&
-32
View File
@@ -179,38 +179,6 @@ describe("ESP flash layout plans", () => {
});
describe("ESP flash layout overlaps", () => {
it.each([
["inside another partition", 0xa000],
["at the end of the dump", 0x4_0000],
])(
"retains a zero-byte partition %s as an empty declaration",
(_, offset) => {
const plan = planEspFlashLayout(
input({
table: table([
{
label: "data",
type: 1,
subtype: 2,
offset: 0x9000,
size: 0x4000,
},
{ label: "empty", type: 1, subtype: 0x82, offset, size: 0 },
]),
}),
);
expect(plan.regions.at(-1)).toMatchObject({
path: "partitions/empty.bin",
fileOffset: offset,
length: 0,
available: 0,
});
expect(plan.limitations).toEqual([
`Partition empty at 0x${offset.toString(16)} declares zero bytes.`,
]);
},
);
it("reports every region inside a longer one", () => {
const plan = planEspFlashLayout(
input({
@@ -247,6 +247,26 @@ it("preserves TShark canonical output for a caller-selected field alias", async
expect(report.tool.arguments).toContain("bootp.type");
});
it("refuses producer frames outside the selected input read scope before paging", async () => {
const f = await fixture("many");
const request = { path: f.path, fields: ["ip.addr"], match_limit: 1 };
expect(
await f.service.inspect({ ...request, packet_limit: 10 }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError", operation: "inspect_packet_capture" },
});
const admitted = await f.service.inspect({ ...request, packet_limit: 90 });
if (!admitted.ok) throw admitted.error;
const report = packetCaptureSchema.parse(admitted.value.normalized_result);
expect(report.output_window).toEqual({
matching_packets: 90,
returned_packets: 1,
has_more: true,
});
expect(report.packets[0]?.["frame.number"]).toEqual(["1"]);
});
it("returns canonical alias output through the public packet-capture CLI", async () => {
const f = await fixture("alias-canonical");
const cli = Cli.create("capture-alias-test", { sync: false });
+15 -3
View File
@@ -17,7 +17,7 @@ it("preserves repeated field values and missing fields while discarding export i
},
{ _source: { layers: { "frame.number": ["7"] } } },
]);
expect(parsePacketOutput(output)).toEqual([
expect(parsePacketOutput(output, 7)).toEqual([
{ "frame.number": ["2"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
{ "frame.number": ["7"] },
]);
@@ -49,7 +49,7 @@ it.each([
])("rejects malformed producer fields: $layers", ({ layers, issue }) => {
let failure: unknown;
try {
parsePacketOutput(JSON.stringify([{ _source: { layers } }]));
parsePacketOutput(JSON.stringify([{ _source: { layers } }]), null);
} catch (error) {
failure = error;
}
@@ -72,6 +72,7 @@ it.each([
_source: { layers: { "frame.number": frame } },
})),
),
null,
);
} catch (error) {
failure = error;
@@ -88,7 +89,18 @@ it("preserves canonical field names emitted for a selected alias", () => {
},
},
]);
expect(parsePacketOutput(output)).toEqual([
expect(parsePacketOutput(output, null)).toEqual([
{ "frame.number": ["1"], "dhcp.type": ["1"] },
]);
});
it("validates every frame against the input read limit while allowing filtered gaps", () => {
const output = JSON.stringify(
[2, 7].map((frame) => ({
_source: { layers: { "frame.number": [String(frame)] } },
})),
);
expect(parsePacketOutput(output, 7)).toHaveLength(2);
expect(() => parsePacketOutput(output, 6)).toThrow(AnalysisOutputError);
expect(parsePacketOutput(output, null)).toHaveLength(2);
});