MongoDB Collection Level Permission Issues

mongodb

I am trying to set up a MongoDB user that only has access to certain collections across several databases. The issue is that these databases are created dynamically at runtime.

I decided to employ collection level access in order to do this with the following permission on the user role:

"db" : "admin",
"privileges" : [ 
    {
        "resource " : {
            "cluster" : true
        },
        "actions" : [ 
            "listDatabases"
        ]
    }, 
    {
        "resource" : {
            "db" : "",
            "collection" : "packages"
        },
        "actions" : [ 
            "find", 
            "insert", 
            "remove", 
            "update", 
            "listCollections"
        ]
    }]

What I want is for any user with this role to be able to read/write/remove in any database but only on the packages collection inside of that database, and be unable to read or write to any other collection. When I launch mongod in –auth I do not see any databases besides admin.

I am certain this is just me being unable to figure out exactly what actions / resources / roles I am supposed to grant.

Best Answer

Not clear what you mean but this could be a solution:

var role = "<role name>"; 
admin = db.getSiblingDB("admin");
if (admin.getRoles({ rolesInfo: role }).length == 0)
   admin.createRole({ role: role, privileges: [], roles: [] });
admin.grantRolesToUser(<the user>, [role]);
   

Then you would have to run this code every time when a new database is created.

db.getSiblingDB(<your dynamic database name>).getCollectionNames().forEach(function (item) {
   db.getSiblingDB("admin").grantPrivilegesToRole(role, [{
      resource: {
         db: <your dynamic database name>, collection: item }, 
         actions: ["find", "insert", "remove", "update"] }])
   })