Files
reverse-engineering-anything/tests/boundary/filesystem/pythonBeamCleanup.test.ts
T
morluto 1badb6a8ae fix(native)!: report details.limit for remaining native reader budgets and make BEAM table rows adjustable (#14631)
* fix(native)!: report details.limit for native reader per-call budgets

Devicetree, Windows shortcut, kernel build config, firmware staging and
byte-entropy refusals of caller-selected budgets named their control only
in remediation prose. Each now sets details.limit from a domain-owned
budget object that also builds the schema (src/domain/parameterBudget.ts),
so the reported range is the one the next call accepts.

inspect_devicetree's fixed 32 MiB decoded representation allowance becomes
the per-call max_decoded_bytes (default 32 MiB, 1 KiB to 256 MiB); its
refusal reports boundary max_decoded_bytes instead of decoded_bytes.

The pwntools allocation failure declares measuredExhaustion, the firmware
inherited RLIMIT_FSIZE refusal declares measuredExhaustion, and the LLDB
combined-result ceiling is a registered representation bound.

Part of #14234 and #14235.

BREAKING CHANGE: inspect_devicetree's decoded-representation refusal reports
reported_limits.boundary "max_decoded_bytes" with details.limit, instead of
"decoded_bytes".

* fix(native): keep FIT decoded-budget boundary, LLDB narrowing and entropy length range exact

The FIT reader compared the renamed devicetree limit against decoded_bytes, so a decoded-budget refusal became capacity; it now checks max_decoded_bytes, with a test. The LLDB representation ceiling keeps a short name and carries its recovery as narrowing. The byte-entropy length maximum is the window the selected block_size admits.

* fix(cli): describe inspect-devicetree --max-decoded-bytes

* refactor(native): let the generated adjustable-budget recovery name the native reader controls

With #14625 the refusal owns per-call recovery, so the devicetree, Windows shortcut, kernel build config, firmware staging and byte-entropy refusals drop their authored sentences. inspect_byte_entropy reports the smallest admitting block_size as required_value.

* fix(native)!: report details.limit for remaining native reader budgets and make BEAM table rows adjustable

inspect_elf_dependencies, inspect_elf_unwind_ranges, inspect_apple_ips,
inspect_dwarf_units, inspect_native_initializers and inspect_pe_resources
named their per-call budgets only in remediation prose. Each now reports
details.limit from a domain-owned budget object that also builds the
schema. The unwind per-page symbol-name text refusal names the page size
`limit`, the control that admits it.

The fixed 65,536-row BEAM table ceiling becomes the per-call
max_table_rows (default 65,536, at most 1,048,576).

The plist nesting allowance is reclassified as a representation bound
(MAX_JSON_DEPTH less the report envelope). GPU and APK input refusals that
named their fixed allowances only in prose now declare them, registered
as pending #14235.

Part of #14234 and #14235.

BREAKING CHANGE: a BEAM table-row refusal reports details.limit for
max_table_rows instead of a fixed_ceiling refusal.

* fix(native): keep naming the dependency and BEAM row controls in recovery

* refactor(native): let the generated adjustable-budget recovery name the remaining native controls

With #14625 the refusal owns per-call recovery, so the ELF dependency, ELF unwind, Apple IPS, DWARF, initializer, PE resource and BEAM refusals drop their authored sentences. BEAM reports the complete row and atom counts as required_value. The unwind per-page text allowance is a registered fixed allowance whose narrowing names a smaller limit, because a larger page would not admit it.

* style: format the PE resources provider test

* refactor(native): keep one owner of the IPS budget bounds and document the unwind text allowance
2026-11-26 04:31:33 +00:00

315 lines
11 KiB
TypeScript

import { createHash } from "node:crypto";
import { fstatSync } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import * as fileSystem from "node:fs/promises";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { resolvedAnalysisError } from "../../../src/domain/analysisErrorBase.js";
import { pythonPycFixture } from "../../../src/python/PythonPyc.fixture.js";
import { PythonPycProvider } from "../../../src/python/PythonPycProvider.js";
import { PythonPycService } from "../../../src/application/python/PythonPycService.js";
import { BeamService } from "../../../src/application/erlang/BeamService.js";
import { BeamProvider } from "../../../src/erlang/BeamProvider.js";
import { erlangBeamFixture } from "../../../src/erlang/Beam.fixture.js";
import { DevicetreeService } from "../../../src/application/binaryDiagnostics/DevicetreeService.js";
import { DevicetreeProvider } from "../../../src/firmware/devicetree/DevicetreeProvider.js";
import { devicetreeFixture } from "../../../src/domain/firmware/devicetree.fixture.js";
const injected = vi.hoisted(() => ({
opened: undefined as
| ((path: unknown, handle: FileHandle) => void)
| undefined,
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
...actual,
open: async (...args: Parameters<typeof actual.open>) => {
const handle = await actual.open(...args);
injected.opened?.(args[0], handle);
return handle;
},
};
});
afterEach(() => {
injected.opened = undefined;
vi.restoreAllMocks();
});
const providers = [
{
name: "Python pyc",
operation: "inspect_python_pyc",
bytes: pythonPycFixture(),
create: () => new PythonPycService(new PythonPycProvider()),
},
{
name: "Erlang BEAM",
operation: "inspect_erlang_beam",
bytes: erlangBeamFixture(),
create: () => new BeamService(new BeamProvider()),
},
{
name: "devicetree",
operation: "inspect_devicetree",
bytes: devicetreeFixture(),
create: () => new DevicetreeService(new DevicetreeProvider()),
},
];
const beamInput = (path: string, bytes: Buffer) => ({
path,
max_file_bytes: bytes.length,
max_chunks: 5,
max_atoms: 5,
max_table_rows: 65536,
});
const expectBeamEvidence = (
observation: unknown,
path: string,
bytes: Buffer,
) => {
const evidence = parseEvidence(observation);
const sha256 = createHash("sha256").update(bytes).digest("hex");
expect(evidence).toMatchObject({
operation: "inspect_erlang_beam",
subject: { identity: { format: "file", sha256 }, local_path: path },
locations: [
{ kind: "artifact-path", path },
{ kind: "file-offset-range", start: 0, end: bytes.length },
],
normalized_result: {
artifact: { path, sha256, bytes: bytes.length },
form: {
location: { offset: 0, bytes: bytes.length },
size: bytes.length - 8,
},
module: "beam_fixture",
lambdas: [{ function: "start", arity: 1, index: 0, old_unique: 42 }],
coverage: {
status: "complete",
examined_chunks: 5,
atoms: 5,
trailing_bytes: 0,
},
},
});
expect(evidence.parameters).toEqual(beamInput(path, bytes));
};
const outcomes = [
{ stage: "completed read", cancelDuringClose: false, failRead: false },
{
stage: "cancellation during close",
cancelDuringClose: true,
failRead: false,
},
{
stage: "read failure then cancellation",
cancelDuringClose: true,
failRead: true,
},
];
it.each(
providers.flatMap((provider) =>
outcomes.map((outcome) => ({ ...provider, ...outcome })),
),
)(
"$name preserves acquired facts and resolves cleanup after retries: $stage",
async ({ operation, bytes, create, cancelDuringClose, failRead }) => {
const root = await createTestTempDirectory("rea-python-beam-close-owner-");
const path = join(root, "selected-artifact");
await fileSystem.writeFile(path, bytes);
const releases: (() => Promise<void>)[] = [];
const descriptors: number[] = [];
const controller = new AbortController();
const reason = { source: "cancelled during descriptor finalization" };
const readFailure = new Error("injected physical artifact read failure");
let denyClose = true;
injected.opened = (openedPath, file) => {
if (String(openedPath) !== path) return;
descriptors.push(file.fd);
if (failRead) vi.spyOn(file, "read").mockRejectedValueOnce(readFailure);
const close = file.close.bind(file);
releases.push(close);
vi.spyOn(file, "close").mockImplementation(async () => {
if (cancelDuringClose) controller.abort(reason);
if (denyClose)
throw new Error("injected artifact descriptor close failure");
await close();
});
};
const service = create();
try {
const result = await service.inspect(
operation === "inspect_erlang_beam" ? beamInput(path, bytes) : { path },
{ signal: controller.signal },
);
if (result.ok) throw new Error("Expected incomplete descriptor cleanup");
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual([path]);
const expectedSnapshot = failRead
? undefined
: {
kind: "file-snapshot-hash",
path,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
};
const observation = result.error.partialObservation;
if (operation === "inspect_erlang_beam" && !failRead) {
expectBeamEvidence(observation, path, bytes);
expect(result.error.cleanupPrimary?.partialObservation).toBe(
observation,
);
expect(
projectAnalysisError(result.error).details?.partial_observation,
).toEqual(observation);
} else {
expect(observation).toEqual(expectedSnapshot);
}
if (failRead)
expect(result.error.cleanupPrimary?.cause).toBe(readFailure);
else if (cancelDuringClose) {
expect(result.error.cleanupPrimary?._tag).toBe(
"AnalysisCancelledError",
);
expect(result.error.cleanupPrimary?.cause).toBe(reason);
}
expect(fstatSync(descriptors[0]!)).toBeDefined();
const closeErrors: ProviderCleanupError[] = [];
for (let attempt = 0; attempt < 2; attempt += 1) {
const failure: unknown = await service.close().then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(ProviderCleanupError);
if (!(failure instanceof ProviderCleanupError))
throw new Error("Expected a translated provider cleanup failure");
expect(failure.operation).toBe(operation);
expect(failure.cleanupIncomplete).toBe(true);
expect(failure.cleanupResources).toEqual([path]);
closeErrors.push(failure);
}
expect(descriptors).toHaveLength(1);
expect(result.error.cleanupIncomplete).toBe(true);
denyClose = false;
await service.close();
expect(() => fstatSync(descriptors[0]!)).toThrow();
for (const failure of [result.error, ...closeErrors]) {
expect(failure.cleanupIncomplete).toBe(false);
expect(failure.cleanupResources).toEqual([]);
}
expect(result.error.partialObservation).toBe(observation);
expect(
projectAnalysisError(resolvedAnalysisError(result.error)).details
?.partial_observation,
).toEqual(observation);
} finally {
denyClose = false;
await service.close();
for (const close of releases) await close();
}
},
);
it.each([{ source: "BEAM successful close" }, null])(
"preserves BEAM cancellation during successful close with reason %j",
async (reason) => {
const root = await createTestTempDirectory("rea-beam-successful-close-");
const path = join(root, "selected.beam");
const bytes = erlangBeamFixture();
await fileSystem.writeFile(path, bytes);
const controller = new AbortController();
const handles: FileHandle[] = [];
injected.opened = (openedPath, handle) => {
if (String(openedPath) !== path) return;
handles.push(handle);
const close = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
controller.abort(reason);
await close();
});
};
const service = new BeamService(new BeamProvider());
try {
const result = await service.inspect(beamInput(path, bytes), {
signal: controller.signal,
});
if (result.ok) throw new Error("Expected finalization cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(reason);
expect(result.error.cleanupIncomplete).toBe(false);
expectBeamEvidence(result.error.partialObservation, path, bytes);
expect(handles).toHaveLength(1);
expect(handles[0]?.fd).toBe(-1);
await service.close();
expect(handles).toHaveLength(1);
} finally {
await service.close();
}
},
);
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();
}
});