Unverified Commit 93cb9089 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

fix(next/image): improve performance of detectContentType() (#96006)

https://github.com/vercel/next.js/security/advisories/GHSA-q8wf-6r8g-63chCo-authored-by: 's avatarSteven <steven@ceriously.com>
parent 93c59f02
......@@ -268,7 +268,6 @@ export const experimentalSchema = {
imgOptTimeoutInSeconds: z.number().int().optional(),
imgOptMaxInputPixels: z.number().int().optional(),
imgOptSequentialRead: z.boolean().optional().nullable(),
imgOptSkipMetadata: z.boolean().optional().nullable(),
isrFlushToDisk: z.boolean().optional(),
largePageDataBytes: z.number().optional(),
linkNoTouchStart: z.boolean().optional(),
......
......@@ -566,7 +566,6 @@ export interface ExperimentalConfig {
imgOptTimeoutInSeconds?: number
imgOptMaxInputPixels?: number
imgOptSequentialRead?: boolean | null
imgOptSkipMetadata?: boolean | null
optimisticClientCache?: boolean
/**
* @deprecated use config.expireTime instead
......@@ -2155,7 +2154,6 @@ export const defaultConfig = Object.freeze({
imgOptTimeoutInSeconds: 7,
imgOptMaxInputPixels: 268_402_689, // https://sharp.pixelplumbing.com/api-constructor#:~:text=%5Boptions.limitInputPixels%5D
imgOptSequentialRead: null,
imgOptSkipMetadata: null,
isrFlushToDisk: true,
workerThreads: false,
proxyTimeout: undefined,
......@@ -2323,7 +2321,6 @@ export interface NextConfigRuntime {
| 'imgOptOperationCache'
| 'imgOptMaxInputPixels'
| 'imgOptSequentialRead'
| 'imgOptSkipMetadata'
| 'imgOptTimeoutInSeconds'
| 'proxyClientMaxBodySize'
| 'proxyTimeout'
......@@ -2392,7 +2389,6 @@ export function getNextConfigRuntime(
imgOptOperationCache: ex.imgOptOperationCache,
imgOptMaxInputPixels: ex.imgOptMaxInputPixels,
imgOptSequentialRead: ex.imgOptSequentialRead,
imgOptSkipMetadata: ex.imgOptSkipMetadata,
imgOptTimeoutInSeconds: ex.imgOptTimeoutInSeconds,
proxyClientMaxBodySize: ex.proxyClientMaxBodySize,
proxyTimeout: ex.proxyTimeout,
......
......@@ -227,10 +227,7 @@ async function deleteFromCacheDir(cacheDir: string, cacheKey: string) {
* https://en.wikipedia.org/wiki/List_of_file_signatures
*/
export async function detectContentType(
buffer: Buffer,
skipMetadata: boolean | null | undefined,
concurrency?: number | null | undefined,
operationCache?: boolean | null | undefined
buffer: Buffer
): Promise<string | null> {
if (buffer.byteLength === 0) {
return null
......@@ -308,28 +305,13 @@ export async function detectContentType(
return JP2
}
let format:
| import('sharp').Metadata['format']
| ReturnType<typeof detector>
| undefined
format = detector(buffer)
if (!format && !skipMetadata) {
const sharp = getSharp(concurrency, operationCache)
const meta = await sharp(buffer)
.metadata()
.catch((_) => null)
format = meta?.format
}
const format = detector(buffer.subarray(0, 1024))
switch (format) {
case 'avif':
return AVIF
case 'webp':
return WEBP
case 'png':
return PNG
case 'jpeg':
case 'jpg':
return JPEG
case 'gif':
......@@ -342,28 +324,14 @@ export async function detectContentType(
case 'jp2':
return JP2
case 'tiff':
case 'tif':
return TIFF
case 'pdf':
return PDF
case 'bmp':
return BMP
case 'ico':
return ICO
case 'icns':
return ICNS
case 'dcraw':
case 'dz':
case 'exr':
case 'fits':
case 'heif':
case 'input':
case 'magick':
case 'openslide':
case 'ppm':
case 'rad':
case 'raw':
case 'v':
case 'cur':
case 'dds':
case 'j2c':
......@@ -372,8 +340,10 @@ export async function detectContentType(
case 'psd':
case 'tga':
case undefined:
return null // unsupported formats
default:
return null
format satisfies never // exhaustive check
return null // impossible to reach
}
}
......@@ -1066,7 +1036,6 @@ export async function imageOptimizer(
| 'imgOptOperationCache'
| 'imgOptMaxInputPixels'
| 'imgOptSequentialRead'
| 'imgOptSkipMetadata'
| 'imgOptTimeoutInSeconds'
>
images: Pick<
......@@ -1094,12 +1063,7 @@ export async function imageOptimizer(
getMaxAge(imageUpstream.cacheControl)
)
const upstreamType = await detectContentType(
upstreamBuffer,
nextConfig.experimental.imgOptSkipMetadata,
nextConfig.experimental.imgOptConcurrency,
nextConfig.experimental.imgOptOperationCache
)
const upstreamType = await detectContentType(upstreamBuffer)
if (
!upstreamType ||
......
/* eslint-env jest */
import { detectContentType } from 'next/dist/server/image-optimizer'
import { detectContentType as dct } from 'next/dist/server/image-optimizer'
import { readFile } from 'fs-extra'
import { join } from 'path'
const getImage = (filepath) => readFile(join(__dirname, filepath))
const getImage = (filepath: string) => readFile(join(__dirname, filepath))
describe.each([false, true])(
'detectContentType with imgOptSkipMetadata: %s',
(imgOptSkipMetadata) => {
it('should return null for empty buffer', async () => {
expect(await detectContentType(Buffer.alloc(0), imgOptSkipMetadata)).toBe(
null
)
})
it('should return null for unrecognized buffer', async () => {
expect(
await detectContentType(
Buffer.from([0xa, 0xb, 0xc]),
imgOptSkipMetadata
)
).toBe(null)
})
it('should return jpg', async () => {
const buffer = await getImage('./images/test.jpg')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/jpeg'
)
})
it('should return png', async () => {
const buffer = await getImage('./images/test.png')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/png'
)
})
it('should return webp', async () => {
const buffer = await getImage('./images/animated.webp')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/webp'
)
})
it('should return svg', async () => {
const buffer = await getImage('./images/test.svg')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/svg+xml'
)
})
it('should return svg for inline svg', async () => {
const buffer = await getImage('./images/test-inline.svg')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/svg+xml'
)
})
it('should return svg when starts with space', async () => {
const buffer = Buffer.from(
' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>'
)
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/svg+xml'
)
})
it('should return svg when starts with newline', async () => {
const buffer = Buffer.from(
'\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>'
)
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/svg+xml'
)
})
it('should return svg when starts with tab', async () => {
const buffer = Buffer.from(
'\t<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>'
)
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/svg+xml'
)
})
it('should return avif', async () => {
const buffer = await getImage('./images/test.avif')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/avif'
)
})
it('should return icon', async () => {
const buffer = await getImage('./images/test.ico')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/x-icon'
)
})
it('should return icns', async () => {
const buffer = await getImage('./images/test.icns')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/x-icns'
)
})
it('should return jxl', async () => {
const buffer = await getImage('./images/test.jxl')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/jxl'
)
})
it('should return jp2', async () => {
const buffer = await getImage('./images/test.jp2')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/jp2'
)
})
it('should return heic', async () => {
const buffer = await getImage('./images/test.heic')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/heic'
)
})
it('should return pdf', async () => {
const buffer = await getImage('./images/test.pdf')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'application/pdf'
)
})
it('should return tiff', async () => {
const buffer = await getImage('./images/test.tiff')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/tiff'
)
})
it('should return bmp', async () => {
const buffer = await getImage('./images/test.bmp')
expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
'image/bmp'
)
})
const detectContentType = async (buffer: Buffer, isRetry = false) => {
let maxBlockedMs = 0
let lastTick = performance.now()
let running = true
const sample = () => {
const now = performance.now()
maxBlockedMs = Math.max(maxBlockedMs, now - lastTick)
lastTick = now
if (running) {
setImmediate(sample)
}
}
setImmediate(sample)
const result = await dct(buffer)
running = false
maxBlockedMs = Math.max(maxBlockedMs, performance.now() - lastTick)
if (maxBlockedMs > 1) {
if (isRetry) {
throw new Error(
`detectContentType blocked the event loop for ${maxBlockedMs.toFixed(1)}ms`
)
} else {
// try again because the first run after compile can be slow due to JIT optimizations
return await detectContentType(buffer, true)
}
}
)
return result
}
describe('detectContentType', () => {
it('should return null for empty buffer', async () => {
expect(await detectContentType(Buffer.alloc(0))).toBe(null)
})
it('should return null for unrecognized buffer', async () => {
expect(await detectContentType(Buffer.from([0xa, 0xb, 0xc]))).toBe(null)
})
it('should return null for over 50MB of whitespace', async () => {
const buffer = Buffer.alloc(50_000_001).fill(' ')
expect(await detectContentType(buffer)).toBe(null)
})
it('should return jpg', async () => {
const buffer = await getImage('./images/test.jpg')
expect(await detectContentType(buffer)).toBe('image/jpeg')
})
it('should return png', async () => {
const buffer = await getImage('./images/test.png')
expect(await detectContentType(buffer)).toBe('image/png')
})
it('should return webp', async () => {
const buffer = await getImage('./images/animated.webp')
expect(await detectContentType(buffer)).toBe('image/webp')
})
it('should return svg', async () => {
const buffer = await getImage('./images/test.svg')
expect(await detectContentType(buffer)).toBe('image/svg+xml')
})
it('should return svg for inline svg', async () => {
const buffer = await getImage('./images/test-inline.svg')
expect(await detectContentType(buffer)).toBe('image/svg+xml')
})
it('should return svg for slow svg', async () => {
const buffer = await getImage('./images/slow.svg.txt')
expect(await detectContentType(buffer)).toBe('image/svg+xml')
})
it('should return avif', async () => {
const buffer = await getImage('./images/test.avif')
expect(await detectContentType(buffer)).toBe('image/avif')
})
it('should return icon', async () => {
const buffer = await getImage('./images/test.ico')
expect(await detectContentType(buffer)).toBe('image/x-icon')
})
it('should return icns', async () => {
const buffer = await getImage('./images/test.icns')
expect(await detectContentType(buffer)).toBe('image/x-icns')
})
it('should return jxl', async () => {
const buffer = await getImage('./images/test.jxl')
expect(await detectContentType(buffer)).toBe('image/jxl')
})
it('should return jp2', async () => {
const buffer = await getImage('./images/test.jp2')
expect(await detectContentType(buffer)).toBe('image/jp2')
})
it('should return heic', async () => {
const buffer = await getImage('./images/test.heic')
expect(await detectContentType(buffer)).toBe('image/heic')
})
it('should return pdf', async () => {
const buffer = await getImage('./images/test.pdf')
expect(await detectContentType(buffer)).toBe('application/pdf')
})
it('should return tiff', async () => {
const buffer = await getImage('./images/test.tiff')
expect(await detectContentType(buffer)).toBe('image/tiff')
})
it('should return bmp', async () => {
const buffer = await getImage('./images/test.bmp')
expect(await detectContentType(buffer)).toBe('image/bmp')
})
})
<svg xmlns="http://www.w3.org/2000/svg" data-stealth-meta="....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................">
<defs>
<g id="bomb">
<path d="M0 0 A 58.398 42.821 45 1 1 100 100 A 42.821 58.398 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 44.811 43.096 45 1 1 100 100 A 43.096 44.811 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 25.054 12.985 45 1 1 100 100 A 12.985 25.054 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 38.554 41.764 45 1 1 100 100 A 41.764 38.554 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 50.078 24.133 45 1 1 100 100 A 24.133 50.078 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 15.395 32.152 45 1 1 100 100 A 32.152 15.395 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 19.956 30.757 45 1 1 100 100 A 30.757 19.956 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 39.212 23.888 45 1 1 100 100 A 23.888 39.212 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 53.895 37.062 45 1 1 100 100 A 37.062 53.895 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 17.238 26.596 45 1 1 100 100 A 26.596 17.238 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 30.559 34.960 45 1 1 100 100 A 34.960 30.559 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 54.193 35.742 45 1 1 100 100 A 35.742 54.193 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 46.798 50.350 45 1 1 100 100 A 50.350 46.798 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
<path d="M0 0 A 10.046 26.234 45 1 1 100 100 A 26.234 10.046 -45 1 1 0 0" stroke="black" stroke-width="2" stroke-dasharray="0.001, 0.002" fill="none"/>
</g>
</defs>
<use href="#bomb" x="0.00" y="0.00"/>
<use href="#bomb" x="0.00" y="-0.00"/>
<use href="#bomb" x="0.00" y="-0.00"/>
<use href="#bomb" x="0.00" y="-0.00"/>
<use href="#bomb" x="0.00" y="-0.00"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.01" y="-0.01"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.02" y="-0.02"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.03" y="-0.03"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.04" y="-0.04"/>
<use href="#bomb" x="0.05" y="-0.05"/>
<use href="#bomb" x="0.05" y="-0.05"/>
<use href="#bomb" x="0.05" y="-0.05"/>
<use href="#bomb" x="0.05" y="-0.05"/>
<use href="#bomb" x="0.05" y="-0.05"/>
<use href="#bomb" x="0.05" y="-0.05"/>
<use href="#bomb" x="0.05" y="-0.05"/>
</svg>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment