A MongoDB checkout service moved off a shared admin login now gets Unauthorized errors despite a readWrite grant; how do you diagnose and fix it?
answer
- refused action, not refused login
- ask the session what it holds
- which database did the grant name
- match the failed command to its action
- grant one action, not admin again
basics
~20 sRead what the session really holds with connectionStatus and showPrivileges, then compare it with the action the failed command needs. Usual causes are a bare role name resolved against admin, or an action such as collMod that readWrite lacks.
solid answer
~50 s`Unauthorized`, code 13, means the server refused an action; a rejected credential gives `AuthenticationFailed`, code 18. I run `db.runCommand({ connectionStatus: 1, showPrivileges: true })` on the service's own credentials and read `authenticatedUsers`, `authenticatedUserRoles` and the privileges. A classic result is `{ role: "readWrite", db: "admin" }`: someone ran `db.grantRolesToUser("checkout", ["readWrite"])` on `admin`, where the user lives, and a bare name resolves to the database the command runs on. The fix is to revoke it and grant `{ role: "readWrite", db: "shop" }`. If the role is right, I look the failed command up in the privilege actions reference: `collMod` is not in `readWrite`, and `serverStatus` is a cluster action. Then I grant just that action through a custom role, never `root` again. A mongod applies the change on the session's next request without a reconnect; a mongos checks its user cache every 30 seconds by default.
code
javascript · 3 linesuse admin
db.getUser("checkout")
db.getSiblingDB("shop").getRole("readWrite", { showPrivileges: true })go deeper
Recall the difference between a refused login and a refused action, and that connectionStatus shows what the current connection holds.
Explain why a bare role name resolves to the database where the command runs, and read the db field on each role rather than trusting the role name alone.
Work from evidence: session state first, then the failed command's action and resource. Fix with the narrowest privilege, and resist returning the service to a wide role under incident pressure.
Make this failure cheap by having grants use the document form and by testing new roles against each service's real commands before cutover, so that a migration off a shared login does not depend on incident-time judgment.
## Separate the two failures first An application error during a login migration can come from two very different places, and the fix for one does nothing for the other: - `AuthenticationFailed` (code 18) means the credential was rejected. That is a question of the password, the mechanism or the user's database, not of roles. - `Unauthorized` (code 13) means the server refused an operation. Either the client has the wrong privileges, or it never logged in at all. Everything below concerns the second. Where the user is defined does not limit what it may do: `authSource` only tells the server where to look the user up, and a role's reach comes from the grant. ## Ask the session what it holds Do not reason from what you think was granted. Connect with the service's own credentials and ask: ```javascript db.runCommand({ connectionStatus: 1, showPrivileges: true }) ``` ```plaintext authInfo: { authenticatedUsers: [ { user: "checkout", db: "admin" } ], authenticatedUserRoles: [ { role: "readWrite", db: "admin" } ], authenticatedUserPrivileges: [ ... ] } ``` Read it in order: 1. `authenticatedUsers`. If it is empty, the client never logged in. If it names another user, the service is using the wrong credentials. 2. `authenticatedUserRoles`. Check the `db` on every role, not only the role name. 3. `authenticatedUserPrivileges`. Look for the action you need on a resource that covers the target. For the definition behind a role, run `db.getRole("checkoutWriter", { showPrivileges: true })` on its database, and `db.getUser("checkout")` on the user's database. ## Match what you see to a cause | What you see | Cause | Fix | |---|---|---| | Role shows `db: "admin"` where you expected `shop` | A bare role name resolved on `admin`, where the command ran | Revoke it and grant `{ role: "readWrite", db: "shop" }` | | Role is right, and `collMod` is refused | `readWrite` has no `collMod` | `dbAdmin`, or a custom role holding `collMod` | | Role is right, and `serverStatus` is refused | That is a cluster action, outside any database role | `clusterMonitor`, or `serverStatus` on `{ cluster: true }` | | A custom role, and only a new collection is refused | Exact-namespace resources do not cover later collections | Add a privilege, or use a database-level resource | | `system.profile` is refused | Database-level resources exclude system collections | Name the collection in a privilege | | The privilege is listed, but the command is still refused | A real action on the wrong kind of resource, which the server generally accepts | Re-create the privilege on the right resource | The first row is the classic one. `db.grantRolesToUser` must run on the user's own database, and a string in the `roles` array resolves against that same database. So `use admin` followed by `["readWrite"]` grants `readWrite` on `admin`. The call succeeds, the user looks fully granted, and every operation on `shop` stays refused. The document form cannot go wrong that way: ```javascript use admin db.revokeRolesFromUser("checkout", ["readWrite"]) db.grantRolesToUser("checkout", [{ role: "readWrite", db: "shop" }]) ``` One more case looks like a broken role and is not. Holding `find` authorizes `aggregate`, but not its `$out`, `$collStats` and `$indexStats` stages, so a report can run for months and then be refused the day someone adds `$out`. Those stages need their own actions. ## Fix it narrowly The pressure in an incident is to put the service back on `root` or hand it `readWriteAnyDatabase`. That quietly undoes the migration. A better routine: 1. Take the failed command from the error. 2. Find the action it needs in the privilege actions reference. Note which resource that action applies to. 3. Pick the smallest resource that covers the target. 4. Grant it, through a built-in that fits or a custom role. 5. Re-run `connectionStatus`, then the command itself. ## When the right grant still seems not to work - **On a mongod,** a session refreshes its user information at the start of each request, so the service does not need to reconnect. - **On a replica set,** the grant has to reach the member being read from. These commands use `"majority"` write concern by default, so a member outside that majority can lag behind for a moment. - **On a mongos,** the user cache is checked on a timer, `userCacheInvalidationIntervalSecs`, 30 seconds by default. `invalidateUserCache` flushes it straight away.
- The grant is correct, yet a service behind a mongos stays refused for a short while. Why?A mongos is not told about user changes directly. It compares a cache generation on a timer, `userCacheInvalidationIntervalSecs`, which defaults to 30 seconds, so a grant can take that long to show. Running `invalidateUserCache` on that mongos flushes the cache straight away. A mongod that has applied the change needs no such step.
- Does the service have to reconnect to pick up a corrected grant?No. At the start of each request, the session re-checks its cached user and picks up the change when the user's information has been invalidated, so an open connection gains the new role without logging in again. Restarting the service to fix a role is unnecessary and can hide what actually fixed it.
- A service with collection-level privileges is refused only on a collection added in its latest release. Is that a bug?No, it is what an exact-namespace resource means: `{ db: "shop", collection: "orders" }` covers that name only. Add a privilege for the new collection as part of the release, or move the role to `{ db: "shop", collection: "" }` and accept reach over later collections. That is the standing tradeoff of narrow roles, so the deploy process should own it.
- An Unauthorized error means the password or the authSource is wrong.
- A bare role name in db.grantRolesToUser refers to the database the service uses.
- The safe fix during an incident is readWriteAnyDatabase, because it only touches data.
- The service must reconnect before a corrected grant takes effect on a mongod.
- readWrite includes collMod, because it can already create and drop collections.