In MongoDB, how do you write a custom role with db.createRole, and what limits the privileges and roles it can include?
answer
- name, privileges, inherited roles
- the database you run it on matters
- admin is the exception
- inheritance only ever adds
- built-ins cannot be edited
basics
~20 sdb.createRole takes a role name, a privileges array and a roles array to inherit from. Outside admin, a role may only target and inherit from its own database; a role in admin can reach other databases and the cluster.
solid answer
~50 sYou run `db.createRole` on the database the role should live in, passing `role`, a `privileges` array of resource-and-actions entries, and a `roles` array to inherit from. Both arrays are required, and either may be empty. A role's identity is its database plus its name. A role outside `admin` may only target its own database and inherit from roles there, and the server refuses anything else. A role in `admin` can target other databases and the cluster, and inherit from any database. Inheritance only adds: a user's access is the union of everything in all their roles, so a narrower role takes nothing away. The creator needs `createRole` on that database and `grantRole` on what the role refers to. Built-in roles cannot be edited or shadowed, so you narrow `readWrite` by creating a new role, granting it and revoking the old one.
code
javascript · 9 linesuse admin
db.createRole({
role: "onCallDba",
privileges: [
{ resource: { cluster: true }, actions: ["killop"] }
],
roles: ["clusterMonitor"]
})
db.grantRolesToUser("oncall", ["onCallDba"])go deeper
Recall the three required parts of the call: a role name, a privileges array, and a roles array that may be empty. Remember that a role belongs to the database you ran the command on.
Explain the scope rule and why admin is the exception, then describe inheritance as a union by reference. Mention that a bare role name resolves in the database where the command runs.
Show the safe sequence for narrowing a service: create, grant, verify, then revoke. Know that db.updateRole replaces whole arrays and that db.dropRole removes the role from its holders immediately.
Weigh defining roles per service database, where the server contains them, against defining them in admin, where they can reach further. Decide who may create roles, because that power is close to granting anything.
## When a custom role earns its place Built-in roles are coarse. On a replica set shared by a checkout service, an analytics job and an on-call DBA, `readWrite` gives the checkout service `dropCollection` and `dropIndex` it should never use. A **custom role**, which the manual calls a user-defined role, lets you list exactly the actions and resources it needs. ## The shape of the call Run `db.createRole` on the database the role should belong to: ```javascript use shop db.createRole({ role: "checkoutWriter", privileges: [ { resource: { db: "shop", collection: "orders" }, actions: ["find", "insert", "update"] }, { resource: { db: "shop", collection: "carts" }, actions: ["find", "insert", "update", "remove"] } ], roles: [] }) ``` - `role` is the name. **Database plus name** identifies a role, so `shop.checkoutWriter` and `billing.checkoutWriter` are different roles. - `privileges` is required, and may be an empty array. - `roles` is required, and may be an empty array. A bare name means a role in the database where the command runs. A role elsewhere needs the document form `{ role: "...", db: "..." }`. - `authenticationRestrictions` is optional, and limits the addresses that holders of the role can connect from or to. All role definitions are stored in `admin.system.roles`, wherever they are scoped. Use the role management commands rather than touching that collection. ## The scope rule | Role created in | Privileges may target | May inherit from | |---|---|---| | any database except `admin` | that database only | roles in that database only | | `admin` | `admin`, other databases, the cluster | roles in any database | The server enforces this when the role is written, with `InvalidRoleModification`, and being `root` does not get around it. A role in `shop` cannot hold `serverStatus`, because that is a cluster action. So a role that mixes data and cluster needs belongs in `admin`. There are a few more refusals: no roles in `local` or `$external`, no role reusing a built-in role's name in that database, and no grant that would make a cycle in the role graph. ## How inheritance behaves - **It only adds.** A user's effective privileges are the union of the whole tree of roles they hold. If a user has `readWriteAnyDatabase` and you grant `read` on `shop`, they can still write to `shop`. - **It works by reference.** A role document stores the names of the roles it inherits, not a copy of their privileges, so a later change to the inherited role reaches everyone. - **To take access away, revoke.** No role subtracts anything. This means narrowing a built-in takes a sequence: 1. Create the narrower role. 2. Grant it with `db.grantRolesToUser`. 3. Confirm the service still works. 4. Revoke the built-in with `db.revokeRolesFromUser`. ## Granting it to a user A user defined in one database can hold a role defined in another, so a `checkout` user in `admin` can hold `shop.checkoutWriter`. Run the grant on the user's database, and use the document form, because a bare name would mean a role in `admin`: ```javascript use admin db.grantRolesToUser("checkout", [{ role: "checkoutWriter", db: "shop" }]) ``` Each action in a role can be scoped to a different collection, as above. The manual's own advice is to avoid handing `createCollection` to users who have no read privileges on that collection. ## Who may create a role Creating a role takes two things, and the server checks both: `createRole` on the role's database, and `grantRole` on every database the new role refers to. For privileges affecting several databases or the cluster, it wants `grantRole` on `admin`. `userAdmin` and `userAdminAnyDatabase` hold these on their respective resources, which is why those roles are so powerful. ## Changing a role later - `db.updateRole` **replaces** whatever it is given: pass `privileges` and the old array is gone. - `db.grantPrivilegesToRole`, `db.revokePrivilegesFromRole`, `db.grantRolesToRole` and `db.revokeRolesFromRole` change one piece at a time, and suit incremental edits. - `db.dropRole` deletes the role and also removes it from every user and every other role that held it, so dropping can cut access on the spot. - Built-in roles stay as shipped: the grant, revoke and drop commands refuse them with an error saying that a built-in role cannot be modified. For the on-call DBA, inheritance is the neat tool. A role in `admin` can inherit `clusterMonitor` and add one privilege, `killop` on `{ cluster: true }`, which gives inspection plus kill without `shutdown` or replica set configuration.
- Can a second, narrower role restrict what a user's first role allows?No. The manual is explicit that roles never limit privileges, and the effective set is the union across all of a user's roles. Granting `read` on `shop` to someone with `readWriteAnyDatabase` changes nothing. The only way to reduce access is to revoke the wider role with `db.revokeRolesFromUser`, after granting whatever narrower role should replace it.
- What must an administrator hold to create a role in admin that includes a cluster privilege?`createRole` on `admin`, plus `grantRole` on `admin`, because granting privileges that affect several databases or the cluster requires it. Each inherited role also needs `grantRole` on that role's database. `userAdmin` on `admin` holds both, as does `userAdminAnyDatabase`. `userAdmin` on `shop` fails, since it holds neither action on `admin`.
- How do you add one action to a custom role without risking the rest of its definition?Use `db.grantPrivilegesToRole`, which adds to what the role has. `db.updateRole` replaces the arrays it receives, so a call carrying a single privilege wipes the others. The change reaches every holder of the role through their next request on a mongod; a mongos notices on its cache check, every 30 seconds by default.
A role is a keyring, and inheriting a role clips another ring onto it. A user with several rings can open any door that any ring opens, and being handed one more ring never takes a key away.
- A role in the shop database can hold cluster privileges if a root user creates it.
- Granting read to a user who already has readWrite reduces that user to read-only.
- You can remove dropCollection from the built-in readWrite role for your deployment.
- db.updateRole appends to the role's existing privileges array.
- Inheriting a role copies its privileges once, so later changes do not flow through.