Unverified Commit 3dc2e672 authored by Steven's avatar Steven Committed by GitHub

fix(next/image): add missing svg test refactor missing types (#65345)

The tests added in https://github.com/vercel/next.js/pull/46219 were
never correctly testing the headers because `detectContentType()` is
called first and only when we can't detect the type from the response
body do we fallback to the `Content-Type` header.

I also refactored some of the tests because the `ctx: any` type was
causing some tests to not run when testing different configuration
options.

Closes NEXT-3321
parent 180d4f5a
......@@ -138,6 +138,9 @@ export function detectContentType(buffer: Buffer) {
if ([0x3c, 0x3f, 0x78, 0x6d, 0x6c].every((b, i) => buffer[i] === b)) {
return SVG
}
if ([0x3c, 0x73, 0x76, 0x67].every((b, i) => buffer[i] === b)) {
return SVG
}
if (
[0, 0, 0, 0, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66].every(
(b, i) => !b || buffer[i] === b
......
export default function handler(_req, res) {
res.setHeader('Content-Type', 'application/svg+xml')
res.end(
`<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="60" height="60"><text x="20" y="30">hi</text></svg>`
)
res.end('body is not svg to force fallback to Content-Type header')
}
export default function handler(_req, res) {
res.setHeader('Content-Type', 'image/foo, text/html')
res.end(
`<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="60" height="60"><text x="20" y="30">hi</text></svg>`
)
res.end('body is not svg to force fallback to Content-Type header')
}
const images = [
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEBgIApD5fRAAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPj/HwADBwIAMCbHYQAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5/hPwAIAgL/4d1j8wAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P//PwAGBAL/VJiKjgAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=',
]
let state = 0
export default function handler(_req, res) {
state++
const index = state % images.length
const buffer = Buffer.from(images[index], 'base64')
res.setHeader('Content-Type', 'image/png')
return res.end(buffer)
}
export default function handler(_req, res) {
res.setHeader('Content-Type', 'image/SVG+XML')
res.end(
`<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="60" height="60"><text x="20" y="30">hi</text></svg>`
)
res.end('body is not svg to force fallback to Content-Type header')
}
export default function handler(_req, res) {
res.setHeader('Content-Type', 'image/png')
res.end(
`<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="60" height="60"><text x="20" y="30">hi</text></svg>`
)
}
import { join } from 'path'
import { setupTests } from './util'
const appDir = join(__dirname, '../app')
const imagesDir = join(appDir, '.next', 'cache', 'images')
describe('with dangerouslyAllowSVG config', () => {
setupTests({
nextConfigImages: { dangerouslyAllowSVG: true },
appDir,
imagesDir,
})
})
......@@ -17,6 +17,21 @@ import {
import isAnimated from 'next/dist/compiled/is-animated'
import type { RequestInit } from 'node-fetch'
type SetupTestsCtx = {
appDir: string
imagesDir: string
nextConfigImages?: Partial<import('next').NextConfig['images']>
isDev?: boolean
}
type RunTestsCtx = SetupTestsCtx & {
w: number
app?: import('child_process').ChildProcess
appDir?: string
appPort?: number
nextOutput?: string
}
const largeSize = 1080 // defaults defined in server/config.ts
const animatedWarnText =
'is an animated image so it will not be optimized. Consider adding the "unoptimized" property to the <Image>.'
......@@ -53,7 +68,7 @@ export async function serveSlowImage() {
}
}
export async function fsToJson(dir, output = {}) {
export async function fsToJson(dir: string, output = {}) {
const files = await fs.readdir(dir)
for (let file of files) {
const fsPath = join(dir, file)
......@@ -77,12 +92,16 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) {
expect(isAnimated(buffer)).toBe(expectAnimated)
}
export const cleanImagesDir = async (ctx) => {
export const cleanImagesDir = async (ctx: { imagesDir: string }) => {
console.warn('Cleaning', ctx.imagesDir)
await fs.remove(ctx.imagesDir)
}
async function expectAvifSmallerThanWebp(w, q, appPort) {
async function expectAvifSmallerThanWebp(
w: number,
q: number,
appPort: number
) {
const query = { url: '/mountains.jpg', w, q }
const res1 = await fetchViaHTTP(appPort, '/_next/image', query, {
headers: {
......@@ -130,7 +149,7 @@ async function fetchWithDuration(
return { duration, buffer, res }
}
export function runTests(ctx) {
export function runTests(ctx: RunTestsCtx) {
const { isDev, nextConfigImages } = ctx
const {
contentDispositionType = 'inline',
......@@ -279,7 +298,7 @@ export function runTests(ctx) {
expect(ctx.nextOutput).toContain(animatedWarnText)
})
if (ctx.dangerouslyAllowSVG) {
if (ctx.nextConfigImages?.dangerouslyAllowSVG) {
it('should maintain vector svg', async () => {
const query = { w: ctx.w, q: 90, url: '/test.svg' }
const opts = { headers: { accept: 'image/webp' } }
......@@ -303,7 +322,12 @@ export function runTests(ctx) {
'utf8'
)
expect(actual).toMatch(expected)
expect(ctx.nextOutput).not.toContain('The requested resource')
expect(ctx.nextOutput).not.toContain(
`The requested resource isn't a valid image`
)
expect(ctx.nextOutput).not.toContain(
`valid but image type is not allowed`
)
})
} else {
it('should not allow vector svg', async () => {
......@@ -343,6 +367,16 @@ export function runTests(ctx) {
'"url" parameter is valid but image type is not allowed'
)
})
it('should not allow svg with wrong header', async () => {
const query = { w: ctx.w, q: 65, url: '/api/wrong-header.svg' }
const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.status).toBe(400)
expect(await res.text()).toContain(
'"url" parameter is valid but image type is not allowed'
)
})
}
it('should maintain ico format', async () => {
......@@ -820,8 +854,14 @@ export function runTests(ctx) {
await cleanImagesDir(ctx)
const delay = 500
if (globalThis.isrImgQuality) {
globalThis.isrImgQuality++
} else {
globalThis.isrImgQuality = 40
}
const url = `http://localhost:${slowImageServer.port}/slow.png?delay=${delay}`
const query = { url, w: ctx.w, q: 39 }
const query = { url, w: ctx.w, q: globalThis.isrImgQuality }
const opts = { headers: { accept: 'image/webp' } }
const one = await fetchWithDuration(
......@@ -864,9 +904,9 @@ export function runTests(ctx) {
const json2 = await fsToJson(ctx.imagesDir)
expect(json2).toStrictEqual(json1)
if (ctx.minimumCacheTTL) {
if (ctx.nextConfigImages?.minimumCacheTTL) {
// Wait until expired so we can confirm image is regenerated
await waitFor(ctx.minimumCacheTTL * 1000)
await waitFor(ctx.nextConfigImages.minimumCacheTTL * 1000)
const [three, four] = await Promise.all([
fetchWithDuration(ctx.appPort, '/_next/image', query, opts),
......@@ -968,7 +1008,17 @@ export function runTests(ctx) {
it('should use cache and stale-while-revalidate when query is the same for internal image', async () => {
await cleanImagesDir(ctx)
const query = { url: '/test.png', w: ctx.w, q: 80 }
if (globalThis.isrImgQuality) {
globalThis.isrImgQuality++
} else {
globalThis.isrImgQuality = 80
}
const query = {
url: '/api/stateful/test.png',
w: ctx.w,
q: globalThis.isrImgQuality,
}
const opts = { headers: { accept: 'image/webp' } }
const one = await fetchWithDuration(
......@@ -1010,16 +1060,15 @@ export function runTests(ctx) {
const json2 = await fsToJson(ctx.imagesDir)
expect(json2).toStrictEqual(json1)
if (ctx.minimumCacheTTL) {
if (ctx.nextConfigImages?.minimumCacheTTL) {
// Wait until expired so we can confirm image is regenerated
await waitFor(ctx.minimumCacheTTL * 1000)
await waitFor(ctx.nextConfigImages.minimumCacheTTL * 1000)
const [three, four] = await Promise.all([
fetchWithDuration(ctx.appPort, '/_next/image', query, opts),
fetchWithDuration(ctx.appPort, '/_next/image', query, opts),
])
expect(three.duration).toBeLessThan(one.duration)
expect(three.res.status).toBe(200)
expect(three.res.headers.get('X-Nextjs-Cache')).toBe('STALE')
expect(three.res.headers.get('Content-Type')).toBe('image/webp')
......@@ -1027,7 +1076,6 @@ export function runTests(ctx) {
`${contentDispositionType}; filename="test.webp"`
)
expect(four.duration).toBeLessThan(one.duration)
expect(four.res.status).toBe(200)
expect(four.res.headers.get('X-Nextjs-Cache')).toBe('STALE')
expect(four.res.headers.get('Content-Type')).toBe('image/webp')
......@@ -1069,7 +1117,7 @@ export function runTests(ctx) {
}
})
if (ctx.dangerouslyAllowSVG) {
if (ctx.nextConfigImages?.dangerouslyAllowSVG) {
it('should use cached image file when parameters are the same for svg', async () => {
await cleanImagesDir(ctx)
......@@ -1340,7 +1388,7 @@ export function runTests(ctx) {
}
}
export const setupTests = (ctx) => {
export const setupTests = (ctx: SetupTestsCtx) => {
const nextConfig = new File(join(ctx.appDir, 'next.config.js'))
describe('dev support w/o next.config.js', () => {
......@@ -1349,7 +1397,7 @@ export const setupTests = (ctx) => {
return
}
const size = 384 // defaults defined in server/config.ts
const curCtx = {
const curCtx: RunTestsCtx = {
...ctx,
w: size,
isDev: true,
......@@ -1382,7 +1430,7 @@ export const setupTests = (ctx) => {
describe('dev support with next.config.js', () => {
const size = 400
const curCtx = {
const curCtx: RunTestsCtx = {
...ctx,
w: size,
isDev: true,
......@@ -1394,7 +1442,7 @@ export const setupTests = (ctx) => {
'assets.vercel.com',
'image-optimization-test.vercel.app',
],
formats: ['image/avif', 'image/webp'],
formats: ['image/avif', 'image/webp'] as any,
deviceSizes: [largeSize],
imageSizes: [size],
...ctx.nextConfigImages,
......@@ -1425,15 +1473,15 @@ export const setupTests = (ctx) => {
runTests(curCtx)
})
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'Production Mode Server support w/o next.config.js',
() => {
;(process.env.TURBOPACK_DEV || process.env.TURBOPACK_BUILD
? describe.skip
: describe)('Production Mode Server support w/o next.config.js', () => {
if (ctx.nextConfigImages) {
// skip this test because it requires next.config.js
return
}
const size = 384 // defaults defined in server/config.ts
const curCtx = {
const curCtx: RunTestsCtx = {
...ctx,
w: size,
isDev: false,
......@@ -1462,13 +1510,12 @@ export const setupTests = (ctx) => {
})
runTests(curCtx)
}
)
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'Production Mode Server support with next.config.js',
() => {
})
;(process.env.TURBOPACK_DEV || process.env.TURBOPACK_BUILD
? describe.skip
: describe)('Production Mode Server support with next.config.js', () => {
const size = 399
const curCtx = {
const curCtx: RunTestsCtx = {
...ctx,
w: size,
isDev: false,
......@@ -1480,7 +1527,7 @@ export const setupTests = (ctx) => {
'assets.vercel.com',
'image-optimization-test.vercel.app',
],
formats: ['image/avif', 'image/webp'],
formats: ['image/avif', 'image/webp'] as any,
deviceSizes: [size, largeSize],
...ctx.nextConfigImages,
},
......@@ -1510,6 +1557,5 @@ export const setupTests = (ctx) => {
})
runTests(curCtx)
}
)
})
}
This diff is collapsed.
......@@ -22,6 +22,10 @@ describe('detectContentType', () => {
const buffer = await getImage('./images/test.svg')
expect(detectContentType(buffer)).toBe('image/svg+xml')
})
it('should return svg for inline svg', async () => {
const buffer = await getImage('./images/test-inline.svg')
expect(detectContentType(buffer)).toBe('image/svg+xml')
})
it('should return avif', async () => {
const buffer = await getImage('./images/test.avif')
expect(detectContentType(buffer)).toBe('image/avif')
......
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="400" height="400">
<path d="M0 200v200h400V0H0v200zm240.1-11.8 39.6 69.3-39.8.3c-22 .1-57.8.1-79.8 0l-39.8-.3 39.6-69.3c21.7-38 39.8-69.2 40.1-69.2.3 0 18.4 31.2 40.1 69.2z"/>
</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