Skip to main content

Rails security checks: strong parameters, raw SQL, html_safe and send_file

Rails is safe by default in a way few frameworks match. Queries built with hash conditions are parameterised, views escape output, forms carry CSRF tokens, and strong parameters refuse attributes you did not list. Most Rails vulnerabilities are therefore not missing protections. They are places where someone switched a protection off, usually with one method call that reads like a convenience.

This post covers the six calls that do it most often, what each one gives an attacker, and the replacement. Every example is a controller method, because that is where a request value meets the call.

1. permit! and strong parameters that are too wide

Strong parameters exist so a request cannot set attributes the form never offered. permit! turns that off. The Rails API docs describe it as setting the permitted attribute to true, so the whole hash passes mass assignment, nested hashes included.

# Wrong: the request can set admin, role, account_id, anything with a column
def update
  current_user.update(params.require(:user).permit!)
end
# Right: name the fields this form edits
def update
  current_user.update(params.require(:user).permit(:name, :email, :time_zone))
end

A narrower version of the same bug is a permit list that includes a privileged field because one admin form needed it: permit(:name, :email, :role) in a controller that regular users can reach. Keep admin fields in admin controllers. To catch drift early, set config.action_controller.action_on_unpermitted_parameters = :raise in development and test, so a request carrying an unlisted key fails loudly instead of being dropped silently.

2. Interpolated SQL

Active Record parameterises hash conditions and ? placeholders. It cannot parameterise a string you have already built. The Rails security guide uses this exact example:

# Wrong
Project.where("name = '#{params[:name]}'")

# Right
Project.where(name: params[:name])
Project.where("name = ? AND created_at > ?", params[:name], 1.week.ago)

The same applies to find_by_sql, count_by_sql, connection.execute, select, group, having, joins with a string, and pluck with a string. find_by_sql takes an array for binding:

User.find_by_sql(["SELECT * FROM users WHERE email = ?", params[:email]])

Sorting deserves a note. Recent Rails versions refuse order arguments that do not look like a column reference, unless the string is wrapped in Arel.sql, so the dangerous form is now order(Arel.sql(params[:sort])). Map sort keys to columns instead:

SORTS = { "newest" => { created_at: :desc }, "name" => { name: :asc } }.freeze

def index
  @projects = Project.order(SORTS.fetch(params[:sort], SORTS["newest"]))
end

3. html_safe, raw and render html:

Rails escapes everything a view outputs unless the string is marked safe. html_safe, raw and render html: all mark it safe, and none of them escape anything; they are an assertion that the string is already safe.

# Wrong: the bio is user input, now rendered as HTML
def show
  @bio = "<p>#{@user.bio}</p>".html_safe
end
<%# Right: let the helper escape the content %>
<%= content_tag(:p, @user.bio) %>

<%# Or, if users may use a small set of tags %>
<%= sanitize(@user.bio, tags: %w[p br strong em a], attributes: %w[href]) %>

The rule for review: html_safe belongs on strings your code built entirely from constants and already-escaped parts. If any part came from a request or a user-editable column, it is an XSS waiting for the right input.

4. send_file with a request value

send_file reads whatever path it is given. The security guide's example is send_file("/var/www/uploads/" + params[:filename]), which serves ../../../config/master.key as readily as an upload. Resolve the path and check it stays inside the directory:

EXPORT_DIR = Rails.root.join("storage", "exports").to_s

def download
  name = File.basename(params[:file].to_s)
  path = File.expand_path(name, EXPORT_DIR)
  unless path.start_with?(EXPORT_DIR + File::SEPARATOR) && File.file?(path)
    return head :not_found
  end
  send_file path, disposition: "attachment"
end

Better still, do not take a file name at all. Look up a record the user owns and serve its attachment, so the path never comes from the request. The same review applies to File.read, File.open and render file:.

5. constantize and send with a request value

Dynamic dispatch is idiomatic Ruby and dangerous with input. params[:type].constantize lets the request pick any class loaded in the process; object.send(params[:action]) lets it call any method, private ones included.

# Wrong
def create
  klass = params[:type].constantize
  klass.create!(payload_params)
end
# Right: a fixed map from request values to classes
NOTIFIERS = { "email" => EmailNotifier, "sms" => SmsNotifier }.freeze

def create
  klass = NOTIFIERS.fetch(params[:type]) { return head :unprocessable_entity }
  klass.create!(payload_params)
end

Use public_send over send when dispatch is genuinely needed, and still check the method name against a list.

6. Switching off CSRF protection

Forgery protection is on for ActionController::Base controllers in any app on load_defaults 5.2 or later, through default_protect_from_forgery. It goes away when a controller calls skip_forgery_protection or skip_before_action :verify_authenticity_token, usually to make a JavaScript client or a webhook work.

# Risky: the whole controller accepts cross-site POSTs with the user's cookie
class PreferencesController < ApplicationController
  skip_forgery_protection
end

A webhook endpoint that authenticates with a signature and never reads the session can skip the check safely, if it is limited to that action with only:. A browser-facing controller that uses the session cookie cannot. Send the CSRF token from csrf_meta_tags in the X-CSRF-Token header from your JavaScript instead. Controllers that inherit from ActionController::API have no forgery protection at all, which is fine for token-authenticated APIs and wrong for any that read a session cookie.

A seventh one: redirect_to

redirect_to params[:return_to] is an open redirect. Rails apps on load_defaults 7.0 or later raise on a redirect to another host unless the call passes allow_other_host: true, so search for that option and check each use. Our post on open redirects in OAuth flows covers validating return paths.

Review table

Search for Question to ask
permit! Why is every attribute assignable here?
where(", find_by_sql, execute(, Arel.sql Is any part of this string from a request?
html_safe, raw(, render html: Was every part of this string built from constants?
send_file, File.read, render file: Does a request value choose the path?
constantize, .send(, public_send Does a request value choose the class or method?
skip_forgery_protection, verify_authenticity_token Does this controller read the session cookie?
allow_other_host: true Is the destination validated?

What Vulkro checks in Rails

Vulkro Core reads Rails and Sinatra applications with a Ruby rule pack. Routes in config/routes.rb (resources, namespaces, scopes, member and collection routes) are joined to their controller actions, and before_action authentication filters, including inherited ones and skip_before_action, count as guards. Inside each action it follows a request value (params, cookies, headers, the raw body) into the sinks above:

Rule Reports
RUBY-MASS-001 params.permit!
RUBY-SQLI-001 A request value interpolated or concatenated into Active Record or raw SQL
RUBY-XSS-001 A request value marked safe with html_safe, raw or render html:
RUBY-PATH-001 A request value naming a file for send_file, File or render file:
RUBY-CODE-001 A request value reaching eval, constantize or send
RUBY-REDIRECT-001 A request value as the redirect_to destination

RUBY-CMDI-001, RUBY-DESER-001, RUBY-SSRF-001 and RUBY-SSTI-001 cover shell commands, Marshal.load and YAML.load, outbound HTTP and render inline:. The flow is followed within one method only; a value passed to a helper method is not tracked. There is no dedicated rule for skipped CSRF protection, so keep that row of the review table as a manual check. Gemfile.lock is matched against the local vulnerability data.

vulkro scan .
vulkro rbac .    # each route with the login level its before_action filters require

FAQ

Is permit! ever safe?

Only on a hash you built yourself from trusted data, never on request parameters. If a model has many editable fields, list them; the list doubles as documentation of what the form can change.

Does Active Record prevent SQL injection?

For hash conditions, ? placeholders, named placeholders and finders like find, yes. It cannot protect a SQL string that already contains interpolated input, which is what where("name = '#{x}'") produces.

Is html_safe the same as sanitize?

No. html_safe escapes nothing; it marks a string as trusted. sanitize removes tags and attributes outside an allowlist. Use sanitize or a tag helper for anything that contains user content.

See the API security use case and the scan reference, or start a 14-day trial. Related: mass assignment and CSRF in 2026.