Rails 8.2 用 Sec-Fetch-Site 做 CSRF 校验:默认策略变化与其余变更清单
CSRF / 请求伪造防护
Rails 8.2 新增基于 Sec-Fetch-Site 请求头的 CSRF 防护。现代浏览器会发送该头,表示请求发起方与目标源的关系,Rails 用它验证同源请求,不再需要 authenticity token。两种策略通过 protect_from_forgery using: 指定:
:header_only:默认值,用于新建的 8.2 应用,只用Sec-Fetch-Site,拒绝没有有效头的请求。:header_or_legacy_token:有该头时用该头,否则回退到 token 校验,用于兼容旧浏览器。
合法跨站请求(OAuth 回调、第三方嵌入)用 trusted_origins 配置。
不带 strategy 调用 protect_from_forgery 被弃用,原因是当前默认的 :null_session 与 config.action_controller.default_protect_from_forgery 的 :exception 不一致。可用 config.action_controller.default_protect_from_forgery_with = :exception 切到新行为。
其他相关变动:
InvalidAuthenticityToken弃用,改用InvalidCrossOriginRequest。verify_authenticity_token改名为verify_request_for_forgery_protection。- CSRF 警告改为事件驱动日志,新事件:
csrf_token_fallback.action_controller、csrf_request_blocked.action_controller、csrf_javascript_blocked.action_controller。
其他 notable 变更
Rails.app
Rails.app 作为 Rails.application 的别名。Rails.app.revision 提供版本标识,默认读取 REVISION 文件或本地 git SHA。Rails.app.creds 合并 ENV 与加密凭据的访问,含 require 与 option。
Active Record
PostgreSQL 在支持的版本上执行 DROP DATABASE 时自动使用 FORCE 选项,先断开客户端再删库,bin/rails db:reset 不再需要先关闭应用实例。
修复了 SQLite3 表结构变更时,子表存在 ON DELETE CASCADE 外键导致的数据丢失。
新增 implicit_persistence_transaction 钩子。
Active Model
新增 has_json / has_delegated_json。
has_secure_password 支持 Argon2,用 algorithm: :argon2 启用;Argon2 没有 BCrypt 的 72 字节长度限制。新增 ActiveModel::SecurePassword.register_algorithm 用于注册自定义哈希算法。
Active Support
新增 SecureRandom.base32,生成对人无歧义、大小写不敏感的 key。
并行测试按 round-robin 确定性分配 worker,可用 work_stealing: true 让空闲 worker 窃取测试。
Active Job
移除 sidekiq 适配器,适配器现在在 sidekiq gem 里。
弃用内置的 queue_classic、resque、delayed_job、backburner、sneakers 适配器。如果使用 resque 3.0+ 或 delayed_job 4.2.0+,升级后改用 gem 自带适配器。
config.active_job.enqueue_after_transaction_commit 取消弃用并默认 true(新应用),修复了以前对未提交或已回滚记录执行 job 的问题。
Active Storage
附件在验证前分析,宽度/高度/时长可用于 validations,analyze: :immediately 为默认值,另有 :later、:lazily。process: :immediately 立即生成 variants。preprocessed: true 弃用,改为 process: :later。
Action View
渲染 collection 时可以传块。
Action Controller Live
config.action_controller.live.streaming_excluded_keys 用于排除不共享的状态 key。
routes inspector
rails routes --expanded 新增 Action Location 字段,显示 controller action 的定义位置。
其他
minitest 升级到 6.0+。
来源: