How to let script to use setAttribute 'style' without braking CSP
Im am trying to keep my CSP policy as strict as possible. I need to include 3d party component in my bundle. But it uses
element.setAttribute('style'...) method which breaks CSP. Is there a way to allow this particular script to inline styles in that manner?
The only way to allow
styleattributes is to use
unsafe-inline. It doesn’t matter whether the
styleattributes are coming from a different origin or from
self—they’re still going to be considered a CSP violation unless you have
Specifically, one solution that won’t work for
styleattributes is to use a nonce or hash—because in CSP, nonce and hash usage are only defined for
scriptelements; the spec has a Hash usage for style elements section that explicitly omits defining hash use for style attributes.
So even if in your policy you specify the correct hash for the contents of a
styleattribute, your browser will still handle it as a violation.
The bottom line is that since
unsafe-inlineis the only way to allow
unsafe-inlinepretty much completely defeats the purpose of having any CSP policy to begin with—the only safe solution from a CSP perspective is just to never use
styleattributes—neither directly from your own markup/code nor by way of any third-party code.