Pins this version in aipm.package.json and aipm-lock.json.
aipm add @affaan-m/rails-security@1.0.0
Without project tracking
Writes the skill files only. Add --no-init to skip aipm.package.json and the lockfile.
aipm add @affaan-m/rails-security@1.0.0 --no-init
How to use
Install the skill above, then run this in your AI tool:
/rails-security <your description>
About
Security practices for Ruby on Rails applications (Rails 7.1+ and 8.x). Rails is secure by
default in most places; the vulnerabilities that reach production usually come from opting
out of a default rather than failing to add protection. This skill is the "how." For the
decisions about which control to reach for, see the Ruby security rules —
`rules/ruby/security.md` in this repository, installed as `rules/ecc/ruby/security.md`.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
x apps. Covers production configuration, authentication, authorization, strong parameters, SQL injection, XSS and output escaping, CSRF, file uploads, API security, credentials, untru...
Skill instructions
Rails Security
Security practices for Ruby on Rails applications (Rails 7.1+ and 8.x). Rails is secure by
default in most places; the vulnerabilities that reach production usually come from opting
out of a default rather than failing to add protection. This skill is the "how." For the
decisions about which control to reach for, see the Ruby security rules —
rules/ruby/security.md in this repository, installed as rules/ecc/ruby/security.md.
When to Activate
Writing or reviewing authentication, sessions, or account recovery
Adding authorization checks to controllers or views
Handling user input, file uploads, or webhook payloads
Configuring a Rails app for production
Reviewing a PR that touches config/, app/controllers/, or Gemfile
Any use of html_safe, raw, Arel.sql, or raw SQL strings
Production Configuration
ruby
# config/environments/production.rbRails.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 = :infoend
authenticate_by looks up and verifies in one call, so a missing user and a wrong password
take the same time:
ruby
# 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])
Rotate the session on sign-in and on any privilege change:
Password reset tokens must expire, be single-use, and not reveal whether an account exists.
Signed tokens generated by the model give you both:
ruby
classUser < ApplicationRecord
generates_token_for :password_reset, expires_in:15.minutes do
password_salt&.last(10) # invalidates the token once the password changesendend
user = User.find_by_token_for(:password_reset, params[:token])
Render the same response whether or not the address matched.
Authorization
Authentication is not authorization. Every action that touches a record must check that the
current user may act on it.
ruby
# 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])
For anything past ownership, use a policy object (Pundit, Action Policy, or CanCanCan):
Fail closed — verify that authorization ran rather than trusting each action to remember:
ruby
classApplicationController < ActionController::BaseincludePundit::Authorization
after_action :verify_authorized, except::index
after_action :verify_policy_scoped, only::indexend# Public actions have no record to authorize, so exempt them explicitly.classSessionsController < ApplicationController
skip_after_action :verify_authorizedend
Strong Parameters and Mass Assignment
Never pass raw params to a model. Permit an explicit list:
ruby
# Bad: a crafted request can set adminUser.new(params[:user])
# Gooddefuser_params
params.require(:user).permit(:email, :name)
end
Rails 8 adds expect, which raises on a malformed structure instead of returning an empty
hash:
ruby
defuser_params
params.expect(user: [:email, :name])
end
Attributes such as admin, role, user_id, and account_id should never appear in a
permit list driven by request data. Assign them explicitly from the session or a checked
policy.
SQL Injection
Active Record parameterizes by default. Injection appears when a string is built by hand:
# config/initializers/content_security_policy.rbRails.application.configure do
config.content_security_policy do |policy|
policy.default_src :self
policy.script_src :self
policy.object_src :none
policy.frame_ancestors :noneendend
CSRF
Rails enables CSRF protection for new apps. Keep it on, and do not exempt actions to make a
client work:
ruby
# Bad: disables protection for every action in the controller
skip_before_action :verify_authenticity_token
If an endpoint genuinely cannot carry the token — a third-party webhook, say — authenticate
it another way (signature verification) and scope the exemption to that action alone.
API-only controllers inheriting from ActionController::API have no cookie session, so CSRF
does not apply; token or session-cookie APIs still need it.
File Uploads
The content_type a client sends is attacker-controlled, and blob.content_type is not a
substitute for it. Active Storage derives that column through Marcel::MimeType.for, which
treats the client's declared type as one candidate alongside magic-byte detection and keeps
it when the bytes match nothing known — so opaque bytes declared image/png are stored as
image/png with identified? true. Inspect the stored bytes yourself:
ruby
moduleUploadsRejected = 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
defself.verified!(blob)
# Fail closed: an object that is missing or still pending cannot be inspected.raiseRejected, "could not be verified"unless blob.service.exist?(blob.key)
raiseRejected, "is too large"if blob.byte_size > MAX_BYTES
extension = File.extname(blob.filename.to_s).downcase
raiseRejected, "extension not allowed"unlessALLOWED_EXTENSIONS.include?(extension)
head = blob.service.download_chunk(blob.key, 0...8)
raiseRejected, "type not allowed"unlessMAGIC.any? { |_mime, magic| head.start_with?(magic) }
blob
endend
The check reads from storage, so it has to run where the bytes already exist. A form upload
is not yet in storage when model validations run — Active Storage uploads on save — so
upload explicitly first, and attach only what passed:
ruby
# 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])))
Attach to a private service — a public bucket makes every upload world-readable regardless
of the checks above.
rails_blob_url and url_for(attachment) are stable references that never expire; they
redirect to a short-lived service URL, so anyone holding one keeps access. Serve
user-scoped files from your own controller that authorizes each request, with
config.active_storage.draw_routes = false, which removes every default Active Storage
route; apps using direct uploads need a replacement route:
ruby
get "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_uploadsendclassDocumentPolicy < ApplicationPolicydefshow?
record.user_id == user.id
endendclassDocumentFilesController < ApplicationControllerdefshow
document = current_user.documents.find(params[:id])
authorize document, :show?
redirect_to document.file.blob.url(expires_in:5.minutes), allow_other_host:trueendend
Never interpolate a user-supplied path into send_file:
Rate-limit authentication and other abusable endpoints. Action Controller ships
rate_limit from Rails 7.2; use rack-attack on 7.1 or for app-wide throttling:
The job marks processed_at when it finishes. Jobs retry, so perform must be
idempotent for the same reason. Requires a stable id in the signed body.
Keep CORS narrow — never reflect an arbitrary origin alongside credentials:
ruby
# Bad
origins "*"# Good
origins "https://app.example.com"
Serialize responses explicitly so new columns do not leak:
ruby
# Bad: ships every column, including ones added later
render json:@user# Good
render json:@user.as_json(only: %i[id name created_at])
Secrets and Credentials
Secrets belong in Rails credentials, environment variables, or a secret manager:
bash
bin/rails credentials:edit --environment production
config/credentials/production.key must stay out of version control. Read secrets through
Rails.application.credentials or ENV.fetch — ENV[...] returns nil and fails silently
when a variable is missing:
If a key is ever committed, rotate it. Removing the commit does not un-expose it.
Untrusted Boundaries
Controller params are not the only entry point. Job arguments, webhook payloads, Action
Cable messages, and Turbo Stream targets all carry outside data:
Pass record IDs to jobs and re-scope inside perform; a queued job runs without the
original request's session.
Authorize in ApplicationCable::Connection and in each channel's subscribed.
Never build a Turbo Stream target from user input.
ruby
classExportJob < ApplicationJobdefperform(user_id, invoice_id)
user = User.find(user_id)
invoice = user.invoices.find(invoice_id) # scoped, not Invoice.find# ...endend
Brakeman flags the patterns above statically. Treat new warnings as blocking, and record
deliberate exceptions in config/brakeman.ignore with a reason rather than lowering the
confidence threshold.
Verification Checklist
force_ssl and config.hosts set in production
Sensitive parameters filtered from logs
Sessions rotated on sign-in and privilege change
Every record lookup scoped to the current user or checked by a policy
No permit list contains a role, ownership, or account column
No raw SQL string interpolation; order and pluck inputs allowlisted
Every html_safe and raw reviewed
CSRF exemptions scoped to specific actions with another auth mechanism
Uploads validated against stored bytes, not blob.content_type, and fail closed when the object is unavailable
Auth endpoints rate-limited; webhook signatures compared in constant time
No secrets in version control; master key excluded
bundle-audit and brakeman clean
Related Skills
rails-patterns — the architectural patterns these controls sit inside
security-review — secure-by-default review patterns across languages
Ruby security rules (rules/ruby/security.md, installed as rules/ecc/ruby/security.md)
— the decisions and when-to-use guidance this skill implements
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/affaan-m/rails-security/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@affaan-m/rails-security@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: 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, untru...
Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You the...
Run aipm add @affaan-m/rails-security@1.0.0 in a project that has AIPM initialized.
Supported tools
@affaan-m/rails-security@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.