diff --git a/scripts/verify/baselines/raw-buffer-read.json b/scripts/verify/baselines/raw-buffer-read.json index 18fce61f3c..ee39fdd731 100644 --- a/scripts/verify/baselines/raw-buffer-read.json +++ b/scripts/verify/baselines/raw-buffer-read.json @@ -40,8 +40,7 @@ "src/domain/pe/peResourceInventory.ts": 7, "src/domain/pe/peResourceTreeFacts.ts": 9, "src/domain/peSectionHeader.ts": 5, - "src/domain/pngHeader.ts": 4, - "src/domain/pngVisualDiff.ts": 7, + "src/domain/pngVisualDiff.ts": 2, "src/domain/python/marshalReader.ts": 4, "src/domain/python/pythonBytecodeIdentity.ts": 1, "src/domain/riscvIsaDeclaration.ts": 1, diff --git a/src/domain/pngHeader.ts b/src/domain/pngHeader.ts index 96d43056cd..1510055814 100644 --- a/src/domain/pngHeader.ts +++ b/src/domain/pngHeader.ts @@ -1,13 +1,49 @@ import { crc32 } from "node:zlib"; +import { BinaryReader } from "./binaryContainer.js"; import { err, ok, type Result } from "./result.js"; const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); -const IHDR_TYPE = Buffer.from("IHDR"); +const IHDR_DATA_BYTES = 13; +const PNG_CHUNK_OVERHEAD = 12; /** PNG signature recognition does not establish image validity. */ export const hasPngSignature = (bytes: Buffer): boolean => bytes.subarray(0, 8).equals(PNG_SIGNATURE); +interface PngChunk { + readonly type: string; + readonly data: Buffer; + readonly nextOffset: number; +} + +/** Frame reader for one PNG datastream, including each chunk's type and data CRC. */ +export const createPngChunkReader = (bytes: Buffer) => { + const reader = new BinaryReader(bytes, false, "png"); + return ( + offset: number, + maxDataBytes = 0x7fff_ffff, + ): Result => { + const remaining = bytes.length - offset; + if (remaining < PNG_CHUNK_OVERHEAD) return err("Truncated PNG chunk"); + const length = reader.u32(offset); + if (length > maxDataBytes) return err("Invalid PNG chunk length"); + if (length > remaining - PNG_CHUNK_OVERHEAD) + return err("Truncated PNG data"); + const typeAndData = reader.range(offset + 4, 4 + length, "PNG chunk"); + const checksumOffset = offset + 8 + length; + if (crc32(typeAndData) !== reader.u32(checksumOffset)) + return err("Invalid PNG chunk checksum"); + const type = typeAndData.toString("latin1", 0, 4); + if (!/^[A-Za-z]{4}$/u.test(type) || type[2] !== type[2]?.toUpperCase()) + return err("Invalid PNG chunk type"); + return ok({ + type, + data: typeAndData.subarray(4), + nextOffset: checksumOffset + 4, + }); + }; +}; + export interface PngIhdrFacts { readonly width: number; readonly height: number; @@ -23,9 +59,10 @@ export interface PngIhdrFacts { export const readPngIhdrFacts = ( data: Buffer, ): Result => { - if (data.length !== 13) return err("Invalid PNG header"); - const width = data.readUInt32BE(0); - const height = data.readUInt32BE(4); + if (data.length !== IHDR_DATA_BYTES) return err("Invalid PNG header"); + const header = new BinaryReader(data, false, "png"); + const width = header.u32(0); + const height = header.u32(4); if ( width === 0 || height === 0 || @@ -33,9 +70,9 @@ export const readPngIhdrFacts = ( height > 0x7fff_ffff ) return err("Invalid PNG header"); - const bitDepth = data[8]!; - const colorType = data[9]!; - const interlaceMethod = data[12]!; + const bitDepth = header.u8(8); + const colorType = header.u8(9); + const interlaceMethod = header.u8(12); const validDepth = (colorType === 0 && [1, 2, 4, 8, 16].includes(bitDepth)) || (colorType === 2 && [8, 16].includes(bitDepth)) || @@ -44,8 +81,8 @@ export const readPngIhdrFacts = ( (colorType === 6 && [8, 16].includes(bitDepth)); if ( !validDepth || - data[10] !== 0 || - data[11] !== 0 || + header.u8(10) !== 0 || + header.u8(11) !== 0 || (interlaceMethod !== 0 && interlaceMethod !== 1) ) return err("Invalid PNG header"); @@ -56,15 +93,10 @@ export const readPngIhdrFacts = ( export const readPngHeaderDimensions = ( bytes: Buffer, ): { readonly width: number; readonly height: number } | undefined => { - if ( - bytes.byteLength < 33 || - !hasPngSignature(bytes) || - bytes.readUInt32BE(8) !== 13 || - !bytes.subarray(12, 16).equals(IHDR_TYPE) || - crc32(bytes.subarray(12, 29)) !== bytes.readUInt32BE(29) - ) - return undefined; - const facts = readPngIhdrFacts(bytes.subarray(16, 29)); + if (!hasPngSignature(bytes)) return undefined; + const chunk = createPngChunkReader(bytes)(8, IHDR_DATA_BYTES); + if (!chunk.ok || chunk.value.type !== "IHDR") return undefined; + const facts = readPngIhdrFacts(chunk.value.data); return facts.ok ? { width: facts.value.width, height: facts.value.height } : undefined; diff --git a/src/domain/pngVisualDiff.test.ts b/src/domain/pngVisualDiff.test.ts index 9a989dd3a6..7ad2d4daf2 100644 --- a/src/domain/pngVisualDiff.test.ts +++ b/src/domain/pngVisualDiff.test.ts @@ -254,6 +254,9 @@ describe("PNG chunk integrity", () => { } offset += length + 12; } + expect(readPngHeaderDimensions(bytes)).toEqual( + type === "IHDR" ? undefined : { width: 1, height: 1 }, + ); const image = createWebScreenshotArtifact(bytes); expect(() => comparePngScreenshots( diff --git a/src/domain/pngVisualDiff.ts b/src/domain/pngVisualDiff.ts index 3578eeecbf..4b9250b06c 100644 --- a/src/domain/pngVisualDiff.ts +++ b/src/domain/pngVisualDiff.ts @@ -1,4 +1,4 @@ -import { constants as zlibConstants, crc32, inflateSync } from "node:zlib"; +import { constants as zlibConstants, inflateSync } from "node:zlib"; import type { CompareWebScreenshotsInput, @@ -10,7 +10,12 @@ import { AnalysisUnsupportedTargetError, } from "./analysisErrorCore.js"; import { decodeCanonicalBase64 } from "./webScreenshot.js"; -import { hasPngSignature, readPngIhdrFacts } from "./pngHeader.js"; +import { + createPngChunkReader, + hasPngSignature, + readPngIhdrFacts, +} from "./pngHeader.js"; +import { BinaryReader } from "./binaryContainer.js"; interface DecodedPng { readonly width: number; @@ -125,6 +130,7 @@ const parsePng = ( const bytes = decodeCanonicalBase64(artifact.data_base64); if (bytes === undefined || !hasPngSignature(bytes)) throw new TypeError("Invalid PNG signature"); + const readChunk = createPngChunkReader(bytes); let offset = 8; let header: ReturnType | undefined; const compressed: Buffer[] = []; @@ -136,20 +142,10 @@ const parsePng = ( let sawTransparency = false; let unsupportedReason: string | undefined; while (offset < bytes.length) { - if (offset + 12 > bytes.length) throw new TypeError("Truncated PNG chunk"); - const length = bytes.readUInt32BE(offset); - if (length > 0x7fffffff) throw new TypeError("Invalid PNG chunk length"); - const type = bytes.subarray(offset + 4, offset + 8).toString("latin1"); - const dataStart = offset + 8; - const dataEnd = dataStart + length; - if (dataEnd + 4 > bytes.length) throw new TypeError("Truncated PNG data"); - const data = bytes.subarray(dataStart, dataEnd); - if ( - crc32(bytes.subarray(offset + 4, dataEnd)) !== bytes.readUInt32BE(dataEnd) - ) - throw new TypeError("Invalid PNG chunk checksum"); - if (!/^[A-Za-z]{4}$/u.test(type) || type[2] !== type[2]?.toUpperCase()) - throw new TypeError("Invalid PNG chunk type"); + const chunk = readChunk(offset); + if (!chunk.ok) throw new TypeError(chunk.error); + const { type, data, nextOffset } = chunk.value; + const length = data.length; if (type !== "IDAT" && compressed.length > 0) imageDataEnded = true; if (type === "IHDR") { if (offset !== 8 || header !== undefined) @@ -163,10 +159,11 @@ const parsePng = ( sawTransparency = true; if (header.colorType === 2 && data.length === 6) { const sampleMask = (1 << header.bitDepth) - 1; + const transparency = new BinaryReader(data, false, "png"); transparentColor = [ - data.readUInt16BE(0), - data.readUInt16BE(2), - data.readUInt16BE(4), + transparency.u16(0), + transparency.u16(2), + transparency.u16(4), ].map((value) => value & sampleMask); } else if ( (header.colorType === 0 && data.length === 2) || @@ -200,14 +197,14 @@ const parsePng = ( if (imageDataEnded) throw new TypeError("Nonconsecutive PNG image data"); compressed.push(data); } else if (type === "IEND") { - if (length !== 0 || dataEnd + 4 !== bytes.length) + if (length !== 0 || nextOffset !== bytes.length) throw new TypeError("Invalid PNG end chunk"); sawEnd = true; break; } else if (/^[A-Z]/u.test(type)) { unsupportedReason ??= `Unsupported critical PNG chunk ${type}.`; } - offset = dataEnd + 4; + offset = nextOffset; } if (header === undefined || !sawEnd || compressed.length === 0) throw new TypeError("Incomplete PNG");