javascriptcontent-security-policy

Way to handle inline styles added from external library respecting CSP


Is there way to handle inline script/styles added from external library ? In my own styles i just use nonce but i can't add it to external library.

I use tooltip.io and problem appears when library try to run:

function() {
    var n = e("./styles/css/styles.scss")
      , t = document.createElement("style");
    t.innerHTML = n,
    document.head.appendChild(t)
}(),

CSP shows

[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'nonce-b123d558a63bc7e84aa7' ". Either the 'unsafe-inline' keyword, a hash ('sha256-SamqqFx+xVKq8AnoIWgeammNlDl/h4AP94HthfQO43Q='), or a nonce ('nonce-...') is required to enable inline execution.

Is there any way to handle this kind of errors ?


Solution

  • Recently I faced the similar issue for Jquery unobtrusive javascript file I used in one of project it was adding inline style="display:none" on html element Ul So, I prefered Hash approach to allow inline style in this you need to add style-src 'self' 'unsafe-hashes' 'sha-256 {sha hashed string}'

    if you use chrome in chrome developer tools in console where csp violation is shown, in last line of error message it also shows sha-256 string you can add to your content security policy header, so that inline css or js can be allowed by csp, this unsafe-hashes approach is better than unsafe-nonces as nonce needs to be unique per request and hash is irreversible so content matching hash only allowed always

    I feel you should try to open your page which gives error in chrome and see if it shows sha-256 hash as last line in console error message, if you want to manually generate hash like sha-512, you can generate hash for the styles.css generated after ./styles/css/styles.scss is processed and add this hash in csp attribute like

    Content-Security-Policy: default-src 'none'; style-src 'self' 'sha-512{Manually generated sha-512}';
    
    

    last option you can use is unsafe-inline in style src but you can give try for unsafe-hashes which will be better than unsafe-inline