diff --git a/docs/development/tool-design.md b/docs/development/tool-design.md index b4fbb589d9..3159dadb75 100644 --- a/docs/development/tool-design.md +++ b/docs/development/tool-design.md @@ -287,6 +287,19 @@ Complete traversal or inventory does not make unavailable values equal. A partial aggregate fingerprint difference cannot establish modification when omissions alone explain it; independently proven differences still survive. +A byte-format parser reports failure with `ParseFailureError` from +`src/domain/parseFailure.ts`: `malformed`, `truncated`, `unsupported`, or +`limit`, with the format and, when known, the offset and field. Read bounded +fields through `BinaryReader` (`src/native/metadata/BinaryContainer.ts`), which +raises that failure instead of a bare `RangeError`. Providers project the +failure with `parseFailureAnalysisError` rather than their own `instanceof` +ladder; a `limit` stays with its producer, which knows the budget to name. +`scripts/verify/architecture-guards.mjs` counts the remaining raw `Buffer` and +`DataView` reads, plain `Error` throws in parser folders, and plain `JSON.parse` +of parser input against `scripts/verify/architecture-guard-baselines.json`. A +file may not exceed its count; after removing copies, run +`node scripts/verify/architecture-guards.mjs --shrink-baselines`. + Keep format recognition separate from provider admission. A recognizable header can supply useful observations while later structure remains unresolved or a provider cannot accept the artifact. Report the reason at the affected boundary diff --git a/scripts/verify/architecture-guard-baselines.json b/scripts/verify/architecture-guard-baselines.json new file mode 100644 index 0000000000..b12e726ef2 --- /dev/null +++ b/scripts/verify/architecture-guard-baselines.json @@ -0,0 +1,209 @@ +{ + "parser-json-parse": { + "src/android/JadxProtocol.ts": 2, + "src/android/JadxWorkspaceRoot.ts": 1, + "src/artifacts/AsarHeader.ts": 1, + "src/artifacts/ReleaseExposureReader.ts": 1, + "src/artifacts/apple/AppleAssetCatalogAnalysis.ts": 1, + "src/artifacts/deno/DenoSectionLayout.ts": 1, + "src/domain/android/proguardMapping.ts": 1, + "src/domain/apple/interfaceBuilderKeyedArchive.ts": 1, + "src/evm/EvmoleInterfaceWorker.ts": 2, + "src/firmware/FirmwareReports.ts": 1, + "src/model/SafetensorsHeader.ts": 1, + "src/native/LldbRetainedObservations.ts": 1, + "src/native/apple/losslessJson.ts": 1, + "src/native/parsers/plist.ts": 1, + "src/rust/RustAuditableReader.ts": 1 + }, + "parser-plain-throw": { + "src/android/JadxJavaProbe.ts": 1, + "src/android/JadxWorkspaceRoot.ts": 4, + "src/artifacts/DirectoryArtifactReader.ts": 1, + "src/artifacts/NativeDmgArtifactReader.ts": 1, + "src/artifacts/ReleaseExposureReader.ts": 1, + "src/artifacts/StreamBytes.ts": 1, + "src/artifacts/ZipArtifactReader.ts": 1, + "src/artifacts/apple/BinaryPlistMaterializer.ts": 4, + "src/artifacts/apple/KeyedArchiveReader.ts": 1, + "src/artifacts/apple/NibArchive.ts": 19, + "src/artifacts/apple/PlistScalars.ts": 3, + "src/artifacts/apple/PropertyListDecodeBudget.ts": 25, + "src/domain/apple/interfaceBuilderKeyedArchive.ts": 1, + "src/domain/apple/keyedArchive.ts": 5, + "src/domain/apple/plistValue.ts": 3, + "src/domain/native/functionByteCoverage.ts": 1, + "src/domain/python/marshalUtf8.ts": 1, + "src/dotnet/ManagedArtifactInspector.ts": 1, + "src/dotnet/ManagedDecodeBudget.ts": 1, + "src/dotnet/ManagedMemberInspector.ts": 2, + "src/dotnet/ManagedMethodBodyReader.ts": 6, + "src/dotnet/ManagedSnapshot.ts": 1, + "src/dotnet/ManagedStaticProvider.ts": 1, + "src/firmware/FirmwareCommand.ts": 2, + "src/il2cpp/Il2cppMetadataFile.ts": 2, + "src/model/ModelFormat.ts": 2, + "src/model/ModelHeaderReader.ts": 1, + "src/native/AppleDispatchMetadata.ts": 3, + "src/native/AppleMachoFixups.ts": 48, + "src/native/AppleMachoSelection.ts": 25, + "src/native/AppleObjcCategories.ts": 1, + "src/native/AppleObjcDispatchFacets.ts": 6, + "src/native/AppleObjcProperties.ts": 2, + "src/native/AppleObjcProtocols.ts": 4, + "src/native/AppleSwiftConformanceTypeReference.ts": 1, + "src/native/AppleSwiftDispatchFacets.ts": 1, + "src/native/AppleSwiftNominalTypes.ts": 3, + "src/native/AppleSwiftVtables.ts": 3, + "src/native/LldbCallTracer.ts": 1, + "src/native/LldbRetainedObservations.ts": 1, + "src/native/MachoCommandNames.ts": 1, + "src/native/NativeMacOSProvider.ts": 2, + "src/native/NativeMachoInspection.ts": 4, + "src/native/NativeUiHelperRuntime.ts": 1, + "src/native/NativeUiInterruptionControl.ts": 1, + "src/native/apple/AppleIpsFieldReader.ts": 1, + "src/native/parsers/demangle.ts": 3, + "src/native/parsers/lipo.ts": 1, + "src/native/parsers/plist.ts": 1, + "src/native/pwndbg/PwndbgCoreContext.ts": 2, + "src/native/pwntools/PwntoolsDecoder.ts": 2, + "src/native/pwntools/PwntoolsResourceLimits.ts": 1 + }, + "raw-buffer-read": { + "src/application/BinaryTargetResolver.ts": 1, + "src/application/MipsElfMetadata.ts": 10, + "src/application/MipsGnuAttributes.ts": 2, + "src/artifacts/AsarHeader.ts": 4, + "src/artifacts/DesktopFileInspection.ts": 4, + "src/artifacts/FitArtifactReader.ts": 1, + "src/artifacts/GodotPckArtifactReader.ts": 6, + "src/artifacts/UnityFsStructures.ts": 8, + "src/artifacts/WxapkgStructures.ts": 3, + "src/artifacts/apple/MachoEncryptionReader.ts": 1, + "src/artifacts/apple/MachoLoadCommandReader.ts": 12, + "src/artifacts/apple/NibArchive.ts": 8, + "src/artifacts/apple/PlistScalars.ts": 6, + "src/artifacts/apple/PropertyListDecodeBudget.ts": 2, + "src/artifacts/bun/BunModuleGraphLayout.ts": 22, + "src/artifacts/deno/DenoSectionLayout.ts": 2, + "src/artifacts/deno/DenoStandaloneLocation.ts": 3, + "src/artifacts/dotnet/DotnetBundle.ts": 5, + "src/artifacts/fit/FitStructure.ts": 3, + "src/artifacts/nodeSea/NodeSeaBlob.ts": 4, + "src/artifacts/nodeSea/NodeSeaLocation.ts": 2, + "src/artifacts/pyinstaller/CArchiveLayout.ts": 8, + "src/artifacts/pyinstaller/MarshalSubset.ts": 2, + "src/artifacts/pyinstaller/PyzArchive.ts": 1, + "src/browser/PngVisualDiff.ts": 7, + "src/domain/apkSignature/apkSignatureSchemes.ts": 1, + "src/domain/apkSignature/apkSigningBlock.ts": 7, + "src/domain/apkSignature/apkV1Signature.ts": 15, + "src/domain/apple/diskImageFormat.ts": 4, + "src/domain/apple/jvmClassFile.ts": 2, + "src/domain/apple/machoContainer.ts": 13, + "src/domain/apple/machoDylibCommand.ts": 4, + "src/domain/apple/machoLoadCommands.ts": 8, + "src/domain/apple/machoSectionHeader.ts": 8, + "src/domain/apple/machoSegmentHeader.ts": 5, + "src/domain/binaryTarget.ts": 10, + "src/domain/desktop/elfDependencies.ts": 4, + "src/domain/desktop/openPgpKeys.ts": 2, + "src/domain/desktop/zipDirectory.ts": 14, + "src/domain/dosMz.ts": 10, + "src/domain/elfDynamicEntry.ts": 4, + "src/domain/elfFixedHeader.ts": 4, + "src/domain/elfProgramHeader.ts": 4, + "src/domain/elfRawTableDeclarations.ts": 7, + "src/domain/elfRelocation.ts": 6, + "src/domain/elfSectionHeader.ts": 6, + "src/domain/elfSymbol.ts": 8, + "src/domain/firmware/fitImage.ts": 1, + "src/domain/gamecubeDol.ts": 6, + "src/domain/godotPckFormat.ts": 5, + "src/domain/il2cpp/il2cppMetadataHeaderPrefix.ts": 3, + "src/domain/inesContainer.ts": 5, + "src/domain/managed/managedCliHeaderPrefix.ts": 5, + "src/domain/native/elfNoteLayout.ts": 3, + "src/domain/native/nativeAotPe.ts": 37, + "src/domain/peCoffHeader.ts": 4, + "src/domain/peOptionalHeader.ts": 12, + "src/domain/peSectionHeader.ts": 5, + "src/domain/pngHeader.ts": 4, + "src/domain/python/pythonBytecodeIdentity.ts": 1, + "src/domain/riscvIsaDeclaration.ts": 1, + "src/domain/uimageFormat.ts": 10, + "src/domain/unityfsFormat.ts": 5, + "src/domain/windows/ntfsMft.ts": 19, + "src/domain/windows/ntfsMftAttributes.ts": 38, + "src/domain/windows/ntfsUsnJournal.ts": 23, + "src/domain/wxapkgFormat.ts": 4, + "src/domain/zipEndOfCentralDirectory.ts": 8, + "src/domain/zipPackageFormat.ts": 3, + "src/dotnet/ManagedConstantValue.ts": 12, + "src/dotnet/ManagedFieldConstants.ts": 1, + "src/dotnet/ManagedFieldDefinitionRows.ts": 1, + "src/dotnet/ManagedMemberInstructionDecoder.ts": 30, + "src/dotnet/ManagedMemberPointers.ts": 2, + "src/dotnet/ManagedMemberRows.ts": 2, + "src/dotnet/ManagedMetadataHeaps.ts": 8, + "src/dotnet/ManagedMetadataInventoryRows.ts": 16, + "src/dotnet/ManagedMetadataLayout.ts": 7, + "src/dotnet/ManagedMethodBodyReader.ts": 5, + "src/dotnet/ManagedMethodDefinitionRows.ts": 3, + "src/dotnet/ManagedNativeBoundaryHelpers.ts": 1, + "src/dotnet/ManagedPeReader.ts": 5, + "src/dotnet/ManagedTypeDefinitionRows.ts": 1, + "src/erlang/BeamParser.ts": 3, + "src/firmware/devicetree/DevicetreeParser.ts": 4, + "src/flutter/DartElf.ts": 2, + "src/ghidra/GhidraLoadImageValues.ts": 1, + "src/ghidra/extensions/GhidraExtensions.ts": 1, + "src/go/GoStringLiterals.ts": 4, + "src/gpu/AmdGpuMetadata.ts": 4, + "src/gpu/ClangOffloadBundle.ts": 14, + "src/gpu/CudaFatbinary.ts": 13, + "src/gpu/GpuInventory.ts": 3, + "src/hopper/HopperAnalysisProfile.ts": 1, + "src/il2cpp/Il2cppBinaryImage.ts": 2, + "src/il2cpp/Il2cppBinaryRegistration.ts": 8, + "src/il2cpp/Il2cppMetadataFile.ts": 24, + "src/il2cpp/Il2cppMetadataFormat.ts": 3, + "src/il2cpp/Il2cppMetadataMembers.ts": 5, + "src/il2cpp/Il2cppMetadataV108.ts": 3, + "src/model/GgufHeader.ts": 26, + "src/model/SafetensorsHeader.ts": 2, + "src/native/AppleDispatchMetadata.ts": 4, + "src/native/AppleMachoFixups.ts": 22, + "src/native/AppleMachoSelection.ts": 2, + "src/native/AppleObjcClassImportBindings.ts": 1, + "src/native/AppleObjcDispatchFacets.ts": 1, + "src/native/AppleSwiftDispatchFacets.ts": 1, + "src/native/MachoCommandNames.ts": 35, + "src/native/elf/ElfNoteParser.ts": 27, + "src/native/elf/ElfUnwindTables.ts": 6, + "src/native/elf/KernelBuildConfig.ts": 7, + "src/native/elf/KernelModuleParser.ts": 5, + "src/native/hardening/ElfHardening.ts": 2, + "src/native/hardening/MachoHardening.ts": 4, + "src/native/initializers/ElfInitializerSymbols.ts": 4, + "src/native/initializers/MachoInitializers.ts": 22, + "src/native/initializers/NativeInitializersProvider.ts": 1, + "src/native/metadata/ElfPointerRelocations.ts": 6, + "src/native/metadata/ElfSectionNameTable.ts": 6, + "src/native/metadata/readBinaryContainer.ts": 1, + "src/native/pe/PeCertificateAsn1.ts": 2, + "src/native/pe/PeCertificateParser.ts": 3, + "src/native/pe/PeLoadConfigParser.ts": 7, + "src/native/pe/PeResourceLayout.ts": 3, + "src/native/pe/PeResourceParser.ts": 11, + "src/native/pe/PeResourceTreeFacts.ts": 9, + "src/native/pwndbg/CoreFileMappingAuthority.ts": 1, + "src/native/pwntools/PwntoolsRecordedCrashProvider.ts": 1, + "src/native/pwntools/RecordedCrashSourceBindings.ts": 6, + "src/native/windows/WindowsShortcutParser.ts": 49, + "src/pcap/PcapDnsWire.ts": 5, + "src/python/PythonPycParser.ts": 9, + "src/v8/V8CodeCacheParser.ts": 1 + } +} diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index 540c72f76f..d6176f59dc 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -1,6 +1,6 @@ import { spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; -import { readFile, readdir } from "node:fs/promises"; +import { readFile, readdir, writeFile } from "node:fs/promises"; import { join, relative, sep } from "node:path"; import { fileURLToPath } from "node:url"; @@ -162,6 +162,149 @@ check( ], ); +// Counted baselines record the remaining copies of a pattern that has one +// owner. A file may not gain copies and a baseline may not grow; when copies +// are removed, `--shrink-baselines` lowers the recorded counts (and never +// raises them) so the next removal cannot be undone silently. +const baselinePath = join( + root, + "scripts/verify/architecture-guard-baselines.json", +); +const baselines = JSON.parse(await readFile(baselinePath, "utf8")); +const shrinkBaselines = process.argv.includes("--shrink-baselines"); +let baselinesShrunk = false; +const checkCounted = (label, key, selected, pattern, owners) => { + const baseline = baselines[key] ?? {}; + const counts = new Map(); + for (const file of selected) { + if (owners.includes(file.path)) continue; + const count = file.content.match(pattern)?.length ?? 0; + if (count > 0) counts.set(file.path, count); + } + const grown = []; + const stale = []; + for (const [path, count] of counts) { + const allowed = baseline[path] ?? 0; + if (count > allowed) + grown.push(` ${path}: ${count} (baseline ${allowed})`); + } + for (const [path, allowed] of Object.entries(baseline)) { + const count = counts.get(path) ?? 0; + if (count < allowed) stale.push({ path, count, allowed }); + } + if (grown.length > 0) + failures.push(`${label}; new copies are not allowed:\n${grown.join("\n")}`); + if (stale.length === 0) return; + if (shrinkBaselines) { + for (const { path, count } of stale) + if (count === 0) delete baseline[path]; + else baseline[path] = count; + baselines[key] = baseline; + baselinesShrunk = true; + return; + } + failures.push( + `${label}; copies were removed, so lower the baseline with \`node scripts/verify/architecture-guards.mjs --shrink-baselines\`:\n${stale + .map( + ({ path, count, allowed }) => + ` ${path}: ${count} (baseline ${allowed})`, + ) + .join("\n")}`, + ); +}; + +// Byte-format parsers read untrusted input. Bounds, truncation and failure +// kind belong to BinaryReader (src/native/metadata/BinaryContainer.ts) and +// the ParseFailure algebra (src/domain/parseFailure.ts), not to each parser. +const PARSER_FOLDERS = [ + "src/android/", + "src/apkSignature/", + "src/artifacts/", + "src/dotnet/", + "src/electron/", + "src/erlang/", + "src/evm/", + "src/firmware/", + "src/flutter/", + "src/go/", + "src/gpu/", + "src/il2cpp/", + "src/model/", + "src/native/", + "src/python/", + "src/rust/", + "src/v8/", + "src/wasm/", + ...[ + "android", + "apkSignature", + "apple", + "electron", + "erlang", + "evm", + "firmware", + "flutter", + "go", + "gpu", + "il2cpp", + "managed", + "model", + "native", + "python", + "rust", + "v8", + "wasm", + "windows", + ].map((folder) => `src/domain/${folder}/`), +]; +const parserFiles = files.filter((file) => + PARSER_FOLDERS.some((folder) => file.path.startsWith(folder)), +); + +// An unchecked Buffer or DataView read throws a bare RangeError past the end, +// which a catch site cannot tell from a host stack or string limit. +checkCounted( + "raw Buffer or DataView numeric read (use BinaryReader from src/native/metadata/BinaryContainer)", + "raw-buffer-read", + files, + /\.(?:read(?:Big)?U?Int(?:8|16|32|64)?(?:LE|BE)?|readBigUint64(?:LE|BE)|readUint(?:8|16|32)(?:LE|BE)?|read(?:Float|Double)(?:LE|BE)|get(?:Big)?(?:Uint|Int)(?:8|16|32|64)|getFloat(?:32|64))\(/gu, + ["src/native/metadata/BinaryContainer.ts"], +); + +checkCounted( + "plain Error, TypeError or RangeError thrown by a parser (throw a ParseFailureError from src/domain/parseFailure)", + "parser-plain-throw", + parserFiles, + /throw new (?:Error|TypeError|RangeError)\(/gu, + [], +); + +// JSON.parse keeps the last of repeated member names without saying so; a +// parser of artifact content must state its duplicate-member policy +// (src/domain/jsonDuplicateMember.ts finds a repeated name). +checkCounted( + "plain JSON.parse of parser input (state the duplicate-member policy; see src/domain/jsonDuplicateMember)", + "parser-json-parse", + parserFiles, + /JSON\.parse\(/gu, + [], +); + +if (baselinesShrunk) { + const sorted = Object.fromEntries( + Object.entries(baselines).map(([key, counts]) => [ + key, + Object.fromEntries( + Object.entries(counts).sort(([left], [right]) => + left < right ? -1 : left > right ? 1 : 0, + ), + ), + ]), + ); + await writeFile(baselinePath, `${JSON.stringify(sorted, null, 2)}\n`); + console.log(`Lowered counted baselines in ${relative(root, baselinePath)}.`); +} + if (failures.length > 0) { console.error(`Architecture guards failed:\n\n${failures.join("\n\n")}\n`); process.exit(1); diff --git a/src/domain/parseFailure.ts b/src/domain/parseFailure.ts new file mode 100644 index 0000000000..caa10ef1db --- /dev/null +++ b/src/domain/parseFailure.ts @@ -0,0 +1,85 @@ +/** + * How a byte-format parser failed. One algebra for every format, so the + * public category depends on what the parser established, not on which error + * class it happened to throw. + * + * - `malformed`: the bytes violate the format's structure. + * - `truncated`: a declared structure starts in the bytes but ends past them. + * - `unsupported`: the bytes use a form outside this decoder's coverage. + * - `limit`: a named decode budget stopped the parse; the input is not shown + * to be invalid. + */ +export type ParseFailureKind = + | "malformed" + | "truncated" + | "unsupported" + | "limit"; + +interface ParseFailureFacts { + /** The format being decoded, such as `elf` or `windows-shortcut`. */ + readonly format: string; + readonly detail: string; + /** Byte offset of the structure that failed, when the parser knows it. */ + readonly offset?: number; + /** The structure or field that failed, when the parser names it. */ + readonly field?: string; +} + +/** A parse outcome the parser established, carried with its facts. */ +export type ParseFailure = ParseFailureFacts & + ( + | { readonly kind: "malformed" } + | { readonly kind: "truncated" } + | { + readonly kind: "unsupported"; + /** The input holds the content, in a form this decoder cannot read. */ + readonly undecodedContent: boolean; + } + | { + readonly kind: "limit"; + readonly limit: { readonly name: string; readonly maximum: number }; + } + ); + +/** The one throwable carrier for a {@link ParseFailure}. */ +export class ParseFailureError< + Kind extends ParseFailureKind = ParseFailureKind, +> extends Error { + readonly _tag = "ParseFailureError"; + + constructor( + readonly failure: Extract, + options?: ErrorOptions, + ) { + super(failure.detail, options); + this.name = "ParseFailureError"; + } + + get kind(): Kind { + return this.failure.kind as Kind; + } +} + +/** The bytes violate the format's structure. */ +export const malformedInput = ( + format: string, + detail: string, + facts?: Pick, +): ParseFailureError<"malformed"> => + new ParseFailureError({ kind: "malformed", format, detail, ...facts }); + +/** The bytes use a form outside this decoder's coverage. */ +export const unsupportedInput = ( + format: string, + detail: string, + facts?: Pick & { + readonly undecodedContent?: boolean; + }, +): ParseFailureError<"unsupported"> => + new ParseFailureError({ + kind: "unsupported", + format, + detail, + ...facts, + undecodedContent: facts?.undecodedContent ?? false, + }); diff --git a/src/domain/parseFailureAnalysisError.test.ts b/src/domain/parseFailureAnalysisError.test.ts new file mode 100644 index 0000000000..a55605dde4 --- /dev/null +++ b/src/domain/parseFailureAnalysisError.test.ts @@ -0,0 +1,69 @@ +import { expect, it } from "vitest"; + +import { + AnalysisInputError, + AnalysisUnsupportedTargetError, +} from "./analysisErrorCore.js"; +import { + malformedInput, + ParseFailureError, + unsupportedInput, +} from "./parseFailure.js"; +import { parseFailureAnalysisError } from "./parseFailureAnalysisError.js"; + +const project = (cause: unknown) => + parseFailureAnalysisError("inspect_example", "/tmp/sample.bin", cause); + +it.each([ + malformedInput("elf", "section table overlaps the header"), + new ParseFailureError({ + kind: "truncated", + format: "elf", + detail: "section table runs past the end of the file", + offset: 64, + field: "section table", + }), +])("refuses $failure.kind bytes as an invalid selected path", (cause) => { + const error = project(cause); + expect(error).toBeInstanceOf(AnalysisInputError); + expect(error).toMatchObject({ + cause, + issues: [ + { + path: ["path"], + reason: "invalid_format", + message: `Selected artifact /tmp/sample.bin: ${cause.message}`, + }, + ], + }); +}); + +it("refuses an unsupported form as an unsupported target, keeping undecoded content", () => { + const cause = unsupportedInput("go", "compressed build-info section", { + undecodedContent: true, + }); + const error = project(cause); + expect(error).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(error).toMatchObject({ + cause, + path: "/tmp/sample.bin", + reason: "compressed build-info section", + undecodedContent: true, + }); +}); + +it("leaves a limit and any other cause to the producer", () => { + expect( + project( + new ParseFailureError({ + kind: "limit", + format: "elf", + detail: "section table exceeds the structural budget", + limit: { name: "structure", maximum: 16 }, + }), + ), + ).toBeUndefined(); + expect(project(new RangeError("Maximum call stack size exceeded"))).toBe( + undefined, + ); +}); diff --git a/src/domain/parseFailureAnalysisError.ts b/src/domain/parseFailureAnalysisError.ts new file mode 100644 index 0000000000..20b21d756a --- /dev/null +++ b/src/domain/parseFailureAnalysisError.ts @@ -0,0 +1,41 @@ +import { + AnalysisInputError, + AnalysisUnsupportedTargetError, +} from "./analysisErrorCore.js"; +import { ParseFailureError } from "./parseFailure.js"; + +/** + * The public refusal for a parser's format failure on the selected artifact. + * + * Malformed and truncated bytes are an invalid `path`; unsupported bytes are + * an unsupported target. A `limit` and any other cause return `undefined`: + * a limit's recovery names a budget only its producer knows. + */ +export const parseFailureAnalysisError = ( + operation: string, + path: string, + cause: unknown, +): AnalysisInputError | AnalysisUnsupportedTargetError | undefined => { + if (!(cause instanceof ParseFailureError)) return undefined; + const { failure } = cause; + switch (failure.kind) { + case "limit": + return undefined; + case "unsupported": + return new AnalysisUnsupportedTargetError( + operation, + path, + failure.detail, + { cause, undecodedContent: failure.undecodedContent }, + ); + case "malformed": + case "truncated": + return new AnalysisInputError(operation, { cause }, [ + { + path: ["path"], + reason: "invalid_format", + message: `Selected artifact ${path}: ${failure.detail}`, + }, + ]); + } +}; diff --git a/src/electron/ElectronFuseFailures.ts b/src/electron/ElectronFuseFailures.ts index 7a63d618d6..fbbd472c52 100644 --- a/src/electron/ElectronFuseFailures.ts +++ b/src/electron/ElectronFuseFailures.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../domain/parseFailureAnalysisError.js"; import { ELECTRON_FUSE_PROVIDER_IDENTITY } from "./ElectronFuseProviderIdentity.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { @@ -17,7 +18,6 @@ import { AnalysisInputError, AnalysisOutputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, } from "../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; @@ -27,10 +27,7 @@ import { NonRegularFileReadError, } from "../filesystem/RegularFile.js"; import { ElectronFusePathFailure } from "./ElectronFusePath.js"; -import { - ElectronFuseFormatFailure, - ElectronFuseResourceFailure, -} from "./ElectronFuseReader.js"; +import { ElectronFuseResourceFailure } from "./ElectronFuseReader.js"; const OPERATION = "inspect_electron_fuses"; @@ -100,18 +97,8 @@ export const electronFuseFailure = ( ), }, ); - if (cause instanceof ElectronFuseFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError(operation, path, cause.message, { - cause, - }) - : new AnalysisInputError(operation, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${path}: ${cause.message}`, - }, - ]); + const formatFailure = parseFailureAnalysisError(operation, path, cause); + if (formatFailure !== undefined) return formatFailure; if (cause instanceof RegularFileChangedError) return new AnalysisArtifactChangedError(operation, path, cause.message, { cause, diff --git a/src/electron/ElectronFuseReader.ts b/src/electron/ElectronFuseReader.ts index a5eadc6062..25418a0c93 100644 --- a/src/electron/ElectronFuseReader.ts +++ b/src/electron/ElectronFuseReader.ts @@ -1,4 +1,5 @@ import { observeMzWindowsHeader } from "../domain/dosMz.js"; +import { malformedInput, unsupportedInput } from "../domain/parseFailure.js"; import { readPeCoffHeader } from "../domain/peCoffHeader.js"; import { readElfFixedHeader } from "../domain/elfFixedHeader.js"; import { decodePeMachine } from "../domain/peMachine.js"; @@ -59,17 +60,6 @@ interface SliceRange { readonly hidden?: boolean; } -/** The selected container is malformed or outside the supported formats. */ -export class ElectronFuseFormatFailure extends Error { - constructor( - readonly kind: "malformed" | "unsupported", - message: string, - ) { - super(message); - this.name = "ElectronFuseFormatFailure"; - } -} - /** A measured bound was hit before a complete fuse report could be returned. */ export class ElectronFuseResourceFailure extends Error { constructor( @@ -130,8 +120,8 @@ export const readElectronFuseImage = async ( ) throw new RegularFileChangedError(path); if (!before.isFile() || before.isSymbolicLink()) - throw new ElectronFuseFormatFailure( - "unsupported", + throw unsupportedInput( + "native-binary", `Expected a regular file without a symlink: ${path}`, ); if (before.size > BigInt(ELECTRON_FUSE_LIMITS.maximumFileBytes)) @@ -227,8 +217,8 @@ const identifyContainer = async ( { index: 0, fileOffset: 0, size, architecture: pe.architecture }, ], }; - throw new ElectronFuseFormatFailure( - "unsupported", + throw unsupportedInput( + "native-binary", `Selected artifact ${path} does not contain a Mach-O, ELF, or PE container.`, ); }; @@ -248,10 +238,9 @@ const identifyMacho = async ( facts.status === "not-mach-o" ? `Selected artifact ${path} does not contain a Mach-O, ELF, or PE container.` : facts.reason; - throw new ElectronFuseFormatFailure( - facts.status === "malformed" ? "malformed" : "unsupported", - reason, - ); + throw facts.status === "malformed" + ? malformedInput("macho", reason) + : unsupportedInput("macho", reason); } const fat = readFatHeaderPrefix(head); const format = diff --git a/src/firmware/devicetree/DevicetreeProvider.ts b/src/firmware/devicetree/DevicetreeProvider.ts index ee14aba535..be4d5e3499 100644 --- a/src/firmware/devicetree/DevicetreeProvider.ts +++ b/src/firmware/devicetree/DevicetreeProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { projectOwnedArtifactIdentityFailure, projectSelectedArtifactFileFailure, @@ -18,18 +19,13 @@ import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js" import type { DevicetreePort } from "../../application/binaryDiagnostics/DevicetreePort.js"; import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; -import { - AnalysisInputError, - AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { MAX_DEVICETREE_FILE_BYTES, type InspectDevicetreeInput, } from "../../domain/firmware/devicetree.js"; import { err, ok } from "../../domain/result.js"; import { DEVICETREE_PROVIDER } from "../../domain/investigationProviders.js"; -import { BinaryFormatFailure } from "../../native/metadata/BinaryContainer.js"; import { DevicetreeLimitFailure, parseDevicetree } from "./DevicetreeParser.js"; const OPERATION = "inspect_devicetree"; @@ -97,21 +93,8 @@ const devicetreeFailurePrimary = ( }, { cause, retryable: false, remediationAction: cause.message }, ); - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: cause.message, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; const identityFailure = projectOwnedArtifactIdentityFailure( facts, OPERATION, diff --git a/src/go/GoBinaryImage.ts b/src/go/GoBinaryImage.ts index e89856b93b..9c54c67be5 100644 --- a/src/go/GoBinaryImage.ts +++ b/src/go/GoBinaryImage.ts @@ -122,14 +122,18 @@ export const readGoBinaryImage = ( ); }; verifyMapping(32); - const reader = new BinaryReader(bytes, byte_order === "little"); + const reader = new BinaryReader( + bytes, + byte_order === "little", + container.format, + ); const ptrSize = bytes[header + 14]; const flags = bytes[header + 15] ?? 0; if ((flags & ~3) !== 0) throw new BinaryFormatFailure( "unsupported", "Go build-info flags contain an unsupported format bit", - true, + { undecodedContent: true }, ); if ((flags & 2) === 0 && (flags & 1) !== (byte_order === "big" ? 1 : 0)) throw new BinaryFormatFailure( diff --git a/src/go/GoBinaryProvider.ts b/src/go/GoBinaryProvider.ts index 9c66a2de72..911aa42273 100644 --- a/src/go/GoBinaryProvider.ts +++ b/src/go/GoBinaryProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../domain/parseFailureAnalysisError.js"; import { jsonValueByteLength } from "../domain/jsonValueByteLength.js"; import { GO_BINARY_PROVIDER_IDENTITY } from "./GoBinaryProviderIdentity.js"; import { @@ -22,10 +23,8 @@ import type { ExecutionOptions } from "../application/AnalysisProvider.js"; import type { GoBinaryPort } from "../application/go/GoBinaryPort.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { - AnalysisInputError, AnalysisOutputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, } from "../domain/analysisErrorCore.js"; import { goBinarySchema, @@ -41,10 +40,7 @@ import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; import { err, ok, type Result } from "../domain/result.js"; import { readGoBinaryImage, type GoBinaryImage } from "./GoBinaryImage.js"; import { requireSelectedNativeImage } from "../native/metadata/MachoSliceSelection.js"; -import { - BinaryFormatFailure, - BinaryResourceFailure, -} from "../native/metadata/BinaryContainer.js"; +import { BinaryResourceFailure } from "../native/metadata/BinaryContainer.js"; const OPERATION = "inspect_go_binary"; @@ -100,19 +96,8 @@ const failureForPrimary = ( }, ); } - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError(OPERATION, path, cause.message, { - cause, - undecodedContent: cause.undecodedContent, - }) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${path}: ${cause.message}`, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, path, cause); + if (formatFailure !== undefined) return formatFailure; if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure diff --git a/src/go/GoBuildInfoSearch.ts b/src/go/GoBuildInfoSearch.ts index 0941cf5df3..7f6c28eb74 100644 --- a/src/go/GoBuildInfoSearch.ts +++ b/src/go/GoBuildInfoSearch.ts @@ -52,7 +52,11 @@ export const goBuildInfoSearch = ( bytes: Buffer, container: BinaryContainer, ): readonly GoBuildInfoSearchRange[] => { - const reader = new BinaryReader(bytes, container.byte_order === "little"); + const reader = new BinaryReader( + bytes, + container.byte_order === "little", + container.format, + ); const named: GoBuildInfoSearchRange[] = []; for (const section of container.sections) { if (section.format === "elf" && section.name === ".go.buildinfo") { @@ -70,7 +74,7 @@ export const goBuildInfoSearch = ( throw new BinaryFormatFailure( "unsupported", "Compressed ELF build-info sections are unsupported", - true, + { undecodedContent: true }, ); const search = { ...reader.fileRange( diff --git a/src/gpu/CudaInfo.ts b/src/gpu/CudaInfo.ts index cfe7b36d93..67a12a4dbf 100644 --- a/src/gpu/CudaInfo.ts +++ b/src/gpu/CudaInfo.ts @@ -53,7 +53,7 @@ export function* readCudaInfo( little: boolean, budget = new CudaMetadataBudget(), ): Generator { - const reader = new BinaryReader(bytes, little); + const reader = new BinaryReader(bytes, little, "cuda-nv-info"); for (let offset = 0; offset < bytes.length;) { budget.visit(); const head = reader.range(offset, 4, "CUDA nv.info record"); @@ -98,7 +98,7 @@ export const readCudaParameters = ( complete = false; continue; } - const r = new BinaryReader(record.data, little); + const r = new BinaryReader(record.data, little, "cuda-nv-info"); if (r.u32(0) !== 0) complete = false; const parameter = { ordinal: r.u16(4), diff --git a/src/gpu/GpuElfKernels.ts b/src/gpu/GpuElfKernels.ts index 116e6f3871..ffb5e44b98 100644 --- a/src/gpu/GpuElfKernels.ts +++ b/src/gpu/GpuElfKernels.ts @@ -172,7 +172,7 @@ const indexCudaMetadata = async ( if (record.format !== 4 || record.attribute !== 0x2f) continue; if (record.data.length !== 8) rejectGpu("CUDA register count record has an unsupported extent"); - const r = new BinaryReader(record.data, directory.little), + const r = new BinaryReader(record.data, directory.little, "elf"), key = `${row.link}:${r.u32(0)}`; const values = registerFacts.get(key) ?? new Map(); const value = r.u32(4); @@ -311,9 +311,11 @@ const cudaKernels = async ( ); extendedIndices = await sectionBytes(source, extended, index.budget); } - sectionIndex = new BinaryReader(extendedIndices, directory.little).u32( - (offset / width) * 4, - ); + sectionIndex = new BinaryReader( + extendedIndices, + directory.little, + "elf", + ).u32((offset / width) * 4); } const text = directory.sections[sectionIndex]; if (text === undefined || text.type !== 1 || (text.flags & 4n) === 0n) @@ -460,7 +462,7 @@ export const readAmdElfMetadata = async ( ); retainedBytes += sectionSize; const bytes = await sectionBytes(source, section), - r = new BinaryReader(bytes, directory.little); + r = new BinaryReader(bytes, directory.little, "elf"); for (let p = 0; p < bytes.length;) { if (bytes.length - p < 12) rejectGpu("Truncated ELF note header"); const namesize = r.u32(p), diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts index 9d5dddce90..b3ef2922e7 100644 --- a/src/native/AppleDispatchMetadata.ts +++ b/src/native/AppleDispatchMetadata.ts @@ -467,7 +467,7 @@ const appleDispatchMetadataPrimaryFailure = ( { cause, remediationAction: - cause.kind === "malformed" + cause.kind !== "unsupported" ? "Select a Mach-O artifact with well-formed metadata sections, reopen the target, then retry." : "Select a supported little-endian 64-bit Mach-O artifact, reopen the target, then retry.", }, diff --git a/src/native/android/AndroidJniLibrary.ts b/src/native/android/AndroidJniLibrary.ts index 39197fc004..5d31e698dc 100644 --- a/src/native/android/AndroidJniLibrary.ts +++ b/src/native/android/AndroidJniLibrary.ts @@ -506,7 +506,10 @@ export const inspectAndroidJniLibrary = async ( ) return err({ kind: "capacity", message: cause.message }); if (cause instanceof BinaryFormatFailure) - return err({ kind: cause.kind, message: cause.message }); + return err({ + kind: cause.kind === "unsupported" ? "unsupported" : "malformed", + message: cause.message, + }); if (cause instanceof ElfPointerRelocationFailure) return err({ kind: diff --git a/src/native/elf/ElfNotesProvider.ts b/src/native/elf/ElfNotesProvider.ts index 4994990b0a..d6158d03ab 100644 --- a/src/native/elf/ElfNotesProvider.ts +++ b/src/native/elf/ElfNotesProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { projectOwnedArtifactIdentityFailure, projectSelectedArtifactFileFailure, @@ -18,11 +19,7 @@ import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js" import type { ElfNotesPort } from "../../application/binaryDiagnostics/ElfNotesPort.js"; import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; -import { - AnalysisInputError, - AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { MAX_INSPECT_ELF_NOTE_ENTRIES, @@ -31,7 +28,6 @@ import { } from "../../domain/native/elfNotes.js"; import { err, ok } from "../../domain/result.js"; import { ELF_NOTES_PROVIDER } from "../../domain/investigationProviders.js"; -import { BinaryFormatFailure } from "../metadata/BinaryContainer.js"; import { ElfNoteSectionNameBudgetFailure, parseElfNotes, @@ -127,21 +123,8 @@ const elfNotesFailurePrimary = ( remediationAction: sectionNameBudgetRemediation(cause), }, ); - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: cause.message, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; const identityFailure = projectOwnedArtifactIdentityFailure( facts, OPERATION, diff --git a/src/native/elf/ElfUnwindRangesProvider.ts b/src/native/elf/ElfUnwindRangesProvider.ts index 4a68a87e48..d4f80f286c 100644 --- a/src/native/elf/ElfUnwindRangesProvider.ts +++ b/src/native/elf/ElfUnwindRangesProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { projectOwnedArtifactIdentityFailure, projectSelectedArtifactFileFailure, @@ -15,11 +16,7 @@ import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js" import type { ElfUnwindRangesPort } from "../../application/binaryDiagnostics/ElfUnwindRangesPort.js"; import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; -import { - AnalysisInputError, - AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { MAX_INSPECT_ELF_UNWIND_FILE_BYTES, @@ -28,10 +25,7 @@ import { } from "../../domain/native/elfUnwindRanges.js"; import { err, ok } from "../../domain/result.js"; import { ELF_UNWIND_RANGES_PROVIDER } from "../../domain/investigationProviders.js"; -import { - BinaryFormatFailure, - BinaryResourceFailure, -} from "../metadata/BinaryContainer.js"; +import { BinaryResourceFailure } from "../metadata/BinaryContainer.js"; import { ElfUnwindSymbolTextFailure, parseElfUnwindRanges, @@ -132,21 +126,8 @@ const elfUnwindFailurePrimary = ( ), }, ); - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: cause.message, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; const identityFailure = projectOwnedArtifactIdentityFailure( facts, OPERATION, diff --git a/src/native/elf/KernelModuleProvider.ts b/src/native/elf/KernelModuleProvider.ts index f13e1beebf..32d05c978e 100644 --- a/src/native/elf/KernelModuleProvider.ts +++ b/src/native/elf/KernelModuleProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { projectOwnedArtifactIdentityFailure, projectSelectedArtifactFileFailure, @@ -18,11 +19,7 @@ import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js" import type { KernelModulePort } from "../../application/binaryDiagnostics/KernelModulePort.js"; import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; -import { - AnalysisInputError, - AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { MAX_INSPECT_KERNEL_MODULE_ENTRIES, @@ -31,10 +28,7 @@ import { } from "../../domain/native/kernelModule.js"; import { err, ok } from "../../domain/result.js"; import { KERNEL_MODULE_PROVIDER } from "../../domain/investigationProviders.js"; -import { - BinaryFormatFailure, - BinaryResourceFailure, -} from "../metadata/BinaryContainer.js"; +import { BinaryResourceFailure } from "../metadata/BinaryContainer.js"; import { parseKernelModule } from "./KernelModuleParser.js"; const OPERATION = "inspect_kernel_module"; @@ -119,21 +113,8 @@ const kernelModuleFailurePrimary = ( ), }, ); - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: cause.message, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; const identityFailure = projectOwnedArtifactIdentityFailure( facts, OPERATION, diff --git a/src/native/exports/NativeExportParser.ts b/src/native/exports/NativeExportParser.ts index 119e3907f1..d87f1c8d0a 100644 --- a/src/native/exports/NativeExportParser.ts +++ b/src/native/exports/NativeExportParser.ts @@ -181,7 +181,7 @@ const parsePeExports = (bytes: Buffer, artifact: Artifact): NativeExports => { ...PE_LIMITATIONS, ], }; - const reader = new BinaryReader(bytes, true); + const reader = new BinaryReader(bytes, true, "pe"); const mappings = imageFileMappings(image); const map = (rva: number, size: number): number => mappedFileOffset(mappings, base + BigInt(rva), size, image.zero_fills); @@ -636,7 +636,7 @@ function* parseElfExports( artifact: Artifact, ): Generator { const directory = readElfDirectoryFromBuffer(bytes); - const reader = new BinaryReader(bytes, directory.little); + const reader = new BinaryReader(bytes, directory.little, "elf"); const result = { artifact, format: "elf" as const, diff --git a/src/native/exports/NativeExportsProvider.ts b/src/native/exports/NativeExportsProvider.ts index 57eea47376..bdb446426b 100644 --- a/src/native/exports/NativeExportsProvider.ts +++ b/src/native/exports/NativeExportsProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { imageFileSizeRemediation, projectSelectedArtifactFileFailure, @@ -21,11 +22,7 @@ import type { NativeExportsPort } from "../../application/binaryDiagnostics/Nati import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import type { ResourceConstraintRecovery } from "../../domain/analysisErrorCore.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { - AnalysisInputError, - AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { MAX_INSPECT_NATIVE_EXPORTS_FILE_BYTES, @@ -34,10 +31,7 @@ import { import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { err, ok } from "../../domain/result.js"; import { NATIVE_EXPORTS_PROVIDER } from "../../domain/investigationProviders.js"; -import { - BinaryFormatFailure, - BinaryResourceFailure, -} from "../metadata/BinaryContainer.js"; +import { BinaryResourceFailure } from "../metadata/BinaryContainer.js"; import { NativeExportLimitFailure, type NativeExportLimit, @@ -140,23 +134,8 @@ const nativeExportsFailurePrimary = ( ), }, ); - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { - cause, - }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${input.path}: ${cause.message}`, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure diff --git a/src/native/hardening/BinaryHardeningProvider.ts b/src/native/hardening/BinaryHardeningProvider.ts index d2ac7d2d74..fbec8ba874 100644 --- a/src/native/hardening/BinaryHardeningProvider.ts +++ b/src/native/hardening/BinaryHardeningProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { imageFileSizeRemediation, projectOwnedArtifactIdentityFailure, @@ -20,11 +21,7 @@ import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js" import type { BinaryHardeningPort } from "../../application/binaryDiagnostics/BinaryHardeningPort.js"; import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { - AnalysisInputError, - AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { BINARY_HARDENING_LIMITATIONS, @@ -35,10 +32,7 @@ import { import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { err, ok } from "../../domain/result.js"; import { BINARY_HARDENING_PROVIDER } from "../../domain/investigationProviders.js"; -import { - BinaryFormatFailure, - BinaryResourceFailure, -} from "../metadata/BinaryContainer.js"; +import { BinaryResourceFailure } from "../metadata/BinaryContainer.js"; import { readElfHardening } from "./ElfHardening.js"; import { readMachoHardening } from "./MachoHardening.js"; import { readPeHardening } from "./PeHardening.js"; @@ -157,21 +151,8 @@ const binaryHardeningFailurePrimary = ( ), }, ); - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${input.path}: ${cause.message}`, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure diff --git a/src/native/hardening/MachoHardening.ts b/src/native/hardening/MachoHardening.ts index 3cb9855115..a0e953fa62 100644 --- a/src/native/hardening/MachoHardening.ts +++ b/src/native/hardening/MachoHardening.ts @@ -296,7 +296,7 @@ const readSliceImage = async ( rows, }; } catch (cause) { - if (cause instanceof BinaryFormatFailure && cause.kind === "malformed") { + if (cause instanceof BinaryFormatFailure && cause.kind !== "unsupported") { if (ref.thin) throw cause; return failedImage(ref, "malformed", cause.message, header); } diff --git a/src/native/initializers/NativeInitializersProvider.ts b/src/native/initializers/NativeInitializersProvider.ts index a0f488e625..79083c6af5 100644 --- a/src/native/initializers/NativeInitializersProvider.ts +++ b/src/native/initializers/NativeInitializersProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { imageFileSizeRemediation, projectSelectedArtifactFileFailure, @@ -17,11 +18,7 @@ import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js" import type { NativeInitializersPort } from "../../application/binaryDiagnostics/NativeInitializersPort.js"; import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { - AnalysisInputError, - AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { MAX_INSPECT_NATIVE_INITIALIZERS_FILE_BYTES, @@ -231,21 +228,8 @@ const failurePrimary = ( ), }, ); - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${input.path}: ${cause.message}`, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure diff --git a/src/native/metadata/BinaryContainer.test.ts b/src/native/metadata/BinaryContainer.test.ts index e0a017c539..677bfff8e4 100644 --- a/src/native/metadata/BinaryContainer.test.ts +++ b/src/native/metadata/BinaryContainer.test.ts @@ -7,6 +7,7 @@ import { expect, it } from "vitest"; import { BinaryFormatFailure, BinaryMappingFailure, + BinaryReader, BinaryStringReadLimitFailure, createFileMappingIndex, mappedFileOffset, @@ -14,6 +15,27 @@ import { type BinaryContainer, } from "./BinaryContainer.js"; +it("preserves representable offsets for invalid file ranges", () => { + const reader = new BinaryReader(Buffer.alloc(120), true, "elf"); + for (const read of [ + () => reader.range(128, 1, "segment"), + () => reader.fileRange(128n, 1n, "segment"), + ]) { + try { + read(); + throw new Error("Expected malformed range"); + } catch (error) { + expect(error).toBeInstanceOf(BinaryFormatFailure); + expect(error).toMatchObject({ + failure: { kind: "malformed", offset: 128, field: "segment" }, + }); + } + } + expect(() => reader.fileRange(2n ** 60n, 1n, "segment")).toThrow( + BinaryFormatFailure, + ); +}); + it("distinguishes a mapped string read allowance from malformed bytes", () => { const bytes = Buffer.from("long-name\0"); const index = createFileMappingIndex([ @@ -232,3 +254,42 @@ it("keeps a JVM-sized FAT count unconfirmed while rejecting malformed zero-count ), ); }); + +/** An x86-64 ELF executable with one PT_LOAD declaring `fileSize` bytes. */ +const elfWithLoadSegment = (fileSize: bigint): Buffer => { + const bytes = Buffer.alloc(64 + 56); + bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1]); + bytes.writeUInt16LE(2, 16); // ET_EXEC + bytes.writeUInt16LE(0x3e, 18); // EM_X86_64 + bytes.writeUInt32LE(1, 20); + bytes.writeBigUInt64LE(64n, 32); // e_phoff + bytes.writeUInt16LE(64, 52); + bytes.writeUInt16LE(56, 54); + bytes.writeUInt16LE(1, 56); // e_phnum + bytes.writeUInt16LE(64, 58); + bytes.writeUInt32LE(1, 64); // PT_LOAD + bytes.writeUInt32LE(5, 68); + bytes.writeBigUInt64LE(0x400000n, 80); + bytes.writeBigUInt64LE(0x400000n, 88); + bytes.writeBigUInt64LE(fileSize, 96); + bytes.writeBigUInt64LE(fileSize, 104); + bytes.writeBigUInt64LE(0x1000n, 112); + return bytes; +}; + +it("names a load segment that runs past the end of the file as truncated", () => { + expect(readBinaryContainer(elfWithLoadSegment(120n)).mappings).toHaveLength( + 1, + ); + expect(() => readBinaryContainer(elfWithLoadSegment(0x1000n))).toThrow( + expect.objectContaining({ + failure: { + kind: "truncated", + format: "elf", + detail: "ELF load segment range is outside the file", + offset: 0, + field: "ELF load segment", + }, + }), + ); +}); diff --git a/src/native/metadata/BinaryContainer.ts b/src/native/metadata/BinaryContainer.ts index a587637ad0..2347806cc2 100644 --- a/src/native/metadata/BinaryContainer.ts +++ b/src/native/metadata/BinaryContainer.ts @@ -4,18 +4,40 @@ import { type ZeroFillMapping, } from "../../domain/virtualFileMapping.js"; import type { PeDataDirectory } from "../../domain/peOptionalHeader.js"; +import { ParseFailureError } from "../../domain/parseFailure.js"; + +/** Native container facts a format failure can name. */ +interface BinaryFormatFailureFacts { + /** The image holds the metadata, in a form this reader cannot decode. */ + readonly undecodedContent?: boolean; + /** The native format, when the reader knows it. */ + readonly format?: string; + readonly offset?: number; + readonly field?: string; +} /** Distinguish corrupt recognized binaries from containers outside parser coverage. */ -export class BinaryFormatFailure extends Error { +export class BinaryFormatFailure extends ParseFailureError< + "malformed" | "truncated" | "unsupported" +> { constructor( - readonly kind: "malformed" | "unsupported", + kind: "malformed" | "truncated" | "unsupported", message: string, - /** The image holds the metadata, in a form this reader cannot decode. */ - readonly undecodedContent = false, + facts: BinaryFormatFailureFacts = {}, ) { - super(message); + const { undecodedContent = false, format = "native-binary", ...at } = facts; + super( + kind === "unsupported" + ? { kind, format, detail: message, undecodedContent, ...at } + : { kind, format, detail: message, ...at }, + ); this.name = "BinaryFormatFailure"; } + + /** The image holds the metadata, in a form this reader cannot decode. */ + get undecodedContent(): boolean { + return this.failure.kind === "unsupported" && this.failure.undecodedContent; + } } /** A missing file span is a candidate miss; conflicting owners are malformed. */ @@ -29,13 +51,18 @@ export class BinaryMappingFailure extends BinaryFormatFailure { } /** Resource boundary exceeded while decoding metadata or native container structure. */ -export class BinaryResourceFailure extends Error { +export class BinaryResourceFailure extends ParseFailureError<"limit"> { constructor( readonly boundary: "build-info" | "structure" | "search", readonly maximum_bytes: number, message: string, ) { - super(message); + super({ + kind: "limit", + format: "native-binary", + detail: message, + limit: { name: boundary, maximum: maximum_bytes }, + }); this.name = "BinaryResourceFailure"; } } @@ -177,6 +204,8 @@ export class BinaryReader { constructor( readonly bytes: Buffer, readonly little: boolean, + /** The native format these bytes hold, named in every failure. */ + readonly format: string, ) {} range(offset: number, size: number, label: string): Buffer { @@ -185,12 +214,22 @@ export class BinaryReader { !Number.isSafeInteger(size) || offset < 0 || size < 0 || - offset > this.bytes.length || - size > this.bytes.length - offset + offset > this.bytes.length ) throw new BinaryFormatFailure( "malformed", `${label} range is truncated or outside the file`, + { + format: this.format, + field: label, + ...(Number.isSafeInteger(offset) ? { offset } : {}), + }, + ); + if (size > this.bytes.length - offset) + throw new BinaryFormatFailure( + "truncated", + `${label} range is truncated or outside the file`, + { format: this.format, offset, field: label }, ); return this.bytes.subarray(offset, offset + size); } @@ -212,13 +251,25 @@ export class BinaryReader { } fileRange(offset: bigint, size: bigint, label: string): FileMapping { - if ( - offset > BigInt(this.bytes.length) || - size > BigInt(this.bytes.length) - offset - ) + const length = BigInt(this.bytes.length); + if (offset < 0n || offset > length) throw new BinaryFormatFailure( "malformed", `${label} range is outside the file`, + { + format: this.format, + field: label, + ...(offset >= BigInt(Number.MIN_SAFE_INTEGER) && + offset <= BigInt(Number.MAX_SAFE_INTEGER) + ? { offset: Number(offset) } + : {}), + }, + ); + if (size > length - offset) + throw new BinaryFormatFailure( + "truncated", + `${label} range is outside the file`, + { format: this.format, offset: Number(offset), field: label }, ); const result = { address: 0n, offset: Number(offset), size: Number(size) }; this.range(result.offset, result.size, label); diff --git a/src/native/metadata/ElfImage.ts b/src/native/metadata/ElfImage.ts index 2679080095..25d0ec27c1 100644 --- a/src/native/metadata/ElfImage.ts +++ b/src/native/metadata/ElfImage.ts @@ -21,7 +21,7 @@ export const readElfImage = ( ): Extract => { const directory = readElfDirectoryFromBuffer(bytes); const { bits } = directory; - const reader = new BinaryReader(bytes, directory.little); + const reader = new BinaryReader(bytes, directory.little, "elf"); const mappings: FileMapping[] = []; const loadRegions: LoadRegion[] = []; const executableMappings: FileMapping[] = []; diff --git a/src/native/metadata/MachoImage.ts b/src/native/metadata/MachoImage.ts index 933777aab6..c0bc408748 100644 --- a/src/native/metadata/MachoImage.ts +++ b/src/native/metadata/MachoImage.ts @@ -34,7 +34,7 @@ export const readMachoImage = (bytes: Buffer): BinaryContainer => { const table = parsed.value; const { headerSize, commandBytes, littleEndian: little } = table; const bits = table.wide ? 64 : 32; - const reader = new BinaryReader(bytes, little); + const reader = new BinaryReader(bytes, little, "macho"); const commandStart = reader.table( BigInt(headerSize), commandBytes, diff --git a/src/native/metadata/NativeSectionDirectory.ts b/src/native/metadata/NativeSectionDirectory.ts index 051fb0714d..ebad21239e 100644 --- a/src/native/metadata/NativeSectionDirectory.ts +++ b/src/native/metadata/NativeSectionDirectory.ts @@ -334,7 +334,7 @@ export function* readElfSectionDirectory( export function* readPeSectionDirectory( fileSize: number, ): Generator { - const dos = new BinaryReader(yield request(fileSize, 0n, 64n), true); + const dos = new BinaryReader(yield request(fileSize, 0n, 64n), true, "pe"); if (dos.u16(0) !== 0x5a4d) reject("Missing DOS MZ header"); const evidence = parseMzHeaderEvidence(dos.bytes, fileSize); const observed = evidence.windowsHeader; @@ -348,7 +348,11 @@ export function* readPeSectionDirectory( throw new BinaryFormatFailure("unsupported", limitation); } const pe = observed.offset; - const coff = new BinaryReader(yield request(fileSize, BigInt(pe), 24n), true); + const coff = new BinaryReader( + yield request(fileSize, BigInt(pe), 24n), + true, + "pe", + ); const confirmed = withMzWindowsHeaderSignature( dos.bytes, fileSize, diff --git a/src/native/metadata/PeImage.ts b/src/native/metadata/PeImage.ts index 1441829ac1..9b311408b5 100644 --- a/src/native/metadata/PeImage.ts +++ b/src/native/metadata/PeImage.ts @@ -79,7 +79,7 @@ export type PeImage = BinaryContainer & { /** Read PE32/PE32+ native image mappings and section facts. */ export const readPeImage = (bytes: Buffer): PeImage => { - const reader = new BinaryReader(bytes, true); + const reader = new BinaryReader(bytes, true, "pe"); const pe = peHeaderOffset(reader); const optional = pe + 24; const coff = readPeCoffHeader(bytes.subarray(pe + 4, pe + 24)); diff --git a/src/native/pe/PeBinaryFailure.ts b/src/native/pe/PeBinaryFailure.ts index 8b0b99c4dd..1d6706e304 100644 --- a/src/native/pe/PeBinaryFailure.ts +++ b/src/native/pe/PeBinaryFailure.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { projectSelectedArtifactFileFailure, stableArtifactInputFailure, @@ -14,16 +15,11 @@ import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisArtifactChangedError, AnalysisCancelledError, - AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, type ResourceConstraintRecovery, } from "../../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; -import { - BinaryFormatFailure, - BinaryResourceFailure, -} from "../metadata/BinaryContainer.js"; +import { BinaryResourceFailure } from "../metadata/BinaryContainer.js"; interface PeBinaryInput { readonly path: string; @@ -75,21 +71,8 @@ const peBinaryFailurePrimary = ( { cause, ...options.limitRecovery(limit) }, ); } - if (cause instanceof BinaryFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - operation, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(operation, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${input.path}: ${cause.message}`, - }, - ]); + const formatFailure = parseFailureAnalysisError(operation, input.path, cause); + if (formatFailure !== undefined) return formatFailure; if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure diff --git a/src/native/pe/PeImportParser.ts b/src/native/pe/PeImportParser.ts index 6208eb28ec..7fe54e8fb7 100644 --- a/src/native/pe/PeImportParser.ts +++ b/src/native/pe/PeImportParser.ts @@ -145,7 +145,7 @@ export const parsePeImports = async ( const image = readPeImage(bytes); const bits = image.bits; const base = image.image_base; - const reader = new BinaryReader(bytes, true); + const reader = new BinaryReader(bytes, true, "pe"); const lookup = createFileMappingIndex( imageFileMappings(image), image.zero_fills, diff --git a/src/native/windows/WindowsShortcut.errors.ts b/src/native/windows/WindowsShortcut.errors.ts index 53f753841a..7045542a7c 100644 --- a/src/native/windows/WindowsShortcut.errors.ts +++ b/src/native/windows/WindowsShortcut.errors.ts @@ -1,14 +1,3 @@ -/** Distinguish a file that is not a Shell Link from later structural damage. */ -export class WindowsShortcutFormatFailure extends Error { - constructor( - readonly kind: "malformed" | "unsupported", - message: string, - ) { - super(message); - this.name = "WindowsShortcutFormatFailure"; - } -} - /** Caller-selected budgets that bound Shell Link expansion. */ export type WindowsShortcutSelectedBoundary = | "id_list_items" diff --git a/src/native/windows/WindowsShortcutParser.test.ts b/src/native/windows/WindowsShortcutParser.test.ts index ae8de3c88a..29847f4402 100644 --- a/src/native/windows/WindowsShortcutParser.test.ts +++ b/src/native/windows/WindowsShortcutParser.test.ts @@ -18,10 +18,8 @@ import { wrongClsidShortcut, } from "../../../tests/fixtures/binaryDiagnostics/windowsShortcut.js"; import { parseWindowsShortcut } from "./WindowsShortcutParser.js"; -import { - WindowsShortcutFormatFailure, - WindowsShortcutResourceFailure, -} from "./WindowsShortcut.errors.js"; +import { WindowsShortcutResourceFailure } from "./WindowsShortcut.errors.js"; +import { ParseFailureError } from "../../domain/parseFailure.js"; const input = inspectWindowsShortcutInputSchema.parse({ path: "/artifacts/shortcut.lnk", @@ -311,7 +309,7 @@ it("lists an unknown ExtraData signature instead of dropping it", async () => { it("rejects a Shell Link whose CLSID is not the documented value", async () => { await expect(parse(wrongClsidShortcut())).rejects.toBeInstanceOf( - WindowsShortcutFormatFailure, + ParseFailureError, ); }); @@ -319,8 +317,12 @@ it("rejects a HeaderSize other than 0x4C", async () => { await expect( parse(windowsShortcutBytes({ headerSize: 0x50, extraData: [] })), ).rejects.toMatchObject({ - name: "WindowsShortcutFormatFailure", - kind: "malformed", + failure: { + kind: "malformed", + format: "windows-shortcut", + offset: 0, + field: "HeaderSize", + }, }); }); diff --git a/src/native/windows/WindowsShortcutParser.ts b/src/native/windows/WindowsShortcutParser.ts index e2bc7771bd..371ca5e090 100644 --- a/src/native/windows/WindowsShortcutParser.ts +++ b/src/native/windows/WindowsShortcutParser.ts @@ -11,10 +11,8 @@ import type { WindowsShortcutStringField, WindowsShortcutUuidV1, } from "../../domain/native/windowsShortcut.js"; -import { - WindowsShortcutFormatFailure, - WindowsShortcutResourceFailure, -} from "./WindowsShortcut.errors.js"; +import { WindowsShortcutResourceFailure } from "./WindowsShortcut.errors.js"; +import { malformedInput } from "../../domain/parseFailure.js"; type Artifact = WindowsShortcut["artifact"]; @@ -1156,21 +1154,23 @@ export const parseWindowsShortcut = async ( ): Promise => { assertArtifactReadActive(signal); if (bytes.length < HEADER_BYTES) - throw new WindowsShortcutFormatFailure( - "malformed", + throw malformedInput( + "windows-shortcut", `File is ${String(bytes.length)} bytes, below the 76-byte ShellLinkHeader`, ); const headerSize = bytes.readUInt32LE(0); if (headerSize !== HEADER_BYTES) - throw new WindowsShortcutFormatFailure( - "malformed", + throw malformedInput( + "windows-shortcut", `HeaderSize ${String(headerSize)} is not 0x4C`, + { offset: 0, field: "HeaderSize" }, ); const clsid = formatGuid(bytes, 4); if (clsid !== SHELL_LINK_CLSID) - throw new WindowsShortcutFormatFailure( - "malformed", + throw malformedInput( + "windows-shortcut", `LinkCLSID ${clsid} is not ${SHELL_LINK_CLSID}`, + { offset: 4, field: "LinkCLSID" }, ); const flags = bytes.readUInt32LE(20); const unicode = (flags & 0x00000080) !== 0; diff --git a/src/native/windows/WindowsShortcutProvider.ts b/src/native/windows/WindowsShortcutProvider.ts index f51c8a6ab0..549bd8356c 100644 --- a/src/native/windows/WindowsShortcutProvider.ts +++ b/src/native/windows/WindowsShortcutProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { lstat, open } from "node:fs/promises"; import { projectSelectedArtifactFileFailure, @@ -24,7 +25,6 @@ import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, } from "../../domain/analysisErrorCore.js"; import { MAX_INSPECT_WINDOWS_SHORTCUT_EXTRA_DATA_BLOCKS, @@ -37,7 +37,6 @@ import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { err, ok } from "../../domain/result.js"; import { WINDOWS_SHORTCUT_PROVIDER } from "../../domain/investigationProviders.js"; import { - WindowsShortcutFormatFailure, WindowsShortcutResourceFailure, type WindowsShortcutSelectedBoundary, } from "./WindowsShortcut.errors.js"; @@ -297,21 +296,8 @@ const windowsShortcutFailurePrimary = ( remediationAction: budgetRemediation(input, cause.boundary), }, ); - if (cause instanceof WindowsShortcutFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${input.path}: ${cause.message}`, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure diff --git a/src/rust/RustBinaryImage.ts b/src/rust/RustBinaryImage.ts index fb8efa916f..13e2c07637 100644 --- a/src/rust/RustBinaryImage.ts +++ b/src/rust/RustBinaryImage.ts @@ -60,9 +60,11 @@ const readContainer = (bytes: Buffer) => { return readBinaryContainer(bytes); } catch (cause) { if (cause instanceof BinaryFormatFailure) - throw new RustAuditableFormatFailure(cause.kind, cause.message, { - cause, - }); + throw new RustAuditableFormatFailure( + cause.kind === "unsupported" ? "unsupported" : "malformed", + cause.message, + { cause }, + ); if (cause instanceof BinaryResourceFailure) throw new RustAuditableResourceFailure( { diff --git a/src/v8/V8CodeCache.errors.ts b/src/v8/V8CodeCache.errors.ts index 8ecd42fefc..207443cf9e 100644 --- a/src/v8/V8CodeCache.errors.ts +++ b/src/v8/V8CodeCache.errors.ts @@ -1,16 +1,5 @@ import type { V8CodeCacheInputBudget } from "../domain/v8/v8CodeCacheBudget.js"; -/** Distinguish corrupt containers from unrecognized formats. */ -export class V8CodeCacheFormatFailure extends Error { - constructor( - readonly kind: "malformed" | "unsupported", - message: string, - ) { - super(message); - this.name = "V8CodeCacheFormatFailure"; - } -} - /** A caller-selected budget was exceeded while scanning the payload. */ export class V8CodeCacheBudgetFailure extends Error { constructor( diff --git a/src/v8/V8CodeCacheParser.test.ts b/src/v8/V8CodeCacheParser.test.ts index 3fa88ec0a6..0430882b7f 100644 --- a/src/v8/V8CodeCacheParser.test.ts +++ b/src/v8/V8CodeCacheParser.test.ts @@ -179,8 +179,10 @@ it("fails closed on a foreign magic", () => { const foreign = withHeaderWord(real, 0, 0xdeadbeef); expect(() => parse(foreign)).toThrow( expect.objectContaining({ - name: "V8CodeCacheFormatFailure", - kind: "unsupported", + failure: expect.objectContaining({ + kind: "unsupported", + format: "v8-code-cache", + }), message: expect.stringContaining("not a V8 code cache"), }), ); diff --git a/src/v8/V8CodeCacheParser.ts b/src/v8/V8CodeCacheParser.ts index 4616a92c8d..1044d3685a 100644 --- a/src/v8/V8CodeCacheParser.ts +++ b/src/v8/V8CodeCacheParser.ts @@ -10,16 +10,14 @@ import { type V8CodeCache, } from "../domain/v8/v8CodeCache.js"; import type { V8CodeCacheInputBudget } from "../domain/v8/v8CodeCacheBudget.js"; -import { - V8CodeCacheBudgetFailure, - V8CodeCacheFormatFailure, -} from "../v8/V8CodeCache.errors.js"; +import { V8CodeCacheBudgetFailure } from "../v8/V8CodeCache.errors.js"; +import { malformedInput, unsupportedInput } from "../domain/parseFailure.js"; const unsupported = (message: string): never => { - throw new V8CodeCacheFormatFailure("unsupported", message); + throw unsupportedInput("v8-code-cache", message); }; const malformed = (message: string): never => { - throw new V8CodeCacheFormatFailure("malformed", message); + throw malformedInput("v8-code-cache", message); }; /** diff --git a/src/v8/V8CodeCacheProvider.ts b/src/v8/V8CodeCacheProvider.ts index 20622f3d0d..54317035d3 100644 --- a/src/v8/V8CodeCacheProvider.ts +++ b/src/v8/V8CodeCacheProvider.ts @@ -1,3 +1,4 @@ +import { parseFailureAnalysisError } from "../domain/parseFailureAnalysisError.js"; import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { @@ -21,7 +22,6 @@ import { AnalysisAccessDeniedError, AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, } from "../domain/analysisErrorCore.js"; import { ArtifactOperationError } from "../domain/artifactOperationError.js"; import { @@ -32,10 +32,7 @@ import { type InspectV8CodeCacheInput, } from "../domain/v8/v8CodeCache.js"; import { err, ok } from "../domain/result.js"; -import { - V8CodeCacheBudgetFailure, - V8CodeCacheFormatFailure, -} from "./V8CodeCache.errors.js"; +import { V8CodeCacheBudgetFailure } from "./V8CodeCache.errors.js"; import { V8_CODE_CACHE_PROVIDER_IDENTITY } from "./V8CodeCacheProviderIdentity.js"; import { parseV8CodeCache } from "./V8CodeCacheParser.js"; @@ -183,21 +180,8 @@ const v8CodeCacheFailurePrimary = ( remediationAction: observationBudgetRemediation(cause, input), }, ); - if (cause instanceof V8CodeCacheFormatFailure) - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError( - OPERATION, - input.path, - cause.message, - { cause }, - ) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: ["path"], - reason: "invalid_format", - message: cause.message, - }, - ]); + const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause); + if (formatFailure !== undefined) return formatFailure; const identityFailure = projectOwnedArtifactIdentityFailure( facts, OPERATION,