MongoDB "not authorized on X to execute command" in CI
Authentication succeeded but authorization did not: the user has no role that grants the attempted action on that database. This is a permissions problem, not bad credentials.
What this error means
A command fails with "MongoServerError: not authorized on <db> to execute command { ... }", naming the operation the user may not run (createCollection, dropDatabase, a query on another db).
MongoServerError: not authorized on appdb to execute command
{ createIndexes: "users", indexes: [ ... ] }
code: 13, codeName: 'Unauthorized'Common causes
The user has too narrow a role
The CI user was granted only read (or a role scoped to one db) but the test needs readWrite or admin actions like index or collection creation.
The action targets a database the role does not cover
A role scoped to appdb cannot act on admin or another database, so cross-db operations are denied.
How to fix it
Grant the role the tests require
- Decide the least privilege the suite needs (usually
readWriteon the test db). - Grant that role to the CI user, or create a dedicated test user with it.
- Re-run so the command is now authorized.
db.getSiblingDB("admin").grantRolesToUser(
"ciuser",
[ { role: "readWrite", db: "appdb" } ]
)Use a fresh admin user for a throwaway test db
For an ephemeral CI mongod, create the user with the needed role at startup via root credentials.
services:
mongo:
image: mongo:7
env:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: rootpass
ports: ['27017:27017']How to prevent it
- Grant least-privilege roles matched to what the suite actually does.
- Use a dedicated CI user rather than reusing production roles.
- Scope roles to the exact test database.