Mass assignment
Mass assignment didn’t die with attr_accessible
Strong parameters fixed the default. They didn’t fix permit!, or permitting the one attribute that decides who owns a record.
In March 2012, Egor Homakov pushed a commit to the master branch of rails/rails. He wasn’t a Rails committer. GitHub’s form for adding an SSH key trusted a user_id field in the request, so he submitted it with the Rails account’s ID, and his key became theirs. GitHub’s write-up is short. The bug was mass assignment, a ton of Rails apps had it, and it’s the reason strong parameters exist.
Strong parameters killed the classic version of this bug. Pass raw params[:user] into update and Rails raises ActiveModel::ForbiddenAttributesError instead of writing whatever the request sent. What’s left are the places where someone told strong parameters to stand down, usually to make an error go away at 6PM on a Friday.
The basic bug
def update
current_user.update!(params.require().permit!)
redirect_to profile_path
end
permit! marks every key as permitted, including admin, role, and whatever column gets added to the table next year. Send user[admin]=1 along with a profile update and you’re an admin. No exploit kit required; curl is plenty.
The basic fix
def update
current_user.update!(profile_params)
redirect_to profile_path
end
private
def profile_params
params.require().permit(, )
end
Name the fields. New columns stay unwritable until someone adds them here on purpose.
The hardcore version
def create
@project = Project.create!(project_params)
redirect_to @project
end
def update
@project.update!(project_params)
redirect_to @project
end
private
def project_params
params.require().permit(, , , )
end
Everything is explicitly permitted, so it looks right. But account_id and owner_id decide who the record belongs to, and they’re coming from the request. A user can create a project inside another company’s account, or move one of theirs over there. Usually this happens because the same params method serves an admin screen too, and the form for regular users simply doesn’t render those fields. The controller doesn’t care what the form renders.
The nested attributes version
class Team < ApplicationRecord
has_many
accepts_nested_attributes_for , true
end
def team_params
params.require().permit(, [, , , ])
end
The top-level list is short, so it gets a quick glance in review. The nested hash is where the trouble is. Any member who can rename the team can also send memberships_attributes with their own membership ID and role: "owner", or remove the actual owner with _destroy. The settings page only shows the member list to admins. The controller doesn’t know that.
Renaming a team and deciding who’s on it are different permissions, so give them different endpoints:
def team_params
params.require().permit()
end
class Teams::MembershipsController < ApplicationController
def update
team = current_user.teams.find(params[])
authorize team,
membership = team.memberships.find(params[])
membership.update!(params.require().permit())
redirect_to team_path(team)
end
end
accepts_nested_attributes_for is fine for line items on an order, where anyone allowed to edit the parent should be allowed to edit the children. It gets dangerous the moment the children carry permissions.
The JSON column version
def account_params
params.require().permit(, {})
end
class Account < ApplicationRecord
def seat_limit
settings.fetch("seat_limit", plan.seat_limit)
end
end
settings: {} permits a hash with any keys at any depth. The column started out holding a timezone and a theme. Two years later it also holds seat_limit, because sales needed a one-off override for a big customer and a migration felt like a lot. Now any account admin can send settings[seat_limit]=10000 along with their timezone. (Assigning the hash also replaces the whole column, so a normal save from the settings form quietly wipes the override. Two bugs for the price of one.)
class Account < ApplicationRecord
store_accessor , ,
end
def account_params
params.require().permit(, , )
end
store_accessor gives each key its own attribute, so you permit them by name like any other column, and a write only touches the keys it names. Anything that changes what a customer pays for gets a real column, written by billing code and nothing else.
Fix #1: Ownership comes from the session
def create
@project = Current.account.projects.build(project_params)
@project.owner = current_user
@project.save!
redirect_to @project
end
private
def project_params
params.require().permit(, )
end
Build through the association and set the owner yourself. Anything that decides who can see or change a record should never be in a permit list.
Here’s GitHub’s key form with that rule applied:
def create
@public_key = current_user.public_keys.build(params.require().permit(, ))
@public_key.save!
redirect_to settings_keys_path
end
user_id isn’t in the permit list and the key is built through current_user, so there’s nothing to forge. Send a user_id anyway and it gets dropped (or raises, with the development setting in Fix #3).
Fix #2: One form object per job
When the same model gets edited from three screens by three kinds of user, one shared permit list will eventually permit too much. Give each screen its own form object that only knows about its own fields:
class ProfileForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute ,
attribute ,
validates , , true
def initialize(user, attributes = {})
@user = user
super(attributes)
end
def save
return false unless valid?
@user.update( name, email)
end
end
def update
@form = ProfileForm.new(current_user, params.require().permit(, ))
if @form.save
redirect_to profile_path
else
render ,
end
end
Even if someone "fixes" that controller with permit! later, ProfileForm has no role attribute to assign. It raises ActiveModel::UnknownAttributeError instead of quietly promoting somebody. Role changes live in an admin-only form object that the profile screen never touches.
Fix #3: Make the model refuse
class Project < ApplicationRecord
belongs_to
belongs_to , "User"
attr_readonly
end
config.action_controller.action_on_unpermitted_parameters =
attr_readonly means account_id can be set on create and never changed after. On Rails 7.1+ with the 7.1 defaults, assigning it raises ActiveRecord::ReadonlyAttributeError; on older versions the change is silently dropped, which still beats saving it. Raising on unpermitted params in development means you find out the day a form starts sending a field you didn’t plan for, instead of it quietly getting dropped (or quietly getting permitted by the next person to touch it). Then write the spec that tries:
it "ignores role changes from the profile form" do
user = create(, "member")
sign_in user
patch profile_path, { { "Sam", "admin" } }
expect(user.reload.role).to eq("member")
end
Then grep for permit!. If it turns up outside an admin namespace, that’s your afternoon.