How to enable and disable upgradeInsecureRequests csp directive using Helmet 4.4.1 version node.js module

Viewed 2126

I have tried this using Helmet 4.4.1 version both of them below sets to true for upgrade-insecure-requests CSP

upgradeInsecureRequests: [] and upgradeInsecureRequests: ['true']

Which of the above format is correct to use?

4 Answers

This works for me:

app.use(
        helmet.contentSecurityPolicy({
            directives: {
                "script-src": ["'self'"],
                upgradeInsecureRequests: null
            },
        })
    );

Setting upgradeInsecureRequests to null:

upgradeInsecureRequests: null

Solved: we can simply add upgradeInsecureRequests: []

This worked for me:

defaultDirectives = helmet.contentSecurityPolicy.getDefaultDirectives();
delete defaultDirectives['upgrade-insecure-requests'];

app.use( helmet() );
app.use(helmet.contentSecurityPolicy({
  directives: {
    ...defaultDirectives,
  },
}));

The delete part removes the upgrade-insecure-requests key in the defaultDirectives object.

After few hours of trial and errors, I've got it working. I did it like this:

const defaultCspOptions = helmet.contentSecurityPolicy.getDefaultDirectives();
delete defaultCspOptions["upgrade-insecure-requests"]

app.use(helmet({
  contentSecurityPolicy: {
    useDefaults: false,
    directives: { ...defaultCspOptions },
  })
)

Almost like Nico Serrano's answer, yes. In fact it inspired this. I just add useDefaults: false. Otherwise, even though the 'upgrade-insecure-requests' property is no longer exists in the defaultCspOptions, the helmet automatically reappend any missing property with the default value. Rendering the delete part useless.

Related