fix(erlang): require complete positional BEAM reads (#14045)

This commit is contained in:
morluto authored and GitHub committed 2026-11-23 12:13:25 +00:00
1 parent ac774bcd70
commit 2e47bc09f3
6 files changed
+275 -249

No files matched your search

+2 -8
View File
@@ -46,18 +46,12 @@ it("applies the shared absolute local-path policy to the public input", () => {
expect(path?.description).toBe("Absolute filesystem path to a BEAM file");
});
it("rejects extra caller arguments and admits a BEAM form with no tables", () => {
expect(
inspectErlangBeamInputSchema.safeParse({
path: "/artifacts/app.beam",
extra: true,
}).success,
).toBe(false);
it("admits a BEAM form with no tables", () => {
const report = erlangBeamSchema.parse({
artifact: {
path: "/artifacts/app.beam",
sha256: "a".repeat(64),
bytes: 16,
bytes: 12,
},
form: { location: { offset: 0, bytes: 12 }, size: 4 },
chunks: [],
+157 -148
View File
@@ -13,7 +13,7 @@ import {
erlangBeamLegacyAtomsFixture,
erlangBeamOtp29Fixture,
} from "./Beam.fixture.js";
import { parseErlangBeam, parseErlangBeamFromHandle } from "./BeamParser.js";
import { parseErlangBeamFromHandle } from "./BeamParser.js";
import { BeamProvider } from "./BeamProvider.js";
import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js";
@@ -21,18 +21,11 @@ const defaults = inspectErlangBeamInputSchema.parse({
path: "/artifacts/app.beam",
});
const parse = (bytes: Buffer, input = defaults) =>
parseErlangBeam(
bytes,
{
path: input.path,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
input,
);
const streamBeam = (bytes: Buffer, reads: number[] = []) => {
const parse = (
bytes: Buffer,
input = defaults,
observeRead?: (offset: number, length: number) => void,
) => {
const sha256 = createHash("sha256").update(bytes).digest("hex");
return parseErlangBeamFromHandle(
{
@@ -40,53 +33,79 @@ const streamBeam = (bytes: Buffer, reads: number[] = []) => {
size: bytes.length,
prefix: bytes.subarray(0, 12),
readRange: async (offset, length) => {
reads.push(length);
observeRead?.(offset, length);
return bytes.subarray(offset, offset + length);
},
},
{ path: defaults.path, sha256, bytes: bytes.length },
defaults,
{ path: input.path, sha256, bytes: bytes.length },
input,
);
};
it("streams bulk BEAM chunks and selects the last Code header", async () => {
const code = Buffer.alloc(1024 * 1024 + 123, 0x62);
it("streams bounded Code and opaque payload reads and keeps the last Code header", async () => {
const window = 1024 * 1024;
const code = Buffer.alloc(window + 123, 0x62);
[16, 0, 169, 4, 2].forEach((field, index) =>
code.writeUInt32BE(field, 4 * index),
);
const decoy = Buffer.from(code.subarray(0, 20));
decoy.writeUInt32BE(99, 16);
const opaque = Buffer.alloc(window + 3, 0x63);
const bytes = erlangBeamChunksFixture([
["Code", decoy],
["Code", code],
["Dbgi", opaque],
]);
const reads: number[] = [];
const streamed = await streamBeam(bytes, reads);
expect(streamed).toEqual(parse(bytes));
expect(streamed.code?.functions).toBe(2);
expect(streamed.chunks.map(({ payload }) => payload.sha256)).toEqual(
[decoy, code].map((payload) =>
createHash("sha256").update(payload).digest("hex"),
),
const reads: [offset: number, length: number][] = [];
const streamed = await parse(bytes, defaults, (offset, length) =>
reads.push([offset, length]),
);
expect(reads).toEqual([8, 20, 8, 1024 * 1024, 123]);
const codeStart = 48;
const codeEnd = codeStart + code.length;
const opaqueStart = codeEnd + 1 + 8; // One padding byte and the next header.
expect(streamed.code).toEqual({
instruction_set: 0,
opcode_max: 169,
labels: 4,
functions: 2,
extra_header_bytes: 0,
instructions: { offset: codeStart + 20, bytes: code.length - 20 },
});
expect(streamed.chunks.map(({ payload }) => payload)).toEqual(
[decoy, code, opaque].map((payload, index) => ({
location: {
offset: [20, codeStart, opaqueStart][index],
bytes: payload.length,
},
bytes: payload.length,
sha256: createHash("sha256").update(payload).digest("hex"),
})),
);
expect(reads).toEqual([
[12, 8],
[20, 20],
[40, 8],
[codeStart, window],
[codeStart + window, 123],
[opaqueStart - 8, 8],
[opaqueStart, window],
[opaqueStart + window, 3],
]);
});
it("preserves the buffered failure for an invalid chunk extent", async () => {
it("refuses a declared chunk extent outside the BEAM form", async () => {
const bytes = erlangBeamChunksFixture([["Code", Buffer.alloc(20)]]);
bytes.writeUInt32BE(100, 16);
expect(() => parse(bytes)).toThrow("BEAM chunk payload exceeds the form.");
await expect(streamBeam(bytes)).rejects.toMatchObject({
await expect(parse(bytes)).rejects.toMatchObject({
reason: "format",
message: "BEAM chunk payload exceeds the form.",
});
});
it("selects the last table and Code payload for every repeated chunk name", () => {
it("selects the last decoded payload of each repeated BEAM table", async () => {
const original = erlangBeamFixture("selected");
const decoy = erlangBeamFixture("decoy");
const changedFields = new Map([
["Code", 16],
["ExpT", 8],
["ImpT", 12],
["FunT", 8],
@@ -104,49 +123,46 @@ it("selects the last table and Code payload for every repeated chunk name", () =
original.subarray(12),
]);
repeated.writeUInt32BE(repeated.length - 8, 4);
const report = parse(repeated);
const control = parse(original);
expect(control.module).toBe("selected");
expect(control.atoms?.map(({ name }) => name)).toEqual([
const report = await parse(repeated);
expect(report.module).toBe("selected");
expect(report.atoms?.map(({ name }) => name)).toEqual([
"selected",
"module_info",
"start",
"erlang",
"get_module_info",
]);
expect(control.exports).toHaveLength(3);
expect(control.imports).toHaveLength(1);
expect(control.lambdas).toHaveLength(1);
expect(control.code).toMatchObject({
opcode_max: 169,
labels: 4,
functions: 2,
});
expect(report.atoms).toEqual(control.atoms);
expect(report.exports).toEqual(control.exports);
expect(report.imports).toEqual(control.imports);
expect(report.lambdas).toEqual(control.lambdas);
expect(report.code).toEqual({
...control.code,
instructions: {
...control.code!.instructions,
offset: control.code!.instructions.offset + decoy.length - 12,
},
});
expect(report.chunks).toHaveLength(control.chunks.length * 2);
expect(
report.exports?.map(({ function: name, arity }) => [name, arity]),
).toEqual([
["start", 0],
["module_info", 0],
["module_info", 1],
]);
expect(report.imports).toMatchObject([
{ module: "erlang", function: "get_module_info", arity: 1 },
]);
expect(report.lambdas).toMatchObject([
{ function: "start", arity: 1, index: 0 },
]);
const chunkNames = ["AtU8", "Code", "ExpT", "ImpT", "FunT"];
expect(report.chunks.map(({ name }) => name)).toEqual([
...chunkNames,
...chunkNames,
]);
});
it("rejects a malformed selected atom table instead of using an earlier table", () => {
it("rejects a malformed selected atom table instead of using an earlier table", async () => {
const original = erlangBeamFixture();
const invalid = erlangBeamChunksFixture([["AtU8", Buffer.from([0])]]);
const repeated = Buffer.concat([original, invalid.subarray(12)]);
repeated.writeUInt32BE(repeated.length - 8, 4);
expect(() => parse(repeated)).toThrow(/truncated/);
await expect(parse(repeated)).rejects.toThrow(/truncated/);
});
it("falls back from an empty AtU8 to legacy Atom, while nonempty alternates keep precedence", () => {
const control = parse(erlangBeamLegacyAtomsFixture());
const empty = parse(erlangBeamLegacyAtomsFixture(Buffer.alloc(0)));
it("falls back from an empty AtU8 to legacy Atom, while nonempty alternates keep precedence", async () => {
const control = await parse(erlangBeamLegacyAtomsFixture());
const empty = await parse(erlangBeamLegacyAtomsFixture(Buffer.alloc(0)));
expect(empty.atoms).toEqual(control.atoms);
expect(empty.atom_encoding).toBe("latin1");
expect(empty.module).toBe("demo");
@@ -157,7 +173,7 @@ it("falls back from an empty AtU8 to legacy Atom, while nonempty alternates keep
"ExpT",
]);
expect(empty.chunks[1]?.payload.bytes).toBe(0);
const alternate = parse(
const alternate = await parse(
erlangBeamLegacyAtomsFixture(
Buffer.concat([
Buffer.from([0, 0, 0, 2, 4]),
@@ -169,7 +185,7 @@ it("falls back from an empty AtU8 to legacy Atom, while nonempty alternates keep
);
expect(alternate.atom_encoding).toBe("utf8");
expect(alternate.exports?.[0]?.function).toBe("new");
const zeroCount = parse(erlangBeamLegacyAtomsFixture(Buffer.alloc(4)));
const zeroCount = await parse(erlangBeamLegacyAtomsFixture(Buffer.alloc(4)));
expect(zeroCount.atom_encoding).toBe("utf8");
expect(zeroCount.atoms).toEqual([]);
expect(zeroCount.exports?.[0]?.function).toBeNull();
@@ -177,8 +193,8 @@ it("falls back from an empty AtU8 to legacy Atom, while nonempty alternates keep
it.each([Buffer.from([0]), Buffer.from([0, 0, 0, 1])])(
"rejects a malformed nonempty AtU8 without falling back: %j",
(payload) => {
expect(() => parse(erlangBeamLegacyAtomsFixture(payload))).toThrow(
async (payload) => {
await expect(parse(erlangBeamLegacyAtomsFixture(payload))).rejects.toThrow(
/truncated/,
);
},
@@ -186,19 +202,19 @@ it.each([Buffer.from([0]), Buffer.from([0, 0, 0, 1])])(
it.each(["AtU8", "Atom"])(
"does not turn an empty standalone %s atom table into decoded facts",
(name) => {
expect(() =>
async (name) => {
await expect(
parse(erlangBeamChunksFixture([[name, Buffer.alloc(0)]])),
).toThrow(/atom table is truncated/);
).rejects.toThrow(/atom table is truncated/);
},
);
it("uses the last AtU8 occurrence even when empty", () => {
it("uses the last AtU8 occurrence even when empty", async () => {
const control = erlangBeamLegacyAtomsFixture(Buffer.from([0, 0, 0, 0]));
const empty = erlangBeamChunksFixture([["AtU8", Buffer.alloc(0)]]);
const bytes = Buffer.concat([control, empty.subarray(12)]);
bytes.writeUInt32BE(bytes.length - 8, 4);
const report = parse(bytes);
const report = await parse(bytes);
expect(report.atom_encoding).toBe("latin1");
expect(report.exports?.[0]?.function).toBe("ÿ");
expect(
@@ -213,13 +229,13 @@ it.each([
{ payload: Buffer.alloc(4), expected: [] },
])(
"distinguishes empty optional FunT from a zero row count: $payload",
({ payload, expected }) => {
async ({ payload, expected }) => {
const original = erlangBeamOtp29Fixture();
const extension = erlangBeamChunksFixture([["FunT", payload]]);
const bytes = Buffer.concat([original, extension.subarray(12)]);
bytes.writeUInt32BE(bytes.length - 8, 4);
const control = parse(original);
const report = parse(bytes);
const control = await parse(original);
const report = await parse(bytes);
expect(control.lambdas).toBeNull();
expect(report.lambdas).toEqual(expected);
expect(report.atoms).toEqual(control.atoms);
@@ -230,12 +246,12 @@ it.each([
},
);
it("does not reuse an earlier FunT when its last occurrence is empty", () => {
it("does not reuse an earlier FunT when its last occurrence is empty", async () => {
const original = erlangBeamFixture();
const extension = erlangBeamChunksFixture([["FunT", Buffer.alloc(0)]]);
const bytes = Buffer.concat([original, extension.subarray(12)]);
bytes.writeUInt32BE(bytes.length - 8, 4);
const report = parse(bytes);
const report = await parse(bytes);
expect(report.lambdas).toBeNull();
expect(
report.chunks
@@ -246,14 +262,14 @@ it("does not reuse an earlier FunT when its last occurrence is empty", () => {
it.each([Buffer.from([0]), Buffer.from([0, 0, 0, 1])])(
"rejects truncated nonempty FunT payloads: %j",
(payload) => {
expect(() => parse(erlangBeamChunksFixture([["FunT", payload]]))).toThrow(
/lambda table is truncated/,
);
async (payload) => {
await expect(
parse(erlangBeamChunksFixture([["FunT", payload]])),
).rejects.toThrow(/lambda table is truncated/);
},
);
it("accepts extended compact atom lengths and rejects truncated or overflowing values", () => {
it("accepts extended compact atom lengths and rejects truncated or overflowing values", async () => {
const compactAtom = (length: Buffer, name: Buffer): Buffer =>
erlangBeamChunksFixture([
[
@@ -262,53 +278,55 @@ it("accepts extended compact atom lengths and rejects truncated or overflowing v
],
]);
const name = Buffer.from("0123456789abcdef", "ascii");
const extended = parse(compactAtom(Buffer.from([0x18, 0x00, 0x10]), name));
expect(extended.module).toBe(name.toString("ascii"));
expect(() => parse(compactAtom(Buffer.from([0x18, 0x00]), name))).toThrow(
/BEAM atom table is truncated/,
const extended = await parse(
compactAtom(Buffer.from([0x18, 0x00, 0x10]), name),
);
expect(() => parse(compactAtom(Buffer.from([0x19]), name))).toThrow(
expect(extended.module).toBe(name.toString("ascii"));
await expect(
parse(compactAtom(Buffer.from([0x18, 0x00]), name)),
).rejects.toThrow(/BEAM atom table is truncated/);
await expect(parse(compactAtom(Buffer.from([0x19]), name))).rejects.toThrow(
/BEAM atom length is not a u tag/,
);
expect(() =>
await expect(
parse(
compactAtom(
Buffer.from([0xd8, 0x80, 0, 0, 0, 0, 0, 0, 0]),
Buffer.alloc(0),
),
),
).toThrow(/BEAM atom length encoding overflows/);
expect(() =>
).rejects.toThrow(/BEAM atom length encoding overflows/);
await expect(
parse(
compactAtom(
Buffer.from([0xf8, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Buffer.alloc(0),
),
),
).toThrow(/BEAM atom length encoding overflows/);
).rejects.toThrow(/BEAM atom length encoding overflows/);
});
it("fails a truncated FOR1 container without partial success", () => {
expect(() => parse(Buffer.from("FOR1"))).toThrow(ArtifactReaderFailure);
it("refuses truncated and non-BEAM FOR1 headers", async () => {
await expect(parse(Buffer.from("FOR1"))).rejects.toThrow(
ArtifactReaderFailure,
);
const foreign = erlangBeamChunksFixture([]);
foreign.write("WAVE", 8);
await expect(parse(foreign)).rejects.toMatchObject({
reason: "format",
message: "Expected a BEAM form type.",
});
});
it("fails a FOR1 form that is not BEAM", () => {
const bytes = Buffer.alloc(16);
bytes.write("FOR1");
bytes.writeUInt32BE(8, 4);
bytes.write("WAVE", 8);
expect(() => parse(bytes)).toThrow(ArtifactReaderFailure);
});
it("discloses bytes that trail the declared FOR1 form", () => {
it("discloses bytes that trail the declared FOR1 form", async () => {
const valid = erlangBeamFixture("trailing_probe");
const clean = parse(valid);
const clean = await parse(valid);
expect(clean.coverage.status).toBe("complete");
expect(clean.coverage.trailing_bytes).toBe(0);
// Append foreign bytes past the declared form; a conformant file ends there.
const trailing = Buffer.concat([valid, Buffer.from("APPENDEDOVERLAY!")]);
const report = parse(trailing);
const report = await parse(trailing);
expect(report.form.location.bytes).toBe(valid.length);
expect(report.coverage.status).toBe("partial");
expect(report.coverage.trailing_bytes).toBe(16);
@@ -320,7 +338,7 @@ it("discloses bytes that trail the declared FOR1 form", () => {
`The declared FOR1 form ends at offset ${String(valid.length)}; 16 trailing bytes were not examined.`,
]);
const single = parse(Buffer.concat([valid, Buffer.from("!")]));
const single = await parse(Buffer.concat([valid, Buffer.from("!")]));
expect(single.coverage.status).toBe("partial");
expect(single.coverage.trailing_bytes).toBe(1);
expect(single.limitations.at(-1)).toBe(
@@ -328,24 +346,24 @@ it("discloses bytes that trail the declared FOR1 form", () => {
);
});
it("rejects a short remainder inside the BEAM form", () => {
it("rejects a short remainder inside the BEAM form", async () => {
const bytes = Buffer.alloc(16);
bytes.write("FOR1");
bytes.writeUInt32BE(8, 4);
bytes.write("BEAM", 8);
expect(() => parse(bytes)).toThrow(/BEAM chunk header is truncated/);
await expect(parse(bytes)).rejects.toThrow(/BEAM chunk header is truncated/);
});
it("rejects an AtU8 atom name that is not UTF-8", () => {
expect(() =>
it("rejects an AtU8 atom name that is not UTF-8", async () => {
await expect(
parse(
erlangBeamChunksFixture([["AtU8", Buffer.from([0, 0, 0, 1, 1, 0xff])]]),
),
).toThrow(/BEAM atom name is not valid UTF-8/);
).rejects.toThrow(/BEAM atom name is not valid UTF-8/);
});
it("uses a one-byte length and preserves Latin-1 bytes in legacy Atom", () => {
const report = parse(
it("uses a one-byte length and preserves Latin-1 bytes in legacy Atom", async () => {
const report = await parse(
erlangBeamChunksFixture([
["Atom", Buffer.from([0, 0, 0, 1, 2, 0x61, 0xff])],
]),
@@ -361,16 +379,16 @@ it("uses a one-byte length and preserves Latin-1 bytes in legacy Atom", () => {
it.each([
["a negative count", [0xff, 0xff, 0xff, 0xff, 0x20, 0x61, 0x62]],
["a compact length", [0, 0, 0, 1, 0x20, 0x61, 0x62]],
])("rejects %s in legacy Atom", (_name, payload) => {
expect(() =>
])("rejects %s in legacy Atom", async (_name, payload) => {
await expect(
parse(erlangBeamChunksFixture([["Atom", Buffer.from(payload)]])),
).toThrow(expect.objectContaining({ reason: "format" }));
).rejects.toThrow(expect.objectContaining({ reason: "format" }));
});
it("rejects combined table rows before allocating them", () => {
it("checks aggregate table capacity after each table is framed", async () => {
const below = Math.floor(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS / 2);
const overflow = MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS - below * 2 + 1;
expect(() =>
await expect(
parse(
erlangBeamRowsFixture([
["ExpT", below],
@@ -378,7 +396,7 @@ it("rejects combined table rows before allocating them", () => {
["FunT", overflow],
]),
),
).toThrow(
).rejects.toThrow(
expect.objectContaining({
failure: expect.objectContaining({
kind: "limit",
@@ -394,23 +412,28 @@ it("rejects combined table rows before allocating them", () => {
4 + (MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1) * 12,
);
complete.writeUInt32BE(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1);
expect(() =>
await expect(
parse(
erlangBeamChunksFixture([
["ExpT", complete],
["ImpT", Buffer.alloc(1)],
]),
),
).toThrow(/import table is truncated/);
const count = Buffer.alloc(4);
count.writeUInt32BE(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1);
expect(() => parse(erlangBeamChunksFixture([["ExpT", count]]))).toThrow(
/truncated/,
);
count.writeUInt32BE(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS);
expect(() => parse(erlangBeamChunksFixture([["ExpT", count]]))).toThrow(
/truncated/,
);
).rejects.toThrow(/import table is truncated/);
for (const [chunk, label] of [
["ExpT", "export"],
["ImpT", "import"],
["FunT", "lambda"],
] as const) {
const count = Buffer.alloc(4);
count.writeUInt32BE(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1);
await expect(
parse(erlangBeamChunksFixture([[chunk, count]])),
).rejects.toMatchObject({
reason: "format",
message: `BEAM ${label} table is truncated.`,
});
}
});
it.each([
@@ -419,20 +442,20 @@ it.each([
["compact AtU8", "AtU8", [0xff, 0xff, 0xff, 0xfe], [0x10, 0x20]],
] as const)(
"checks only the admitted atom lengths in %s",
(_name, chunk, count, [validLength, invalidLength]) => {
async (_name, chunk, count, [validLength, invalidLength]) => {
const fixture = (firstLength: number, lastByte: number) =>
erlangBeamChunksFixture([
[chunk, Buffer.from([...count, firstLength, 0x61, lastByte])],
]);
const input = { ...defaults, max_atoms: 1 };
const valid = fixture(validLength, 0);
expect(parse(valid).atoms).toEqual([
expect((await parse(valid)).atoms).toEqual([
{ index: 1, name: "a" },
{ index: 2, name: "" },
]);
for (const bytes of [valid, fixture(validLength, validLength)]) {
// The second name is complete or truncated, beyond the admitted prefix.
expect(() => parse(bytes, input)).toThrow(
await expect(parse(bytes, input)).rejects.toThrow(
expect.objectContaining({
failure: expect.objectContaining({
kind: "limit",
@@ -443,26 +466,12 @@ it.each([
);
}
// The first name would consume the second entry's required length byte.
expect(() => parse(fixture(invalidLength, 0x62), input)).toThrow(
await expect(parse(fixture(invalidLength, 0x62), input)).rejects.toThrow(
expect.objectContaining({ reason: "format" }),
);
},
);
it("retains the exhausted chunk allowance", () => {
expect(() =>
parse(erlangBeamFixture(), { ...defaults, max_chunks: 1 }),
).toThrow(
expect.objectContaining({
failure: expect.objectContaining({
kind: "limit",
format: "beam",
limit: { name: "max_chunks", maximum: 1 },
}),
}),
);
});
it("does not infer a BEAM budget from diagnostic prose", async () => {
const provider = new BeamProvider();
const injection = vi
@@ -497,10 +506,10 @@ it.each([
["FunT", Buffer.alloc(4)],
] as const)(
"reports unexamined bytes inside a selected %s table",
(name, payload) => {
const control = parse(erlangBeamChunksFixture([[name, payload]]));
async (name, payload) => {
const control = await parse(erlangBeamChunksFixture([[name, payload]]));
const extended = Buffer.concat([payload, Buffer.from([0x61])]);
const report = parse(erlangBeamChunksFixture([[name, extended]]));
const report = await parse(erlangBeamChunksFixture([[name, extended]]));
expect(control.coverage.status).toBe("complete");
expect(report.coverage).toMatchObject({
status: "partial",
+21 -74
View File
@@ -360,70 +360,19 @@ const buildErlangBeamReport = (
};
};
/** Decode one FOR1/BEAM IFF container into bounded chunk and table facts. */
export const parseErlangBeam = (
bytes: Buffer,
artifact: ErlangBeam["artifact"],
input: InspectErlangBeamInput,
): ErlangBeam => {
requireRange(bytes.length, 0, 12);
if (bytes.subarray(0, 4).toString("latin1") !== "FOR1")
fail("Expected a FOR1 IFF container.");
const carrier = new BinaryReader(bytes, false, "beam");
const formSize = carrier.u32(4);
if (formSize < 4) fail("BEAM form size is shorter than the BEAM tag.");
requireRange(bytes.length, 8, formSize);
if (bytes.subarray(8, 12).toString("latin1") !== "BEAM")
fail("Expected a BEAM form type.");
const formEnd = 8 + formSize;
const form = new BinaryReader(
carrier.range(0, formEnd, "BEAM form"),
false,
"beam",
);
const chunks: ErlangBeam["chunks"] = [];
const payloads = new Map<string, RetainedBeamChunk>();
let at = 12;
while (at < formEnd) {
if (formEnd - at < 8) fail("BEAM chunk header is truncated.");
const size = form.u32(at + 4);
const payloadOffset = at + 8;
if (size > formEnd - payloadOffset)
fail("BEAM chunk payload exceeds the form.");
const padded = payloadOffset + size + ((4 - (size % 4)) % 4);
if (padded > formEnd) fail("BEAM chunk padding exceeds the form.");
if (chunks.length >= input.max_chunks)
throw decodeLimit(
"beam",
`BEAM form exceeds the ${String(input.max_chunks)}-chunk budget.`,
{ name: "max_chunks", maximum: input.max_chunks },
);
const name = form.range(at, 4, "BEAM chunk name").toString("latin1");
const payload = form.range(payloadOffset, size, "BEAM chunk payload");
chunks.push({
index: chunks.length,
name,
location: { offset: at, bytes: padded - at },
payload: {
location: { offset: payloadOffset, bytes: size },
bytes: size,
sha256: sha256Hex(payload),
},
});
// OTP's loader replaces the selected payload on each matching chunk.
// Keep every occurrence above; decode the last occurrence of each name.
payloads.set(name, { payload, payloadLength: size, offset: at });
at = padded;
}
return buildErlangBeamReport(
bytes.length,
formSize,
formEnd,
chunks,
payloads,
artifact,
input,
);
const readAdmittedRange = async (
handle: StableArtifactHandle,
offset: number,
length: number,
): Promise<Buffer> => {
const bytes = await handle.readRange(offset, length);
if (bytes.length !== length)
throw new ArtifactReaderFailure(
"integrity",
`BEAM read at offset ${String(offset)} ended before its ${String(length)} admitted bytes.`,
{ integrityCheck: "read-coverage" },
);
return bytes;
};
const streamChunkDigest = async (
@@ -436,13 +385,11 @@ const streamChunkDigest = async (
const prefix = Buffer.alloc(Math.min(size, retainPrefixBytes));
for (let offset = 0; offset < size; offset += STREAM_CHUNK_BYTES) {
const length = Math.min(STREAM_CHUNK_BYTES, size - offset);
const part = await handle.readRange(payloadOffset + offset, length);
if (part.length !== length)
throw new ArtifactReaderFailure(
"integrity",
"BEAM payload ended before its admitted extent.",
{ integrityCheck: "read-coverage" },
);
const part = await readAdmittedRange(
handle,
payloadOffset + offset,
length,
);
hash.update(part);
if (offset < prefix.length)
part.copy(
@@ -469,7 +416,7 @@ export const parseErlangBeamFromHandle = async (
const header =
handle.prefix.length >= 12
? handle.prefix.subarray(0, 12)
: await handle.readRange(0, 12);
: await readAdmittedRange(handle, 0, 12);
if (header.subarray(0, 4).toString("latin1") !== "FOR1")
fail("Expected a FOR1 IFF container.");
const formSize = new BinaryReader(header, false, "beam").u32(4);
@@ -483,7 +430,7 @@ export const parseErlangBeamFromHandle = async (
let at = 12;
while (at < formEnd) {
if (formEnd - at < 8) fail("BEAM chunk header is truncated.");
const chunkHeader = await handle.readRange(at, 8);
const chunkHeader = await readAdmittedRange(handle, at, 8);
const size = new BinaryReader(chunkHeader, false, "beam").u32(4);
const payloadOffset = at + 8;
if (size > formEnd - payloadOffset)
@@ -502,7 +449,7 @@ export const parseErlangBeamFromHandle = async (
const payload =
size === 0
? Buffer.alloc(0)
: await handle.readRange(payloadOffset, size);
: await readAdmittedRange(handle, payloadOffset, size);
sha256 = sha256Hex(payload);
payloads.set(name, { payload, payloadLength: size, offset: at });
} else if (name === "Code") {
+18 -2
View File
@@ -487,14 +487,30 @@ cliTest(
arguments: ["inspect-erlang-beam", path, "--max-chunks", "1", "--json"],
});
const admitted = await inspect();
expect(admitted.json).toMatchObject({ code: "resource_constraint" });
expect(admitted.exitCode).toBe(1);
expect(admitted.json).toMatchObject({
code: "resource_constraint",
retryable: false,
details: {
operation: "inspect_erlang_beam",
resource: "capacity",
reported_limits: { max_chunks: 1 },
},
});
// Retain bytes beyond the declared form. They cannot supply the second
// chunk's payload even though the complete file contains it.
bytes.writeUInt32BE(secondHeader, 4);
await writeFile(path, bytes);
const refused = await inspect();
expect(refused.json).toMatchObject({ code: "invalid_request" });
expect(refused.exitCode).toBe(1);
expect(refused.json).toMatchObject({
code: "invalid_request",
details: {
operation: "inspect_erlang_beam",
issues: [{ path: ["path"], reason: "invalid_format" }],
},
});
},
);
@@ -205,3 +205,57 @@ it.each([{ source: "BEAM successful close" }, null])(
}
},
);
it("refuses a short positional read of the selected BEAM lambda table", async () => {
const root = await createTestTempDirectory("rea-beam-table-eof-");
const path = join(root, "selected.beam");
const bytes = erlangBeamFixture();
await fileSystem.writeFile(path, bytes);
const payloadBytes = 28;
const payloadOffset = bytes.length - payloadBytes;
expect(bytes.toString("latin1", payloadOffset - 8, payloadOffset - 4)).toBe(
"FunT",
);
const service = new BeamService(new BeamProvider());
const handles: FileHandle[] = [];
let shortReads = 0;
injected.opened = (openedPath, handle) => {
if (String(openedPath) !== path) return;
handles.push(handle);
const read = handle.read.bind(handle) as (
buffer: Buffer,
offset: number,
length: number,
position: number,
) => Promise<{ bytesRead: number; buffer: Buffer }>;
const instrumented = handle as unknown as { read: typeof read };
instrumented.read = (buffer, offset, length, position) => {
if (position !== payloadOffset || length !== payloadBytes)
return read(buffer, offset, length, position);
shortReads += 1;
return Promise.resolve({ bytesRead: 0, buffer });
};
};
try {
const result = await service.inspect({ path });
expect(shortReads).toBe(1);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisArtifactChangedError",
integrityCheck: "read-coverage",
cleanupIncomplete: false,
partialObservation: {
kind: "file-snapshot-hash",
path,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
},
});
expect(handles).toHaveLength(1);
expect(handles[0]?.fd).toBe(-1);
} finally {
await service.close();
}
});
+23 -17
View File
@@ -248,23 +248,29 @@ mcpTest(
const { client, session } = await connect(mcp);
const root = await createTestTempDirectory("rea-beam-malformed-rows-");
try {
for (const chunk of ["ExpT", "ImpT", "FunT"]) {
const path = join(root, `${chunk}.beam`);
await writeFile(
path,
erlangBeamDeclaredRowsFixture([
[chunk, MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1],
]),
);
const response = await client.callTool({
name: "inspect_erlang_beam",
arguments: { path },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
});
}
const path = join(root, "lambda.beam");
await writeFile(
path,
erlangBeamDeclaredRowsFixture([
["FunT", MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1],
]),
);
const response = await client.callTool({
name: "inspect_erlang_beam",
arguments: { path },
});
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["path"],
reason: "invalid_format",
message: expect.stringContaining("lambda table is truncated"),
},
],
},
});
} finally {
await session.close();
}