From d8a0e06c61b2295eeaedf0f43a89a781e678505d Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:28:07 -0500 Subject: [PATCH] perf(ida): avoid double full-binary SHA-256 re-hashing and redundant observation cloning (#13445) * perf(ida): avoid double full-binary SHA-256 re-hashing and redundant observation cloning * style(ida): format workspace thinning test * fix(ida): refresh cached stat after fallback digest and preserve 64 KiB copy boundary coverage --- src/ida/IdaSessionClient.ts | 19 ++++--- src/ida/IdaWorkspace.ts | 78 ++++++++++++++++++++++++++-- src/ida/IdaWorkspaceThinning.test.ts | 31 ++++++++++- 3 files changed, 113 insertions(+), 15 deletions(-) diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index 3d16596a92..33401e307b 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -23,7 +23,11 @@ import { AnalysisError } from "../domain/analysisErrorBase.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js"; -import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js"; +import { + jsonValueSchema, + ownedJsonValueSchema, + type JsonValue, +} from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; import type { IdaConfiguration } from "./IdaConfiguration.js"; import { IdaToolRejection, type IdaMcpConnection } from "./IdaMcpConnection.js"; @@ -69,11 +73,7 @@ import { rejectedOpenDatabaseSchema, supervisorOpenTimeoutSeconds, } from "./IdaProtocolValues.js"; -import { - idaFileDigest, - IdaWorkspace, - sameIdaHostPath, -} from "./IdaWorkspace.js"; +import { IdaWorkspace, sameIdaHostPath } from "./IdaWorkspace.js"; import { parseIdaInput } from "./IdaInput.js"; import { createEvidence } from "../domain/evidence.js"; import { @@ -933,14 +933,14 @@ export class IdaSessionClient implements AnalysisClient { upstream: this.connection.serverInfo(), metadata_before: metadataBefore, ...(metadataAfter === undefined ? {} : { metadata_after: metadataAfter }), - observations: jsonValueSchema.parse(runner.raw), + observations: ownedJsonValueSchema.parse(runner.raw), ...(this.#hexRaysOpenedBackend === undefined ? {} : { worker_backend: this.#hexRaysOpenedBackend }), ...(this.#healthObservations.length === 0 ? {} : { - health_observations: jsonValueSchema.parse( + health_observations: ownedJsonValueSchema.parse( this.#healthObservations, ), }), @@ -1009,8 +1009,7 @@ export class IdaSessionClient implements AnalysisClient { (metadata.input_sha256 != null && metadata.input_sha256.toLowerCase() !== this.#workspace.inputSha256) || - (await idaFileDigest(this.#workspace.inputPath)) !== - this.#workspace.inputSha256 + !(await this.#workspace.verifyInputUnchanged()) ) throw new IdaIdentityRefusal( "IDA headless input identity changed after target admission.", diff --git a/src/ida/IdaWorkspace.ts b/src/ida/IdaWorkspace.ts index dda1fb644e..bdec81eb58 100644 --- a/src/ida/IdaWorkspace.ts +++ b/src/ida/IdaWorkspace.ts @@ -1,8 +1,8 @@ import { createHash, randomUUID } from "node:crypto"; -import { createReadStream } from "node:fs"; +import fs, { type BigIntStats } from "node:fs"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; -import { open, realpath, stat, type FileHandle } from "node:fs/promises"; +import { lstat, open, realpath, stat, type FileHandle } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, isAbsolute, join, normalize } from "node:path"; import { @@ -25,7 +25,7 @@ import { errorMessage } from "../kernel/errorMessage.js"; /** Read a file digest with bounded memory rather than retaining binary bytes. */ export const idaFileDigest = async (path: string): Promise => { const hash = createHash("sha256"); - for await (const chunk of createReadStream(path)) hash.update(chunk); + for await (const chunk of fs.createReadStream(path)) hash.update(chunk); return hash.digest("hex"); }; @@ -51,9 +51,41 @@ export const resolveIdaWorkspaceParent = async ( * original. An IDA database target is copied whole, so the worker unpacks and * releases only the copy; the selected database is never opened for writing. */ +interface InputFileStat { + readonly dev: bigint; + readonly ino: bigint; + readonly size: bigint; + readonly mtimeNs: bigint; + readonly ctimeNs: bigint; +} + +const COPY_BUFFER_BYTES = 64 * 1024; + +const isRegularInputFile = (observed: BigIntStats): boolean => + observed.isFile() && !observed.isSymbolicLink(); + +const captureInputStat = (observed: BigIntStats): InputFileStat => ({ + dev: observed.dev, + ino: observed.ino, + size: observed.size, + mtimeNs: observed.mtimeNs, + ctimeNs: observed.ctimeNs, +}); + +const sameInputStat = ( + expected: InputFileStat, + observed: BigIntStats, +): boolean => + observed.dev === expected.dev && + observed.ino === expected.ino && + observed.size === expected.size && + observed.mtimeNs === expected.mtimeNs && + observed.ctimeNs === expected.ctimeNs; + export class IdaWorkspace { readonly sessionId = `rea-${randomUUID()}`; #inputSha256: string | undefined; + #inputStat: InputFileStat | undefined; readonly #files = new ArtifactResourceScope(); private constructor( private readonly runtime: PrivateRuntimeRoot, @@ -152,7 +184,7 @@ export class IdaWorkspace { : undefined; const sourceHash = createHash("sha256"); const inputHash = createHash("sha256"); - const chunk = Buffer.allocUnsafe(64 * 1024); + const chunk = Buffer.allocUnsafe(COPY_BUFFER_BYTES); let position = 0; for (;;) { assertArtifactReadActive(signal); @@ -194,7 +226,45 @@ export class IdaWorkspace { throw new AnalysisProtocolError( "IDA target changed between admission and the private input copy; reopen the target.", ); + const observed = await input.stat({ bigint: true }); this.#inputSha256 = inputHash.digest("hex"); + this.#inputStat = captureInputStat(observed); + } + + /** + * Confirm the private input still matches the bytes copyInput admitted. + * Avoids re-streaming large binaries through SHA-256 on every IDA RPC when + * the private file's stat identity is unchanged; falls back to a full digest + * whenever metadata differs or is unavailable, refreshing the recorded stat + * identity when the file remains unchanged around a matching digest read. + */ + async verifyInputUnchanged(): Promise { + if (this.#inputSha256 === undefined) return false; + const before = await lstat(this.inputPath, { bigint: true }).catch( + () => undefined, + ); + const expected = this.#inputStat; + if ( + expected !== undefined && + before !== undefined && + isRegularInputFile(before) && + sameInputStat(expected, before) + ) + return true; + if ((await idaFileDigest(this.inputPath)) !== this.#inputSha256) + return false; + if (before !== undefined && isRegularInputFile(before)) { + const after = await lstat(this.inputPath, { bigint: true }).catch( + () => undefined, + ); + if ( + after !== undefined && + isRegularInputFile(after) && + sameInputStat(captureInputStat(before), after) + ) + this.#inputStat = captureInputStat(after); + } + return true; } /** Delete only this object's privately allocated directory after worker cleanup. */ diff --git a/src/ida/IdaWorkspaceThinning.test.ts b/src/ida/IdaWorkspaceThinning.test.ts index 7f40c4148e..2c7ed4fd94 100644 --- a/src/ida/IdaWorkspaceThinning.test.ts +++ b/src/ida/IdaWorkspaceThinning.test.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; -import { open, readFile, rm, writeFile } from "node:fs/promises"; +import fs from "node:fs"; +import { open, readFile, rm, utimes, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -257,4 +258,32 @@ describe("IDA workspace admission identity", () => { expect(String(open?.args.input_path)).toContain("universal"); expect((await client.close()).ok).toBe(true); }); + + it("verifies unchanged private inputs via stat and refreshes stat after a metadata-only fallback", async () => { + const { root, target } = await createIdaTarget("arm64"); + roots.push(root); + const workspace = await IdaWorkspace.allocate(target); + roots.push(workspace.directory); + expect(await workspace.verifyInputUnchanged()).toBe(false); + await workspace.copyInput(); + const readStream = vi.spyOn(fs, "createReadStream"); + expect(await workspace.verifyInputUnchanged()).toBe(true); + expect(readStream).toHaveBeenCalledTimes(0); + // Touching timestamps forces one fallback digest and refreshes the cached stat. + const bumped = new Date(Date.now() + 5_000); + await utimes(workspace.inputPath, bumped, bumped); + expect(await workspace.verifyInputUnchanged()).toBe(true); + expect(readStream).toHaveBeenCalledTimes(1); + expect(await workspace.verifyInputUnchanged()).toBe(true); + expect(readStream).toHaveBeenCalledTimes(1); + // Modifying the private input bytes is detected and refused. + const original = await readFile(workspace.inputPath); + const tampered = Buffer.from(original); + tampered[tampered.length - 1] = + (tampered[tampered.length - 1]! ^ 0xff) & 0xff; + await writeFile(workspace.inputPath, tampered); + expect(await workspace.verifyInputUnchanged()).toBe(false); + expect(readStream).toHaveBeenCalledTimes(2); + await workspace.remove(); + }); });