mirror of
https://github.com/morluto/rea.git
synced 2026-12-05 22:41:36 +00:00
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:
1 parent
55b6d2ca20
commit
cb4e5cfbff
515 files changed
+21066
-3637
No files matched your search
@@ -75,6 +75,10 @@ it("keeps accepted operations and their typed provider views stable across concu
|
||||
const pending = store.run(async () => {
|
||||
await barrier;
|
||||
expect(asar.maximumBytes).toBe(16777216);
|
||||
expect(asar.listing?.maximumBytes).toBe(67108864);
|
||||
expect(live.ghidraValueFlowMaxOperations).toBe(3000);
|
||||
expect(live.ghidraValueFlowMaxInputsPerOperation).toBe(64);
|
||||
expect(live.ghidraValueFlowMaxEdges).toBe(12000);
|
||||
expect(live.ghidraStartupTimeoutMs).toBe(330000);
|
||||
expect(live.regexMatchingDeadline.deadlineMs).toBe(5000);
|
||||
expect(store.read().revision).toBe(0);
|
||||
@@ -83,6 +87,18 @@ it("keeps accepted operations and their typed provider views stable across concu
|
||||
const changed = store.update({
|
||||
changes: [
|
||||
{ setting: "asar.max_header_bytes", action: "set", value: 33554432 },
|
||||
{ setting: "asar.max_listing_bytes", action: "set", value: 134217728 },
|
||||
{
|
||||
setting: "ghidra.value_flow_max_operations",
|
||||
action: "set",
|
||||
value: 6000,
|
||||
},
|
||||
{
|
||||
setting: "ghidra.value_flow_max_inputs_per_operation",
|
||||
action: "set",
|
||||
value: 128,
|
||||
},
|
||||
{ setting: "ghidra.value_flow_max_edges", action: "set", value: 24000 },
|
||||
{ setting: "ghidra.startup_timeout_ms", action: "set", value: 999999 },
|
||||
{ setting: "regex.matching_deadline_ms", action: "set", value: 10000 },
|
||||
],
|
||||
@@ -95,17 +111,25 @@ it("keeps accepted operations and their typed provider views stable across concu
|
||||
await pending;
|
||||
store.run(() => {
|
||||
expect(asar.maximumBytes).toBe(33554432);
|
||||
expect(asar.listing?.maximumBytes).toBe(134217728);
|
||||
expect(live.ghidraValueFlowMaxOperations).toBe(6000);
|
||||
expect(live.ghidraValueFlowMaxInputsPerOperation).toBe(128);
|
||||
expect(live.ghidraValueFlowMaxEdges).toBe(24000);
|
||||
expect(live.ghidraStartupTimeoutMs).toBe(999999);
|
||||
expect(live.regexMatchingDeadline.deadlineMs).toBe(10000);
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes shared provider controls and preserves the explicit unbounded decompile value", () => {
|
||||
const environment = { REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS: "7" };
|
||||
const environment = {
|
||||
REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS: "7",
|
||||
REA_GHIDRA_DECOMPILE_MAX_PAYLOAD_MIB: "64",
|
||||
};
|
||||
const store = new AnalysisSettings(environment);
|
||||
const parsed = parseConfig(environment);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const config = runtimeAnalysisConfig(parsed.value, store.read);
|
||||
expect(config.ghidraDecompileMaxPayloadMiB).toBe(64);
|
||||
expect(
|
||||
store
|
||||
.inspect({ provider: "ghidra", operation: "search_strings" })
|
||||
@@ -120,7 +144,7 @@ it("exposes shared provider controls and preserves the explicit unbounded decomp
|
||||
store
|
||||
.inspect({ operation: "inventory_artifact" })
|
||||
.settings.map(({ setting }) => setting),
|
||||
).toEqual(["asar.max_header_bytes"]);
|
||||
).toEqual(["asar.max_listing_bytes", "asar.max_header_bytes"]);
|
||||
expect(
|
||||
store.update({
|
||||
changes: [
|
||||
@@ -129,16 +153,27 @@ it("exposes shared provider controls and preserves the explicit unbounded decomp
|
||||
action: "set",
|
||||
value: null,
|
||||
},
|
||||
{
|
||||
setting: "ghidra.decompile_max_payload_mib",
|
||||
action: "set",
|
||||
value: null,
|
||||
},
|
||||
],
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
expect(config.ghidraDecompileTimeoutSeconds).toBeUndefined();
|
||||
expect(config.ghidraDecompileMaxPayloadMiB).toBeUndefined();
|
||||
expect(
|
||||
store.inspect({ settings: ["ghidra.decompile_timeout_seconds"] })
|
||||
.settings[0],
|
||||
).toMatchObject({ value: null, launch_value: 7, source: "runtime" });
|
||||
for (const [setting, value] of [
|
||||
["asar.max_header_bytes", null],
|
||||
["asar.max_listing_bytes", 0],
|
||||
["asar.max_listing_bytes", Number.MAX_SAFE_INTEGER + 1],
|
||||
["ghidra.value_flow_max_operations", 0],
|
||||
["ghidra.value_flow_max_inputs_per_operation", 2147483648],
|
||||
["ghidra.decompile_max_payload_mib", 2048],
|
||||
["asar.max_header_bytes", 268435457],
|
||||
["javascript.max_heap_mb", 127],
|
||||
["regex.matching_deadline_ms", 1.5],
|
||||
|
||||
@@ -110,3 +110,24 @@ describe("web bundle Evidence origin scope", () => {
|
||||
expect(evidence.parameters.allowed_origins).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([undefined, {}, { decoded_records: 1024 }])(
|
||||
"preserves the selected source-map admission policy %j without resolving defaults",
|
||||
(selection) => {
|
||||
const selected = analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
fetch_source_maps: true,
|
||||
...(selection === undefined ? {} : { source_map_limits: selection }),
|
||||
});
|
||||
const evidence = createBrowserEvidence(
|
||||
"analyze_web_bundle",
|
||||
selected,
|
||||
result,
|
||||
provider,
|
||||
);
|
||||
if (selection === undefined)
|
||||
expect(evidence.parameters).not.toHaveProperty("source_map_limits");
|
||||
else expect(evidence.parameters.source_map_limits).toEqual(selection);
|
||||
},
|
||||
);
|
||||
@@ -195,6 +195,12 @@ const browserParameters = (
|
||||
...("fetch_source_maps" in input
|
||||
? {
|
||||
fetch_source_maps: input.fetch_source_maps,
|
||||
...(input.source_map_limits === undefined
|
||||
? {}
|
||||
: { source_map_limits: input.source_map_limits }),
|
||||
...(input.semantic_precision === undefined
|
||||
? {}
|
||||
: { semantic_precision: input.semantic_precision }),
|
||||
...(input.max_heap_mb === undefined
|
||||
? {}
|
||||
: { max_heap_mb: input.max_heap_mb }),
|
||||
|
||||
@@ -19,9 +19,43 @@ it("stops a bounded representation scan before visiting an over-budget tail", ()
|
||||
});
|
||||
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 values = ["ev_123", null, 'escaped"\n😀'];
|
||||
const empty = estimateJsonStorage({ evidence_links: [] });
|
||||
const incremental = values.reduce((total, value, index) => {
|
||||
const entry = estimateJsonArrayScalarEntry(value, index > 0);
|
||||
|
||||
@@ -89,6 +89,8 @@ export const requireAuthenticationHeadroom = (
|
||||
readonly path: string;
|
||||
readonly description: string;
|
||||
readonly availableBytes?: number;
|
||||
/** A caller's real serialization ceiling, checked before allocating JSON text. */
|
||||
readonly serializedCodeUnitLimit?: number;
|
||||
readonly additional?: {
|
||||
readonly valueBytes: number;
|
||||
readonly serializedUtf16Bytes: number;
|
||||
@@ -103,6 +105,28 @@ export const requireAuthenticationHeadroom = (
|
||||
const serializedUtf16Bytes =
|
||||
estimate.serializedUtf16Bytes +
|
||||
(options.additional?.serializedUtf16Bytes ?? 0);
|
||||
const serializedCodeUnits = serializedUtf16Bytes / 2;
|
||||
if (
|
||||
options.serializedCodeUnitLimit !== undefined &&
|
||||
serializedCodeUnits > options.serializedCodeUnitLimit
|
||||
)
|
||||
return err(
|
||||
new AnalysisResourceConstraintError(
|
||||
options.operation,
|
||||
"memory",
|
||||
`${options.description}: expanded JSON exceeds the single-string serialization limit.`,
|
||||
{
|
||||
input_path: options.path,
|
||||
serialized_json_code_units: serializedCodeUnits,
|
||||
maximum_serialized_json_code_units: options.serializedCodeUnitLimit,
|
||||
},
|
||||
{
|
||||
retryable: false,
|
||||
remediationAction:
|
||||
"Reduce the selected facts before serialization. If the question requires the complete representation above this ceiling, report this unsupported size instead of repeating the unchanged request. Increasing heap or command-output admission does not raise the serialization ceiling. A delivery summary cannot repair an Evidence record that could not be assembled.",
|
||||
},
|
||||
),
|
||||
);
|
||||
// Canonical hashing and manifest normalization can still encode scalars or
|
||||
// metadata; account for their escaped representations before allocating them.
|
||||
const requiredBytes =
|
||||
|
||||
@@ -54,6 +54,11 @@ const SELECTED_REGISTRATION_SETTINGS = [
|
||||
"REA_KUNA_JOBS",
|
||||
"REA_ANALYSIS_PROVIDER",
|
||||
"REA_ASAR_MAX_HEADER_BYTES",
|
||||
"REA_ASAR_MAX_LISTING_BYTES",
|
||||
"REA_GHIDRA_VALUE_FLOW_MAX_OPERATIONS",
|
||||
"REA_GHIDRA_VALUE_FLOW_MAX_INPUTS_PER_OPERATION",
|
||||
"REA_GHIDRA_VALUE_FLOW_MAX_EDGES",
|
||||
"REA_GHIDRA_DECOMPILE_MAX_PAYLOAD_MIB",
|
||||
"REA_BRIDGE_MAX_REQUEST_BYTES",
|
||||
"REA_CAPTURE_DECODER_OLD_GENERATION_MIB",
|
||||
"REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS",
|
||||
|
||||
@@ -243,6 +243,15 @@ export class WebNetworkCaptureService {
|
||||
},
|
||||
}),
|
||||
sensitive_value_count: input.sensitive_values.length,
|
||||
...(input.max_input_bytes === undefined
|
||||
? {}
|
||||
: { max_input_bytes: input.max_input_bytes }),
|
||||
...(input.max_reply_bytes === undefined
|
||||
? {}
|
||||
: { max_reply_bytes: input.max_reply_bytes }),
|
||||
...(input.max_nesting_depth === undefined
|
||||
? {}
|
||||
: { max_nesting_depth: input.max_nesting_depth }),
|
||||
...(input.capture_timeout_ms === undefined
|
||||
? {}
|
||||
: { capture_timeout_ms: input.capture_timeout_ms }),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { SourceMapLimitSelection } from "../domain/sourceMapLimits.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type {
|
||||
@@ -39,6 +40,7 @@ export interface WebSourceMapPort {
|
||||
readonly url: string;
|
||||
readonly position: WebSourceLocationInput["generated_position"];
|
||||
readonly decodeTimeoutMs?: number;
|
||||
readonly limits?: SourceMapLimitSelection;
|
||||
},
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebSourceMapReport, AnalysisError>>;
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
selectedSourceMapLimits,
|
||||
type SourceMapLimits,
|
||||
} from "../domain/sourceMapLimits.js";
|
||||
import { WEB_SOURCE_LOCATION_PROVIDER } from "../domain/webTraceProviders.js";
|
||||
import { closeOwnedWebResources } from "./closeOwnedWebResources.js";
|
||||
import { createHash } from "node:crypto";
|
||||
@@ -19,7 +23,6 @@ import {
|
||||
} from "../domain/webScriptArtifacts.js";
|
||||
import {
|
||||
DEFAULT_WEB_SOURCE_MAP_DECODE_TIMEOUT_MS,
|
||||
WEB_SOURCE_MAP_LIMITS,
|
||||
webSourceLocationInputSchema,
|
||||
webSourceLocationResultSchema,
|
||||
webSourceMapReportSchema,
|
||||
@@ -56,16 +59,17 @@ const LIMITATIONS = [
|
||||
"Lookup returns all segments at the greatest generated position not greater than the selected point, including earlier lines and generated-only segments. A mapped point does not establish an executed range or UI causality.",
|
||||
"Regular maps and inline indexed sections are supported. External section URLs are unsupported; unknown extensions are retained in raw map text and are not interpreted.",
|
||||
];
|
||||
const codecBudget = (timeoutMs: number): string =>
|
||||
`Complete evidence has a 4 MiB map, 32 MiB reply and a ${String(WEB_SOURCE_MAP_LIMITS.decodedRecords)}-record shared decoder budget for generated rows, mapping segments, leaf maps, source and name declarations, sourcesContent entries, and indexed sections. Generated rows and mapping segments have separate ${String(WEB_SOURCE_MAP_LIMITS.decodedRows)} and ${String(WEB_SOURCE_MAP_LIMITS.decodedSegments)} limits, and indexed maps have a ${String(WEB_SOURCE_MAP_LIMITS.sectionDepth)}-level section budget. The owned codec has a ${String(timeoutMs)} ms decode_timeout_ms deadline`;
|
||||
const codecBudget = (timeoutMs: number, limits: SourceMapLimits): string =>
|
||||
`Complete evidence has a ${String(limits.mapBytes)}-byte map, ${String(limits.outputBytes)}-byte reply and a ${String(limits.decodedRecords)}-record shared decoder budget for generated rows, mapping segments, leaf maps, source and name declarations, sourcesContent entries, and indexed sections. Generated rows and mapping segments have separate ${String(limits.decodedRows)} and ${String(limits.decodedSegments)} limits, and indexed maps have a ${String(limits.sectionDepth)}-level section budget. The owned codec has a ${String(timeoutMs)} ms decode_timeout_ms deadline`;
|
||||
/** Bun accepts but ignores the codec's V8 heap flags; Windows enforces a commit limit instead. */
|
||||
const codecBudgetLimitation = (
|
||||
runtime: WebSourceMapReport["runtime"],
|
||||
timeoutMs: number,
|
||||
limits: SourceMapLimits,
|
||||
): string => {
|
||||
const budget = codecBudget(timeoutMs);
|
||||
const budget = codecBudget(timeoutMs, limits);
|
||||
if (runtime.id === "node-v8")
|
||||
return `${budget}, ${String(WEB_SOURCE_MAP_LIMITS.codecHeapMiB)} MiB old-generation heap and one V8 worker; cleanup may extend the deadline. V8 heap limits do not establish aggregate RSS limits.`;
|
||||
return `${budget}, ${String(limits.codecHeapMiB)} MiB old-generation heap and one V8 worker; cleanup may extend the deadline. V8 heap limits do not establish aggregate RSS limits.`;
|
||||
return runtime.process_memory_limit_bytes === null
|
||||
? `${budget}; cleanup may extend the deadline. The codec ran on Bun, which does not enforce REA's V8 heap flags, so no codec heap limit is established.`
|
||||
: `${budget}; cleanup may extend the deadline. The codec ran on Bun, which does not enforce REA's V8 heap flags; a Windows Job Object limited its committed memory to ${String(runtime.process_memory_limit_bytes)} bytes, which is not a heap or RSS limit.`;
|
||||
@@ -158,6 +162,9 @@ export class WebSourceLocationService {
|
||||
path: map.file.path,
|
||||
url: map.url,
|
||||
position: input.generated_position,
|
||||
...(input.source_map_limits === undefined
|
||||
? {}
|
||||
: { limits: input.source_map_limits }),
|
||||
...(input.decode_timeout_ms === undefined
|
||||
? {}
|
||||
: { decodeTimeoutMs: input.decode_timeout_ms }),
|
||||
@@ -171,7 +178,11 @@ export class WebSourceLocationService {
|
||||
input.decode_timeout_ms ?? DEFAULT_WEB_SOURCE_MAP_DECODE_TIMEOUT_MS;
|
||||
const limitations = [
|
||||
...LIMITATIONS,
|
||||
codecBudgetLimitation(report.value.runtime, decodeTimeoutMs),
|
||||
codecBudgetLimitation(
|
||||
report.value.runtime,
|
||||
decodeTimeoutMs,
|
||||
selectedSourceMapLimits(input.source_map_limits),
|
||||
),
|
||||
];
|
||||
const normalized = webSourceLocationResultSchema.safeParse({
|
||||
...report.value,
|
||||
@@ -285,7 +296,7 @@ const verifyPairing = (
|
||||
map.url !== input.source_map.url ||
|
||||
Buffer.byteLength(map.text) !== map.file.bytes ||
|
||||
createHash("sha256").update(map.text).digest("hex") !== map.file.sha256 ||
|
||||
map.file.bytes > WEB_SOURCE_MAP_LIMITS.mapBytes
|
||||
map.file.bytes > selectedSourceMapLimits(input.source_map_limits).mapBytes
|
||||
)
|
||||
return invalidOutput(
|
||||
"Artifact port changed the selected source-map byte identity or URL context.",
|
||||
|
||||
@@ -328,12 +328,14 @@ export const projectRetainedAnalysis = (
|
||||
if (!retained.ok) return retained;
|
||||
// Duplicate semantic records retain their original ledger metadata. Detail
|
||||
// selection changes presentation, not the historical lookup or payload owner.
|
||||
return projectResolvedAnalysisView(
|
||||
const projected = projectResolvedAnalysisView(
|
||||
{ source, view },
|
||||
prepareAnalysisViewProjection(view),
|
||||
retained.value,
|
||||
evidenceSubjectTarget(evidence.subject),
|
||||
);
|
||||
if (!projected.ok) projected.error.retainPartialObservation(source);
|
||||
return projected;
|
||||
};
|
||||
|
||||
const resolveAnalysisViewSource = (
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import { EvidenceLedger } from "../investigation/EvidenceLedger.js";
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
webSourceLocationArgs,
|
||||
webSourceLocationFixture,
|
||||
webSourceMapDecoderFixture,
|
||||
} from "../../../tests/fixtures/webSourceLocation.js";
|
||||
import { WebSourceLocationService } from "../WebSourceLocationService.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
import {
|
||||
inspectAnalysisView,
|
||||
projectRetainedAnalysis,
|
||||
} from "./AnalysisViewService.js";
|
||||
import { analysisViewRequestSchema } from "../../domain/analysisView/analysisView.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
|
||||
const trace = async (
|
||||
mappings = "AAAA,ACAA,A",
|
||||
sourcesContent: (string | null)[] = ["a😀b", null],
|
||||
) => {
|
||||
const fixture = webSourceLocationFixture(
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
sources: ["one.ts", "one.ts"],
|
||||
sourcesContent,
|
||||
names: [],
|
||||
mappings,
|
||||
}),
|
||||
);
|
||||
const service = new WebSourceLocationService(
|
||||
{ load: async () => ok(fixture) },
|
||||
webSourceMapDecoderFixture,
|
||||
);
|
||||
const result = await service.trace(webSourceLocationArgs);
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
const viewOf = (evidence: Evidence, view: unknown) =>
|
||||
inspectAnalysisView(
|
||||
{
|
||||
source: { kind: "retained-evidence", evidence_id: evidence.evidence_id },
|
||||
view,
|
||||
},
|
||||
(id) => (id === evidence.evidence_id ? evidence : undefined),
|
||||
);
|
||||
|
||||
it("keeps every equal-position alternative and original indices without embedded text", async () => {
|
||||
const parent = await trace();
|
||||
const summary = await viewOf(parent, { kind: "summary" });
|
||||
if (!summary.ok) throw summary.error;
|
||||
expect(summary.value.normalized_result).toMatchObject({
|
||||
parent_evidence_id: parent.evidence_id,
|
||||
summary: {
|
||||
match_count: 3,
|
||||
matches: [
|
||||
{
|
||||
match_index: 0,
|
||||
source_index: 0,
|
||||
reported_source: "one.ts",
|
||||
content: { state: "embedded", code_units: 4 },
|
||||
},
|
||||
{
|
||||
match_index: 1,
|
||||
source_index: 1,
|
||||
reported_source: "one.ts",
|
||||
content: { state: "unavailable" },
|
||||
},
|
||||
{ match_index: 2, state: "generated-only" },
|
||||
],
|
||||
},
|
||||
coverage: { total: 3, examined: 3, exhausted: true },
|
||||
});
|
||||
expect(JSON.stringify(summary.value)).not.toContain('"text":');
|
||||
const page = await viewOf(parent, {
|
||||
kind: "source-location",
|
||||
collection: "matches",
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
});
|
||||
if (!page.ok) throw page.error;
|
||||
expect(page.value.normalized_result).toMatchObject({
|
||||
items: [{ match_index: 1, source_index: 1 }],
|
||||
coverage: { total: 3, examined: 1, next_offset: 2, exhausted: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an empty lookup without inventing a mapping", async () => {
|
||||
const summary = await viewOf(await trace(""), { kind: "summary" });
|
||||
if (!summary.ok) throw summary.error;
|
||||
expect(summary.value.normalized_result).toMatchObject({
|
||||
summary: { match_count: 0, matches: [] },
|
||||
coverage: { status: "empty", total: 0, examined: 0, exhausted: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("selects exact UTF-16 content pages and preserves unavailable content", async () => {
|
||||
const parent = await trace();
|
||||
const view = {
|
||||
kind: "source-location",
|
||||
collection: "source-text",
|
||||
match_index: 0,
|
||||
offset: 1,
|
||||
limit: 2,
|
||||
};
|
||||
const text = await viewOf(parent, view);
|
||||
if (!text.ok) throw text.error;
|
||||
expect(text.value.normalized_result).toMatchObject({
|
||||
match: { match_index: 0, content: { code_units: 4 } },
|
||||
item: { text: "😀", unit: "utf16-code-units" },
|
||||
coverage: { total: 4, examined: 2, next_offset: 3 },
|
||||
});
|
||||
expect((await viewOf(parent, { ...view, offset: 2 })).ok).toBe(false);
|
||||
expect((await viewOf(parent, { ...view, limit: 1 })).ok).toBe(false);
|
||||
const unavailable = await viewOf(parent, { ...view, match_index: 1 });
|
||||
if (!unavailable.ok) throw unavailable.error;
|
||||
expect(unavailable.value.normalized_result).toMatchObject({
|
||||
item: null,
|
||||
match: { content: { state: "unavailable" } },
|
||||
coverage: { status: "unavailable", total: null, exhausted: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns recoverable byte admission and rejects invalid indices", async () => {
|
||||
const parent = await trace();
|
||||
const selected = {
|
||||
kind: "source-location",
|
||||
collection: "matches",
|
||||
max_bytes: 1,
|
||||
};
|
||||
const refused = await viewOf(parent, selected);
|
||||
if (refused.ok) throw new Error("expected view byte refusal");
|
||||
expect(refused.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
reportedLimits: { max_bytes: 1 },
|
||||
remediationAction: expect.stringContaining("view.max_bytes"),
|
||||
});
|
||||
expect((await viewOf(parent, { ...selected, max_bytes: 65536 })).ok).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await viewOf(parent, {
|
||||
kind: "source-location",
|
||||
collection: "source-text",
|
||||
match_index: 3,
|
||||
})
|
||||
).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves already retained parent recovery when a selected projection fails", async () => {
|
||||
const parent = await trace("AAAA", ["a".repeat(10000), null]);
|
||||
const records = new EvidenceLedger();
|
||||
const retention = {
|
||||
recordEvidence: (evidence: Evidence) => records.record(evidence),
|
||||
evidenceById: (id: string) => records.forAnalysis(id),
|
||||
};
|
||||
const view = {
|
||||
kind: "source-location",
|
||||
collection: "source-text",
|
||||
match_index: 0,
|
||||
limit: 10000,
|
||||
max_bytes: 2000,
|
||||
};
|
||||
const refused = projectRetainedAnalysis(
|
||||
parent,
|
||||
retention,
|
||||
analysisViewRequestSchema.parse(view),
|
||||
);
|
||||
if (refused.ok) throw new Error("expected projection admission failure");
|
||||
expect(refused.error.partialObservation).toEqual({
|
||||
kind: "retained-evidence",
|
||||
evidence_id: parent.evidence_id,
|
||||
});
|
||||
expect(records.forAnalysis(parent.evidence_id)?.evidence_id).toBe(
|
||||
parent.evidence_id,
|
||||
);
|
||||
const recovered = await viewOf(parent, { ...view, max_bytes: 20000 });
|
||||
if (!recovered.ok) throw recovered.error;
|
||||
const output = recovered.value.normalized_result as {
|
||||
item: { text: string };
|
||||
};
|
||||
expect(output.item.text.length).toBe(10000);
|
||||
});
|
||||
@@ -93,6 +93,9 @@ export class BinaryLayoutService {
|
||||
operation: OPERATION,
|
||||
parameters: {
|
||||
path: input.value.path,
|
||||
...(input.value.producer_limits === undefined
|
||||
? {}
|
||||
: { producer_limits: input.value.producer_limits }),
|
||||
...(input.value.pwntools_timeout_ms === undefined
|
||||
? {}
|
||||
: { pwntools_timeout_ms: input.value.pwntools_timeout_ms }),
|
||||
|
||||
@@ -67,7 +67,7 @@ const report: KernelModule = {
|
||||
limitations: ["Kernel module metadata was not executed."],
|
||||
};
|
||||
|
||||
it("rejects a relative path and extra arguments before reading", async () => {
|
||||
it("rejects relative paths, extra arguments and invalid field budgets before reading", async () => {
|
||||
let calls = 0;
|
||||
const service = new KernelModuleService({
|
||||
identity,
|
||||
@@ -85,6 +85,20 @@ it("rejects a relative path and extra arguments before reading", async () => {
|
||||
expect(extra.ok).toBe(false);
|
||||
if (!relative.ok) expect(relative.error).toBeInstanceOf(AnalysisInputError);
|
||||
if (!extra.ok) expect(extra.error).toBeInstanceOf(AnalysisInputError);
|
||||
for (const budget of ["max_modinfo_key_bytes", "max_modinfo_value_bytes"]) {
|
||||
for (const value of [0, 536870913]) {
|
||||
const invalid = await service.inspect({
|
||||
path: report.artifact.path,
|
||||
[budget]: value,
|
||||
});
|
||||
expect(invalid.ok).toBe(false);
|
||||
if (!invalid.ok)
|
||||
expect(invalid.error).toMatchObject({
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [expect.objectContaining({ path: [budget] })],
|
||||
});
|
||||
}
|
||||
}
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
MODULE_SIGNATURE_MAGIC,
|
||||
MODULE_SIGNATURE_PKCS7_ID_TYPE,
|
||||
type KernelModule,
|
||||
type InspectKernelModuleInput,
|
||||
} from "../../domain/native/kernelModule.js";
|
||||
import { BINARY_ARCHITECTURES } from "../../domain/binaryTargetTypes.js";
|
||||
import { elfArchitecture } from "../../domain/elfFixedHeader.js";
|
||||
@@ -49,11 +50,7 @@ export class KernelModuleService {
|
||||
if (
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.value.path ||
|
||||
!validReport(
|
||||
report.data,
|
||||
input.value.max_entries,
|
||||
input.value.max_file_bytes,
|
||||
)
|
||||
!validReport(report.data, input.value)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
@@ -124,6 +121,7 @@ const rangesOf = (report: KernelModule): Range[] => {
|
||||
|
||||
const modinfoConsistent = (
|
||||
modinfo: NonNullable<KernelModule["modinfo"]>,
|
||||
input: InspectKernelModuleInput,
|
||||
): boolean => {
|
||||
const closed =
|
||||
modinfo.status === "malformed" || modinfo.status === "unsupported";
|
||||
@@ -145,6 +143,17 @@ const modinfoConsistent = (
|
||||
return false;
|
||||
return modinfo.entries.every((entry, index) => {
|
||||
if (entry.index !== index) return false;
|
||||
if (new Set(entry.omitted_fields).size !== entry.omitted_fields.length)
|
||||
return false;
|
||||
for (const field of ["key", "value"] as const) {
|
||||
const text = entry[field];
|
||||
if (entry.omitted_fields.includes(field) && text !== null) return false;
|
||||
const maximum =
|
||||
field === "key"
|
||||
? input.max_modinfo_key_bytes
|
||||
: input.max_modinfo_value_bytes;
|
||||
if (text !== null && text.length > maximum) return false;
|
||||
}
|
||||
const rawFits = entry.location.bytes <= MAX_KERNEL_MODULE_RAW_BYTES;
|
||||
if (rawFits) {
|
||||
if (
|
||||
@@ -155,7 +164,9 @@ const modinfoConsistent = (
|
||||
} else if (entry.raw_hex !== null) return false;
|
||||
if (entry.status === "observed")
|
||||
return (
|
||||
entry.reason === null && entry.key !== null && entry.value !== null
|
||||
entry.reason === null &&
|
||||
(entry.key !== null || entry.omitted_fields.includes("key")) &&
|
||||
(entry.value !== null || entry.omitted_fields.includes("value"))
|
||||
);
|
||||
return entry.reason !== null;
|
||||
});
|
||||
@@ -274,12 +285,11 @@ const metadataAbsent = (report: KernelModule): boolean =>
|
||||
|
||||
const validReport = (
|
||||
report: KernelModule,
|
||||
maxEntries: number,
|
||||
maxBytes: number,
|
||||
input: InspectKernelModuleInput,
|
||||
): boolean => {
|
||||
if (
|
||||
report.artifact.bytes > maxBytes ||
|
||||
report.coverage.examined_entries > maxEntries ||
|
||||
report.artifact.bytes > input.max_file_bytes ||
|
||||
report.coverage.examined_entries > input.max_entries ||
|
||||
!rangesOf(report).every(inside(report.artifact.bytes))
|
||||
)
|
||||
return false;
|
||||
@@ -342,7 +352,7 @@ const validReport = (
|
||||
return false;
|
||||
if (report.type !== 1) return false;
|
||||
return (
|
||||
modinfoConsistent(report.modinfo) &&
|
||||
modinfoConsistent(report.modinfo, input) &&
|
||||
versionsConsistent(report.versions) &&
|
||||
signatureConsistent(report.signature) &&
|
||||
sizedConsistent(report.init_text) &&
|
||||
|
||||
@@ -95,6 +95,9 @@ export class RecordedCrashService {
|
||||
parameters: {
|
||||
path: input.value.path,
|
||||
include_debugger_context: input.value.include_debugger_context,
|
||||
...(input.value.producer_limits === undefined
|
||||
? {}
|
||||
: { producer_limits: input.value.producer_limits }),
|
||||
...(input.value.pwntools_timeout_ms === undefined
|
||||
? {}
|
||||
: { pwntools_timeout_ms: input.value.pwntools_timeout_ms }),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DesktopLibraryPolicyInput } from "../../domain/desktop/libraryPolicy.js";
|
||||
import { arch, hostname, userInfo } from "node:os";
|
||||
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
@@ -57,6 +58,7 @@ const POLL_INTERVAL_MS = 500;
|
||||
|
||||
/** What the caller asked to capture, after CLI parsing. */
|
||||
export interface DesktopCaptureRequest {
|
||||
readonly libraryPolicy?: DesktopLibraryPolicyInput;
|
||||
readonly desktopEntry: string | undefined;
|
||||
readonly executable: string | undefined;
|
||||
readonly arguments: readonly string[];
|
||||
@@ -176,6 +178,9 @@ const captureEvidence = (
|
||||
state_path_count: request.statePaths.length,
|
||||
exclude_count: request.excludes.length,
|
||||
package_file: request.packageFile !== undefined,
|
||||
...(request.libraryPolicy === undefined
|
||||
? {}
|
||||
: { library_policy: request.libraryPolicy }),
|
||||
},
|
||||
result: capture,
|
||||
confidence: "observed",
|
||||
|
||||
@@ -125,6 +125,35 @@ const exists = (path: string) =>
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
/** Read the exported module's literal alias metadata without importing the desktop SDK. */
|
||||
const exportedAliases = async (directory: string) => {
|
||||
const { stdout } = await execute(
|
||||
process.platform === "win32" ? "python" : "python3",
|
||||
[
|
||||
"-I",
|
||||
"-B",
|
||||
"-c",
|
||||
`import ast, json, sys
|
||||
from pathlib import Path
|
||||
module = ast.parse(Path(sys.argv[1]).read_text(encoding="utf-8"))
|
||||
assignments = [node.value for node in module.body if isinstance(node, ast.Assign)
|
||||
and any(isinstance(target, ast.Name) and target.id == "STATE_ALIASES" for target in node.targets)]
|
||||
assert len(assignments) == 1
|
||||
print(json.dumps(ast.literal_eval(assignments[0])))`,
|
||||
join(directory, "envs/notes/notes_app.py"),
|
||||
],
|
||||
);
|
||||
return z
|
||||
.array(
|
||||
z.tuple([
|
||||
z.string(),
|
||||
z.string(),
|
||||
z.enum(["file", "directory"]).nullable(),
|
||||
]),
|
||||
)
|
||||
.parse(JSON.parse(stdout));
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
@@ -311,11 +340,9 @@ it("seeds the app's state at its own path and retains a selected alias", async (
|
||||
"utf8",
|
||||
),
|
||||
).toBe("milk\n");
|
||||
const module = await readFile(
|
||||
join(directory, "envs/notes/notes_app.py"),
|
||||
"utf8",
|
||||
);
|
||||
expect(module).toContain('("settings", ".config/notes", "directory")');
|
||||
expect(await exportedAliases(directory)).toEqual([
|
||||
["settings", ".config/notes", "directory"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("restores a selected alias when the state directory has no files", async () => {
|
||||
@@ -377,11 +404,9 @@ it.each(["settings/notes", "chosen/notes"])(
|
||||
"utf8",
|
||||
),
|
||||
).toBe("[ui]\nwrap=false\n");
|
||||
const module = await readFile(
|
||||
join(directory, "envs/notes/notes_app.py"),
|
||||
"utf8",
|
||||
);
|
||||
expect(module).toContain(`("${selected}", ".config/notes", "directory")`);
|
||||
expect(await exportedAliases(directory)).toEqual([
|
||||
[selected, ".config/notes", "directory"],
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -426,18 +451,14 @@ it.each([true, false])(
|
||||
},
|
||||
});
|
||||
if (result instanceof Error) throw result;
|
||||
const module = await readFile(
|
||||
join(directory, "envs/notes/notes_app.py"),
|
||||
"utf8",
|
||||
);
|
||||
expect(module).toContain('("settings", ".config/notes", "directory")');
|
||||
expect(module).not.toContain(
|
||||
'("settings/state/notes", ".config/notes/state/notes", "directory")',
|
||||
);
|
||||
const aliases = [["settings", ".config/notes", "directory"]];
|
||||
if (!redundant)
|
||||
expect(module).toContain(
|
||||
'("settings/state/notes", ".local/share/separate", "directory")',
|
||||
);
|
||||
aliases.push([
|
||||
"settings/state/notes",
|
||||
".local/share/separate",
|
||||
"directory",
|
||||
]);
|
||||
expect(await exportedAliases(directory)).toEqual(aliases);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DesktopViewPolicyInput } from "../../domain/desktop/desktopViewPolicy.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { DownloadInstall } from "../../domain/desktop/appDownloadInstall.js";
|
||||
import {
|
||||
@@ -14,13 +15,11 @@ import {
|
||||
type HomePathCollision,
|
||||
type SeedScrubReport,
|
||||
} from "../../domain/desktop/appExport.js";
|
||||
import { INSTALL_SCRIPT } from "../../domain/desktop/appExportInstall.js";
|
||||
import type { WithheldFile } from "../../domain/desktop/appWithheld.js";
|
||||
import {
|
||||
trashedFiles,
|
||||
runtimeSeeds,
|
||||
unownedChangedFolders,
|
||||
unownedFoldersLimitation,
|
||||
unreadDconfLimitation,
|
||||
} from "../../domain/desktop/appExportUnowned.js";
|
||||
import { installLimitations } from "../../domain/desktop/appExportInstallLimitations.js";
|
||||
@@ -32,7 +31,6 @@ import {
|
||||
} from "../../domain/desktop/desktopState.js";
|
||||
import { isWithinAny } from "../../domain/desktop/desktopStateDiff.js";
|
||||
import type { HostIdentity } from "../../domain/desktop/hostIdentity.js";
|
||||
import { recoveryListLimitation } from "../../domain/desktop/seedRecoveryList.js";
|
||||
import { scrubDconf } from "../../domain/desktop/seedScrub.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
@@ -80,6 +78,7 @@ const SEED_MAX_BYTES = 1024 * 1024 * 1024;
|
||||
|
||||
/** What the caller asked to export, after CLI parsing. */
|
||||
export interface DesktopExportRequest extends WithheldRequest {
|
||||
readonly viewPolicy?: DesktopViewPolicyInput | undefined;
|
||||
readonly capture: string;
|
||||
readonly directory: string;
|
||||
readonly name: string | undefined;
|
||||
@@ -235,6 +234,7 @@ const planExport = async (
|
||||
});
|
||||
const launch = planLaunch(capture, electron, seeds, files);
|
||||
const plan: DesktopAppExportPlan = {
|
||||
viewPolicy: request.viewPolicy,
|
||||
name: source,
|
||||
className: className(source),
|
||||
title: application.desktop_entry?.name ?? source,
|
||||
@@ -349,6 +349,7 @@ const runExport = async (
|
||||
request.capture,
|
||||
readers,
|
||||
signal,
|
||||
{ viewPolicy: request.viewPolicy },
|
||||
);
|
||||
if (stateEvidence instanceof AnalysisError) throw stateEvidence;
|
||||
const state = desktopApplicationStateSchema.parse(
|
||||
@@ -477,6 +478,9 @@ export const exportDesktopApplication = async (
|
||||
withhold_to: request.withhold?.to ?? null,
|
||||
withhold_paths: [...(request.withhold?.paths ?? [])],
|
||||
seed_withheld: request.seedWithheld === true,
|
||||
...(request.viewPolicy === undefined
|
||||
? {}
|
||||
: { view_policy: { ...request.viewPolicy } }),
|
||||
},
|
||||
result: {
|
||||
...result,
|
||||
|
||||
@@ -98,6 +98,36 @@ it("treats both explicitly selected files as documents when one ends in -journal
|
||||
});
|
||||
});
|
||||
|
||||
describe("desktop state view admission", () => {
|
||||
it.each([{ text_lines: 0 }, { xml_depth: 495 }, { json_depth: 992 }])(
|
||||
"rejects an invalid view policy before reading a capture: %j",
|
||||
async (viewPolicy) => {
|
||||
const refused = await inspectDesktopApplicationState(
|
||||
"/must-not-read",
|
||||
readers,
|
||||
undefined,
|
||||
{ viewPolicy },
|
||||
);
|
||||
expect(refused).toMatchObject({ _tag: "AnalysisInputError" });
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves an unresolved captured path instead of reading the current file", async () => {
|
||||
const folder = await writeCaptureFolder(capture());
|
||||
const missing = `${HOME}/Documents/missing.txt`;
|
||||
const refused = await inspectDesktopApplicationState(
|
||||
folder,
|
||||
readers,
|
||||
undefined,
|
||||
{ paths: [missing] },
|
||||
);
|
||||
expect(refused).toMatchObject({
|
||||
_tag: "AnalysisInputError",
|
||||
userMessage: expect.stringContaining(missing),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("inspectDesktopApplicationState", () => {
|
||||
it("assigns roles and reads each version into typed views and changes", async () => {
|
||||
const folder = await writeCaptureFolder(capture());
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import {
|
||||
desktopViewPolicy,
|
||||
desktopViewPolicyInputSchema,
|
||||
type DesktopViewPolicy,
|
||||
type DesktopViewPolicyInput,
|
||||
} from "../../domain/desktop/desktopViewPolicy.js";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import {
|
||||
desktopApplicationCaptureSchema,
|
||||
type DesktopApplicationCapture,
|
||||
@@ -63,6 +70,7 @@ export interface DesktopStateReaders {
|
||||
readonly sqlite: (
|
||||
database: string,
|
||||
signal?: AbortSignal,
|
||||
policy?: DesktopViewPolicy,
|
||||
) => Promise<{ ok: true; view: JsonValue } | { ok: false; error: string }>;
|
||||
readonly dconf: (
|
||||
database: string,
|
||||
@@ -130,6 +138,7 @@ interface ViewContext {
|
||||
readonly names: ReadonlySet<string>;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly index: StateIndex;
|
||||
readonly policy: DesktopViewPolicy;
|
||||
}
|
||||
|
||||
const dconfGroups = (text: string, names: ReadonlySet<string>) => {
|
||||
@@ -242,7 +251,11 @@ const sqliteView = async (
|
||||
staged.push({ name: `state.db${sidecar.suffix}`, bytes: bytes.value });
|
||||
}
|
||||
return withStaged(staged, async ([database]) => {
|
||||
const read = await context.readers.sqlite(database ?? "", context.signal);
|
||||
const read = await context.readers.sqlite(
|
||||
database ?? "",
|
||||
context.signal,
|
||||
context.policy,
|
||||
);
|
||||
return read.ok ? { view: read.view, error: null } : failed(read.error);
|
||||
});
|
||||
};
|
||||
@@ -273,9 +286,11 @@ const viewOf = async (
|
||||
case "json":
|
||||
case "keyfile":
|
||||
case "xml":
|
||||
return outcomeOf(textualView(format, input.bytes));
|
||||
return outcomeOf(textualView(format, input.bytes, context.policy));
|
||||
case "zip":
|
||||
return outcomeOf(await readZipView(input.bytes, context.signal));
|
||||
return outcomeOf(
|
||||
await readZipView(input.bytes, context.signal, context.policy),
|
||||
);
|
||||
case "dconf":
|
||||
return dconfView(input, context);
|
||||
case "sqlite":
|
||||
@@ -341,7 +356,7 @@ const readVersion = async (
|
||||
version.view_error = `retained content ${bytes.error}`;
|
||||
return;
|
||||
}
|
||||
const document = openStateDocument(path, bytes.value);
|
||||
const document = openStateDocument(path, bytes.value, context.policy);
|
||||
version.format = document.format;
|
||||
if (document.compression !== undefined)
|
||||
version.compression = document.compression;
|
||||
@@ -404,14 +419,15 @@ const describePath = async (
|
||||
};
|
||||
};
|
||||
|
||||
const STATE_LIMITATIONS = [
|
||||
const stateLimitations = (policy: DesktopViewPolicy) => [
|
||||
"Roles are inferred from state directories, open files, window titles, selected paths and dconf key names; a path can be misattributed.",
|
||||
"Views cover retained content only; a file that existed before the capture but outside the content roots has no starting view.",
|
||||
"SQLite views list at most 500 rows of at most 64 ordinary tables, text views at most 5,000 lines and XML views at most 5,000 nodes; changes between truncated views, or views with an unread table, are marked incomplete.",
|
||||
"JSON and key file views read files of at most 4 MiB, JSON nested at most 500 levels and only numbers JavaScript holds exactly; other files of those formats have a view_error.",
|
||||
`SQLite views list at most ${String(policy.sqlite_rows)} rows of ${String(policy.sqlite_tables)} ordinary tables, text views ${String(policy.text_lines)} lines and XML views ${String(policy.xml_nodes)} nodes; changes between truncated views, or views with an unread table, are marked incomplete. Increase the corresponding --view-policy budget and retry the same capture; no restart is needed.`,
|
||||
`Each projected SQLite table view is bounded at sqlite_view_bytes=${String(policy.sqlite_view_bytes)} UTF-8 JSON bytes. A refused table keeps its error; other tables remain readable. Raise sqlite_view_bytes in --view-policy on the next call for that refusal. The separate SQLite worker reply and value/record limits may refuse earlier and are not raised by view policy.`,
|
||||
`JSON and key file views read files of at most ${String(policy.parsed_bytes)} bytes and JSON nested at most ${String(policy.json_depth)} levels; only numbers JavaScript holds exactly are admitted. Increase parsed_bytes or json_depth in --view-policy for a budget refusal; byte budgets do not change numeric exactness or Evidence nesting.`,
|
||||
"dconf views keep only groups whose path names the application.",
|
||||
"Zip views list at most 1,000 entries and read an entry only when it is unencrypted, stored or deflated, at most 16 MiB and at most 100 times its compressed size, up to 64 MiB per archive; databases and archives inside an archive are not read.",
|
||||
"A gzip file's view is its document's, read only when it is at most 16 MiB and at most 100 times the file's size; a database inside one is not read, nor a gzip file inside an archive.",
|
||||
`Zip views list at most ${String(policy.zip_entries)} entries and read an entry only when unencrypted, stored or deflated, at most ${String(policy.zip_entry_bytes)} bytes and ${String(policy.zip_ratio)} times its compressed size, up to ${String(policy.zip_bytes)} bytes per archive. Increase the corresponding --view-policy budget for a resource refusal; databases and archives inside an archive are not read.`,
|
||||
`A gzip file's view is its document's, read only when it is at most ${String(policy.zip_entry_bytes)} bytes and at most ${String(policy.zip_ratio)} times the file's size; a database inside one is not read, nor a gzip file inside an archive.`,
|
||||
];
|
||||
|
||||
/** Read a capture folder into the application's state view. */
|
||||
@@ -419,20 +435,46 @@ const inspectState = async (
|
||||
folder: string,
|
||||
readers: DesktopStateReaders,
|
||||
signal: AbortSignal | undefined,
|
||||
options: DesktopStateViewOptions,
|
||||
): Promise<Evidence> => {
|
||||
const policy = desktopViewPolicy(options.viewPolicy);
|
||||
const { evidence, capture } = await readDesktopCapture(folder, signal);
|
||||
const names = applicationNames(capture);
|
||||
const facts = roleFacts(capture);
|
||||
const index = indexState(capture);
|
||||
const paths = await withRetainedContent(folder, async (content) => {
|
||||
const context: ViewContext = { content, readers, names, signal, index };
|
||||
const described: DesktopStatePath[] = [];
|
||||
for (const path of statePaths(index))
|
||||
described.push(await describePath(capture, path, facts, context));
|
||||
return described;
|
||||
});
|
||||
const candidates = statePaths(index);
|
||||
for (const selected of options.paths ?? [])
|
||||
if (!candidates.includes(selected))
|
||||
throw new AnalysisInputError(
|
||||
OPERATION,
|
||||
{
|
||||
userMessage: `Captured path ${JSON.stringify(selected)} was not found.`,
|
||||
remediationAction:
|
||||
"Use an exact path from this capture's state view; no current filesystem path is substituted.",
|
||||
},
|
||||
[{ path: ["paths"], reason: "invalid_value" }],
|
||||
);
|
||||
const paths = await withRetainedContent(
|
||||
folder,
|
||||
async (content) => {
|
||||
const context: ViewContext = {
|
||||
content,
|
||||
readers,
|
||||
names,
|
||||
signal,
|
||||
index,
|
||||
policy,
|
||||
};
|
||||
const described: DesktopStatePath[] = [];
|
||||
for (const path of candidates)
|
||||
if (options.paths === undefined || options.paths.includes(path))
|
||||
described.push(await describePath(capture, path, facts, context));
|
||||
return described;
|
||||
},
|
||||
policy.file_bytes,
|
||||
);
|
||||
const limitations = [
|
||||
...STATE_LIMITATIONS,
|
||||
...stateLimitations(policy),
|
||||
...(capture.state.state_directories === undefined
|
||||
? [
|
||||
"The capture does not record its state directories as walked, so files in a symlinked state directory may be classed as documents.",
|
||||
@@ -440,6 +482,7 @@ const inspectState = async (
|
||||
: []),
|
||||
];
|
||||
const result: DesktopApplicationState = {
|
||||
effective_view_policy: policy,
|
||||
capture: {
|
||||
evidence_id: evidence.evidence_id,
|
||||
home: capture.host.home,
|
||||
@@ -457,7 +500,13 @@ const inspectState = async (
|
||||
return createEvidence(undefined, DESKTOP_PROVIDER, {
|
||||
predicateType: "rea.desktop-application-state",
|
||||
operation: OPERATION,
|
||||
parameters: { capture_evidence_id: evidence.evidence_id },
|
||||
parameters: {
|
||||
capture_evidence_id: evidence.evidence_id,
|
||||
...(options.viewPolicy === undefined
|
||||
? {}
|
||||
: { view_policy: { ...options.viewPolicy } }),
|
||||
...(options.paths === undefined ? {} : { paths: [...options.paths] }),
|
||||
},
|
||||
result,
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
@@ -465,14 +514,35 @@ const inspectState = async (
|
||||
});
|
||||
};
|
||||
|
||||
export interface DesktopStateViewOptions {
|
||||
readonly viewPolicy?: DesktopViewPolicyInput | undefined;
|
||||
/** Exact original captured paths; omission examines every retained path. */
|
||||
readonly paths?: readonly string[] | undefined;
|
||||
}
|
||||
|
||||
/** Inspect one capture folder, returning its state view Evidence or a failure. */
|
||||
export const inspectDesktopApplicationState = async (
|
||||
folder: string,
|
||||
readers: DesktopStateReaders,
|
||||
signal?: AbortSignal,
|
||||
options: DesktopStateViewOptions = {},
|
||||
): Promise<Evidence | AnalysisError> => {
|
||||
try {
|
||||
return await inspectState(folder, readers, signal);
|
||||
const admitted = desktopViewPolicyInputSchema.safeParse(
|
||||
options.viewPolicy === undefined ? {} : options.viewPolicy,
|
||||
);
|
||||
if (!admitted.success)
|
||||
return analysisInputErrorFromIssues(
|
||||
OPERATION,
|
||||
admitted.error.issues,
|
||||
options.viewPolicy,
|
||||
);
|
||||
return await inspectState(folder, readers, signal, {
|
||||
...options,
|
||||
...(options.viewPolicy === undefined
|
||||
? {}
|
||||
: { viewPolicy: admitted.data }),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return desktopOperationFailure(
|
||||
cause,
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
DESKTOP_VIEW_DEFAULTS,
|
||||
desktopViewFileLimitMessage,
|
||||
type DesktopViewPolicy,
|
||||
} from "../../domain/desktop/desktopViewPolicy.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
@@ -138,6 +143,7 @@ export const shippedSeedViews = async (
|
||||
copies: readonly RetainedCopy[],
|
||||
identity: HostIdentity,
|
||||
signal: AbortSignal | undefined,
|
||||
policy: DesktopViewPolicy = DESKTOP_VIEW_DEFAULTS,
|
||||
): Promise<ReadonlyMap<string, TaskFileView>> => {
|
||||
const views = new Map<string, TaskFileView>();
|
||||
for (const copy of copies) {
|
||||
@@ -150,15 +156,23 @@ export const shippedSeedViews = async (
|
||||
const bytes = await retainedBytes(content, copy, signal);
|
||||
const shipped = shippedSeed(bytes, seed, identity).bytes;
|
||||
if (shipped === undefined) continue;
|
||||
const document = openStateDocument(seed.home, shipped);
|
||||
if (shipped.length > policy.file_bytes) {
|
||||
views.set(seed.home, {
|
||||
format: null,
|
||||
view: null,
|
||||
error: desktopViewFileLimitMessage(policy),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const document = openStateDocument(seed.home, shipped, policy);
|
||||
const { format } = document;
|
||||
const view =
|
||||
"error" in document
|
||||
? err(document.error)
|
||||
: format === "zip"
|
||||
? await readZipView(document.bytes, signal)
|
||||
? await readZipView(document.bytes, signal, policy)
|
||||
: isTextualFormat(format)
|
||||
? textualView(format, document.bytes)
|
||||
? textualView(format, document.bytes, policy)
|
||||
: undefined;
|
||||
views.set(seed.home, {
|
||||
format,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
desktopViewPolicy,
|
||||
type DesktopViewPolicyInput,
|
||||
} from "../../domain/desktop/desktopViewPolicy.js";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -29,6 +33,7 @@ import type { DesktopExportRequest } from "./DesktopApplicationExport.js";
|
||||
/** What the export reads a reader's file from: the retained content, the seeds it ships and each file's versions. */
|
||||
export interface ReaderSources {
|
||||
readonly capture: string;
|
||||
readonly viewPolicy?: DesktopViewPolicyInput | undefined;
|
||||
readonly copies: readonly RetainedCopy[];
|
||||
readonly files: ReadonlyMap<string, DesktopStatePath>;
|
||||
readonly ends: StateEnds;
|
||||
@@ -107,14 +112,18 @@ const exportReaderViews =
|
||||
|
||||
/** What a task's checks read beyond the state view: the text seeds' views as the bundle ships them, its readers' and its screenshots. */
|
||||
export const taskReads = async (
|
||||
request: Pick<DesktopExportRequest, "capture" | "tasks" | "screens">,
|
||||
request: Pick<
|
||||
DesktopExportRequest,
|
||||
"capture" | "tasks" | "screens" | "viewPolicy"
|
||||
>,
|
||||
maxBytes: number,
|
||||
found: Omit<ReaderSources, "capture" | "screens" | "maxBytes">,
|
||||
found: Omit<ReaderSources, "capture" | "screens" | "maxBytes" | "viewPolicy">,
|
||||
) => {
|
||||
const sources = {
|
||||
...found,
|
||||
capture: request.capture,
|
||||
screens: request.screens,
|
||||
viewPolicy: request.viewPolicy,
|
||||
maxBytes,
|
||||
};
|
||||
return readsOf(request.tasks.length, sources);
|
||||
@@ -132,6 +141,7 @@ const readsOf = async (tasks: number, sources: ReaderSources) => ({
|
||||
sources.copies,
|
||||
sources.identity,
|
||||
sources.signal,
|
||||
desktopViewPolicy(sources.viewPolicy),
|
||||
),
|
||||
sources.maxBytes,
|
||||
),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DESKTOP_VIEW_DEFAULTS } from "../../domain/desktop/desktopViewPolicy.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -22,7 +23,7 @@ import {
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
/** Largest retained file the state view reads. */
|
||||
const DEFAULT_MAX_BYTES = 64 * MIB;
|
||||
const DEFAULT_MAX_BYTES = DESKTOP_VIEW_DEFAULTS.file_bytes;
|
||||
|
||||
type FailedRelease = Extract<
|
||||
ArtifactCleanupAttempt,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { z } from "zod";
|
||||
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { jsonValueByteLength } from "../../domain/jsonValueByteLength.js";
|
||||
import {
|
||||
sqliteDatabaseSchema,
|
||||
sqliteValueSchema,
|
||||
@@ -10,8 +11,11 @@ import {
|
||||
import { plainRecord } from "../../domain/desktop/stateFormats.js";
|
||||
import type { SqliteDatabaseService } from "../sqlite/SqliteDatabaseService.js";
|
||||
|
||||
const ROW_LIMIT = 500;
|
||||
const MAX_TABLES = 64;
|
||||
import {
|
||||
DESKTOP_VIEW_DEFAULTS,
|
||||
desktopSqliteViewLimitMessage,
|
||||
type DesktopViewPolicy,
|
||||
} from "../../domain/desktop/desktopViewPolicy.js";
|
||||
|
||||
/** A database's ordinary tables as JSON rows, or why it could not be read. */
|
||||
export type SqliteStateView =
|
||||
@@ -79,6 +83,7 @@ export const readSqliteStateView = async (
|
||||
service: SqliteReader,
|
||||
database: string,
|
||||
signal?: AbortSignal,
|
||||
policy: DesktopViewPolicy = DESKTOP_VIEW_DEFAULTS,
|
||||
): Promise<SqliteStateView> => {
|
||||
const inventory = await report(
|
||||
service,
|
||||
@@ -90,10 +95,10 @@ export const readSqliteStateView = async (
|
||||
const ordinary = inventory.schema.tables.filter(
|
||||
(table) => table.kind === "table",
|
||||
);
|
||||
for (const table of ordinary.slice(0, MAX_TABLES)) {
|
||||
for (const table of ordinary.slice(0, policy.sqlite_tables)) {
|
||||
const selected = await report(
|
||||
service,
|
||||
{ path: database, table: table.name, row_limit: ROW_LIMIT },
|
||||
{ path: database, table: table.name, row_limit: policy.sqlite_rows },
|
||||
signal,
|
||||
);
|
||||
if (typeof selected === "string") {
|
||||
@@ -101,7 +106,7 @@ export const readSqliteStateView = async (
|
||||
continue;
|
||||
}
|
||||
const rows = selected.rows;
|
||||
tables[table.name] = {
|
||||
const view = {
|
||||
columns: rows?.columns ?? [],
|
||||
primary_key: table.columns
|
||||
.filter((column) => column.primary_key_position > 0)
|
||||
@@ -110,12 +115,25 @@ export const readSqliteStateView = async (
|
||||
left.primary_key_position - right.primary_key_position,
|
||||
)
|
||||
.map((column) => column.name),
|
||||
rows: (rows?.values ?? []).map((row) => row.map(cellValue)),
|
||||
rows: [] as JsonValue[][],
|
||||
truncated: rows?.truncated ?? false,
|
||||
};
|
||||
let bytes = jsonValueByteLength(view, policy.sqlite_view_bytes);
|
||||
for (const row of rows?.values ?? []) {
|
||||
if (bytes > policy.sqlite_view_bytes) break;
|
||||
const projected = row.map(cellValue);
|
||||
bytes +=
|
||||
(view.rows.length === 0 ? 0 : 1) +
|
||||
jsonValueByteLength(projected, policy.sqlite_view_bytes - bytes);
|
||||
if (bytes <= policy.sqlite_view_bytes) view.rows.push(projected);
|
||||
}
|
||||
tables[table.name] =
|
||||
bytes > policy.sqlite_view_bytes
|
||||
? { error: desktopSqliteViewLimitMessage(policy) }
|
||||
: view;
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
view: { tables, tables_truncated: ordinary.length > MAX_TABLES },
|
||||
view: { tables, tables_truncated: ordinary.length > policy.sqlite_tables },
|
||||
};
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DesktopViewPolicyInput } from "../../domain/desktop/desktopViewPolicy.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { exportedStateFiles } from "../../domain/desktop/appExport.js";
|
||||
import { DRAFT_PROMPT } from "../../domain/desktop/appTask.js";
|
||||
@@ -56,12 +57,14 @@ const draft = async (
|
||||
readers: DesktopStateReaders,
|
||||
signal: AbortSignal | undefined,
|
||||
selection: DraftSelection,
|
||||
viewPolicy: DesktopViewPolicyInput | undefined,
|
||||
): Promise<Evidence> => {
|
||||
const { evidence, capture } = await readDesktopCapture(folder, signal);
|
||||
const stateEvidence = await inspectDesktopApplicationState(
|
||||
folder,
|
||||
readers,
|
||||
signal,
|
||||
{ viewPolicy },
|
||||
);
|
||||
if (stateEvidence instanceof AnalysisError) throw stateEvidence;
|
||||
const state = desktopApplicationStateSchema.parse(
|
||||
@@ -114,6 +117,9 @@ const draft = async (
|
||||
});
|
||||
const environment = exportEnvironmentName(capture, undefined);
|
||||
const result = {
|
||||
...(state.effective_view_policy === undefined
|
||||
? {}
|
||||
: { effective_view_policy: state.effective_view_policy }),
|
||||
application: {
|
||||
environment,
|
||||
title: capture.application.desktop_entry?.name ?? environment,
|
||||
@@ -160,6 +166,9 @@ const draft = async (
|
||||
capture_evidence_id: evidence.evidence_id,
|
||||
seed_checkpoint: selection.seed ?? null,
|
||||
end_checkpoint: selection.end ?? null,
|
||||
...(stateEvidence.parameters.view_policy === undefined
|
||||
? {}
|
||||
: { view_policy: stateEvidence.parameters.view_policy }),
|
||||
},
|
||||
result,
|
||||
confidence: "inferred",
|
||||
@@ -177,9 +186,10 @@ export const draftDesktopApplicationTask = async (
|
||||
readers: DesktopStateReaders,
|
||||
signal?: AbortSignal,
|
||||
selection: DraftSelection = {},
|
||||
viewPolicy?: DesktopViewPolicyInput,
|
||||
): Promise<Evidence | AnalysisError> => {
|
||||
try {
|
||||
return await draft(folder, readers, signal, selection);
|
||||
return await draft(folder, readers, signal, selection, viewPolicy);
|
||||
} catch (cause: unknown) {
|
||||
return desktopOperationFailure(
|
||||
cause,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
DESKTOP_VIEW_DEFAULTS,
|
||||
type DesktopViewPolicy,
|
||||
} from "../../domain/desktop/desktopViewPolicy.js";
|
||||
import {
|
||||
Reader,
|
||||
Uint8ArrayWriter,
|
||||
@@ -12,7 +16,6 @@ import {
|
||||
} from "../../artifacts/ZipArtifactReader.js";
|
||||
import {
|
||||
DAMAGED_ZIP_ENTRY,
|
||||
MAX_ZIP_ENTRIES,
|
||||
UNREADABLE_ZIP,
|
||||
unreadZipEntry,
|
||||
zipEntry,
|
||||
@@ -63,6 +66,7 @@ const readEntry = async (
|
||||
entry: FileEntry,
|
||||
header: ZipEntryHeader,
|
||||
signal: AbortSignal | undefined,
|
||||
policy: DesktopViewPolicy,
|
||||
): Promise<JsonValue> => {
|
||||
let bytes: Uint8Array;
|
||||
try {
|
||||
@@ -74,7 +78,7 @@ const readEntry = async (
|
||||
signal?.throwIfAborted();
|
||||
return unreadZipEntry(header, DAMAGED_ZIP_ENTRY);
|
||||
}
|
||||
return zipEntry(header, bytes);
|
||||
return zipEntry(header, bytes, policy);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -86,9 +90,10 @@ const readEntry = async (
|
||||
export const readZipView = async (
|
||||
bytes: Uint8Array,
|
||||
signal?: AbortSignal,
|
||||
policy: DesktopViewPolicy = DESKTOP_VIEW_DEFAULTS,
|
||||
): Promise<Result<JsonValue, string>> => {
|
||||
// The directory is scanned first, so zip.js sees only the records the view lists.
|
||||
const directory = scanZipDirectory(bytes, MAX_ZIP_ENTRIES);
|
||||
const directory = scanZipDirectory(bytes, policy.zip_entries);
|
||||
if (directory === undefined) return err(UNREADABLE_ZIP);
|
||||
const reader = new ZipReader(
|
||||
new BoundedArchiveReader(
|
||||
@@ -113,11 +118,11 @@ export const readZipView = async (
|
||||
method: entry.compressionMethod,
|
||||
encrypted: entry.encrypted,
|
||||
};
|
||||
const refusal = zipEntryRefusal(header, spent);
|
||||
const refusal = zipEntryRefusal(header, spent, policy);
|
||||
if (refusal === undefined) spent += header.size;
|
||||
entries.push(
|
||||
refusal === undefined
|
||||
? await readEntry(entry, header, signal)
|
||||
? await readEntry(entry, header, signal, policy)
|
||||
: unreadZipEntry(header, refusal),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import type {
|
||||
FridaCapturePolicy,
|
||||
FridaCapturePolicyInput,
|
||||
} from "../../domain/fridaCapturePolicy.js";
|
||||
import type {
|
||||
AnalysisError,
|
||||
AnalysisErrorOptions,
|
||||
@@ -32,8 +36,9 @@ export interface FridaProcessObservation {
|
||||
readonly identifier: string | null;
|
||||
}
|
||||
|
||||
export type StartFridaSessionInput = FridaDeviceSelector &
|
||||
(
|
||||
export type StartFridaSessionInput = FridaDeviceSelector & {
|
||||
readonly captureLimits?: FridaCapturePolicyInput;
|
||||
} & (
|
||||
| { readonly mode: "attach"; readonly pid: number }
|
||||
| {
|
||||
readonly mode: "spawn";
|
||||
@@ -47,6 +52,7 @@ export type FridaScriptSource =
|
||||
| { readonly sourceKind: "file"; readonly path: string };
|
||||
|
||||
export interface FridaSessionObservation {
|
||||
readonly captureLimits?: FridaCapturePolicy;
|
||||
readonly sessionId: string;
|
||||
readonly deviceId: string;
|
||||
readonly target: string;
|
||||
@@ -56,6 +62,7 @@ export interface FridaSessionObservation {
|
||||
}
|
||||
|
||||
export interface FridaScriptObservation {
|
||||
readonly captureLimits?: FridaCapturePolicy;
|
||||
readonly scriptId: string;
|
||||
readonly sourceKind: "inline" | "file";
|
||||
readonly sourcePath: string | null;
|
||||
|
||||
@@ -128,7 +128,9 @@ it("keeps default Frida status identity and messages and refreshes every summary
|
||||
expect(parent?.limitations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("16777216"),
|
||||
expect.stringContaining("no runtime override"),
|
||||
expect.stringContaining(
|
||||
"Already discarded observations cannot be recovered",
|
||||
),
|
||||
]),
|
||||
);
|
||||
expect(parent?.authority).toBe("external-service");
|
||||
|
||||
@@ -11,7 +11,6 @@ import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorClean
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
@@ -548,6 +547,9 @@ const fridaParameters = (
|
||||
},
|
||||
}),
|
||||
mode: input.mode,
|
||||
...(input.captureLimits === undefined
|
||||
? {}
|
||||
: { capture_limits: input.captureLimits }),
|
||||
...(input.mode === "attach"
|
||||
? { pid: input.pid }
|
||||
: {
|
||||
@@ -563,6 +565,9 @@ const sourceOutput = (script: FridaScriptObservation) => ({
|
||||
});
|
||||
|
||||
const scriptOutput = (script: FridaScriptObservation) => ({
|
||||
...(script.captureLimits === undefined
|
||||
? {}
|
||||
: { capture_limits: script.captureLimits }),
|
||||
script_id: script.scriptId,
|
||||
...sourceOutput(script),
|
||||
messages: script.messages,
|
||||
@@ -570,6 +575,9 @@ const scriptOutput = (script: FridaScriptObservation) => ({
|
||||
});
|
||||
|
||||
const sessionStatusOutput = (status: FridaSessionStatus) => ({
|
||||
...(status.captureLimits === undefined
|
||||
? {}
|
||||
: { capture_limits: status.captureLimits }),
|
||||
session_id: status.sessionId,
|
||||
device_id: status.deviceId,
|
||||
state: status.state,
|
||||
|
||||
@@ -290,7 +290,7 @@ it("validates string_literals input options and output invariants", async () =>
|
||||
{
|
||||
path: report.artifact.path,
|
||||
include_string_literals: true,
|
||||
max_string_literals: 10_001,
|
||||
max_string_literals: Number.MAX_SAFE_INTEGER + 1,
|
||||
},
|
||||
]) {
|
||||
const refused = await service.inspect(invalidInput);
|
||||
@@ -298,6 +298,18 @@ it("validates string_literals input options and output invariants", async () =>
|
||||
if (!refused.ok) expect(refused.error).toBeInstanceOf(AnalysisInputError);
|
||||
}
|
||||
expect(calls).toBe(0);
|
||||
const admitted = await service.inspect({
|
||||
path: report.artifact.path,
|
||||
include_string_literals: true,
|
||||
max_string_literals: 10_001,
|
||||
});
|
||||
if (!admitted.ok) throw admitted.error;
|
||||
expect(admitted.value.parameters).toEqual({
|
||||
path: report.artifact.path,
|
||||
include_string_literals: true,
|
||||
max_string_literals: 10_001,
|
||||
});
|
||||
expect(calls).toBe(1);
|
||||
|
||||
const baseLiterals: NonNullable<GoBinary["string_literals"]> = {
|
||||
evidence_kind: "inferred",
|
||||
|
||||
@@ -90,6 +90,9 @@ const parameters = (
|
||||
input: AnalyzeJavaScriptApplicationInput,
|
||||
): EvidenceObservation["parameters"] => ({
|
||||
input_path: input.input_path,
|
||||
...(input.semantic_precision === undefined
|
||||
? {}
|
||||
: { semantic_precision: input.semantic_precision }),
|
||||
format: input.format,
|
||||
integrity_policy: input.integrity_policy,
|
||||
...(input.max_semantic_nodes === undefined
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ASAR_HEADER_ADMISSION_SETTING,
|
||||
parseAsarHeaderAdmission,
|
||||
} from "../../config/asarHeaderAdmission.js";
|
||||
import { parseAsarListingAdmission } from "../../config/asarListingAdmission.js";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
@@ -69,12 +70,22 @@ export const analyzeJavaScriptApplicationValidated = async (
|
||||
options.environment?.[ASAR_HEADER_ADMISSION_SETTING],
|
||||
);
|
||||
if (!asarHeaderAdmission.ok) return asarHeaderAdmission;
|
||||
const listingAdmission = parseAsarListingAdmission(
|
||||
options.environment?.REA_ASAR_MAX_LISTING_BYTES,
|
||||
);
|
||||
if (!listingAdmission.ok) return listingAdmission;
|
||||
const overrides = options.settings?.().overrides;
|
||||
const header = overrides?.["asar.max_header_bytes"];
|
||||
const acceptedAdmission =
|
||||
header === undefined
|
||||
const listing = overrides?.["asar.max_listing_bytes"];
|
||||
const acceptedAdmission = {
|
||||
...(header === undefined
|
||||
? asarHeaderAdmission.value
|
||||
: { maximumBytes: header, source: "runtime" as const };
|
||||
: { maximumBytes: header, source: "runtime" as const }),
|
||||
listing:
|
||||
listing === undefined
|
||||
? listingAdmission.value
|
||||
: { maximumBytes: listing, source: "runtime" as const },
|
||||
};
|
||||
let reconstructed: JavaScriptArtifactReconstructionResult | undefined;
|
||||
let result: JavaScriptApplicationAnalysisResult | undefined;
|
||||
let evidence: Evidence | undefined;
|
||||
|
||||
@@ -317,7 +317,9 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
|
||||
const limits = [
|
||||
...new Map(
|
||||
[
|
||||
...semanticResourceLimitCoverage(resourceLimits),
|
||||
...semanticResourceBounds(context).flatMap(({ limit, precision }) =>
|
||||
semanticResourceLimitCoverage([limit], precision),
|
||||
),
|
||||
...executionLimits,
|
||||
...(inlineScriptsTruncated
|
||||
? [HTML_INLINE_SCRIPT_LOCATION_COVERAGE_LIMIT]
|
||||
@@ -340,17 +342,24 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
|
||||
return completeApplicationCoverage();
|
||||
};
|
||||
|
||||
const semanticResourceBounds = (context: JavaScriptArtifactGraphContext) => [
|
||||
...new Map(
|
||||
context.analysis.files.flatMap(({ semantic }) =>
|
||||
semantic === null
|
||||
? []
|
||||
: semanticCoverageResourceLimits(semantic.ir.coverage).map((limit) => {
|
||||
const fact = { limit, precision: semantic.ir.coverage.precision };
|
||||
return [JSON.stringify(fact), fact] as const;
|
||||
}),
|
||||
),
|
||||
).values(),
|
||||
];
|
||||
|
||||
const semanticResourceLimits = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
): JavaScriptSemanticResourceLimit[] =>
|
||||
[
|
||||
...new Set(
|
||||
context.analysis.files.flatMap(({ semantic }) =>
|
||||
semantic === null
|
||||
? []
|
||||
: semanticCoverageResourceLimits(semantic.ir.coverage),
|
||||
),
|
||||
),
|
||||
...new Set(semanticResourceBounds(context).map(({ limit }) => limit)),
|
||||
].sort();
|
||||
|
||||
const graphLimitations = (
|
||||
@@ -426,7 +435,9 @@ const graphLimitations = (
|
||||
"Sender, frame, URL, and origin checks are observations only; REA does not claim that they enforce a complete authorization policy.",
|
||||
]
|
||||
: []),
|
||||
...semanticResourceLimits(context).map(semanticResourceLimitReason),
|
||||
...semanticResourceBounds(context).map(({ limit, precision }) =>
|
||||
semanticResourceLimitReason(limit, precision),
|
||||
),
|
||||
...(context.analysis.files.some(
|
||||
({ javascript }) =>
|
||||
(javascript?.electron.native_addon_bindings.length ?? 0) > 0,
|
||||
|
||||
@@ -182,6 +182,9 @@ export const reconstructJavaScriptArtifact = async (
|
||||
: { fileNodes: input.max_semantic_nodes_per_file }),
|
||||
});
|
||||
const sourceLimits = {
|
||||
...(input.semantic_precision === undefined
|
||||
? {}
|
||||
: { semanticPrecision: input.semantic_precision }),
|
||||
heapMb:
|
||||
input.max_heap_mb ??
|
||||
overrides?.["javascript.max_heap_mb"] ??
|
||||
|
||||
@@ -518,7 +518,11 @@ const relationshipEvidence = (
|
||||
limitations: [
|
||||
...input.semantic.ir.limitations,
|
||||
...semanticCoverageResourceLimits(input.semantic.ir.coverage).map(
|
||||
semanticResourceLimitReason,
|
||||
(limit) =>
|
||||
semanticResourceLimitReason(
|
||||
limit,
|
||||
input.semantic.ir.coverage.precision,
|
||||
),
|
||||
),
|
||||
...limitations,
|
||||
],
|
||||
@@ -531,7 +535,10 @@ const semanticCoverage = (
|
||||
if (semantic.ir.coverage.status === "complete" && resourceLimits.length === 0)
|
||||
return completeApplicationCoverage();
|
||||
return partialApplicationCoverage(
|
||||
semanticResourceLimitCoverage(resourceLimits),
|
||||
semanticResourceLimitCoverage(
|
||||
resourceLimits,
|
||||
semantic.ir.coverage.precision,
|
||||
),
|
||||
semantic.ir.coverage.omittedCount,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -723,15 +723,17 @@ const projectFileResourceLimits = (
|
||||
family: "data-flow",
|
||||
relation_kinds: ["defines"],
|
||||
reason: "resource-limit",
|
||||
detail: semanticResourceLimitReason(limit),
|
||||
detail: semanticResourceLimitReason(limit, context.ir.coverage.precision),
|
||||
candidate_node_ids: [],
|
||||
evidence: {
|
||||
...unknownSemanticEvidence(context.file, null),
|
||||
coverage: partialApplicationCoverage(
|
||||
semanticResourceLimitCoverage([limit]),
|
||||
semanticResourceLimitCoverage([limit], context.ir.coverage.precision),
|
||||
null,
|
||||
),
|
||||
limitations: [semanticResourceLimitReason(limit)],
|
||||
limitations: [
|
||||
semanticResourceLimitReason(limit, context.ir.coverage.precision),
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -859,15 +861,17 @@ function* createCallSiteNodes(
|
||||
family: "call-flow",
|
||||
relation_kinds: ["argument-to-parameter"],
|
||||
reason: "resource-limit",
|
||||
detail: semanticResourceLimitReason(limit),
|
||||
detail: semanticResourceLimitReason(limit, ir.coverage.precision),
|
||||
candidate_node_ids: [],
|
||||
evidence: {
|
||||
...unknownSemanticEvidence(file, call.location),
|
||||
coverage: partialApplicationCoverage(
|
||||
semanticResourceLimitCoverage([limit]),
|
||||
semanticResourceLimitCoverage([limit], ir.coverage.precision),
|
||||
null,
|
||||
),
|
||||
limitations: [semanticResourceLimitReason(limit)],
|
||||
limitations: [
|
||||
semanticResourceLimitReason(limit, ir.coverage.precision),
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ it("cancels actual call-path work while its first seed indexes a long block", as
|
||||
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
|
||||
expect(work.next()).toEqual({ done: true, value: undefined });
|
||||
expect(accumulator.ipc).toEqual([]);
|
||||
expect(accumulator.electronCallPathLimitReached).toBeUndefined();
|
||||
expect(accumulator.electronCallPathLimits).toBeUndefined();
|
||||
|
||||
// A new analysis owns a new index and can still complete the same source.
|
||||
const completed = createJavaScriptAnalysisAccumulator(source.length);
|
||||
@@ -57,5 +57,5 @@ it("cancels actual call-path work while its first seed indexes a long block", as
|
||||
),
|
||||
),
|
||||
).toContainEqual(expect.objectContaining({ entry: "first", conditions: [] }));
|
||||
expect(completed.electronCallPathLimitReached).toBeUndefined();
|
||||
expect(completed.electronCallPathLimits).toBeUndefined();
|
||||
});
|
||||
@@ -97,14 +97,18 @@ interface ManagedMemberComparisonPathDependencies {
|
||||
readonly readSnapshot: typeof readManagedSnapshot;
|
||||
}
|
||||
|
||||
interface ManagedMemberComparisonPathInput {
|
||||
readonly leftPath: string;
|
||||
readonly rightPath: string;
|
||||
/** Applied to both sides with inspect_managed_members selection semantics. */
|
||||
readonly typeNames?: readonly string[];
|
||||
readonly maxSnapshotBytes?: number;
|
||||
readonly maxRepresentationBytes?: number;
|
||||
}
|
||||
|
||||
/** Inspect two local PE artifacts and return one derived comparison Evidence. */
|
||||
export const compareManagedMemberPaths = async (
|
||||
input: {
|
||||
readonly leftPath: string;
|
||||
readonly rightPath: string;
|
||||
/** Applied to both sides with inspect_managed_members selection semantics. */
|
||||
readonly typeNames?: readonly string[];
|
||||
},
|
||||
input: ManagedMemberComparisonPathInput,
|
||||
dependencies: Partial<ManagedMemberComparisonPathDependencies> = {},
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
@@ -146,6 +150,9 @@ export const compareManagedMemberPaths = async (
|
||||
let snapshot: Awaited<ReturnType<typeof readManagedSnapshot>>;
|
||||
try {
|
||||
snapshot = await readSnapshot(path, operation, {
|
||||
...(input.maxSnapshotBytes === undefined
|
||||
? {}
|
||||
: { maxBytes: input.maxSnapshotBytes }),
|
||||
expectedSha256: target.sha256,
|
||||
...(resources === undefined ? {} : { resources }),
|
||||
});
|
||||
@@ -161,6 +168,9 @@ export const compareManagedMemberPaths = async (
|
||||
try {
|
||||
inspection = inspectManagedMembersBytes(snapshot.bytes, target, {
|
||||
userStrings: false,
|
||||
...(input.maxRepresentationBytes === undefined
|
||||
? {}
|
||||
: { maxRepresentationBytes: input.maxRepresentationBytes }),
|
||||
...(input.typeNames === undefined
|
||||
? {}
|
||||
: { typeNames: input.typeNames }),
|
||||
@@ -177,10 +187,19 @@ export const compareManagedMemberPaths = async (
|
||||
}
|
||||
const evidence = createEvidence(target, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters:
|
||||
input.typeNames === undefined
|
||||
parameters: {
|
||||
...(input.typeNames === undefined
|
||||
? {}
|
||||
: { type_names: [...input.typeNames] },
|
||||
: { type_names: [...input.typeNames] }),
|
||||
...(input.maxSnapshotBytes === undefined
|
||||
? {}
|
||||
: { max_snapshot_bytes: input.maxSnapshotBytes }),
|
||||
...(input.maxRepresentationBytes === undefined
|
||||
? {}
|
||||
: {
|
||||
max_metadata_representation_bytes: input.maxRepresentationBytes,
|
||||
}),
|
||||
},
|
||||
result: inspection,
|
||||
rawResult: null,
|
||||
limitations: inspection.limitations,
|
||||
@@ -223,11 +242,7 @@ const createManagedMemberComparisonEvidence = (
|
||||
left: Evidence,
|
||||
right: Evidence,
|
||||
result: ManagedMemberComparisonResult,
|
||||
sourcePaths?: {
|
||||
readonly leftPath: string;
|
||||
readonly rightPath: string;
|
||||
readonly typeNames?: readonly string[];
|
||||
},
|
||||
pathRequest?: ManagedMemberComparisonPathInput,
|
||||
): Evidence =>
|
||||
createEvidence(undefined, MANAGED_WORKFLOW_PROVIDER, {
|
||||
predicateType: "rea.managed-member-comparison",
|
||||
@@ -235,15 +250,24 @@ const createManagedMemberComparisonEvidence = (
|
||||
parameters: {
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: right.evidence_id,
|
||||
...(sourcePaths === undefined
|
||||
...(pathRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
left_path: sourcePaths.leftPath,
|
||||
right_path: sourcePaths.rightPath,
|
||||
left_path: pathRequest.leftPath,
|
||||
right_path: pathRequest.rightPath,
|
||||
}),
|
||||
...(sourcePaths?.typeNames === undefined
|
||||
...(pathRequest?.typeNames === undefined
|
||||
? {}
|
||||
: { type_names: [...sourcePaths.typeNames] }),
|
||||
: { type_names: [...pathRequest.typeNames] }),
|
||||
...(pathRequest?.maxSnapshotBytes === undefined
|
||||
? {}
|
||||
: { max_snapshot_bytes: pathRequest.maxSnapshotBytes }),
|
||||
...(pathRequest?.maxRepresentationBytes === undefined
|
||||
? {}
|
||||
: {
|
||||
max_metadata_representation_bytes:
|
||||
pathRequest.maxRepresentationBytes,
|
||||
}),
|
||||
},
|
||||
result,
|
||||
rawResult: null,
|
||||
@@ -252,11 +276,11 @@ const createManagedMemberComparisonEvidence = (
|
||||
environment: null,
|
||||
limitations: result.limitations,
|
||||
locations:
|
||||
sourcePaths === undefined
|
||||
pathRequest === undefined
|
||||
? []
|
||||
: [
|
||||
{ kind: "artifact-path", path: sourcePaths.leftPath },
|
||||
{ kind: "artifact-path", path: sourcePaths.rightPath },
|
||||
{ kind: "artifact-path", path: pathRequest.leftPath },
|
||||
{ kind: "artifact-path", path: pathRequest.rightPath },
|
||||
],
|
||||
evidenceLinks: result.evidence_links,
|
||||
});
|
||||
|
||||
@@ -28,6 +28,8 @@ import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
|
||||
DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES,
|
||||
MAX_REVERSE_COMMAND_OUTPUT_BYTES,
|
||||
MAX_REVERSE_COMMAND_TIMEOUT_MS,
|
||||
objdumpInputSchema,
|
||||
rizinInputSchema,
|
||||
@@ -88,10 +90,16 @@ interface CommandLaunchOutcome {
|
||||
succeeded: number;
|
||||
}
|
||||
|
||||
const MAX_COMBINED_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
export const REVERSE_COMMAND_OUTPUT_LIMITATION = `REA stopped collecting output at its ${String(MAX_COMBINED_OUTPUT_BYTES)}-byte cap and requested termination of the provider process; the captured stdout and stderr are a prefix and command completion is unknown. Narrow the command or page its output.`;
|
||||
// Eight concurrent captures bound retained provider output to 128 MiB.
|
||||
const reverseCommandOutputLimitation = (
|
||||
bytes: number,
|
||||
source: "default" | "request",
|
||||
): string =>
|
||||
`REA stopped collecting output at max_output_bytes=${String(bytes)} bytes (source ${source}, default ${String(DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES)}, range 1..${String(MAX_REVERSE_COMMAND_OUTPUT_BYTES)}) and requested termination of the provider process; captured stdout and stderr are a prefix and command completion is unknown. Narrow or page the provider command, or increase max_output_bytes (--max-output-bytes on the CLI) for the next call; no restart is required. Confirm command effects and cleanup before deciding whether it is safe to repeat. Client receive limits are separate.`;
|
||||
// Bound simultaneous provider process families independently of output admission.
|
||||
const MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS = 8;
|
||||
const MAX_ACTIVE_CAPTURE_BYTES =
|
||||
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS *
|
||||
DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES;
|
||||
|
||||
export interface ReverseEngineeringServiceOptions {
|
||||
readonly environment?: Readonly<NodeJS.ProcessEnv>;
|
||||
@@ -140,6 +148,17 @@ export const resolveRizinCommandRequest = (
|
||||
);
|
||||
};
|
||||
|
||||
/** One accepted command, including the controls retained through admission and cleanup. */
|
||||
interface ReverseCommandObservation {
|
||||
readonly operation: ReverseEngineeringOperation;
|
||||
readonly profile: ReverseEngineeringProviderCommand;
|
||||
readonly path: string | undefined;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly timeoutMs: number;
|
||||
readonly outputBudgetBytes: number;
|
||||
}
|
||||
|
||||
/** Shared application workflow for caller-selected local analysis commands. */
|
||||
export class ReverseEngineeringService {
|
||||
readonly #environment: Readonly<NodeJS.ProcessEnv>;
|
||||
@@ -159,6 +178,7 @@ export class ReverseEngineeringService {
|
||||
AbortController,
|
||||
Promise<Result<Evidence, AnalysisError>>
|
||||
>();
|
||||
#reservedOutputBytes = 0;
|
||||
#closing = false;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
#dispatched = 0;
|
||||
@@ -297,6 +317,7 @@ export class ReverseEngineeringService {
|
||||
const {
|
||||
detail,
|
||||
command_timeout_ms: commandTimeoutMs,
|
||||
max_output_bytes: maxOutputBytes,
|
||||
...input
|
||||
} = parsed.value;
|
||||
if (detail === "summary") {
|
||||
@@ -314,14 +335,17 @@ export class ReverseEngineeringService {
|
||||
} else parameters = input;
|
||||
if (commandTimeoutMs !== undefined)
|
||||
parameters = { ...parameters, command_timeout_ms: commandTimeoutMs };
|
||||
const observed = await this.#observe(
|
||||
"inspect_with_objdump",
|
||||
command,
|
||||
input.operation === "architectures" ? undefined : input.path,
|
||||
if (maxOutputBytes !== undefined)
|
||||
parameters = { ...parameters, max_output_bytes: maxOutputBytes };
|
||||
const observed = await this.#observe({
|
||||
operation: "inspect_with_objdump",
|
||||
profile: command,
|
||||
path: input.operation === "architectures" ? undefined : input.path,
|
||||
parameters,
|
||||
options.signal,
|
||||
commandTimeoutMs ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
|
||||
);
|
||||
signal: options.signal,
|
||||
timeoutMs: commandTimeoutMs ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
|
||||
outputBudgetBytes: maxOutputBytes ?? DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES,
|
||||
});
|
||||
return observed.ok && detail === "summary"
|
||||
? summarizeRetainedAnalysis(observed.value, retention)
|
||||
: observed;
|
||||
@@ -342,26 +366,27 @@ export class ReverseEngineeringService {
|
||||
request: RizinInput,
|
||||
options: { readonly signal?: AbortSignal } = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const { command_timeout_ms: commandTimeoutMs, ...input } = request;
|
||||
const {
|
||||
command_timeout_ms: commandTimeoutMs,
|
||||
max_output_bytes: maxOutputBytes,
|
||||
...input
|
||||
} = request;
|
||||
const command = this.#commands.rizin(input);
|
||||
return this.#observe(
|
||||
"execute_rizin_command",
|
||||
command,
|
||||
input.path,
|
||||
commandTimeoutMs === undefined ? input : request,
|
||||
options.signal,
|
||||
commandTimeoutMs ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
|
||||
);
|
||||
return this.#observe({
|
||||
operation: "execute_rizin_command",
|
||||
profile: command,
|
||||
path: input.path,
|
||||
parameters: request,
|
||||
signal: options.signal,
|
||||
timeoutMs: commandTimeoutMs ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
|
||||
outputBudgetBytes: maxOutputBytes ?? DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
#observe(
|
||||
operation: ReverseEngineeringOperation,
|
||||
profile: ReverseEngineeringProviderCommand,
|
||||
path: string | undefined,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
signal: AbortSignal | undefined,
|
||||
timeoutMs: number,
|
||||
request: ReverseCommandObservation,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const { operation, signal, outputBudgetBytes } = request;
|
||||
if (signal?.aborted)
|
||||
return Promise.resolve(
|
||||
err(new AnalysisCancelledError(operation, { cause: signal.reason })),
|
||||
@@ -377,21 +402,26 @@ export class ReverseEngineeringService {
|
||||
);
|
||||
if (
|
||||
this.#activeOperations.size >=
|
||||
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS
|
||||
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS ||
|
||||
this.#reservedOutputBytes + outputBudgetBytes > MAX_ACTIVE_CAPTURE_BYTES
|
||||
)
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"transport",
|
||||
`Concurrent reverse-engineering operation capacity reached (${String(MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS)} operations). This release has no runtime override.`,
|
||||
`Reverse-engineering capture capacity reached (${String(MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS)} operations or ${String(MAX_ACTIVE_CAPTURE_BYTES)} reserved output bytes).`,
|
||||
{
|
||||
max_concurrent_operations:
|
||||
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS,
|
||||
active_operations: this.#activeOperations.size,
|
||||
max_active_capture_bytes: MAX_ACTIVE_CAPTURE_BYTES,
|
||||
reserved_output_bytes: this.#reservedOutputBytes,
|
||||
requested_output_bytes: outputBudgetBytes,
|
||||
},
|
||||
{
|
||||
remediationAction: `Wait for an active objdump or rizin command to finish, then retry. This capacity of ${String(MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS)} operations has no runtime override, and command_timeout_ms does not raise it.`,
|
||||
retryable: true,
|
||||
remediationAction: `Wait for active objdump or rizin work to finish, then retry, or lower max_output_bytes to fit the ${String(MAX_ACTIVE_CAPTURE_BYTES)}-byte aggregate capture admission. This live capacity has no runtime override; command_timeout_ms does not raise it. No restart is required.`,
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -406,30 +436,32 @@ export class ReverseEngineeringService {
|
||||
signal === undefined || signal instanceof AbortSignal
|
||||
? controller.signal
|
||||
: signal;
|
||||
const running = this.#observeProvider(
|
||||
operation,
|
||||
profile,
|
||||
path,
|
||||
parameters,
|
||||
operationSignal,
|
||||
timeoutMs,
|
||||
);
|
||||
this.#reservedOutputBytes += outputBudgetBytes;
|
||||
const running = this.#observeProvider({
|
||||
...request,
|
||||
signal: operationSignal,
|
||||
});
|
||||
const tracked = running.finally(() => {
|
||||
signal?.removeEventListener("abort", relayAbort);
|
||||
this.#activeOperations.delete(controller);
|
||||
this.#reservedOutputBytes -= outputBudgetBytes;
|
||||
});
|
||||
this.#activeOperations.set(controller, tracked);
|
||||
return tracked;
|
||||
}
|
||||
|
||||
async #observeProvider(
|
||||
operation: ReverseEngineeringOperation,
|
||||
profile: ReverseEngineeringProviderCommand,
|
||||
path: string | undefined,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
signal: AbortSignal | undefined,
|
||||
timeoutMs: number,
|
||||
request: ReverseCommandObservation,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const {
|
||||
operation,
|
||||
profile,
|
||||
path,
|
||||
parameters,
|
||||
signal,
|
||||
timeoutMs,
|
||||
outputBudgetBytes,
|
||||
} = request;
|
||||
const { executable: command, arguments: args } = profile;
|
||||
if (signal?.aborted)
|
||||
return err(
|
||||
@@ -540,7 +572,7 @@ export class ReverseEngineeringService {
|
||||
signal,
|
||||
timeout: timeoutMs,
|
||||
stopSignal: "SIGTERM",
|
||||
maxBuffer: MAX_COMBINED_OUTPUT_BYTES,
|
||||
maxBuffer: outputBudgetBytes,
|
||||
});
|
||||
stdout = output.stdout;
|
||||
stderr = output.stderr;
|
||||
@@ -718,8 +750,6 @@ export class ReverseEngineeringService {
|
||||
: { cleanupOwner: darwinFailure.cleanupOwner }),
|
||||
});
|
||||
} else {
|
||||
const provider =
|
||||
operation === "inspect_with_objdump" ? "objdump" : "rizin";
|
||||
const setting =
|
||||
operation === "inspect_with_objdump"
|
||||
? "REA_OBJDUMP_COMMAND"
|
||||
@@ -994,11 +1024,15 @@ export class ReverseEngineeringService {
|
||||
: digestAfter === null || digest === undefined
|
||||
? null
|
||||
: digestAfter !== digest;
|
||||
const outputBudgetSource =
|
||||
parameters.max_output_bytes === undefined ? "default" : "request";
|
||||
const result = {
|
||||
stdout,
|
||||
stderr,
|
||||
exit_code: exitCode,
|
||||
signal: signalName,
|
||||
output_budget_bytes: outputBudgetBytes,
|
||||
output_budget_source: outputBudgetSource,
|
||||
output_truncated: outputTruncated,
|
||||
completion_status: completionStatus,
|
||||
artifact_sha256_after: absolutePath === undefined ? null : digestAfter,
|
||||
@@ -1043,7 +1077,12 @@ export class ReverseEngineeringService {
|
||||
]
|
||||
: []),
|
||||
...(outputLimitReached
|
||||
? [REVERSE_COMMAND_OUTPUT_LIMITATION]
|
||||
? [
|
||||
reverseCommandOutputLimitation(
|
||||
outputBudgetBytes,
|
||||
outputBudgetSource,
|
||||
),
|
||||
]
|
||||
: outputTruncated
|
||||
? [
|
||||
"Captured provider output is partial because bytes were omitted; process completion is reported separately.",
|
||||
@@ -1092,6 +1131,9 @@ export class ReverseEngineeringService {
|
||||
...(absolutePath === undefined
|
||||
? {
|
||||
operation: "architectures",
|
||||
...(typeof parameters.max_output_bytes === "number"
|
||||
? { max_output_bytes: parameters.max_output_bytes }
|
||||
: {}),
|
||||
...(typeof parameters.command_timeout_ms === "number"
|
||||
? { command_timeout_ms: parameters.command_timeout_ms }
|
||||
: {}),
|
||||
@@ -1212,7 +1254,8 @@ const runOwnedCommandOutput =
|
||||
},
|
||||
{
|
||||
timeoutMs: options.timeout ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
|
||||
diagnosticBytes: MAX_COMBINED_OUTPUT_BYTES,
|
||||
diagnosticBytes:
|
||||
options.maxBuffer ?? DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES,
|
||||
acceptNonZeroExit: true,
|
||||
},
|
||||
{ signal: options.signal },
|
||||
@@ -1349,7 +1392,7 @@ const reverseCommandTimeoutGuidance = (
|
||||
timeoutMs < MAX_REVERSE_COMMAND_TIMEOUT_MS
|
||||
? `Increase command_timeout_ms above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_REVERSE_COMMAND_TIMEOUT_MS)}; omitted means ${String(DEFAULT_REVERSE_COMMAND_TIMEOUT_MS)}), or use --command-timeout-ms on the CLI.`
|
||||
: `command_timeout_ms is already at the maximum ${String(MAX_REVERSE_COMMAND_TIMEOUT_MS)} ms; no higher deadline is supported.`
|
||||
} The new value applies on the next call; no restart is required. The ${String(MAX_COMBINED_OUTPUT_BYTES)} byte (16 MiB) combined output cap has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
|
||||
} The new value applies on the next call; no restart is required. The combined output allowance is separately selected by max_output_bytes (default ${String(DEFAULT_REVERSE_COMMAND_OUTPUT_BYTES)} bytes). Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
|
||||
});
|
||||
|
||||
export const digestFile = async (
|
||||
|
||||
@@ -20,6 +20,18 @@ it.each([
|
||||
path: "/module",
|
||||
command_timeout_ms,
|
||||
})),
|
||||
...[
|
||||
"max_input_bytes",
|
||||
"max_tool_bytes",
|
||||
"max_output_bytes",
|
||||
"max_interface_bytes",
|
||||
"max_artifact_paths",
|
||||
].flatMap((name) =>
|
||||
[0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, "1000", null].map((value) => ({
|
||||
path: "/module",
|
||||
[name]: value,
|
||||
})),
|
||||
),
|
||||
])("rejects invalid selection before effects: %j", async (input) => {
|
||||
const service = new WasmArtifactService({
|
||||
close: () => Promise.resolve(),
|
||||
@@ -52,19 +64,22 @@ it("preserves the selected command budget in provider input and Evidence", async
|
||||
expect(result.value.normalized_result).toEqual(value);
|
||||
});
|
||||
|
||||
it("rejects a provider report that silently changes the selected command budget", async () => {
|
||||
const value = wasmArtifactFixture();
|
||||
const service = new WasmArtifactService({
|
||||
close: () => Promise.resolve(),
|
||||
inspect: async () => ok(wasmArtifactExecution(value)),
|
||||
});
|
||||
expect(
|
||||
await service.inspect({
|
||||
path: value.artifact.path,
|
||||
command_timeout_ms: 42_000,
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
|
||||
});
|
||||
it.each([{ command_timeout_ms: 42_000 }, { max_output_bytes: 1024 }])(
|
||||
"rejects a provider report that silently changes the selected budget: %j",
|
||||
async (selection) => {
|
||||
const value = wasmArtifactFixture();
|
||||
const service = new WasmArtifactService({
|
||||
close: () => Promise.resolve(),
|
||||
inspect: async () => ok(wasmArtifactExecution(value)),
|
||||
});
|
||||
expect(
|
||||
await service.inspect({
|
||||
path: value.artifact.path,
|
||||
...selection,
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
|
||||
},
|
||||
);
|
||||
it.each(["path", "subject-path", "digest", "wat", "candidates", "glue"])(
|
||||
"rejects mismatched upstream observation: %s",
|
||||
async (problem) => {
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
import type { AnalysisSettingsReader } from "../../domain/analysisSettings.js";
|
||||
import { constants as bufferConstants } from "node:buffer";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import { createAnalysisExecutionEvidence } from "../../domain/analysisObservation.js";
|
||||
import {
|
||||
analysisExecutionEnvelopeForAdmission,
|
||||
createAnalysisExecutionEvidence,
|
||||
} from "../../domain/analysisObservation.js";
|
||||
import type { WasmArtifactPort } from "./WasmArtifactPort.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisOutputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
inspectWasmArtifactInputSchema,
|
||||
wasmArtifactSchema,
|
||||
wasmArtifactMatchesSubject,
|
||||
DEFAULT_WASM_COMMAND_TIMEOUT_MS,
|
||||
DEFAULT_WASM_ARTIFACT_PATHS,
|
||||
MAX_WASM_ARTIFACT_PATHS,
|
||||
wasmResourceLimits,
|
||||
} from "../../domain/wasm/wasmArtifact.js";
|
||||
import { err, type Result } from "../../domain/result.js";
|
||||
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
|
||||
import { parseAnalysisInput } from "../AnalysisInput.js";
|
||||
import { requireAuthenticationHeadroom } from "../JsonAuthenticationHeadroom.js";
|
||||
|
||||
const OPERATION = "inspect_wasm_artifact";
|
||||
|
||||
@@ -41,6 +52,32 @@ export class WasmArtifactService {
|
||||
options?.signal,
|
||||
);
|
||||
if (!input.ok) return input;
|
||||
const maximumPaths =
|
||||
input.value.max_artifact_paths ?? DEFAULT_WASM_ARTIFACT_PATHS;
|
||||
for (const field of ["glue_paths", "candidate_paths"] as const) {
|
||||
if (input.value[field].length > maximumPaths)
|
||||
return err(
|
||||
new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"capacity",
|
||||
`${field} exceeds max_artifact_paths (${String(maximumPaths)} paths)`,
|
||||
{
|
||||
maximum_paths: maximumPaths,
|
||||
default_paths: DEFAULT_WASM_ARTIFACT_PATHS,
|
||||
source:
|
||||
input.value.max_artifact_paths === undefined
|
||||
? "default"
|
||||
: "request",
|
||||
selected_paths: input.value[field].length,
|
||||
input_field: field,
|
||||
},
|
||||
{
|
||||
retryable: false,
|
||||
remediationAction: `Raise max_artifact_paths to at least ${String(input.value[field].length)} (maximum ${String(MAX_WASM_ARTIFACT_PATHS)}), or use --max-artifact-paths on the CLI; then retry the same selection. The value applies on the next inspection without restart. File and command byte budgets remain independent.`,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
const timeout =
|
||||
input.value.command_timeout_ms ??
|
||||
this.settings?.().overrides["wasm.command_timeout_ms"] ??
|
||||
@@ -51,12 +88,29 @@ export class WasmArtifactService {
|
||||
});
|
||||
if (!inspected.ok) return inspected;
|
||||
const execution = inspected.value;
|
||||
const admission = requireAuthenticationHeadroom(
|
||||
analysisExecutionEnvelopeForAdmission(
|
||||
OPERATION,
|
||||
input.value,
|
||||
execution,
|
||||
"observed",
|
||||
),
|
||||
{
|
||||
operation: OPERATION,
|
||||
path: input.value.path,
|
||||
description: "Complete WASM Evidence cannot be assembled",
|
||||
serializedCodeUnitLimit: bufferConstants.MAX_STRING_LENGTH,
|
||||
},
|
||||
);
|
||||
if (!admission.ok) return admission;
|
||||
const report = wasmArtifactSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.value.path ||
|
||||
execution.subject.path !== input.value.path ||
|
||||
report.data.tool_profile.timeout_ms !== timeout ||
|
||||
report.data.tool_profile.output_budget_bytes !==
|
||||
wasmResourceLimits(input.value).outputBytes ||
|
||||
!wasmArtifactMatchesSubject(report.data.artifact, execution.subject) ||
|
||||
JSON.stringify(report.data.glue.map((item) => item.artifact.path)) !==
|
||||
JSON.stringify(input.value.glue_paths) ||
|
||||
|
||||
@@ -6,11 +6,7 @@ import { wasmInterfaceComparisonSchema } from "../../contracts/wasm/wasmComparis
|
||||
import { compareWasmInterfaces } from "./WasmInterfaceComparisonService.js";
|
||||
import { retainAnalysisResultSources } from "../investigation/recordEvidenceSources.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
import {
|
||||
WASM_INTERFACE_REPRESENTATION_BYTES,
|
||||
wasmInterfaceEntryRepresentationBytes,
|
||||
type WasmInterface,
|
||||
} from "../../domain/wasm/wasmInterface.js";
|
||||
import type { WasmInterface } from "../../domain/wasm/wasmInterface.js";
|
||||
import { wasmArtifactFixture } from "../../../tests/fixtures/wasm/artifact.js";
|
||||
|
||||
const facts = (
|
||||
@@ -240,69 +236,43 @@ it("resolves exact retained references and permits cancellation between comparis
|
||||
expect(cancelled.error.partialObservation).toBeUndefined();
|
||||
});
|
||||
|
||||
/** One inventory under the comparison cap; two of them exceed it together. */
|
||||
const admittedInventory = (label: string): WasmInterface => {
|
||||
const base = facts(label).entries[0]!;
|
||||
const minimum = Math.floor(WASM_INTERFACE_REPRESENTATION_BYTES / 2) + 4096;
|
||||
let low = 0;
|
||||
let high = 4_000_000;
|
||||
let best = 0;
|
||||
while (low <= high) {
|
||||
const mid = Math.floor((low + high) / 2);
|
||||
const name = `${label}-${"n".repeat(mid)}`;
|
||||
const bytes = wasmInterfaceEntryRepresentationBytes({
|
||||
...base,
|
||||
name,
|
||||
wat_form: `(export "${name}" (func 0))`,
|
||||
});
|
||||
if (bytes >= minimum) {
|
||||
best = mid;
|
||||
high = mid - 1;
|
||||
} else low = mid + 1;
|
||||
}
|
||||
const name = `${label}-${"n".repeat(best)}`;
|
||||
const entry = {
|
||||
...base,
|
||||
name,
|
||||
wat_form: `(export "${name}" (func 0))`,
|
||||
};
|
||||
const bytes = wasmInterfaceEntryRepresentationBytes(entry);
|
||||
if (
|
||||
bytes >= WASM_INTERFACE_REPRESENTATION_BYTES ||
|
||||
bytes + 512 >= WASM_INTERFACE_REPRESENTATION_BYTES
|
||||
)
|
||||
throw new Error("Sized inventory is not individually admitted");
|
||||
return { state: "complete", issues: [], entries: [entry] };
|
||||
};
|
||||
|
||||
it("refuses two admitted inventories that together exceed the comparison cap", async () => {
|
||||
const left = admittedInventory("left");
|
||||
const right = admittedInventory("right");
|
||||
const empty: WasmInterface = { state: "complete", issues: [], entries: [] };
|
||||
it("admits each selected inventory independently and recovers a combined comparison with more capacity", async () => {
|
||||
const left = evidence(facts("left"));
|
||||
const right = evidence(facts("right"));
|
||||
const empty = evidence({ state: "complete", issues: [], entries: [] });
|
||||
const alone = await compareWasmInterfaces({
|
||||
left: evidence(left),
|
||||
right: evidence(empty),
|
||||
left,
|
||||
right: empty,
|
||||
scope: "both",
|
||||
max_interface_bytes: 2048,
|
||||
});
|
||||
expect(alone.ok).toBe(true);
|
||||
const selected = { left, right, scope: "both" as const };
|
||||
const combined = await compareWasmInterfaces({
|
||||
left: evidence(left),
|
||||
right: evidence(right),
|
||||
scope: "both",
|
||||
...selected,
|
||||
max_interface_bytes: 2048,
|
||||
});
|
||||
if (combined.ok) throw new Error("Expected comparison allowance refusal");
|
||||
if (combined.ok)
|
||||
throw new Error("Expected combined comparison capacity refusal");
|
||||
const projected = projectAnalysisError(combined.error);
|
||||
expect(projected.retryable).toBe(false);
|
||||
expect(projected.code).toBe("resource_constraint");
|
||||
expect(combined.error).toMatchObject({ resource: "capacity" });
|
||||
expect(projected.remediation.action).toContain(
|
||||
"The WASM interface comparison inventory",
|
||||
);
|
||||
expect(projected.remediation.action).toContain("fixed byte allowance");
|
||||
expect(projected.remediation.action).not.toContain("fixed count");
|
||||
expect(projected.remediation.action).not.toMatch(
|
||||
/Wait for an active analysis/u,
|
||||
);
|
||||
expect(projected).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
retryable: false,
|
||||
details: { reported_limits: { maximum_bytes: 2048, source: "request" } },
|
||||
});
|
||||
expect(projected.remediation.action).toContain("max_interface_bytes");
|
||||
const recovered = await compareWasmInterfaces({
|
||||
...selected,
|
||||
max_interface_bytes: 8192,
|
||||
});
|
||||
if (!recovered.ok) throw recovered.error;
|
||||
expect(recovered.value.evidence.normalized_result).toMatchObject({
|
||||
coverage: "complete-within-inputs",
|
||||
summary: { added: 1, removed: 1 },
|
||||
});
|
||||
expect(recovered.value.evidence.parameters).toMatchObject({
|
||||
max_interface_bytes: 8192,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import {
|
||||
WASM_INTERFACE_REPRESENTATION_BYTES,
|
||||
wasmInterfaceEntryRepresentationBytes,
|
||||
} from "../../domain/wasm/wasmInterface.js";
|
||||
import { wasmInterfaceEntryRepresentationBytes } from "../../domain/wasm/wasmInterface.js";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
import { constants as bufferConstants } from "node:buffer";
|
||||
import { requireAuthenticationHeadroom } from "../JsonAuthenticationHeadroom.js";
|
||||
import { ARTIFACT_COMPARISON_PROVIDER } from "../../domain/comparisonEvidenceIdentity.js";
|
||||
import {
|
||||
compareWasmInterfacesInputSchema,
|
||||
wasmInterfaceComparisonSchema,
|
||||
} from "../../contracts/wasm/wasmComparisonContracts.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
createEvidence,
|
||||
evidenceEnvelopeForAdmission,
|
||||
type Evidence,
|
||||
} from "../../domain/evidence.js";
|
||||
import {
|
||||
wasmArtifactSchema,
|
||||
wasmArtifactMatchesSubject,
|
||||
@@ -18,9 +21,8 @@ import type { WasmInterfaceEntry } from "../../domain/wasm/wasmInterface.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js";
|
||||
import { WasmInterfaceBudget } from "../../domain/wasm/wasmInterfaceBudget.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
@@ -131,6 +133,10 @@ export const compareWasmInterfaces = async (
|
||||
entry: WasmInterfaceEntry;
|
||||
}
|
||||
>();
|
||||
const budget = new WasmInterfaceBudget(
|
||||
resolved.value.input.max_interface_bytes,
|
||||
OPERATION,
|
||||
);
|
||||
let work = 0;
|
||||
for (const [side, inspection] of [
|
||||
["left", left],
|
||||
@@ -142,9 +148,11 @@ export const compareWasmInterfaces = async (
|
||||
assertActive();
|
||||
}
|
||||
if (!selected(entry)) continue;
|
||||
budget.reserve(wasmInterfaceEntryRepresentationBytes(entry));
|
||||
const key = JSON.stringify([entry.direction, entry.module, entry.name]);
|
||||
let group = groups.get(key);
|
||||
if (group === undefined) {
|
||||
budget.reserve(512);
|
||||
group = { left: [], right: [], entry };
|
||||
groups.set(key, group);
|
||||
}
|
||||
@@ -162,29 +170,7 @@ export const compareWasmInterfaces = async (
|
||||
unchanged: 0,
|
||||
unknown: 0,
|
||||
};
|
||||
let remaining = WASM_INTERFACE_REPRESENTATION_BYTES;
|
||||
for (const group of groups.values()) {
|
||||
remaining -=
|
||||
512 +
|
||||
group.left.reduce(
|
||||
(sum, entry) => sum + wasmInterfaceEntryRepresentationBytes(entry),
|
||||
0,
|
||||
) +
|
||||
group.right.reduce(
|
||||
(sum, entry) => sum + wasmInterfaceEntryRepresentationBytes(entry),
|
||||
0,
|
||||
);
|
||||
if (remaining < 0)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"capacity",
|
||||
"WASM comparison exceeds typed interface representation capacity",
|
||||
{ maximum_bytes: WASM_INTERFACE_REPRESENTATION_BYTES },
|
||||
fixedAllowanceOptions(
|
||||
"The WASM interface comparison inventory",
|
||||
"bytes",
|
||||
),
|
||||
);
|
||||
if (++work % 256 === 0) {
|
||||
await setImmediate();
|
||||
assertActive();
|
||||
@@ -251,7 +237,7 @@ export const compareWasmInterfaces = async (
|
||||
"Exact declared interface equality is not runtime/ABI compatibility, successful linking or original-source identity.",
|
||||
"Typed facts come from the selected validated WABT decoding; unsupported signature semantics and duplicate names remain unknown.",
|
||||
];
|
||||
const report = wasmInterfaceComparisonSchema.parse({
|
||||
const observedReport = {
|
||||
left: {
|
||||
evidence_id: left.evidence.evidence_id,
|
||||
artifact: left.result.artifact,
|
||||
@@ -265,20 +251,42 @@ export const compareWasmInterfaces = async (
|
||||
changes,
|
||||
summary,
|
||||
limitations,
|
||||
});
|
||||
const evidence = createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
|
||||
};
|
||||
const observation = {
|
||||
operation: OPERATION,
|
||||
predicateType: "rea.wasm-interface-comparison",
|
||||
parameters: {
|
||||
left_evidence_id: left.evidence.evidence_id,
|
||||
right_evidence_id: right.evidence.evidence_id,
|
||||
scope,
|
||||
...(resolved.value.input.max_interface_bytes === undefined
|
||||
? {}
|
||||
: { max_interface_bytes: resolved.value.input.max_interface_bytes }),
|
||||
},
|
||||
result: report,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
result: observedReport,
|
||||
confidence: "derived" as const,
|
||||
authority: "analyst-inference" as const,
|
||||
limitations,
|
||||
evidenceLinks: [left.evidence.evidence_id, right.evidence.evidence_id],
|
||||
};
|
||||
const admission = requireAuthenticationHeadroom(
|
||||
evidenceEnvelopeForAdmission(
|
||||
undefined,
|
||||
ARTIFACT_COMPARISON_PROVIDER,
|
||||
observation,
|
||||
),
|
||||
{
|
||||
operation: OPERATION,
|
||||
path: "selected WASM Evidence",
|
||||
description: "Complete WASM comparison Evidence cannot be assembled",
|
||||
serializedCodeUnitLimit: bufferConstants.MAX_STRING_LENGTH,
|
||||
},
|
||||
);
|
||||
if (!admission.ok) return admission;
|
||||
const report = wasmInterfaceComparisonSchema.parse(observedReport);
|
||||
const evidence = createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
|
||||
...observation,
|
||||
result: report,
|
||||
});
|
||||
await setImmediate();
|
||||
const completed = completeProviderEvidence(evidence, options?.signal);
|
||||
|
||||
Reference in new issue
Block a user