Sunday
14Dec2008
Auditing for attr_accessible
Sunday, December 14, 2008 at 2:27PM
By now, you all know that you need to use attr_accessible to protect your application from having any old Active Record attribute changed by a malicious user. I find myself, in the course of consulting, looking at a great number of existing applications, and I've grown tired of having to open up every model and look. So, let's be a bit smart: here's a rake task that you can drop in any existing application to do the audit for you:
[sourcecode language='ruby']
namespace :utility do
desc 'Find models that are not using attr_accessible'
task :audit_attr_accessible => :environment do
all_models = Dir.glob(
File.join(Rails.root, 'app', 'models', '*.rb')
).map{|path| path[/.+\/(.+).rb/,1] }
ar_models = all_models.select{|m|
m.classify.constantize < ActiveRecord::Base}
ar_models.each do |model|
model_class = model.classify.constantize
if model_class.send("attr_accessible").empty? &&
model_class.send("attr_protected").empty?
puts model_class.class_name +
" allows unprotected mass assignment"
end
end
end
end
[/sourcecode]
(Hat tip Matt for the snippet to find all models).
[sourcecode language='ruby']
namespace :utility do
desc 'Find models that are not using attr_accessible'
task :audit_attr_accessible => :environment do
all_models = Dir.glob(
File.join(Rails.root, 'app', 'models', '*.rb')
).map{|path| path[/.+\/(.+).rb/,1] }
ar_models = all_models.select{|m|
m.classify.constantize < ActiveRecord::Base}
ar_models.each do |model|
model_class = model.classify.constantize
if model_class.send("attr_accessible").empty? &&
model_class.send("attr_protected").empty?
puts model_class.class_name +
" allows unprotected mass assignment"
end
end
end
end
[/sourcecode]
(Hat tip Matt for the snippet to find all models).

Reader Comments (2)
The Insoshi guys created a plugin to help with this;
http://blog.insoshi.com/2008/09/21/finding-and-fixing-mass-assignment-problems-in-rails-applications/
Couldn't adding :
class ActiveRecord::Base; attr_accessible nil; enddo the trick of quickly helping find the trespassers and as an added bonus help have sane defaults ?