Skip to content

Support Rails Content-Security-Policy nonces#542

Open
tuxagon wants to merge 4 commits intoTrestleAdmin:mainfrom
tuxagon:support-csp
Open

Support Rails Content-Security-Policy nonces#542
tuxagon wants to merge 4 commits intoTrestleAdmin:mainfrom
tuxagon:support-csp

Conversation

@tuxagon
Copy link

@tuxagon tuxagon commented May 28, 2025

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 added 2 commits May 28, 2025 00:31
Despite `stylesheet_link_tag` having a helper, the effort to update
sandbox to conform to nonced styles would be major and largely more
of a distraction for demonstrating how it works.
@tuxagon
Copy link
Author

tuxagon commented May 28, 2025

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

@CLAassistant
Copy link

CLAassistant commented May 28, 2025

CLA assistant check
All committers have signed the CLA.

Initially I considered not having an option, but since a nonce generator
doesn't care about what's using it from a caller's perspective, it would
apply nonces everywhere, even if you didn't want them.

These options makes their application a little more explicit and avoids
the helper from needing to dig into the Rails config to see if
`script-src` or `style-src` are declared to use a nonce.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow to pass nonce attribute to stylesheet_link_tag and javascript_include_tag helpers used in Trestle views

2 participants