fix(io): consolidate managed snapshots and retain cleanup ownership

Reuse managed snapshot admission and hashing in sequential path comparisons, retaining caller paths and completed inspection Evidence on later failure. Preserve exact failed-close owners alongside typed read and cancellation failures, and retry them through caller-owned resource scopes. Require canonical Hopper lease identities, remove signed offset coercion, and repair stale setup cleanup expectations that failed CI.
This commit is contained in:
morluto
2026-10-12 14:46:37 +08:00
parent e9970855ba
commit 98d8470d36
16 changed files with 899 additions and 225 deletions
+1 -1
View File
@@ -135,7 +135,7 @@ const requireRange = (
);
};
const align4 = (value: number): number => (value + 3) & ~3;
const align4 = (value: number): number => Math.ceil(value / 4) * 4;
const readStreamName = (
bytes: Buffer,
+1 -1
View File
@@ -132,7 +132,7 @@ export const methodBody = (
"utf8",
);
const methodEnd = ilOffset + header.ilSize;
const sectionOffset = (methodEnd + 3) & ~3;
const sectionOffset = Math.ceil(methodEnd / 4) * 4;
const exceptionRegions =
header.format === "fat" && (header.flags & 8) !== 0
? validateExceptionRegionRanges(
+190
View File
@@ -0,0 +1,190 @@
import { createHash } from "node:crypto";
import type { Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js";
import { classifyBinaryTargetFilesystemFailure } from "../application/BinaryTargetResolver.js";
import { withRegularFile } from "../application/RegularFileRead.js";
import {
RegularFileCleanupFailure,
type RegularFileReadOptions,
} from "../application/RegularFileRead.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
// Managed static inspection retains the complete PE snapshot in memory.
export const MAX_MANAGED_SNAPSHOT_BYTES = 128 * 1024 * 1024;
interface ManagedSourceObservation {
readonly byteLength: number;
readonly sha256: string;
readonly bytes?: Buffer;
}
interface ManagedSnapshot extends ManagedSourceObservation {
readonly bytes: Buffer;
}
const managedSnapshotCapacityError = (
operation: string,
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(
operation,
"memory",
"Managed static inspection requires an eagerly retained PE snapshot within its input byte budget.",
{ max_snapshot_bytes: MAX_MANAGED_SNAPSHOT_BYTES },
);
export const readManagedSnapshot = async (
path: string,
operation: string,
options: RegularFileReadOptions = {},
): Promise<ManagedSnapshot> => {
return readManagedFile(
path,
operation,
async (handle, metadata) => {
const signal = options.signal;
if (metadata.size > MAX_MANAGED_SNAPSHOT_BYTES)
throw managedSnapshotCapacityError(operation);
const bytes = await readBoundedFileBytes(
handle,
MAX_MANAGED_SNAPSHOT_BYTES,
signal,
);
if (bytes === undefined) throw managedSnapshotCapacityError(operation);
signal?.throwIfAborted();
return {
byteLength: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes,
};
},
options,
);
};
export const hashManagedSource = async (
path: string,
operation: string,
options: RegularFileReadOptions = {},
): Promise<ManagedSourceObservation> =>
readManagedFile(
path,
operation,
async (handle, metadata) => {
const signal = options.signal;
if (metadata.size > MAX_MANAGED_SNAPSHOT_BYTES)
throw managedSnapshotCapacityError(operation);
const digest = createHash("sha256");
let byteLength = 0;
const stream = handle.createReadStream({
autoClose: false,
...(signal === undefined ? {} : { signal }),
});
for await (const chunk of stream) {
signal?.throwIfAborted();
if (!Buffer.isBuffer(chunk))
throw new TypeError("Managed source stream returned non-buffer data");
if (chunk.length > MAX_MANAGED_SNAPSHOT_BYTES - byteLength)
throw managedSnapshotCapacityError(operation);
byteLength += chunk.length;
digest.update(chunk);
}
return { byteLength, sha256: digest.digest("hex") };
},
options,
);
const readManagedFile = <Value>(
path: string,
operation: string,
read: (handle: FileHandle, metadata: Stats) => Promise<Value>,
options: RegularFileReadOptions,
): Promise<Value> =>
withRegularFile(path, read, options).catch((cause: unknown) => {
throw normalizeManagedReadFailure(cause, path, operation, options.signal);
});
/** Keep cleanup ownership and the original typed read failure at this boundary. */
const normalizeManagedReadFailure = (
cause: unknown,
fallbackPath: string,
operation: string,
signal?: AbortSignal,
): unknown => {
const cleanupError = managedCleanupError(
cause,
fallbackPath,
operation,
signal,
);
if (cleanupError !== undefined) return cleanupError;
return normalizeReadFailure(cause, fallbackPath, operation, signal);
};
/** Project cleanup failures owned by managed file reads or their shared scope. */
export const managedCleanupError = (
cause: unknown,
fallbackPath: string,
operation: string,
signal?: AbortSignal,
): AnalysisError | undefined => {
if (cause instanceof RegularFileCleanupFailure) {
const cleanup = new ProviderCleanupError(
MANAGED_STATIC_PROVIDER.id,
[cause.path],
{ reason: "A managed input file handle could not be closed" },
{ cause, operation },
);
const failure =
cause.outcome.kind === "failed"
? normalizeReadFailure(
cause.outcome.cause,
cause.path,
operation,
signal,
)
: undefined;
return failure instanceof AnalysisError
? analysisErrorWithCleanupFailure(failure, cleanup, operation)
: cleanup;
}
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return new ProviderCleanupError(
MANAGED_STATIC_PROVIDER.id,
cause.cleanup.resources.length > 0
? cause.cleanup.resources
: [fallbackPath],
{ reason: cause.cleanup.reason },
{ cause, operation },
);
return undefined;
};
const normalizeReadFailure = (
cause: unknown,
path: string,
operation: string,
signal?: AbortSignal,
): unknown =>
cause instanceof RegularFileChangedError
? new EvidenceIntegrityError(
`Managed source changed while ${operation} was reading ${path}.`,
{ cause },
)
: cause instanceof AnalysisError
? cause
: (classifyBinaryTargetFilesystemFailure(path, cause) ??
(signal?.aborted === true
? new AnalysisCancelledError(operation, { cause })
: cause));
+49 -96
View File
@@ -1,5 +1,3 @@
import { createHash } from "node:crypto";
import {
createAnalysisExecution,
type AnalysisClient,
@@ -9,6 +7,8 @@ import {
type ExecutionOptions,
type ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { managedStaticCapabilities } from "./ManagedStaticProviderMetadata.js";
import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js";
import {
@@ -22,10 +22,10 @@ import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type {
@@ -37,23 +37,12 @@ import { err, ok, type Result } from "../domain/result.js";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
import { openRegularFile } from "../filesystem/RegularFile.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
// This provider eagerly retains the full PE snapshot. Keep its input resource
// policy separate from decoded metadata/output capacity; it is not a PE format limit.
const MAX_MANAGED_SNAPSHOT_BYTES = 128 * 1024 * 1024;
const snapshotCapacityError = (
operation: string,
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(
operation,
"memory",
"Managed static inspection requires an eagerly retained PE snapshot within its input byte budget.",
{ max_snapshot_bytes: MAX_MANAGED_SNAPSHOT_BYTES },
);
import { RegularFileCleanupFailure } from "../application/RegularFileRead.js";
import {
hashManagedSource,
managedCleanupError,
readManagedSnapshot,
} from "./ManagedSnapshot.js";
/** Execution-free managed PE/CLI auxiliary provider. */
export class ManagedStaticProvider implements AnalysisProvider {
@@ -75,6 +64,7 @@ export class ManagedStaticProvider implements AnalysisProvider {
class ManagedStaticClient implements AnalysisClient {
#snapshotBytes: Buffer | undefined;
readonly #resources = new ArtifactResourceScope();
constructor(private readonly target: BinaryTarget) {}
@@ -107,16 +97,14 @@ class ManagedStaticClient implements AnalysisClient {
const snapshot = this.#snapshotBytes;
const observed =
snapshot === undefined
? await readManagedSnapshot(
this.target.path,
operation,
options?.signal,
)
: await hashManagedSource(
this.target.path,
operation,
options?.signal,
);
? await readManagedSnapshot(this.target.path, operation, {
signal: options?.signal,
resources: this.#resources,
})
: await hashManagedSource(this.target.path, operation, {
signal: options?.signal,
resources: this.#resources,
});
if (observed.sha256 !== this.target.sha256)
return err(
new EvidenceIntegrityError(
@@ -142,9 +130,11 @@ class ManagedStaticClient implements AnalysisClient {
}),
);
} catch (cause: unknown) {
if (isCleanupFailure(cause))
return err(this.#cleanupError(operation, cause));
if (cause instanceof AnalysisError) return err(cause);
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
if (cause instanceof AnalysisError) return err(cause);
return err(
new ProviderAdapterError(MANAGED_STATIC_PROVIDER.id, operation, {
cause,
@@ -153,74 +143,37 @@ class ManagedStaticClient implements AnalysisClient {
}
}
close(): Promise<Result<null, AnalysisError>> {
async close(): Promise<Result<null, AnalysisError>> {
this.#snapshotBytes = undefined;
return Promise.resolve(ok(null));
}
}
interface ManagedSourceObservation {
readonly byteLength: number;
readonly sha256: string;
readonly bytes?: Buffer;
}
const readManagedSnapshot = async (
path: string,
operation: string,
signal?: AbortSignal,
): Promise<ManagedSourceObservation> => {
const handle = await openRegularFile(path, { symlinks: "follow", signal });
try {
const metadata = await handle.stat();
if (metadata.size > MAX_MANAGED_SNAPSHOT_BYTES)
throw snapshotCapacityError(operation);
const bytes = await readBoundedFileBytes(
handle,
MAX_MANAGED_SNAPSHOT_BYTES,
signal,
);
if (bytes === undefined) throw snapshotCapacityError(operation);
signal?.throwIfAborted();
return {
byteLength: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes,
};
} finally {
await handle.close();
}
};
const hashManagedSource = async (
path: string,
operation: string,
signal?: AbortSignal,
): Promise<ManagedSourceObservation> => {
const handle = await openRegularFile(path, { symlinks: "follow", signal });
try {
if ((await handle.stat()).size > MAX_MANAGED_SNAPSHOT_BYTES)
throw snapshotCapacityError(operation);
const digest = createHash("sha256");
let byteLength = 0;
const stream = handle.createReadStream({
autoClose: false,
...(signal === undefined ? {} : { signal }),
});
for await (const chunk of stream) {
signal?.throwIfAborted();
if (!Buffer.isBuffer(chunk))
throw new TypeError("Managed source stream returned non-buffer data");
if (chunk.length > MAX_MANAGED_SNAPSHOT_BYTES - byteLength)
throw snapshotCapacityError(operation);
byteLength += chunk.length;
digest.update(chunk);
try {
await this.#resources.close();
return ok(null);
} catch (cause: unknown) {
return err(this.#cleanupError("close", cause));
}
return { byteLength, sha256: digest.digest("hex") };
} finally {
await handle.close();
}
};
#cleanupError(operation: string, cause: unknown): ProviderCleanupError {
const failure = managedCleanupError(cause, this.target.path, operation);
if (failure instanceof ProviderCleanupError) return failure;
const cleanup =
cause instanceof ArtifactReaderFailure ? cause.cleanup : undefined;
return new ProviderCleanupError(
MANAGED_STATIC_PROVIDER.id,
cleanup?.resources ?? [this.target.path],
{
reason:
cleanup?.reason ??
(cause instanceof Error ? cause.message : String(cause)),
},
{ cause, operation },
);
}
}
const isCleanupFailure = (cause: unknown): boolean =>
cause instanceof RegularFileCleanupFailure ||
(cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined);
const isManagedOperation = (
operation: AnalysisOperation,