Files
reverse-engineering-anything/tests/boundary/filesystem/mavenGradleMetadata.test.ts
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

151 lines
5.6 KiB
TypeScript

import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createMavenGradleMetadataService } from "../../../src/composition/mavenGradleMetadata.js";
import { mavenGradleMetadataSchema } from "../../../src/domain/java/mavenGradleMetadata.js";
import { mavenPomFixture } from "../../../src/java/MavenGradleMetadata.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("Maven POM and Gradle module metadata stable filesystem boundary", () => {
it("admits a minimal Gradle document by its first decoded member", async () => {
const root = await createTestTempDirectory("rea-gradle-format-order-");
const path = join(root, "module.json");
const service = createMavenGradleMetadataService();
const inspect = async (source: string) => {
await writeFile(path, source);
return service.inspect({ path });
};
try {
// JSON object enumeration promotes numeric keys ahead of string keys.
const minimal = await inspect(
String.raw`{"f\u006frmatVersion":"1.1","0":null}`,
);
if (!minimal.ok) throw minimal.error;
expect(minimal.value.normalized_result).toMatchObject({
format: "gradle-module",
gradle: { format_version: "1.1", variants: [] },
dependencies: [],
coverage: { status: "complete" },
});
expect(minimal.value.limitations).not.toContainEqual(
expect.stringContaining("interpreted using Gradle module metadata 1.1"),
);
for (const invalid of [
'{"variants":[],"formatVersion":"1.1"}',
'{"formatVersion":"1.1","component":null,"variants":[]}',
'{"formatVersion":"1.1","createdBy":[]}',
'{"formatVersion":"1.1","createdBy":{"gradle":false}}',
'{"formatVersion":"1.1","variants":[{"name":"runtime","attributes":[]}]}',
]) {
const result = await inspect(invalid);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisMalformedTargetError" },
});
}
const unfamiliar = await inspect(
'{"formatVersion":"2.0","component":{"module":"demo"},"variants":[]}',
);
if (!unfamiliar.ok) throw unfamiliar.error;
expect(unfamiliar.value.normalized_result).toMatchObject({
coordinates: { artifact_id: "demo" },
gradle: { format_version: "2.0", variants: [] },
});
expect(unfamiliar.value.limitations).toContainEqual(
expect.stringContaining("interpreted using Gradle module metadata 1.1"),
);
} finally {
await service.close();
}
});
it("uses exact Gradle variant names to identify their dependency rows", async () => {
const root = await createTestTempDirectory("rea-gradle-variant-identity-");
const path = join(root, "demo.module");
const service = createMavenGradleMetadataService();
const inspect = async (names: readonly unknown[]) => {
const variants = names.map((name, index) => ({
name,
dependencies: [{ group: "example", module: `dep-${String(index)}` }],
dependencyConstraints: [{ group: "example", module: "shared" }],
}));
await writeFile(path, JSON.stringify({ formatVersion: "1.1", variants }));
return service.inspect({ path });
};
try {
const whitespaceOnlyName = " \t ";
const distinct = await inspect([
"runtime",
" runtime ",
"",
undefined,
whitespaceOnlyName,
"",
undefined,
]);
if (!distinct.ok) throw distinct.error;
const report = mavenGradleMetadataSchema.parse(
distinct.value.normalized_result,
);
const expectedNames = [
"runtime",
" runtime ",
null,
null,
whitespaceOnlyName,
null,
null,
];
expect(report.gradle?.variants.map((row) => row.name)).toEqual(
expectedNames,
);
expect(report.dependencies.map((row) => row.variant)).toEqual(
expectedNames,
);
expect(report.dependency_management.map((row) => row.variant)).toEqual(
expectedNames,
);
expect(await inspect(["runtime", "runtime"])).toMatchObject({
ok: false,
error: {
_tag: "AnalysisMalformedTargetError",
failure: {
detail: expect.stringContaining("duplicate variant name"),
},
},
});
expect(await inspect([false])).toMatchObject({
ok: false,
error: {
_tag: "AnalysisMalformedTargetError",
failure: { detail: expect.stringContaining("variant.name") },
},
});
} finally {
await service.close();
}
});
it("returns typed resource and cancellation failures", async () => {
const root = await createTestTempDirectory("rea-maven-gradle-budget-");
const path = join(root, "pom.xml");
await writeFile(path, mavenPomFixture);
const service = createMavenGradleMetadataService();
try {
const tooSmall = await service.inspect({ path, max_file_bytes: 16 });
if (tooSmall.ok) throw new Error("Expected resource budget failure");
expect(tooSmall.error._tag).toBe("AnalysisResourceConstraintError");
const cancelled = await service.inspect(
{ path },
{ signal: AbortSignal.abort() },
);
if (cancelled.ok) throw new Error("Expected cancellation");
expect(cancelled.error._tag).toBe("AnalysisCancelledError");
const control = await service.inspect({ path });
if (!control.ok) throw control.error;
} finally {
await service.close();
}
});
});