calyxofheld
calyxofheld

Reputation: 2128

why is this content security policy violation telling me to add a hash that already exists?

When I moved my assets from the Rails asset pipeline to webpacker, I started getting CSP violations that said to add the same hash twice:

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'sha256-LHNh9xw1VeZTANwMt4DeW/YM2X358wyOgpJN8RDGF1U='". Either the 'unsafe-inline' keyword, a hash ('sha256-LHNh9xw1VeZTANwMt4DeW/YM2X358wyOgpJN8RDGF1U='), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

Why is that? I read that webpacker serves files from port 3035 by default, and that this could interfere with the content security policy, so I changed the port in my CSP's connect_src directive to :self, :https, 'https://example.ngrok.io:3000', 'wss://example.ngrok.io:3000' and my webpacker.yml config to this:

development:
 dev_server:
  https: false
  host: localhost
  port: 3000
  public: localhost:3000

3000 being the port my app runs on.

So I guess this is two questions: 1) why is my CSP telling me to add the same hash twice, and 2) does webpacker need to serve files from the same port that my app runs on?

Upvotes: 1

Views: 667

Answers (1)

Halvor Sakshaug
Halvor Sakshaug

Reputation: 3455

The reason is likely that hashes work on inline style tags, not style attributes. Even though the style attribute hash won't work, the browser still suggests it in the error message. The best option is to move the styling into a css file. Your current implementation might work if you add 'unsafe-hashes' of CSP level 3, but this is currently only implemented in Chromium browsers.

Upvotes: 1

Related Questions