Loading...
Loading...
Ruby on Rails security practices for Rails 7.1+ and 8.x apps. Covers production configuration, authentication, authorization, strong parameters, SQL injection, XSS and output escaping, CSRF, file uploads, API security, credentials, untrusted boundaries, and dependency scanning. Use when reviewing or writing Rails authentication, authorization, input handling, uploads, or deployment configuration.
npx skill4agent add affaan-m/ecc rails-securityrules/ruby/security.mdrules/ecc/ruby/security.mdconfig/app/controllers/Gemfilehtml_saferawArel.sql# config/environments/production.rb
Rails.application.configure do
config.force_ssl = true
# Only use when all requests pass through a proxy that rejects or redirects HTTP.
config.assume_ssl = true # behind a proxy that terminates TLS
# Reject requests with unexpected Host headers.
config.hosts << "example.com"
config.hosts << /.*\.example\.com/
config.action_dispatch.cookies_same_site_protection = :lax
config.log_level = :info
end# config/initializers/filter_parameter_logging.rb
Rails.application.config.filter_parameters += %i[
passw secret token _key crypt salt certificate otp ssn cvv card_number
]bin/rails generate authenticationhas_secure_passwordclass User < ApplicationRecord
has_secure_password
validates :email, presence: true, uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 12 }, allow_nil: true
endauthenticate_by# Bad: the timing difference reveals whether the email exists
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
# Good
user = User.authenticate_by(email: params[:email], password: params[:password])class SessionsController < ApplicationController
def create
user = User.authenticate_by(email: params[:email], password: params[:password])
return render :new, status: :unprocessable_entity unless user
reset_session
session[:user_id] = user.id
redirect_to root_path
end
def destroy
reset_session
redirect_to root_path
end
endclass User < ApplicationRecord
generates_token_for :password_reset, expires_in: 15.minutes do
password_salt&.last(10) # invalidates the token once the password changes
end
end
user = User.find_by_token_for(:password_reset, params[:token])# Bad: any signed-in user can load any invoice
@invoice = Invoice.find(params[:id])
# Good: scope through the owner
@invoice = current_user.invoices.find(params[:id])class InvoicePolicy < ApplicationPolicy
def update?
user.admin? || record.user_id == user.id
end
end
class InvoicesController < ApplicationController
def update
@invoice = Invoice.find(params[:id])
authorize @invoice
# ...
end
endclass ApplicationController < ActionController::Base
include Pundit::Authorization
after_action :verify_authorized, except: :index
after_action :verify_policy_scoped, only: :index
end
# Public actions have no record to authorize, so exempt them explicitly.
class SessionsController < ApplicationController
skip_after_action :verify_authorized
endparams# Bad: a crafted request can set admin
User.new(params[:user])
# Good
def user_params
params.require(:user).permit(:email, :name)
endexpectdef user_params
params.expect(user: [:email, :name])
endadminroleuser_idaccount_id# Bad
User.where("email = '#{params[:email]}'")
Order.order("#{params[:sort]} #{params[:dir]}")
# Good
User.where(email: params[:email])
User.where("email = ?", params[:email])orderpluckgroupselectSORTABLE = { "created_at" => "created_at", "total" => "total" }.freeze
DIRECTIONS = { "asc" => "ASC", "desc" => "DESC" }.freeze
column = SORTABLE.fetch(params[:sort], "created_at")
direction = DIRECTIONS.fetch(params[:dir], "DESC")
Order.order(Arel.sql("#{column} #{direction}"))LIKE%_term = User.sanitize_sql_like(params[:q])
User.where("name LIKE ?", "%#{term}%")<%# Bad: renders attacker-controlled markup %>
<%= @comment.body.html_safe %>
<%= raw @comment.body %>
<%# Good: escaped %>
<%= @comment.body %>
<%# Good: allowlisted markup when the field is genuinely rich text %>
<%= sanitize @comment.body, tags: %w[p br strong em a], attributes: %w[href] %>html_safe<script>
const payload = <%= raw @data.to_json %>; // Bad
const payload = <%= raw json_escape(@data.to_json) %>; // Good
</script>link_tojavascript:uri = URI.parse(url) rescue nil
safe = uri.is_a?(URI::HTTP) # URI::HTTPS subclasses URI::HTTP# 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.object_src :none
policy.frame_ancestors :none
end
end# Bad: disables protection for every action in the controller
skip_before_action :verify_authenticity_tokenActionController::APIcontent_typeblob.content_typeMarcel::MimeType.forimage/pngimage/pngidentified?module Uploads
Rejected = Class.new(StandardError)
MAGIC = {
"application/pdf" => "%PDF-".b,
"image/png" => "\x89PNG\r\n\x1a\n".b,
"image/jpeg" => "\xFF\xD8\xFF".b
}.freeze
ALLOWED_EXTENSIONS = %w[.pdf .png .jpg .jpeg].freeze
MAX_BYTES = 10.megabytes
def self.verified!(blob)
# Fail closed: an object that is missing or still pending cannot be inspected.
raise Rejected, "could not be verified" unless blob.service.exist?(blob.key)
raise Rejected, "is too large" if blob.byte_size > MAX_BYTES
extension = File.extname(blob.filename.to_s).downcase
raise Rejected, "extension not allowed" unless ALLOWED_EXTENSIONS.include?(extension)
head = blob.service.download_chunk(blob.key, 0...8)
raise Rejected, "type not allowed" unless MAGIC.any? { |_mime, magic| head.start_with?(magic) }
blob
end
end# Form upload
blob = ActiveStorage::Blob.create_and_upload!(io: params[:file], filename: params[:file].original_filename)
document.file.attach(Uploads.verified!(blob))
# Direct upload: the client already stored the object, so verify before the record
# points at it.
document.file.attach(Uploads.verified!(ActiveStorage::Blob.find_signed!(params[:file])))has_one_attached :file, service: :private_documentsrails_blob_urlurl_for(attachment)config.active_storage.draw_routes = falseget "documents/:id/file", to: "document_files#show", as: :document_file
# Rails' direct-upload endpoint has no authentication of its own. This example uses a
# hand-rolled session sign-in; see Devise or the Rails 8 generator for their equivalents.
constraints ->(req) { req.session[:user_id].present? } do
post "uploads", to: "active_storage/direct_uploads#create", as: :rails_direct_uploads
end
class DocumentPolicy < ApplicationPolicy
def show?
record.user_id == user.id
end
end
class DocumentFilesController < ApplicationController
def show
document = current_user.documents.find(params[:id])
authorize document, :show?
redirect_to document.file.blob.url(expires_in: 5.minutes), allow_other_host: true
end
endsend_file# Bad: path traversal
send_file Rails.root.join("storage", params[:name])rate_limitrack-attackclass SessionsController < ApplicationController
rate_limit to: 10, within: 3.minutes, only: :create
endclass WebhooksController < ApplicationController
skip_before_action :verify_authenticity_token, only: :create
def create
expected = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("WEBHOOK_SECRET"), request.raw_post)
given = request.headers["X-Signature"].to_s
unless ActiveSupport::SecurityUtils.secure_compare(expected, given)
return head :unauthorized
end
event_id = JSON.parse(request.raw_post).fetch("id")
delivery = WebhookDelivery.create_or_find_by!(provider: "billing", delivery_id: event_id)
return head :ok if delivery.processed_at?
ProcessWebhookJob.perform_later(delivery.id, request.raw_post)
head :ok
end
endadd_index :webhook_deliveries, %i[provider delivery_id], unique: trueprocessed_atperform# Bad
origins "*"
# Good
origins "https://app.example.com"# Bad: ships every column, including ones added later
render json: @user
# Good
render json: @user.as_json(only: %i[id name created_at])bin/rails credentials:edit --environment productionconfig/credentials/production.keyRails.application.credentialsENV.fetchENV[...]nil# Bad
ENV["STRIPE_SECRET"]
# Good
Rails.application.credentials.dig(:stripe, :secret)
ENV.fetch("STRIPE_SECRET")performApplicationCable::Connectionsubscribedclass ExportJob < ApplicationJob
def perform(user_id, invoice_id)
user = User.find(user_id)
invoice = user.invoices.find(invoice_id) # scoped, not Invoice.find
# ...
end
endbundle exec bundle-audit check --update
bundle exec brakeman --no-progressconfig/brakeman.ignoreforce_sslconfig.hostsorderpluckhtml_saferawblob.content_typebundle-auditbrakemanrails-patternssecurity-reviewrules/ruby/security.mdrules/ecc/ruby/security.md