Files
rea/tests/acceptance/elfDebugLinkCli.test.ts
T
morluto 89c1dd3c32 fix(errors): refuse malformed target bytes as a target, not invalid input (#14195)
* fix(errors): refuse malformed target bytes as a target, not invalid input

parseFailureAnalysisError is the shared owner that turns a byte-format
parser's ParseFailure into a public refusal. It mapped malformed and
truncated bytes to an AnalysisInputError on the path field. The envelope
then reported invalid_request, with inspect_input_contract recovery and
"correct the listed fields". The arguments were valid; the target bytes
were the problem. Readers that wrap the ParseFailureError in an
ArtifactReaderFailure, and ArtifactOperationError reason=malformed, were
classified the same way.

Add AnalysisMalformedTargetError. It keeps the parser's kind, format,
detail, offset and field, and projects as unsupported_target with
details.format_failure. Its recovery is to choose another operation or a
well-formed copy of the target. Route both parser entry points through it
and reclassify ArtifactOperationError reason=malformed. Argument and
selection errors (missing files, directories, symlinks, JSON arguments)
stay invalid_request.

Fixes #14170

* docs(maven): describe duplicate variant names as malformed metadata

Duplicate Gradle variant names go through malformedInput, which now
reports unsupported_target with details.format_failure: malformed.
Point the earlier statement at that section instead of the old
invalid_format code.

* test(errors): expect malformed-target refusals from CLI byte-format readers

Truncated IPS, ELF, PE and shortcut bytes now project as unsupported_target with format_failure=malformed. Update the CLI acceptance cases that still expected invalid_request.

* fix(errors): keep a cancelled read a cancellation whatever its abort reason

projectOwnedArtifactInputFailure read the reader failure's cause without
checking the reader's own reason. A cancelled read carries the caller's
opaque abort reason as that cause, so aborting with a ParseFailureError
turned the cancellation into a non-retryable malformed-target refusal
before the shared cancellation projection ran. Only a reader whose own
reason is malformed or truncated now yields a malformed target.

The ELF dependency checkpoint cancellation test now also aborts with a
parser failure as the reason, through the public provider read.

* test(pe): expect malformed-target refusals from the PE filesystem boundaries

Short non-PE bytes now refuse the target rather than the request field.
The missing-file, directory, symlink and child-path controls keep their
caller-input expectations.

* fix(elf): refuse malformed ELF note bytes as a target, not invalid input

inspect_elf_notes shared this PR's root cause: its parser reported
structural violations as a reader "format" failure, which the shared
stable-artifact projection treats as a request-field error, so truncated
or non-ELF bytes still returned invalid_request. The parser now raises
malformed or truncated ParseFailureErrors, which the shared projection
reports as a malformed target with format_failure and format facts.

Consumers that interpreted the old reader reason now use the parser's
facts: debug-link build-id observation keys on ParseFailureError kinds,
and binary hardening drops its rewrap of note-parser format failures
into BinaryFormatFailure, which the parser's own failure supersedes.

* test(errors): own the byte readers' malformed-target projection in one CLI table

The PR repeated the same malformed -> unsupported_target mapping in a
dedicated CLI test per command and again in each provider's filesystem
boundary test. The stable-artifact parser-failure CLI table now owns it:
every byte reader it covers (now including ELF dependencies, debug link,
unwind ranges and native initializers) refuses a truncated ELF header as
a malformed target with operation, path, format_failure, retained file
identity and no argument recovery.

Removed as redundant with that table: the truncated or non-ELF/non-PE
CLI tests for ELF debug link, dependencies, unwind ranges and notes,
native initializers, and PE imports and certificates; and the
malformed-file blocks in thirteen filesystem boundary tests, which keep
their directory, symlink, missing-file and child-path controls. Format
specific refusals (a truncated IPS body, a wrong shortcut CLSID, DWARF
units) keep their own tests, as do the owner tests in
parseFailureAnalysisError and ArtifactOperationFailure.

* test(errors): expect malformed target bytes as unsupported_target in acceptance tests

The first full acceptance run of this PR found five expectations still
asserting invalid_request for target-byte failures: the timing test's
truncated ELF, a truncated DTB, duplicate Rust dependency JSON, and PE32
and PE64 load-config images without an MZ header. Assert the
unsupported_target code, with format_failure malformed where the
non-MZ PE path matches the already-updated PE imports test.
2026-11-24 00:44:40 +00:00

270 lines
9.3 KiB
TypeScript

import { writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect } from "vitest";
import { contractNamed } from "../../src/cli/contractCliDescription.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../../src/contracts/native/binaryDiagnosticsToolContracts.js";
import {
debuglinkSection,
elfDebugCandidateFixture,
elfDebugLinkFixture,
FIXTURE_BUILD_ID_HEX,
FIXTURE_DEBUG_NAME,
} from "../../src/native/elf/ElfDebugLink.fixture.js";
import {
compressedElfNoteSectionFixture,
coreFileNote,
gnuBuildIdNote,
withElf64DirectSectionCount,
} from "../../src/native/elf/ElfNotes.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
const debugLinkContract = contractNamed(
BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
"inspect_elf_debug_link",
);
cliTest(
"verifies a debug file while preserving both relative caller paths",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-debug-link-cli-");
const candidate = elfDebugCandidateFixture();
const image = elfDebugLinkFixture({
debuglink: debuglinkSection(FIXTURE_DEBUG_NAME, 0xae159abd, true),
});
const imagePath = join(root, "prog");
const candidatePath = join(root, "prog.debug");
await writeFile(imagePath, image);
await writeFile(candidatePath, candidate);
const selected = await cli.run({
arguments: [
"inspect-elf-debug-link",
"prog",
"--candidate-path",
"prog.debug",
"--json",
],
cwd: root,
});
expect(selected.exitCode, selected.stderr).toBe(0);
const evidence = debugLinkContract.outputSchema.parse(selected.json);
expect(evidence.subject.local_path).toBe(imagePath);
expect(evidence.caller_input_path).toBe("prog");
expect(evidence.caller_input_paths).toEqual({
candidate_path: "prog.debug",
});
expect(evidence.parameters).toEqual({
path: imagePath,
candidate_path: candidatePath,
});
expect(evidence.normalized_result.verification).toMatchObject({
status: "matches",
reason: null,
crc32: {
status: "match",
expected_hex: "ae159abd",
observed_hex: "ae159abd",
},
build_id: { status: "match", candidate_hex: FIXTURE_BUILD_ID_HEX },
});
expect(evidence.normalized_result.candidate).toMatchObject({
path: candidatePath,
format: "elf64",
debug_info: "present",
symtab: "present",
});
expect(evidence.normalized_result.debuglink.crc32_hex).toBe("ae159abd");
expect(evidence.normalized_result.build_id.hex).toBe(FIXTURE_BUILD_ID_HEX);
expect(evidence.normalized_result.debuglink.filename?.trust).toBe(
"observed-untrusted",
);
// Spelled out from the selected image directory, not by the derivation.
const directory = dirname(imagePath);
const globalDirectory =
process.platform === "win32"
? `${directory.slice(0, 1)}/${directory.slice(3).replaceAll("\\", "/")}`
: directory.slice(1);
const separator = process.platform === "win32" ? "\\" : "/";
expect(evidence.normalized_result.lookup_paths).toEqual(
[
[
"build_id",
`/usr/lib/debug/.build-id/${FIXTURE_BUILD_ID_HEX.slice(0, 2)}/${FIXTURE_BUILD_ID_HEX.slice(2)}.debug`,
],
[
"debug_subdirectory",
`${directory}${separator}.debug${separator}${FIXTURE_DEBUG_NAME}`,
],
[
"global_debug_directory",
`/usr/lib/debug/${globalDirectory}/${FIXTURE_DEBUG_NAME}`,
],
].map(([kind, path]) => ({ kind, path, trust: "observed-untrusted" })),
);
},
);
cliTest(
"compares both build IDs beside unrelated CORE mappings",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-debug-link-cli-miss-");
const imagePath = join(root, "prog");
const candidatePath = join(root, "other.debug");
const fileNote = coreFileNote(
Array.from({ length: 60 }, (_, index) => ({
start: 0x1000 + index * 0x1000,
end: 0x2000 + index * 0x1000,
file_ofs: 0,
path: "/bin/core-app",
})),
);
const notes = (hex: string) =>
Buffer.concat([fileNote, gnuBuildIdNote(hex)]);
await writeFile(
imagePath,
elfDebugLinkFixture({
type: 4,
notes: notes(FIXTURE_BUILD_ID_HEX),
debuglink: debuglinkSection(FIXTURE_DEBUG_NAME, 0x11111111, true),
}),
);
await writeFile(
candidatePath,
elfDebugLinkFixture({
type: 4,
debuglink: null,
notes: notes("dd".repeat(20)),
}),
);
const result = await cli.run({
arguments: [
"inspect-elf-debug-link",
imagePath,
"--candidate-path",
candidatePath,
"--json",
],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = debugLinkContract.outputSchema.parse(result.json);
expect(evidence.normalized_result.verification).toMatchObject({
status: "does_not_match",
reason: "crc32_and_build_id_mismatch",
crc32: { status: "mismatch", expected_hex: "11111111" },
build_id: {
status: "mismatch",
binary_hex: FIXTURE_BUILD_ID_HEX,
candidate_hex: "dd".repeat(20),
},
});
},
);
cliTest(
"retains separate readable build IDs beside compressed ELF notes",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-elf-debug-link-note-storage-",
);
const candidatePath = join(root, "candidate.debug");
const compressed = withElf64DirectSectionCount(
compressedElfNoteSectionFixture(64, true, "both"),
4,
);
const buildId = "a1".repeat(20);
const program = gnuBuildIdNote(buildId);
const section = gnuBuildIdNote(buildId);
await writeFile(
candidatePath,
elfDebugCandidateFixture({ buildIdHex: buildId }),
);
const programOffset = compressed.length;
const sectionOffset = programOffset + program.length;
const mixed = Buffer.concat([compressed, program, section]);
// Point the existing PT_NOTE at the readable program range rather than
// its initial alias of the compressed section, which is still section 1.
mixed.writeBigUInt64LE(BigInt(programOffset), 64 + 8);
mixed.writeBigUInt64LE(BigInt(program.length), 64 + 32);
mixed.writeBigUInt64LE(BigInt(program.length), 64 + 40);
mixed.writeBigUInt64LE(4n, 64 + 48);
// Add a readable section after the compressed section in directory order.
const row = Number(mixed.readBigUInt64LE(40)) + 3 * 64;
mixed.writeUInt32LE(1, row);
mixed.writeUInt32LE(7, row + 4);
mixed.writeBigUInt64LE(BigInt(sectionOffset), row + 24);
mixed.writeBigUInt64LE(BigInt(section.length), row + 32);
mixed.writeBigUInt64LE(4n, row + 48);
const withAlias = Buffer.from(mixed);
const compressedRow = row - 2 * 64;
const compressedOffset = withAlias.readBigUInt64LE(compressedRow + 24);
const compressedBytes = withAlias.readBigUInt64LE(compressedRow + 32);
// The relocated section directory leaves this program header slot free.
// Its range starts inside compressed storage, so it provides no note.
const aliasHeader = 64 + 56;
withAlias.writeUInt16LE(2, 56);
withAlias.fill(0, aliasHeader, aliasHeader + 56);
withAlias.writeUInt32LE(4, aliasHeader);
withAlias.writeBigUInt64LE(compressedOffset + 4n, aliasHeader + 8);
withAlias.writeBigUInt64LE(compressedBytes - 4n, aliasHeader + 32);
withAlias.writeBigUInt64LE(compressedBytes - 4n, aliasHeader + 40);
withAlias.writeBigUInt64LE(4n, aliasHeader + 48);
for (const [name, image] of [
["mixed-notes", mixed],
["partial-alias", withAlias],
] as const) {
const path = join(root, name);
await writeFile(path, image);
const result = await cli.run({
arguments: [
"inspect-elf-debug-link",
path,
"--candidate-path",
candidatePath,
"--json",
],
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const report = debugLinkContract.outputSchema.parse(
result.json,
).normalized_result;
expect(report.build_id).toMatchObject({
status: "unknown",
reason: "note_tables_unsupported",
hex: null,
ids: [buildId],
sources: [
{
hex: buildId,
table_kind: "program",
table_index: 0,
note: { offset: programOffset, bytes: program.length },
descriptor: { offset: programOffset + 16, bytes: 20 },
},
{
hex: buildId,
table_kind: "section",
table_index: 3,
note: { offset: sectionOffset, bytes: section.length },
descriptor: { offset: sectionOffset + 16, bytes: 20 },
},
],
});
expect(report.coverage.status).toBe("partial");
expect(report.lookup_paths.some(({ kind }) => kind === "build_id")).toBe(
false,
);
expect(report.verification).toMatchObject({
status: "cannot_verify",
build_id: {
status: "unavailable",
reason: "binary_build_id_unknown",
binary_hex: null,
candidate_hex: buildId,
},
});
}
},
);