Files
reverse-engineering-anything/tests/boundary/go/goBinaryProvider.test.ts
T
7fd50eb361 fix(zstd): share exact-frame Zstandard decoding across ELF and OTA (#12416)
* fix(zstd): share exact-frame Zstandard decoding across ELF and OTA

Walk RFC 8878 frames once so ELF sections, Android OTA REPLACE_ZSTD, and GPU payloads reject truncated headers, blocks, checksums, and trailing bytes on every supported Node runtime. Bound that walk with the runtime zstd.max_frames setting.

* fix(zstd): keep frame output tight and report GPU frame-cap refusals

Copy each Node 22 frame off its decoder chunk before the next frame is decoded. Map a GPU zstd.max_frames refusal through the resource-limit contract instead of a provider failure.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): keep frame-cap refusals and bad seeds out of malformed results

Project zstd.max_frames through one resource-limit helper for ELF notes, DWARF, GPU, and artifact reads. An invalid REA_ZSTD_MAX_FRAMES seed stays a configuration failure, and frame-header tests cover content size, window, dictionary id, and RLE blocks.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield GPU frame decoding so cancellation can land

The frame-by-frame fallback awaits a caller pause before each data frame. GPU yields and checks the read signal there, so a many-frame payload does not finish before a disconnect is observed.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): advertise the frame cap and keep strict GPU decode cancellable

List every operation that enforces zstd.max_frames, including GPU, DWARF, and ELF notes. The strict sequence uses the async decoder and checks the caller signal again after it returns, and a single output buffer is not copied a second time.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): refresh analysis-setting schemas and GPU frame-cap projection

Regenerate the advertised input summaries for inspect_analysis_settings and update_analysis_settings. GPU inventory now throws the projected zstd.max_frames resource limit from payload decode and #retainFailure, so the adjustable setting survives the public failure.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* style(gpu): format the frame-cap projection throw

oxfmt keeps the zstd.max_frames throw in #retainFailure on one line so CI format:check matches the local formatter.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield after the last frame-by-frame GPU decode

The fallback returned success in the same turn as the final synchronous frame, so a queued abort was still invisible to the caller's signal check. Pause once more before that success, matching the strict sequence.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield ELF, OTA, and DWARF frame decoding on the caller signal

The synchronous frame loop ignored abort signals owned by inspect_elf_notes, inspect_dwarf_units, and Android OTA partition reads. Those callers now use the cooperative decoder and yield before Zstandard work, and 32-frame cancellations cover each path.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): observe cancellation during structural parsing

* fix(zstd): project section-name frame caps at the ELF directory boundary

readElfDirectoryFromBuffer now requires the caller's operation and throws the adjustable zstd.max_frames resource limit. Hardening, unwind, and the other directory consumers keep that typed refusal instead of an adapter or I/O error.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): preserve optional ELF evidence when frames are capped

* fix(zip): validate Zstandard members through frame completion (#12461)

fix(zip): require complete Zstandard member frames

* fix(elf): yield hardening section name decoding

* fix(elf): yield section names for unwind and export reads

* fix(zstd): yield ELF directory reads that already own a cancellation signal

Hardening, unwind, initializers, exports, kernel modules, debug link, and Android JNI now read section names through the cooperative directory when their caller has a signal. Readers with no signal stay synchronous.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(elf): share one initializer directory and retain its snapshot

* fix(android): reuse the admitted JNI ELF directory

* fix(elf): retain optional debug candidate evidence through cooperative decoding

* fix(zstd): yield ELF section names for Go, Rust, and IL2CPP

These inspections already own an abort signal. Their ELF directory read now uses the cooperative container decoder so a queued cancellation can land during a many-frame section-name table.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(elf): recognize compressed kernel modules before ELF decoding

The cooperative module reader decoded the bytes as ELF before the container check, so gzip, xz, and zstd modules became malformed images. The compression check now returns the unsupported-container report first.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* refactor(elf): classify each container once before reading it

* fix(il2cpp): preserve admission order during cooperative linking

* fix(elf): reuse section-name decoding in debug-link comparison (#12472)

* style(elf): format updated section-reader test calls

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-11-19 19:45:26 +00:00

391 lines
14 KiB
TypeScript

import { truncate, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { scheduler } from "node:timers/promises";
import { expect, it, vi } from "vitest";
import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js";
import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js";
import {
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../../../src/domain/analysisErrorCore.js";
import { BinaryFormatFailure } from "../../../src/domain/binaryContainer.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
createGoBinaryFixture,
createGoInlineAggregateFixture,
createGoOverlappingElfFixture,
} from "../../fixtures/go/image.js";
import { createGoRodataStringFixture } from "../../fixtures/go/rodataStringImage.js";
import { CPU_ARM64, universalMacho } from "../../fixtures/universalMacho.js";
import { elfFrameAllowanceFixture } from "../../fixtures/binaryDiagnostics/elfFrameAllowance.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("rejects advertised PE32 data directories outside the optional header", async () => {
const root = await createTestTempDirectory("rea-go-pe-directories-");
const fixture = createGoBinaryFixture({ format: "pe", bits: 32 });
fixture.bytes.writeUInt32LE(1, 152 + 92);
const path = join(root, "truncated-pe32.exe");
await writeFile(path, fixture.bytes);
const result = await new GoBinaryProvider().inspect({ path });
if (result.ok) throw new Error("Truncated PE32 directories must be refused");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: { issues: [{ path: ["path"], reason: "invalid_format" }] },
});
});
it.each([false, true])(
"reports whether an oversized Mach-O command table is file-backed (%s)",
async (stored) => {
const tableBytes = 16 * 1024 * 1024 + 8;
const bytes = Buffer.alloc(stored ? 40 : 32);
bytes.writeUInt32LE(0xfeedfacf, 0);
bytes.writeUInt32LE(0x01000007, 4);
bytes.writeUInt32LE(3, 8);
bytes.writeUInt32LE(2, 12);
bytes.writeUInt32LE(1, 16);
bytes.writeUInt32LE(tableBytes, 20);
if (stored) {
bytes.writeUInt32LE(0x1234, 32);
bytes.writeUInt32LE(tableBytes, 36);
}
const root = await createTestTempDirectory("rea-go-macho-table-");
const path = join(root, "image");
await writeFile(path, bytes);
if (stored) await truncate(path, 32 + tableBytes);
const provider = new GoBinaryProvider();
try {
const result = await provider.inspect({ path });
if (result.ok) throw new Error("Expected a command-table refusal");
const projected = projectAnalysisError(result.error);
if (stored)
expect(projected).toMatchObject({
code: "resource_constraint",
details: {
reported_limits: {
boundary: "structure",
maximum: 16 * 1024 * 1024,
},
},
});
else {
expect(result.error).toBeInstanceOf(AnalysisInputError);
if (!(result.error instanceof AnalysisInputError)) throw result.error;
expect(result.error.cause).toBeInstanceOf(BinaryFormatFailure);
if (!(result.error.cause instanceof BinaryFormatFailure))
throw result.error.cause;
expect(result.error.cause.failure).toMatchObject({
kind: "truncated",
format: "macho",
field: "Mach-O load commands",
offset: 32,
});
expect(projected).toMatchObject({
code: "invalid_request",
details: {
issues: [{ path: ["path"], reason: "invalid_format" }],
},
});
}
} finally {
await provider.close();
}
},
);
it("preserves the actual build-info byte guard as a resource failure", async () => {
const fixture = createGoInlineAggregateFixture(1024 * 1024 + 2);
const root = await createTestTempDirectory("rea-go-resource-");
const path = join(root, "oversized-metadata.elf");
await writeFile(path, fixture.bytes);
const result = await new GoBinaryProvider().inspect({ path });
expect(result.ok).toBe(false);
if (result.ok)
throw new Error("Oversized embedded metadata must not succeed");
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(result.error instanceof AnalysisResourceConstraintError))
throw result.error;
expect(result.error.reason).toContain(path);
expect(result.error.reportedLimits).toEqual({
boundary: "build-info",
maximum: 1024 * 1024,
});
const projected = projectAnalysisError(result.error);
expect(projected.details?.limit).toMatchObject({
control_kind: "parameter",
parameter: "max_build_info_bytes",
unit: "bytes",
});
expect(projected.retryable).toBe(false);
expect(projected.remediation.action).toContain(
"Go build-info string allowance",
);
expect(projected.remediation.action).not.toMatch(/available host memory/u);
});
it("keeps the header-search budget distinct from a worker CPU limit", async () => {
const root = await createTestTempDirectory("rea-go-search-");
const path = join(root, "overlapping.elf");
await writeFile(path, createGoOverlappingElfFixture());
const result = await new GoBinaryProvider().inspect({ path });
if (result.ok) throw new Error("Overlapping header search must be refused");
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
retryable: false,
details: {
resource: "cpu",
reported_limits: {
boundary: "search",
maximum: 256 * 1024 * 1024,
},
},
});
expect(projected.remediation.action).toContain("header-search allowance");
expect(projected.remediation.action).not.toMatch(/observed signal/u);
});
it("reports unreadable ELF names alongside the no-record limitation", async () => {
const bytes = createGoBinaryFixture({ omitBuildInfo: true }).bytes;
const nameTableHeader = 256 + 64;
bytes.writeBigUInt64LE(0x800n, nameTableHeader + 8);
bytes.writeBigUInt64LE(24n, nameTableHeader + 32);
bytes.writeUInt32LE(3, 768);
const root = await createTestTempDirectory("rea-go-unknown-section-names-");
const path = join(root, "unknown-names.elf");
await writeFile(path, bytes);
const result = await new GoBinaryProvider().inspect({ path });
if (!result.ok) throw result.error;
expect(result.value.build_info).toBeNull();
expect(result.value.limitations).toContain(
"No recognized Go build-info record was found in the inspected image; absent metadata does not establish that the binary is not Go.",
);
expect(result.value.limitations).toContainEqual(
expect.stringMatching(
/section names.*unavailable.*compression type 3.*unsupported/iu,
),
);
expect(result.value).not.toHaveProperty("section_names_limitation");
});
it("keeps a module-mode build with no dependency records as an observed empty list", async () => {
const moduleText =
"path\texample.com/tool\n" +
"mod\texample.com/tool\t(devel)\t\n" +
"build\tGOOS=linux\n";
const root = await createTestTempDirectory("rea-go-empty-module-deps-");
const path = join(root, "application.elf");
await writeFile(path, createGoBinaryFixture({ moduleText }).bytes);
const result = await new GoBinaryProvider().inspect({ path });
if (!result.ok) throw result.error;
expect(result.value.build_info?.module_text).toBe(moduleText);
expect(result.value.build_info?.module).toMatchObject({
main: { path: "example.com/tool", version: "(devel)" },
dependencies: [],
complete: true,
});
expect(result.value.limitations.join(" ")).not.toContain(
"Dependency coverage is unknown",
);
});
it("adjusts string_literals file offsets inside a universal Mach-O slice and records chained-fixup/truncation limitations", async () => {
const rodata = Buffer.from(
"ListResourceProvidersgenaihttps://example.invalid/v1",
"utf8",
);
const thin = createGoRodataStringFixture({
format: "macho",
machoChainedFixups: true,
rodata,
headers: [
{ section: "data", offsetInSection: 0, ptr: 0x102000n, len: 21n },
{ section: "data", offsetInSection: 16, ptr: 0x102015n, len: 5n },
{ section: "data", offsetInSection: 32, ptr: 0x10201an, len: 26n },
],
});
const fat = universalMacho([
{ bytes: thin.bytes, cpuType: CPU_ARM64, cpuSubtype: 0 },
]);
const sliceOffset = fat.slices[0]!.offset;
const root = await createTestTempDirectory("rea-go-fat-strings-");
const path = join(root, "universal-go");
await writeFile(path, fat.bytes);
const result = await new GoBinaryProvider().inspect({
path,
architecture: "arm64",
include_string_literals: true,
max_string_literals: 2,
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.selected_slice?.offset).toBe(sliceOffset);
expect(result.value.string_literals).toEqual({
evidence_kind: "inferred",
discovered_count: 3,
aggregate_bytes: 26,
max_items: 2,
truncated: true,
limits_reached: ["max_string_literals"],
items: [
{
value: "ListResourceProviders",
location: { offset: sliceOffset + thin.rodataOffset, bytes: 21 },
first_header_offset: sliceOffset + thin.dataOffset,
reference_count: 1,
},
{
value: "genai",
location: { offset: sliceOffset + thin.rodataOffset + 21, bytes: 5 },
first_header_offset: sliceOffset + thin.dataOffset + 16,
reference_count: 1,
},
],
});
for (const item of result.value.string_literals?.items ?? []) {
expect(
fat.bytes
.subarray(
item.location.offset,
item.location.offset + item.location.bytes,
)
.toString("utf8"),
).toBe(item.value);
}
const limitationsText = result.value.limitations.join(" ");
expect(limitationsText).toContain("LC_DYLD_CHAINED_FIXUPS");
expect(limitationsText).toContain("truncated");
});
it.each([
[
"max_input_bytes",
4095,
8192,
{ maximum_input_bytes: 4095, parameter: "max_input_bytes", unit: "bytes" },
],
[
"max_report_bytes",
1,
16384,
{ maximum_output_bytes: 1, parameter: "max_report_bytes", unit: "bytes" },
],
["max_build_info_bytes", 1, 4096, { boundary: "build-info", maximum: 1 }],
["max_header_search_bytes", 1, 4096, { boundary: "search", maximum: 1 }],
] as const)(
"recovers the same Go artifact after increasing %s",
async (parameter, low, raised, reportedLimits) => {
const root = await createTestTempDirectory("rea-go-budget-recovery-");
const path = join(root, "application.elf");
await writeFile(path, createGoBinaryFixture().bytes);
const service = new GoBinaryService(new GoBinaryProvider());
try {
const refused = await service.inspect({ path, [parameter]: low });
if (refused.ok)
throw new Error(
"Selected low budget must refuse this complete artifact",
);
expect(projectAnalysisError(refused.error)).toMatchObject({
code: "resource_constraint",
details: {
reported_limits: reportedLimits,
limit: {
control_kind: "parameter",
parameter,
unit: "bytes",
},
},
remediation: { action: expect.stringContaining(parameter) },
});
const recovered = await service.inspect({ path, [parameter]: raised });
if (!recovered.ok) throw recovered.error;
expect(recovered.value.normalized_result).toMatchObject({
artifact: { path, bytes: 4096 },
build_info: { go_version: "go1.26.0" },
});
expect(recovered.value.parameters).toEqual({ path, [parameter]: raised });
} finally {
await service.close();
}
},
);
it.each([
["max_string_literals", 1],
["max_string_literal_bytes", 3],
["max_string_bytes", 5],
["max_string_header_scan_bytes", 16],
["max_string_candidates", 1],
] as const)(
"identifies and recovers the exact inferred-string limit %s",
async (parameter, low) => {
const fixture = createGoRodataStringFixture({
format: "elf",
rodata: Buffer.from("alphabeta"),
headers: [
{ section: "data", offsetInSection: 0, ptr: 0x102000n, len: 5n },
{ section: "data", offsetInSection: 16, ptr: 0x102005n, len: 4n },
],
});
const root = await createTestTempDirectory(
"rea-go-string-budget-recovery-",
);
const path = join(root, "strings.elf");
await writeFile(path, fixture.bytes);
const service = new GoBinaryService(new GoBinaryProvider());
try {
const selected = { path, include_string_literals: true };
const limited = await service.inspect({ ...selected, [parameter]: low });
if (!limited.ok) throw limited.error;
expect(limited.value.normalized_result).toMatchObject({
string_literals: { truncated: true, limits_reached: [parameter] },
});
const recovered = await service.inspect({
...selected,
[parameter]: 1048576,
});
if (!recovered.ok) throw recovered.error;
expect(recovered.value.normalized_result).toMatchObject({
string_literals: {
truncated: false,
items: [{ value: "alpha" }, { value: "beta" }],
},
});
expect(recovered.value.subject).toEqual(limited.value.subject);
} finally {
await service.close();
}
},
);
it("cancels a many-frame compressed ELF section-name table", async () => {
const root = await createTestTempDirectory("rea-go-zstd-cancel-");
const path = join(root, "app");
await writeFile(path, elfFrameAllowanceFixture());
const reason = new Error("stop go frames");
const controller = new AbortController();
const yieldImpl = scheduler.yield.bind(scheduler);
let yields = 0;
const spy = vi.spyOn(scheduler, "yield").mockImplementation(async () => {
yields += 1;
await yieldImpl();
if (yields === 1) controller.abort(reason);
});
try {
const result = await new GoBinaryProvider().inspect(
{ path },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
_tag: "AnalysisCancelledError",
operation: "inspect_go_binary",
cause: reason,
});
} finally {
spy.mockRestore();
}
});