Unverified Commit 8a55612c authored by Steven's avatar Steven Committed by GitHub

Add image config for `dangerouslyAllowSVG` and `contentSecurityPolicy` (#34431)

## Feature

- [x] Integration tests added
- [x] Documentation added
- [x] Errors have helpful link attached, see `contributing.md`
Co-authored-by: 's avatarLee Robinson <9113740+leerob@users.noreply.github.com>
parent 9639fe70
...@@ -16,7 +16,8 @@ description: Enable Image Optimization with the built-in Image component. ...@@ -16,7 +16,8 @@ description: Enable Image Optimization with the built-in Image component.
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------- | | --------- | ------------------------------------------------------------------------------------------------- |
| `v12.0.9` | `lazyRoot` prop added | | `v12.1.0` | `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. |
| `v12.0.9` | `lazyRoot` prop added. |
| `v12.0.0` | `formats` configuration added.<br/>AVIF support added.<br/>Wrapper `<div>` changed to `<span>`. | | `v12.0.0` | `formats` configuration added.<br/>AVIF support added.<br/>Wrapper `<div>` changed to `<span>`. |
| `v11.1.0` | `onLoadingComplete` and `lazyBoundary` props added. | | `v11.1.0` | `onLoadingComplete` and `lazyBoundary` props added. |
| `v11.0.0` | `src` prop support for static import.<br/>`placeholder` prop added.<br/>`blurDataURL` prop added. | | `v11.0.0` | `src` prop support for static import.<br/>`placeholder` prop added.<br/>`blurDataURL` prop added. |
...@@ -439,6 +440,21 @@ module.exports = { ...@@ -439,6 +440,21 @@ module.exports = {
} }
``` ```
### Dangerously Allow SVG
The default [loader](#loader) does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/advanced-features/security-headers.md).
If you need to serve SVG images with the default Image Optimization API, you can set `dangerouslyAllowSVG` and `contentSecurityPolicy` inside your `next.config.js`:
```js
module.exports = {
images: {
dangerouslyAllowSVG: true,
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
}
```
## Related ## Related
For an overview of the Image component features and usage guidelines, see: For an overview of the Image component features and usage guidelines, see:
......
...@@ -27,6 +27,10 @@ module.exports = { ...@@ -27,6 +27,10 @@ module.exports = {
minimumCacheTTL: 60, minimumCacheTTL: 60,
// ordered list of acceptable optimized image formats (mime types) // ordered list of acceptable optimized image formats (mime types)
formats: ['image/webp'], formats: ['image/webp'],
// enable dangerous use of SVG images
dangerouslyAllowSVG: false,
// set the Content-Security-Policy header
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
}, },
} }
``` ```
......
...@@ -385,6 +385,10 @@ export default function Image({ ...@@ -385,6 +385,10 @@ export default function Image({
isLazy = false isLazy = false
} }
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
unoptimized = true
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( throw new Error(
......
...@@ -351,6 +351,28 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -351,6 +351,28 @@ function assignDefaults(userConfig: { [key: string]: any }) {
) )
} }
} }
if (
typeof images.dangerouslyAllowSVG !== 'undefined' &&
typeof images.dangerouslyAllowSVG !== 'boolean'
) {
throw new Error(
`Specified images.dangerouslyAllowSVG should be a boolean
', '
)}), received (${images.dangerouslyAllowSVG}).\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`
)
}
if (
typeof images.contentSecurityPolicy !== 'undefined' &&
typeof images.contentSecurityPolicy !== 'string'
) {
throw new Error(
`Specified images.contentSecurityPolicy should be a string
', '
)}), received (${images.contentSecurityPolicy}).\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`
)
}
} }
if (result.webpack5 === false) { if (result.webpack5 === false) {
......
...@@ -29,16 +29,22 @@ export type ImageConfigComplete = { ...@@ -29,16 +29,22 @@ export type ImageConfigComplete = {
path: string path: string
/** @see [Image domains configuration](https://nextjs.org/docs/basic-features/image-optimization#domains) */ /** @see [Image domains configuration](https://nextjs.org/docs/basic-features/image-optimization#domains) */
domains?: string[] domains: string[]
/** @see [Cache behavior](https://nextjs.org/docs/api-reference/next/image#caching-behavior) */ /** @see [Cache behavior](https://nextjs.org/docs/api-reference/next/image#caching-behavior) */
disableStaticImages?: boolean disableStaticImages: boolean
/** @see [Cache behavior](https://nextjs.org/docs/api-reference/next/image#caching-behavior) */ /** @see [Cache behavior](https://nextjs.org/docs/api-reference/next/image#caching-behavior) */
minimumCacheTTL?: number minimumCacheTTL: number
/** @see [Acceptable formats](https://nextjs.org/docs/api-reference/next/image#acceptable-formats) */ /** @see [Acceptable formats](https://nextjs.org/docs/api-reference/next/image#acceptable-formats) */
formats?: ImageFormat[] formats: ImageFormat[]
/** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */
dangerouslyAllowSVG: boolean
/** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */
contentSecurityPolicy: string
} }
export type ImageConfig = Partial<ImageConfigComplete> export type ImageConfig = Partial<ImageConfigComplete>
...@@ -52,4 +58,6 @@ export const imageConfigDefault: ImageConfigComplete = { ...@@ -52,4 +58,6 @@ export const imageConfigDefault: ImageConfigComplete = {
disableStaticImages: false, disableStaticImages: false,
minimumCacheTTL: 60, minimumCacheTTL: 60,
formats: ['image/webp'], formats: ['image/webp'],
dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
} }
...@@ -380,6 +380,16 @@ export async function imageOptimizer( ...@@ -380,6 +380,16 @@ export async function imageOptimizer(
} }
} }
if (upstreamType === SVG && !nextConfig.images.dangerouslyAllowSVG) {
console.error(
`The requested resource "${href}" has type "${upstreamType}" but dangerouslyAllowSVG is disabled`
)
throw new ImageError(
400,
'"url" parameter is valid but image type is not allowed'
)
}
if (upstreamType) { if (upstreamType) {
const vector = VECTOR_TYPES.includes(upstreamType) const vector = VECTOR_TYPES.includes(upstreamType)
const animate = const animate =
...@@ -576,14 +586,15 @@ function getFileNameWithExtension( ...@@ -576,14 +586,15 @@ function getFileNameWithExtension(
return `${fileName}.${extension}` return `${fileName}.${extension}`
} }
export function setResponseHeaders( function setResponseHeaders(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
url: string, url: string,
etag: string, etag: string,
contentType: string | null, contentType: string | null,
isStatic: boolean, isStatic: boolean,
xCache: XCacheHeader xCache: XCacheHeader,
contentSecurityPolicy: string
) { ) {
res.setHeader('Vary', 'Accept') res.setHeader('Vary', 'Accept')
res.setHeader( res.setHeader(
...@@ -608,7 +619,9 @@ export function setResponseHeaders( ...@@ -608,7 +619,9 @@ export function setResponseHeaders(
) )
} }
res.setHeader('Content-Security-Policy', `script-src 'none'; sandbox;`) if (contentSecurityPolicy) {
res.setHeader('Content-Security-Policy', contentSecurityPolicy)
}
res.setHeader('X-Nextjs-Cache', xCache) res.setHeader('X-Nextjs-Cache', xCache)
return { finished: false } return { finished: false }
...@@ -621,7 +634,8 @@ export function sendResponse( ...@@ -621,7 +634,8 @@ export function sendResponse(
extension: string, extension: string,
buffer: Buffer, buffer: Buffer,
isStatic: boolean, isStatic: boolean,
xCache: XCacheHeader xCache: XCacheHeader,
contentSecurityPolicy: string
) { ) {
const contentType = getContentType(extension) const contentType = getContentType(extension)
const etag = getHash([buffer]) const etag = getHash([buffer])
...@@ -632,7 +646,8 @@ export function sendResponse( ...@@ -632,7 +646,8 @@ export function sendResponse(
etag, etag,
contentType, contentType,
isStatic, isStatic,
xCache xCache,
contentSecurityPolicy
) )
if (!result.finished) { if (!result.finished) {
res.end(buffer) res.end(buffer)
......
...@@ -255,7 +255,8 @@ export default class NextNodeServer extends BaseServer { ...@@ -255,7 +255,8 @@ export default class NextNodeServer extends BaseServer {
cacheEntry.value.extension, cacheEntry.value.extension,
cacheEntry.value.buffer, cacheEntry.value.buffer,
paramsResult.isStatic, paramsResult.isStatic,
cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT' cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',
imagesConfig.contentSecurityPolicy
) )
} catch (err) { } catch (err) {
if (err instanceof ImageError) { if (err instanceof ImageError) {
......
...@@ -208,7 +208,7 @@ function runTests(mode) { ...@@ -208,7 +208,7 @@ function runTests(mode) {
) )
await check( await check(
() => browser.eval(`document.getElementById("img3").currentSrc`), () => browser.eval(`document.getElementById("img3").currentSrc`),
/test(.*)svg/ /test\.svg/
) )
await check( await check(
() => browser.eval(`document.getElementById("img4").currentSrc`), () => browser.eval(`document.getElementById("img4").currentSrc`),
...@@ -224,7 +224,7 @@ function runTests(mode) { ...@@ -224,7 +224,7 @@ function runTests(mode) {
) )
await check( await check(
() => browser.eval(`document.getElementById("msg3").textContent`), () => browser.eval(`document.getElementById("msg3").textContent`),
'loaded 1 img3 with dimensions 266x266' 'loaded 1 img3 with dimensions 400x400'
) )
await check( await check(
() => browser.eval(`document.getElementById("msg4").textContent`), () => browser.eval(`document.getElementById("msg4").textContent`),
...@@ -1077,7 +1077,7 @@ function runTests(mode) { ...@@ -1077,7 +1077,7 @@ function runTests(mode) {
expect( expect(
await hasImageMatchingUrl( await hasImageMatchingUrl(
browser, browser,
`http://localhost:${appPort}/_next/image?url=%2Ftest.svg&w=828&q=75` `http://localhost:${appPort}/test.svg`
) )
).toBe(true) ).toBe(true)
expect( expect(
......
...@@ -224,6 +224,56 @@ describe('Image Optimizer', () => { ...@@ -224,6 +224,56 @@ describe('Image Optimizer', () => {
`Specified images.loader property (imgix) also requires images.path property to be assigned to a URL prefix.` `Specified images.loader property (imgix) also requires images.path property to be assigned to a URL prefix.`
) )
}) })
it('should error when images.dangerouslyAllowSVG is not a boolean', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
dangerouslyAllowSVG: 'foo',
},
})
)
let stderr = ''
app = await launchApp(appDir, await findPort(), {
onStderr(msg) {
stderr += msg || ''
},
})
await waitFor(1000)
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(stderr).toContain(
`Specified images.dangerouslyAllowSVG should be a boolean`
)
})
it('should error when images.contentSecurityPolicy is not a string', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
contentSecurityPolicy: 1,
},
})
)
let stderr = ''
app = await launchApp(appDir, await findPort(), {
onStderr(msg) {
stderr += msg || ''
},
})
await waitFor(1000)
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(stderr).toContain(
`Specified images.contentSecurityPolicy should be a string`
)
})
}) })
// domains for testing // domains for testing
...@@ -240,11 +290,13 @@ describe('Image Optimizer', () => { ...@@ -240,11 +290,13 @@ describe('Image Optimizer', () => {
describe('Server support for minimumCacheTTL in next.config.js', () => { describe('Server support for minimumCacheTTL in next.config.js', () => {
const size = 96 // defaults defined in server/config.ts const size = 96 // defaults defined in server/config.ts
const dangerouslyAllowSVG = true
const ctx = { const ctx = {
w: size, w: size,
isDev: false, isDev: false,
domains, domains,
minimumCacheTTL, minimumCacheTTL,
dangerouslyAllowSVG,
imagesDir, imagesDir,
appDir, appDir,
} }
...@@ -253,6 +305,7 @@ describe('Image Optimizer', () => { ...@@ -253,6 +305,7 @@ describe('Image Optimizer', () => {
images: { images: {
domains, domains,
minimumCacheTTL, minimumCacheTTL,
dangerouslyAllowSVG,
}, },
}) })
ctx.nextOutput = '' ctx.nextOutput = ''
......
...@@ -186,29 +186,39 @@ export function runTests(ctx) { ...@@ -186,29 +186,39 @@ export function runTests(ctx) {
expect(isAnimated(await res.buffer())).toBe(true) expect(isAnimated(await res.buffer())).toBe(true)
}) })
it('should maintain vector svg', async () => { if (ctx.dangerouslyAllowSVG) {
const query = { w: ctx.w, q: 90, url: '/test.svg' } it('should maintain vector svg', async () => {
const opts = { headers: { accept: 'image/webp' } } const query = { w: ctx.w, q: 90, url: '/test.svg' }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const opts = { headers: { accept: 'image/webp' } }
expect(res.status).toBe(200) const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.headers.get('Content-Type')).toContain('image/svg+xml') expect(res.status).toBe(200)
expect(res.headers.get('Cache-Control')).toBe( expect(res.headers.get('Content-Type')).toContain('image/svg+xml')
`public, max-age=0, must-revalidate` expect(res.headers.get('Cache-Control')).toBe(
) `public, max-age=0, must-revalidate`
// SVG is compressible so will have accept-encoding set from )
// compression // SVG is compressible so will have accept-encoding set from
expect(res.headers.get('Vary')).toMatch(/^Accept(,|$)/) // compression
expect(res.headers.get('etag')).toBeTruthy() expect(res.headers.get('Vary')).toMatch(/^Accept(,|$)/)
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('etag')).toBeTruthy()
`inline; filename="test.svg"` expect(res.headers.get('Content-Disposition')).toBe(
) `inline; filename="test.svg"`
const actual = await res.text() )
const expected = await fs.readFile( const actual = await res.text()
join(ctx.appDir, 'public', 'test.svg'), const expected = await fs.readFile(
'utf8' join(ctx.appDir, 'public', 'test.svg'),
) 'utf8'
expect(actual).toMatch(expected) )
}) expect(actual).toMatch(expected)
})
} else {
it('should not allow vector svg', async () => {
const query = { w: ctx.w, q: 35, url: '/test.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('valid but image type is not allowed')
})
}
it('should maintain ico format', async () => { it('should maintain ico format', async () => {
const query = { w: ctx.w, q: 90, url: `/test.ico` } const query = { w: ctx.w, q: 90, url: `/test.ico` }
...@@ -778,41 +788,43 @@ export function runTests(ctx) { ...@@ -778,41 +788,43 @@ export function runTests(ctx) {
} }
}) })
it('should use cached image file when parameters are the same for svg', async () => { if (ctx.dangerouslyAllowSVG) {
await cleanImagesDir(ctx) it('should use cached image file when parameters are the same for svg', async () => {
await cleanImagesDir(ctx)
const query = { url: '/test.svg', w: ctx.w, q: 80 } const query = { url: '/test.svg', w: ctx.w, q: 80 }
const opts = { headers: { accept: 'image/webp' } } const opts = { headers: { accept: 'image/webp' } }
const res1 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const res1 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res1.status).toBe(200) expect(res1.status).toBe(200)
expect(res1.headers.get('X-Nextjs-Cache')).toBe('MISS') expect(res1.headers.get('X-Nextjs-Cache')).toBe('MISS')
expect(res1.headers.get('Content-Type')).toBe('image/svg+xml') expect(res1.headers.get('Content-Type')).toBe('image/svg+xml')
expect(res1.headers.get('Content-Disposition')).toBe( expect(res1.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"` `inline; filename="test.svg"`
) )
const etagOne = res1.headers.get('etag') const etagOne = res1.headers.get('etag')
let json1 let json1
await check(async () => { await check(async () => {
json1 = await fsToJson(ctx.imagesDir) json1 = await fsToJson(ctx.imagesDir)
return Object.keys(json1).some((dir) => { return Object.keys(json1).some((dir) => {
return Object.keys(json1[dir]).some((file) => file.includes(etagOne)) return Object.keys(json1[dir]).some((file) => file.includes(etagOne))
}) })
? 'success' ? 'success'
: 'fail' : 'fail'
}, 'success') }, 'success')
const res2 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const res2 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res2.status).toBe(200) expect(res2.status).toBe(200)
expect(res2.headers.get('X-Nextjs-Cache')).toBe('HIT') expect(res2.headers.get('X-Nextjs-Cache')).toBe('HIT')
expect(res2.headers.get('Content-Type')).toBe('image/svg+xml') expect(res2.headers.get('Content-Type')).toBe('image/svg+xml')
expect(res2.headers.get('Content-Disposition')).toBe( expect(res2.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"` `inline; filename="test.svg"`
) )
const json2 = await fsToJson(ctx.imagesDir) const json2 = await fsToJson(ctx.imagesDir)
expect(json2).toStrictEqual(json1) expect(json2).toStrictEqual(json1)
}) })
}
it('should use cached image file when parameters are the same for animated gif', async () => { it('should use cached image file when parameters are the same for animated gif', async () => {
await cleanImagesDir(ctx) await cleanImagesDir(ctx)
......
...@@ -39,4 +39,8 @@ module.exports = { ...@@ -39,4 +39,8 @@ module.exports = {
}, },
] ]
}, },
images: {
// Make sure we have sane default CSP, even when SVG is enabled
dangerouslyAllowSVG: true,
},
} }
...@@ -319,7 +319,7 @@ module.exports = (context) => { ...@@ -319,7 +319,7 @@ module.exports = (context) => {
}) })
if (browserName !== 'internet explorer') { if (browserName !== 'internet explorer') {
it('should not execute script embedded inside svg image', async () => { it('should not execute script embedded inside svg image, even if dangerouslyAllowSVG=true', async () => {
let browser let browser
try { try {
browser = await webdriver(context.appPort, '/svg-image') browser = await webdriver(context.appPort, '/svg-image')
......
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