Skip to main content

Rails 4 and Mass Assignment – How to protect yourself!

By March 3, 2014Rails, Ruby

Recently, we had a colleague of ours do some penetration testing on our website in order to see how safe our site was for our users. Needless to say, no website is foolproof! It was pointed out to us that the way we had structured our mass assignments could potentially lead to many things which could be severely harmful to our data and users.

When it comes to mass assignment, one of the common problems is that we forget to whitelist what a common user is allowed to edit. I was quite foolish in not realizing this, but it was ridiculously easy to hack our website by just editing the input name and id’s to suit a hackers needs. Here is how our mass-assignments were handled before.

models/posts.rb

attr_accessible :title, :summary, :content, :status, :user_id

controllers/posts_controller.rb

    def post_params
        params.require(:post).permit(:title, :summary, :content, :status, :user_id)
    end

Now the problem with this was that we had allowed ANY users to update ANY of these fields as they saw fit. Just a little bit of editing in the forms could potentially mean that they were able to update the status of the post or even the user_id, and there was nothing stopping them! This is where whitelisting in Rails 4 comes into play. In order to tell rails which params a normal user is allowed to edit, all you would need to do is the following:

    def post_params
      if current_user && current_user.admin?
        params.require(:post).permit(:title, :summary, :content, :status, :user_id)
      else
        params.require(:post).permit(:title, :summary, :content)
      end
    end

What this does is, it lets Rails know that unless the user is logged in and has admin rights, only allow them to update the title, summary and content — anything else is ignored. It is as simple as that. Although this seems quite simple, for many newcomers to Rails might find this information a little bit difficult to find.