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?
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 for more details 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.
Yes, there is a way.
There is much discussion about this here: https://github.com/w3c/webappsec-csp/issues/212
Which is succinctly summarised towards the end:
CSP is checked at parsing and blocks parsing the style attribute. Any direct operations go through.
Using setAttribute
invokes the HTML parser and CSP is triggered.
So, instead of:
.setAttribute("style","background:red"); // needs HTML parsing
You would need:
.style.background = "red"; // direct manipulation
It may sound odd that one method works and the other does not, I think the understanding here is that there is a subtle difference between HTML attributes and DOM properties. https://joji.me/en-us/blog/html-attribute-vs-dom-property/
来源:https://stackoverflow.com/questions/44608927/how-to-let-script-to-use-setattribute-style-without-breaking-csp