Skip to content

Commit

Permalink
Add CSP to Image Optimization API (#28620)
Browse files Browse the repository at this point in the history
Add CSP header to Image Optimization API
  • Loading branch information
styfle authored Aug 30, 2021
1 parent 8711c5c commit 7afc97c
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 1 deletion.
2 changes: 2 additions & 0 deletions packages/next/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,8 @@ function setResponseHeaders(
res.setHeader('Content-Disposition', `inline; filename="${fileName}"`)
}

res.setHeader('Content-Security-Policy', `script-src 'none'; sandbox;`)

return { finished: false }
}

Expand Down
14 changes: 14 additions & 0 deletions test/integration/production/pages/svg-image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import React from 'react'
import Image from 'next/image'

const Page = () => {
return (
<div>
<h1>SVG with a script tag attempting XSS</h1>
<Image id="img" src="/xss.svg" width="100" height="100" />
<p id="msg">safe</p>
</div>
)
}

export default Page
9 changes: 9 additions & 0 deletions test/integration/production/public/xss.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion test/integration/production/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ describe('Production Usage', () => {
})

it('should contain generated page count in output', async () => {
const pageCount = process.env.NEXT_PRIVATE_TEST_WEBPACK4_MODE ? 37 : 38
const pageCount = process.env.NEXT_PRIVATE_TEST_WEBPACK4_MODE ? 38 : 39
expect(output).toContain(`Generating static pages (0/${pageCount})`)
expect(output).toContain(
`Generating static pages (${pageCount}/${pageCount})`
Expand Down
19 changes: 19 additions & 0 deletions test/integration/production/test/security.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,5 +342,24 @@ module.exports = (context) => {
expect(pathname).toBe('/%2fexample.com')
expect(hostname).not.toBe('example.com')
})

it('should not execute script embedded inside svg image', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/svg-image')
await browser.eval(`document.getElementById("img").scrollIntoView()`)
expect(await browser.elementById('img').getAttribute('src')).toContain(
'xss.svg'
)
expect(await browser.elementById('msg').text()).toBe('safe')
browser = await webdriver(
context.appPort,
'/_next/image?url=%2Fxss.svg&w=256&q=75'
)
expect(await browser.elementById('msg').text()).toBe('safe')
} finally {
if (browser) await browser.close()
}
})
})
}

0 comments on commit 7afc97c

Please sign in to comment.