diff --git a/src/application/LinuxHopperPublisher.ts b/src/application/LinuxHopperPublisher.ts index 5d60483e4e..7c19ffadc8 100644 --- a/src/application/LinuxHopperPublisher.ts +++ b/src/application/LinuxHopperPublisher.ts @@ -909,6 +909,7 @@ export class LinuxHopperPublisher { ); const bytes = await readBoundedFileBytes(handle, stats.size, { signal, + expectedSize: stats.size, }); if (bytes === undefined) throw new HopperReleaseError( diff --git a/src/application/SetupSkill.ts b/src/application/SetupSkill.ts index 4716bdc260..6c8823c0ee 100644 --- a/src/application/SetupSkill.ts +++ b/src/application/SetupSkill.ts @@ -61,13 +61,10 @@ const readSkillFileSnapshot = async ( withRegularFile( path, async (handle, stats) => { - const bytes = await readBoundedFileBytes( - handle, - Math.min(stats.size, maxBytes), - { - expectedSize: stats.size, - }, - ); + if (stats.size > maxBytes) throw new RegularFileChangedError(path); + const bytes = await readBoundedFileBytes(handle, stats.size, { + expectedSize: stats.size, + }); if (bytes === undefined || bytes.length !== stats.size) throw new RegularFileChangedError(path); return { bytes, mode: stats.mode & 0o7777, state: stats }; diff --git a/src/cutter/CutterBridgeClient.ts b/src/cutter/CutterBridgeClient.ts index 50db936840..0da1e2183e 100644 --- a/src/cutter/CutterBridgeClient.ts +++ b/src/cutter/CutterBridgeClient.ts @@ -1018,6 +1018,7 @@ export class CutterBridgeClient { const bytes = await readBoundedFileBytes( file, MAX_DESCRIPTOR_BYTES, + { expectedSize: info.size }, ); assertArtifactReadActive(signal); return bytes; diff --git a/src/dotnet/ManagedSnapshot.ts b/src/dotnet/ManagedSnapshot.ts index 712c0a303f..79ac948ed6 100644 --- a/src/dotnet/ManagedSnapshot.ts +++ b/src/dotnet/ManagedSnapshot.ts @@ -106,7 +106,10 @@ export const readManagedSnapshot = async ( const signal = options.signal; if (metadata.size > maxBytes) throw managedSnapshotCapacityError(operation, maxBytes); - const bytes = await readBoundedFileBytes(handle, maxBytes, { signal }); + const bytes = await readBoundedFileBytes(handle, maxBytes, { + signal, + expectedSize: metadata.size, + }); if (bytes === undefined) throw managedSnapshotCapacityError(operation, maxBytes); signal?.throwIfAborted(); diff --git a/src/ghidra/GhidraDosSnapshot.ts b/src/ghidra/GhidraDosSnapshot.ts index 699d476483..ec7cd5d96e 100644 --- a/src/ghidra/GhidraDosSnapshot.ts +++ b/src/ghidra/GhidraDosSnapshot.ts @@ -12,7 +12,6 @@ import { } from "../domain/dosMz.js"; import { err } from "../domain/result.js"; import type { NativeLoadImageObservation } from "../domain/native/nativeLoadImage.js"; -import { readBoundedFileBytes } from "../process/BoundedFileBytes.js"; import { RegularFileChangedError } from "../filesystem/RegularFile.js"; import { attestGhidraDosLoadImage, @@ -34,13 +33,20 @@ export const attestGhidraDosSnapshot = async ( signal?: AbortSignal, ) => { const headerBytes = Math.min(fileBytes, 64); - const header = await readBoundedFileBytes(handle, headerBytes, { - signal, - expectedSize: headerBytes, - cancellationFailure: cancelled, - }); - if (header === undefined || header.length !== headerBytes) - throw new RegularFileChangedError(path); + const header = Buffer.allocUnsafe(headerBytes); + let headerRead = 0; + while (headerRead < headerBytes) { + if (signal?.aborted) throw cancelled(signal.reason); + const { bytesRead } = await handle.read( + header, + headerRead, + headerBytes - headerRead, + headerRead, + ); + if (signal?.aborted) throw cancelled(signal.reason); + if (bytesRead === 0) throw new RegularFileChangedError(path); + headerRead += bytesRead; + } const declarations = readDosMzDeclarations(header); if (!declarations.ok) return declarations; const extent = dosMzDeclaredImageByteLength(declarations.value); diff --git a/src/ida/IdaConfiguration.ts b/src/ida/IdaConfiguration.ts index 12ff633aab..47586996c1 100644 --- a/src/ida/IdaConfiguration.ts +++ b/src/ida/IdaConfiguration.ts @@ -210,6 +210,7 @@ export const readIdaConfiguration = ( MAXIMUM_REGISTRATION_BYTES, { signal: options.signal, + expectedSize: metadata.size, cancellationFailure: (reason) => new RegularFileOperationCancelled(reason), }, diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts index c56de57a5f..c7b1088a08 100644 --- a/src/native/AppleDispatchMetadata.ts +++ b/src/native/AppleDispatchMetadata.ts @@ -432,6 +432,7 @@ export const inspectAppleDispatchMetadata = async ( if (signal?.aborted) throw cancelled(); const read = await readBoundedFileBytes(handle, maximumBytes, { signal, + expectedSize: before.size, cancellationFailure: () => cancelled(), }); if (read === undefined) throw inputBudgetExceeded(admission, null); diff --git a/src/process/BoundedFileBytes.ts b/src/process/BoundedFileBytes.ts index d42725b0ee..688add7264 100644 --- a/src/process/BoundedFileBytes.ts +++ b/src/process/BoundedFileBytes.ts @@ -42,10 +42,14 @@ export const readBoundedFileBytes = async ( ) throw new RangeError("Expected file size must fit the byte limit"); assertActive(); - if (expectedSize === undefined) { - const chunks: Buffer[] = []; - const buffer = Buffer.allocUnsafe(Math.min(64 * 1_024, maxBytes + 1)); - let total = 0; + const readChunks = async ( + chunks: Buffer[], + initialTotal: number, + ): Promise => { + const buffer = Buffer.allocUnsafe( + Math.min(64 * 1_024, maxBytes - initialTotal + 1), + ); + let total = initialTotal; for (;;) { assertActive(); const { bytesRead } = await read( @@ -59,17 +63,19 @@ export const readBoundedFileBytes = async ( if (total > maxBytes) return undefined; chunks.push(Buffer.from(buffer.subarray(0, bytesRead))); } - } - const buffer = Buffer.allocUnsafe(expectedSize); - if (expectedSize === 0) return buffer; + }; + if (expectedSize === undefined) return readChunks([], 0); + // Allocate one extra probe byte so an unchanged file is read in a single + // buffer without Buffer.concat while still proving EOF (or detecting growth). + const buffer = Buffer.allocUnsafe(expectedSize + 1); let total = 0; for (;;) { assertActive(); - const { bytesRead } = await read(buffer, total, expectedSize - total); + const { bytesRead } = await read(buffer, total, buffer.length - total); assertActive(); if (bytesRead === 0) return buffer.subarray(0, total); total += bytesRead; if (total > maxBytes) return undefined; - if (total === expectedSize) return buffer; + if (total === buffer.length) return readChunks([buffer], total); } }; diff --git a/src/process/RegularFileRead.ts b/src/process/RegularFileRead.ts index d5955ab339..eaeb848e25 100644 --- a/src/process/RegularFileRead.ts +++ b/src/process/RegularFileRead.ts @@ -359,6 +359,7 @@ const readRegularFileContent = ( options.admit?.(stats); const bytes = await readBoundedFileBytes(handle, stats.size, { ...(options.signal === undefined ? {} : { signal: options.signal }), + expectedSize: stats.size, cancellationFailure: (reason) => new RegularFileOperationCancelled(reason), operationFailure: (cause) => new RegularFileReadFailure(cause), diff --git a/tests/boundary/filesystem/boundedFileBytes.test.ts b/tests/boundary/filesystem/boundedFileBytes.test.ts index f2813adf19..ca4044a863 100644 --- a/tests/boundary/filesystem/boundedFileBytes.test.ts +++ b/tests/boundary/filesystem/boundedFileBytes.test.ts @@ -120,3 +120,79 @@ describe("bounded file byte reads", () => { } }); }); + +describe("bounded file byte reads with expectedSize", () => { + it.each([0, 65_536])( + "accepts a file matching expectedSize %i at the byte limit", + async (limit) => { + const root = await createTestTempDirectory("rea-bounded-expected-"); + const path = join(root, "input"); + const content = Buffer.alloc(limit, 0x62); + await writeFile(path, content); + const handle = await open(path, "r"); + try { + const actual = await readBoundedFileBytes(handle, limit, { + expectedSize: limit, + }); + if (actual === undefined) + throw new Error("Expected complete file bytes"); + expect(actual.equals(content)).toBe(true); + } finally { + await handle.close(); + } + }, + ); + + it.each([0, 10])( + "detects growth past maxBytes when expectedSize equals maxBytes (%i)", + async (expectedSize) => { + const root = await createTestTempDirectory("rea-growing-expected-"); + const path = join(root, "input"); + await writeFile(path, "0".repeat(expectedSize)); + const handle = await open(path, "r"); + try { + await appendFile(path, "abcdef"); + expect( + await readBoundedFileBytes(handle, expectedSize, { expectedSize }), + ).toBeUndefined(); + const next = Buffer.alloc(1); + expect((await handle.read(next, 0, 1, null)).bytesRead).toBe(1); + expect(next.toString()).toBe("b"); + } finally { + await handle.close(); + } + }, + ); + + it("reads through EOF when a file grows beyond expectedSize but stays within maxBytes", async () => { + const root = await createTestTempDirectory("rea-growing-within-max-"); + const path = join(root, "input"); + await writeFile(path, "hello"); + const handle = await open(path, "r"); + try { + await appendFile(path, " world!"); + const actual = await readBoundedFileBytes(handle, 32, { + expectedSize: 5, + }); + if (actual === undefined) throw new Error("Expected complete file bytes"); + expect(actual.toString("utf8")).toBe("hello world!"); + } finally { + await handle.close(); + } + }); + + it("returns undefined when a file grows beyond expectedSize and exceeds maxBytes", async () => { + const root = await createTestTempDirectory("rea-growing-past-max-"); + const path = join(root, "input"); + await writeFile(path, "hello"); + const handle = await open(path, "r"); + try { + await appendFile(path, "0123456789"); + expect( + await readBoundedFileBytes(handle, 10, { expectedSize: 5 }), + ).toBeUndefined(); + } finally { + await handle.close(); + } + }); +});