threepointone/glamor

Support CSP Restrictions Without Nonce Attribute

Closed this issue · 2 comments

I have a project that I would like to explore using a css-in-js library like glamor, glamorous, etc.

However, the Content-Security-Policy restrictions for this project are such that style tags are not allowed to be injected onto the page, and must be served in the initial static html file.

One solution around this would be to provide a nonce attribute. Styled components accomplishes this through an undocumented feature of webpack (See Issue).

However, IE11 does not support nonce attributes, and CSP Level 2 in general, which is a browser I need to support for this project.

More info on this security policy here.

I had an initial discussion on this topic on Twitter. But I believe the discussion on this problem goes deeper than Twitter allows for. NOTE: I had mentioned the idea of being able to target an already existing style tag, I believe I was mistaken, and I don't believe this will work for the given CSP restrictions.

I've created a minimal server example that should (theoretically) produce the same CSP restrictions for loading styles.

There may be another way around these CSP settings that are equally as secure, but allow for dynamic styles from a trusted source such as glamor. But I am not aware of any. (I'm also not an expert in CSP 😞 )

I suppose one way around this would be to somehow statically analyze the styles and generate a stylesheet at build time. However, I think we would lose out on one of the very powerful features of glamor and related libraries: dynamically re-defining styles based on props, state, and theming.

Came across this via a discussion about emotion. I am not using glamor, but thought I would add some thoughts, especially as I think people looking at stricter CSP rules is a good thing, and that css-in-js libs working within those envs would be great!

Two points:

  1. IE11's CSP support is basically 0, so there's no point working around it. It will just ignore CSP rules regardless, so style tags will work just fine there.

  2. I think a nonce is a good solution to this problem, as discussed emotion-js/emotion#403 there are two approaches that I can see (one of which styled-components is using already).

This is a great point. I actually had a similar discussion on styled-components about this. I agree, the solution is a nonce attribute with the understanding that there's simply no way to prevent inline style injection in IE

I'm going to close this issue since my question has been effectively resolved