Over on less everything,
Steven Bristol makes the very good point that Ruby on Rails’ mass-assignment shortcut can be horrible, horrible
security hole. In many ways it’s a modern version of PHP’s register globals setting and most of us remember what became of that “feature”.
I do disagree with him on one point though; where he favours explicitly hiding attributes with attr_protected I’d much rather people started with everything hidden and chose to explicitly expose attributes with attr_accessible.
This has long been a bugbear of mine with Rails. So much so that the first plugin I wrote was explicit_assignment.rb, below
class ActiveRecord::Base
attr_accessible
end
That might not look like much but it’s three powerful lines of code.
Calling attr_accessible with no parameters in Base effectively means all application models start life completely ignoring calls to model.attributes = attrs. If I want to use mass-assignment for any value I have to specifically ask for it.
class AppModel < ActiveRecord::Base
attr_accessible :a_small_series, :of_accessible, :attribute_values
end
The only issue I’ve had is that this does tend to screw up a number plugin models that rely on mass-assignment. In this case all you have to do is read through all the plugins you use, make judgment calls on what should be accessible and update accordingly. What? You mean you don’t read every line of evey plugin you use? Nah, me neither, so I usually just change the explicit_assigment plugin to:
class AccessibleRecord < ActiveRecord::Base
self.abstract_class = true
attr_accessible
end
I then subclass all my application models from AccessibleRecord.
Yes, this is perhaps a bit verbose for a framework that prizes terseness and DRYness above all else but, if you value security too, I think it’s worth the extra text.
1 year ago