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
This commit is contained in:
morluto authored and GitHub committed 2026-11-10 05:11:20 -05:00
1 parent 55b6d2ca20
commit cb4e5cfbff
515 files changed
+21066 -3637

No files matched your search

+18 -16
View File
@@ -2,6 +2,7 @@ import { nodeCodecResult } from "../compression/NodeCodecResult.js";
import { inflateSync } from "node:zlib";
import { visit } from "jsonc-parser";
import { z } from "zod";
import { RUST_PRODUCER_DEFAULTS } from "../domain/rust/rustResourceLimits.js";
import {
cyclicDependencyIndices,
type RustAuditableMetadata,
@@ -9,16 +10,12 @@ import {
} from "../domain/rust/rustBinary.js";
import { jsonValueByteLength } from "../domain/jsonValueByteLength.js";
/** Selected-file admission limit shared with the stable artifact reader. */
export const RUST_BINARY_INPUT_BYTES = 256 * 1024 * 1024;
/** Compressed zlib stream limit. */
export const RUST_SECTION_BYTES = 1024 * 1024;
/** Inflated JSON may grow by at most this multiple of the compressed stream. */
export const RUST_INFLATE_RATIO = 64;
/** Absolute inflated JSON limit, applied together with the ratio. */
export const RUST_UNCOMPRESSED_BYTES = 8 * 1024 * 1024;
/** Complete normalized report limit. */
export const RUST_OUTPUT_BYTES = 8 * 1024 * 1024;
const JSON_DEPTH = 32;
const packageSchema = z.strictObject({
@@ -60,10 +57,6 @@ export type RustAuditableConstraint =
| {
readonly resource: "transport";
readonly reported_limits: { readonly maximum_output_bytes: number };
}
| {
readonly resource: "capacity";
readonly reported_limits: { readonly maximum_rustc_hashes: number };
};
/** Admission refused before retained output or graph expansion. */
@@ -83,7 +76,10 @@ export const readAuditableSection = (
sectionName: RustAuditableMetadata["section_name"],
fileOffset: number,
bytes: Buffer,
options: { readonly peFileAlignment?: number | undefined } = {},
options: {
readonly peFileAlignment?: number | undefined;
readonly maxOutputBytes?: number | undefined;
} = {},
): RustAuditableMetadata => {
if (bytes.length === 0)
throw new RustAuditableFormatFailure(
@@ -102,7 +98,10 @@ export const readAuditableSection = (
"Dependency section exceeds the 1 MiB compressed limit",
);
const inflated = inflateSection(bytes, options.peFileAlignment);
const document = parseDocument(inflated.bytes);
const document = parseDocument(
inflated.bytes,
options.maxOutputBytes ?? RUST_PRODUCER_DEFAULTS.output_bytes,
);
const packages = normalizePackages(document.packages);
const root = rootIndex(packages);
return {
@@ -207,7 +206,10 @@ const inflateFailure = (cause: unknown, maximum: number): Error => {
return cause instanceof Error ? cause : new Error(String(cause));
};
const parseDocument = (bytes: Buffer): z.infer<typeof documentSchema> => {
const parseDocument = (
bytes: Buffer,
maxOutputBytes: number,
): z.infer<typeof documentSchema> => {
let text: string;
try {
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
@@ -274,7 +276,7 @@ const parseDocument = (bytes: Buffer): z.infer<typeof documentSchema> => {
"Dependency JSON does not match the format schema",
{ cause: version.error },
);
admitGraphExpansion(value);
admitGraphExpansion(value, maxOutputBytes);
// One malformed package must fail before Zod retains an issue for every field.
rejectMalformedPackages(value);
const parsed = documentSchema.safeParse(value);
@@ -303,7 +305,7 @@ const MIN_EDGE_OUTPUT_BYTES = JSON.stringify({
from_index: 0,
to_index: 0,
}).length;
const admitGraphExpansion = (value: unknown): void => {
const admitGraphExpansion = (value: unknown, maxOutputBytes: number): void => {
if (
typeof value !== "object" ||
value === null ||
@@ -318,11 +320,11 @@ const admitGraphExpansion = (value: unknown): void => {
let edges = 0;
const admit = () => {
const edgeBytes = edges * MIN_EDGE_OUTPUT_BYTES + Math.max(0, edges - 1);
if (minimumBytes + edgeBytes > RUST_OUTPUT_BYTES)
if (minimumBytes + edgeBytes > maxOutputBytes)
throw new RustAuditableResourceFailure(
{
resource: "transport",
reported_limits: { maximum_output_bytes: RUST_OUTPUT_BYTES },
reported_limits: { maximum_output_bytes: maxOutputBytes },
},
"Dependency graph exceeds the complete report byte budget before expansion",
);
@@ -340,7 +342,7 @@ const admitGraphExpansion = (value: unknown): void => {
pkg.features.every((feature) => typeof feature === "string")
) {
const featureBudget =
RUST_OUTPUT_BYTES - minimumBytes - currentEdgeBytes() + 4;
maxOutputBytes - minimumBytes - currentEdgeBytes() + 4;
const featureBytes = jsonValueByteLength(
pkg.features as string[],
featureBudget,
+68 -23
View File
@@ -9,6 +9,8 @@ import type {
RustAuditableMetadata,
RustBinary,
} from "../domain/rust/rustBinary.js";
import { DEFAULT_RUSTC_HASH_LIMIT } from "../domain/rust/rustBinary.js";
import { RUST_PRODUCER_DEFAULTS } from "../domain/rust/rustResourceLimits.js";
import {
readAuditableSection,
RustAuditableFormatFailure,
@@ -17,8 +19,6 @@ import {
const RUSTC_PREFIX = Buffer.from("/rustc/");
const HASH_BYTES = 40;
/** One toolchain normally leaves one hash; a small cap bounds retained output. */
const MAX_RUSTC_HASHES = 64;
/** Container identity plus optional dependency metadata and inferred rustc commits. */
export interface RustBinaryImage {
@@ -32,7 +32,11 @@ export interface RustBinaryImage {
}
/** Read dependency metadata from container sections without executing the image. */
export const readRustBinaryImage = (bytes: Buffer): RustBinaryImage => {
export const readRustBinaryImage = (
bytes: Buffer,
maxRustcHashes = DEFAULT_RUSTC_HASH_LIMIT,
maxOutputBytes: number = RUST_PRODUCER_DEFAULTS.output_bytes,
): RustBinaryImage => {
const container = readContainer(bytes);
const dependency = dependencySection(container.format, container.sections);
return {
@@ -43,8 +47,8 @@ export const readRustBinaryImage = (bytes: Buffer): RustBinaryImage => {
auditable_metadata:
dependency === null
? null
: readDependency(bytes, container.format, dependency),
rustc_commit: rustcCommit(bytes, container),
: readDependency(bytes, container.format, dependency, maxOutputBytes),
rustc_commit: rustcCommit(bytes, container, maxRustcHashes, maxOutputBytes),
...(container.section_names_limitation === undefined
? {}
: { section_names_limitation: container.section_names_limitation }),
@@ -104,12 +108,14 @@ const readDependency = (
bytes: Buffer,
format: RustBinaryImage["format"],
section: ImageSection,
maxOutputBytes: number,
): RustAuditableMetadata =>
readAuditableSection(
format === "macho" ? "__DATA,.dep-v0" : ".dep-v0",
section.offset,
bytes.subarray(section.offset, section.offset + section.size),
{
maxOutputBytes,
peFileAlignment:
section.format === "pe" &&
section.virtual_size === 0 &&
@@ -123,9 +129,17 @@ const readDependency = (
const rustcCommit = (
bytes: Buffer,
container: BinaryContainer,
maxHashes: number,
maxOutputBytes: number,
): RustBinaryImage["rustc_commit"] => {
const hashes: { hash: string; file_offset: number }[] = [];
const seen = new Set<string>();
const retention: RustcPathRetention = {
hashes: [],
seen: new Set(),
maxHashes,
maxBytes: maxOutputBytes,
bytes: 2,
reason: undefined,
};
const sections = container.sections
.filter((section) => section.read_only)
.map(({ offset, size }) => ({ offset, size }));
@@ -137,11 +151,40 @@ const rustcCommit = (
: [];
// Overlapping section and ELF load ranges are scanned once, so total work
// stays bounded by the file size however many mappings reference a range.
for (const range of mergedReadOnlyFileRanges([...sections, ...loadRegions]))
collectHashes(bytes, range, seen, hashes);
return hashes.length === 0 ? null : { evidence_kind: "inferred", hashes };
for (const range of mergedReadOnlyFileRanges([...sections, ...loadRegions])) {
collectHashes(bytes, range, retention);
if (retention.reason !== undefined) break;
}
return retention.hashes.length === 0
? null
: {
evidence_kind: "inferred",
hashes: retention.hashes,
...(retention.reason !== undefined
? {
coverage: {
status: "partial" as const,
reason: retention.reason,
effective_limit:
retention.reason === "report_bytes"
? maxOutputBytes
: maxHashes,
},
}
: {}),
};
};
/** One owner for compiler-path uniqueness, retained output and exhaustion. */
interface RustcPathRetention {
readonly hashes: { hash: string; file_offset: number }[];
readonly seen: Set<string>;
readonly maxHashes: number;
readonly maxBytes: number;
bytes: number;
reason: "max_rustc_hashes" | "report_bytes" | undefined;
}
const mergedReadOnlyFileRanges = (
ranges: readonly { readonly offset: number; readonly size: number }[],
): { readonly offset: number; readonly end: number }[] => {
@@ -162,8 +205,7 @@ const mergedReadOnlyFileRanges = (
const collectHashes = (
bytes: Buffer,
range: { readonly offset: number; readonly end: number },
seen: Set<string>,
hashes: { hash: string; file_offset: number }[],
retention: RustcPathRetention,
): void => {
const region = bytes.subarray(range.offset, range.end);
let cursor = 0;
@@ -172,17 +214,20 @@ const collectHashes = (
if (at < 0) return;
const start = at + RUSTC_PREFIX.length;
const hash = hashAt(region, start);
if (hash !== null && !seen.has(hash)) {
if (seen.size >= MAX_RUSTC_HASHES)
throw new RustAuditableResourceFailure(
{
resource: "capacity",
reported_limits: { maximum_rustc_hashes: MAX_RUSTC_HASHES },
},
`Read-only data contains more than ${MAX_RUSTC_HASHES} distinct rustc commit paths.`,
);
seen.add(hash);
hashes.push({ hash, file_offset: range.offset + at });
if (hash !== null && !retention.seen.has(hash)) {
if (retention.seen.size >= retention.maxHashes) {
retention.reason = "max_rustc_hashes";
return;
}
const entry = { hash, file_offset: range.offset + at };
const entryBytes = Buffer.byteLength(JSON.stringify(entry)) + 1;
if (entryBytes > retention.maxBytes - retention.bytes) {
retention.reason = "report_bytes";
return;
}
retention.bytes += entryBytes;
retention.seen.add(hash);
retention.hashes.push(entry);
}
cursor = at + 1;
}
+120 -30
View File
@@ -44,12 +44,17 @@ import {
} from "./RustBinaryImage.js";
import { requireSelectedNativeImage } from "../native/metadata/MachoSliceSelection.js";
import {
RUST_BINARY_INPUT_BYTES,
RUST_OUTPUT_BYTES,
RustAuditableFormatFailure,
RustAuditableResourceFailure,
} from "./RustAuditableReader.js";
import {
resolveRustProducerLimits,
rustProducerLimitsSchema,
type RustProducerLimits,
} from "../domain/rust/rustResourceLimits.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
const OPERATION = "inspect_rust_binary";
/** Stable in-process dependency inspection without subprocesses, temporary files, or a Rust toolchain. */
@@ -75,11 +80,26 @@ export class RustBinaryProvider implements RustBinaryPort {
options?: ExecutionOptions,
): Promise<Result<RustBinary, AnalysisError>> {
let snapshot: StableArtifactSnapshot | undefined;
const selectedLimits = rustProducerLimitsSchema.safeParse(
input.producer_limits === undefined ? {} : input.producer_limits,
);
if (!selectedLimits.success)
return err(
analysisInputErrorFromIssues(
OPERATION,
selectedLimits.error.issues.map((issue) => ({
...issue,
path: ["producer_limits", ...issue.path],
})),
input,
),
);
const limits = resolveRustProducerLimits(selectedLimits.data);
try {
return await this.#resources.run(async () => {
snapshot = await readStableArtifact(
input.path,
RUST_BINARY_INPUT_BYTES,
limits.input_bytes,
options?.signal,
undefined,
this.#resources,
@@ -92,10 +112,14 @@ export class RustBinaryProvider implements RustBinaryPort {
input.architecture,
);
const image = inFile(
readRustBinaryImage(selected.bytes),
readRustBinaryImage(
selected.bytes,
input.max_rustc_hashes,
limits.output_bytes,
),
selected.fileOffset,
);
const report = {
const report: RustBinary = {
format: image.format,
architecture: image.architecture,
bits: image.bits,
@@ -110,12 +134,17 @@ export class RustBinaryProvider implements RustBinaryPort {
...(selected.selection === null
? {}
: { selected_slice: selected.selection }),
limitations: limitationsFor(image),
limitations: [
...limitationsFor(image),
`Selected producer_limits.input_bytes=${String(limits.input_bytes)} and output_bytes=${String(limits.output_bytes)} bytes; compressed/inflated dependency parser limits remain independent.`,
],
};
retainCompilerPathsWithinReport(report, limits.output_bytes);
if (
Buffer.byteLength(JSON.stringify(report), "utf8") > RUST_OUTPUT_BYTES
Buffer.byteLength(JSON.stringify(report), "utf8") >
limits.output_bytes
)
throw outputLimit(input.path);
throw outputLimit(input.path, limits.output_bytes);
const parsed = rustBinarySchema.safeParse(report);
if (!parsed.success)
throw new AnalysisOutputError(
@@ -127,7 +156,7 @@ export class RustBinaryProvider implements RustBinaryPort {
return ok(parsed.data);
});
} catch (cause: unknown) {
return err(failureFor(cause, input.path, snapshot));
return err(failureFor(cause, input.path, limits, snapshot));
}
}
}
@@ -157,18 +186,21 @@ const inFile = (image: RustBinaryImage, fileOffset: number): RustBinaryImage =>
},
};
const outputLimit = (path: string) =>
const outputLimit = (path: string, maxOutputBytes: number) =>
new AnalysisResourceConstraintError(
OPERATION,
"transport",
`Complete Rust metadata for ${path} exceeds the inline output budget; no partial success is returned.`,
{ maximum_output_bytes: RUST_OUTPUT_BYTES },
fixedAllowanceOptions("The Rust complete-report allowance", "report"),
{ maximum_output_bytes: maxOutputBytes },
{
retryable: false,
remediationAction: `Increase producer_limits.output_bytes above ${String(maxOutputBytes)} bytes on the next inspect_rust_binary call (CLI --producer-limits JSON); no restart is required. Input, dependency parser and transport limits remain independent. Repeating the unchanged request does not raise admission.`,
},
);
/** Resource-guard guidance delivered with every Rust inspection report. */
export const RUST_RESOURCE_GUARD_LIMITATION =
"Resource guards bound the selected file to 256 MiB, the compressed dependency stream to 1 MiB, inflated JSON to the smaller of 8 MiB and 64 times the consumed compressed-stream length, and the complete report to 8 MiB. Package and dependency counts are admitted against that output budget before schema cloning, graph objects, or reverse-edge allocation.";
"Default input and complete-report admission are 256 MiB and 8 MiB; producer_limits.input_bytes/output_bytes select larger or smaller values for the next call without restart. Independent parser guards bound the compressed dependency stream to 1 MiB and inflated JSON to the smaller of 8 MiB and 64 times the consumed compressed-stream length. Report admission applies before package schema cloning, graph objects, or reverse-edge allocation.";
const limitationsFor = (
image: ReturnType<typeof readRustBinaryImage>,
@@ -227,6 +259,14 @@ const rustcLimitation = (
return [
"No /rustc/<40-hex>/ path was found in read-only data, so a rustc commit hash is unknown.",
];
if (commit.coverage?.reason === "report_bytes")
return [
"Compiler-path retention exhausted the complete-report byte allowance; retained hashes are a prefix and compiler coverage is partial. Dependency observations are independent. Increase producer_limits.output_bytes on the next call (CLI --producer-limits JSON) to raise report admission; no restart is required. Increasing max_rustc_hashes alone does not raise it.",
];
if (commit.coverage?.status === "partial")
return [
`Compiler-path retention reached max_rustc_hashes=${String(commit.coverage.effective_limit)}; the listed hashes are a prefix and compiler coverage is partial. Increase max_rustc_hashes on the next inspect_rust_binary call (CLI --max-rustc-hashes) to retain more paths; no restart is required. Dependency observations are independent. The complete-report byte allowance still applies.`,
];
if (commit.hashes.length === 1)
return [
"The rustc commit hash is inferred from a /rustc/<40-hex>/ path in read-only data. It does not by itself prove which compiler produced the binary.",
@@ -236,9 +276,54 @@ const rustcLimitation = (
];
};
/** Optional inferred paths never displace independently observed dependency facts. */
const retainCompilerPathsWithinReport = (
report: RustBinary,
maxOutputBytes: number,
): void => {
const commit = report.rustc_commit;
if (
commit === null ||
Buffer.byteLength(JSON.stringify(report)) <= maxOutputBytes
)
return;
const limitation =
"Compiler paths were omitted to preserve dependency facts within the complete-report byte allowance; compiler-path coverage is partial. Increase producer_limits.output_bytes on the next call (CLI --producer-limits JSON); no restart is required. Increasing max_rustc_hashes alone does not raise this allowance.";
const baseline = {
...report,
rustc_commit: null,
limitations: [...report.limitations, limitation],
};
const empty = {
...commit,
hashes: [],
coverage: {
status: "partial" as const,
reason: "report_bytes" as const,
effective_limit: maxOutputBytes,
},
};
const available =
maxOutputBytes -
Buffer.byteLength(JSON.stringify({ ...baseline, rustc_commit: empty }));
let retainedBytes = 0;
let count = 0;
for (const hash of commit.hashes) {
const bytes =
Buffer.byteLength(JSON.stringify(hash)) + (count === 0 ? 0 : 1);
if (bytes > available - retainedBytes) break;
retainedBytes += bytes;
count++;
}
report.rustc_commit =
count === 0 ? null : { ...empty, hashes: commit.hashes.slice(0, count) };
report.limitations = baseline.limitations;
};
const failureForPrimary = (
facts: ArtifactFilePrimaryFacts,
path: string,
limits: RustProducerLimits,
): AnalysisError => {
const { cause, origin } = facts;
if (origin === "owned-or-classified" && cause instanceof AnalysisError)
@@ -251,18 +336,15 @@ const failureForPrimary = (
cause.constraint.reported_limits,
{
cause,
...fixedAllowanceOptions(
cause.constraint.resource === "capacity"
? "The rustc commit-path inventory"
: cause.constraint.resource === "transport"
? "The Rust complete-report allowance"
: "This Rust inspection allowance",
cause.constraint.resource === "capacity"
? "count"
: cause.constraint.resource === "transport"
? "report"
: "parser",
),
...(cause.constraint.resource === "transport"
? {
retryable: false,
remediationAction: `Increase producer_limits.output_bytes above ${String(limits.output_bytes)} bytes on the next call (CLI --producer-limits JSON); no restart is required. Compressed/inflated dependency parser and transport limits remain independent.`,
}
: fixedAllowanceOptions(
"This Rust dependency parser allowance",
"parser",
)),
},
);
if (cause instanceof RustAuditableFormatFailure)
@@ -277,15 +359,20 @@ const failureForPrimary = (
message: `Selected artifact ${path}: ${cause.message}`,
},
]);
return artifactFailure(facts, path);
return artifactFailure(facts, path, limits);
};
const failureFor = (
cause: unknown,
path: string,
limits: RustProducerLimits,
snapshot?: StableArtifactSnapshot,
): AnalysisError => {
const primary = failureForPrimary(artifactFilePrimaryFacts(cause), path);
const primary = failureForPrimary(
artifactFilePrimaryFacts(cause),
path,
limits,
);
return projectStableArtifactFailure(
cause,
primary,
@@ -299,13 +386,14 @@ const failureFor = (
const artifactFailure = (
facts: ArtifactFilePrimaryFacts,
path: string,
limits: RustProducerLimits,
): AnalysisError => {
const { cause, origin } = facts;
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure
)
return artifactReaderFailure(cause, path);
return artifactReaderFailure(cause, path, limits);
if (cause instanceof Error && "code" in cause) {
if (cause.code === "EACCES" || cause.code === "EPERM")
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
@@ -332,6 +420,7 @@ const artifactFailure = (
const artifactReaderFailure = (
cause: ArtifactReaderFailure,
path: string,
limits: RustProducerLimits,
): AnalysisError => {
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(OPERATION, path, cause.message, {
@@ -346,10 +435,11 @@ const artifactReaderFailure = (
OPERATION,
"file-size",
cause.message,
{ maximum_input_bytes: RUST_BINARY_INPUT_BYTES },
{ maximum_input_bytes: limits.input_bytes },
{
cause,
...fixedAllowanceOptions("the fixed Rust input allowance", "input"),
retryable: false,
remediationAction: `Increase producer_limits.input_bytes above ${String(limits.input_bytes)} bytes on the next inspect_rust_binary call (CLI --producer-limits JSON); no restart is required. Select the same complete artifact, without truncating its bytes. Report, dependency parser and host memory limits remain independent.`,
},
);
if (cause.reason === "path")