diff --git a/src/config/bridgeMaxRequestBytes.ts b/src/config/bridgeMaxRequestBytes.ts index e2451dd96d..c56f66a734 100644 --- a/src/config/bridgeMaxRequestBytes.ts +++ b/src/config/bridgeMaxRequestBytes.ts @@ -131,7 +131,7 @@ const limitFacts = ( export const bridgeRequestOversizeError = ( operation: string, limit: BridgeMaxRequestBytes, - payloadBytes: number, + payload: number | { readonly bytesAtLeast: number }, peer: BridgePeer, ): AnalysisResourceConstraintError => { const recovery = bridgeMaxRequestBytesRecovery(limit, peer); @@ -143,7 +143,12 @@ export const bridgeRequestOversizeError = ( operation, "transport", `${refusal} ${recovery}`, - { ...limitFacts(limit), payload_bytes: payloadBytes }, + { + ...limitFacts(limit), + ...(typeof payload === "number" + ? { payload_bytes: payload } + : { payload_bytes_at_least: payload.bytesAtLeast }), + }, { remediationAction: recovery, retryable: false, diff --git a/src/cutter/CutterBridgeClient.ts b/src/cutter/CutterBridgeClient.ts index 0da1e2183e..a5ab669742 100644 --- a/src/cutter/CutterBridgeClient.ts +++ b/src/cutter/CutterBridgeClient.ts @@ -158,7 +158,7 @@ const serializeRequest = ( throw bridgeRequestOversizeError( "cutter_command", limit, - measured, + { bytesAtLeast: measured }, "Cutter", ); const requestBytes = JSON.stringify(requestValue); diff --git a/src/ghidra/GhidraClientWire.test.ts b/src/ghidra/GhidraClientWire.test.ts index bd092bc1dd..177ccb0f7b 100644 --- a/src/ghidra/GhidraClientWire.test.ts +++ b/src/ghidra/GhidraClientWire.test.ts @@ -71,6 +71,36 @@ const harness = ( }; }; +it("reports a lower bound for a request whose size scan stopped early", async () => { + const method = "search_strings"; + const params = { pattern: "x".repeat(32_768) }; + const maximum = 8_192; + const { wire, writes, pending } = harness(limit(maximum)); + const result = await wire.request(method, params, {}); + if (result.ok) throw new Error("Expected a request ceiling refusal"); + const cause = result.error.cause; + if (!(cause instanceof AnalysisResourceConstraintError)) + throw new Error("Expected a transport resource constraint"); + const facts = cause.reportedLimits; + const measured = facts?.payload_bytes_at_least; + if (typeof measured !== "number") + throw new Error("Missing request size lower bound"); + expect(measured).toBeGreaterThan(maximum); + expect(measured).toBeLessThan( + Buffer.byteLength( + JSON.stringify({ + id: 1, + token: "b".repeat(64), + method, + params, + }), + ), + ); + expect(facts).not.toHaveProperty("payload_bytes"); + expect(writes).toEqual([]); + expect(pending.size).toBe(0); +}); + it("admits the exact UTF-8 request boundary without changing reply ownership on refusal", async () => { const method = "search_strings"; const params = { pattern: 'å‰įž€"\\\u0000😀\ud800'.repeat(1024) }; @@ -118,7 +148,10 @@ it("admits the exact UTF-8 request boundary without changing reply ownership on AnalysisResourceConstraintError, ); expect(result.error.cause).toMatchObject({ - reportedLimits: { max_request_bytes: size - 1, payload_bytes: size }, + reportedLimits: { + max_request_bytes: size - 1, + payload_bytes_at_least: size, + }, retryable: false, }); expect( diff --git a/src/ghidra/GhidraClientWire.ts b/src/ghidra/GhidraClientWire.ts index 8415c45042..e57d154b68 100644 --- a/src/ghidra/GhidraClientWire.ts +++ b/src/ghidra/GhidraClientWire.ts @@ -140,14 +140,17 @@ export class GhidraWire { options.limits === undefined ? this.admitLimits() : ok(options.limits); if (!limits.ok) return limits; const { requestLimit, replyLimit } = limits.value; - const payloadBytes = jsonValueByteLength(payloadValue); + const payloadBytes = jsonValueByteLength( + payloadValue, + requestLimit.maximumBytes, + ); // Refuse before registering the operation and before any socket write, so // an oversized request never reaches the bridge or occupies a pending key. if (payloadBytes > requestLimit.maximumBytes) { const oversize = bridgeRequestOversizeError( method, requestLimit, - payloadBytes, + { bytesAtLeast: payloadBytes }, "Ghidra", ); return err( diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index ee9a2be821..7064bcbe84 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -1302,7 +1302,7 @@ export class HopperClient< bridgeRequestOversizeError( method, requestLimit.value, - measured, + { bytesAtLeast: measured }, "Hopper", ), ); diff --git a/src/hopper/HopperFileOffset.ts b/src/hopper/HopperFileOffset.ts index afa8e0216f..994484d764 100644 --- a/src/hopper/HopperFileOffset.ts +++ b/src/hopper/HopperFileOffset.ts @@ -412,7 +412,7 @@ async function readSourceSnapshot(file: FileHandle, signal?: AbortSignal) { signal, cancellationFailure: (reason) => new RegularFileOperationCancelled(reason), })) { - const bytes = Buffer.from(chunk); + const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); hash.update(bytes); if (size < prefix.length) bytes.copy(prefix, size, 0, Math.min(bytes.length, prefix.length - size)); diff --git a/src/hopper/HopperMachOImage.ts b/src/hopper/HopperMachOImage.ts index 33f15ca1f0..972578b09c 100644 --- a/src/hopper/HopperMachOImage.ts +++ b/src/hopper/HopperMachOImage.ts @@ -290,7 +290,7 @@ const inspectHopperMachOImage = async ( cancelledBy("open_binary", carriedReason(reason)), })) { if (signal?.aborted) return err(cancelledBy("open_binary", signal)); - const bytes = Buffer.from(chunk); + const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); hash.update(bytes); size += bytes.length; if (!Number.isSafeInteger(size)) diff --git a/src/process/capture/ProcessCaptureObservation.test.ts b/src/process/capture/ProcessCaptureObservation.test.ts index 58b70abf73..c5ae05e3c6 100644 --- a/src/process/capture/ProcessCaptureObservation.test.ts +++ b/src/process/capture/ProcessCaptureObservation.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { sep } from "node:path"; import { failedInspectionDescriptor } from "../../../tests/fixtures/processInspectionCleanup.js"; import { @@ -17,6 +18,8 @@ import { import { SamplingReadBatchFailure } from "./ProcessSamplingObservation.js"; import { TerminalRenderer } from "./TerminalRenderer.js"; import { processScenarioSchema } from "../../domain/process/processScenario.js"; +import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js"; +import type { ProcessFilesystemSnapshot } from "../../domain/process/processCapture.js"; import type { ProcessCapture } from "../../domain/process/processCaptureParsing.js"; import type { FilesystemCoverage, @@ -339,6 +342,63 @@ it.each(["symlink_not_followed", "observer_owned"] as const)( }, ); +it.each(["before", "after"] as const)( + "classifies absence against exact subtree coverage on the %s side", + (phase) => { + const paths = [ + `root_0:link${sep}child${sep}file`, + "root_0:observer", + `root_0:link-sibling${sep}file`, + ] as const; + const partial: ProcessFilesystemSnapshot = { + files: [], + completeRoots: ["root_0"], + truncated: true, + coverage: { + ...emptyFilesystemCoverage(), + unobserved_subtrees: [ + { path: "root_0:link", reason: "symlink_not_followed" }, + { path: "root_0:observer", reason: "observer_owned" }, + ], + }, + }; + const observed: ProcessFilesystemSnapshot = { + ...partial, + truncated: false, + coverage: { ...emptyFilesystemCoverage(), unobserved_subtrees: [] }, + files: paths.map((path) => ({ + path, + type: "file", + mode: 0o100644, + size: 1, + sha256: "a".repeat(64), + symlink_target: null, + })), + }; + const effects = + phase === "before" + ? classifyFilesystemEffects(partial, observed) + : classifyFilesystemEffects(observed, partial); + expect(effects).toHaveLength(paths.length); + const byPath = new Map(effects.map((effect) => [effect.path, effect])); + expect(byPath.get(paths[0])).toMatchObject({ + status: "unknown", + reason: expect.stringContaining( + `The ${phase} snapshot did not observe the subtree at root_0:link (symlink_not_followed)`, + ), + }); + expect(byPath.get(paths[1])).toMatchObject({ + status: "unknown", + reason: expect.stringContaining( + `The ${phase} snapshot did not observe the subtree at root_0:observer (observer_owned)`, + ), + }); + expect(byPath.get(paths[2])?.status).toBe( + phase === "before" ? "created" : "deleted", + ); + }, +); + it("records the PTY session-leader SIGHUP limitation on POSIX captures only", () => { const capture = emptyCapture(); const buildForPlatform = (platform: string) => diff --git a/src/process/capture/ProcessFilesystemEffects.ts b/src/process/capture/ProcessFilesystemEffects.ts index 3a533e3361..24f2f54152 100644 --- a/src/process/capture/ProcessFilesystemEffects.ts +++ b/src/process/capture/ProcessFilesystemEffects.ts @@ -4,27 +4,79 @@ import type { } from "../../domain/process/processCapture.js"; import { sep } from "node:path"; +type UnobservedSubtree = NonNullable< + ProcessFilesystemSnapshot["coverage"]["unobserved_subtrees"] +>[number]; + +interface IndexedAbsenceSnapshot { + readonly completeRoots: ReadonlySet; + readonly subtreesByPath: + | ReadonlyMap< + string, + { readonly subtree: UnobservedSubtree; readonly index: number } + > + | undefined; +} + +const indexAbsenceSnapshot = ( + snapshot: ProcessFilesystemSnapshot, +): IndexedAbsenceSnapshot => { + const subtrees = snapshot.coverage.unobserved_subtrees; + let subtreesByPath: + | Map< + string, + { readonly subtree: UnobservedSubtree; readonly index: number } + > + | undefined; + if (subtrees !== undefined) { + subtreesByPath = new Map(); + for (let index = 0; index < subtrees.length; index += 1) { + const subtree = subtrees[index]!; + if (!subtreesByPath.has(subtree.path)) + subtreesByPath.set(subtree.path, { subtree, index }); + } + } + return { + completeRoots: new Set(snapshot.completeRoots), + subtreesByPath, + }; +}; + const unobservedAbsenceReason = ( path: string, phase: "before" | "after", - snapshot: ProcessFilesystemSnapshot, + indexed: IndexedAbsenceSnapshot, ): string | undefined => { const alias = path.slice(0, path.indexOf(":")); - if (!snapshot.completeRoots.includes(alias)) + if (!indexed.completeRoots.has(alias)) return `The ${phase} snapshot did not exhaust path enumeration under ${alias}; absence remains unknown.`; const rootPath = `${alias}:.`; if (path === rootPath) return undefined; - if (snapshot.coverage.unobserved_subtrees === undefined) + const subtreesByPath = indexed.subtreesByPath; + if (subtreesByPath === undefined) return `The ${phase} snapshot has no subtree coverage facts; descendant absence remains unknown.`; - for (const subtree of snapshot.coverage.unobserved_subtrees) { - const below = - subtree.path === rootPath - ? path.startsWith(`${alias}:`) - : path.startsWith(`${subtree.path}${sep}`); - if (below || (subtree.reason === "observer_owned" && path === subtree.path)) - return `The ${phase} snapshot did not observe the subtree at ${subtree.path} (${subtree.reason}); descendant absence remains unknown.`; + if (subtreesByPath.size === 0) return undefined; + let best: + | { readonly subtree: UnobservedSubtree; readonly index: number } + | undefined; + const consider = ( + entry: + | { readonly subtree: UnobservedSubtree; readonly index: number } + | undefined, + ): void => { + if (entry !== undefined && (best === undefined || entry.index < best.index)) + best = entry; + }; + if (path.startsWith(`${alias}:`)) consider(subtreesByPath.get(rootPath)); + const exact = subtreesByPath.get(path); + if (exact?.subtree.reason === "observer_owned") consider(exact); + for (let cut = path.lastIndexOf(sep); cut !== -1;) { + consider(subtreesByPath.get(path.slice(0, cut))); + cut = cut > 0 ? path.lastIndexOf(sep, cut - 1) : -1; } - return undefined; + return best === undefined + ? undefined + : `The ${phase} snapshot did not observe the subtree at ${best.subtree.path} (${best.subtree.reason}); descendant absence remains unknown.`; }; /** Classify effects only from observed path absence, metadata, and content hashes. */ @@ -34,6 +86,8 @@ export const classifyFilesystemEffects = ( ): FilesystemCheckpoint["effects"] => { const beforeByPath = new Map(before.files.map((file) => [file.path, file])); const afterByPath = new Map(after.files.map((file) => [file.path, file])); + let beforeIndexed: IndexedAbsenceSnapshot | undefined; + let afterIndexed: IndexedAbsenceSnapshot | undefined; return [...new Set([...beforeByPath.keys(), ...afterByPath.keys()])] .sort() .map((path) => { @@ -41,9 +95,17 @@ export const classifyFilesystemEffects = ( const afterFile = afterByPath.get(path) ?? null; const reason = beforeFile === null - ? unobservedAbsenceReason(path, "before", before) + ? unobservedAbsenceReason( + path, + "before", + (beforeIndexed ??= indexAbsenceSnapshot(before)), + ) : afterFile === null - ? unobservedAbsenceReason(path, "after", after) + ? unobservedAbsenceReason( + path, + "after", + (afterIndexed ??= indexAbsenceSnapshot(after)), + ) : undefined; if (reason !== undefined) return { diff --git a/src/process/capture/ProcessSensitiveOutput.ts b/src/process/capture/ProcessSensitiveOutput.ts index a744df28be..54140bad09 100644 --- a/src/process/capture/ProcessSensitiveOutput.ts +++ b/src/process/capture/ProcessSensitiveOutput.ts @@ -80,7 +80,7 @@ const visibleUnits = function* (parts: readonly string[]) { ? "csi" : code === 0x5d ? "osc" - : [0x50, 0x58, 0x5e, 0x5f].includes(code) + : code === 0x50 || code === 0x58 || code === 0x5e || code === 0x5f ? "string" : code >= 0x20 && code <= 0x2f ? "intermediate" @@ -103,7 +103,7 @@ const visibleUnits = function* (parts: readonly string[]) { state = "osc"; continue; } - if ([0x90, 0x98, 0x9e, 0x9f].includes(code)) { + if (code === 0x90 || code === 0x98 || code === 0x9e || code === 0x9f) { state = "string"; continue; }