ankane / chartkick

Create beautiful JavaScript charts with one line of Ruby
https://chartkick.com
MIT License
6.33k stars 565 forks source link

CSP compliance breaks when used with Turbo Drive w/ and random nonce generator #600

Closed tonywok closed 1 year ago

tonywok commented 1 year ago

Hi there,

Thank you for your time and work on this library.

First

I see there is existing documentation and are a handful of issues related to configuring CSP, but I think this is slightly different because it's related to the interplay between the default recommended nonce generation strategy, turbo and CSP. Apologies if I somehow managed to miss somewhere this is being discussed.

Describe the bug

When using turbo drive, it seems very likely folks using a CSP will run into violations due to the generated CSP nonce not matching the nonce used in the script tags on turbo visit.

To reproduce

I render a chart successfully on load. I can observe that the nonce generated alongside the script tag matches the csp nonce in the document head. All is well.

If I navigate away (a turbo drive visit) and back (another turbo drive visit), I observe that the nonce used in the script tags no-longer matches the nonce in the head.


Would you expect this to work? I suspect this is a limitation of the inline script tag approach under the circumstances described above.

If anyone else is running into this, you can, of course, disable turbo when clicking whatever thing ultimately lands you on a view displaying a chart, but this can be a kind of jarring user experience.

Another thing would be to use a session based nonce generation strategy like:

Rails.application.config.content_security_policy_nonce_generator = -> request { request.session.id.to_s }

I suspect many folks will run into this, since it seems the default recommended strategy at the moment is a unique per request approach:


Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }

So perhaps this is partially solved by some additional documentation (which I can help with).

Thanks again :)

tonywok commented 1 year ago

I suspect this is what https://github.com/ankane/chartkick/issues/585 ran into as well.

ankane commented 1 year ago

Hey @tonywok, thanks for sharing. This seems like expected behavior. fwiw, Rails 7 uses request.session.id.to_s in the generated initializer. Since this isn't really specific to Chartkick, I'm not sure there's anything more to do here.

tonywok commented 1 year ago

Gotcha. Alright, appreciate your response.