trestle icon indicating copy to clipboard operation
trestle copied to clipboard

Support Rails Content-Security-Policy nonces

Open tuxagon opened this issue 9 months ago • 2 comments

Closes #529

About

This change adds initial support for Content-Security-Policy provided by Rails. This primarily focuses on nonces which are necessary to avoid unsafe-inline. For scripts this is more important, but due to the fact that stylesheets can also support this in Rails, it includes those as well.

I've also updated the sandbox to enable a content security policy, but I didn't fully enable it for styles because it's quite a task to do "properly" and sandbox is more of an example to showcase Trestle from what I understand.

Testing

If you start the sandbox app and open the dev tools, you shouldn't see any violations. Easiest way to see violations in sandbox is to remove :unsafe_inline from the style-src directive and restart the server.

Workaround

There is a workaround that can be leveraged at the moment

config.helper [] do
  def javascript_include_tag(*sources)
    options = sources.extract_options!.stringify_keys
    options['nonce'] = true # content_security_policy_nonce can be used if on older version of Rails

    sources << options

    super
  end

  def stylesheet_link_tag(*sources)
    options = sources.extract_options!.stringify_keys
    options['nonce'] = true # content_security_policy_nonce can be used if on older version of Rails

    sources << options

    super
  end
end

tuxagon avatar May 28 '25 04:05 tuxagon

codeclimate did detect issues, claiming the code to be too similar, but I don't think these methods should be considered such.

tuxagon avatar May 28 '25 14:05 tuxagon

CLA assistant check
All committers have signed the CLA.

CLAassistant avatar May 28 '25 15:05 CLAassistant