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.
| 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>`. |
| `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. |
......@@ -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
For an overview of the Image component features and usage guidelines, see:
......
......@@ -27,6 +27,10 @@ module.exports = {
minimumCacheTTL: 60,
// ordered list of acceptable optimized image formats (mime types)
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({
isLazy = false
}
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
unoptimized = true
}
if (process.env.NODE_ENV !== 'production') {
if (!src) {
throw new Error(
......
......@@ -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) {
......
......@@ -29,16 +29,22 @@ export type ImageConfigComplete = {
path: string
/** @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) */
disableStaticImages?: boolean
disableStaticImages: boolean
/** @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) */
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>
......@@ -52,4 +58,6 @@ export const imageConfigDefault: ImageConfigComplete = {
disableStaticImages: false,
minimumCacheTTL: 60,
formats: ['image/webp'],
dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
}
......@@ -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) {
const vector = VECTOR_TYPES.includes(upstreamType)
const animate =
......@@ -576,14 +586,15 @@ function getFileNameWithExtension(
return `${fileName}.${extension}`
}
export function setResponseHeaders(
function setResponseHeaders(
req: IncomingMessage,
res: ServerResponse,
url: string,
etag: string,
contentType: string | null,
isStatic: boolean,
xCache: XCacheHeader
xCache: XCacheHeader,
contentSecurityPolicy: string
) {
res.setHeader('Vary', 'Accept')
res.setHeader(
......@@ -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)
return { finished: false }
......@@ -621,7 +634,8 @@ export function sendResponse(
extension: string,
buffer: Buffer,
isStatic: boolean,
xCache: XCacheHeader
xCache: XCacheHeader,
contentSecurityPolicy: string
) {
const contentType = getContentType(extension)
const etag = getHash([buffer])
......@@ -632,7 +646,8 @@ export function sendResponse(
etag,
contentType,
isStatic,
xCache
xCache,
contentSecurityPolicy
)
if (!result.finished) {
res.end(buffer)
......
......@@ -255,7 +255,8 @@ export default class NextNodeServer extends BaseServer {
cacheEntry.value.extension,
cacheEntry.value.buffer,
paramsResult.isStatic,
cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT'
cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',
imagesConfig.contentSecurityPolicy
)
} catch (err) {
if (err instanceof ImageError) {
......
......@@ -208,7 +208,7 @@ function runTests(mode) {
)
await check(
() => browser.eval(`document.getElementById("img3").currentSrc`),
/test(.*)svg/
/test\.svg/
)
await check(
() => browser.eval(`document.getElementById("img4").currentSrc`),
......@@ -224,7 +224,7 @@ function runTests(mode) {
)
await check(
() => browser.eval(`document.getElementById("msg3").textContent`),
'loaded 1 img3 with dimensions 266x266'
'loaded 1 img3 with dimensions 400x400'
)
await check(
() => browser.eval(`document.getElementById("msg4").textContent`),
......@@ -1077,7 +1077,7 @@ function runTests(mode) {
expect(
await hasImageMatchingUrl(
browser,
`http://localhost:${appPort}/_next/image?url=%2Ftest.svg&w=828&q=75`
`http://localhost:${appPort}/test.svg`
)
).toBe(true)
expect(
......
......@@ -224,6 +224,56 @@ describe('Image Optimizer', () => {
`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
......@@ -240,11 +290,13 @@ describe('Image Optimizer', () => {
describe('Server support for minimumCacheTTL in next.config.js', () => {
const size = 96 // defaults defined in server/config.ts
const dangerouslyAllowSVG = true
const ctx = {
w: size,
isDev: false,
domains,
minimumCacheTTL,
dangerouslyAllowSVG,
imagesDir,
appDir,
}
......@@ -253,6 +305,7 @@ describe('Image Optimizer', () => {
images: {
domains,
minimumCacheTTL,
dangerouslyAllowSVG,
},
})
ctx.nextOutput = ''
......
......@@ -186,29 +186,39 @@ export function runTests(ctx) {
expect(isAnimated(await res.buffer())).toBe(true)
})
it('should maintain vector svg', async () => {
const query = { w: ctx.w, q: 90, url: '/test.svg' }
const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('image/svg+xml')
expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=0, must-revalidate`
)
// SVG is compressible so will have accept-encoding set from
// compression
expect(res.headers.get('Vary')).toMatch(/^Accept(,|$)/)
expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"`
)
const actual = await res.text()
const expected = await fs.readFile(
join(ctx.appDir, 'public', 'test.svg'),
'utf8'
)
expect(actual).toMatch(expected)
})
if (ctx.dangerouslyAllowSVG) {
it('should maintain vector svg', async () => {
const query = { w: ctx.w, q: 90, url: '/test.svg' }
const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('image/svg+xml')
expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=0, must-revalidate`
)
// SVG is compressible so will have accept-encoding set from
// compression
expect(res.headers.get('Vary')).toMatch(/^Accept(,|$)/)
expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"`
)
const actual = await res.text()
const expected = await fs.readFile(
join(ctx.appDir, 'public', 'test.svg'),
'utf8'
)
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 () => {
const query = { w: ctx.w, q: 90, url: `/test.ico` }
......@@ -778,41 +788,43 @@ export function runTests(ctx) {
}
})
it('should use cached image file when parameters are the same for svg', async () => {
await cleanImagesDir(ctx)
if (ctx.dangerouslyAllowSVG) {
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 opts = { headers: { accept: 'image/webp' } }
const query = { url: '/test.svg', w: ctx.w, q: 80 }
const opts = { headers: { accept: 'image/webp' } }
const res1 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res1.status).toBe(200)
expect(res1.headers.get('X-Nextjs-Cache')).toBe('MISS')
expect(res1.headers.get('Content-Type')).toBe('image/svg+xml')
expect(res1.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"`
)
const etagOne = res1.headers.get('etag')
const res1 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res1.status).toBe(200)
expect(res1.headers.get('X-Nextjs-Cache')).toBe('MISS')
expect(res1.headers.get('Content-Type')).toBe('image/svg+xml')
expect(res1.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"`
)
const etagOne = res1.headers.get('etag')
let json1
await check(async () => {
json1 = await fsToJson(ctx.imagesDir)
return Object.keys(json1).some((dir) => {
return Object.keys(json1[dir]).some((file) => file.includes(etagOne))
})
? 'success'
: 'fail'
}, 'success')
let json1
await check(async () => {
json1 = await fsToJson(ctx.imagesDir)
return Object.keys(json1).some((dir) => {
return Object.keys(json1[dir]).some((file) => file.includes(etagOne))
})
? 'success'
: 'fail'
}, 'success')
const res2 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res2.status).toBe(200)
expect(res2.headers.get('X-Nextjs-Cache')).toBe('HIT')
expect(res2.headers.get('Content-Type')).toBe('image/svg+xml')
expect(res2.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"`
)
const json2 = await fsToJson(ctx.imagesDir)
expect(json2).toStrictEqual(json1)
})
const res2 = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res2.status).toBe(200)
expect(res2.headers.get('X-Nextjs-Cache')).toBe('HIT')
expect(res2.headers.get('Content-Type')).toBe('image/svg+xml')
expect(res2.headers.get('Content-Disposition')).toBe(
`inline; filename="test.svg"`
)
const json2 = await fsToJson(ctx.imagesDir)
expect(json2).toStrictEqual(json1)
})
}
it('should use cached image file when parameters are the same for animated gif', async () => {
await cleanImagesDir(ctx)
......
......@@ -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) => {
})
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
try {
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