I'm fixing some mass assignment vulnerabilities in a client's application and I want to make sure Rails isn开发者_如何学Go'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
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
精彩评论