mirror of
https://github.com/morluto/rea.git
synced 2026-11-30 18:39:24 +00:00
* 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.
170 lines
6.8 KiB
TypeScript
170 lines
6.8 KiB
TypeScript
import { readFile, symlink, writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { scheduler } from "node:timers/promises";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
import { runWithAnalysisOperationSnapshot } from "../../../src/domain/analysisOperationSnapshot.js";
|
|
import {
|
|
MAXIMUM_ZSTD_MAX_FRAMES,
|
|
MINIMUM_ZSTD_MAX_FRAMES,
|
|
} from "../../../src/domain/analysisResourceLimits.js";
|
|
import { createBinaryHardeningService } from "../../../src/composition/binaryDiagnostics/binaryHardening.js";
|
|
import { elfHardeningFixture } from "../../../src/native/hardening/BinaryHardening.fixture.js";
|
|
import { elfFrameAllowanceFixture } from "../../fixtures/binaryDiagnostics/elfFrameAllowance.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
|
|
describe("binary hardening stable filesystem boundary", () => {
|
|
it("reports non-file and missing selections as caller input errors", async () => {
|
|
const root = await createTestTempDirectory("rea-binary-hardening-files-");
|
|
const path = join(root, "app");
|
|
const alias = join(root, "alias");
|
|
const bytes = elfHardeningFixture();
|
|
await writeFile(path, bytes);
|
|
await symlink(path, alias);
|
|
const service = createBinaryHardeningService();
|
|
try {
|
|
for (const [candidate, reason] of [
|
|
[root, "invalid_format"],
|
|
[alias, "invalid_format"],
|
|
[join(root, "missing"), "invalid_value"],
|
|
[join(path, "child"), "invalid_value"],
|
|
] as const) {
|
|
const result = await service.inspect({ path: candidate });
|
|
if (result.ok) throw new Error("Expected file acquisition failure");
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisInputError",
|
|
operation: "inspect_binary_hardening",
|
|
issues: [{ path: ["path"], reason, message: expect.any(String) }],
|
|
});
|
|
}
|
|
const foreign = join(root, "foreign");
|
|
await writeFile(foreign, Buffer.from("not a binary"));
|
|
const unsupported = await service.inspect({ path: foreign });
|
|
if (unsupported.ok) throw new Error("Expected an unsupported target");
|
|
expect(unsupported.error._tag).toBe("AnalysisUnsupportedTargetError");
|
|
} finally {
|
|
await service.close();
|
|
}
|
|
});
|
|
|
|
it("returns typed resource and cancellation failures and leaves bytes unchanged", async () => {
|
|
const root = await createTestTempDirectory("rea-binary-hardening-budget-");
|
|
const path = join(root, "app");
|
|
const bytes = elfHardeningFixture();
|
|
await writeFile(path, bytes);
|
|
const service = createBinaryHardeningService();
|
|
try {
|
|
const tooSmall = await service.inspect({ path, max_file_bytes: 64 });
|
|
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 result = await service.inspect({ path });
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.normalized_result).toMatchObject({
|
|
format: "elf",
|
|
images: [{ status: "parsed", architecture: "x86_64" }],
|
|
});
|
|
expect(Buffer.compare(await readFile(path), bytes)).toBe(0);
|
|
} finally {
|
|
await service.close();
|
|
}
|
|
});
|
|
|
|
it("reports the dynamic-table allowance in entries, not bytes", async () => {
|
|
const root = await createTestTempDirectory("rea-binary-hardening-entries-");
|
|
const path = join(root, "app");
|
|
// A file-backed PT_DYNAMIC of 65,537 entries (16 bytes each in ELF64).
|
|
const fixture = elfHardeningFixture();
|
|
const bytes = Buffer.concat([fixture, Buffer.alloc(65_537 * 16)]);
|
|
const programs = Number(bytes.readBigUInt64LE(32));
|
|
const dynamic = Array.from(
|
|
{ length: bytes.readUInt16LE(56) },
|
|
(_, index) => programs + index * bytes.readUInt16LE(54),
|
|
).find((at) => bytes.readUInt32LE(at) === 2);
|
|
if (dynamic === undefined) throw new Error("Fixture has no PT_DYNAMIC");
|
|
bytes.writeBigUInt64LE(BigInt(fixture.length), dynamic + 8);
|
|
bytes.writeBigUInt64LE(65_537n * 16n, dynamic + 32);
|
|
await writeFile(path, bytes);
|
|
const service = createBinaryHardeningService();
|
|
try {
|
|
const result = await service.inspect({ path });
|
|
if (result.ok) throw new Error("Expected the entry allowance refusal");
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisResourceConstraintError",
|
|
fixedAllowance: { limit: 65_536, unit: "entries" },
|
|
});
|
|
} finally {
|
|
await service.close();
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("binary hardening compressed ELF names", () => {
|
|
it("projects a section-name frame cap as an adjustable zstd.max_frames limit", async () => {
|
|
const root = await createTestTempDirectory("rea-binary-hardening-zstd-");
|
|
const path = join(root, "app");
|
|
await writeFile(path, elfFrameAllowanceFixture());
|
|
const service = createBinaryHardeningService();
|
|
try {
|
|
const result = await runWithAnalysisOperationSnapshot(
|
|
{ revision: 1, overrides: { "zstd.max_frames": 1 } },
|
|
() =>
|
|
service.inspect({ path }, { signal: new AbortController().signal }),
|
|
);
|
|
expect(result.ok).toBe(false);
|
|
if (result.ok) return;
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisResourceConstraintError",
|
|
operation: "inspect_binary_hardening",
|
|
resource: "cpu",
|
|
limit: {
|
|
setting: "zstd.max_frames",
|
|
effective_value: 1,
|
|
source: "runtime",
|
|
minimum: MINIMUM_ZSTD_MAX_FRAMES,
|
|
maximum: MAXIMUM_ZSTD_MAX_FRAMES,
|
|
unit: "count",
|
|
},
|
|
});
|
|
} finally {
|
|
await service.close();
|
|
}
|
|
});
|
|
|
|
it("cancels a many-frame compressed section-name table", async () => {
|
|
const root = await createTestTempDirectory("rea-binary-hardening-cancel-");
|
|
const path = join(root, "app");
|
|
await writeFile(path, elfFrameAllowanceFixture());
|
|
const reason = new Error("stop hardening 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);
|
|
});
|
|
const service = createBinaryHardeningService();
|
|
try {
|
|
const result = await service.inspect(
|
|
{ path },
|
|
{ signal: controller.signal },
|
|
);
|
|
expect(result.ok).toBe(false);
|
|
if (result.ok) return;
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisCancelledError",
|
|
operation: "inspect_binary_hardening",
|
|
cause: reason,
|
|
});
|
|
} finally {
|
|
spy.mockRestore();
|
|
await service.close();
|
|
}
|
|
});
|
|
});
|