8

我正在修复客户端应用程序中的一些批量分配漏洞,并且我想确保 Rails 不会默默地放弃批量分配受保护属性的尝试。相反,我想抛出一个异常以便进行调查。

即,每当这通常出现在日志中时:

WARNING: Can't mass-assign these protected attributes: ...

我想改为抛出异常(或另外)

编辑:我正在使用 Rails 2.3.4

4

1 回答 1

10

你必须做一些 Rails 猴子补丁才能做到这一点。请确保仅在开发和/或测试中使用此代码,因为如果用户尝试进行批量分配,您不希望您的应用程序引发错误。我会将以下内容添加到config/initializers/error_mass_assign.rb

module ActiveModel
  module MassAssignmentSecurity
    module Sanitizer
    protected
      def warn!(attrs)
        self.logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if self.logger
        raise(RuntimeError, "Mass assignment error") if ['test', 'development'].include?(Rails.env)
      end
    end
  end
end

这将引发常规警告,但在测试和开发环境中任何时候大规模分配受保护的属性时,它也会引发带有消息“大规模分配错误”的 RuntimeError。如果您更喜欢另一个异常,您也可以修改上面代码中的错误消息或错误。

请务必重新启动控制台或服务器以使其生效。

PS:在 Rails 2 中,您需要执行以下操作:

module ActiveRecord
  class Base
    def log_protected_attribute_removal(*attributes)
      logger.debug "WARNING: Can't mass-assign these protected attributes: #{attributes.join(', ')}"
      raise(RuntimeError, "Mass assignment error")
    end
  end
end
于 2011-04-05T21:23:39.803 回答