← 返回列表
全部 Skill›开发 Development›rails-security

rails-security

作者 @affaan-m · 语言 en
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.
开发 Development前端开发通用执行命令访问网络待翻译
存储库
最近源活动
—
检测 SKILL.md 语言
en
星标 ★
309,846
分支 Fork
0
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

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

# 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

Filter sensitive values out of logs:

# config/initializers/filter_parameter_logging.rb
Rails.application.config.filter_parameters += %i[
  passw secret token _key crypt salt certificate otp ssn cvv card_number
]

Authentication

Rails 8 ships an authentication generator that produces session-based auth with password

reset and metadata tracking:

bin/rails generate authentication

Use Devise when you need OAuth, MFA, confirmable, lockable, or multi-model auth. For

hand-rolled auth, has_secure_password handles bcrypt hashing:

class User < ApplicationRecord
  has_secure_password

  validates :email, presence: true, uniqueness: { case_sensitive: false }
  validates :password, length: { minimum: 12 }, allow_nil: true
end

authenticate_by looks up and verifies in one call, so a missing user and a wrong password

take the same time:

# 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:

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
end

Account recovery

Password reset tokens must expire, be single-use, and not reveal whether an account exists.

Signed tokens generated by the model give you both:

class 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])

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.

# 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):

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
end

Fail closed — verify that authorization ran rather than trusting each action to remember:

class 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
end

Strong Parameters and Mass Assignment

Never pass raw params to a model. Permit an explicit list:

# Bad: a crafted request can set admin
User.new(params[:user])

# Good
def user_params
  params.require(:user).permit(:email, :name)
end

Rails 8 adds expect, which raises on a malformed structure instead of returning an empty

hash:

def user_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:

# Bad
User.where("email = '#{params[:email]}'")
Order.order("#{params[:sort]} #{params[:dir]}")

# Good
User.where(email: params[:email])
User.where("email = ?", params[:email])

order, pluck, group, and select accept raw SQL and are not sanitized. Allowlist the

input rathe

评论
Aaffaan-m
affaan-m
affaan-m/ECC
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@affaan-m
所属大类开发 Development / 前端开发
国内可用性通用
最近源活动—
风险提示执行命令、访问网络
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。