diff --git a/docs/bun-standalone.md b/docs/bun-standalone.md index 069f32184a..1e92c8143f 100644 --- a/docs/bun-standalone.md +++ b/docs/bun-standalone.md @@ -59,6 +59,9 @@ are `payload_bytes`, `module_count`, `representation_bytes`, `metadata_read_byte absence. ELF section names are examined at their actual offsets, including names beyond a large section-name prefix. Select `artifact_limits.expanded_bytes` to change the aggregate referenced-plaintext work allowance. +The reader validates the graph extent and suffix before applying `payload_bytes`. +A declared extent outside its carrier or a suffix count that disagrees with the +located payload is a format error. For a reported metadata-read refusal, keep the same carrier and retry with `--artifact-limits '{"bun":{"metadata_read_bytes":536870912}}'` or the equivalent diff --git a/scripts/verify/baselines/raw-buffer-read.json b/scripts/verify/baselines/raw-buffer-read.json index 2d493094e5..1e00667a19 100644 --- a/scripts/verify/baselines/raw-buffer-read.json +++ b/scripts/verify/baselines/raw-buffer-read.json @@ -2,7 +2,6 @@ "src/application/MipsElfMetadata.ts": 10, "src/application/MipsGnuAttributes.ts": 2, "src/artifacts/DesktopFileInspection.ts": 4, - "src/artifacts/bun/BunModuleGraphLayout.ts": 10, "src/domain/apkSignature/apkSignatureSchemes.ts": 1, "src/domain/apkSignature/apkSigningBlock.ts": 2, "src/domain/apkSignature/apkV1Signature.ts": 5, diff --git a/src/artifacts/bun/BunModuleGraph.test.ts b/src/artifacts/bun/BunModuleGraph.test.ts index f49900825b..a682a19c58 100644 --- a/src/artifacts/bun/BunModuleGraph.test.ts +++ b/src/artifacts/bun/BunModuleGraph.test.ts @@ -248,13 +248,7 @@ it("locates the legacy trailer before its final carrier length", async () => { expect((await decodeBunModuleGraph(result.graph)).modules).toHaveLength(1); }); -it("does not admit oversized payloads or truncated length prefixes", async () => { - const prefix = Buffer.alloc(8); - prefix.writeBigUInt64LE(300n * 1024n * 1024n); - expect(await locate(machoBunSection(prefix))).toMatchObject({ - status: "present", - failure: { reason: "limit" }, - }); +it("rejects truncated length prefixes and ignores empty placeholders", async () => { expect(await locate(machoBunSection(Buffer.from([1])))).toMatchObject({ status: "present", failure: { reason: "format" }, @@ -264,6 +258,76 @@ it("does not admit oversized payloads or truncated length prefixes", async () => }); }); +it.each([ + { + name: "Mach-O section", + carrier: (payload: Buffer) => machoBunSection(bunPrefixedPayload(payload)), + breakExtent: (bytes: Buffer, payload: Buffer) => + bytes.writeBigUInt64LE( + BigInt(payload.length + 1), + bytes.length - payload.length - 8, + ), + }, + { + name: "appended ELF trailer", + carrier: elfAppendedBunPayload, + breakExtent: (bytes: Buffer) => + bytes.writeBigUInt64LE( + BigInt(bytes.length), + bytes.length - BUN_FIXTURE_GRAPH_SUFFIX_BYTES, + ), + }, +])( + "checks the $name payload extent before its configured limit", + async ({ carrier, breakExtent }) => { + const payload = bunModuleGraphPayload({ modules: [{ name: "main.js" }] }); + const bytes = carrier(payload); + const limits = { + ...DEFAULT_BUN_READER_LIMITS, + payload_bytes: payload.length - 1, + }; + expect((await probe(bytes, limits)).result).toMatchObject({ + status: "present", + failure: { + reason: "limit", + readerLimit: { parameter: "artifact_limits.bun.payload_bytes" }, + }, + }); + breakExtent(bytes, payload); + expect((await probe(bytes, limits)).result).toMatchObject({ + status: "present", + failure: { + reason: "format", + message: expect.stringContaining("truncated"), + }, + }); + }, +); + +it("reports an impossible Bun suffix byte count as a format error", async () => { + const payload = bunModuleGraphPayload({ modules: [{ name: "main.js" }] }); + const limits = { + ...DEFAULT_BUN_READER_LIMITS, + payload_bytes: payload.length, + }; + const section = () => peBunSection(bunPrefixedPayload(payload)); + expect((await probe(section(), limits)).result).toMatchObject({ + status: "present", + claim: { payloadLength: payload.length }, + }); + payload.writeBigUInt64LE( + BigInt(payload.length + 1), + payload.length - BUN_FIXTURE_GRAPH_SUFFIX_BYTES, + ); + expect((await probe(section(), limits)).result).toMatchObject({ + status: "present", + failure: { + reason: "format", + message: expect.stringContaining("byte_count"), + }, + }); +}); + it("refuses multiple embedded graphs instead of selecting one", async () => { const section = bunPrefixedPayload(bunModuleGraphPayload({ modules: [{}] })); expect(await locate(machoBunSections([section, section]))).toMatchObject({ diff --git a/src/artifacts/bun/BunModuleGraphLayout.ts b/src/artifacts/bun/BunModuleGraphLayout.ts index bc9b2cd225..751e579fde 100644 --- a/src/artifacts/bun/BunModuleGraphLayout.ts +++ b/src/artifacts/bun/BunModuleGraphLayout.ts @@ -1,6 +1,10 @@ import { LC } from "../../domain/apple/machoLoadCommandCodes.js"; import { Budget } from "../../domain/budget.js"; -import { declaredFileRange } from "../../domain/binaryContainer.js"; +import { + BinaryReader, + declaredFileRange, +} from "../../domain/binaryContainer.js"; +import { err, ok, type Result } from "../../domain/result.js"; import { parseMzHeaderEvidence } from "../../domain/dosMz.js"; import { observePeCoffFrame, @@ -233,9 +237,9 @@ export const loadBunStandaloneGraph = async ( BUN_GRAPH_SUFFIX_BYTES, signal, ); - const failure = suffixFailure(suffix, claim.payloadLength, limits); - if (failure !== undefined) return { status: "present", failure }; - const offsets = suffix.subarray(0, BUN_OFFSETS_BYTES); + const parsed = readBunSuffix(suffix, claim.payloadLength); + if (!parsed.ok) return { status: "present", failure: parsed.error }; + const offsets = parsed.value; return { status: "present", graph: { @@ -248,9 +252,9 @@ export const loadBunStandaloneGraph = async ( limits.metadata_read_bytes, ), modules: readPointer(offsets, 8), - entryPointId: offsets.readUInt32LE(16), + entryPointId: offsets.u32(16), compileExecArgv: readPointer(offsets, 20), - flags: offsets.readUInt32LE(28), + flags: offsets.u32(28), }, }; }; @@ -379,18 +383,17 @@ const evaluateSection = async ( ); if (claim.available < BUN_LENGTH_PREFIX_BYTES) return presentFailure(bunFormatFailure("trailer is truncated")); - const prefix = await readExact( - handle, - claim.fileOffset, - BUN_LENGTH_PREFIX_BYTES, - signal, + const prefix = new BinaryReader( + await readExact(handle, claim.fileOffset, BUN_LENGTH_PREFIX_BYTES, signal), + true, + "bun-standalone", ); let prefixBytes = BUN_LENGTH_PREFIX_BYTES; - let payloadLength = prefix.readBigUInt64LE(0); + let payloadLength = prefix.word(0, 64); // Legacy Mach-O writers used a u32 length. Validate its suffix before // interpreting payload bytes as the upper half of a current u64 prefix. if (claim.carrier === "mach-o-section") { - const legacyLength = prefix.readUInt32LE(0); + const legacyLength = prefix.u32(0); if ( legacyLength >= BUN_GRAPH_SUFFIX_BYTES && legacyLength + 4 <= claim.available @@ -401,37 +404,37 @@ const evaluateSection = async ( BUN_GRAPH_SUFFIX_BYTES, signal, ); - if ( - suffix.subarray(BUN_OFFSETS_BYTES).equals(BUN_TRAILER) && - suffix.readBigUInt64LE(0) + BigInt(BUN_GRAPH_SUFFIX_BYTES) === - BigInt(legacyLength) - ) { + if (readBunSuffix(suffix, legacyLength).ok) { prefixBytes = 4; payloadLength = BigInt(legacyLength); } } } if (payloadLength === 0n) return { status: "placeholder" }; - if (payloadLength > BigInt(limits.payload_bytes)) - return presentFailure(bunPayloadBytesLimit(payloadLength, limits)); - if (payloadLength < BigInt(BUN_GRAPH_SUFFIX_BYTES)) + if ( + payloadLength < BigInt(BUN_GRAPH_SUFFIX_BYTES) || + payloadLength > BigInt(claim.available - prefixBytes) + ) return presentFailure(bunFormatFailure("trailer is truncated")); const length = Number(payloadLength); - if (claim.available < prefixBytes + length) - return presentFailure(bunFormatFailure("trailer is truncated")); const payloadOffset = claim.fileOffset + prefixBytes; - const suffix = await readExact( - handle, - payloadOffset + length - BUN_GRAPH_SUFFIX_BYTES, - BUN_GRAPH_SUFFIX_BYTES, - signal, - ); - const failure = suffixFailure(suffix, length, limits); - if (failure !== undefined) return presentFailure(failure); + // The legacy width is selected only after its suffix has been validated. + if (prefixBytes === BUN_LENGTH_PREFIX_BYTES) { + const suffix = await readExact( + handle, + payloadOffset + length - BUN_GRAPH_SUFFIX_BYTES, + BUN_GRAPH_SUFFIX_BYTES, + signal, + ); + const parsed = readBunSuffix(suffix, length); + if (!parsed.ok) return presentFailure(parsed.error); + } if (claim.loadCommandsFailure !== undefined) return presentFailure( bunFormatFailure(`Mach-O load commands: ${claim.loadCommandsFailure}`), ); + if (payloadLength > BigInt(limits.payload_bytes)) + return presentFailure(bunPayloadBytesLimit(payloadLength, limits)); return { status: "present", claim: { carrier: claim.carrier, payloadOffset, payloadLength: length }, @@ -464,7 +467,10 @@ const evaluateAppendedTrailer = async ( trailer = await readTrailer(graphEnd); if (!trailer?.equals(BUN_TRAILER)) return { status: "absent" }; const length = await readExact(handle, graphEnd, 8, signal); - if (length.readBigUInt64LE() !== BigInt(fileSize)) + if ( + new BinaryReader(length, true, "bun-standalone").word(0, 64) !== + BigInt(fileSize) + ) return presentFailure( bunFormatFailure("appended carrier length does not match file size"), ); @@ -475,8 +481,9 @@ const evaluateAppendedTrailer = async ( BUN_OFFSETS_BYTES, signal, ); - const payloadLength = - offsets.readBigUInt64LE(0) + BigInt(BUN_GRAPH_SUFFIX_BYTES); + const payloadLength = graphPayloadLength( + new BinaryReader(offsets, true, "bun-standalone"), + ); const payloadStart = BigInt(graphEnd) - payloadLength; if ( !outsideRejectedSlices( @@ -485,10 +492,10 @@ const evaluateAppendedTrailer = async ( ) ) return { status: "absent" }; - if (payloadLength > BigInt(limits.payload_bytes)) - return presentFailure(bunPayloadBytesLimit(payloadLength, limits)); if (payloadStart < 0n) return presentFailure(bunFormatFailure("trailer is truncated")); + if (payloadLength > BigInt(limits.payload_bytes)) + return presentFailure(bunPayloadBytesLimit(payloadLength, limits)); return { status: "present", claim: { @@ -499,30 +506,36 @@ const evaluateAppendedTrailer = async ( }; }; -/** Validate the Offsets and trailer that end a payload of `payloadLength` bytes. */ -const suffixFailure = ( +const graphPayloadLength = (offsets: BinaryReader): bigint => + offsets.word(0, 64) + BigInt(BUN_GRAPH_SUFFIX_BYTES); + +/** Validate framing before exposing the Offsets record at the end of a graph. */ +const readBunSuffix = ( suffix: Buffer, payloadLength: number, - limits: BunReaderLimits, -): ArtifactReaderFailure | undefined => { +): Result => { if (suffix.length < BUN_GRAPH_SUFFIX_BYTES) - return bunFormatFailure("trailer is truncated"); + return err(bunFormatFailure("trailer is truncated")); if (!suffix.subarray(BUN_OFFSETS_BYTES).equals(BUN_TRAILER)) - return bunFormatFailure("trailer does not match the Bun sentinel"); - const byteCount = suffix.readBigUInt64LE(0); - if (byteCount > BigInt(limits.payload_bytes)) - return bunPayloadBytesLimit(byteCount, limits); - if (byteCount + BigInt(BUN_GRAPH_SUFFIX_BYTES) !== BigInt(payloadLength)) - return bunFormatFailure("byte_count does not match the located payload"); - return undefined; + return err(bunFormatFailure("trailer does not match the Bun sentinel")); + const offsets = new BinaryReader( + suffix.subarray(0, BUN_OFFSETS_BYTES), + true, + "bun-standalone", + ); + if (graphPayloadLength(offsets) !== BigInt(payloadLength)) + return err( + bunFormatFailure("byte_count does not match the located payload"), + ); + return ok(offsets); }; export const readPointer = ( - bytes: Buffer, + reader: BinaryReader, offset: number, ): BunStringPointer => ({ - offset: bytes.readUInt32LE(offset), - length: bytes.readUInt32LE(offset + 4), + offset: reader.u32(offset), + length: reader.u32(offset + 4), }); const machOClaims = async ( diff --git a/src/artifacts/bun/BunModuleGraphMembers.ts b/src/artifacts/bun/BunModuleGraphMembers.ts index b5b56ebbad..2c727d7485 100644 --- a/src/artifacts/bun/BunModuleGraphMembers.ts +++ b/src/artifacts/bun/BunModuleGraphMembers.ts @@ -3,6 +3,7 @@ import { type BunReaderLimits, } from "../../domain/artifactReaderLimits.js"; import { isStrictUtf8 } from "../../domain/strictUtf8.js"; +import { BinaryReader } from "../../domain/binaryContainer.js"; import { setImmediate } from "node:timers/promises"; import { ArtifactReaderFailure } from "../../resources/index.js"; import { @@ -150,10 +151,7 @@ export const decodeBunModuleGraph = async ( if (retained > limits.representation_bytes) throw bunMetadataBytesLimit(retained, limits); for (let index = 0; index < count; index += 1) { - const record = records.subarray( - index * recordBytes, - (index + 1) * recordBytes, - ); + const record = readRecord(records, index, recordBytes); retained += 512 + readPointer(record, 0).length * 6; if (recordBytes === BUN_RECORD_BYTES_1_3_9) retained += readPointer(record, 40).length * 6; @@ -190,6 +188,17 @@ const recordSizes = (length: number): readonly number[] => { return sizes; }; +const readRecord = ( + records: Buffer, + index: number, + width: number, +): BinaryReader => + new BinaryReader( + records.subarray(index * width, (index + 1) * width), + true, + "bun-standalone", + ); + const assessLayout = async ( graph: LocatedBunGraph, records: Buffer, @@ -200,10 +209,7 @@ const assessLayout = async ( const count = records.length / recordBytes; if (count > limits.module_count) return bunModuleCountLimit(count, limits); for (let index = 0; index < count; index += 1) { - const record = records.subarray( - index * recordBytes, - (index + 1) * recordBytes, - ); + const record = readRecord(records, index, recordBytes); if (index % 256 === 0) await setImmediate(); const failure = await recordPointerFailure(data, record, recordBytes); if (failure !== null) return failure; @@ -217,7 +223,7 @@ const assessLayout = async ( const recordPointerFailure = async ( data: BunGraphData, - record: Buffer, + record: BinaryReader, recordBytes: number, verifyTextNuls = true, ): Promise => { @@ -251,16 +257,17 @@ const recordPointerFailure = async ( const decodeRecord = async ( data: BunGraphData, - record: Buffer, + record: BinaryReader, index: number, revision: BunLayoutRevision, ): Promise => { const wide = revision === "bun-1.3.9"; const metadataAt = wide ? 48 : 32; - const encoding = record[metadataAt] ?? 0; - const loader = record[metadataAt + 1] ?? 0; - const moduleFormat = record[metadataAt + 2] ?? 0; - const side = record[metadataAt + 3] ?? 0; + const bytes = record.bytes; + const encoding = bytes[metadataAt] ?? 0; + const loader = bytes[metadataAt + 1] ?? 0; + const moduleFormat = bytes[metadataAt + 2] ?? 0; + const side = bytes[metadataAt + 3] ?? 0; const name = await readNul(data, readPointer(record, 0), "name"); const contents = readPointer(record, 8); const sourcemap = optionalRange(readPointer(record, 16)); diff --git a/tests/acceptance/bunStandaloneCli.test.ts b/tests/acceptance/bunStandaloneCli.test.ts index 78977a801f..f2e08b6ed3 100644 --- a/tests/acceptance/bunStandaloneCli.test.ts +++ b/tests/acceptance/bunStandaloneCli.test.ts @@ -7,6 +7,7 @@ import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { bunModuleGraphPayload, bunPrefixedPayload, + machoBunSection, machoBunSections, elfAppendedBunPayload, } from "../../src/artifacts/bun/BunStandalone.fixture.js"; @@ -19,6 +20,52 @@ import { artifactExtractionResultSchema, } from "../../src/domain/artifactGraph.js"; +cliTest( + "distinguishes a truncated Bun graph from an intact graph over the selected limit", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-bun-payload-extent-"); + const source = join(root, "app"); + const payload = bunModuleGraphPayload({ modules: [{ name: "main.js" }] }); + const section = bunPrefixedPayload(payload); + const limits = JSON.stringify({ + bun: { payload_bytes: payload.length - 1 }, + }); + const inspect = async () => { + await writeFile(source, machoBunSection(section)); + const result = await cli.run({ + arguments: [ + "inspect-artifact", + source, + "--artifact-limits", + limits, + "--json", + ], + }); + expect(result.exitCode, result.stderr).toBe(1); + return result.json; + }; + expect(await inspect()).toMatchObject({ + retryable: true, + details: { + reason: "limit", + reader_limit: { + parameter: "artifact_limits.bun.payload_bytes", + effective_value: payload.length - 1, + required_value: payload.length, + }, + }, + }); + section.writeBigUInt64LE(BigInt(payload.length + 1)); + expect(await inspect()).toMatchObject({ + retryable: false, + details: { + reason: "format", + detail: expect.stringContaining("truncated"), + }, + }); + }, +); + cliTest( "reports large Bun section ambiguity through the compiled CLI", async ({ cli }) => {