每当有人试图大规模分配保护的属性抛出一个异常 [英] Throw an exception whenever someone tries to mass-assign protected attributes

查看:176
本文介绍了每当有人试图大规模分配保护的属性抛出一个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我固定在一个客户端的应用程序的一些质量分配漏洞,我想确保Rails的是不是默默下降尝试整体分配的保护属性。相反,我想抛出一个异常,这样我就可以调查。

I'm fixing some mass assignment vulnerabilities in a client's application and I want to make sure Rails isn't silently dropping attempts to mass assign protected attributes. Instead, I want to throw an exception so I can investigate.

也就是说,只要这通常出现在日志中:

I.e., whenever this would normally appear in the logs:

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

我想,而不是抛出一个异常(或补充)

I'd like to throw an exception instead (or in addition)

编辑:我用Rails 2.3.4

I'm using Rails 2.3.4

推荐答案

您将不得不做一些Rails的猴子打补丁来做到这一点。务必仅使用code在开发和/或测试,但因为你不希望如果用户试图大规模分配您的应用程序提升的错误。我想补充以下内容配置/初始化/ error_mass_assign.rb

You'll have to do some Rails monkey-patching to do this. Be sure to only use this code in development and/or test though since you don't want your app raising errors if a user tries to mass-assign. I would add the following to 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时在测试和开发环境随时随地保护属性是质量分配。您也可以修改code中的错误信息或错误上面,如果你preFER另外的异常。

This will raise the regular warning, but it will also raise a RuntimeError with the message "Mass assignment error" when in test and development environments anytime protected attributes are mass-assigned. You can also modify the error message or error in the code above if you prefer another exception.

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

Be sure to restart your console or server for this to take effect.

PS:在Rails 2你要做到以下几点:

P.S: In Rails 2 you'll want to do the following:

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

这篇关于每当有人试图大规模分配保护的属性抛出一个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆