skip to content

CSP, SSL & Host Rules

Rails sets response headers through the content_security_policy and permissions_policy DSLs, forces HTTPS with force_ssl, and blocks unknown hosts. Interviewers probe nonces, proxies and hosts.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In a Rails 8.1 app, what does config.force_ssl = true do to each request, and how does config.ssl_options adjust it?

level: juniorimportance: must knowfreq 55%

answer

  1. one middleware, three jobs
  2. ActionDispatch::SSL in the stack
  3. 301 for GET, 308 for the rest
  4. Secure flag added to cookies
  5. HSTS max-age of two years

basics

~10 s

config.force_ssl inserts the ActionDispatch::SSL middleware, which redirects plain-HTTP requests to HTTPS, adds the Secure flag to cookies and sends Strict-Transport-Security; config.ssl_options tunes or switches off each of those three jobs.

solid answer

~40 s

`config.force_ssl = true` adds `ActionDispatch::SSL` near the top of the middleware stack and passes it `config.ssl_options`. It does three things. A request that is not `request.ssl?` is redirected to the same URL on `https://`: 301 for GET and HEAD, and for other methods `config.action_dispatch.ssl_default_redirect_status`, which `load_defaults` 7.0 and later set to 308. On HTTPS responses it appends `secure` to every `Set-Cookie` (excluded requests aside), and it sends `Strict-Transport-Security: max-age=63072000; includeSubDomains` (two years, no `preload`). `ssl_options` adjusts each job: `redirect: { exclude: ->(request) { ... } }` or `redirect: false`, `secure_cookies: false`, and `hsts: { expires:, subdomains:, preload: }` or `hsts: false`, which sends `max-age=0`. The flag also makes URL helpers default to `https://` when no protocol is known. Since Rails 8.1.1 a Kamal-generated `production.rb` leaves the line commented out.

code

ruby · 10 lines
ruby
# config/environments/production.rb
Rails.application.configure do
  config.assume_ssl = true
  config.force_ssl  = true

  config.ssl_options = {
    redirect: { exclude: ->(request) { request.path == "/up" } },
    hsts: { expires: 1.year, subdomains: true }
  }
end

go deeper

for a junior

Name the three jobs of config.force_ssl: redirect HTTP to HTTPS, mark cookies Secure, send HSTS. Know it is an application setting in production.rb, not a controller macro.

for a middle

Explain the redirect statuses (301 for GET and HEAD, 308 otherwise under modern defaults), the two-year includeSubDomains HSTS default, and each ssl_options key, including that hsts: false sends max-age=0.

for a senior

Show you can switch HTTPS on for a live app safely: exclude the plain-HTTP health check, start with a short HSTS expiry, confirm the proxy forwards the scheme, and know why a Kamal-generated 8.1.1 app ships with it commented out.

for a principal

Weigh where HTTPS enforcement should live, at the proxy or in the app, and how long an HSTS commitment the organisation can honour across every subdomain it controls.

## What the flag installs `config.force_ssl` is a single boolean in `config/environments/production.rb`, but it does not act on its own. When it is `true`, Rails' default middleware stack inserts **`ActionDispatch::SSL`**, just after the optional host-authorization and assume-SSL middleware and before anything that serves files or reaches a controller. The middleware receives the hash in **`config.ssl_options`** as keyword arguments. Its class comment describes it as doing three jobs, and every interview answer should name all three. The flag also sets `ActionDispatch::Http::URL.secure_protocol`, so URL generation that has no request protocol to copy (a mailer or a job building a `_url`) defaults to `https://`. Inside a controller the helpers copy `request.protocol` instead. ## Job 1: redirect plain HTTP to HTTPS For each request the middleware asks `request.ssl?`, which is true when Rack sees `HTTPS=on`, `X-Forwarded-Ssl: on`, or a forwarded scheme of `https`. If the request is not secure and not excluded, it never reaches the app: the middleware answers with a redirect to `https://` plus the same host, path and query string. | Request method | Status | Why | |---|---|---| | GET, HEAD | 301 | a permanent redirect is safe for reads | | any other, `load_defaults` 7.0 or later | 308 | `action_dispatch.ssl_default_redirect_status = 308` keeps method and body | | any other, without that default | 307 | the middleware's fallback, also method-preserving | `ssl_options` shapes the redirect: - `redirect: { host: "secure.budget.example", port: 8443 }` changes the destination. - `redirect: { status: 302 }` forces one status for all methods. - `redirect: { exclude: ->(request) { request.path == "/up" } }` lets matching requests through on plain HTTP; the generated `production.rb` carries this line commented out for the health check. - `redirect: false` turns redirection off entirely, and also stops the middleware flagging cookies, because every request then counts as excluded. ## Job 2: secure cookies On an HTTPS response the middleware walks every `Set-Cookie` header and appends `; secure` unless it is already there, so browsers never send those cookies over plain HTTP. Excluded requests are skipped. Separately, when `force_ssl` is on and `secure_cookies` has not been set to `false`, Rails marks the session cookie itself `secure: true` while building the stack. `ssl_options = { secure_cookies: false }` disables both. ## Job 3: the Strict-Transport-Security header On HTTPS responses the middleware sets `Strict-Transport-Security` unless the app already set one. Rails' defaults are: 1. `expires`: 63072000 seconds (two years); 2. `subdomains`: `true`, so the header carries `includeSubDomains`; 3. `preload`: `false`. Override any of them with `hsts: { expires: 1.year, subdomains: false }`; the hash is merged into the defaults. `hsts: false` does **not** omit the header: it is a shortcut for `expires: 0`, so browsers are told to forget an earlier policy. What a browser does with the header is protocol territory; the Rails question is which values Rails sends. ## Checking that it works Three quick checks confirm the middleware is doing its jobs in a deployed budgeting app: 1. Request the `http://` URL with a HEAD request and expect a 301 whose `Location` is the `https://` URL. 2. Request the `https://` URL and expect `Strict-Transport-Security: max-age=63072000; includeSubDomains`, or whatever your `hsts:` hash produces. 3. Inspect the session cookie and expect the `secure` attribute. In an integration test the session is plain HTTP by default; calling `https!` switches it to HTTPS, which is how you test behaviour that only appears on secure requests. `bin/rails middleware` lists `ActionDispatch::SSL` when the flag is on in that environment, which is the fastest way to prove which environment file actually set it. ## What a new 8.1 app ships A generated `production.rb` has `config.assume_ssl = true` and `config.force_ssl = true` active only when the app was created with `--skip-kamal`. Since **8.1.1**, an app generated with Kamal leaves both commented out so the first deploy works before a certificate exists; the changelog still recommends turning them on as soon as you can. Development and test never set the flag. ## Mistakes interviewers listen for - Calling `force_ssl` as a controller class macro: that form was deprecated in 6.0 and removed in 6.1; the application setting is the only one. - Believing `hsts: false` stops the header; it sends `max-age=0`. - Expecting the redirect to protect POST bodies: the first plain-HTTP request has already crossed the network before any redirect. - Forgetting that behind a TLS-terminating proxy that sends no forwarded scheme, every request looks like HTTP and the redirect loops.

  • Why does a plain-HTTP POST get a 308 rather than a 301 under force_ssl?
    `ActionDispatch::SSL` uses 301 only for GET and HEAD. Other methods get `config.action_dispatch.ssl_default_redirect_status`, which `load_defaults` 7.0 and later set to 308, or 307 without it. Both 307 and 308 tell the client to repeat the same method and body, whereas browsers commonly turn a POST into a GET after a 301.
  • You set ssl_options = { hsts: false } to stop sending HSTS. What do browsers receive?
    Still a `Strict-Transport-Security` header, now `max-age=0; includeSubDomains`. Rails treats `false` as `expires: 0`, because omitting the header would leave browsers holding the old policy until it expired. To send no header at all you would have to remove it yourself, which is rarely what you want.
  • Which cookies does force_ssl mark Secure, and when does it skip them?
    On HTTPS responses `ActionDispatch::SSL` appends `secure` to every `Set-Cookie` header that lacks it, and Rails also sets `secure: true` on the session cookie options. The middleware skips requests matched by `redirect: { exclude: ... }`, and all requests under `redirect: false`; `secure_cookies: false` turns off both the flagging and the session-cookie setting.

  • force_ssl only redirects; cookies and HSTS need separate settings
  • Put force_ssl in ApplicationController to protect every action
  • ssl_options hsts: false removes the Strict-Transport-Security header
  • Non-GET requests are redirected with 301 like everything else
  • A new Kamal-generated 8.1 app already forces SSL in production

Assumes Rails 8.1 with load_defaults 8.1: non-GET redirects use 308 (a 7.0 default), and since 8.1.1 a Kamal-generated production.rb leaves force_ssl and assume_ssl commented out.

open as a page

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%

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.

open as a page

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%

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.

open as a page

Behind a TLS-terminating proxy, a Rails 8.1 budgeting app with force_ssl enabled loops on redirects; why, and what does config.assume_ssl change?

level: seniorimportance: should knowfreq 40%

basics

~10 s

The proxy forwards decrypted traffic over HTTP without a forwarded scheme, so request.ssl? is false and ActionDispatch::SSL redirects back to HTTPS forever; config.assume_ssl makes every request look like HTTPS, so the loop stops.

open as a page

In a Rails 8.1 app, what does config.hosts protect against, and how do you configure it in production without blocking health checks?

level: seniorimportance: should knowfreq 35%

basics

~10 s

config.hosts makes ActionDispatch::HostAuthorization answer 403 to any request whose Host or X-Forwarded-Host is not listed, defeating DNS rebinding and forged Host headers; in production list your domains and exclude the health-check path with config.host_authorization.

open as a page

In Rails 8.1, which header does config.permissions_policy actually emit, and how does a controller override it for one action?

level: middleimportance: nice to knowfreq 15%

basics

~10 s

Despite its name, Rails 8.1's permissions_policy DSL writes the legacy Feature-Policy header; a controller's permissions_policy only: block edits a clone of the global policy, which must exist because the override cannot start from nothing.

open as a page