skip to content

In a Rails 8.1 app using import maps and Turbo, how do you configure a nonce-based content security policy so your own scripts still run?

level: middleimportance: must knowfreq 45%

answer

  1. initializer ships commented out
  2. nonce generator receives the request
  3. script-src and style-src by default
  4. javascript_tag nonce: true
  5. csp_meta_tag for Turbo's scripts

basics

~10 s

Uncomment config/initializers/content_security_policy.rb, declare directives with the policy DSL and set content_security_policy_nonce_generator; Rails appends 'nonce-…' to the declared script-src and style-src, and tags get it through nonce: true, javascript_importmap_tags or csp_meta_tag.

solid answer

~40 s

A new Rails 8.1 app sends no CSP: the generated `config/initializers/content_security_policy.rb` is entirely commented out. You enable it with `config.content_security_policy do |policy| ... end`, using symbols such as `:self`, `:none`, `:https` and `:strict_dynamic` that map to the quoted keywords. Setting `config.content_security_policy_nonce_generator = ->(request) { ... }` makes the middleware generate one nonce per request and append `'nonce-…'` to the directives in `content_security_policy_nonce_directives`, which default to `script-src` and `style-src`. Your tags must then carry the same value: `javascript_importmap_tags` adds it automatically, `javascript_tag`, `javascript_include_tag` and `stylesheet_link_tag` take `nonce: true`, and `csp_meta_tag` in the layout lets Turbo stamp the nonce on scripts it re-inserts. Rails 8.1 added `content_security_policy_nonce_auto` to put the nonce on those helpers without `nonce: true`.

code

ruby · 15 lines
ruby
# config/initializers/content_security_policy.rb
Rails.application.configure do
  config.content_security_policy do |policy|
    policy.default_src :self
    policy.script_src  :self
    policy.style_src   :self
    policy.img_src     :self, :data
    policy.object_src  :none
    policy.frame_ancestors :none
  end

  config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
  config.content_security_policy_nonce_directives = %w[script-src style-src]
  config.content_security_policy_nonce_auto = true
end

go deeper

for a junior

Remember that the CSP initializer is generated commented out, and that a nonce is a value shared by the header and each trusted script tag.

for a middle

Explain how the generator, nonce_directives and the tag helpers fit together, why javascript_importmap_tags and csp_meta_tag need no extra work, and why a policy without script_src gets no nonce.

for a senior

Show judgement on the generator choice against ETag caching, on inline style attributes under a nonced style-src, and on moving inline handlers into Stimulus before enforcing.

for a principal

Frame a strict policy as a contract the whole front end must keep, and decide who owns exceptions when third-party widgets or engines need sources added.

## Out of the box there is no policy A **Content Security Policy** (CSP) is a response header listing the sources a browser may load scripts, styles, images and frames from. Rails builds it with a Ruby DSL, but a new 8.1 app ships `config/initializers/content_security_policy.rb` with every line commented out, so `config.content_security_policy` stays `nil` and no header is sent. The middleware that writes the header, `ActionDispatch::ContentSecurityPolicy::Middleware`, is in every non-API stack; it simply has nothing to write. An app created with `--api` does not even include the middleware. ## The DSL Each directive is a method on the policy object, named with underscores: `default_src`, `script_src`, `style_src`, `img_src`, `connect_src`, `frame_src`, `frame_ancestors`, `object_src`, `base_uri`, `form_action` and more. Arguments are mapped as follows: - **Symbols** become CSP keywords: `:self` to `'self'`, `:none` to `'none'`, `:unsafe_inline`, `:strict_dynamic`, `:report_sample`, and schemes such as `:https`, `:data`, `:blob`, `:wss`. An unknown symbol raises `ArgumentError`. - **Strings** pass through, except values starting `sha256-`, `sha384-` or `sha512-`, which are quoted as hash sources. - **Lambdas** are evaluated per request in the controller, for sources that depend on the request. - A value with whitespace or a semicolon raises `ActionDispatch::ContentSecurityPolicy::InvalidDirectiveError` when the header is built. ## Generating the nonce A **nonce** is a random value the server puts both in the header and on each trusted `<script>` or `<style>` tag; the browser runs only tags whose nonce matches. Two settings drive it: 1. `config.content_security_policy_nonce_generator` is a lambda that receives the request. The value is computed once per request and stored in the request env, so every helper in that response sees the same nonce. 2. `config.content_security_policy_nonce_directives` lists which directives get `'nonce-…'` appended. Left unset, it is `script-src` and `style-src`. Rails appends the nonce only to directives the policy actually declares. A policy with only `default_src` gets no nonce at all, so declare `script_src` explicitly. The generated initializer suggests `->(request) { request.session.id.to_s }`. The Securing Rails guide explains the trade-off: `SecureRandom.base64(16)` is fresh per request but changes every response's body, so ETags never match and conditional GETs never answer 304; the session id keeps ETags stable but is only as secret as the session cookie. ## Getting the nonce onto your tags | Tag source | How it gets the nonce | |---|---| | `javascript_importmap_tags` | automatically, on the import map, module preloads and the entry `import` | | `javascript_tag`, `javascript_include_tag`, `stylesheet_link_tag` | `nonce: true`, or automatically with `content_security_policy_nonce_auto = true` (new in 8.1) | | A hand-written `<script>` | `nonce="<%= content_security_policy_nonce %>"` | | Scripts Turbo re-creates during navigation | Turbo reads the `csp-nonce` meta tag that `csp_meta_tag` writes | The generated layout already calls `csp_meta_tag` alongside `csrf_meta_tags`; it renders nothing until a policy exists. `content_security_policy_nonce_auto` reads `content_security_policy_nonce_directives` at boot, so set that list explicitly when you turn it on, as the generated initializer does. ## Checking the header An integration test can pin the policy down so a later change does not quietly loosen it: ```ruby get root_path csp = response.headers["Content-Security-Policy"] assert_match "script-src 'self' 'nonce-", csp assert_includes csp, "object-src 'none'" ``` In the browser, the console names the directive and the blocked source for every violation, which is usually enough to tell a missing `nonce: true` from a third-party script that needs its own source. Lambdas in the policy are evaluated per request in the controller, so a source such as a tenant's receipt host can vary without loosening the policy for everyone. ## Traps - When `style-src` carries a nonce, browsers ignore `'unsafe-inline'` in that directive, so inline `style="..."` attributes stop working. Either drop `style-src` from the nonce directives or add a `style_src_attr` directive. - The middleware leaves 304 responses alone, because a new nonce in the header would not match the cached HTML. - A header already set by the action is never overwritten. - Inline event handlers such as `onclick=` cannot carry a nonce; move them into Stimulus controllers. In a budgeting app, a policy of `script_src :self` plus a nonce lets the import map and Turbo run while an injected `<script>` in a transaction memo field is refused.

  • Your policy declares only default_src :self and a nonce generator, yet inline scripts with nonce: true are blocked. Why?
    Rails appends `'nonce-…'` only to directives that the policy declares and that appear in `content_security_policy_nonce_directives`. With no `script_src`, the header has just `default-src 'self'`, which carries no nonce, so the browser refuses every inline script. Declare `policy.script_src :self` (and `style_src` if needed) and the nonce is added.
  • Should the nonce generator use SecureRandom or the session id?
    `SecureRandom.base64(16)` gives a fresh value per request, the stronger choice, but every response body then differs, so ETags never match and conditional GETs cannot return 304. `request.session.id.to_s`, the generated suggestion, keeps responses cacheable but is only as secret as the session cookie. Pick per app, and remember fragment caches must not store a nonce either way.
  • What does content_security_policy_nonce_auto change in Rails 8.1?
    With it set to `true`, and a generator plus matching nonce directives configured, `javascript_tag`, `javascript_include_tag` and `stylesheet_link_tag` add the nonce without `nonce: true`. That matters for views you do not write, such as an engine's. Passing `nonce: false` still opts a single tag out.

  • A new Rails app already sends a strict CSP header by default
  • The nonce is added to every directive in the policy
  • Rails stores each nonce in the session so later requests can check it
  • csrf_meta_tags is what gives Turbo the CSP nonce
  • Add :unsafe_inline next to the nonce to keep style attributes working

Assumes Rails 8.1: content_security_policy_nonce_auto is new in 8.1.0; earlier releases need nonce: true on each tag helper.