fix: fixes response.attachment behavior leads to Content-Type Sniffing (#1904)
## Checklist Added security-focused tests to verify: 1. Content-Type is preserved when already set 2. Content-Type is still set when not previously defined (backwards compatibility) 3. The fix prevents XSS vulnerabilities with HTML and SVG files credit "Luca Carettoni of Doyensec LLC" as [requested in the advisory](https://github.com/koajs/koa/security/advisories/GHSA-c5vw-j4hf-j526).
This commit is contained in:
@@ -7,6 +7,28 @@ const request = require('supertest')
|
||||
const Koa = require('../..')
|
||||
|
||||
describe('ctx.attachment([filename])', () => {
|
||||
describe('security: prevent Content-Type override (GHSA-c5vw-j4hf-j526)', () => {
|
||||
it('should NOT override Content-Type when already set', () => {
|
||||
const ctx = context()
|
||||
ctx.response.set('Content-Type', 'application/octet-stream')
|
||||
ctx.attachment('malicious.html')
|
||||
assert.strictEqual(ctx.response.get('Content-Type'), 'application/octet-stream')
|
||||
assert.strictEqual(ctx.response.header['content-disposition'], 'attachment; filename="malicious.html"')
|
||||
})
|
||||
|
||||
it('should preserve safe Content-Type for SVG files', () => {
|
||||
const ctx = context()
|
||||
ctx.response.set('Content-Type', 'application/octet-stream')
|
||||
ctx.attachment('image.svg')
|
||||
assert.strictEqual(ctx.response.get('Content-Type'), 'application/octet-stream')
|
||||
})
|
||||
|
||||
it('should set Content-Type when not previously set', () => {
|
||||
const ctx = context()
|
||||
ctx.attachment('document.pdf')
|
||||
assert.strictEqual(ctx.response.get('Content-Type'), 'application/pdf')
|
||||
})
|
||||
})
|
||||
describe('when given a filename', () => {
|
||||
it('should set the filename param', () => {
|
||||
const ctx = context()
|
||||
|
||||
@@ -351,7 +351,9 @@ module.exports = {
|
||||
*/
|
||||
|
||||
attachment (filename, options) {
|
||||
if (filename) this.type = extname(filename)
|
||||
if (filename && !this.has('Content-Type')) {
|
||||
this.type = extname(filename)
|
||||
}
|
||||
this.set('Content-Disposition', contentDisposition(filename, options))
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user