Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid: How to prevent undefined fields from being created by mass assignment?

Here's the code:

class M
  include Mongoid::Document
  field :name
end

params = { name: "foo", age: 20 }
M.create(params)
#=> #<M name: "My Name", age: 20>

Notice that age wasn't defined, yet it was saved.

This is problematic (potentially a source of DoS) because a malicious user can add any parameters in POST and unknown fields with a large string can sneak in. (e.g. name=foo&bogus=#{'x'*1000000})

So far, I couldn't find anything but attr_accessible, but it's not really great for Mongoid as you have to maintain the same field names in both field and attr_accessible all the time, in all models. Not DRY.

I think the attr_accessible API is great for ActiveRecord, because there a. you don't explicitly define fields in the models (DRY) and b. it's guaranteed there's no chance that a nonexistent field gets saved to RDB. But for Mongoid, I think there should be a better solution than attr_accessible.

Note that there's a global config setting allow_dynamic_fields but it's not about mass assignment so it's out of the scope in this discussion, however I think it should actually be a per-model macro and should also take care of mass-assignment.

How are you dealing with this problem?

like image 653
kenn Avatar asked Nov 14 '22 15:11

kenn


1 Answers

I'm always using attr_accessible in models. I rarely found myself including all fields as accessible. Usually there are always a few fields that shouldn't be accessible for mass assignment. If you often need to include every attribute and you're concerned about duplication:

attr_accessible *fields.keys
like image 113
Zargony Avatar answered Dec 20 '22 01:12

Zargony