Skip to content
Latchkey

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).

node
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

  1. Decide the least privilege the suite needs (usually readWrite on the test db).
  2. Grant that role to the CI user, or create a dedicated test user with it.
  3. Re-run so the command is now authorized.
mongosh
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.

.github/workflows/ci.yml
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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →