Skip to content

Commit

Permalink
Respect route-level contentSecurityPolicy: false setting (#262)
Browse files Browse the repository at this point in the history
* Respect route-level `contentSecurityPolicy: false` configuration

Signed-off-by: Alexander Khoroshikh <[email protected]>

* Add test to ensure that route contentSecurityPolicy: false setting is respected

---------

Signed-off-by: Alexander Khoroshikh <[email protected]>
  • Loading branch information
AlexandrHoroshih authored Sep 23, 2024
1 parent 6925055 commit 58362be
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ async function replyDecorators (request, reply, configuration, enableCSP) {
}

async function buildHelmetOnRoutes (request, reply, configuration, enableCSP) {
if (enableCSP === true) {
if (enableCSP === true && configuration.contentSecurityPolicy !== false) {
const cspDirectives = configuration.contentSecurityPolicy
? configuration.contentSecurityPolicy.directives
: helmet.contentSecurityPolicy.getDefaultDirectives()
Expand Down
38 changes: 38 additions & 0 deletions test/routes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,44 @@ test('It should not set default directives when route useDefaults is set to `fal
t.assert.deepStrictEqual(actualResponseHeaders, expected)
})

test('It should not set `content-security-policy` header, if route contentSecurityPolicy is false', async (t) => {
t.plan(1)

const fastify = Fastify()

await fastify.register(helmet, {
global: false,
enableCSPNonces: false,
contentSecurityPolicy: {
directives: {}
}
})

fastify.get(
'/',
{
helmet: {
contentSecurityPolicy: false
}
},
(request, reply) => {
reply.send({ hello: 'world' })
}
)

const response = await fastify.inject({ method: 'GET', path: '/' })

const expected = {
'content-security-policy': undefined
}

const actualResponseHeaders = {
'content-security-policy': response.headers['content-security-policy']
}

t.assert.deepStrictEqual(actualResponseHeaders, expected)
})

test('It should be able to conditionally apply the middlewares through the `helmet` reply decorator', async (t) => {
t.plan(10)

Expand Down

0 comments on commit 58362be

Please sign in to comment.