fix(json): preserve runtime limits across JSON file readers (#1350)
* fix(cli): preserve runtime JSON string-limit diagnostics * test(json): check actionable oversized Evidence recovery * fix(json): decode large UTF-8 inputs by character length * test(json): reject truncated UTF-8 after large input decode
This commit is contained in:
@@ -9,7 +9,10 @@ import {
|
||||
EvidenceIntegrityError,
|
||||
} from "../domain/evidenceErrors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
type AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { parseProcessCapture } from "../domain/process/processCaptureParsing.js";
|
||||
import {
|
||||
bufferedJsonParts,
|
||||
@@ -17,7 +20,10 @@ import {
|
||||
} from "../domain/jsonSerialization.js";
|
||||
import { readJsonFile, writeTextParts } from "./JsonFiles.js";
|
||||
|
||||
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
type EvidenceReadFailure =
|
||||
| EvidenceFileError
|
||||
| EvidenceIntegrityError
|
||||
| AnalysisResourceConstraintError;
|
||||
type EvidenceWriteFailure =
|
||||
| EvidenceFileError
|
||||
| EvidenceIntegrityError
|
||||
|
||||
@@ -12,8 +12,12 @@ import {
|
||||
import { basename, dirname, resolve } from "node:path";
|
||||
|
||||
import { EvidenceFileError } from "../domain/evidenceErrors.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { parseUtf8Json } from "./Utf8JsonInput.js";
|
||||
|
||||
/** Request control and its owning operation for an interruptible atomic write. */
|
||||
export interface TextWriteCancellation {
|
||||
@@ -27,7 +31,9 @@ type TextWriteResult<Failure = EvidenceFileError | AnalysisCancelledError> =
|
||||
/** Read JSON data from a regular file at the caller-supplied path. */
|
||||
export const readJsonFile = async (
|
||||
path: string,
|
||||
): Promise<Result<unknown, EvidenceFileError>> => {
|
||||
): Promise<
|
||||
Result<unknown, EvidenceFileError | AnalysisResourceConstraintError>
|
||||
> => {
|
||||
const requestedPath = resolve(path);
|
||||
try {
|
||||
const canonicalPath = await realpath(requestedPath);
|
||||
@@ -37,23 +43,18 @@ export const readJsonFile = async (
|
||||
new EvidenceFileError("read", "not-file", { path: requestedPath }),
|
||||
);
|
||||
const encoded = await readFile(canonicalPath);
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(
|
||||
new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
|
||||
encoded,
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
const decoded = parseUtf8Json(encoded, "read_evidence_file", requestedPath);
|
||||
if (!decoded.ok) {
|
||||
return err(
|
||||
new EvidenceFileError("read", "invalid-json", {
|
||||
cause,
|
||||
cause: decoded.cause,
|
||||
path: requestedPath,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return ok(decoded);
|
||||
return ok(decoded.value);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisResourceConstraintError) return err(cause);
|
||||
return err(
|
||||
new EvidenceFileError("read", missingOrIo(cause), {
|
||||
cause,
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { constants } from "node:buffer";
|
||||
|
||||
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
|
||||
import { safeParseJson, type SafeJsonParseResult } from "../domain/safeJson.js";
|
||||
|
||||
/** Decode JSON bytes without confusing a runtime string limit with malformed input. */
|
||||
export const parseUtf8Json = (
|
||||
bytes: Uint8Array,
|
||||
operation: string,
|
||||
path: string,
|
||||
boundary = "json-input",
|
||||
): SafeJsonParseResult => {
|
||||
const stringLimitFailure = (
|
||||
cause?: unknown,
|
||||
decodedUnits?: number,
|
||||
): AnalysisResourceConstraintError =>
|
||||
new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"JSON input exceeds the runtime's maximum decoded string length",
|
||||
{
|
||||
boundary,
|
||||
input_path: path,
|
||||
input_bytes: bytes.byteLength,
|
||||
max_string_code_units: constants.MAX_STRING_LENGTH,
|
||||
...(decodedUnits === undefined
|
||||
? {}
|
||||
: { decoded_string_code_units_at_least: decodedUnits }),
|
||||
},
|
||||
{
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
remediationAction:
|
||||
"Provide a smaller JSON document. For Evidence-based workflows, re-analyze a smaller selection of the original target and use its Evidence; splitting JSON text alone does not produce a valid workflow input.",
|
||||
},
|
||||
);
|
||||
let text: string;
|
||||
try {
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||
if (bytes.byteLength <= constants.MAX_STRING_LENGTH) {
|
||||
text = decoder.decode(bytes);
|
||||
} else {
|
||||
// Node 22's UTF-8 fast path bounds encoded bytes before decoding. Decode
|
||||
// large inputs in chunks so valid multibyte text is bounded by its actual
|
||||
// UTF-16 length. Streaming also preserves characters spanning chunks.
|
||||
const parts: string[] = [];
|
||||
let decodedUnits = 0;
|
||||
const append = (part: string): void => {
|
||||
decodedUnits += part.length;
|
||||
if (decodedUnits > constants.MAX_STRING_LENGTH)
|
||||
throw stringLimitFailure(undefined, decodedUnits);
|
||||
parts.push(part);
|
||||
};
|
||||
const chunkBytes = 1024 * 1024;
|
||||
for (let offset = 0; offset < bytes.byteLength; offset += chunkBytes)
|
||||
append(
|
||||
decoder.decode(bytes.subarray(offset, offset + chunkBytes), {
|
||||
stream: true,
|
||||
}),
|
||||
);
|
||||
append(decoder.decode());
|
||||
text = parts.join("");
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisResourceConstraintError) throw cause;
|
||||
const code =
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
if (code === "ERR_STRING_TOO_LONG") throw stringLimitFailure(cause);
|
||||
if (code !== "ERR_ENCODING_INVALID_ENCODED_DATA") throw cause;
|
||||
return {
|
||||
ok: false,
|
||||
error: "JSON input is not valid UTF-8",
|
||||
cause,
|
||||
};
|
||||
}
|
||||
return safeParseJson(text);
|
||||
};
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
EvidenceIntegrityError,
|
||||
} from "../../domain/evidenceErrors.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import type { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
|
||||
import { readJsonFile, writeTextFile } from "../JsonFiles.js";
|
||||
|
||||
type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
@@ -15,7 +16,9 @@ type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
/** Read and validate an analysis snapshot from the caller's path. */
|
||||
export const readAnalysisSnapshot = async (
|
||||
path: string,
|
||||
): Promise<Result<AnalysisSnapshot, SnapshotFailure>> => {
|
||||
): Promise<
|
||||
Result<AnalysisSnapshot, SnapshotFailure | AnalysisResourceConstraintError>
|
||||
> => {
|
||||
const loaded = await readJsonFile(path);
|
||||
if (!loaded.ok) return loaded;
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user