Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let script to use setAttribute 'style' without breaking 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?

like image 426
maxvektor Avatar asked Mar 25 '26 10:03

maxvektor


1 Answers

2018-10-06 update

The original answer here is still correct for now — because with CSP as currently implemented in browsers at least, there’s still no way to have dynamically injected styles at all without specifying unsafe-inline, and specifying unsafe-inline basically negates the whole purpose of CSP.

However, CSP3 adds a new unsafe-hashes expression for enabling you to allow particular inline scripts/styles. See https://w3c.github.io/webappsec-csp/#unsafe-hashes-usage, and see Explainer: ‘unsafe-hashes’, ‘unsafe-inline-attributes’ and CSP directive versioning. It hasn’t shipped in any browsers yet, though. So for the time being, the answer below still fully applies.


The only way to allow style attributes is to use unsafe-inline. It doesn’t matter whether the style attributes are coming from a different origin or from self—they’re still going to be considered a CSP violation unless you have unsafe-inline.

Specifically, one solution that won’t work for style attributes is to use a nonce or hash—because in CSP, nonce and hash usage are only defined for style and script elements; 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 style attribute, your browser will still handle it as a violation.

The bottom line is that since unsafe-inline is the only way to allow style attributes—but using unsafe-inline pretty 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 style attributes—neither directly from your own markup/code nor by way of any third-party code.

like image 132
sideshowbarker Avatar answered Mar 26 '26 23:03

sideshowbarker