-->

Throw an exception whenever someone tries to mass-

2019-04-06 12:13发布

问题:

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)

Edit: I'm using Rails 2.3.4

回答1:

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

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.

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