skip to content

In a Rails controller, how do the content_security_policy and content_security_policy_report_only macros change the global policy for particular actions?

level: middleimportance: should knowfreq 30%

answer

  1. both are before_action filters
  2. the block edits a clone
  3. a directive call replaces its sources
  4. false removes the header
  5. report-only swaps the header name

basics

~10 s

Both macros add a before_action: content_security_policy edits a copy of the global policy for the chosen actions or, given false, removes it, while content_security_policy_report_only makes those responses send Content-Security-Policy-Report-Only instead of the enforcing header.

solid answer

~40 s

`content_security_policy` in a controller registers a `before_action`, so it takes `only:`, `except:` and `if:`. With a block, Rails clones the global policy (or starts an empty one if none exists), runs the block in the controller instance, and stores the result on the request; calling a directive replaces that directive's sources rather than appending to them. `content_security_policy false, only: :embed` sets the request's policy to `nil`, so no header is sent for that action. `content_security_policy_report_only` flips a per-request flag, and the middleware then writes the same policy under `Content-Security-Policy-Report-Only`; the app-wide equivalent is `config.content_security_policy_report_only = true`. The DSL emits one header per response, so enforcing and report-only are not sent together, and an action that sets either header itself keeps it.

code

ruby · 12 lines
ruby
class StatementsController < ApplicationController
  # The charts page only reports violations of the global policy instead of enforcing it
  content_security_policy_report_only only: :charts

  # The legacy PDF preview cannot run under any policy
  content_security_policy false, only: :preview

  # Request-dependent source, evaluated in the controller
  content_security_policy only: :show do |policy|
    policy.img_src :self, :data, -> { current_household.receipt_host }
  end
end

go deeper

for a junior

Know that a controller can change the policy for some actions with content_security_policy and only:, and that false removes the header.

for a middle

Explain the before_action mechanics: a cloned policy, a directive call replacing its sources, the block running in the controller, and report-only changing only the header name.

for a senior

Keep exceptions narrow and reviewable, use report-only per controller to trial changes, and know the middleware's limits: one header, no overwrite, no header on 304.

for a principal

Decide how policy exceptions are approved and tracked so per-action loosening does not quietly erode the global policy over years.

## Where the policy lives during a request The global policy object from `config.content_security_policy` is placed in each request's env when the request enters the app; every request starts out pointing at that same object. Nothing writes the header until the response travels back out through `ActionDispatch::ContentSecurityPolicy::Middleware`, which reads whatever policy object the request holds at that moment and builds the header from it. The controller macros work by changing that request-level value before the action runs. Both macros come from `ActionController::ContentSecurityPolicy`, which `ActionController::Base` includes. `ActionController::API` does not include it. ## content_security_policy with a block ```ruby class BankLinksController < ApplicationController content_security_policy only: :new do |policy| policy.frame_src :self, "https://connect.bank.example" end end ``` What happens on a `new` request: 1. The macro has registered a `before_action` with `only: :new`, so other actions are untouched. 2. Rails takes `request.content_security_policy&.clone`, or a fresh empty policy when no global one is configured. 3. The block runs with `instance_exec`, so `self` is the controller and you can read `current_user`, params or instance variables. 4. `policy.frame_src` **replaces** the `frame-src` sources with the two given. It does not merge them with the global ones; to extend, repeat the global sources in the call. 5. The modified copy is stored back on the request; the global object is never mutated. Calling a directive with no arguments, such as `policy.frame_src`, deletes that directive from the copy. ## content_security_policy false `content_security_policy false, only: :export` sets the request's policy to `nil` for that action, so the middleware writes no header at all. It is the blunt tool for a response that genuinely cannot live under the policy, such as a legacy embedded report, and it removes protection for that response entirely. ## Report-only, globally and per action | Setting | Effect | |---|---| | `config.content_security_policy_report_only = true` | every response sends the policy as `Content-Security-Policy-Report-Only` | | `content_security_policy_report_only only: :index` | only `index` responses switch to the report-only header | | `content_security_policy_report_only false, only: :index` | `index` goes back to enforcing while the app default is report-only | The flag only changes the header **name**; the directives, nonce and all are identical. Violations go to whatever `policy.report_uri` names, and the app needs an endpoint there. ## What the middleware will not do - **Send both headers.** It writes exactly one, choosing its name from the report-only flag. Testing a stricter policy while enforcing the current one needs the second header set by hand in the action. - **Overwrite a header the action set.** If the response already has either CSP header, the middleware leaves it alone. - **Touch a 304.** Not Modified responses get no header, so a nonce in the header cannot disagree with cached HTML. ## Nonces survive overrides An override does not lose the nonce. The middleware generates the nonce from the request and appends it when it builds the header, after the action has run, so an overridden `script_src` still receives `'nonce-…'` as long as `script-src` is in the nonce directives. The flip side is that an override which drops `script_src` altogether also drops the nonce for that action, and any inline script there stops running. ## Testing an override An integration test per overridden action keeps exceptions from spreading: - request the overridden action and assert its `frame-src` value; - request a neighbouring action and assert it still carries the global value; - for report-only actions, assert that `Content-Security-Policy-Report-Only` is present and `Content-Security-Policy` is absent. ## Choosing between the tools - Loosen one directive for one action with a block, and keep the change as narrow as possible. - Use `false` only when there is no workable policy, and record why. - Use report-only to see what a policy would block before enforcing it, globally or one controller at a time. - Prefer request-dependent sources (a lambda) to a broad wildcard when the allowed host varies by tenant. In a budgeting app, a bank-linking page might need one provider's frame while statements, settings and dashboards keep `frame_src :none`.

  • Can the DSL send an enforcing policy and a report-only policy on the same response?
    No. The middleware writes a single header and picks `Content-Security-Policy` or `Content-Security-Policy-Report-Only` from the request's report-only flag. To trial a stricter policy while enforcing the current one, set the second header yourself in the action or an `after_action`; the middleware never overwrites a CSP header that is already present.
  • Why does a policy block in a controller not leak into other controllers?
    The macro works on `request.content_security_policy&.clone`, a copy made for that request, and stores the copy back on the request. The global object from `config.content_security_policy` is never mutated, so the next request starts again from the global policy.

  • A directive call in the block appends to the global sources
  • content_security_policy false disables only the nonce
  • Report-only mode sends both the enforcing and the report-only header
  • The controller block edits the global policy for later requests
  • API controllers inherit the same macros from ActionController::API