fix(native): retain signature snapshot cleanup ownership

Use the shared resource scope and private runtime root for signature snapshots. Retain failed file-handle/root cleanup, preserve primary failures alongside cleanup diagnostics, and wait for binding operations during client close before retrying owned resources.

Validate root cleanup failure, blocked retry, repeated client close and in-flight acquisition. Existing provider/MCP/CLI tests and the real Darwin codesign ancestor-swap case pass. Dedicated native file-handle close-failure injection remains unverified.
This commit is contained in:
morluto
2026-10-13 08:08:40 +08:00
parent 9a18251426
commit ebc22d99d6
5 changed files with 467 additions and 87 deletions
+195 -71
View File
@@ -1,7 +1,6 @@
import { createHash } from "node:crypto";
import { constants, type BigIntStats } from "node:fs";
import { lstat, mkdtemp, open, rm, type FileHandle } from "node:fs/promises";
import { tmpdir } from "node:os";
import { lstat, open, type FileHandle } from "node:fs/promises";
import { basename, join } from "node:path";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
@@ -9,10 +8,17 @@ import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { err, ok, type Result } from "../domain/result.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";
/** Binding of commands to the selected executable's registered content/version. */
@@ -68,41 +74,126 @@ const signatureReadFailure = (
/** Inspect a digest-verified private copy, releasing it on every exit path. */
export const withSignatureTarget = async <T>(
target: BinaryTarget,
resources: ArtifactResourceScope,
inspect: (
binding: SignatureTargetBinding,
) => Promise<Result<T, AnalysisError>>,
signal?: AbortSignal,
createRoot: () => Promise<Pick<PrivateRuntimeRoot, "path" | "close">> = () =>
PrivateRuntimeRoot.create({ prefix: "rea-signature-" }),
): Promise<Result<T, AnalysisError>> => {
let directory: string;
try {
signal?.throwIfAborted();
directory = await mkdtemp(join(tmpdir(), "rea-signature-"));
return await resources.run(async () => {
let root: Pick<PrivateRuntimeRoot, "path" | "close">;
try {
signal?.throwIfAborted();
root = await createRoot();
} catch (cause: unknown) {
return err(
signal?.aborted
? new AnalysisCancelledError("inspect_signature")
: snapshotFailure(target, "create", cause),
);
}
const owner = {
kind: "private-runtime-root" as const,
root,
resource: root.path,
};
let result: Result<T, AnalysisError>;
try {
const binding = await bindSignatureTarget(
target,
join(root.path, basename(target.path)),
resources,
signal,
);
if (!binding.ok) result = binding;
else {
try {
result = await inspect(binding.value);
} catch (cause: unknown) {
result = err(
cause instanceof AnalysisError
? cause
: new AnalysisOutputError(
"inspect_signature",
"Native output parsing failed",
{ cause },
),
);
}
}
} catch (cause: unknown) {
result = err(
cause instanceof AnalysisError
? cause
: signatureReadFailure(target, cause),
);
}
const cleanup = await resources.release(owner);
if (cleanup.kind === "failed")
return combineCleanupFailure(
target,
result,
[root.path],
cleanup.cause,
"cleanup",
);
return result;
});
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
const retained =
cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined
? cause.cleanup
: undefined;
if (retained !== undefined)
return combineCleanupFailure(
target,
err(
signal?.aborted
? new AnalysisCancelledError("inspect_signature")
: signatureReadFailure(target, cause),
),
retained.resources,
cause,
"retry",
);
return err(
signal?.aborted
? new AnalysisCancelledError("inspect_signature")
: snapshotFailure(target, "create", cause),
: signatureReadFailure(target, cause),
);
}
let result: Result<T, AnalysisError>;
let cleanup: Result<void, AnalysisError>;
try {
const binding = await bindSignatureTarget(
target,
join(directory, basename(target.path)),
signal,
);
result = binding.ok ? await inspect(binding.value) : binding;
} finally {
try {
await rm(directory, { recursive: true, force: true });
cleanup = ok(undefined);
} catch (cause: unknown) {
cleanup = err(snapshotFailure(target, "cleanup", cause));
}
}
// Cleanup cannot replace the operation's original actionable failure.
return result.ok && !cleanup.ok ? cleanup : result;
};
const combineCleanupFailure = <T>(
target: BinaryTarget,
primary: Result<T, AnalysisError>,
resources: readonly string[],
cause: unknown,
phase: string,
): Result<T, AnalysisError> => {
const cleanup = new ProviderCleanupError(
NATIVE_MACOS_PROVIDER_IDENTITY.id,
resources,
{
reason: cause instanceof Error ? cause.message : String(cause),
phase: `signature-snapshot-${phase}`,
path: target.path,
},
{ operation: "inspect_signature", cause },
);
return primary.ok
? err(cleanup)
: err(
analysisErrorWithCleanupFailure(
primary.error,
cleanup,
"inspect_signature",
),
);
};
const snapshotFailure = (
@@ -180,22 +271,28 @@ const copySignatureBytes = async (
const bindSignatureTarget = async (
target: BinaryTarget,
snapshotPath: string,
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<Result<SignatureTargetBinding, AnalysisError>> => {
try {
signal?.throwIfAborted();
const before = await lstat(target.path, { bigint: true });
signal?.throwIfAborted();
if (!before.isFile() || before.isSymbolicLink())
return changedTarget(
target,
`Signature target is no longer a regular file: ${target.path}`,
);
const file = await open(
target.path,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
let sourceOwner: OwnedFileHandle | undefined;
let snapshotOwner: OwnedFileHandle | undefined;
const perform = async (): Promise<
Result<SignatureTargetBinding, AnalysisError>
> => {
try {
signal?.throwIfAborted();
const before = await lstat(target.path, { bigint: true });
signal?.throwIfAborted();
if (!before.isFile() || before.isSymbolicLink())
return changedTarget(
target,
`Signature target is no longer a regular file: ${target.path}`,
);
const file = await open(
target.path,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
sourceOwner = new OwnedFileHandle(file);
const opened = await file.stat({ bigint: true });
signal?.throwIfAborted();
if (identity(opened) !== identity(before))
@@ -206,44 +303,71 @@ const bindSignatureTarget = async (
const snapshot = await snapshotIO(target, "create-file", () =>
open(snapshotPath, "wx", 0o600),
);
try {
const observed = await copySignatureBytes(
snapshotOwner = new OwnedFileHandle(snapshot);
const observed = await copySignatureBytes(
target,
{ file, stat: opened },
snapshot,
signal,
);
if (observed !== target.sha256)
return changedTarget(
target,
{ file, stat: opened },
snapshot,
signal,
`Signature target digest changed: ${target.path}; expected ${target.sha256}, observed ${observed}`,
);
if (observed !== target.sha256)
return changedTarget(
target,
`Signature target digest changed: ${target.path}; expected ${target.sha256}, observed ${observed}`,
);
const after = await file.stat({ bigint: true });
const current = await lstat(target.path, { bigint: true });
signal?.throwIfAborted();
if (
identity(after) !== identity(opened) ||
identity(current) !== identity(opened)
)
return changedTarget(
target,
`Signature target changed while establishing its version: ${target.path}`,
);
await snapshotIO(target, "seal", () => snapshot.chmod(0o400));
return ok({ identity: identity(opened), snapshotPath });
} finally {
await snapshotIO(target, "close", () => snapshot.close());
}
} finally {
await file.close();
const after = await file.stat({ bigint: true });
const current = await lstat(target.path, { bigint: true });
signal?.throwIfAborted();
if (
identity(after) !== identity(opened) ||
identity(current) !== identity(opened)
)
return changedTarget(
target,
`Signature target changed while establishing its version: ${target.path}`,
);
await snapshotIO(target, "seal", () => snapshot.chmod(0o400));
return ok({ identity: identity(opened), snapshotPath });
} catch (cause: unknown) {
return err(
signal?.aborted
? new AnalysisCancelledError("inspect_signature")
: signatureReadFailure(target, cause),
);
}
} catch (cause: unknown) {
return err(
signal?.aborted
? new AnalysisCancelledError("inspect_signature")
: signatureReadFailure(target, cause),
};
let result = await perform();
const cleanupFailures: {
readonly path: string;
readonly cause: unknown;
}[] = [];
for (const [owner, path] of [
[snapshotOwner, snapshotPath],
[sourceOwner, target.path],
] as const) {
if (owner === undefined) continue;
const cleanup = await resources.release({
kind: "file-handle",
handle: owner,
resource: path,
});
if (cleanup.kind === "failed")
cleanupFailures.push({ path, cause: cleanup.cause });
}
if (cleanupFailures.length > 0) {
const cause = new AggregateError(
cleanupFailures.map(({ cause: failure }) => failure),
"Signature snapshot file handles could not be closed",
);
result = combineCleanupFailure(
target,
result,
cleanupFailures.map(({ path }) => path),
cause,
"close",
);
}
return result;
};
/** Reject target drift across signature command captures. */