Files
reverse-engineering-anything/src/application/JsonAuthenticationHeadroom.test.ts
T
morluto cb4e5cfbff feat(analysis): make resource budgets recoverable across CLI and MCP (#9706)
* refactor(analysis): centralize resource budgets and recovery facts

* feat(analysis): expose ASAR and Ghidra runtime admission controls

* feat(artifacts): expose reader admission and preserve limited recognition

* feat(javascript): expose recoverable semantic precision budgets

* feat(web): add recoverable source-map budgets and compact retained views

* feat(web): make historical capture decoding budgets recoverable

* fix(desktop): enforce selected view policies across capture and export

* feat(runtime): make Frida and LLDB retention budgets selectable

* feat(native): expose diagnostic budgets and preserve exhaustion causes

* feat(managed): expose recoverable snapshot and representation budgets

* feat(metadata): make Go and Rust inspection budgets recoverable

* feat(wasm): expose representation and producer admissions

* feat(evm): expose per-call worker resource budgets

* feat(android): make resource and string-pool omissions recoverable

* feat(producers): expose command and recorded-capture budgets

* docs(analysis): record recovery contracts and integrated validation

* fix(docs): link calibration oracle from published verification pages

* fix(docs): restore desktop task anchors and receipt links

* test(analysis): align fixtures with selectable budget contracts

* fix(analysis): remove source-location projector dependency cycle

* test(analysis): refresh budget recovery and verifier regressions

* test(analysis): preserve format and publication recovery expectations

* test(windows): align conformance with owned runtime admission

* fix(desktop): preserve selected alias kinds in exported state

* test(analysis): align provider fixtures with recoverable budgets

* test(desktop): validate emitted alias metadata structurally

* fix(ghidra): classify bounded Windows endpoint refusals

* test(cli): assert selectable artifact admission recovery

* fix(cli): preserve capture provenance in environment builds
2026-11-10 05:11:20 -05:00

237 lines
7.7 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
estimateJsonStorage,
estimateJsonArrayScalarEntry,
requireAuthenticationHeadroom,
} from "./JsonAuthenticationHeadroom.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
it("stops a bounded representation scan before visiting an over-budget tail", () => {
const value = {
first: "x".repeat(1_024),
get tail() {
throw new Error("The rejected representation must not read its tail");
},
};
const measured = estimateJsonStorage(value, {
maximumValueBytes: 512,
includeSerialized: false,
});
expect(measured.valueBytes).toBeGreaterThan(512);
});
it("checks escaped complete JSON against serialization capacity independently of heap", () => {
const value = {
normalized_result: { wat: '\0"\\😀'.repeat(30), imports: ["\0"] },
raw_result: null,
};
const encodedLength = JSON.stringify(value).length;
const options = {
operation: "inspect_wasm_artifact",
path: "/module.wasm",
description: "Complete WASM Evidence cannot be assembled",
availableBytes: Number.MAX_SAFE_INTEGER,
};
const rejected = requireAuthenticationHeadroom(value, {
...options,
serializedCodeUnitLimit: encodedLength - 1,
});
expect(rejected).toMatchObject({
ok: false,
error: {
retryable: false,
reportedLimits: {
serialized_json_code_units: encodedLength,
maximum_serialized_json_code_units: encodedLength - 1,
},
},
});
expect(
requireAuthenticationHeadroom(value, {
...options,
serializedCodeUnitLimit: encodedLength,
}),
).toEqual({ ok: true, value: undefined });
});
describe("JSON authentication headroom", () => {
it("measures source IDs without first constructing their array", () => {
const values = ["ev_123", null, 'escaped"\n😀'];
const empty = estimateJsonStorage({ evidence_links: [] });
const incremental = values.reduce((total, value, index) => {
const entry = estimateJsonArrayScalarEntry(value, index > 0);
return {
valueBytes: total.valueBytes + entry.valueBytes,
serializedUtf16Bytes:
total.serializedUtf16Bytes + entry.serializedUtf16Bytes,
};
}, empty);
expect(incremental).toEqual(
estimateJsonStorage({ evidence_links: values }),
);
});
it("accounts for a measured representation that has not yet been allocated", () => {
const value = { result: "small" };
const base = estimateJsonStorage(value);
const additional = { valueBytes: 8192, serializedUtf16Bytes: 2048 };
const total =
(base.valueBytes +
base.serializedUtf16Bytes +
additional.valueBytes +
additional.serializedUtf16Bytes) *
2;
const request = {
operation: "address_name",
path: "recovery",
description: "Cannot authenticate",
additional,
};
expect(
requireAuthenticationHeadroom(value, {
...request,
availableBytes: total - 1,
}),
).toMatchObject({
ok: false,
error: {
resource: "memory",
reportedLimits: { authentication_bytes: total },
},
});
expect(
requireAuthenticationHeadroom(value, {
...request,
availableBytes: total,
}),
).toEqual({ ok: true, value: undefined });
});
it("does not queue every row while deciding whether a wide report can fit", () => {
let pending = 0;
let peak = 0;
const rows: { admission_probe: boolean }[] = [];
for (let index = 0; index < 512; index++) {
const row = {
get admission_probe() {
pending--;
return true;
},
};
// Observe reading a row separately from examining its scalar. A width
// queue reads every row first; an iterator finishes each row before advancing.
Object.defineProperty(rows, index, {
enumerable: true,
get: () => {
peak = Math.max(peak, ++pending);
if (pending > 32)
throw new Error(
"Admission queued report rows before refusing their allocation",
);
return row;
},
});
}
const value = { rows };
const result = requireAuthenticationHeadroom(value, {
operation: "inspect_managed_members",
path: "/tmp/parent.json",
description: "Cannot authenticate",
availableBytes: 0,
});
expect(pending).toBe(0);
expect(peak).toBe(1);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
reportedLimits: {
serialized_json_utf16_bytes: JSON.stringify(value).length * 2,
},
},
});
});
it("reports parsed storage in authentication refusals", () => {
const text = "x".repeat(1000);
const projectedBytes: number[] = [];
for (const value of [text, { outer: [text, { inner: text }] }]) {
const result = requireAuthenticationHeadroom(value, {
operation: "inspect_analysis_view",
path: "/tmp/bundle.json",
description: "Cannot authenticate bundle",
availableBytes: 0,
});
if (result.ok) throw new Error("Expected authentication refusal");
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
const bytes = result.error.reportedLimits?.projected_value_bytes;
if (typeof bytes !== "number")
throw new Error("Expected parsed storage bytes in refusal diagnostics");
projectedBytes.push(bytes);
}
const [scalar, nested] = projectedBytes;
if (scalar === undefined || nested === undefined)
throw new Error("Expected scalar and nested refusal diagnostics");
expect(scalar).toBeGreaterThanOrEqual(2000);
expect(nested).toBeGreaterThan(2 * scalar);
});
it("refuses authentication when live heap headroom cannot hold its copies", () => {
const value = { normalized_result: "y".repeat(10_000) };
expect(
requireAuthenticationHeadroom(value, {
operation: "compare_source_to_bundle",
path: "/tmp/capture.json",
description: "Cannot authenticate graph",
availableBytes: 1024,
}),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
resource: "memory",
reportedLimits: {
input_path: "/tmp/capture.json",
available_heap_bytes: 1024,
},
},
});
expect(
requireAuthenticationHeadroom(value, {
operation: "compare_source_to_bundle",
path: "/tmp/capture.json",
description: "Cannot authenticate graph",
availableBytes: 1 << 30,
}),
).toEqual({ ok: true, value: undefined });
});
});
it.each([
["control characters", { text: "\u0000\u0001\b\t\n\f\r".repeat(2000) }],
[
"escaped keys",
{ ['\u0000\\"'.repeat(2000)]: [true, false, null, -0, 1e30] },
],
["surrogate boundaries", { text: "😀\ud800x\udfff".repeat(2000) }],
])("reserves actual escaped JSON storage for %s", (_label, value) => {
const allowance = 64 * 1024;
const result = requireAuthenticationHeadroom(value, {
operation: "inspect_analysis_view",
path: "/tmp/bundle.json",
description: "Cannot authenticate bundle",
availableBytes: allowance,
});
if (result.ok) throw new Error("Expected authentication refusal");
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
expect(result.error.reportedLimits?.projected_value_bytes).toBeLessThan(
allowance / 2,
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
reportedLimits: {
available_heap_bytes: allowance,
serialized_json_utf16_bytes: JSON.stringify(value).length * 2,
},
},
});
});