skip to content

Hardening & Secrets

Rails ships its own defences: forgery tokens, encrypted credentials, column encryption, CSP and host checks, and rate_limit. Interviewers ask which are on by default and which you must enable.

part ofRuby on Railsread it →
on this pageshow

explore

questions

page 1 of 2

In a Rails 8.1 app, how do you add a mapping-service API key to the encrypted credentials, and how does application code read it?

level: juniorimportance: must knowfreq 74%

answer

  1. an encrypted YAML file in config/
  2. bin/rails credentials:edit opens $EDITOR
  3. master.key decrypts, and it is git-ignored
  4. credentials.dig(:maps, :api_key)
  5. bang accessor raises KeyError when blank

basics

~10 s

Run bin/rails credentials:edit, which decrypts config/credentials.yml.enc with config/master.key into your editor and re-encrypts it on save. Code reads Rails.application.credentials.dig(:maps, :api_key), or the bang accessor to fail on a blank value.

solid answer

~30 s

`bin/rails credentials:edit` opens a temporary decrypted copy of `config/credentials.yml.enc` in `$VISUAL` or `$EDITOR`; when you save and close, Rails encrypts the YAML again with the key from `RAILS_MASTER_KEY` or `config/master.key` and deletes the temporary file. You add something like `maps: { api_key: ... }`. The encrypted file is committed; `master.key` is generated by `rails new` and git-ignored, and the team shares it through a password manager. At runtime `Rails.application.credentials` returns an `ActiveSupport::EncryptedConfiguration` with symbolized keys: `credentials.dig(:maps, :api_key)` and `credentials.maps.api_key` return nil when missing, `credentials.maps.api_key!` raises `KeyError` when the value is blank, and `credentials.fetch(:maps)` raises `KeyError` when the key is absent.

code

yaml · 6 lines
yaml
# Decrypted view inside bin/rails credentials:edit
maps:
  api_key: mk_live_9f2c...
  account_id: courier-routing

secret_key_base: 3b7c...

go deeper

for a junior

Recall the two files, which one is committed, and that bin/rails credentials:edit is the only way to change them.

for a middle

Explain the edit cycle, the key lookup order, and the difference between dig, the dynamic accessor, fetch and the bang accessor.

for a senior

Show judgement about failing fast on required secrets, avoiding leaks through credentials:show, and handling merge conflicts in ciphertext.

for a principal

Discuss when an encrypted file in the repository stops scaling and a central secret store becomes worth its operational cost.

## What Rails credentials are **Credentials** are Rails' built-in place for secrets such as API keys, SMTP passwords and `secret_key_base`. They live in one YAML document that is stored **encrypted** in the repository, so the secret travels with the code but cannot be read without a key. A new Rails 8.1 app gets two files from `rails new`: - `config/credentials.yml.enc`, the encrypted YAML (AES-128-GCM), committed to git; - `config/master.key`, 32 hexadecimal characters that decrypt it, written with file mode 0600 and added to `.gitignore` (in 8.1 the ignore entry covers every `*.key` file in that directory). `rails new` prints a reminder to store the key in a password manager the team can reach, because without it nobody can decrypt the file again. ## Editing: `bin/rails credentials:edit` For a food-delivery app that needs a key for its mapping service: 1. Run `EDITOR="code --wait" bin/rails credentials:edit` (any editor that blocks until the file is closed works). 2. Rails reads the key, preferring `ENV["RAILS_MASTER_KEY"]` over `config/master.key`, decrypts the file into a temporary path and opens it. 3. You add the value and save. Rails encrypts the content, writes `credentials.yml.enc`, removes the temporary file and then checks that the YAML parses. 4. You commit the changed `.yml.enc`; the diff is ciphertext unless the project is enrolled in decrypted diffs. If the YAML is invalid, Rails warns that the app will not be able to load the file until it is fixed. If the key is wrong, it says it could not decrypt the file and changes nothing. ## Reading values in code `Rails.application.credentials` is an `ActiveSupport::EncryptedConfiguration`. It decrypts once, symbolizes keys and offers several ways in: | Call | Missing key | Blank value | |---|---|---| | `credentials.dig(:maps, :api_key)` | `nil` | the blank value | | `credentials.maps.api_key` | `nil` (or `NoMethodError` if `maps` itself is missing) | the blank value | | `credentials.maps.api_key!` | `KeyError` | `KeyError` (`":api_key is blank"`) | | `credentials.fetch(:maps)` | `KeyError` | the value | | `credentials[:maps]` | `nil` | the value | The bang accessor comes from `ActiveSupport::OrderedOptions`, which Rails builds for each nested hash. It is the idiomatic way to fail loudly when a required secret is missing, for example in an initializer: ```ruby MapsClient.api_key = Rails.application.credentials.maps.api_key! ``` `dig` is the safe choice for optional values, because a missing intermediate key returns nil instead of raising `NoMethodError` on nil. ## What is safe to commit and what is not - **Commit** `config/credentials.yml.enc`: without the key it is unreadable ciphertext. - **Never commit** `config/master.key`; anyone holding it plus the repository can read every secret. - **Do not paste** decrypted output from `bin/rails credentials:show` into tickets or logs; it prints the whole file. ## Where it stops Credentials are read when the app runs, from the key available on that machine. A server therefore needs the key, usually as `RAILS_MASTER_KEY` in its environment. Per-environment files and how the key reaches a server are the natural next questions. ## What interviewers check - That you edit with `bin/rails credentials:edit`, never by hand. - That you know which file is committed and which is secret. - That you can read a nested value and choose between `dig` and the bang form.

  • Why might `Rails.application.credentials.maps.api_key` raise NoMethodError while `dig(:maps, :api_key)` returns nil?
    If the `maps` section is missing, `credentials.maps` returns nil, and calling `api_key` on nil raises `NoMethodError`. `dig` walks the hash and returns nil at the first missing level. Use `dig` for optional values and the bang accessor, `maps.api_key!`, when the section is known to exist and the value is required.
  • A colleague edits credentials.yml.enc on another branch at the same time; how do you resolve the merge conflict?
    Ciphertext cannot be merged line by line. Take one side's file, run `bin/rails credentials:edit`, and re-add the other branch's values by hand, reading them from that branch with the key. Keeping each change small and merging quickly avoids most conflicts.

  • Commit config/master.key so new developers can boot the app.
  • Edit config/credentials.yml.enc directly in the editor and commit it.
  • credentials.dig raises KeyError when the key is missing.
  • Credentials are decrypted at build time and baked into the app as plain YAML.
  • When RAILS_MASTER_KEY is set, Rails still prefers config/master.key.
open as a page

In a Rails 8.1 app whose ApplicationController never calls protect_from_forgery, what stops a forged POST, and where does the token come from?

level: juniorimportance: must knowfreq 72%

basics

~10 s

Rails' Action Controller railtie runs protect_from_forgery with: :exception on ActionController::Base because load_defaults sets default_protect_from_forgery. form_with and button_to embed a hidden authenticity_token, csrf_meta_tags exposes one for scripts, and a bad token raises InvalidAuthenticityToken.

open as a page

How do you set up Active Record Encryption in a Rails 8.1 app to encrypt a patient's national ID column, and what does the database store?

level: juniorimportance: must knowfreq 52%

basics

~10 s

Run bin/rails db:encryption:init, paste its primary_key, deterministic_key and key_derivation_salt under active_record_encryption in credentials, then declare encrypts :national_id. Rails stores a Base64 JSON envelope of ciphertext, IV and auth tag, and decrypts on read.

open as a page

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%

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.

open as a page

In an Active Record query, why is Car.where("make = '#{params[:make]}'") unsafe, and which forms of where pass values safely?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Ruby interpolates params[:make] into the string before Active Record sees it, and where treats a lone string as raw SQL, so a quote in the input rewrites the query; hash conditions, ? placeholders and :named binds quote the value instead.

open as a page

In a Rails 8.1 controller, what does rate_limit to: 10, within: 3.minutes, only: :create do, and what does a client get when it trips?

level: juniorimportance: must knowfreq 45%

basics

~20 s

rate_limit adds a before_action that increments a per-IP counter in the cache store on each create request; the eleventh request within three minutes raises ActionController::TooManyRequests, which Action Dispatch turns into a 429 Too Many Requests response.

open as a page

In Rails 8.1, how do per-environment credentials files work, and which key must a production server have to decrypt them?

level: middleimportance: must knowfreq 58%

basics

~10 s

bin/rails credentials:edit -e production writes config/credentials/production.yml.enc with its own production.key. When that file exists, production reads it instead of credentials.yml.enc, without merging, so the server's RAILS_MASTER_KEY must hold production.key's value.

open as a page

In a Rails controller, what do protect_from_forgery with: :exception, :reset_session and :null_session each do to an unverified POST?

level: middleimportance: must knowfreq 58%

basics

~20 s

:exception raises ActionController::InvalidAuthenticityToken, so the action never runs. :reset_session clears the session and lets the action run. :null_session runs the action with an empty session, no flash and a cookie jar that reads nothing and writes nothing.

open as a page

In an Active Record model, when do you need encrypts :national_id, deterministic: true, and what does it cost compared with the default?

level: middleimportance: must knowfreq 50%

basics

~20 s

Use deterministic: true only when you must query or enforce uniqueness on the column, such as finding patients by national ID. It derives the IV from the plaintext, so equal values give equal ciphertexts, revealing which rows share a value.

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, why does Listing.update(params[:listing].permit!) create a mass-assignment hole, and how does Brakeman report it?

level: middleimportance: must knowfreq 55%

basics

~20 s

permit! marks every key, nested ones included, as allowed, so a request can set any column such as dealer_id or featured; Brakeman reports it as a Mass Assignment warning, High confidence when the params then reach a mass-assignment call.

open as a page

A Rails 8.1 app deployed without RAILS_MASTER_KEY reads every credential as nil instead of failing; why, and what does config.require_master_key change?

level: middleimportance: should knowfreq 40%

basics

~10 s

With no key, Rails treats the credentials as an empty file, so every lookup returns nil until something like secret_key_base raises. config.require_master_key = true makes the first credentials read raise ActiveSupport::EncryptedFile::MissingKeyError instead.

open as a page

A payment provider's webhook POSTs to a Rails 8.1 donation app fail with InvalidAuthenticityToken; how should that controller opt out of forgery protection?

level: middleimportance: should knowfreq 48%

basics

~10 s

Add skip_forgery_protection to the webhook controller, scoped with only:, and authenticate each call by verifying the provider's signature over request.raw_post in a before_action. Leave Base's protection on everywhere else.

open as a page

What does Active Record Encryption protect a Rails hospital app's national ID column against, and what does it leave exposed?

level: middleimportance: should knowfreq 34%

basics

~20 s

It keeps the column unreadable to anyone who sees only the database, such as dumps, backups or read-only SQL, and filters it from logs and inspect. Code running with the app's keys, and copies outside the column, still see plain text.

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

In a Rails view, which code patterns bypass ERB's automatic escaping and let a car listing's user-written text run as script?

level: middleimportance: should knowfreq 50%

basics

~10 s

Escaping is bypassed by <%== %>, raw, .html_safe on strings that contain user data, render inline: or html: with user input, and link_to with a user-supplied URL, whose javascript: scheme survives escaping.

open as a page

In Rails 8.1, what happens when a controller calls redirect_to params[:return_to], and how do allow_other_host: and action_on_open_redirect change it?

level: middleimportance: should knowfreq 45%

basics

~10 s

redirect_to allows a path or a URL on request.host; another host raises ActionController::Redirecting::OpenRedirectError when action_on_open_redirect is :raise, the load_defaults 7.0+ value, while allow_other_host: true allows it and false always refuses it.

open as a page

In Rails 8.1, what does Active Record do when params[:sort] reaches order or pluck, and how do you sort by a user-chosen column safely?

level: middleimportance: should knowfreq 40%

basics

~10 s

order, reorder, pluck and in_order_of reject strings that do not look like column names, raising ActiveRecord::UnknownAttributeReference, but any column-shaped string passes, so map params[:sort] through an allowlist to symbols.

open as a page

In Rails 8.1's rate_limit macro, how do the by:, name: and scope: options change which requests share a counter?

level: middleimportance: should knowfreq 30%

basics

~20 s

Each option fills one part of the cache key rate-limit:<scope>:<name>:<by>: by: chooses the identity counted, name: lets one controller keep several limits apart, and scope:, new in 8.1, replaces controller_path so different controllers can share one counter.

open as a page

Why does a rate_limit never trip in a generated Rails 8.1 test suite, and how do you test the limit anyway?

level: middleimportance: should knowfreq 30%

basics

~20 s

The generated test environment sets config.cache_store = :null_store, whose increment returns nil, so the count never exceeds to:; test it by giving the limit a real store, such as a memory store in test, and clearing it between tests.

open as a page

In a Rails 8.1 app, where does secret_key_base come from, what is derived from it, and what breaks if you replace it after a leak?

level: seniorimportance: should knowfreq 38%

basics

~20 s

secret_key_base comes from ENV['SECRET_KEY_BASE'], then credentials, then in development and test tmp/local_secret.txt. It seeds the key generator behind signed and encrypted cookies, cookie sessions and message verifiers, so replacing it invalidates them all unless old values are rotated in.

open as a page

Behind a TLS-terminating proxy, every Rails 8.1 form POST fails with "HTTP Origin header didn't match request.base_url" - which check fires, and how do you fix it?

level: seniorimportance: should knowfreq 32%

basics

~20 s

forgery_protection_origin_check, on since load_defaults 5.0, compares the browser's Origin with request.base_url. Behind a proxy that ends TLS and sends no X-Forwarded-Proto, base_url starts with http://, so the comparison fails. Forward the scheme or set config.assume_ssl.

open as a page

After a suspected key leak, how do you rotate Active Record Encryption keys in Rails 8.1, and why is a deterministic national-ID column harder?

level: seniorimportance: should knowfreq 26%

basics

~20 s

List the new primary_key after the old one: Rails encrypts with the last key and tries all keys to decrypt. Re-encrypt rows with record.encrypt, then drop the old key. deterministic_key takes one value, so it needs a previous: scheme.

open as a page

A Rails 8.1 hospital app already stores national IDs in plain text; how do you switch the column to encrypts without breaking reads or lookups?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Declare encrypts with support_unencrypted_data: true so plain rows still read, enable extend_queries so deterministic lookups match both forms, re-encrypt existing rows with record.encrypt in batches, then remove both settings.

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 a Rails 8.1 app, how do you run Brakeman, read its confidence levels, and record a reviewed false positive in config/brakeman.ignore?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Run bin/brakeman, which Rails 8.1 generates with --ensure-latest prepended; each warning has a type and a High, Medium or Weak confidence; fix real findings, and record reviewed false positives with bin/brakeman -I, which writes fingerprints and notes to config/brakeman.ignore.

open as a page

A Rails 8.1 ride-hailing app runs on several servers with Puma workers behind a load balancer; what must its rate_limit store and client identity be for the limit to hold?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The counter needs a store every process shares, such as the generated Solid Cache store, and by: must name the real client: request.remote_ip does so only when every proxy hop is trusted, so key signed-in endpoints on the account.

open as a page

In Rails 8.1, what do bin/rails credentials:diff and credentials:fetch do, and how do they help a team review and ship a new credential?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

credentials:diff --enroll makes git diff show decrypted YAML to anyone holding the key; rails new enrolls by default. credentials:fetch, new in 8.1, prints one value by dotted path and exits 1 when it is missing.

open as a page

With Rails' per_form_csrf_tokens on, why is a token rendered for one form rejected at another action, while the csrf_meta_tags token works anywhere?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

With per_form_csrf_tokens on, form_with signs each form's token with the session secret over its action path and method, so it verifies only there. csrf_meta_tags passes no form options and gets the global token, valid for any action.

open as a page

showing 1–30 of 32