Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a secure way to prevent a user from updating specific fields in a MongoDB document?

I am trying to prevent users from updating certain fields in a mongodb object for which they are allowed to edit every other field. For instance the user should be able to edit/add/remove all fields except the field "permissions". My current approach is to test each key the user is trying to "$set" and see if it starts with the substring "permissions" (to cover dot notation). Example in python:

def sanitize_set(son):
    return {"$set": {k: v for k, v in son.get("$set", {}).items()
            if not k.startswith("permissions")}}

This approach is beautifully simple and seems to work. I wanted to reach out to the community to see if anyone else has tackled this issue before or sees obvious flaws in my approach. Thank you,

Joshua

like image 766
Joshua Avatar asked Oct 30 '22 10:10

Joshua


1 Answers

Without seeing some example data with an explanation of what should/shouldn't be updatable - it's hard to say for sure, but the way I would prevent this would be to not allow the user to directly supply the fields they will be updating. For example say you had a function called update_employee which updated information in an employee document. If you implement it like this:

update_employee(employee):
   db.employees.update({_id: session.user_id}, {$set: employee})

Whatever gets passed in as the employee object is what will be updated. Instead you could create the update object using the values passed in like so:

update_employee(employee):
   updatedEmployee = {
      email: employee.email,
      address: employee.address,
      phone: employee.phone
   }
   db.employees.update({_id: session.user_id}, {$set: updatedEmployee})

This way you have complete control over what is being updated in your database. So if an extra field (such as salary) is passed in, it will be ignored.

like image 146
Abe Miessler Avatar answered Nov 15 '22 08:11

Abe Miessler