rails-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rails Security

Rails 安全

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
.
适用于 Ruby on Rails 应用(Rails 7.1+ 和 8.x)的安全实践。Rails 在大多数方面默认是安全的;真正进入生产环境的漏洞通常源于主动关闭了某项默认保护,而不是因为没有额外添加保护。本 skill 关注“如何做”。至于应选择哪种控制措施,请参阅本仓库中的 Ruby 安全规则
rules/ruby/security.md
(安装后位于
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
  • 编写或审查身份验证、会话或账户恢复
  • 向控制器或视图添加授权检查
  • 处理用户输入、文件上传或 webhook 负载
  • 为生产环境配置 Rails 应用
  • 审查涉及
    config/
    、
    app/controllers/
    或
    Gemfile
    的 PR
  • 任何对
    html_safe
    、
    raw
    、
    Arel.sql
    或原始 SQL 字符串的使用

Production Configuration

生产环境配置

ruby
undefined
ruby
undefined

config/environments/production.rb

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:

```ruby
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

从日志中过滤敏感值:

```ruby

config/initializers/filter_parameter_logging.rb

config/initializers/filter_parameter_logging.rb

Rails.application.config.filter_parameters += %i[ passw secret token _key crypt salt certificate otp ssn cvv card_number ]
undefined
Rails.application.config.filter_parameters += %i[ passw secret token _key crypt salt certificate otp ssn cvv card_number ]
undefined

Authentication

身份验证

Rails 8 ships an authentication generator that produces session-based auth with password reset and metadata tracking:
bash
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:
ruby
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:
ruby
undefined
Rails 8 提供了身份验证生成器,可生成基于会话的身份验证,并支持密码重置和元数据跟踪:
bash
bin/rails generate authentication
当需要 OAuth、MFA、可确认、可锁定或多模型身份验证时,使用 Devise。对于自行实现的身份验证,
has_secure_password
可以处理 bcrypt 哈希:
ruby
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
通过一次调用完成用户查找和验证,因此用户不存在与密码错误时的耗时相同:
ruby
undefined

Bad: the timing difference reveals whether the email exists

Bad: the timing difference reveals whether the email exists

user = User.find_by(email: params[:email]) if user&.authenticate(params[:password])
user = User.find_by(email: params[:email]) if user&.authenticate(params[:password])

Good

Good

user = User.authenticate_by(email: params[:email], password: params[:password])

Rotate the session on sign-in and on any privilege change:

```ruby
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
user = User.authenticate_by(email: params[:email], password: params[:password])

在登录以及任何权限变更时轮换会话:

```ruby
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:
ruby
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.
密码重置令牌必须过期、单次使用,并且不能泄露账户是否存在。模型生成的有签名令牌可以同时满足这些要求:
ruby
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])
无论地址是否匹配,都应返回相同的响应。

Authorization

授权

Authentication is not authorization. Every action that touches a record must check that the current user may act on it.
ruby
undefined
身份验证不等于授权。每个涉及记录的操作都必须检查当前用户是否有权对其执行操作。
ruby
undefined

Bad: any signed-in user can load any invoice

Bad: any signed-in user can load any invoice

@invoice = Invoice.find(params[:id])
@invoice = Invoice.find(params[:id])

Good: scope through the owner

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

```ruby
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:
ruby
class ApplicationController < ActionController::Base
  include Pundit::Authorization

  after_action :verify_authorized, except: :index
  after_action :verify_policy_scoped, only: :index
end
@invoice = current_user.invoices.find(params[:id])

对于所有权检查之外的权限控制,使用策略对象(Pundit、Action Policy 或 CanCanCan):

```ruby
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(默认拒绝)策略——验证授权检查确实已经执行,而不是依赖每个操作都记得调用授权:
ruby
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.

Public actions have no record to authorize, so exempt them explicitly.

class SessionsController < ApplicationController skip_after_action :verify_authorized end
undefined
class SessionsController < ApplicationController skip_after_action :verify_authorized end
undefined

Strong Parameters and Mass Assignment

Strong Parameters 与批量赋值

Never pass raw
params
to a model. Permit an explicit list:
ruby
undefined
绝不要把原始
params
传给模型。应显式列出允许的属性:
ruby
undefined

Bad: a crafted request can set admin

Bad: a crafted request can set admin

User.new(params[:user])
User.new(params[:user])

Good

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:

```ruby
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.
def user_params params.require(:user).permit(:email, :name) end

Rails 8 新增了 `expect`,遇到结构错误时会抛出异常,而不是返回空哈希:

```ruby
def user_params
  params.expect(user: [:email, :name])
end
诸如
admin
、
role
、
user_id
和
account_id
之类的属性绝不应出现在由请求数据驱动的 permit list 中。应根据会话或经过检查的策略显式赋值。

SQL Injection

SQL 注入

Active Record parameterizes by default. Injection appears when a string is built by hand:
ruby
undefined
Active Record 默认会对参数进行参数化处理。当手工拼接字符串时,就可能出现注入:
ruby
undefined

Bad

Bad

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

Good

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 rather than escaping it:

```ruby
SORTABLE = { "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
needs its own escaping, since
%
and
_
are wildcards:
ruby
term = User.sanitize_sql_like(params[:q])
User.where("name LIKE ?", "%#{term}%")
User.where(email: params[:email]) User.where("email = ?", params[:email])

`order`、`pluck`、`group` 和 `select` 接受原始 SQL,且不会自动净化。应使用 allowlist 处理输入,而不是对其进行转义:

```ruby
SORTABLE = { "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
需要单独的转义处理,因为
%
和
_
都是通配符:
ruby
term = User.sanitize_sql_like(params[:q])
User.where("name LIKE ?", "%#{term}%")

XSS and Output Escaping

XSS 与输出转义

ERB escapes interpolated values by default. Every bypass is security-sensitive:
erb
<%# 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
does not sanitize — it marks a string as already safe and skips escaping. Only call it on strings you constructed.
Interpolating into JavaScript needs the matching escape, not the HTML one:
erb
<script>
  const payload = <%= raw @data.to_json %>;              // Bad
  const payload = <%= raw json_escape(@data.to_json) %>; // Good
</script>
link_to
's href accepts
javascript:
URLs, so validate user-supplied links:
ruby
uri = URI.parse(url) rescue nil
safe = uri.is_a?(URI::HTTP) # URI::HTTPS subclasses URI::HTTP
Set a Content Security Policy:
ruby
undefined
ERB 默认会转义插值后的值。每次绕过转义都涉及安全风险:
erb
<%# 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
不会进行净化——它只会将字符串标记为已经安全,从而跳过转义。仅对自己构造的字符串调用它。
插入 JavaScript 时需要使用匹配的转义方式,而不是 HTML 转义:
erb
<script>
  const payload = <%= raw @data.to_json %>;              // Bad
  const payload = <%= raw json_escape(@data.to_json) %>; // Good
</script>
link_to
的 href 接受
javascript:
URL,因此必须验证用户提供的链接:
ruby
uri = URI.parse(url) rescue nil
safe = uri.is_a?(URI::HTTP) # URI::HTTPS subclasses URI::HTTP
设置内容安全策略(Content Security Policy):
ruby
undefined

config/initializers/content_security_policy.rb

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
undefined
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
undefined

CSRF

CSRF

Rails enables CSRF protection for new apps. Keep it on, and do not exempt actions to make a client work:
ruby
undefined
Rails 会为新应用启用 CSRF 防护。保持其开启,不要为了迁就客户端而豁免操作:
ruby
undefined

Bad: disables protection for every action in the controller

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.
skip_before_action :verify_authenticity_token

如果某个端点确实无法携带令牌(例如第三方 webhook),应改用其他方式进行身份验证(如验证签名),并且仅对该操作单独设置豁免。

继承 `ActionController::API` 的纯 API 控制器没有基于 Cookie 的会话,因此不适用 CSRF;但使用令牌或会话 Cookie 的 API 仍需要 CSRF 防护。

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
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
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
undefined
客户端发送的
content_type
可由攻击者控制,
blob.content_type
不能替代它。Active Storage 通过
Marcel::MimeType.for
推导该列;该方法会将客户端声明的类型与 magic-byte 检测一起作为候选,并且当字节内容不匹配任何已知类型时仍保留客户端声明的类型——因此,声明为
image/png
的不透明字节会以
image/png
存储,且
identified?
为 true。请自行检查已存储的字节:
ruby
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
该检查从存储中读取数据,因此必须在字节已经写入存储后执行。运行模型验证时,表单上传的文件尚未进入存储——Active Storage 会在保存时上传——因此应先显式上传,并且只附加通过验证的对象:
ruby
undefined

Form upload

Form upload

blob = ActiveStorage::Blob.create_and_upload!(io: params[:file], filename: params[:file].original_filename) document.file.attach(Uploads.verified!(blob))
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

Direct upload: the client already stored the object, so verify before the record

points at it.

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.

```ruby
has_one_attached :file, service: :private_documents
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
document.file.attach(Uploads.verified!(ActiveStorage::Blob.find_signed!(params[:file])))

将文件附加到私有服务——无论上述检查如何,使用公共存储桶都会让每个上传文件都可被公开读取。

```ruby
has_one_attached :file, service: :private_documents
rails_blob_url
和
url_for(attachment)
是永不过期的稳定引用;它们会重定向到短时效的服务 URL,因此任何持有该引用的人都可持续访问。应使用自己的控制器提供按用户限定范围的文件,并对每次请求执行授权;同时设置
config.active_storage.draw_routes = false
,这会移除所有默认 Active Storage 路由;使用直接上传的应用需要提供替代路由:
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

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.

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 end

Never interpolate a user-supplied path into `send_file`:

```ruby
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 end

绝不要将用户提供的路径插入 `send_file`:

```ruby

Bad: path traversal

Bad: path traversal

send_file Rails.root.join("storage", params[:name])
undefined
send_file Rails.root.join("storage", params[:name])
undefined

API Security

API 安全

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:
ruby
class SessionsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create
end
Verify webhook signatures with a constant-time comparison:
ruby
class 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
end
ruby
add_index :webhook_deliveries, %i[provider delivery_id], unique: true
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
undefined
对身份验证及其他可被滥用的端点进行速率限制。Action Controller 从 Rails 7.2 起提供
rate_limit
;在 7.1 上可以使用
rack-attack
,也可用于应用级限流:
ruby
class SessionsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create
end
使用恒定时间比较验证 webhook 签名:
ruby
class 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
end
ruby
add_index :webhook_deliveries, %i[provider delivery_id], unique: true
该任务完成后会将
processed_at
标记为已处理。任务会重试,因此出于同样原因,
perform
必须具备幂等性。这要求签名请求体中包含稳定的 id。
保持 CORS 范围严格——绝不要在启用凭据的同时反射任意来源:
ruby
undefined

Bad

Bad

origins "*"
origins "*"

Good

Good


Serialize responses explicitly so new columns do not leak:

```ruby

显式序列化响应,防止新增字段泄露:

```ruby

Bad: ships every column, including ones added later

Bad: ships every column, including ones added later

render json: @user
render json: @user

Good

Good

render json: @user.as_json(only: %i[id name created_at])
undefined
render json: @user.as_json(only: %i[id name created_at])
undefined

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:
ruby
undefined
密钥应存放在 Rails credentials、环境变量或 secrets manager 中:
bash
bin/rails credentials:edit --environment production
config/credentials/production.key
必须排除在版本控制之外。通过
Rails.application.credentials
或
ENV.fetch
读取密钥——
ENV[...]
在变量缺失时返回
nil
并静默失败:
ruby
undefined

Bad

Bad

ENV["STRIPE_SECRET"]
ENV["STRIPE_SECRET"]

Good

Good

Rails.application.credentials.dig(:stripe, :secret) ENV.fetch("STRIPE_SECRET")

If a key is ever committed, rotate it. Removing the commit does not un-expose it.
Rails.application.credentials.dig(:stripe, :secret) ENV.fetch("STRIPE_SECRET")

如果密钥曾经被提交,应立即轮换。删除提交记录并不能消除已经暴露的风险。

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
class ExportJob < ApplicationJob
  def perform(user_id, invoice_id)
    user = User.find(user_id)
    invoice = user.invoices.find(invoice_id) # scoped, not Invoice.find
    # ...
  end
end
控制器参数并非唯一入口。任务参数、webhook 负载、Action Cable 消息和 Turbo Stream 目标都包含外部数据:
  • 向任务传递记录 ID,并在
    perform
    内重新限定查询范围;排队任务运行时没有原始请求的会话。
  • 在
    ApplicationCable::Connection
    和每个 channel 的
    subscribed
    中执行授权。
  • 绝不要根据用户输入构建 Turbo Stream 目标。
ruby
class ExportJob < ApplicationJob
  def perform(user_id, invoice_id)
    user = User.find(user_id)
    invoice = user.invoices.find(invoice_id) # scoped, not Invoice.find
    # ...
  end
end

Dependency Scanning

依赖项扫描

Run these when the lockfile changes, and in CI:
bash
bundle exec bundle-audit check --update
bundle exec brakeman --no-progress
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.
当 lockfile 发生变化时以及在 CI 中运行以下命令:
bash
bundle exec bundle-audit check --update
bundle exec brakeman --no-progress
Brakeman 会静态标记上述模式。将新的警告视为阻断项,并在
config/brakeman.ignore
中记录有意豁免及其原因,而不是降低置信度阈值。

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
  • 已在生产环境设置
    force_ssl
    和
    config.hosts
  • 已从日志中过滤敏感参数
  • 登录及权限变更时已轮换会话
  • 每项记录查询均按当前用户限定范围或经策略检查
  • permit list 中不包含角色、所有权或账户字段
  • 不存在原始 SQL 字符串插值;
    order
    和
    pluck
    的输入均使用 allowlist
  • 每个
    html_safe
    和
    raw
    都已审查
  • CSRF 豁免仅限于特定操作,并采用其他身份验证机制
  • 上传文件根据已存储的字节而非
    blob.content_type
    进行验证,并在对象不可用时 fail closed
  • 身份验证端点已限流;webhook 签名使用恒定时间比较
  • 版本控制中不包含密钥;主密钥已排除
  • bundle-audit
    和
    brakeman
    检查均无问题

Related Skills

相关 Skill

  • 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
  • rails-patterns
    ——这些控制措施所在的架构模式
  • security-review
    ——跨语言的默认安全审查模式
  • Ruby 安全规则(
    rules/ruby/security.md
    ,安装后位于
    rules/ecc/ruby/security.md
    )——本 skill 所实现的控制选择与适用场景指导