fix(io): retain cleanup ownership and honor cancellation

Keep failed JSON read handles in the existing server resource scope and fail admission until cleanup succeeds. Thread cancellation through every process CLI input read and replace timer-driven cancellation checks with a shared first-read gate.

Classify authenticated standalone Evidence as wrong-kind input while preserving tampered-record integrity failures and actionable messages across ledger, CLI, and MCP consumers. Record unrelated CS_RESTRICT process neighbors as unverified without weakening related-process ownership checks. Update stale ADB fixtures for the actual shell protocol.

Validated focused CLI, MCP, filesystem, ownership, and error projection tests; static, docs, and duplication gates pass. The host-level CS_RESTRICT load reproduction was not run. Refs #2050, #2035, #2064.
This commit is contained in:
morluto
2026-10-12 14:12:44 +08:00
parent e4532b5376
commit d8c76b6296
32 changed files with 1007 additions and 318 deletions
+30 -13
View File
@@ -1,3 +1,5 @@
import { resolve } from "node:path";
import {
createImmutableEvidenceBundle,
describeEvidenceBundleFailure,
@@ -37,13 +39,15 @@ type EvidenceWriteFailure =
export const readEvidenceBundle = (
path: string,
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
readBundle(path, parseEvidenceBundle, signal);
readBundle(path, parseEvidenceBundle, signal, resources);
/** Read an authenticated immutable snapshot for a subsequent session import. */
export const readImmutableEvidenceBundle = (
path: string,
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
readBundle(
path,
@@ -52,26 +56,30 @@ export const readImmutableEvidenceBundle = (
return createImmutableEvidenceBundle(bundle.records, bundle.unknowns);
},
signal,
resources,
);
const readBundle = async (
path: string,
parseBundle: (input: unknown) => EvidenceBundle,
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
if (signal?.aborted)
return err(new AnalysisCancelledError("import_evidence_bundle"));
const loaded = await readJsonFile(path, signal).catch((cause: unknown) => {
// A failed close transfers a live handle owner; preserve that failure.
if (
signal?.aborted === true &&
!(cause instanceof RegularFileCleanupFailure)
)
return err(
new AnalysisCancelledError("import_evidence_bundle", { cause }),
);
throw cause;
});
const loaded = await readJsonFile(path, signal, resources).catch(
(cause: unknown) => {
// A failed close transfers a live handle owner; preserve that failure.
if (
signal?.aborted === true &&
!(cause instanceof RegularFileCleanupFailure)
)
return err(
new AnalysisCancelledError("import_evidence_bundle", { cause }),
);
throw cause;
},
);
if (!loaded.ok) return loaded;
if (signal?.aborted)
return err(new AnalysisCancelledError("import_evidence_bundle"));
@@ -79,10 +87,19 @@ const readBundle = async (
try {
bundle = parseBundle(loaded.value);
} catch (cause: unknown) {
const failure = describeEvidenceBundleFailure(loaded.value, cause);
if (failure.kind === "single-record")
return err(
new EvidenceFileError("read", "wrong-kind", {
path: resolve(path),
cause,
userMessage: failure.message,
}),
);
return err(
new EvidenceIntegrityError("Evidence bundle validation failed", {
cause,
userMessage: describeEvidenceBundleFailure(loaded.value, cause),
userMessage: failure.message,
}),
);
}
+13 -2
View File
@@ -24,6 +24,7 @@ import {
type JsonObjectMemberReader,
} from "./JsonInputFile.js";
import { NonRegularFileReadError } from "../filesystem/RegularFile.js";
import { RegularFileCleanupFailure } from "./RegularFileRead.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
@@ -42,12 +43,14 @@ type TextWriteResult<Failure = EvidenceFileError | AnalysisCancelledError> =
export const readJsonFile = async (
path: string,
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<
Result<unknown, EvidenceFileError | AnalysisResourceConstraintError>
> =>
readJsonFileInput(
path,
(selected) => readJsonInputFile(selected, "read_evidence_file", signal),
(selected) =>
readJsonInputFile(selected, "read_evidence_file", signal, resources),
signal,
);
@@ -56,6 +59,7 @@ export const readJsonObjectMembersFile = (
path: string,
scans: readonly ReadonlyMap<string, JsonObjectMemberReader>[],
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<
Result<
void,
@@ -65,7 +69,13 @@ export const readJsonObjectMembersFile = (
readJsonFileInput(
path,
(selected) =>
readJsonObjectFile(selected, "read_evidence_file", scans, signal),
readJsonObjectFile(
selected,
"read_evidence_file",
scans,
signal,
resources,
),
signal,
);
@@ -103,6 +113,7 @@ const readJsonFileInput = async <Value>(
}
return ok(decoded.value);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
if (cause instanceof AnalysisResourceConstraintError) return err(cause);
if (signal?.aborted === true) throw cause;
return err(
+11 -2
View File
@@ -11,6 +11,7 @@ import streamValues from "stream-json/streamers/stream-values.js";
import streamArray from "stream-json/streamers/stream-array.js";
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { withRegularFile } from "./RegularFileRead.js";
import {
JSON_BYTE_ORDER_MARK_MESSAGE,
@@ -55,6 +56,7 @@ export const readJsonObjectFile = (
operation: string,
scans: readonly ReadonlyMap<string, JsonObjectMemberReader>[],
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<Result<void, JsonInputFileFailure>> =>
withRegularFile(
path,
@@ -188,7 +190,10 @@ export const readJsonObjectFile = (
throw cause;
}
},
{ signal },
{
signal,
...(resources === undefined ? {} : { resources }),
},
);
const memberConsumer = (
@@ -236,6 +241,7 @@ export const readJsonInputFile = (
path: string,
operation: string,
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<Result<unknown, JsonInputFileFailure>> =>
withRegularFile(
path,
@@ -294,7 +300,10 @@ export const readJsonInputFile = (
throw cause;
}
},
{ signal },
{
signal,
...(resources === undefined ? {} : { resources }),
},
);
const jsonReadFailure = (
+6 -4
View File
@@ -95,7 +95,8 @@ const withRegularFileOwned = async <Value>(
cause.cleanupCause,
);
if (options.resources === undefined) throw failure;
await retryRegularFileCleanup(failure, options.resources);
const retry = await retryRegularFileCleanup(failure, options.resources);
if (retry.cleanup !== undefined) throw failure;
throw cause.cause;
}
const owner = new OwnedFileHandle(handle);
@@ -128,9 +129,10 @@ const withRegularFileOwned = async <Value>(
cleanupCause,
);
if (options.resources === undefined) throw failure;
const cleanup = await retryRegularFileCleanup(failure, options.resources);
if (cleanup.outcome.kind === "failed") throw cleanup.outcome.cause;
return cleanup.outcome.value;
const retry = await retryRegularFileCleanup(failure, options.resources);
if (retry.cleanup !== undefined) throw failure;
if (retry.outcome.kind === "failed") throw retry.outcome.cause;
return retry.outcome.value;
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.value;
@@ -8,6 +8,7 @@ import {
} from "../../domain/evidenceErrors.js";
import { NoBinaryOpenError } from "../../domain/configurationErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { rebindEvidenceSubjectTargetPath } from "../../domain/evidence.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
@@ -190,7 +191,7 @@ export class AnalysisSnapshotCache {
| undefined,
mergeEvidence: (
bundle: EvidenceBundle,
) => Result<number, EvidenceIntegrityError>,
) => Result<number, EvidenceIntegrityError | AnalysisInputError>,
): Result<number, AnalysisError> {
let validated: AnalysisSnapshot;
try {
@@ -15,6 +15,7 @@ import { err, ok, type Result } from "../../domain/result.js";
import type { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { readJsonObjectMembersFile, writeTextFile } from "../JsonFiles.js";
import { RegularFileCleanupFailure } from "../RegularFileRead.js";
import type { JsonObjectMemberReader } from "../JsonInputFile.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
@@ -24,6 +25,7 @@ type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
export const readAnalysisSnapshot = async (
path: string,
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<
Result<
AnalysisSnapshot,
@@ -61,6 +63,7 @@ export const readAnalysisSnapshot = async (
metadata,
],
signal,
resources,
);
if (!loaded.ok) return loaded;
signal?.throwIfAborted();
@@ -74,6 +77,7 @@ export const readAnalysisSnapshot = async (
signal?.throwIfAborted();
return ok(snapshot);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
if (signal?.aborted === true)
return err(new AnalysisCancelledError("read_evidence_file", { cause }));
return err(
@@ -11,6 +11,7 @@ import {
AnalysisSnapshotMismatchError,
} from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
@@ -129,7 +130,7 @@ export abstract class BinarySessionRecords {
importEvidenceBundle(
bundle: unknown,
): Result<number, EvidenceIntegrityError> {
): Result<number, EvidenceIntegrityError | AnalysisInputError> {
const imported = this.#records.mergeEvidenceBundle(bundle);
if (!imported.ok) return imported;
if (imported.value.metadataChanged) this.invalidateSnapshot();
@@ -4,6 +4,7 @@ import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
import { createEvidence } from "../../domain/evidence.js";
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
import { recordUnknownInputSchema } from "../../domain/residualUnknown.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { EvidenceLedger } from "./EvidenceLedger.js";
const TARGET: BinaryTarget = {
@@ -234,6 +235,32 @@ describe("evidence ledger metadata imports", () => {
});
describe("evidence bundle imports", () => {
it("classifies an authenticated Evidence record as the wrong import kind", () => {
const record = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
});
const result = new EvidenceLedger().import(record);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
userMessage: expect.stringContaining(
`this JSON is one Evidence record (${record.evidence_id})`,
),
},
});
if (result.ok) throw new Error("Expected a wrong-kind import failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
category: "invalid_input",
message: expect.stringContaining(
`this JSON is one Evidence record (${record.evidence_id})`,
),
});
});
it("rejects conflicting duplicate IDs without mutating the ledger", () => {
const ledger = new EvidenceLedger();
const first = createEvidence(TARGET, PROVIDER, {
@@ -8,6 +8,7 @@ import {
validateResidualUnknownAddition,
type EvidenceBundle,
} from "../../domain/evidenceBundle.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import {
@@ -37,7 +38,10 @@ export interface EvidenceImportDelta {
readonly metadataChanged: boolean;
}
type ImportResult = Result<EvidenceImportDelta, EvidenceLedgerFailure>;
type ImportResult = Result<
EvidenceImportDelta,
EvidenceLedgerFailure | AnalysisInputError
>;
/** Session-owned set of immutable evidence records. */
export class EvidenceLedger {
@@ -76,10 +80,18 @@ export class EvidenceLedger {
try {
bundle = parseEvidenceBundle(input);
} catch (cause: unknown) {
const failure = describeEvidenceBundleFailure(input, cause);
if (failure.kind === "single-record")
return err(
new AnalysisInputError("import_evidence_bundle", {
cause,
userMessage: failure.message,
}),
);
return err(
new EvidenceIntegrityError("Evidence bundle validation failed", {
cause,
userMessage: describeEvidenceBundleFailure(input, cause),
userMessage: failure.message,
}),
);
}
@@ -2,6 +2,7 @@ import type { Evidence } from "../../domain/evidence.js";
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
@@ -67,5 +68,7 @@ export interface InvestigationRecordPort
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort {
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
importEvidenceBundle(
bundle: unknown,
): Result<number, EvidenceIntegrityError | AnalysisInputError>;
}
@@ -3,6 +3,7 @@ import type { Evidence } from "../../domain/evidence.js";
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
import type {
RecordUnknownInput,
@@ -65,7 +66,7 @@ export class InvestigationRecords
/** Atomically merge a bundle and report changes for the owner's post-commit observers. */
mergeEvidenceBundle(
bundle: unknown,
): Result<EvidenceImportDelta, EvidenceIntegrityError> {
): Result<EvidenceImportDelta, EvidenceIntegrityError | AnalysisInputError> {
return this.#evidence.import(bundle);
}
+35 -7
View File
@@ -1,7 +1,10 @@
import { z } from "zod";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisInputError,
} from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { createEvidence, parseEvidence } from "../../domain/evidence.js";
import { describeValidationFailure } from "../../domain/evidenceBundle.js";
@@ -23,6 +26,7 @@ import {
} from "../../domain/process/processEvidenceProvider.js";
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
import { readJsonFile } from "../JsonFiles.js";
import { RegularFileCleanupFailure } from "../RegularFileRead.js";
/** Safe process-command failure returned to the CLI adapter. */
export interface ProcessCliErrorOutput {
@@ -51,7 +55,7 @@ export const captureProcessScenarioFile = async (
signal?: AbortSignal,
) => {
try {
const input = await readJson(path);
const input = await readJson(path, "capture_process_scenario", signal);
const parsed = processScenarioSchema.safeParse(input);
if (!parsed.success)
throw analysisInputErrorFromIssues(
@@ -86,6 +90,7 @@ export const captureProcessScenarioFile = async (
if (!captured.ok) return cliAnalysisError(captured.error);
return createProcessCaptureEvidence(parsed.data, captured.value);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
return projectProcessCliError(cause);
}
};
@@ -95,14 +100,23 @@ export const compareProcessEvidenceFiles = async (
leftPath: string,
rightPath: string,
traceSpecPath?: string,
signal?: AbortSignal,
) => {
try {
const left = parseCaptureEvidence(await readJson(leftPath), "left");
const right = parseCaptureEvidence(await readJson(rightPath), "right");
const left = parseCaptureEvidence(
await readJson(leftPath, "compare_process_captures", signal),
"left",
);
const right = parseCaptureEvidence(
await readJson(rightPath, "compare_process_captures", signal),
"right",
);
const traceSpecification =
traceSpecPath === undefined
? undefined
: parseTraceSpecification(await readJson(traceSpecPath));
: parseTraceSpecification(
await readJson(traceSpecPath, "compare_process_captures", signal),
);
const comparison =
traceSpecification === undefined
? compareProcessCaptures(left.capture, right.capture)
@@ -129,6 +143,7 @@ export const compareProcessEvidenceFiles = async (
evidenceLinks: [left.id, right.id],
});
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
return projectProcessCliError(cause);
}
};
@@ -194,8 +209,21 @@ const invalidCaptureEvidence = (cause: unknown): ProcessCliFailure =>
`Capture evidence is malformed (${describeValidationFailure(cause)}). Create new capture evidence, then try again.`,
);
const readJson = async (path: string): Promise<unknown> => {
const loaded = await readJsonFile(path);
const readJson = async (
path: string,
operation: "capture_process_scenario" | "compare_process_captures",
signal?: AbortSignal,
): Promise<unknown> => {
if (signal?.aborted) throw new AnalysisCancelledError(operation);
const loaded = await readJsonFile(path, signal).catch((cause: unknown) => {
if (
signal?.aborted === true &&
!(cause instanceof RegularFileCleanupFailure)
)
throw new AnalysisCancelledError(operation, { cause });
throw cause;
});
if (signal?.aborted) throw new AnalysisCancelledError(operation);
if (loaded.ok) return loaded.value;
if (loaded.error._tag !== "EvidenceFileError") throw loaded.error;
const detail = describeValidationFailure(loaded.error.cause);