Mongoose Connection Authentication vs. MongoDB Driver Pooled Credential Persistence
0 reputation · 08 Jul 2020, 14:55 UTC
0 reputation · 08 Jul 2020, 14:55 UTC
Mongoose’s `mongoose.connect()` options let you specify `user`, `pass`, `authSource` and `authMechanism` to enforce least‑privilege access, while the underlying MongoDB driver maintains a pooled connection cache that may retain authentication state after credentials change.
The current behavior raises a security gap: unless the application forces a reconnect, a pooled connection can continue using stale credentials even after a password is marked expired, and Mongoose provides no built‑in mechanism to invalidate authentication automatically.
Key questions: How does Mongoose’s `authSource`/`authMechanism` enforce least‑privilege when the driver reuses pooled connections after a password change? Does the MongoDB driver automatically re‑authenticate a connection when the user’s credentials are marked expired, or must the application force a reconnect? What strategy should be used to detect and close stale connections in a Mongoose 6.x Node.js application?
Mongoose's user, pass, authSource, and authMechanism options enforce least-privilege only at the time a new socket is established; they do not automatically re-authenticate existing pooled connections when a password changes. The MongoDB driver does not automatically invalidate stale credentials on an open, pooled socket.
await mongoose.connection.close().await mongoose.connect(uri, { user, pass, authSource, authMechanism, /* other options */ }), ensuring the new credentials are provided.Model.findOne().limit(1)) after reconnection.To refine the strategy, please specify the exact versions of Mongoose and the underlying MongoDB Node.js driver being used.
Use comments to ask for clarification. Post a solution as an answer.
35,775 reputation · 09 Jul 2020, 00:52 UTC
Set maxIdleTimeMS in the connection options (passed through to the driver) to bound how long a stale authenticated socket can survive after a credential change. A value of 30000–60000 limits exposure without excessive churn; the driver evicts idle connections at that interval and forces a fresh handshake on the next checkout.
If maintaining two pools is impractical, wrap the default connection in a small module that exposes rotateCredentials(newUri). The function calls await mongoose.connection.close(), then await mongoose.connect(newUri), and resolves only after a lightweight db.command({ ping: 1 }) succeeds. Route all model access through this wrapper so callers automatically retry on the brief MongooseServerSelectionError window.
Mongoose 6.x bundles the 4.x driver series; maxIdleTimeMS was stabilized in driver 4.2. Verify the exact driver version with npm ls mongodb before relying on the eviction timer.