From c214fc44a8db4fe678fc23823f08d44b1b79ff52 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:51:47 -0500 Subject: [PATCH] fix(errors)!: report inventory refusals as target failures of the selected path (#14277) * feat(errors)!: add the TargetFailure model, its projection table and conformance registry Introduce one domain-owned TargetFailure value whose kind alone derives the public code, category, retryability, recovery and details, for CLI and MCP alike. Selected-file malformed and truncated refusals are the first area on it: AnalysisMalformedTargetError is replaced by AnalysisTargetFailureError, and ParseFailure's byte-structure variants are TargetFailure variants rather than a parallel type. The shared stableArtifactParserFailureCli loop is replaced by a declarative registry (tests/support/targetFailure/readers/*.ts) and one generated suite that runs every registered case through the CLI and MCP. BREAKING CHANGE: selected-file malformed and truncated refusals add details.failure_kind, and a truncated target's remediation now says to re-acquire the complete file instead of choosing another target. Codes are unchanged. Affected operations: every operation that refuses a selected file's malformed or truncated bytes, including the ELF, PE, Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel module, binary hardening, managed PE/CLI and IL2CPP readers. * test(managed): name the target failure error in the merged status test * docs(reference): name the error CSV instead of linking a non-page file * fix(tests): expect the path reason for non-regular dyld inputs #14225 refuses a non-regular dyld input as ArtifactReaderFailure("path"); dylibFileLifetime still expected "format" and fails on main's shard 9. * fix(tests): expect io, invariant and path where #14225 reclassified stableArtifact expected "format" for an impossible descriptor byte count (now io) and an invalid chunk size (now InternalInvariantError); directoryArtifactReaderOpen expected "format" for a non-file entry (now path, the same change as #14238). All three fail on main. * fix(errors)!: raise container reader byte faults as malformed or truncated targets Delete the ambiguous `format` reason from ArtifactReaderFailure and ArtifactOperationError. Each container reader now raises its owner's fact once, through malformedArtifact / truncatedArtifact, with format, offset, field and measured extents. Short reads inside a measured extent are read-coverage integrity failures, path-kind refusals are `path`, foreign or recovery-requiring inputs are `unsupported`, host tool output is `io`, and REA defects are InternalInvariantError. The trace, NTFS journal, release exposure, web capture, native macOS and web artifact adapters project the reader's parsed facts as AnalysisTargetFailureError instead of invalid_request. Inventory malformed, truncated, unsupported and cancelled reasons take their code from the TargetFailure projection table, so a truncated container is unsupported_target with failure_kind "truncated" on both paths. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact, analyze_javascript_application, inspect_desktop_application, inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg, trace_dylib_resolution, trace_web_module_imports and trace_web_source_location report damaged container bytes as unsupported_target (details.reason "malformed" or "truncated", with failure_kind and format) instead of artifact_operation_failed with reason "format", and a truncated container as unsupported_target instead of truncated. inspect_playwright_trace, inspect_ntfs_journal, audit_release_exposure, the web capture inspection operations and the caller-selected import and source maps report damaged selected bytes as unsupported_target instead of invalid_request. The `format` reason no longer appears in details.reason. * test(artifacts): expect target failure codes in compiled CLI and MCP suites * fix(errors)!: refuse malformed SQLite, pwntools and EVM inputs as target failures The SQLite engine's `format` reason is renamed to `malformed` at its owner (SQLITE_INSPECTION_REASONS), and its refusal becomes an AnalysisTargetFailureError at the selected path with format "sqlite". The pwntools and EVM worker replies keep their wire reason "format", which their workers define, and the adapters translate it once into a malformed target failure with the profile's format (elf, elf-core, evm-bytecode) instead of an invalid_format argument issue. SQLite joins the target-failure conformance registry. BREAKING CHANGE: inspect_sqlite_database, inspect_binary_layout, inspect_recorded_crash and inspect_evm_interface report a selected file's malformed bytes as unsupported_target with details.failure_kind "malformed", format_failure, format and path, instead of invalid_request with an invalid_format issue on path. * fix(errors): give the integrity kind a schema-valid code and list the reference page artifact_integrity_mismatch's projection schema requires declared and calculated digests, which a TargetFailure of kind integrity does not carry, so the kind now projects artifact_operation_failed with category integrity_mismatch. The model test validates every kind's projection against analysisErrorProjectionSchema. The reference page joins the documentation sidebar. * fix(artifacts): report a short carrier read as a changed file and keep unsupported desktop probes local A Bun or Node SEA short read inside a range already checked against the measured size meant the file changed, not that it was truncated. The carrier range reader and Bun's readExact now raise read-coverage integrity for it, and keep 'outside the file' as the truncated case. DesktopFileInspection records an unsupported managed-metadata probe as a row issue again, so later file checks still run. * test(errors): expect target failure facts in the pwntools and EVM reply suites The literal-replacement scenario now reads the failure's detail instead of an issues[] message, and a malformed reply wrapped by cleanup failure reports category unsupported_target. * test(errors): register PE DOS-signature and truncated IPS refusals and drop their per-command copies The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit signatures) and the truncated Apple IPS body move into the conformance registry, which runs them through the CLI and MCP and now also checks that a refusal leaves the selected file unchanged. The per-command tests keep only their valid-image controls. * test(sqlite): drop the malformed-database provider test the conformance registry covers inspect_sqlite_database/not-a-database in the target-failure registry runs the same non-SQLite bytes through the CLI and MCP, asserts the malformed target facts and checks the selected file is unchanged. * feat(errors)!: make failure_kind the identifier and derive code and retry from it Apply the owner review on #14239 to the TargetFailure model: - remove details.format_failure; failure_kind is the only identifier; - give integrity, conflict and io their own codes (target_integrity_mismatch, input_conflict, host_io_failed) and derive inventory malformed, truncated and unsupported codes from the same table; - add a retry hint (none, backoff, after_change) derived from the kind, with io refined by its transient errno fact; retryable stays the unchanged-retry flag and is true exactly for backoff; - rename the limit-cut result code and category truncated to partial; - drop cancelled and resource from the target kinds and spell identifiers in American English (unrecognized); - return a target failure a tool handler throws as a projected isError result instead of letting the SDK flatten it to text. BREAKING CHANGE: details.format_failure is removed (read details.failure_kind). The truncated result code and category are now partial. Target integrity failures report target_integrity_mismatch, host read failures host_io_failed and disagreeing inputs input_conflict. Inventory operations (inventory_artifact, inspect_artifact, extract_artifact and the other inventory callers) report truncated container bytes as unsupported_target. Every target failure carries a top-level retry hint. * test(sqlite): expect a malformed target for non-database bytes in the CLI suite * fix(artifacts): keep changed-file short reads, invalid offsets and EOF declarations apart PyInstaller reads inside the measured size, and .NET bundle manifest refills, now raise read-coverage integrity on a zero-byte read instead of truncated. A .NET bundle field and a Godot PCK directory entry that extend past the file are truncated (with offset and extents) instead of malformed. An absent or invalid ASAR packed offset is malformed; only a valid range past the archive is truncated. The .NET manifest string offset is reported in file coordinates. * fix(pwntools): report a short ELF header as a truncated target The layout and recorded-crash workers raise a distinct truncated reason when the file ends inside the ELF identification or header, and the decoder projects it as failure_kind truncated instead of inferring it from the message. * fix(errors)!: report managed coverage gaps and IL2CPP pair conflicts as target failures Managed readers interpret an issue code once, in managedIssueTargetFailure: a coverage gap is an unsupported target, every other rule violation is a malformed target, and the inventory metadata status is derived from that same fact. managedInspectionTargetFailure now returns only AnalysisTargetFailureError. An IL2CPP binary that parses but does not link to its metadata is a conflict target failure that lists both inputs and blames neither, in place of an invalid_request with two issue entries. Metadata version 108 is an unsupported target. The CLI spells each conflict input's field by the command's option name. BREAKING CHANGE: inspect_managed_artifact, inspect_managed_members, inspect_managed_native_boundaries and the managed comparison operations report unsupported metadata or signature forms as an AnalysisTargetFailureError (failure_kind unsupported, format pe-cli, field, offset) instead of a bare unsupported target. inspect_il2cpp_metadata reports a binary/metadata pair that does not link as code input_conflict with failure_kind conflict and details.inputs, instead of invalid_request with details.issues, and metadata version 108 with failure_kind unsupported. * fix(artifacts): verify the carrier before blaming a short read on the bytes The NTFS $MFT decoder, positional members (FIT, uImage, Bun, Deno) and .NET bundle members now re-verify the source before reporting a short stream as malformed, so a file that changed during the read reports the change. The truncation site builds the model's measured extent. * fix(errors)!: report inventory refusals as target failures of the selected path An inventory, inspection or extraction refused damaged or unsupported container bytes as an ArtifactOperationError whose reason repeated the format owner's kind. It carried no path or retry hint, so the conformance registry could not express container cases. translateArtifactFailure now takes the selected path and returns the reader's TargetFailure as an AnalysisTargetFailureError. The malformed, truncated and unsupported reasons, their classification rows and their presentation branch are deleted from ArtifactOperationError. Readers' unsupported refusals carry their format facts through unsupportedArtifact. Container cases move into the conformance registry, which now opens the target first for session tools such as inspect_artifact. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the bundle readers report a refused container as a target failure of details.path with a top-level retry. details.reason is the owner's description and details.detail is removed. * docs(il2cpp): describe pair conflicts as input_conflict with both inputs * docs(android): name unsupported_target for truncated boot image structures * fix(errors)!: report a target that changed during the read as failure_kind changed Inventory integrity failures whose check means the target moved under the read (container, member and unpacked-entry identity, read coverage, traversal coverage) now take the model's changed projection: code artifact_changed, retry backoff and details.failure_kind changed. A selected target that no longer matches the one the session admitted gets its own admitted-identity check and keeps its reopen recovery. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the other inventory operations report a target that changed during the read as artifact_changed (retryable, failure_kind changed) instead of artifact_operation_failed. Admission-identity refusals report integrity_check admitted-identity instead of container-identity. * test(artifacts): raise the cleanup fixture's decode refusal with its format facts * test(artifacts): expect admitted-identity for selections replaced before admission A selected source replaced before admission fails the admitted-identity check rather than container-identity since the changed/admitted split. * test(go): name the fixture and result when an MZ carrier is not refused through MCP * test(verify): expect target failures for damaged ELF, core and EVM inputs in real-provider verifiers The binary-layout, recorded-crash and EVM verifiers still expected invalid_input for malformed or truncated selected bytes. The pwntools and EVM adapters now report those as unsupported_target with failure_kind; a missing path remains invalid_input. * test(web): expect the partial code for a refused source-map admission The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling. * fix(artifacts): keep refusal facts on DMG verdicts and the selected bundle path hdiutil's "image not recognized" verdict raised the unsupported reason without the owner's facts, so the inventory translation treated it as a reader defect. It now carries an unsupported dmg target failure, and the reader-failure constructor requires facts for every target reason. A bundle resource refusal names the caller's selected bundle path rather than its resolved target. The real-provider verifiers and the Android, source-location acceptance tests expect the model's target-failure categories and codes. * test(errors): check the MCP target failure as the text clients receive The stdio transport removes the private structured carrier from every isError result, so the conformance suite asserted a field that never reaches clients and failed every case. The projected diagnostic is checked from the JSON text instead. * test(artifacts): expect artifact_changed when selected bytes change after inventory Bundle resources replaced after open and unselected JavaScript sources rewritten after inventory now fail a change check, so they report artifact_changed with retry backoff rather than artifact_operation_failed. * fix(errors): report a session digest mismatch as admitted-identity The digest the session admitted does not change when the same request is repeated, so targetDigestChangedFailure was inviting a backoff retry that fails the same way. It now names admitted-identity, which stays artifact_operation_failed and not retryable, and tells the caller to reopen. Co-authored-by: morluto * fix(artifacts): classify unused PyInstaller compressed input as layout zlib stops at the first complete stream, so a declared span that arrives intact but is not fully consumed is trailing junk or a second stream, not a file that changed. A source that ends before that span stays read-coverage. The cached-carrier test replaces the file with a different size so a shared timestamp cannot hide the rewrite. Co-authored-by: morluto * test(applications): expect unsupported_target for a damaged trace stream A trace member whose CRC fails is a malformed zip target. The partial Evidence assertion now checks that code, failure_kind and format. Co-authored-by: morluto * test(artifacts): assert Android refusal kinds and drop the SEA registry case details.reason is the owner's description, so the boot-image refusals assert failure_kind and format. A malformed SEA blob inside an ELF stays an outer-format inventory with a recognition limitation, which the Node SEA reader tests already cover, so it is not an inspect_artifact refusal. Co-authored-by: morluto * fix(artifacts): pass the selected path into translated target failures translateArtifactFailure names the caller-selected path on a format refusal. Directory inspection and a retained artifact scope both know that path and now supply it. Co-authored-by: morluto * test(dylib): expect admitted-identity when the opened target is replaced The session keeps the digest it admitted, so replacing the executable and repeating trace_dylib_resolution is not a retryable container change. Co-authored-by: morluto * style: format the inventory path translation and conformance suite * test(errors): expect target failures for ZIP inventory refusals and input_conflict for an unlinked IL2CPP pair * test(web): expect a malformed target failure on the captured source path * test(artifacts): expect a malformed ZIP target failure for a corrupt Zstandard member --------- Co-authored-by: Cursor Agent Co-authored-by: morluto --- docs/reference/target-failures.md | 1 + docs/user-visible-errors.csv | 3 - src/apkSignature/ApkSignatureProvider.test.ts | 2 +- src/application/DirectAnalysis.ts | 1 + src/application/PublishWebScripts.ts | 8 +- src/application/WebScriptExportService.ts | 17 +- .../artifacts/ArtifactPathInspection.ts | 5 +- .../JavaScriptApplicationService.ts | 10 +- .../javascript/JavaScriptArtifactAnalysis.ts | 4 +- .../JavaScriptArtifactReconstruction.ts | 5 +- .../javascript/JavaScriptPreloadDiscovery.ts | 4 +- ...BootImageArtifactReader.boundaries.test.ts | 5 +- src/artifacts/ArtifactProvider.ts | 18 +- src/artifacts/ArtifactProviderCleanup.test.ts | 4 +- .../ArtifactProviderTargetPath.test.ts | 66 +++++++ src/artifacts/DesktopApplicationReader.ts | 1 + src/artifacts/DesktopFileInspection.ts | 23 +-- src/artifacts/DotnetBundleArtifactReader.ts | 5 +- src/artifacts/NativeDmgArtifactReader.ts | 11 ++ src/artifacts/NativeDmgProtocol.test.ts | 14 +- .../NativeDmgRootObservation.test.ts | 6 +- src/artifacts/NtfsMftArtifactReader.test.ts | 6 +- src/artifacts/PyInstallerArtifactReader.ts | 5 +- src/artifacts/ReleaseExposureReader.test.ts | 5 +- src/artifacts/ZipArtifactReader.test.ts | 16 +- .../apple/AppleAssetCatalogAnalysis.test.ts | 4 +- .../apple/AppleAssetCatalogAnalysis.ts | 28 +-- src/artifacts/apple/DylibResolutionReader.ts | 5 +- .../InterfaceBuilderFinalization.test.ts | 2 + .../apple/KeyedArchiveRawRefusal.test.ts | 6 +- src/artifacts/apple/KeyedArchiveReader.ts | 4 +- .../extraction/ArtifactExtraction.test.ts | 7 +- .../ArtifactGraphConstruction.test.ts | 2 +- .../ArtifactInventoryFinalization.test.ts | 10 +- .../pyinstaller/PyInstallerBoundaries.test.ts | 6 +- src/browser/assets/WebArtifactReads.ts | 33 ++-- .../history/playwrightTrace/TraceFailure.ts | 3 +- .../analysisErrorClassification.test.ts | 11 +- src/domain/analysisErrorClassification.ts | 7 +- src/domain/analysisErrorPresentation.ts | 6 - src/domain/analysisErrorProjection.ts | 3 - src/domain/artifactOperationError.ts | 15 +- src/domain/targetFailure.ts | 9 +- src/java/MavenGradleMetadataProvider.ts | 2 +- src/nuget/NugetNupkgProvider.ts | 2 +- src/providers/offlineArtifactFailure.ts | 3 +- src/resources/ArtifactFileOperation.ts | 2 - .../ArtifactOperationFailure.test.ts | 125 ++++++++------ src/resources/ArtifactOperationFailure.ts | 163 ++++++++++++------ src/resources/ArtifactReader.ts | 59 ++++++- src/resources/ArtifactResourceScope.test.ts | 31 +++- src/resources/StableArtifactFailure.ts | 15 +- src/resources/index.ts | 8 +- tests/acceptance/androidBootImageCli.test.ts | 6 +- .../javascriptSourceSelectionCli.test.ts | 2 +- .../keyedArchiveScalarKinds.test.ts | 4 +- .../keyedArchiveXmlNumbers.test.ts | 8 +- .../artifactReaderLimitsCli.test.ts | 2 +- .../artifactZipCurrentDirectory.test.ts | 32 ---- tests/acceptance/bunStandaloneCli.test.ts | 3 +- tests/acceptance/denoStandaloneCli.test.ts | 2 +- .../acceptance/firmwareContainersCli.test.ts | 38 ---- tests/acceptance/hexRecordsCli.test.ts | 22 --- tests/acceptance/iso9660Cli.test.ts | 11 +- .../targetFailureConformance.test.ts | 11 +- .../webArtifactErrorProvenance.test.ts | 21 ++- .../cli/artifactZstandardWindow.test.ts | 7 +- .../boundary/cli/il2cppElfRelocations.test.ts | 4 +- tests/boundary/cli/unityFsCli.test.ts | 2 +- .../artifactInventorySnapshot.test.ts | 6 +- .../filesystem/artifactZipIntegrity.test.ts | 24 ++- .../filesystem/asarHeaderAdmission.test.ts | 15 +- .../filesystem/desktopApplication.test.ts | 10 +- .../filesystem/webModuleArtifacts.test.ts | 3 +- .../boundary/mcp/androidBootImageMcp.test.ts | 6 +- tests/boundary/mcp/hexRecordsMcp.test.ts | 3 +- .../mcp/javascriptSourceSelection.test.ts | 2 +- .../process/artifactFileOutcomes.test.ts | 10 +- .../contracts/analysisErrorProjection.test.ts | 1 - tests/fixtures/androidBootImage.ts | 2 + .../dmgCancellationReason.test.ts | 10 +- .../stableArtifactConsumers.test.ts | 6 +- .../targetFailure/readers/containers.ts | 80 +++++++++ tests/support/targetFailure/registry.ts | 5 + 84 files changed, 740 insertions(+), 434 deletions(-) create mode 100644 src/artifacts/ArtifactProviderTargetPath.test.ts create mode 100644 tests/support/targetFailure/readers/containers.ts diff --git a/docs/reference/target-failures.md b/docs/reference/target-failures.md index f78bea9309..e35e9670bf 100644 --- a/docs/reference/target-failures.md +++ b/docs/reference/target-failures.md @@ -71,5 +71,6 @@ Container and inventory readers (ZIP, ASAR, PyInstaller, .NET bundles, Node SEA, - The Playwright trace, NTFS journal, release exposure and web capture operations report a damaged selected file as `unsupported_target`, not `invalid_request`. - `inspect_sqlite_database`, `inspect_binary_layout`, `inspect_recorded_crash` and `inspect_evm_interface` also report a damaged selected file as `unsupported_target` (`failure_kind: "malformed"`, with `format` `sqlite`, `elf`, `elf-core` or `evm-bytecode`), not `invalid_request`. - A short read after REA measured the file is now an integrity failure with `details.integrity_check: "read-coverage"` (the file changed during the read), not a format error. +- An inventory, inspection or extraction of a container (`inventory_artifact`, `inspect_artifact`, `extract_artifact` and the bundle readers such as `inspect_keyed_archive`) reports damaged or unsupported bytes as a target failure of the selected `path`, with top-level `retry`, like every other operation. `details.reason` is now the owner's description, and `details.detail` is gone. Before, these refusals reported `details.reason: "malformed"`, `"truncated"` or `"unsupported"` with the description in `details.detail`, and no `path`. Related: [settings, limits and recovery](limits-and-recovery.md) for limit failures, and `docs/user-visible-errors.csv` for every error case and its code. diff --git a/docs/user-visible-errors.csv b/docs/user-visible-errors.csv index 4046cfc36c..b37c70e53e 100644 --- a/docs/user-visible-errors.csv +++ b/docs/user-visible-errors.csv @@ -25,9 +25,6 @@ AnalysisTargetFailureError,kind=changed,artifact_changed,integrity_mismatch,true AnalysisTargetFailureError,kind=access,access_denied,unavailable,false AnalysisTargetFailureError,kind=io,host_io_failed,execution_failure,false ArtifactOperationError,reason=cancelled,cancelled,cancelled,true -ArtifactOperationError,reason=malformed,unsupported_target,unsupported_target,false -ArtifactOperationError,reason=truncated,unsupported_target,unsupported_target,false -ArtifactOperationError,reason=unsupported,unsupported_target,unsupported_target,false ArtifactOperationError,reason=integrity,artifact_operation_failed,integrity_mismatch,false ArtifactOperationError,reason=limit,partial,partial,false ArtifactOperationError,reason=path,artifact_operation_failed,execution_failure,false diff --git a/src/apkSignature/ApkSignatureProvider.test.ts b/src/apkSignature/ApkSignatureProvider.test.ts index ecf88a63cc..88b0a3204a 100644 --- a/src/apkSignature/ApkSignatureProvider.test.ts +++ b/src/apkSignature/ApkSignatureProvider.test.ts @@ -408,7 +408,7 @@ const registerSignatureInputAdmissionCases = () => { expect( tagOf(new ArtifactReaderFailure("path", "Expected a regular file")), ).toBe("AnalysisInputError"); - for (const reason of ["io", "unavailable", "malformed"] as const) + for (const reason of ["io", "unavailable"] as const) expect(tagOf(new ArtifactReaderFailure(reason, "reader failed"))).toBe( "ProviderAdapterError", ); diff --git a/src/application/DirectAnalysis.ts b/src/application/DirectAnalysis.ts index 88fe67a0cc..28f5e414bf 100644 --- a/src/application/DirectAnalysis.ts +++ b/src/application/DirectAnalysis.ts @@ -407,6 +407,7 @@ const runAnalysis = async ( const inspectDirectory = dependencies.inspectArtifactDirectory; const execution = await runInRetainedArtifactScope( session.resourceScope, + path, () => inspectDirectory( directory, diff --git a/src/application/PublishWebScripts.ts b/src/application/PublishWebScripts.ts index 400bc6cee6..b170e55d86 100644 --- a/src/application/PublishWebScripts.ts +++ b/src/application/PublishWebScripts.ts @@ -9,6 +9,7 @@ import { SafeOutputTree, outputDirectoryAdmissionRefusal, SafeOutputTreeCreationFailure, + artifactOperationReason, } from "../resources/index.js"; import { PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION } from "../domain/browserNetworkEvidence.js"; import { @@ -169,7 +170,12 @@ export const publishWebScripts = async ( throw cancelled; } const error = new WebScriptExportError( - cause instanceof ArtifactReaderFailure ? cause.reason : "io", + // The output tree raises no format refusals; any other reader + // fault is reported as the publication's I/O, with its cause. + cause instanceof ArtifactReaderFailure && + cause.parseFailure === undefined + ? artifactOperationReason(cause) + : "io", tree.outputRoot, diagnostic, { cause, residualPaths: [tree.outputRoot] }, diff --git a/src/application/WebScriptExportService.ts b/src/application/WebScriptExportService.ts index 9b3368e070..ebb073c1f8 100644 --- a/src/application/WebScriptExportService.ts +++ b/src/application/WebScriptExportService.ts @@ -8,6 +8,8 @@ import { type AnalysisCleanupLease, type ArtifactResourceScope, bindArtifactFileCleanup, + artifactOperationReason, + artifactReaderTargetFailure, } from "../resources/index.js"; import { publishWebScripts } from "./PublishWebScripts.js"; import { selectScriptCapture } from "../domain/webScriptCaptureAdapters.js"; @@ -183,16 +185,17 @@ const mapExportFailure = ( if (cause instanceof AnalysisError) return cause; if (cause instanceof ArtifactReaderFailure) { const primary = - cause.cancellation === undefined - ? new WebScriptExportError( - cause.reason, + cause.cancellation !== undefined + ? cancelledBy(OPERATION, carriedReason(cause.cancellation.reason), { + partialObservation: cause.partialObservation, + }) + : (artifactReaderTargetFailure(OPERATION, input.capture_path, cause) ?? + new WebScriptExportError( + artifactOperationReason(cause), input.output_directory, cause.message, { cause, partialObservation: cause.partialObservation }, - ) - : cancelledBy(OPERATION, carriedReason(cause.cancellation.reason), { - partialObservation: cause.partialObservation, - }); + )); if (cause.cleanup === undefined) return primary; const error = analysisErrorWithCleanupFailure( primary, diff --git a/src/application/artifacts/ArtifactPathInspection.ts b/src/application/artifacts/ArtifactPathInspection.ts index 2c2d90400e..1749cc599f 100644 --- a/src/application/artifacts/ArtifactPathInspection.ts +++ b/src/application/artifacts/ArtifactPathInspection.ts @@ -56,13 +56,14 @@ export const selectedArtifactDirectory = async ( */ export const runInRetainedArtifactScope = async ( retained: RetainedResourceScope | undefined, + path: string, operation: () => Promise>, ): Promise> => { if (retained === undefined) return operation(); try { return await retained.run(operation); } catch (cause: unknown) { - return err(translateArtifactFailure("inspect_artifact", cause)); + return err(translateArtifactFailure("inspect_artifact", path, cause)); } }; @@ -80,7 +81,7 @@ export const executeArtifactPathInspection = async ( options: ExecutionOptions = {}, retained?: RetainedResourceScope, ): Promise> => - runInRetainedArtifactScope(retained, async () => { + runInRetainedArtifactScope(retained, path, async () => { const directory = await selectedArtifactDirectory(path); if (directory !== undefined) return dependencies.inspectArtifactDirectory( diff --git a/src/application/javascript/JavaScriptApplicationService.ts b/src/application/javascript/JavaScriptApplicationService.ts index 80345d3839..d7b38a9d6a 100644 --- a/src/application/javascript/JavaScriptApplicationService.ts +++ b/src/application/javascript/JavaScriptApplicationService.ts @@ -183,9 +183,11 @@ export const analyzeJavaScriptApplicationValidated = async ( result, ); return err( - translateArtifactFailure(OPERATION, cause).retainPartialObservation( - evidence, - ), + translateArtifactFailure( + OPERATION, + input.input_path, + cause, + ).retainPartialObservation(evidence), ); } catch (completionCause: unknown) { // A validation or Evidence failure while finishing the partial result @@ -196,7 +198,7 @@ export const analyzeJavaScriptApplicationValidated = async ( // Preserve execution constraints and their completed partial Evidence. if (cause instanceof AnalysisError) return err(cause); if (cause instanceof ArtifactReaderFailure) - return err(translateArtifactFailure(OPERATION, cause)); + return err(translateArtifactFailure(OPERATION, input.input_path, cause)); if (cause instanceof z.ZodError) return err( new AnalysisOutputError(OPERATION, describeResultSchemaFailure(cause), { diff --git a/src/application/javascript/JavaScriptArtifactAnalysis.ts b/src/application/javascript/JavaScriptArtifactAnalysis.ts index f9daa5aa92..d91913c942 100644 --- a/src/application/javascript/JavaScriptArtifactAnalysis.ts +++ b/src/application/javascript/JavaScriptArtifactAnalysis.ts @@ -44,7 +44,7 @@ import type { JavaScriptSemanticGraphProjection } from "./JavaScriptSemanticGrap import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { ArtifactReaderFailure, - translateArtifactFailure, + translateArtifactOperationFailure, } from "../../resources/index.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { @@ -231,7 +231,7 @@ export const analyzeAndAdoptJavaScriptArtifactFiles = async ( cause instanceof ArtifactReaderFailure && cause.reason === "cancelled" ) - interruption = translateArtifactFailure( + interruption = translateArtifactOperationFailure( "analyze_javascript_application", cause, ); diff --git a/src/application/javascript/JavaScriptArtifactReconstruction.ts b/src/application/javascript/JavaScriptArtifactReconstruction.ts index e0242c4a3a..52061051d1 100644 --- a/src/application/javascript/JavaScriptArtifactReconstruction.ts +++ b/src/application/javascript/JavaScriptArtifactReconstruction.ts @@ -20,6 +20,7 @@ import { setImmediate } from "node:timers/promises"; import { ArtifactReaderFailure, type ArtifactResourceScope, + unsupportedArtifact, } from "../../resources/index.js"; import { AnalysisAccessDeniedError, @@ -132,8 +133,8 @@ export const reconstructJavaScriptArtifact = async ( selectedPath, ); if (snapshot.manifest.root_format !== format) - throw new ArtifactReaderFailure( - "unsupported", + throw unsupportedArtifact( + format, `Artifact inventory classified ${path} as ${snapshot.manifest.root_format}, not ${format}`, ); const reader = createReader( diff --git a/src/application/javascript/JavaScriptPreloadDiscovery.ts b/src/application/javascript/JavaScriptPreloadDiscovery.ts index 0671b35635..ce61849d06 100644 --- a/src/application/javascript/JavaScriptPreloadDiscovery.ts +++ b/src/application/javascript/JavaScriptPreloadDiscovery.ts @@ -6,7 +6,7 @@ import { AnalysisCancelledError, AnalysisResourceConstraintError, } from "../../domain/analysisErrorCore.js"; -import { translateArtifactFailure } from "../../resources/index.js"; +import { translateArtifactOperationFailure } from "../../resources/index.js"; import type { JavaScriptArtifactFileSet } from "../../domain/javascript/javascriptArtifactFiles.js"; import type { JavaScriptSourceAnalysisLimits } from "../../domain/javascript/javascriptSourceAnalysis.js"; import type { ArtifactResourceScope } from "../../resources/index.js"; @@ -129,7 +129,7 @@ export const discoverJavaScriptPreloadPaths = async ( if (outcome.kind === "failed" && outcome.cause instanceof AnalysisError) throw analysisErrorWithCleanupFailure( outcome.cause, - translateArtifactFailure( + translateArtifactOperationFailure( "analyze_javascript_application", scope.cleanupFailure({ kind: "completed" }, [cleanup]), ), diff --git a/src/artifacts/AndroidBootImageArtifactReader.boundaries.test.ts b/src/artifacts/AndroidBootImageArtifactReader.boundaries.test.ts index d34c2697e6..51667f31ef 100644 --- a/src/artifacts/AndroidBootImageArtifactReader.boundaries.test.ts +++ b/src/artifacts/AndroidBootImageArtifactReader.boundaries.test.ts @@ -9,6 +9,7 @@ import { AndroidBootImageArtifactReader } from "./AndroidBootImageArtifactReader import { ArtifactReaderFailure, artifactFixedLimitFailure, + malformedArtifact, } from "../resources/index.js"; import { openRegularFile } from "../filesystem/RegularFile.js"; import { @@ -67,8 +68,8 @@ it.each(["invalid", "cancelled"] as const)( if (refuse) { refuse = false; if (mode === "invalid") - throw new ArtifactReaderFailure( - "malformed", + throw malformedArtifact( + "android-boot-image", "injected preparation failure", ); controller.abort(new Error("cancel final preparation validation")); diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts index de35f34644..b614724f88 100644 --- a/src/artifacts/ArtifactProvider.ts +++ b/src/artifacts/ArtifactProvider.ts @@ -149,7 +149,9 @@ export class ArtifactProvider implements AnalysisProvider { options, ); } catch (cause: unknown) { - inspected = err(translateArtifactFailure("inspect_artifact", cause)); + inspected = err( + translateArtifactFailure("inspect_artifact", path, cause), + ); } // A completed inspection still fails when its readers could not be // released. The caller's lifetime keeps this scope, so a later close of @@ -286,7 +288,11 @@ class BundleResourceArtifactClient implements AnalysisClient { ); } catch (cause: unknown) { return err( - translateArtifactFailure(operation as ArtifactAnalysisOperation, cause), + translateArtifactFailure( + operation as ArtifactAnalysisOperation, + this.root.callerPath, + cause, + ), ); } } @@ -474,7 +480,13 @@ class ArtifactClient implements AnalysisClient { ); } catch (cause: unknown) { return err( - translateArtifactFailure(operation as ArtifactAnalysisOperation, cause), + translateArtifactFailure( + operation as ArtifactAnalysisOperation, + // The caller's spelling, not the resolved file the reader opened. + this.target.callerInputPath ?? + artifactTargetSelectedPath(this.target), + cause, + ), ); } } diff --git a/src/artifacts/ArtifactProviderCleanup.test.ts b/src/artifacts/ArtifactProviderCleanup.test.ts index 10b57c0b5a..126a4f446c 100644 --- a/src/artifacts/ArtifactProviderCleanup.test.ts +++ b/src/artifacts/ArtifactProviderCleanup.test.ts @@ -1,7 +1,7 @@ import { expect, it, vi } from "vitest"; import { ArtifactProvider } from "./ArtifactProvider.js"; -import { ArtifactReaderFailure } from "../resources/ArtifactReader.js"; +import { malformedArtifact } from "../resources/ArtifactReader.js"; import * as interfaceBuilder from "./apple/InterfaceBuilderAnalysis.js"; it("updates a bundle resource client's returned cleanup error after close retry", async () => { @@ -20,7 +20,7 @@ it("updates a bundle resource client's returned cleanup error after close retry" }, }, }); - throw new ArtifactReaderFailure("malformed", "controlled decode refusal"); + throw malformedArtifact("nib-archive", "controlled decode refusal"); }); const client = new ArtifactProvider({}, "darwin").createBundleResourceClient({ callerPath: "/fixture/Demo.app", diff --git a/src/artifacts/ArtifactProviderTargetPath.test.ts b/src/artifacts/ArtifactProviderTargetPath.test.ts new file mode 100644 index 0000000000..c513f421e6 --- /dev/null +++ b/src/artifacts/ArtifactProviderTargetPath.test.ts @@ -0,0 +1,66 @@ +import { createHash } from "node:crypto"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; + +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { zipArchive } from "../domain/desktop/zipArchive.fixture.js"; + +import { ArtifactProvider } from "./ArtifactProvider.js"; +import { malformedArtifact } from "../resources/ArtifactReader.js"; +import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; +import * as interfaceBuilder from "./apple/InterfaceBuilderAnalysis.js"; + +it("names the bundle the caller selected, not its resolved target, in a target failure", async () => { + const inspect = vi + .spyOn(interfaceBuilder, "analyzeInterfaceBuilderBundle") + .mockRejectedValue(malformedArtifact("nib-archive", "controlled refusal")); + const client = new ArtifactProvider({}, "darwin").createBundleResourceClient({ + callerPath: "/fixture/Selected.app", + canonicalPath: "/fixture/Actual.app", + infoPlistPath: "/fixture/Actual.app/Info.plist", + layout: "root", + executableSha256: null, + }); + try { + const result = await client.execute("decode_interface_builder", {}); + if (result.ok) throw new Error("Expected a target failure"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "unsupported_target", + details: { + path: "/fixture/Selected.app", + failure_kind: "malformed", + format: "nib-archive", + }, + }); + } finally { + inspect.mockRestore(); + await client.close(); + } +}); + +it("names the spelling the caller selected for an opened target, not the resolved file", async () => { + const root = await createTestTempDirectory("rea-target-alias-"); + const path = join(root, "actual.zip"); + const bytes = zipArchive([{ name: "member.bin", data: "member bytes" }]); + const central = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02])); + bytes.writeUInt32LE(bytes.length + 1024, central + 42); + await writeFile(path, bytes); + const client = new ArtifactProvider({}, "darwin").createClient({ + path, + sourcePath: path, + callerInputPath: join(root, "selected.zip"), + sha256: createHash("sha256").update(bytes).digest("hex"), + kind: "archive", + format: "zip", + }); + try { + const result = await client.execute("inventory_artifact", {}); + if (result.ok) throw new Error("Expected a target failure"); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { path: join(root, "selected.zip"), failure_kind: "malformed" }, + }); + } finally { + await client.close(); + } +}); diff --git a/src/artifacts/DesktopApplicationReader.ts b/src/artifacts/DesktopApplicationReader.ts index 62c57b30cc..fab7283bbd 100644 --- a/src/artifacts/DesktopApplicationReader.ts +++ b/src/artifacts/DesktopApplicationReader.ts @@ -103,6 +103,7 @@ export class DesktopApplicationReader implements DesktopApplicationPort { } catch (cause: unknown) { const error = translateArtifactFailure( "inspect_desktop_application", + input.path, cause, ); return err(error); diff --git a/src/artifacts/DesktopFileInspection.ts b/src/artifacts/DesktopFileInspection.ts index d7c7a5d033..0e22fd2a15 100644 --- a/src/artifacts/DesktopFileInspection.ts +++ b/src/artifacts/DesktopFileInspection.ts @@ -21,15 +21,16 @@ import { readManagedMetadataLayout } from "../domain/managed/managedMetadataLayo import { readManagedCliHeaderPrefix } from "../domain/managed/managedCliHeaderPrefix.js"; import { readAssemblyReferenceName } from "../domain/managed/managedMetadataInventoryRows.js"; import { - isManagedCoverageGap, MANAGED_PE_CLI_FORMAT, ManagedReaderFailure, + managedIssueTargetFailure, } from "../domain/managed/managedReaderFailure.js"; import { ArtifactReaderFailure, abortIfNeeded, malformedArtifact, truncatedArtifact, + artifactFormatFailure, } from "../resources/index.js"; import { hasMachoMagic } from "../domain/apple/machoContainer.js"; import { @@ -108,9 +109,7 @@ export const inspectDesktopFile = async ( throw truncatedArtifact( "file", "Declared byte range lies outside the file", - { - ...(Number.isSafeInteger(offset) && offset >= 0 ? { offset } : {}), - }, + Number.isSafeInteger(offset) && offset >= 0 ? { offset } : {}, ); if (bytes > budget.maximum - budget.bytes) throw new DesktopProbeLimit(); // Reserve the retained range before reading its bytes. @@ -262,9 +261,7 @@ export const inspectDesktopFile = async ( } catch (cause: unknown) { if ( !(cause instanceof ArtifactReaderFailure) || - (cause.parseFailure === undefined && - cause.reason !== "limit" && - cause.reason !== "unsupported") + (cause.parseFailure === undefined && cause.reason !== "limit") ) throw cause; if (!row.issues.includes(cause.message)) row.issues.push(cause.message); @@ -412,19 +409,13 @@ const inspectPeFile = async ( } } catch (cause: unknown) { if (!(cause instanceof ManagedReaderFailure)) throw cause; - const { code, scope, offset } = cause.issue; - if (code === "resource-limit") + const failure = managedIssueTargetFailure(cause.issue); + if (failure === undefined) throw new ArtifactReaderFailure("limit", cause.message, { cause, boundary: "memory", }); - if (isManagedCoverageGap(code)) - throw new ArtifactReaderFailure("unsupported", cause.message, { cause }); - throw malformedArtifact(MANAGED_PE_CLI_FORMAT, cause.message, { - cause, - field: scope, - ...(offset === undefined || offset === null ? {} : { offset }), - }); + throw artifactFormatFailure(failure, { cause }); } }; diff --git a/src/artifacts/DotnetBundleArtifactReader.ts b/src/artifacts/DotnetBundleArtifactReader.ts index 40b8c27e09..0ce6157ecc 100644 --- a/src/artifacts/DotnetBundleArtifactReader.ts +++ b/src/artifacts/DotnetBundleArtifactReader.ts @@ -19,6 +19,7 @@ import { readArtifactFileChunks, abortIfNeeded, ArtifactFileSource, + unsupportedArtifact, } from "../resources/index.js"; import type { DotnetBundleAdmission } from "./dotnet/DotnetBundleAdmission.js"; import { @@ -84,8 +85,8 @@ export class DotnetBundleArtifactReader implements ArtifactReader { signal, )); if (header === undefined) - throw new ArtifactReaderFailure( - "unsupported", + throw unsupportedArtifact( + "dotnet-bundle", "Selected file has no .NET bundle header", ); this.#bundle = await readDotnetBundle( diff --git a/src/artifacts/NativeDmgArtifactReader.ts b/src/artifacts/NativeDmgArtifactReader.ts index 1b1e527169..b102057894 100644 --- a/src/artifacts/NativeDmgArtifactReader.ts +++ b/src/artifacts/NativeDmgArtifactReader.ts @@ -123,6 +123,17 @@ class NativeDmgCommandFailure extends ArtifactReaderFailure { // Only hdiutil verify classifies a DMG failure as integrity. integrityCheck: failure.reason === "integrity" ? "image-checksum" : undefined, + // hdiutil's own verdict that the bytes are not a disk image it reads. + ...(failure.reason === "unsupported" + ? { + parseFailure: { + kind: "unsupported", + format: "dmg", + detail: message, + undecodedContent: false, + }, + } + : {}), }); this.processNotStarted = options?.processNotStarted ?? false; this.verifyDiagnostic = failure.verifyDiagnostic; diff --git a/src/artifacts/NativeDmgProtocol.test.ts b/src/artifacts/NativeDmgProtocol.test.ts index 66e989202a..21606b1780 100644 --- a/src/artifacts/NativeDmgProtocol.test.ts +++ b/src/artifacts/NativeDmgProtocol.test.ts @@ -141,7 +141,13 @@ it("retains malformed successful hdiutil inventory output as a typed producer pa if (!(failure instanceof Error)) throw new Error("Expected inventory failure"); expect( - projectAnalysisError(translateArtifactFailure("inspect_artifact", failure)), + projectAnalysisError( + translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + failure, + ), + ), ).toMatchObject({ details: { reason: "io", detail: failure.message }, }); @@ -213,7 +219,11 @@ it("reports an hdiutil retained while the reader closes, after its own cleanup c /* consume */ } })(), - ).rejects.toMatchObject({ reason: "unsupported" }); + ).rejects.toMatchObject({ + reason: "unsupported", + // hdiutil's verdict carries its facts, so it projects as a target failure. + parseFailure: { kind: "unsupported", format: "dmg" }, + }); const refused = await reader.close().catch((cause: unknown) => cause); expect(refused).toBeInstanceOf(ArtifactReaderFailure); expect((refused as ArtifactReaderFailure).cleanup?.resources).toEqual([ diff --git a/src/artifacts/NativeDmgRootObservation.test.ts b/src/artifacts/NativeDmgRootObservation.test.ts index cdb725aac7..f348afa054 100644 --- a/src/artifacts/NativeDmgRootObservation.test.ts +++ b/src/artifacts/NativeDmgRootObservation.test.ts @@ -76,7 +76,11 @@ it.each(["same", "other", "missing-path", "no-path", "empty-group"] as const)( failure = cause; } const projected = projectAnalysisError( - translateArtifactFailure("inspect_artifact", failure), + translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + failure, + ), ); expect(projected).toMatchObject({ category: "unavailable", diff --git a/src/artifacts/NtfsMftArtifactReader.test.ts b/src/artifacts/NtfsMftArtifactReader.test.ts index 51b9583cf8..5ad01102bb 100644 --- a/src/artifacts/NtfsMftArtifactReader.test.ts +++ b/src/artifacts/NtfsMftArtifactReader.test.ts @@ -363,7 +363,11 @@ it("reports a $MFT stream that shrinks during decoding as a changed file, not ma // The public projection names the model's kind: a changed target. expect( projectAnalysisError( - translateArtifactFailure("inspect_artifact", failure), + translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + failure, + ), ), ).toMatchObject({ code: "artifact_changed", diff --git a/src/artifacts/PyInstallerArtifactReader.ts b/src/artifacts/PyInstallerArtifactReader.ts index 896a708f19..4657ebc14f 100644 --- a/src/artifacts/PyInstallerArtifactReader.ts +++ b/src/artifacts/PyInstallerArtifactReader.ts @@ -16,6 +16,7 @@ import { ArtifactResourceScope, abortIfNeeded, ArtifactFileSource, + unsupportedArtifact, } from "../resources/index.js"; import type { FileHandle } from "node:fs/promises"; @@ -472,8 +473,8 @@ export class PyInstallerArtifactReader implements ArtifactReader { if (!found.ok) throw failure(found.error); const observed = found.value; if (observed.state === "absent") - throw new ArtifactReaderFailure( - "unsupported", + throw unsupportedArtifact( + "pyinstaller", "PyInstaller CArchive cookie was not found", ); if (observed.state === "rejected-candidates") diff --git a/src/artifacts/ReleaseExposureReader.test.ts b/src/artifacts/ReleaseExposureReader.test.ts index 8fa8b1b7e9..ba6226395a 100644 --- a/src/artifacts/ReleaseExposureReader.test.ts +++ b/src/artifacts/ReleaseExposureReader.test.ts @@ -45,6 +45,7 @@ import { ArtifactReaderFailure, type ArtifactEntry, type ArtifactReader, + malformedArtifact, } from "../resources/ArtifactReader.js"; import { assembleReleaseExposureReport, @@ -4163,7 +4164,9 @@ describe("ReleaseExposureReader cleanup-bearing read failures", () => { resource: string, ): ArtifactReaderFailure => ArtifactReaderFailure.withCleanup( - new ArtifactReaderFailure(reason, `${reason} failure: ${resource}`), + reason === "malformed" + ? malformedArtifact("source-map", `${reason} failure: ${resource}`) + : new ArtifactReaderFailure(reason, `${reason} failure: ${resource}`), { reason: "close failed", resources: [resource] }, ); diff --git a/src/artifacts/ZipArtifactReader.test.ts b/src/artifacts/ZipArtifactReader.test.ts index ddc0f016a4..9bc0a6418f 100644 --- a/src/artifacts/ZipArtifactReader.test.ts +++ b/src/artifacts/ZipArtifactReader.test.ts @@ -228,12 +228,16 @@ describe("ZIP Zstandard method 93", () => { message: expect.stringContaining("Zstandard dictionary"), cause: { code: "ZSTD_error_dictionary_wrong" }, }); - expect(translateArtifactFailure("extract_artifact", failure)).toMatchObject( - { - reason: "unavailable", - detail: expect.stringContaining("Zstandard dictionary"), - }, - ); + expect( + translateArtifactFailure( + "extract_artifact", + "/selected/artifact", + failure, + ), + ).toMatchObject({ + reason: "unavailable", + detail: expect.stringContaining("Zstandard dictionary"), + }); }); it.each([ diff --git a/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts b/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts index 99fd2338a1..702b812d13 100644 --- a/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts +++ b/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts @@ -894,10 +894,10 @@ it.each(["reported carutil", "tab-indented carutil", "observed assetutil"])( retryable: false, details: { operation: "inspect_asset_catalog", - reason: "malformed", + path, + reason: expect.stringContaining(relativePath), failure_kind: "malformed", format: "asset-catalog", - detail: expect.stringContaining(relativePath), diagnostics: { catalog_path: relativePath }, captured_output: { stdout: "partial metadata", diff --git a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts index 8715f2d888..7112a86ecc 100644 --- a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts +++ b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts @@ -7,6 +7,7 @@ import { AnalysisOutputError, AnalysisCapabilityUnavailableError, OwnerCancellation, + AnalysisTargetFailureError, } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { createHash, randomUUID } from "node:crypto"; @@ -20,6 +21,7 @@ import { type ArtifactReaderTraversal, DirectoryArtifactReader, translateArtifactFailure, + translateArtifactOperationFailure, } from "../../resources/index.js"; import { InternalInvariantError } from "../../domain/internalInvariant.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; @@ -29,7 +31,6 @@ import { ArtifactTraversalObservation, declaredArtifactEntries, } from "../ArtifactTraversalObservation.js"; -import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js"; import { parseJsonWithDuplicatePolicy } from "../../domain/jsonDuplicateMember.js"; import { @@ -154,9 +155,14 @@ export const analyzeAppleAssetCatalogs = async (input: { "inspect_asset_catalog", { cause }, ) - : translateArtifactFailure("inspect_asset_catalog", cause); + : translateArtifactFailure( + "inspect_asset_catalog", + input.bundlePath, + cause, + ); const cleanup = translateArtifactFailure( "inspect_asset_catalog", + input.bundlePath, joined.error, ); throw analysisErrorWithCleanupDependencies( @@ -308,7 +314,7 @@ const collectAssetCatalogs = async (input: { }); if (released.kind === "failed") { if (outcome.kind === "failed" && outcome.cause instanceof AnalysisError) { - const cleanup = translateArtifactFailure( + const cleanup = translateArtifactOperationFailure( "inspect_asset_catalog", input.resources.cleanupFailure({ kind: "completed" }, [released]), ); @@ -599,19 +605,15 @@ const assetUtilOutcomeContext = ( outcome.output?.truncated === false && rejectsCatalog ) - return new ArtifactOperationError( + return new AnalysisTargetFailureError( OPERATION, - "malformed", - undefined, - `assetutil rejected ${entry.path} as an invalid asset catalog`, + entry.adapterKey, { - ...details, - parseFailure: { - kind: "malformed", - format: "asset-catalog", - detail: `assetutil rejected ${entry.path} as an invalid asset catalog`, - }, + kind: "malformed", + format: "asset-catalog", + detail: `assetutil rejected ${entry.path} as an invalid asset catalog`, }, + details, ); return new AnalysisOutputError( OPERATION, diff --git a/src/artifacts/apple/DylibResolutionReader.ts b/src/artifacts/apple/DylibResolutionReader.ts index 13e7143763..30a4621f67 100644 --- a/src/artifacts/apple/DylibResolutionReader.ts +++ b/src/artifacts/apple/DylibResolutionReader.ts @@ -24,6 +24,7 @@ import { assertArtifactReadActive, targetDigestChangedFailure, DirectoryArtifactReader, + unsupportedArtifact, } from "../../resources/index.js"; import { ArtifactTraversalObservation } from "../ArtifactTraversalObservation.js"; import { consumeWithOrderedReads } from "../OrderedReads.js"; @@ -347,7 +348,9 @@ const requireMachoRoots = async ( ? new AnalysisInputError(OPERATION, undefined, [ { path: ["roots", index], reason: "invalid_value", message }, ]) - : new ArtifactReaderFailure(reason, message); + : reason === "unsupported" + ? unsupportedArtifact("macho", message) + : new ArtifactReaderFailure(reason, message); const lookup = await resolveTreePath(view, path); if (lookup.kind === "escapes") throw reject("path", `Root ${path} resolves outside the analyzed root`); diff --git a/src/artifacts/apple/InterfaceBuilderFinalization.test.ts b/src/artifacts/apple/InterfaceBuilderFinalization.test.ts index d14914b69a..4aa9b1a86b 100644 --- a/src/artifacts/apple/InterfaceBuilderFinalization.test.ts +++ b/src/artifacts/apple/InterfaceBuilderFinalization.test.ts @@ -82,6 +82,7 @@ it.each([ }); const projected = translateArtifactFailure( "decode_interface_builder", + "/selected/artifact", outcome.cause, ); if (abort) expect(projected.cause).toBe(reason); @@ -141,6 +142,7 @@ it.each([false, true])( else expect(rejected).toBe(failure); const projected = translateArtifactFailure( "decode_interface_builder", + "/selected/artifact", rejected, ); expect(projected.partialObservation).toBeUndefined(); diff --git a/src/artifacts/apple/KeyedArchiveRawRefusal.test.ts b/src/artifacts/apple/KeyedArchiveRawRefusal.test.ts index 3b6e064c8e..cb3bae12f6 100644 --- a/src/artifacts/apple/KeyedArchiveRawRefusal.test.ts +++ b/src/artifacts/apple/KeyedArchiveRawRefusal.test.ts @@ -100,7 +100,11 @@ it("keeps the reader's raw EIO refusal an artifact failure", async () => { expect(rejected.reason).toBe("io"); expect( projectAnalysisError( - translateArtifactFailure("inspect_keyed_archive", rejected), + translateArtifactFailure( + "inspect_keyed_archive", + "/selected/artifact", + rejected, + ), ), ).toMatchObject({ code: "artifact_operation_failed", diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts index c76e9603a1..9c35846046 100644 --- a/src/artifacts/apple/KeyedArchiveReader.ts +++ b/src/artifacts/apple/KeyedArchiveReader.ts @@ -12,7 +12,7 @@ import { ArtifactResourceScope, DirectoryArtifactReader, DirectoryArtifactEntryAccessDenied, - translateArtifactFailure, + translateArtifactOperationFailure, artifactParseFailure, malformedArtifact, } from "../../resources/index.js"; @@ -226,7 +226,7 @@ export const inspectBundleKeyedArchive = (input: BundleKeyedArchiveInput) => { }); if (released.kind === "failed") { if (outcome.kind === "failed" && outcome.cause instanceof AnalysisError) { - const cleanup = translateArtifactFailure( + const cleanup = translateArtifactOperationFailure( "inspect_keyed_archive", resources.cleanupFailure({ kind: "completed" }, [released]), ); diff --git a/src/artifacts/extraction/ArtifactExtraction.test.ts b/src/artifacts/extraction/ArtifactExtraction.test.ts index ef2502814d..e702ab2ca6 100644 --- a/src/artifacts/extraction/ArtifactExtraction.test.ts +++ b/src/artifacts/extraction/ArtifactExtraction.test.ts @@ -5,7 +5,10 @@ import { createHash } from "node:crypto"; import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js"; import { expect, it, vi } from "vitest"; -import { ArtifactReaderFailure } from "../../resources/ArtifactReader.js"; +import { + ArtifactReaderFailure, + malformedArtifact, +} from "../../resources/ArtifactReader.js"; import { ArtifactResourceScope } from "../../resources/ArtifactResourceScope.js"; import { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js"; import { openRegularFile } from "../../filesystem/RegularFile.js"; @@ -379,7 +382,7 @@ it.each([false, true] as const)( vi.mock("../pyinstaller/CArchiveLayout.js", async (importOriginal) => ({ ...(await importOriginal()), observePyInstallerCookie: () => - Promise.reject(new ArtifactReaderFailure("malformed", "detection failed")), + Promise.reject(malformedArtifact("pyinstaller", "detection failed")), })); vi.mock("../../filesystem/RegularFile.js", async (importOriginal) => { diff --git a/src/artifacts/inventory/ArtifactGraphConstruction.test.ts b/src/artifacts/inventory/ArtifactGraphConstruction.test.ts index 25a0d33a44..65679ac721 100644 --- a/src/artifacts/inventory/ArtifactGraphConstruction.test.ts +++ b/src/artifacts/inventory/ArtifactGraphConstruction.test.ts @@ -164,7 +164,7 @@ it("projects the parsed ASAR header size when admission rejects an archive", () throw new Error("ASAR admission failure was not classified"); const projected = projectAnalysisError( - translateArtifactFailure("inspect_artifact", failure), + translateArtifactFailure("inspect_artifact", "/selected/artifact", failure), ); expect(projected.details?.limit).toMatchObject({ required_value: headerBytes, diff --git a/src/artifacts/inventory/ArtifactInventoryFinalization.test.ts b/src/artifacts/inventory/ArtifactInventoryFinalization.test.ts index 6d1d1d576d..c54eab60ee 100644 --- a/src/artifacts/inventory/ArtifactInventoryFinalization.test.ts +++ b/src/artifacts/inventory/ArtifactInventoryFinalization.test.ts @@ -5,7 +5,10 @@ import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js"; import { afterEach, expect, it, vi } from "vitest"; import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { ArtifactProvider } from "../ArtifactProvider.js"; -import { ArtifactReaderFailure } from "../../resources/ArtifactReader.js"; +import { + ArtifactReaderFailure, + malformedArtifact, +} from "../../resources/ArtifactReader.js"; import { ArtifactResourceScope } from "../../resources/ArtifactResourceScope.js"; import { ZipArtifactReader, @@ -175,10 +178,7 @@ it("keeps an earlier inventory failure primary when cleanup is cancelled", async const { path } = await zipFixture(); const scope = new ArtifactResourceScope(); const controller = new AbortController(); - const primary = new ArtifactReaderFailure( - "malformed", - "member enumeration failed", - ); + const primary = malformedArtifact("zip", "member enumeration failed"); const enumeration = vi .spyOn(ZipArtifactReader.prototype, "entries") .mockImplementation(async function* () { diff --git a/src/artifacts/pyinstaller/PyInstallerBoundaries.test.ts b/src/artifacts/pyinstaller/PyInstallerBoundaries.test.ts index 5ab9879ec5..ece0d7dde0 100644 --- a/src/artifacts/pyinstaller/PyInstallerBoundaries.test.ts +++ b/src/artifacts/pyinstaller/PyInstallerBoundaries.test.ts @@ -574,7 +574,11 @@ it.each(["ENOENT", "ENOTDIR"] as const)( }); expect( projectAnalysisError( - translateArtifactFailure("extract_artifact", cause), + translateArtifactFailure( + "extract_artifact", + "/selected/artifact", + cause, + ), ), ).toMatchObject({ category: "integrity_mismatch", diff --git a/src/browser/assets/WebArtifactReads.ts b/src/browser/assets/WebArtifactReads.ts index 8cfd70375a..cf0349dd91 100644 --- a/src/browser/assets/WebArtifactReads.ts +++ b/src/browser/assets/WebArtifactReads.ts @@ -12,6 +12,8 @@ import { type ArtifactResourceScope, completedStableArtifact, readStableArtifact, + artifactOperationReason, + artifactReaderTargetFailure, } from "../../resources/index.js"; import { AnalysisError, @@ -190,13 +192,22 @@ const webArtifactPrimaryError = ( ? selectedFileError({ cause, origin }, context) : undefined; if (selection !== undefined) return selection; + const target = + origin === "owned-or-classified" + ? artifactReaderTargetFailure( + context.operation, + context.targetPath, + cause, + ) + : undefined; + if (target !== undefined) return target; if ( origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure ) return new ArtifactOperationError( context.operation, - cause.reason, + artifactOperationReason(cause), cause.details, cause.reason === "limit" && context.limitRecovery !== undefined ? `${cause.message} ${context.limitRecovery}` @@ -231,20 +242,12 @@ const webArtifactPrimaryError = ( ? cause.failure : undefined; if (malformed !== undefined) - return context.callerSelected - ? new AnalysisTargetFailureError( - context.operation, - context.targetPath, - malformed, - { cause }, - ) - : new ArtifactOperationError( - context.operation, - "malformed", - undefined, - `${context.targetPath}: ${malformed.detail}`, - { cause, parseFailure: malformed }, - ); + return new AnalysisTargetFailureError( + context.operation, + context.targetPath, + malformed, + { cause }, + ); const invalid = cause instanceof z.ZodError ? cause : undefined; if (invalid !== undefined) return new AnalysisInputError(context.operation, { cause }, [ diff --git a/src/browser/history/playwrightTrace/TraceFailure.ts b/src/browser/history/playwrightTrace/TraceFailure.ts index c7cd373958..525a08d04a 100644 --- a/src/browser/history/playwrightTrace/TraceFailure.ts +++ b/src/browser/history/playwrightTrace/TraceFailure.ts @@ -15,6 +15,7 @@ import { artifactFileCancellationCause, stableArtifactInputFailure, readerIntegrityFailure, + artifactOperationReason, } from "../../../resources/index.js"; import { isSelectedRegularFileError } from "../../../filesystem/RegularFile.js"; @@ -62,7 +63,7 @@ export const traceFailure = (cause: unknown, path: string): AnalysisError => { return stableArtifactInputFailure(cause, operation); return new ArtifactOperationError( operation, - cause.reason, + artifactOperationReason(cause), undefined, cause.message, { cause }, diff --git a/src/domain/analysisErrorClassification.test.ts b/src/domain/analysisErrorClassification.test.ts index c29aba91d1..5c77df2d5b 100644 --- a/src/domain/analysisErrorClassification.test.ts +++ b/src/domain/analysisErrorClassification.test.ts @@ -40,16 +40,7 @@ it.each([ }, ); -it.each([ - "cancelled", - "malformed", - "truncated", - "unsupported", - "integrity", - "path", - "unavailable", - "io", -] as const)( +it.each(["cancelled", "integrity", "path", "unavailable", "io"] as const)( "reports an artifact operation %s failure as its catalogue row", (reason) => { const projected = projectAnalysisError( diff --git a/src/domain/analysisErrorClassification.ts b/src/domain/analysisErrorClassification.ts index bde1d4df74..08d50b0fa3 100644 --- a/src/domain/analysisErrorClassification.ts +++ b/src/domain/analysisErrorClassification.ts @@ -118,12 +118,7 @@ const kindClassification = ( const ARTIFACT_OPERATION_CLASSIFICATIONS = { cancelled: classified("cancelled", "cancelled"), - // Reasons that name a target failure kind take that kind's projection, so - // an inventory refusal and a selected-file refusal of the same bytes report - // the same code. `limit` reports `partial`: the result was cut short. - malformed: kindClassification("malformed"), - truncated: kindClassification("truncated"), - unsupported: kindClassification("unsupported"), + // `limit` reports `partial`: the result was cut short. integrity: classified("artifact_operation_failed", "integrity_mismatch"), limit: classified("partial", "partial"), path: classified("artifact_operation_failed", "execution_failure"), diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index 7c33d16fca..9ce77b72fb 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -562,12 +562,6 @@ const artifactMessage = ({ detail ?? "Artifact processing reached a resource limit. Select an artifact within the reported limits and retry." ); - if (reason === "unsupported") - return "Artifact structure uses an unsupported format or revision. Use a decoder that supports the reported form."; - if (reason === "truncated") - return "A declared artifact structure is truncated. Select a complete copy and retry; do not pad or truncate required bytes."; - if (reason === "malformed") - return "Artifact bytes contain malformed format structure. Review the reported field and select a valid copy."; if (reason === "path") return ( detail ?? diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index 365f3da0c5..a0e269b992 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -763,9 +763,6 @@ const artifactStateErrorDetails = ( ...(error.integrityCheck === undefined ? {} : { integrity_check: error.integrityCheck }), - ...(error.parseFailure === undefined - ? {} - : targetFailureDetails(error.parseFailure)), ...(error.readerLimit === undefined ? {} : { reader_limit: { ...error.readerLimit } }), diff --git a/src/domain/artifactOperationError.ts b/src/domain/artifactOperationError.ts index 37636f019d..bce7be9928 100644 --- a/src/domain/artifactOperationError.ts +++ b/src/domain/artifactOperationError.ts @@ -8,8 +8,7 @@ import { } from "./analysisErrorBase.js"; import type { ArtifactReaderLimitFact } from "./artifactReaderLimits.js"; import type { FixedAllowance } from "./fixedAllowanceRemediation.js"; -import type { LimitRef, ParseFailureKind } from "./parseFailure.js"; -import type { MalformedTargetFailure } from "./targetFailure.js"; +import type { LimitRef } from "./parseFailure.js"; /** The resource class that refused an artifact operation. */ export type ArtifactLimitBoundary = "file-size" | "capacity" | "memory"; @@ -92,7 +91,11 @@ export const integrityCheckMeansChanged = ( check: ArtifactIntegrityCheck | undefined, ): boolean => check !== undefined && INTEGRITY_CHECK_MEANS_CHANGED[check]; -/** Artifact inventory or extraction failed a typed safety boundary. */ +/** + * Artifact inventory or extraction failed a typed safety boundary. A target + * whose bytes its format owner refuses is an `AnalysisTargetFailureError` + * instead, so this error never classifies the target itself. + */ export class ArtifactOperationError extends AnalysisError { readonly _tag = "ArtifactOperationError"; override readonly userMessage: string | undefined; @@ -105,8 +108,6 @@ export class ArtifactOperationError extends AnalysisError { readonly fixedAllowance: FixedAllowance | undefined; /** For an `integrity` reason, the check the producing reader named. */ readonly integrityCheck: ArtifactIntegrityCheck | undefined; - /** For a `malformed` or `truncated` reason, the format owner's parsed facts. */ - readonly parseFailure: MalformedTargetFailure | undefined; constructor( readonly operation: @@ -140,7 +141,7 @@ export class ArtifactOperationError extends AnalysisError { | "trace_web_source_location" | "analyze_javascript_application", readonly reason: - | ParseFailureKind + | "limit" | "cancelled" | "integrity" | "path" @@ -158,7 +159,6 @@ export class ArtifactOperationError extends AnalysisError { readonly parserLimit?: LimitRef; readonly fixedAllowance?: FixedAllowance; readonly integrityCheck?: ArtifactIntegrityCheck; - readonly parseFailure?: MalformedTargetFailure; }, ) { super( @@ -173,7 +173,6 @@ export class ArtifactOperationError extends AnalysisError { this.parserLimit = options?.parserLimit; this.fixedAllowance = options?.fixedAllowance; this.integrityCheck = options?.integrityCheck; - this.parseFailure = options?.parseFailure; this.remediationAction = options?.remediationAction; this.userMessage = options?.userMessage ?? diff --git a/src/domain/targetFailure.ts b/src/domain/targetFailure.ts index aeb02b6ee7..a0fb1c1585 100644 --- a/src/domain/targetFailure.ts +++ b/src/domain/targetFailure.ts @@ -101,8 +101,13 @@ export type TargetFailureOf = Extract< { readonly kind: Kind } >; -/** Bytes that break, or end inside, a structure of the format being read. */ -export type MalformedTargetFailure = TargetFailureOf<"malformed" | "truncated">; +/** + * A format owner's refusal of the bytes it read: they break or end inside a + * structure of the format, or use a form outside the owner's coverage. + */ +export type FormatTargetFailure = TargetFailureOf< + "malformed" | "truncated" | "unsupported" +>; /** * When repeating the request can help, after gRPC's status semantics: diff --git a/src/java/MavenGradleMetadataProvider.ts b/src/java/MavenGradleMetadataProvider.ts index fb6c477765..2ae10ccabc 100644 --- a/src/java/MavenGradleMetadataProvider.ts +++ b/src/java/MavenGradleMetadataProvider.ts @@ -168,7 +168,7 @@ const mavenGradleMetadataFailure = ( unclassified: (failure, origin) => origin === "owned-or-classified" && failure instanceof ArtifactReaderFailure - ? translateArtifactFailure(OPERATION, failure) + ? translateArtifactFailure(OPERATION, input.path, failure) : new ArtifactOperationError( OPERATION, "io", diff --git a/src/nuget/NugetNupkgProvider.ts b/src/nuget/NugetNupkgProvider.ts index 04e7b8b74b..135bbd2baa 100644 --- a/src/nuget/NugetNupkgProvider.ts +++ b/src/nuget/NugetNupkgProvider.ts @@ -98,7 +98,7 @@ const nupkgFailure = ( failure.reason !== "integrity" && failure.reason !== "cancelled" ) - return translateArtifactFailure(OPERATION, failure); + return translateArtifactFailure(OPERATION, input.path, failure); } return undefined; }, diff --git a/src/providers/offlineArtifactFailure.ts b/src/providers/offlineArtifactFailure.ts index e8bc3dc376..22ea06b155 100644 --- a/src/providers/offlineArtifactFailure.ts +++ b/src/providers/offlineArtifactFailure.ts @@ -2,6 +2,7 @@ import { ArtifactReaderFailure, projectOwnedArtifactInputFailure, type ArtifactFilePrimaryFacts, + artifactOperationReason, } from "../resources/index.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { ArtifactOperationError } from "../domain/artifactOperationError.js"; @@ -88,7 +89,7 @@ export const offlineArtifactFailureDialect = ( options.operation, origin === "owned-or-classified" && failure instanceof ArtifactReaderFailure - ? failure.reason + ? artifactOperationReason(failure) : "io", undefined, failure instanceof Error diff --git a/src/resources/ArtifactFileOperation.ts b/src/resources/ArtifactFileOperation.ts index 9470962a8d..008eea502b 100644 --- a/src/resources/ArtifactFileOperation.ts +++ b/src/resources/ArtifactFileOperation.ts @@ -327,8 +327,6 @@ export const artifactParseFailure = ( ...(boundary === undefined ? {} : { boundary }), }); } - if (failure.kind === "unsupported") - return new ArtifactReaderFailure(failure.kind, cause.message, { cause }); return new ArtifactReaderFailure(failure.kind, cause.message, { cause, parseFailure: failure, diff --git a/src/resources/ArtifactOperationFailure.test.ts b/src/resources/ArtifactOperationFailure.test.ts index bea791f82c..cad54e3674 100644 --- a/src/resources/ArtifactOperationFailure.test.ts +++ b/src/resources/ArtifactOperationFailure.test.ts @@ -43,6 +43,7 @@ it("projects a Zstandard frame-cap as an adjustable artifact limit", () => { expect( translateArtifactFailure( "extract_artifact", + "/selected/artifact", new ZstandardFrameAllowanceError({ maxFrames: 4, source: "runtime" }, 10), ), ).toMatchObject({ @@ -95,22 +96,12 @@ const failWithDescriptorCleanup = async ( }; it.each([ - { - cause: malformedInput("pe", "bad field"), - genericCode: "unsupported_target", - }, - // Inventory and selected-file refusals of truncated bytes share one code. - { - cause: truncatedInput("pe", "short field"), - genericCode: "unsupported_target", - }, - { - cause: unsupportedInput("pe", "unsupported image"), - genericCode: "unsupported_target", - }, + { cause: malformedInput("pe", "bad field") }, + { cause: truncatedInput("pe", "short field") }, + { cause: unsupportedInput("pe", "unsupported image") }, ])( "preserves $cause.kind projection and selected identity through descriptor cleanup", - async ({ cause, genericCode }) => { + async ({ cause }) => { const operation = "inspect_pe_resources"; const bytes = Buffer.from("inert snapshot"); const sha256 = createHash("sha256").update(bytes).digest("hex"); @@ -138,7 +129,7 @@ it.each([ operation, { bytes, sha256 }, ); - const generic = translateArtifactFailure("inspect_artifact", wrapped); + const generic = translateArtifactFailure("inspect_artifact", path, wrapped); const observation = { kind: "file-snapshot-hash", path, @@ -153,8 +144,7 @@ it.each([ expect(projectAnalysisError(generic)).toMatchObject({ code: "cleanup_incomplete", details: { - reason: cause.kind, - detail: cause.message, + reason: cause.message, cleanup: "incomplete", resources: [path], }, @@ -177,23 +167,23 @@ it.each([ operation, path, reason: cause.message, - ...(cause.kind === "unsupported" - ? {} - : { failure_kind: cause.kind, format: "pe" }), + failure_kind: cause.kind, + format: "pe", partial_observation: observation, }, }); - // The inventory path carries the format owner's parsed facts too, so - // both adapters name the same format and failure kind. + // An inventory refusal of the same bytes is the same target failure of + // the selected path, with the format owner's facts. expect(projectAnalysisError(generic)).toMatchObject({ - code: genericCode, - category: genericCode, + code: "unsupported_target", + category: "unsupported_target", + retry: "none", details: { - reason: cause.kind, - detail: cause.message, - ...(cause.kind === "unsupported" - ? {} - : { failure_kind: cause.kind, format: "pe" }), + operation: "inspect_artifact", + path, + reason: cause.message, + failure_kind: cause.kind, + format: "pe", }, }); }, @@ -246,7 +236,11 @@ it.each([ required, ); const projected = projectAnalysisError( - translateArtifactFailure("inspect_artifact", failure), + translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + failure, + ), ); expect(projected).toMatchObject({ retryable: false, @@ -268,7 +262,7 @@ it("preserves adjustable reader admission facts and gives cleanup priority", () 2, ); const adjustable = projectAnalysisError( - translateArtifactFailure("inspect_artifact", failure), + translateArtifactFailure("inspect_artifact", "/selected/artifact", failure), ); expect(adjustable).toMatchObject({ code: "partial", @@ -293,7 +287,7 @@ it("preserves adjustable reader admission facts and gives cleanup priority", () resources: ["owned input descriptor"], }); const projected = projectAnalysisError( - translateArtifactFailure("inspect_artifact", wrapped), + translateArtifactFailure("inspect_artifact", "/selected/artifact", wrapped), ); expect(projected.retryable).toBe(false); expect(projected.details).toMatchObject({ @@ -312,7 +306,11 @@ it.each(["capacity", "file-size", "memory"] as const)( { boundary }, ); const result = projectAnalysisError( - translateArtifactFailure("inventory_artifact", failure), + translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + failure, + ), ); expect(result).toMatchObject({ code: "partial", @@ -326,7 +324,11 @@ it.each(["capacity", "file-size", "memory"] as const)( }); expect( projectAnalysisError( - translateArtifactFailure("inventory_artifact", wrapped), + translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + wrapped, + ), ), ).toMatchObject({ code: "cleanup_incomplete", @@ -345,7 +347,11 @@ it("reports a parser limit even when artifact cleanup also fails", () => { }); expect( projectAnalysisError( - translateArtifactFailure("inspect_keyed_archive", wrapped), + translateArtifactFailure( + "inspect_keyed_archive", + "/selected/artifact", + wrapped, + ), ), ).toMatchObject({ code: "cleanup_incomplete", @@ -376,7 +382,13 @@ it("keeps a fixed reader ceiling's refusal through cleanup wrapping and public p unit: "records", }; expect( - projectAnalysisError(translateArtifactFailure("inspect_artifact", failure)), + projectAnalysisError( + translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + failure, + ), + ), ).toMatchObject({ code: "partial", retryable: false, @@ -388,7 +400,7 @@ it("keeps a fixed reader ceiling's refusal through cleanup wrapping and public p resources: ["handle"], }); const projected = projectAnalysisError( - translateArtifactFailure("inspect_artifact", wrapped), + translateArtifactFailure("inspect_artifact", "/selected/artifact", wrapped), ); expect(projected).toMatchObject({ code: "cleanup_incomplete", @@ -411,7 +423,7 @@ it("keeps producer-owned recovery through cleanup wrapping and public projection resources: ["owned staging"], }); const projected = projectAnalysisError( - translateArtifactFailure("inspect_artifact", wrapped), + translateArtifactFailure("inspect_artifact", "/selected/artifact", wrapped), ); expect(projected.message).toBe(userMessage); expect(projected.remediation.action).toBe(userMessage); @@ -427,6 +439,7 @@ it("projects a session digest mismatch as admitted identity, not a retryable cha const projected = projectAnalysisError( translateArtifactFailure( "inspect_keyed_archive", + "/selected/archive", targetDigestChangedFailure("archive", "a".repeat(64), "b".repeat(64)), ), ); @@ -450,7 +463,11 @@ it("names the failed integrity check through cleanup wrapping and public project ); expect( projectAnalysisError( - translateArtifactFailure("inventory_artifact", failure), + translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + failure, + ), ), ).toMatchObject({ details: { reason: "integrity", integrity_check: "container-identity" }, @@ -461,7 +478,11 @@ it("names the failed integrity check through cleanup wrapping and public project }); expect( projectAnalysisError( - translateArtifactFailure("inventory_artifact", wrapped), + translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + wrapped, + ), ), ).toMatchObject({ code: "cleanup_incomplete", @@ -480,7 +501,11 @@ it("names the failed integrity check through cleanup wrapping and public project ); expect( projectAnalysisError( - translateArtifactFailure("extract_artifact", unpacked), + translateArtifactFailure( + "extract_artifact", + "/selected/artifact", + unpacked, + ), ), ).toMatchObject({ details: { @@ -503,7 +528,13 @@ it("keeps the named integrity check through descriptor cleanup", async () => { ), ); expect( - projectAnalysisError(translateArtifactFailure("extract_artifact", wrapped)), + projectAnalysisError( + translateArtifactFailure( + "extract_artifact", + "/selected/artifact", + wrapped, + ), + ), ).toMatchObject({ code: "cleanup_incomplete", details: { integrity_check: "read-coverage", resources: [path] }, @@ -533,7 +564,7 @@ it("keeps a reader's named check when a provider supplies its own cause and opti }); }); -// A reader's `format` reason means target bytes; only `path` names the +// A reader's target reasons mean the bytes; only `path` names the // caller's selection. A non-regular source is a path-kind refusal at its owner. it("keeps only a path-kind reader refusal a selection error", () => { const operation = "inspect_erlang_beam"; @@ -559,12 +590,4 @@ it("keeps only a path-kind reader refusal a selection error", () => { issues: [{ path: ["path"], reason: "invalid_format" }], }, }); - const bytes = new ArtifactReaderFailure("malformed", "Corrupt member table"); - expect( - projectOwnedArtifactInputFailure( - artifactFilePrimaryFacts(bytes), - operation, - path, - ), - ).toBeUndefined(); }); diff --git a/src/resources/ArtifactOperationFailure.ts b/src/resources/ArtifactOperationFailure.ts index f2bf8230af..5b098af101 100644 --- a/src/resources/ArtifactOperationFailure.ts +++ b/src/resources/ArtifactOperationFailure.ts @@ -4,6 +4,7 @@ import { ZstandardFrameAllowanceError, } from "../domain/compression/zstandardFrameAllowance.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; +import { AnalysisTargetFailureError } from "../domain/analysisErrorCore.js"; import { ArtifactOperationError } from "../domain/artifactOperationError.js"; import { InternalInvariantError } from "../domain/internalInvariant.js"; import { ArtifactReaderFailure } from "./ArtifactReader.js"; @@ -16,68 +17,24 @@ import { * Translate one artifact boundary failure while retaining cleanup evidence. A * broken internal assumption is a REA defect, not an artifact read failure, so * it is rethrown for the provider adapter to report. + * + * A format owner's refusal of the bytes becomes the target failure of `path`, + * the target the caller selected, whichever member the reader was reading. */ export const translateArtifactFailure = ( operation: ArtifactOperationError["operation"], + path: string, cause: unknown, ): AnalysisError => { if (cause instanceof InternalInvariantError) throw cause; if (cause instanceof ZstandardFrameAllowanceError) return projectZstandardFrameAllowance(operation, cause); if (cause instanceof ArtifactReaderFailure) { - const error = new ArtifactOperationError( - operation, - cause.reason, - cause.details, - cause.message, - { - ...(cause.userMessage === undefined - ? {} - : { userMessage: cause.userMessage }), - cause: - cause.reason === "cancelled" - ? artifactFileCancellationCause(cause) - : cause, - ...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }), - ...(cause.partialObservation === undefined - ? {} - : { partialObservation: cause.partialObservation }), - ...(cause.admission === undefined - ? {} - : { admission: cause.admission }), - ...(cause.boundary === undefined ? {} : { boundary: cause.boundary }), - ...(cause.readerLimit === undefined - ? {} - : { readerLimit: cause.readerLimit }), - ...(cause.parserLimit === undefined - ? {} - : { parserLimit: cause.parserLimit }), - ...(cause.fixedAllowance === undefined - ? {} - : { fixedAllowance: cause.fixedAllowance }), - ...(cause.integrityCheck === undefined - ? {} - : { integrityCheck: cause.integrityCheck }), - ...(cause.parseFailure === undefined - ? {} - : { parseFailure: cause.parseFailure }), - }, - ); - if (cause.admission !== undefined) - error.bindLimit({ - ...analysisSettingLimit( - cause.admission.kind === "asar-header" - ? "asar.max_header_bytes" - : "asar.max_listing_bytes", - cause.admission.maximumBytes, - cause.admission.source, - ), - ...(cause.admission.requiredBytes === undefined - ? {} - : { required_value: cause.admission.requiredBytes }), - }); - bindArtifactFileCleanup(cause, error); - return error; + const target = artifactReaderTargetFailure(operation, path, cause); + if (target === undefined) + return translateArtifactOperationFailure(operation, cause); + bindArtifactFileCleanup(cause, target); + return target; } // Keep typed Evidence and other analysis failures instead of reducing them to I/O. if (cause instanceof AnalysisError) return cause; @@ -85,3 +42,103 @@ export const translateArtifactFailure = ( cause, }); }; + +/** + * Translate a reader failure of the operation rather than of its target, such + * as a cancellation or a cleanup failure. A format owner's refusal is a + * target failure and needs {@link translateArtifactFailure} with its path. + */ +export const translateArtifactOperationFailure = ( + operation: ArtifactOperationError["operation"], + cause: ArtifactReaderFailure, +): ArtifactOperationError => { + const reason = artifactOperationReason(cause); + const error = new ArtifactOperationError( + operation, + reason, + cause.details, + cause.message, + { + ...(cause.userMessage === undefined + ? {} + : { userMessage: cause.userMessage }), + cause: + cause.reason === "cancelled" + ? artifactFileCancellationCause(cause) + : cause, + ...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }), + ...(cause.partialObservation === undefined + ? {} + : { partialObservation: cause.partialObservation }), + ...(cause.admission === undefined ? {} : { admission: cause.admission }), + ...(cause.boundary === undefined ? {} : { boundary: cause.boundary }), + ...(cause.readerLimit === undefined + ? {} + : { readerLimit: cause.readerLimit }), + ...(cause.parserLimit === undefined + ? {} + : { parserLimit: cause.parserLimit }), + ...(cause.fixedAllowance === undefined + ? {} + : { fixedAllowance: cause.fixedAllowance }), + ...(cause.integrityCheck === undefined + ? {} + : { integrityCheck: cause.integrityCheck }), + }, + ); + if (cause.admission !== undefined) + error.bindLimit({ + ...analysisSettingLimit( + cause.admission.kind === "asar-header" + ? "asar.max_header_bytes" + : "asar.max_listing_bytes", + cause.admission.maximumBytes, + cause.admission.source, + ), + ...(cause.admission.requiredBytes === undefined + ? {} + : { required_value: cause.admission.requiredBytes }), + }); + bindArtifactFileCleanup(cause, error); + return error; +}; + +/** + * The target failure a reader's format owner raised, as the refusal of + * `path`, with the reader's cleanup and completed observation. Undefined when + * `cause` is not a format owner's refusal. + */ +export const artifactReaderTargetFailure = ( + operation: string, + path: string, + cause: unknown, +): AnalysisTargetFailureError | undefined => + cause instanceof ArtifactReaderFailure && cause.parseFailure !== undefined + ? new AnalysisTargetFailureError(operation, path, cause.parseFailure, { + cause, + ...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }), + ...(cause.partialObservation === undefined + ? {} + : { partialObservation: cause.partialObservation }), + }) + : undefined; + +/** + * The operation reason of a reader failure that carries no target failure. + * A target reason without the owner's facts is a reader defect. + */ +export const artifactOperationReason = ( + cause: ArtifactReaderFailure, +): ArtifactOperationError["reason"] => { + switch (cause.reason) { + case "malformed": + case "truncated": + case "unsupported": + throw new InternalInvariantError( + `Artifact reader raised ${cause.reason} without its format facts`, + { cause }, + ); + default: + return cause.reason; + } +}; diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index 603c8b9e99..ab0623e1a1 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -28,7 +28,7 @@ import type { } from "../domain/analysisErrorBase.js"; import { errorMessage } from "../kernel/errorMessage.js"; import type { LimitRef } from "../domain/parseFailure.js"; -import type { MalformedTargetFailure } from "../domain/targetFailure.js"; +import type { FormatTargetFailure } from "../domain/targetFailure.js"; export interface ArtifactReaderFailureOptions extends ErrorOptions { /** Recovery guidance established by the producing adapter, separate from diagnostics. */ @@ -51,10 +51,10 @@ export interface ArtifactReaderFailureOptions extends ErrorOptions { /** For an `integrity` failure, the check that failed, when the reader names it. */ readonly integrityCheck?: ArtifactIntegrityCheck | undefined; /** - * For a `malformed` or `truncated` failure, the format owner's parsed facts. - * Set by {@link artifactParseFailure} from the owner's `ParseFailureError`. + * For a `malformed`, `truncated` or `unsupported` failure, the format + * owner's facts. Set by {@link artifactFormatFailure}. */ - readonly parseFailure?: MalformedTargetFailure | undefined; + readonly parseFailure?: FormatTargetFailure | undefined; } /** Archive-neutral entry metadata. Reader adapters never choose output paths. */ @@ -295,7 +295,9 @@ export type CleanupFailedRead = ArtifactReaderFailure & { }; /** Why an artifact reader failed. */ -export type ArtifactReaderFailureReason = ArtifactOperationError["reason"]; +export type ArtifactReaderFailureReason = + | ArtifactOperationError["reason"] + | FormatTargetFailure["kind"]; export class ArtifactReaderFailure extends Error { readonly userMessage: string | undefined; @@ -312,7 +314,7 @@ export class ArtifactReaderFailure extends Error { readonly parserLimit: LimitRef | undefined; readonly fixedAllowance: ArtifactFixedLimit | undefined; readonly integrityCheck: ArtifactIntegrityCheck | undefined; - readonly parseFailure: MalformedTargetFailure | undefined; + readonly parseFailure: FormatTargetFailure | undefined; /** An `integrity` failure names the check that failed. */ constructor( @@ -323,8 +325,20 @@ export class ArtifactReaderFailure extends Error { }, details?: ArtifactIntegrityDetails, ); + /** A format owner's refusal carries the owner's facts. */ constructor( - reason: Exclude, + reason: FormatTargetFailure["kind"], + message: string, + options: ArtifactReaderFailureOptions & { + readonly parseFailure: FormatTargetFailure; + }, + details?: ArtifactIntegrityDetails, + ); + constructor( + reason: Exclude< + ArtifactReaderFailureReason, + "integrity" | FormatTargetFailure["kind"] + >, message: string, options?: ArtifactReaderFailureOptions, details?: ArtifactIntegrityDetails, @@ -366,7 +380,9 @@ export class ArtifactReaderFailure extends Error { this.fixedAllowance = options?.fixedAllowance; this.integrityCheck = options?.integrityCheck; this.parseFailure = - reason === "malformed" || reason === "truncated" + reason === "malformed" || + reason === "truncated" || + reason === "unsupported" ? options?.parseFailure : undefined; } @@ -531,7 +547,7 @@ export interface ArtifactTruncationSite extends ArtifactFormatSite { * reinterpret the message. */ export const artifactFormatFailure = ( - failure: MalformedTargetFailure, + failure: FormatTargetFailure, options: Omit = {}, ): ArtifactReaderFailure => new ArtifactReaderFailure(failure.kind, failure.detail, { @@ -555,6 +571,31 @@ export const malformedArtifact = ( options, ); +/** + * The bytes use a form outside what this reader of `format` decodes. + * `undecodedContent` says the input holds the content in that form. + */ +export const unsupportedArtifact = ( + format: string, + detail: string, + { + offset, + field, + undecodedContent = false, + ...options + }: ArtifactFormatSite & { readonly undecodedContent?: boolean } = {}, +): ArtifactReaderFailure => + artifactFormatFailure( + { + kind: "unsupported", + format, + detail, + undecodedContent, + ...located(offset, field), + }, + options, + ); + /** The bytes end before a structure `format` declares. */ export const truncatedArtifact = ( format: string, diff --git a/src/resources/ArtifactResourceScope.test.ts b/src/resources/ArtifactResourceScope.test.ts index 38963e7ad3..4f98847cbe 100644 --- a/src/resources/ArtifactResourceScope.test.ts +++ b/src/resources/ArtifactResourceScope.test.ts @@ -433,7 +433,11 @@ it("binds initial mixed cleanup to only its unresolved owners", async () => { throw new Error("Expected owned cleanup failures"); const initial = scope.cleanupFailure({ kind: "completed" }, [a, b]); expect(initial.cleanupLeases).toEqual([a.lease, b.lease]); - const error = translateArtifactFailure("inventory_artifact", initial); + const error = translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + initial, + ); denyFirst = false; const retry = await scope.retryCleanup().catch((cause: unknown) => cause); expect(retry).toBeInstanceOf(ArtifactResourceRetryFailure); @@ -478,7 +482,11 @@ it.each(["owned-close", "independent-primary"] as const)( ? { kind: "completed" as const } : { kind: "failed" as const, cause: unknown }; const initial = scope.cleanupFailure(outcome, [attempt]); - const error = translateArtifactFailure("inventory_artifact", initial); + const error = translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + initial, + ); expect(error.cleanupIncomplete).toBe(true); denied = false; await scope.close(); @@ -521,7 +529,11 @@ it.each([undefined, null, { reason: "opaque reason" }])( ]); expect(initial.reason).toBe("cancelled"); expect(initial.cancellation?.reason).toBe(reason); - const error = translateArtifactFailure("inventory_artifact", initial); + const error = translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + initial, + ); expect(error.cause).toBe(reason); denied = false; await scope.close(); @@ -555,7 +567,11 @@ it("does not clear independent domain cleanup when a new scope owner releases", const initial = scope.cleanupFailure({ kind: "failed", cause: primary }, [ attempt, ]); - const error = translateArtifactFailure("inventory_artifact", initial); + const error = translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + initial, + ); denied = false; await scope.close(); expect(attempt.lease.released).toBe(true); @@ -606,7 +622,11 @@ it.each(["completed", "failed"] as const)( ).catch((cause: unknown) => cause); if (!(failure instanceof ArtifactReaderFailure)) throw new Error("Expected physical file failure"); - const error = translateArtifactFailure("inventory_artifact", failure); + const error = translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + failure, + ); expect(error.cleanupIncomplete).toBe(true); denied = false; await scope.close(); @@ -649,6 +669,7 @@ it.each(["artifact", "domain"] as const)( throw new Error("Expected retained children"); const error = translateArtifactFailure( "inventory_artifact", + "/selected/artifact", scope.cleanupFailure({ kind: "completed" }, [attempt]), ); expect(error.cleanupResources).toEqual(children); diff --git a/src/resources/StableArtifactFailure.ts b/src/resources/StableArtifactFailure.ts index 4acd75a314..a898f79ef1 100644 --- a/src/resources/StableArtifactFailure.ts +++ b/src/resources/StableArtifactFailure.ts @@ -21,7 +21,6 @@ import { AnalysisArtifactChangedError, AnalysisInputError, AnalysisTargetFailureError, - AnalysisUnsupportedTargetError, cancelledBy, carriedReason, } from "../domain/analysisErrorCore.js"; @@ -80,15 +79,11 @@ export const projectOwnedArtifactInputFailure = ( !(cause instanceof ArtifactReaderFailure) ) return undefined; - if (cause.reason === "unsupported") - return new AnalysisUnsupportedTargetError(operation, path, cause.message, { - cause, - }); - // A parser's malformed or truncated bytes keep the format owner's parsed - // facts and are a target refusal; the request that selected the file is not - // at fault. The reader records those facts only for its own malformed or - // truncated reason, so a cancelled read whose opaque abort reason happens to - // be a parser failure stays a cancellation. + // A format owner's malformed, truncated or unsupported bytes keep its facts + // and are a target refusal; the request that selected the file is not at + // fault. The reader records those facts only for its own target reason, so + // a cancelled read whose opaque abort reason happens to be a parser failure + // stays a cancellation. if (cause.parseFailure !== undefined) return new AnalysisTargetFailureError(operation, path, cause.parseFailure, { cause, diff --git a/src/resources/index.ts b/src/resources/index.ts index 4482c2e165..aff96e0973 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -25,7 +25,12 @@ export { ArtifactFileSource, assertArtifactFileSelectedSource, } from "./ArtifactFileSource.js"; -export { translateArtifactFailure } from "./ArtifactOperationFailure.js"; +export { + artifactOperationReason, + artifactReaderTargetFailure, + translateArtifactFailure, + translateArtifactOperationFailure, +} from "./ArtifactOperationFailure.js"; export { ArtifactFileCancelled, ArtifactFileCleanupFailure, @@ -52,6 +57,7 @@ export { artifactFormatFailure, malformedArtifact, truncatedArtifact, + unsupportedArtifact, artifactPrimaryCleanupLeases, assertProducedEntry, copyArtifactEntry, diff --git a/tests/acceptance/androidBootImageCli.test.ts b/tests/acceptance/androidBootImageCli.test.ts index dacf0bf82c..ad0caba910 100644 --- a/tests/acceptance/androidBootImageCli.test.ts +++ b/tests/acceptance/androidBootImageCli.test.ts @@ -117,10 +117,8 @@ cliTest( category: fixture.category, details: { operation: "inspect_artifact", - reason: fixture.kind, - ...("format" in fixture - ? { failure_kind: fixture.kind, format: fixture.format } - : {}), + failure_kind: fixture.kind, + format: "format" in fixture ? fixture.format : "android-boot-image", }, }); expect((await readFile(path)).equals(fixture.bytes)).toBe(true); diff --git a/tests/acceptance/applications/javascriptSourceSelectionCli.test.ts b/tests/acceptance/applications/javascriptSourceSelectionCli.test.ts index e245db3422..c9de228011 100644 --- a/tests/acceptance/applications/javascriptSourceSelectionCli.test.ts +++ b/tests/acceptance/applications/javascriptSourceSelectionCli.test.ts @@ -389,7 +389,7 @@ cliTest( expect(response.exitCode).toBe(1); expect(response.json).toMatchObject({ code: "unsupported_target", - details: { reason: "unsupported" }, + details: { path: archive, failure_kind: "unsupported" }, }); }, ); diff --git a/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts b/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts index ffeaccc94b..c455656f1f 100644 --- a/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts +++ b/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts @@ -275,8 +275,8 @@ cliTest( expect(output.json).toMatchObject({ code: "unsupported_target", details: { - reason: "malformed", - detail: expect.stringContaining("Keyed archive has no $top roots"), + failure_kind: "malformed", + reason: expect.stringContaining("Keyed archive has no $top roots"), }, }); const opened = await call("open_binary", { path }); diff --git a/tests/acceptance/applications/keyedArchiveXmlNumbers.test.ts b/tests/acceptance/applications/keyedArchiveXmlNumbers.test.ts index 436395f119..a2566814f5 100644 --- a/tests/acceptance/applications/keyedArchiveXmlNumbers.test.ts +++ b/tests/acceptance/applications/keyedArchiveXmlNumbers.test.ts @@ -162,8 +162,8 @@ cliTest( expect(output.json).toMatchObject({ code: "unsupported_target", details: { - reason: "malformed", - detail: expect.stringContaining(reason), + failure_kind: "malformed", + reason: expect.stringContaining(reason), }, }); expect((await call("open_binary", { path })).isError).not.toBe(true); @@ -175,8 +175,8 @@ cliTest( error: { code: "unsupported_target", details: { - reason: "malformed", - detail: expect.stringContaining(reason), + failure_kind: "malformed", + reason: expect.stringContaining(reason), }, }, }); diff --git a/tests/acceptance/artifactReaderLimitsCli.test.ts b/tests/acceptance/artifactReaderLimitsCli.test.ts index 4b45e53809..4cccc9a1fb 100644 --- a/tests/acceptance/artifactReaderLimitsCli.test.ts +++ b/tests/acceptance/artifactReaderLimitsCli.test.ts @@ -142,7 +142,7 @@ test("rejects malformed directory dimensions before suggesting a budget increase code: "unsupported_target", retryable: false, details: { - reason: "truncated", + path, failure_kind: "truncated", }, }); diff --git a/tests/acceptance/artifactZipCurrentDirectory.test.ts b/tests/acceptance/artifactZipCurrentDirectory.test.ts index 5c86784c56..734b639aaa 100644 --- a/tests/acceptance/artifactZipCurrentDirectory.test.ts +++ b/tests/acceptance/artifactZipCurrentDirectory.test.ts @@ -13,38 +13,6 @@ import { parseEvidence } from "../../src/domain/evidence.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; -cliTest( - "classifies a ZIP local-header offset beyond EOF as malformed input", - async ({ cli }) => { - const root = await createTestTempDirectory("rea-zip-beyond-eof-"); - const archivePath = join(root, "beyond-eof.zip"); - const writer = new ZipWriter(new Uint8ArrayWriter()); - await writer.add("member.bin", new TextReader("valid member bytes")); - const bytes = Buffer.from(await writer.close()); - const central = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02])); - if (central < 0) throw new Error("Expected a ZIP central directory"); - bytes.writeUInt32LE(bytes.length + 1024, central + 42); - await writeFile(archivePath, bytes); - - const result = await cli.run({ - arguments: ["inspect-artifact", archivePath, "--json"], - }); - expect(result.exitCode, result.stdout + result.stderr).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - category: "unsupported_target", - retryable: false, - details: { - operation: "inspect_artifact", - reason: "malformed", - failure_kind: "malformed", - format: "zip", - detail: expect.stringContaining("extends beyond"), - }, - }); - }, -); - cliTest( "inspects and extracts ZIP members with repeated current-directory prefixes", async ({ cli }) => { diff --git a/tests/acceptance/bunStandaloneCli.test.ts b/tests/acceptance/bunStandaloneCli.test.ts index 3757916cef..f7807791f9 100644 --- a/tests/acceptance/bunStandaloneCli.test.ts +++ b/tests/acceptance/bunStandaloneCli.test.ts @@ -104,8 +104,9 @@ cliTest( expect(await inspect()).toMatchObject({ code: "unsupported_target", retryable: false, + retry: "none", details: { - reason: "truncated", + path: source, failure_kind: "truncated", format: "bun-standalone", }, diff --git a/tests/acceptance/denoStandaloneCli.test.ts b/tests/acceptance/denoStandaloneCli.test.ts index 2c15d824dd..2ec64a068c 100644 --- a/tests/acceptance/denoStandaloneCli.test.ts +++ b/tests/acceptance/denoStandaloneCli.test.ts @@ -132,7 +132,7 @@ cliTest( expect(malformed.json).toMatchObject({ code: "unsupported_target", category: "unsupported_target", - details: { reason: "malformed" }, + details: { path, failure_kind: "malformed" }, }); }, ); diff --git a/tests/acceptance/firmwareContainersCli.test.ts b/tests/acceptance/firmwareContainersCli.test.ts index f487000c80..cc14fdadab 100644 --- a/tests/acceptance/firmwareContainersCli.test.ts +++ b/tests/acceptance/firmwareContainersCli.test.ts @@ -14,7 +14,6 @@ import { RP2040_FAMILY, RP2350_ARM_S_FAMILY, patternBytes, - uf2Block, uf2File, uf2Image, } from "../../src/domain/firmware/uf2.fixture.js"; @@ -179,40 +178,3 @@ cliTest( expect(await readdir(directory)).toEqual(["firmware.dfu"]); }, ); - -cliTest( - "refuses a conflicting UF2 rewrite through the CLI", - async ({ cli }) => { - const directory = await createTestTempDirectory("rea-uf2-conflict-cli-"); - const source = join(directory, "firmware.uf2"); - await writeFile( - source, - uf2File([ - ...uf2Image(RP2040_FAMILY, 0x1000_0000, RP2040_APP), - uf2Block({ - address: 0x1000_0000, - payload: [0xff], - blockNo: 0, - numBlocks: 1, - familyId: RP2040_FAMILY, - }), - ]), - ); - const result = await cli.run({ - arguments: ["inspect-artifact", source, "--json"], - }); - expect(result.exitCode).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - details: { - operation: "inspect_artifact", - reason: "malformed", - failure_kind: "malformed", - format: "uf2", - }, - }); - expect(result.stdout + result.stderr).toMatch( - /0xe48bff56.*RP2040.*0x10000000.*different values.*0-1.*0x01.*2.*0xff/iu, - ); - }, -); diff --git a/tests/acceptance/hexRecordsCli.test.ts b/tests/acceptance/hexRecordsCli.test.ts index 4c7da5482d..521d61de9a 100644 --- a/tests/acceptance/hexRecordsCli.test.ts +++ b/tests/acceptance/hexRecordsCli.test.ts @@ -142,25 +142,3 @@ cliTest.for(cases)( expect((await readFile(source)).equals(Buffer.from(text))).toBe(true); }, ); - -cliTest("rejects a malformed record through the CLI", async ({ cli }) => { - const directory = await createTestTempDirectory("rea-hex-invalid-cli-"); - const source = join(directory, "firmware.hex"); - await writeFile(source, INTEL_HEX_I32_GAP.replace("BEEFC3", "BEEFC4")); - const result = await cli.run({ - arguments: ["inspect-artifact", source, "--json"], - }); - expect(result.exitCode).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - details: { - operation: "inspect_artifact", - reason: "malformed", - failure_kind: "malformed", - format: "intel-hex", - }, - }); - expect(result.stdout + result.stderr).toMatch( - /line 4.*record type 00.*checksum 0xc4.*computed 0xc3/iu, - ); -}); diff --git a/tests/acceptance/iso9660Cli.test.ts b/tests/acceptance/iso9660Cli.test.ts index 6f27e3e499..d626598716 100644 --- a/tests/acceptance/iso9660Cli.test.ts +++ b/tests/acceptance/iso9660Cli.test.ts @@ -104,7 +104,16 @@ cliTest( }); expect(result.exitCode, result.stdout + result.stderr).toBe(1); expect(result.json).toMatchObject({ - details: { operation: "inspect_artifact", reason: "malformed" }, + code: "unsupported_target", + retryable: false, + retry: "none", + details: { + operation: "inspect_artifact", + path, + failure_kind: "malformed", + format: "iso9660", + field: "extent_location", + }, }); }, ); diff --git a/tests/acceptance/targetFailureConformance.test.ts b/tests/acceptance/targetFailureConformance.test.ts index 0e95925b83..0a0b72765b 100644 --- a/tests/acceptance/targetFailureConformance.test.ts +++ b/tests/acceptance/targetFailureConformance.test.ts @@ -19,7 +19,7 @@ const fileIdentity = (path: string, bytes: Buffer) => ({ // One generated suite for every registered reader: each case runs through // the CLI and the MCP adapter, and both must report the kind's contract and // the owner's facts. -for (const { operation, cases } of await loadTargetFailureReaders()) { +for (const { operation, session, cases } of await loadTargetFailureReaders()) { const command = operation.replaceAll("_", "-"); for (const testCase of cases) { cliTest( @@ -52,7 +52,14 @@ for (const { operation, cases } of await loadTargetFailureReaders()) { expect(result.json).not.toHaveProperty("details.format_failure"); const call = await cli.sharedMcpCall!(); - const response = await call(operation, { path, ...testCase.mcp }); + if (session === true) { + const opened = await call("open_binary", { path }); + expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); + } + const response = await call(operation, { + ...(session === true ? {} : { path }), + ...testCase.mcp, + }); // A target failure is an isError tool result carrying the projected // diagnostic as JSON text, never a JSON-RPC error. The transport // removes the private structured carrier before sending errors. diff --git a/tests/acceptance/webArtifactErrorProvenance.test.ts b/tests/acceptance/webArtifactErrorProvenance.test.ts index 2f6fba3dc2..1745c907eb 100644 --- a/tests/acceptance/webArtifactErrorProvenance.test.ts +++ b/tests/acceptance/webArtifactErrorProvenance.test.ts @@ -124,13 +124,20 @@ cliTest( reason === "malformed" ? "unsupported_target" : "artifact_operation_failed", - details: { - operation: selection.operation, - reason, - detail: expect.stringContaining( - reason === "malformed" ? fixture.sourcePath : "../outside.js", - ), - }, + // A malformed captured source is a target failure on that file; + // an escaping manifest path is an artifact operation refusal. + details: + reason === "malformed" + ? { + operation: selection.operation, + failure_kind: "malformed", + path: expect.stringContaining(fixture.sourcePath), + } + : { + operation: selection.operation, + reason, + detail: expect.stringContaining("../outside.js"), + }, }); } } diff --git a/tests/boundary/cli/artifactZstandardWindow.test.ts b/tests/boundary/cli/artifactZstandardWindow.test.ts index 0733430dbc..feefe72ab9 100644 --- a/tests/boundary/cli/artifactZstandardWindow.test.ts +++ b/tests/boundary/cli/artifactZstandardWindow.test.ts @@ -17,10 +17,9 @@ import { ZIP_ZSTANDARD_WINDOW_CEILING } from "../../../src/resources/ZipArtifact const expectRefusal = (diagnostic: unknown, large: boolean): void => { expect(diagnostic).toMatchObject({ code: large ? "partial" : "unsupported_target", - details: { - reason: large ? "limit" : "malformed", - ...(large ? { boundary: "memory", truncated: true } : {}), - }, + details: large + ? { reason: "limit", boundary: "memory", truncated: true } + : { failure_kind: "malformed", format: "zip" }, }); if (large) { expect(diagnostic).toMatchObject({ diff --git a/tests/boundary/cli/il2cppElfRelocations.test.ts b/tests/boundary/cli/il2cppElfRelocations.test.ts index 1d94191c33..72db17dbca 100644 --- a/tests/boundary/cli/il2cppElfRelocations.test.ts +++ b/tests/boundary/cli/il2cppElfRelocations.test.ts @@ -110,7 +110,7 @@ cliTest( }; expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ - code: "invalid_request", + code: "input_conflict", details: { partial_observation: { normalized_result: partial } }, }); const mcpRefused = await call("inspect_il2cpp_metadata", { @@ -120,7 +120,7 @@ cliTest( }); expect(mcpRefused.isError).toBe(true); const mcpError = parseMcpToolError(mcpRefused).error; - expect(mcpError.code).toBe("invalid_request"); + expect(mcpError.code).toBe("input_conflict"); const reference = z .object({ partial_observation: z.object({ diff --git a/tests/boundary/cli/unityFsCli.test.ts b/tests/boundary/cli/unityFsCli.test.ts index 420a2ff7e5..adaf418997 100644 --- a/tests/boundary/cli/unityFsCli.test.ts +++ b/tests/boundary/cli/unityFsCli.test.ts @@ -38,7 +38,7 @@ cliTest.for([ expect(result.exitCode, result.stderr).toBe(1); expect(result.json).toMatchObject({ code: "unsupported_target", - details: { reason: "malformed" }, + details: { path, failure_kind: "malformed", format: "unityfs" }, }); }, ); diff --git a/tests/boundary/filesystem/artifactInventorySnapshot.test.ts b/tests/boundary/filesystem/artifactInventorySnapshot.test.ts index 6860e8a2e0..029a01a690 100644 --- a/tests/boundary/filesystem/artifactInventorySnapshot.test.ts +++ b/tests/boundary/filesystem/artifactInventorySnapshot.test.ts @@ -87,7 +87,11 @@ describe("artifact inventory snapshot", () => { if (snapshotRoot === undefined) throw new Error("ASAR snapshot was not observed"); expect((await lstat(snapshotRoot)).isDirectory()).toBe(true); - const error = translateArtifactFailure("inventory_artifact", failure); + const error = translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + failure, + ); const observation = { kind: "artifact-inventory", inventory: { diff --git a/tests/boundary/filesystem/artifactZipIntegrity.test.ts b/tests/boundary/filesystem/artifactZipIntegrity.test.ts index ebe755d51c..87a693e8a4 100644 --- a/tests/boundary/filesystem/artifactZipIntegrity.test.ts +++ b/tests/boundary/filesystem/artifactZipIntegrity.test.ts @@ -110,9 +110,12 @@ it("does not publish a method-93 member with an incomplete final frame magic", a expect(result).toMatchObject({ ok: false, error: { - _tag: "ArtifactOperationError", - reason: "malformed", - detail: "ZIP archive is malformed: Invalid compressed data", + _tag: "AnalysisTargetFailureError", + failure: { + kind: "malformed", + format: "zip", + detail: "ZIP archive is malformed: Invalid compressed data", + }, }, }); expect(await readdir(root)).toEqual(["method93.zip"]); @@ -783,10 +786,10 @@ it("reports a member with an unsupported compression method as unavailable and k }); }); -/** Inventory one archive through the provider and expect a typed failure. */ +/** Inventory one archive through the provider and expect the ZIP owner's target failure. */ const expectInventoryFailure = async ( path: string, - reason: string, + kind: "malformed" | "truncated", detail: string | RegExp, ): Promise => { const target = await parseBinaryTarget(path); @@ -797,10 +800,13 @@ const expectInventoryFailure = async ( expect(result).toMatchObject({ ok: false, error: { - _tag: "ArtifactOperationError", - reason, - detail: - typeof detail === "string" ? detail : expect.stringMatching(detail), + _tag: "AnalysisTargetFailureError", + failure: { + kind, + format: "zip", + detail: + typeof detail === "string" ? detail : expect.stringMatching(detail), + }, }, }); }; diff --git a/tests/boundary/filesystem/asarHeaderAdmission.test.ts b/tests/boundary/filesystem/asarHeaderAdmission.test.ts index efae0b1779..30d617deef 100644 --- a/tests/boundary/filesystem/asarHeaderAdmission.test.ts +++ b/tests/boundary/filesystem/asarHeaderAdmission.test.ts @@ -184,7 +184,11 @@ it("names the default header admission budget and its setting when source select expect(wrapped.message).toBe(recovery); expect(wrapped.admission).toEqual(inventoryFailure.admission); const inventory = projectAnalysisError( - translateArtifactFailure("inventory_artifact", inventoryFailure), + translateArtifactFailure( + "inventory_artifact", + "/selected/artifact", + inventoryFailure, + ), ); expect(inventory).toMatchObject({ code: "partial", @@ -214,8 +218,13 @@ it("names the default header admission budget and its setting when source select }, }); expect( - projectAnalysisError(translateArtifactFailure("inspect_artifact", wrapped)) - .message, + projectAnalysisError( + translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + wrapped, + ), + ).message, ).toBe(recovery); const selected = await analyzeJavaScriptApplication({ diff --git a/tests/boundary/filesystem/desktopApplication.test.ts b/tests/boundary/filesystem/desktopApplication.test.ts index 149c2cb7ef..716419fa87 100644 --- a/tests/boundary/filesystem/desktopApplication.test.ts +++ b/tests/boundary/filesystem/desktopApplication.test.ts @@ -36,7 +36,10 @@ import { machoImage, } from "../../../src/artifacts/apple/MachoImage.fixture.js"; import { locateGodotPck } from "../../../src/artifacts/GodotPckLocation.js"; -import { ArtifactReaderFailure } from "../../../src/resources/ArtifactReader.js"; +import { + ArtifactReaderFailure, + malformedArtifact, +} from "../../../src/resources/ArtifactReader.js"; import { artifactFilePrimaryFacts } from "../../../src/resources/ArtifactFileOperation.js"; import { DesktopApplicationReader } from "../../../src/artifacts/DesktopApplicationReader.js"; import { inspectDesktopFile } from "../../../src/artifacts/DesktopFileInspection.js"; @@ -1175,10 +1178,7 @@ it.each( const primary = variant === "physical read" ? Object.assign(new Error("physical read denied"), { code: "EACCES" }) - : new ArtifactReaderFailure( - "malformed", - "invalid later format declaration", - ); + : malformedArtifact("pe", "invalid later format declaration"); const validation = Object.assign( new Error("final descriptor stat failed"), { code: "EIO" }, diff --git a/tests/boundary/filesystem/webModuleArtifacts.test.ts b/tests/boundary/filesystem/webModuleArtifacts.test.ts index fd3c1c14be..0f90c32d4f 100644 --- a/tests/boundary/filesystem/webModuleArtifacts.test.ts +++ b/tests/boundary/filesystem/webModuleArtifacts.test.ts @@ -122,9 +122,8 @@ describe("selected captured module artifact boundary", () => { code: "unsupported_target", details: { operation, - reason: "malformed", + path: expect.stringContaining(f.sourcePath), failure_kind: "malformed", - detail: expect.stringContaining(f.sourcePath), }, }); } diff --git a/tests/boundary/mcp/androidBootImageMcp.test.ts b/tests/boundary/mcp/androidBootImageMcp.test.ts index 8d08b223e1..cbfe32ea33 100644 --- a/tests/boundary/mcp/androidBootImageMcp.test.ts +++ b/tests/boundary/mcp/androidBootImageMcp.test.ts @@ -132,10 +132,8 @@ it("keeps Android parser refusal kinds and recovers through compiled MCP", async category: fixture.category, details: { operation: "inspect_artifact", - reason: fixture.kind, - ...("format" in fixture - ? { failure_kind: fixture.kind, format: fixture.format } - : {}), + failure_kind: fixture.kind, + format: "format" in fixture ? fixture.format : "android-boot-image", }, }); expect((await readFile(path)).equals(fixture.bytes)).toBe(true); diff --git a/tests/boundary/mcp/hexRecordsMcp.test.ts b/tests/boundary/mcp/hexRecordsMcp.test.ts index 203d03b803..97967e2acb 100644 --- a/tests/boundary/mcp/hexRecordsMcp.test.ts +++ b/tests/boundary/mcp/hexRecordsMcp.test.ts @@ -73,7 +73,8 @@ it("retains and extracts a high-address S28 region and projects a reserved-recor code: "unsupported_target", details: { operation: "inspect_artifact", - reason: "malformed", + path: invalidPath, + reason: expect.stringContaining("line 2: reserved record type S4"), failure_kind: "malformed", }, }); diff --git a/tests/boundary/mcp/javascriptSourceSelection.test.ts b/tests/boundary/mcp/javascriptSourceSelection.test.ts index 3fa733777f..10fa275d34 100644 --- a/tests/boundary/mcp/javascriptSourceSelection.test.ts +++ b/tests/boundary/mcp/javascriptSourceSelection.test.ts @@ -394,7 +394,7 @@ it("does not parse ASAR-looking JSON beyond the declared JSON extent through MCP expect(JSON.parse(message.text)).toMatchObject({ error: { code: "unsupported_target", - details: { reason: "unsupported" }, + details: { path: archive, failure_kind: "unsupported" }, }, }); await client.ping(); diff --git a/tests/boundary/process/artifactFileOutcomes.test.ts b/tests/boundary/process/artifactFileOutcomes.test.ts index 01e152b6ce..f84831651b 100644 --- a/tests/boundary/process/artifactFileOutcomes.test.ts +++ b/tests/boundary/process/artifactFileOutcomes.test.ts @@ -6,7 +6,10 @@ import { SigrokRecordingProvider } from "../../../src/signals/SigrokRecordingPro import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js"; import { SignalRecordingService } from "../../../src/application/signals/SignalRecordingService.js"; import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js"; -import { ArtifactReaderFailure } from "../../../src/resources/ArtifactReader.js"; +import { + ArtifactReaderFailure, + malformedArtifact, +} from "../../../src/resources/ArtifactReader.js"; import { withArtifactRegularFile } from "../../../src/resources/ArtifactFileOperation.js"; import { readStableArtifact } from "../../../src/resources/readStableArtifact.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; @@ -66,10 +69,7 @@ const physicalFailure = (failure: FileOutcomeControl["failure"]): Error => failure === "denied" ? Object.assign(new Error("controlled read denial"), { code: "EACCES" }) : failure === "format" - ? new ArtifactReaderFailure( - "malformed", - "controlled physical file failure", - ) + ? malformedArtifact("fixture", "controlled physical file failure") : failure === "limit" ? // The stable reader names the bound it refused, as production does. new ArtifactReaderFailure( diff --git a/tests/conformance/contracts/analysisErrorProjection.test.ts b/tests/conformance/contracts/analysisErrorProjection.test.ts index 663d817fdc..7ab0966c31 100644 --- a/tests/conformance/contracts/analysisErrorProjection.test.ts +++ b/tests/conformance/contracts/analysisErrorProjection.test.ts @@ -128,7 +128,6 @@ describe("analysis error projection contract", () => { ...( [ "cancelled", - "malformed", "integrity", "limit", "path", diff --git a/tests/fixtures/androidBootImage.ts b/tests/fixtures/androidBootImage.ts index 7258d4016c..3aefa0764d 100644 --- a/tests/fixtures/androidBootImage.ts +++ b/tests/fixtures/androidBootImage.ts @@ -406,6 +406,7 @@ export const androidBootImageRefusals = () => { kind: "unsupported", code: "unsupported_target", category: "unsupported_target", + format: "android-boot-image", }, { name: "vendor-version", @@ -413,6 +414,7 @@ export const androidBootImageRefusals = () => { kind: "unsupported", code: "unsupported_target", category: "unsupported_target", + format: "android-boot-image", }, { name: "short-image", diff --git a/tests/process-global/dmgCancellationReason.test.ts b/tests/process-global/dmgCancellationReason.test.ts index fe915445aa..a6f5fdb6b0 100644 --- a/tests/process-global/dmgCancellationReason.test.ts +++ b/tests/process-global/dmgCancellationReason.test.ts @@ -100,9 +100,13 @@ it.skipIf(process.platform !== "darwin").each([false, true])( throw new Error("Expected cancellation"); expect(failure.reason).toBe("cancelled"); expect(failure.cancellation?.reason).toBe(reason); - expect(translateArtifactFailure("inspect_artifact", failure).cause).toBe( - reason, - ); + expect( + translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + failure, + ).cause, + ).toBe(reason); expect(state.calls).toBe(preAborted ? 0 : 1); if (!preAborted) { expect(failure.cause).toBeInstanceOf(OwnedCommandFailure); diff --git a/tests/process-global/stableArtifactConsumers.test.ts b/tests/process-global/stableArtifactConsumers.test.ts index 56f3b0cd71..ee531c0a4f 100644 --- a/tests/process-global/stableArtifactConsumers.test.ts +++ b/tests/process-global/stableArtifactConsumers.test.ts @@ -1287,7 +1287,11 @@ it.each([ expect(marker.operationCause).toBe(raw); expect(projected.cleanupLease).toBe(failure.cleanupLease); expect(projected.cleanupLeases).toEqual([failure.cleanupLease]); - const error = translateArtifactFailure("inspect_artifact", projected); + const error = translateArtifactFailure( + "inspect_artifact", + "/selected/artifact", + projected, + ); expect(error.cleanupResources).toEqual([path]); expect(error.cleanupIncomplete).toBe(true); expect(error.partialObservation).toBeUndefined(); diff --git a/tests/support/targetFailure/readers/containers.ts b/tests/support/targetFailure/readers/containers.ts new file mode 100644 index 0000000000..c95cc566b5 --- /dev/null +++ b/tests/support/targetFailure/readers/containers.ts @@ -0,0 +1,80 @@ +import { zipArchive } from "../../../../src/domain/desktop/zipArchive.fixture.js"; +import { INTEL_HEX_I32_GAP } from "../../../../src/domain/firmware/hexRecords.fixture.js"; +import { + RP2040_FAMILY, + uf2Block, + uf2File, + uf2Image, +} from "../../../../src/domain/firmware/uf2.fixture.js"; +import { targetFailureReaders, type TargetFailureCase } from "../registry.js"; + +/** A ZIP whose central directory places its only member past the end of the file. */ +const zipMemberPastEof = (): Buffer => { + const bytes = zipArchive([ + { name: "member.bin", data: "valid member bytes" }, + ]); + const central = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02])); + if (central < 0) throw new Error("Expected a ZIP central directory"); + bytes.writeUInt32LE(bytes.length + 1024, central + 42); + return bytes; +}; + +/** Two UF2 blocks that write different bytes to the same RP2040 address. */ +const conflictingUf2 = (): Buffer => + Buffer.from( + uf2File([ + ...uf2Image(RP2040_FAMILY, 0x1000_0000, Buffer.from([0x01, 0x02])), + uf2Block({ + address: 0x1000_0000, + payload: [0xff], + blockNo: 0, + numBlocks: 1, + familyId: RP2040_FAMILY, + }), + ]), + ); + +const containerCases: readonly TargetFailureCase[] = [ + { + name: "zip-member-past-eof", + kind: "malformed", + bytes: zipMemberPastEof, + facts: { + format: "zip", + reason: + "ZIP archive is malformed: read at 1162 extends beyond the 138-byte archive", + }, + identity: false, + }, + { + name: "intel-hex-record-checksum", + kind: "malformed", + bytes: () => Buffer.from(INTEL_HEX_I32_GAP.replace("BEEFC3", "BEEFC4")), + facts: { + format: "intel-hex", + reason: + "Intel HEX is malformed: line 4: record type 00 checksum 0xc4 does not match computed 0xc3", + }, + identity: false, + }, + { + name: "uf2-conflicting-rewrite", + kind: "malformed", + bytes: conflictingUf2, + facts: { + format: "uf2", + reason: + "UF2 is malformed: family 0xe48bff56 (RP2040) address 0x10000000 is written with different values by block 0 (0x01) and block 1 (0xff)", + }, + identity: false, + }, +]; + +/** + * Container readers that inventory the selected file. Each refusal is the + * selected target's failure, whichever member the reader was reading. + * `inspect_artifact` reads the session's open target through MCP. + */ +export default targetFailureReaders([ + { operation: "inspect_artifact", session: true, cases: containerCases }, +]); diff --git a/tests/support/targetFailure/registry.ts b/tests/support/targetFailure/registry.ts index 6a3a9c7e67..e911d114c7 100644 --- a/tests/support/targetFailure/registry.ts +++ b/tests/support/targetFailure/registry.ts @@ -27,6 +27,11 @@ export interface TargetFailureCase { export interface TargetFailureReader { /** The MCP tool name; the CLI command is its kebab-case spelling. */ readonly operation: string; + /** + * The MCP tool reads the session's open target, so the suite opens the + * selected file with `open_binary` first. The CLI command takes the path. + */ + readonly session?: true; readonly cases: readonly TargetFailureCase[]; }