node.jspugcontent-security-policyocsp

How to fix CSP script-src-elem Error although it is being defined?


I have something like this in a meta tag in my pug. I have a ton 2 3 CDN in my File.

 meta(http-equiv='Content-Security-Policy' content="default-src * 'unsafe-inline' 'unsafe-eval'; script-src-elem * 'unsafe-inline';"  )

I get an error something like this although I have defined the script-src-elem.

Refused to load the script '<URL>' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. I would really appreciate your help. Thank you in Advance


Solution

  • Let me guess. You use PUG linked with Express. In the Express you use Helmet security middleware.

    The point is that Helmet 4 publishes CSPs by default via an HTTP header, and script-src 'self' is a fragment of this Helmet's default CSP.

    Since you have one CSP published, you can't relax it using a meta tag. In case of 2 CSPS published all sources should pass unscratched through both CSPs. Therefore your script-src-elem * 'unsafe-inline' from meta tag does not trigger violation, but script src 'self' from the CSP HTTP header - does rise it.
    You have to remove meta tag and configute Helmet via helmet.contentSecurityPolicy(options). Or disable CSP in Helmet and use a meta tag:

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